/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 4694: /***/ ((module) => { function webpackEmptyContext(req) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } webpackEmptyContext.keys = () => ([]); webpackEmptyContext.resolve = webpackEmptyContext; webpackEmptyContext.id = 4694; module.exports = webpackEmptyContext; /***/ }), /***/ 420: /***/ ((module) => { function webpackEmptyContext(req) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } webpackEmptyContext.keys = () => ([]); webpackEmptyContext.resolve = webpackEmptyContext; webpackEmptyContext.id = 420; module.exports = webpackEmptyContext; /***/ }), /***/ 7492: /***/ ((module) => { function webpackEmptyContext(req) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } webpackEmptyContext.keys = () => ([]); webpackEmptyContext.resolve = webpackEmptyContext; webpackEmptyContext.id = 7492; module.exports = webpackEmptyContext; /***/ }), /***/ 1509: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; __webpack_require__(4917); const inherits = __webpack_require__(1669).inherits; const promisify = __webpack_require__(930); const EventEmitter = __webpack_require__(8614).EventEmitter; module.exports = Agent; function isAgent(v) { return v && typeof v.addRequest === 'function'; } /** * Base `http.Agent` implementation. * No pooling/keep-alive is implemented by default. * * @param {Function} callback * @api public */ function Agent(callback, _opts) { if (!(this instanceof Agent)) { return new Agent(callback, _opts); } EventEmitter.call(this); // The callback gets promisified if it has 3 parameters // (i.e. it has a callback function) lazily this._promisifiedCallback = false; let opts = _opts; if ('function' === typeof callback) { this.callback = callback; } else if (callback) { opts = callback; } // timeout for the socket to be returned from the callback this.timeout = (opts && opts.timeout) || null; this.options = opts; } inherits(Agent, EventEmitter); /** * Override this function in your subclass! */ Agent.prototype.callback = function callback(req, opts) { throw new Error( '"agent-base" has no default implementation, you must subclass and override `callback()`' ); }; /** * Called by node-core's "_http_client.js" module when creating * a new HTTP request with this Agent instance. * * @api public */ Agent.prototype.addRequest = function addRequest(req, _opts) { const ownOpts = Object.assign({}, _opts); // Set default `host` for HTTP to localhost if (null == ownOpts.host) { ownOpts.host = 'localhost'; } // Set default `port` for HTTP if none was explicitly specified if (null == ownOpts.port) { ownOpts.port = ownOpts.secureEndpoint ? 443 : 80; } const opts = Object.assign({}, this.options, ownOpts); if (opts.host && opts.path) { // If both a `host` and `path` are specified then it's most likely the // result of a `url.parse()` call... we need to remove the `path` portion so // that `net.connect()` doesn't attempt to open that as a unix socket file. delete opts.path; } delete opts.agent; delete opts.hostname; delete opts._defaultAgent; delete opts.defaultPort; delete opts.createConnection; // Hint to use "Connection: close" // XXX: non-documented `http` module API :( req._last = true; req.shouldKeepAlive = false; // Create the `stream.Duplex` instance let timeout; let timedOut = false; const timeoutMs = this.timeout; const freeSocket = this.freeSocket; function onerror(err) { if (req._hadError) return; req.emit('error', err); // For Safety. Some additional errors might fire later on // and we need to make sure we don't double-fire the error event. req._hadError = true; } function ontimeout() { timeout = null; timedOut = true; const err = new Error( 'A "socket" was not created for HTTP request before ' + timeoutMs + 'ms' ); err.code = 'ETIMEOUT'; onerror(err); } function callbackError(err) { if (timedOut) return; if (timeout != null) { clearTimeout(timeout); timeout = null; } onerror(err); } function onsocket(socket) { if (timedOut) return; if (timeout != null) { clearTimeout(timeout); timeout = null; } if (isAgent(socket)) { // `socket` is actually an http.Agent instance, so relinquish // responsibility for this `req` to the Agent from here on socket.addRequest(req, opts); } else if (socket) { function onfree() { freeSocket(socket, opts); } socket.on('free', onfree); req.onSocket(socket); } else { const err = new Error( 'no Duplex stream was returned to agent-base for `' + req.method + ' ' + req.path + '`' ); onerror(err); } } if (!this._promisifiedCallback && this.callback.length >= 3) { // Legacy callback function - convert to a Promise this.callback = promisify(this.callback, this); this._promisifiedCallback = true; } if (timeoutMs > 0) { timeout = setTimeout(ontimeout, timeoutMs); } try { Promise.resolve(this.callback(req, opts)).then(onsocket, callbackError); } catch (err) { Promise.reject(err).catch(callbackError); } }; Agent.prototype.freeSocket = function freeSocket(socket, opts) { // TODO reuse sockets socket.destroy(); }; /***/ }), /***/ 4917: /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const url = __webpack_require__(8835); const https = __webpack_require__(7211); /** * This currently needs to be applied to all Node.js versions * in order to determine if the `req` is an HTTP or HTTPS request. * * There is currently no PR attempting to move this property upstream. */ const patchMarker = "__agent_base_https_request_patched__"; if (!https.request[patchMarker]) { https.request = (function(request) { return function(_options, cb) { let options; if (typeof _options === 'string') { options = url.parse(_options); } else { options = Object.assign({}, _options); } if (null == options.port) { options.port = 443; } options.secureEndpoint = true; return request.call(https, options, cb); }; })(https.request); https.request[patchMarker] = true; } /** * This is needed for Node.js >= 9.0.0 to make sure `https.get()` uses the * patched `https.request()`. * * Ref: https://github.com/nodejs/node/commit/5118f31 */ https.get = function (_url, _options, cb) { let options; if (typeof _url === 'string' && _options && typeof _options !== 'function') { options = Object.assign({}, url.parse(_url), _options); } else if (!_options && !cb) { options = _url; } else if (!cb) { options = _url; cb = _options; } const req = https.request(options, cb); req.end(); return req; }; /***/ }), /***/ 7326: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var DiagChannel = __webpack_require__(5026); var AutoCollectConsole = (function () { function AutoCollectConsole(client) { if (!!AutoCollectConsole.INSTANCE) { throw new Error("Console logging adapter tracking should be configured from the applicationInsights object"); } this._client = client; AutoCollectConsole.INSTANCE = this; } AutoCollectConsole.prototype.enable = function (isEnabled, collectConsoleLog) { if (DiagChannel.IsInitialized) { __webpack_require__(7308)/* .enable */ .wp(isEnabled && collectConsoleLog, this._client); __webpack_require__(4751)/* .enable */ .wp(isEnabled, this._client); __webpack_require__(2641)/* .enable */ .wp(isEnabled, this._client); } }; AutoCollectConsole.prototype.isInitialized = function () { return this._isInitialized; }; AutoCollectConsole.prototype.dispose = function () { AutoCollectConsole.INSTANCE = null; this.enable(false, false); }; AutoCollectConsole._methodNames = ["debug", "info", "log", "warn", "error"]; return AutoCollectConsole; }()); module.exports = AutoCollectConsole; //# sourceMappingURL=Console.js.map /***/ }), /***/ 7602: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var Logging = __webpack_require__(4798); var DiagChannel = __webpack_require__(5026); var CorrelationContextManager = (function () { function CorrelationContextManager() { } /** * Provides the current Context. * The context is the most recent one entered into for the current * logical chain of execution, including across asynchronous calls. */ CorrelationContextManager.getCurrentContext = function () { if (!CorrelationContextManager.enabled) { return null; } var context = CorrelationContextManager.session.get(CorrelationContextManager.CONTEXT_NAME); if (context === undefined) { return null; } return context; }; /** * A helper to generate objects conforming to the CorrelationContext interface */ CorrelationContextManager.generateContextObject = function (operationId, parentId, operationName, correlationContextHeader, traceparent, tracestate) { parentId = parentId || operationId; if (this.enabled) { return { operation: { name: operationName, id: operationId, parentId: parentId, traceparent: traceparent, tracestate: tracestate }, customProperties: new CustomPropertiesImpl(correlationContextHeader) }; } return null; }; /** * Runs a function inside a given Context. * All logical children of the execution path that entered this Context * will receive this Context object on calls to GetCurrentContext. */ CorrelationContextManager.runWithContext = function (context, fn) { if (CorrelationContextManager.enabled) { return CorrelationContextManager.session.bind(fn, (_a = {}, _a[CorrelationContextManager.CONTEXT_NAME] = context, _a))(); } else { return fn(); } var _a; }; /** * Wrapper for cls-hooked bindEmitter method */ CorrelationContextManager.wrapEmitter = function (emitter) { if (CorrelationContextManager.enabled) { CorrelationContextManager.session.bindEmitter(emitter); } }; /** * Patches a callback to restore the correct Context when getCurrentContext * is run within it. This is necessary if automatic correlation fails to work * with user-included libraries. * * The supplied callback will be given the same context that was present for * the call to wrapCallback. */ CorrelationContextManager.wrapCallback = function (fn) { if (CorrelationContextManager.enabled) { return CorrelationContextManager.session.bind(fn); } return fn; }; /** * Enables the CorrelationContextManager. */ CorrelationContextManager.enable = function (forceClsHooked) { if (this.enabled) { return; } if (!this.isNodeVersionCompatible()) { this.enabled = false; return; } if (!CorrelationContextManager.hasEverEnabled) { this.forceClsHooked = forceClsHooked; this.hasEverEnabled = true; if (typeof this.cls === "undefined") { if ((CorrelationContextManager.forceClsHooked === true) || (CorrelationContextManager.forceClsHooked === undefined && CorrelationContextManager.shouldUseClsHooked())) { this.cls = __webpack_require__(1006); } else { this.cls = __webpack_require__(1710); } } CorrelationContextManager.session = this.cls.createNamespace("AI-CLS-Session"); DiagChannel.registerContextPreservation(function (cb) { return CorrelationContextManager.session.bind(cb); }); } this.enabled = true; }; /** * Disables the CorrelationContextManager. */ CorrelationContextManager.disable = function () { this.enabled = false; }; /** * Reset the namespace */ CorrelationContextManager.reset = function () { if (CorrelationContextManager.hasEverEnabled) { CorrelationContextManager.session = null; CorrelationContextManager.session = this.cls.createNamespace('AI-CLS-Session'); } }; /** * Reports if CorrelationContextManager is able to run in this environment */ CorrelationContextManager.isNodeVersionCompatible = function () { var nodeVer = process.versions.node.split("."); return parseInt(nodeVer[0]) > 3 || (parseInt(nodeVer[0]) > 2 && parseInt(nodeVer[1]) > 2); }; /** * We only want to use cls-hooked when it uses async_hooks api (8.2+), else * use async-listener (plain -cls) */ CorrelationContextManager.shouldUseClsHooked = function () { var nodeVer = process.versions.node.split("."); return (parseInt(nodeVer[0]) > 8) || (parseInt(nodeVer[0]) >= 8 && parseInt(nodeVer[1]) >= 2); }; /** * A TypeError is triggered by cls-hooked for node [8.0, 8.2) * @internal Used in tests only */ CorrelationContextManager.canUseClsHooked = function () { var nodeVer = process.versions.node.split("."); var greater800 = (parseInt(nodeVer[0]) > 8) || (parseInt(nodeVer[0]) >= 8 && parseInt(nodeVer[1]) >= 0); var less820 = (parseInt(nodeVer[0]) < 8) || (parseInt(nodeVer[0]) <= 8 && parseInt(nodeVer[1]) < 2); var greater470 = parseInt(nodeVer[0]) > 4 || (parseInt(nodeVer[0]) >= 4 && parseInt(nodeVer[1]) >= 7); // cls-hooked requires node 4.7+ return !(greater800 && less820) && greater470; }; CorrelationContextManager.enabled = false; CorrelationContextManager.hasEverEnabled = false; CorrelationContextManager.forceClsHooked = undefined; // true: use cls-hooked, false: use cls, undefined: choose based on node version CorrelationContextManager.CONTEXT_NAME = "ApplicationInsights-Context"; return CorrelationContextManager; }()); exports.CorrelationContextManager = CorrelationContextManager; var CustomPropertiesImpl = (function () { function CustomPropertiesImpl(header) { this.props = []; this.addHeaderData(header); } CustomPropertiesImpl.prototype.addHeaderData = function (header) { var keyvals = header ? header.split(", ") : []; this.props = keyvals.map(function (keyval) { var parts = keyval.split("="); return { key: parts[0], value: parts[1] }; }).concat(this.props); }; CustomPropertiesImpl.prototype.serializeToHeader = function () { return this.props.map(function (keyval) { return keyval.key + "=" + keyval.value; }).join(", "); }; CustomPropertiesImpl.prototype.getProperty = function (prop) { for (var i = 0; i < this.props.length; ++i) { var keyval = this.props[i]; if (keyval.key === prop) { return keyval.value; } } return; }; // TODO: Strictly according to the spec, properties which are recieved from // an incoming request should be left untouched, while we may add our own new // properties. The logic here will need to change to track that. CustomPropertiesImpl.prototype.setProperty = function (prop, val) { if (CustomPropertiesImpl.bannedCharacters.test(prop) || CustomPropertiesImpl.bannedCharacters.test(val)) { Logging.warn("Correlation context property keys and values must not contain ',' or '='. setProperty was called with key: " + prop + " and value: " + val); return; } for (var i = 0; i < this.props.length; ++i) { var keyval = this.props[i]; if (keyval.key === prop) { keyval.value = val; return; } } this.props.push({ key: prop, value: val }); }; CustomPropertiesImpl.bannedCharacters = /[,=]/; return CustomPropertiesImpl; }()); //# sourceMappingURL=CorrelationContextManager.js.map /***/ }), /***/ 8103: /***/ ((module) => { "use strict"; var AutoCollectExceptions = (function () { function AutoCollectExceptions(client) { if (!!AutoCollectExceptions.INSTANCE) { throw new Error("Exception tracking should be configured from the applicationInsights object"); } AutoCollectExceptions.INSTANCE = this; this._client = client; // Only use for 13.7.0+ var nodeVer = process.versions.node.split("."); AutoCollectExceptions._canUseUncaughtExceptionMonitor = parseInt(nodeVer[0]) > 13 || (parseInt(nodeVer[0]) === 13 && parseInt(nodeVer[1]) >= 7); } AutoCollectExceptions.prototype.isInitialized = function () { return this._isInitialized; }; AutoCollectExceptions.prototype.enable = function (isEnabled) { var _this = this; if (isEnabled) { this._isInitialized = true; var self = this; if (!this._exceptionListenerHandle) { // For scenarios like Promise.reject(), an error won't be passed to the handle. Create a placeholder // error for these scenarios. var handle = function (reThrow, name, error) { if (error === void 0) { error = new Error(AutoCollectExceptions._FALLBACK_ERROR_MESSAGE); } _this._client.trackException({ exception: error }); _this._client.flush({ isAppCrashing: true }); // only rethrow when we are the only listener if (reThrow && name && process.listeners(name).length === 1) { console.error(error); process.exit(1); } }; if (AutoCollectExceptions._canUseUncaughtExceptionMonitor) { // Node.js >= 13.7.0, use uncaughtExceptionMonitor. It handles both promises and exceptions this._exceptionListenerHandle = handle.bind(this, false); // never rethrows process.on(AutoCollectExceptions.UNCAUGHT_EXCEPTION_MONITOR_HANDLER_NAME, this._exceptionListenerHandle); } else { this._exceptionListenerHandle = handle.bind(this, true, AutoCollectExceptions.UNCAUGHT_EXCEPTION_HANDLER_NAME); this._rejectionListenerHandle = handle.bind(this, false); // never rethrows process.on(AutoCollectExceptions.UNCAUGHT_EXCEPTION_HANDLER_NAME, this._exceptionListenerHandle); process.on(AutoCollectExceptions.UNHANDLED_REJECTION_HANDLER_NAME, this._rejectionListenerHandle); } } } else { if (this._exceptionListenerHandle) { if (AutoCollectExceptions._canUseUncaughtExceptionMonitor) { process.removeListener(AutoCollectExceptions.UNCAUGHT_EXCEPTION_MONITOR_HANDLER_NAME, this._exceptionListenerHandle); } else { process.removeListener(AutoCollectExceptions.UNCAUGHT_EXCEPTION_HANDLER_NAME, this._exceptionListenerHandle); process.removeListener(AutoCollectExceptions.UNHANDLED_REJECTION_HANDLER_NAME, this._rejectionListenerHandle); } this._exceptionListenerHandle = undefined; this._rejectionListenerHandle = undefined; delete this._exceptionListenerHandle; delete this._rejectionListenerHandle; } } }; AutoCollectExceptions.prototype.dispose = function () { AutoCollectExceptions.INSTANCE = null; this.enable(false); this._isInitialized = false; }; AutoCollectExceptions.INSTANCE = null; AutoCollectExceptions.UNCAUGHT_EXCEPTION_MONITOR_HANDLER_NAME = "uncaughtExceptionMonitor"; AutoCollectExceptions.UNCAUGHT_EXCEPTION_HANDLER_NAME = "uncaughtException"; AutoCollectExceptions.UNHANDLED_REJECTION_HANDLER_NAME = "unhandledRejection"; AutoCollectExceptions._RETHROW_EXIT_MESSAGE = "Application Insights Rethrow Exception Handler"; AutoCollectExceptions._FALLBACK_ERROR_MESSAGE = "A promise was rejected without providing an error. Application Insights generated this error stack for you."; AutoCollectExceptions._canUseUncaughtExceptionMonitor = false; return AutoCollectExceptions; }()); module.exports = AutoCollectExceptions; //# sourceMappingURL=Exceptions.js.map /***/ }), /***/ 4665: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var http = __webpack_require__(8605); var https = __webpack_require__(7211); var Logging = __webpack_require__(4798); var Util = __webpack_require__(604); var RequestResponseHeaders = __webpack_require__(3918); var HttpDependencyParser = __webpack_require__(7021); var CorrelationContextManager_1 = __webpack_require__(7602); var CorrelationIdManager = __webpack_require__(7892); var Traceparent = __webpack_require__(4553); var DiagChannel = __webpack_require__(5026); var AutoCollectHttpDependencies = (function () { function AutoCollectHttpDependencies(client) { if (!!AutoCollectHttpDependencies.INSTANCE) { throw new Error("Client request tracking should be configured from the applicationInsights object"); } AutoCollectHttpDependencies.INSTANCE = this; this._client = client; } AutoCollectHttpDependencies.prototype.enable = function (isEnabled) { this._isEnabled = isEnabled; if (this._isEnabled && !this._isInitialized) { this._initialize(); } if (DiagChannel.IsInitialized) { __webpack_require__(7275)/* .enable */ .wp(isEnabled, this._client); __webpack_require__(1614)/* .enable */ .wp(isEnabled, this._client); __webpack_require__(1953)/* .enable */ .wp(isEnabled, this._client); __webpack_require__(6174)/* .enable */ .wp(isEnabled, this._client); } }; AutoCollectHttpDependencies.prototype.isInitialized = function () { return this._isInitialized; }; AutoCollectHttpDependencies.prototype._initialize = function () { var _this = this; this._isInitialized = true; var originalGet = http.get; var originalRequest = http.request; var originalHttpsRequest = https.request; var clientRequestPatch = function (request, options) { var shouldCollect = !options[AutoCollectHttpDependencies.disableCollectionRequestOption] && !request[AutoCollectHttpDependencies.alreadyAutoCollectedFlag]; request[AutoCollectHttpDependencies.alreadyAutoCollectedFlag] = true; if (request && options && shouldCollect) { CorrelationContextManager_1.CorrelationContextManager.wrapEmitter(request); AutoCollectHttpDependencies.trackRequest(_this._client, { options: options, request: request }); } }; // On node >= v0.11.12 and < 9.0 (excluding 8.9.0) https.request just calls http.request (with additional options). // On node < 0.11.12, 8.9.0, and 9.0 > https.request is handled separately // Patch both and leave a flag to not double-count on versions that just call through // We add the flag to both http and https to protect against strange double collection in other scenarios http.request = function (options) { var requestArgs = []; for (var _i = 1; _i < arguments.length; _i++) { requestArgs[_i - 1] = arguments[_i]; } var request = originalRequest.call.apply(originalRequest, [http, options].concat(requestArgs)); clientRequestPatch(request, options); return request; }; https.request = function (options) { var requestArgs = []; for (var _i = 1; _i < arguments.length; _i++) { requestArgs[_i - 1] = arguments[_i]; } var request = originalHttpsRequest.call.apply(originalHttpsRequest, [https, options].concat(requestArgs)); clientRequestPatch(request, options); return request; }; // Node 8 calls http.request from http.get using a local reference! // We have to patch .get manually in this case and can't just assume request is enough // We have to replace the entire method in this case. We can't call the original. // This is because calling the original will give us no chance to set headers as it internally does .end(). http.get = function (options) { var requestArgs = []; for (var _i = 1; _i < arguments.length; _i++) { requestArgs[_i - 1] = arguments[_i]; } var request = (_a = http.request).call.apply(_a, [http, options].concat(requestArgs)); request.end(); return request; var _a; }; https.get = function (options) { var requestArgs = []; for (var _i = 1; _i < arguments.length; _i++) { requestArgs[_i - 1] = arguments[_i]; } var request = (_a = https.request).call.apply(_a, [https, options].concat(requestArgs)); request.end(); return request; var _a; }; }; /** * Tracks an outgoing request. Because it may set headers this method must be called before * writing content to or ending the request. */ AutoCollectHttpDependencies.trackRequest = function (client, telemetry) { if (!telemetry.options || !telemetry.request || !client) { Logging.info("AutoCollectHttpDependencies.trackRequest was called with invalid parameters: ", !telemetry.options, !telemetry.request, !client); return; } var requestParser = new HttpDependencyParser(telemetry.options, telemetry.request); var currentContext = CorrelationContextManager_1.CorrelationContextManager.getCurrentContext(); var uniqueRequestId; var uniqueTraceparent; if (currentContext && currentContext.operation && currentContext.operation.traceparent && Traceparent.isValidTraceId(currentContext.operation.traceparent.traceId)) { currentContext.operation.traceparent.updateSpanId(); uniqueRequestId = currentContext.operation.traceparent.getBackCompatRequestId(); } else if (CorrelationIdManager.w3cEnabled) { // Start an operation now so that we can include the w3c headers in the outgoing request var traceparent = new Traceparent(); uniqueTraceparent = traceparent.toString(); uniqueRequestId = traceparent.getBackCompatRequestId(); } else { uniqueRequestId = currentContext && currentContext.operation && (currentContext.operation.parentId + AutoCollectHttpDependencies.requestNumber++ + '.'); } // Add the source correlationId to the request headers, if a value was not already provided. // The getHeader/setHeader methods aren't available on very old Node versions, and // are not included in the v0.10 type declarations currently used. So check if the // methods exist before invoking them. if (Util.canIncludeCorrelationHeader(client, requestParser.getUrl()) && telemetry.request.getHeader && telemetry.request.setHeader) { if (client.config && client.config.correlationId) { // getHeader returns "any" type in newer versions of node. In basic scenarios, this will be , but could be modified to anything else via middleware var correlationHeader = telemetry.request.getHeader(RequestResponseHeaders.requestContextHeader); try { Util.safeIncludeCorrelationHeader(client, telemetry.request, correlationHeader); } catch (err) { Logging.warn("Request-Context header could not be set. Correlation of requests may be lost", err); } if (currentContext && currentContext.operation) { try { telemetry.request.setHeader(RequestResponseHeaders.requestIdHeader, uniqueRequestId); // Also set legacy headers telemetry.request.setHeader(RequestResponseHeaders.parentIdHeader, currentContext.operation.id); telemetry.request.setHeader(RequestResponseHeaders.rootIdHeader, uniqueRequestId); // Set W3C headers, if available if (uniqueTraceparent || currentContext.operation.traceparent) { telemetry.request.setHeader(RequestResponseHeaders.traceparentHeader, uniqueTraceparent || currentContext.operation.traceparent.toString()); } else if (CorrelationIdManager.w3cEnabled) { // should never get here since we set uniqueTraceparent above for the w3cEnabled scenario var traceparent = new Traceparent().toString(); telemetry.request.setHeader(RequestResponseHeaders.traceparentHeader, traceparent); } if (currentContext.operation.tracestate) { var tracestate = currentContext.operation.tracestate.toString(); if (tracestate) { telemetry.request.setHeader(RequestResponseHeaders.traceStateHeader, tracestate); } } var correlationContextHeader = currentContext.customProperties.serializeToHeader(); if (correlationContextHeader) { telemetry.request.setHeader(RequestResponseHeaders.correlationContextHeader, correlationContextHeader); } } catch (err) { Logging.warn("Correlation headers could not be set. Correlation of requests may be lost.", err); } } } } // Collect dependency telemetry about the request when it finishes. if (telemetry.request.on) { telemetry.request.on('response', function (response) { requestParser.onResponse(response); var dependencyTelemetry = requestParser.getDependencyTelemetry(telemetry, uniqueRequestId); dependencyTelemetry.contextObjects = dependencyTelemetry.contextObjects || {}; dependencyTelemetry.contextObjects["http.RequestOptions"] = telemetry.options; dependencyTelemetry.contextObjects["http.ClientRequest"] = telemetry.request; dependencyTelemetry.contextObjects["http.ClientResponse"] = response; client.trackDependency(dependencyTelemetry); }); telemetry.request.on('error', function (e) { requestParser.onError(e); var dependencyTelemetry = requestParser.getDependencyTelemetry(telemetry, uniqueRequestId); dependencyTelemetry.contextObjects = dependencyTelemetry.contextObjects || {}; dependencyTelemetry.contextObjects["http.RequestOptions"] = telemetry.options; dependencyTelemetry.contextObjects["http.ClientRequest"] = telemetry.request; dependencyTelemetry.contextObjects["Error"] = e; client.trackDependency(dependencyTelemetry); }); } }; AutoCollectHttpDependencies.prototype.dispose = function () { AutoCollectHttpDependencies.INSTANCE = null; this.enable(false); this._isInitialized = false; }; AutoCollectHttpDependencies.disableCollectionRequestOption = 'disableAppInsightsAutoCollection'; AutoCollectHttpDependencies.requestNumber = 1; AutoCollectHttpDependencies.alreadyAutoCollectedFlag = '_appInsightsAutoCollected'; return AutoCollectHttpDependencies; }()); module.exports = AutoCollectHttpDependencies; //# sourceMappingURL=HttpDependencies.js.map /***/ }), /***/ 7021: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var url = __webpack_require__(8835); var Contracts = __webpack_require__(6812); var Util = __webpack_require__(604); var RequestResponseHeaders = __webpack_require__(3918); var RequestParser = __webpack_require__(1399); var CorrelationIdManager = __webpack_require__(7892); /** * Helper class to read data from the requst/response objects and convert them into the telemetry contract */ var HttpDependencyParser = (function (_super) { __extends(HttpDependencyParser, _super); function HttpDependencyParser(requestOptions, request) { var _this = _super.call(this) || this; if (request && request.method && requestOptions) { // The ClientRequest.method property isn't documented, but is always there. _this.method = request.method; _this.url = HttpDependencyParser._getUrlFromRequestOptions(requestOptions, request); _this.startTime = +new Date(); } return _this; } /** * Called when the ClientRequest emits an error event. */ HttpDependencyParser.prototype.onError = function (error) { this._setStatus(undefined, error); }; /** * Called when the ClientRequest emits a response event. */ HttpDependencyParser.prototype.onResponse = function (response) { this._setStatus(response.statusCode, undefined); this.correlationId = Util.getCorrelationContextTarget(response, RequestResponseHeaders.requestContextTargetKey); }; /** * Gets a dependency data contract object for a completed ClientRequest. */ HttpDependencyParser.prototype.getDependencyTelemetry = function (baseTelemetry, dependencyId) { var urlObject = url.parse(this.url); urlObject.search = undefined; urlObject.hash = undefined; var dependencyName = this.method.toUpperCase() + " " + urlObject.pathname; var remoteDependencyType = Contracts.RemoteDependencyDataConstants.TYPE_HTTP; var remoteDependencyTarget = urlObject.hostname; if (this.correlationId) { remoteDependencyType = Contracts.RemoteDependencyDataConstants.TYPE_AI; if (this.correlationId !== CorrelationIdManager.correlationIdPrefix) { remoteDependencyTarget = urlObject.hostname + " | " + this.correlationId; } } else { remoteDependencyType = Contracts.RemoteDependencyDataConstants.TYPE_HTTP; } if (urlObject.port) { remoteDependencyTarget += ":" + urlObject.port; } var dependencyTelemetry = { id: dependencyId, name: dependencyName, data: this.url, duration: this.duration, success: this._isSuccess(), resultCode: this.statusCode ? this.statusCode.toString() : null, properties: this.properties || {}, dependencyTypeName: remoteDependencyType, target: remoteDependencyTarget }; // We should keep any parameters the user passed in // Except the fields defined above in requestTelemetry, which take priority // Except the properties field, where they're merged instead, with baseTelemetry taking priority if (baseTelemetry) { // Copy missing fields for (var key in baseTelemetry) { if (!dependencyTelemetry[key]) { dependencyTelemetry[key] = baseTelemetry[key]; } } // Merge properties if (baseTelemetry.properties) { for (var key in baseTelemetry.properties) { dependencyTelemetry.properties[key] = baseTelemetry.properties[key]; } } } return dependencyTelemetry; }; /** * Builds a URL from request options, using the same logic as http.request(). This is * necessary because a ClientRequest object does not expose a url property. */ HttpDependencyParser._getUrlFromRequestOptions = function (options, request) { if (typeof options === 'string') { options = url.parse(options); } else { // Avoid modifying the original options object. var originalOptions_1 = options; options = {}; if (originalOptions_1) { Object.keys(originalOptions_1).forEach(function (key) { options[key] = originalOptions_1[key]; }); } } // Oddly, url.format ignores path and only uses pathname and search, // so create them from the path, if path was specified if (options.path) { var parsedQuery = url.parse(options.path); options.pathname = parsedQuery.pathname; options.search = parsedQuery.search; } // Simiarly, url.format ignores hostname and port if host is specified, // even if host doesn't have the port, but http.request does not work // this way. It will use the port if one is not specified in host, // effectively treating host as hostname, but will use the port specified // in host if it exists. if (options.host && options.port) { // Force a protocol so it will parse the host as the host, not path. // It is discarded and not used, so it doesn't matter if it doesn't match var parsedHost = url.parse("http://" + options.host); if (!parsedHost.port && options.port) { options.hostname = options.host; delete options.host; } } // Mix in default values used by http.request and others options.protocol = options.protocol || (request.agent && request.agent.protocol) || undefined; options.hostname = options.hostname || 'localhost'; return url.format(options); }; return HttpDependencyParser; }(RequestParser)); module.exports = HttpDependencyParser; //# sourceMappingURL=HttpDependencyParser.js.map /***/ }), /***/ 5879: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var url = __webpack_require__(8835); var Contracts = __webpack_require__(6812); var Util = __webpack_require__(604); var RequestResponseHeaders = __webpack_require__(3918); var RequestParser = __webpack_require__(1399); var CorrelationIdManager = __webpack_require__(7892); var Tracestate = __webpack_require__(1566); var Traceparent = __webpack_require__(4553); /** * Helper class to read data from the requst/response objects and convert them into the telemetry contract */ var HttpRequestParser = (function (_super) { __extends(HttpRequestParser, _super); function HttpRequestParser(request, requestId) { var _this = _super.call(this) || this; if (request) { _this.method = request.method; _this.url = _this._getAbsoluteUrl(request); _this.startTime = +new Date(); _this.socketRemoteAddress = request.socket && request.socket.remoteAddress; _this.parseHeaders(request, requestId); if (request.connection) { _this.connectionRemoteAddress = request.connection.remoteAddress; _this.legacySocketRemoteAddress = request.connection["socket"] && request.connection["socket"].remoteAddress; } } return _this; } HttpRequestParser.prototype.onError = function (error, ellapsedMilliseconds) { this._setStatus(undefined, error); // This parameter is only for overrides. setStatus handles this internally for the autocollected case if (ellapsedMilliseconds) { this.duration = ellapsedMilliseconds; } }; HttpRequestParser.prototype.onResponse = function (response, ellapsedMilliseconds) { this._setStatus(response.statusCode, undefined); // This parameter is only for overrides. setStatus handles this internally for the autocollected case if (ellapsedMilliseconds) { this.duration = ellapsedMilliseconds; } }; HttpRequestParser.prototype.getRequestTelemetry = function (baseTelemetry) { var requestTelemetry = { id: this.requestId, name: this.method + " " + url.parse(this.url).pathname, url: this.url, /* See https://github.com/Microsoft/ApplicationInsights-dotnet-server/blob/25d695e6a906fbe977f67be3966d25dbf1c50a79/Src/Web/Web.Shared.Net/RequestTrackingTelemetryModule.cs#L250 for reference */ source: this.sourceCorrelationId, duration: this.duration, resultCode: this.statusCode ? this.statusCode.toString() : null, success: this._isSuccess(), properties: this.properties }; // We should keep any parameters the user passed in // Except the fields defined above in requestTelemetry, which take priority // Except the properties field, where they're merged instead, with baseTelemetry taking priority if (baseTelemetry) { // Copy missing fields for (var key in baseTelemetry) { if (!requestTelemetry[key]) { requestTelemetry[key] = baseTelemetry[key]; } } // Merge properties if (baseTelemetry.properties) { for (var key in baseTelemetry.properties) { requestTelemetry.properties[key] = baseTelemetry.properties[key]; } } } return requestTelemetry; }; HttpRequestParser.prototype.getRequestTags = function (tags) { // create a copy of the context for requests since client info will be used here var newTags = {}; for (var key in tags) { newTags[key] = tags[key]; } // don't override tags if they are already set newTags[HttpRequestParser.keys.locationIp] = tags[HttpRequestParser.keys.locationIp] || this._getIp(); newTags[HttpRequestParser.keys.sessionId] = tags[HttpRequestParser.keys.sessionId] || this._getId("ai_session"); newTags[HttpRequestParser.keys.userId] = tags[HttpRequestParser.keys.userId] || this._getId("ai_user"); newTags[HttpRequestParser.keys.userAuthUserId] = tags[HttpRequestParser.keys.userAuthUserId] || this._getId("ai_authUser"); newTags[HttpRequestParser.keys.operationName] = this.getOperationName(tags); newTags[HttpRequestParser.keys.operationParentId] = this.getOperationParentId(tags); newTags[HttpRequestParser.keys.operationId] = this.getOperationId(tags); return newTags; }; HttpRequestParser.prototype.getOperationId = function (tags) { return tags[HttpRequestParser.keys.operationId] || this.operationId; }; HttpRequestParser.prototype.getOperationParentId = function (tags) { return tags[HttpRequestParser.keys.operationParentId] || this.parentId || this.getOperationId(tags); }; HttpRequestParser.prototype.getOperationName = function (tags) { return tags[HttpRequestParser.keys.operationName] || this.method + " " + url.parse(this.url).pathname; }; HttpRequestParser.prototype.getRequestId = function () { return this.requestId; }; HttpRequestParser.prototype.getCorrelationContextHeader = function () { return this.correlationContextHeader; }; HttpRequestParser.prototype.getTraceparent = function () { return this.traceparent; }; HttpRequestParser.prototype.getTracestate = function () { return this.tracestate; }; HttpRequestParser.prototype.getLegacyRootId = function () { return this.legacyRootId; }; HttpRequestParser.prototype._getAbsoluteUrl = function (request) { if (!request.headers) { return request.url; } var encrypted = request.connection ? request.connection.encrypted : null; var requestUrl = url.parse(request.url); var pathName = requestUrl.pathname; var search = requestUrl.search; var absoluteUrl = url.format({ protocol: encrypted ? "https" : "http", host: request.headers.host, pathname: pathName, search: search }); return absoluteUrl; }; HttpRequestParser.prototype._getIp = function () { // regex to match ipv4 without port // Note: including the port would cause the payload to be rejected by the data collector var ipMatch = /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/; var check = function (str) { var results = ipMatch.exec(str); if (results) { return results[0]; } }; var ip = check(this.rawHeaders["x-forwarded-for"]) || check(this.rawHeaders["x-client-ip"]) || check(this.rawHeaders["x-real-ip"]) || check(this.connectionRemoteAddress) || check(this.socketRemoteAddress) || check(this.legacySocketRemoteAddress); // node v12 returns this if the address is "localhost" if (!ip && this.connectionRemoteAddress && this.connectionRemoteAddress.substr && this.connectionRemoteAddress.substr(0, 2) === "::") { ip = "127.0.0.1"; } return ip; }; HttpRequestParser.prototype._getId = function (name) { var cookie = (this.rawHeaders && this.rawHeaders["cookie"] && typeof this.rawHeaders["cookie"] === 'string' && this.rawHeaders["cookie"]) || ""; var value = HttpRequestParser.parseId(Util.getCookie(name, cookie)); return value; }; /** * Sets this operation's operationId, parentId, requestId (and legacyRootId, if necessary) based on this operation's traceparent */ HttpRequestParser.prototype.setBackCompatFromThisTraceContext = function () { // Set operationId this.operationId = this.traceparent.traceId; if (this.traceparent.legacyRootId) { this.legacyRootId = this.traceparent.legacyRootId; } // Set parentId with existing spanId this.parentId = this.traceparent.parentId; // Update the spanId and set the current requestId this.traceparent.updateSpanId(); this.requestId = this.traceparent.getBackCompatRequestId(); }; HttpRequestParser.prototype.parseHeaders = function (request, requestId) { this.rawHeaders = request.headers || request.rawHeaders; this.userAgent = request.headers && request.headers["user-agent"]; this.sourceCorrelationId = Util.getCorrelationContextTarget(request, RequestResponseHeaders.requestContextSourceKey); if (request.headers) { var tracestateHeader = request.headers[RequestResponseHeaders.traceStateHeader]; // w3c header var traceparentHeader = request.headers[RequestResponseHeaders.traceparentHeader]; // w3c header var requestIdHeader = request.headers[RequestResponseHeaders.requestIdHeader]; // default AI header var legacy_parentId = request.headers[RequestResponseHeaders.parentIdHeader]; // legacy AI header var legacy_rootId = request.headers[RequestResponseHeaders.rootIdHeader]; // legacy AI header this.correlationContextHeader = request.headers[RequestResponseHeaders.correlationContextHeader]; if (CorrelationIdManager.w3cEnabled && (traceparentHeader || tracestateHeader)) { // Parse W3C Trace Context headers this.traceparent = new Traceparent(traceparentHeader); // new traceparent is always created from this this.tracestate = traceparentHeader && tracestateHeader && new Tracestate(tracestateHeader); // discard tracestate if no traceparent is present this.setBackCompatFromThisTraceContext(); } else if (requestIdHeader) { // Parse AI headers if (CorrelationIdManager.w3cEnabled) { this.traceparent = new Traceparent(null, requestIdHeader); this.setBackCompatFromThisTraceContext(); } else { this.parentId = requestIdHeader; this.requestId = CorrelationIdManager.generateRequestId(this.parentId); this.operationId = CorrelationIdManager.getRootId(this.requestId); } } else { // Legacy fallback if (CorrelationIdManager.w3cEnabled) { this.traceparent = new Traceparent(); this.traceparent.parentId = legacy_parentId; this.traceparent.legacyRootId = legacy_rootId || legacy_parentId; this.setBackCompatFromThisTraceContext(); } else { this.parentId = legacy_parentId; this.requestId = CorrelationIdManager.generateRequestId(legacy_rootId || this.parentId); this.correlationContextHeader = null; this.operationId = CorrelationIdManager.getRootId(this.requestId); } } if (requestId) { // For the scenarios that don't guarantee an AI-created context, // override the requestId with the provided one. this.requestId = requestId; this.operationId = CorrelationIdManager.getRootId(this.requestId); } } }; HttpRequestParser.parseId = function (cookieValue) { var cookieParts = cookieValue.split("|"); if (cookieParts.length > 0) { return cookieParts[0]; } return ""; // old behavior was to return "" for incorrect parsing }; HttpRequestParser.keys = new Contracts.ContextTagKeys(); return HttpRequestParser; }(RequestParser)); module.exports = HttpRequestParser; //# sourceMappingURL=HttpRequestParser.js.map /***/ }), /***/ 4784: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var http = __webpack_require__(8605); var https = __webpack_require__(7211); var Logging = __webpack_require__(4798); var Util = __webpack_require__(604); var RequestResponseHeaders = __webpack_require__(3918); var HttpRequestParser = __webpack_require__(5879); var CorrelationContextManager_1 = __webpack_require__(7602); var AutoCollectPerformance = __webpack_require__(9270); var AutoCollectHttpRequests = (function () { function AutoCollectHttpRequests(client) { if (!!AutoCollectHttpRequests.INSTANCE) { throw new Error("Server request tracking should be configured from the applicationInsights object"); } AutoCollectHttpRequests.INSTANCE = this; this._client = client; } AutoCollectHttpRequests.prototype.enable = function (isEnabled) { this._isEnabled = isEnabled; // Autocorrelation requires automatic monitoring of incoming server requests // Disabling autocollection but enabling autocorrelation will still enable // request monitoring but will not produce request events if ((this._isAutoCorrelating || this._isEnabled || AutoCollectPerformance.isEnabled()) && !this._isInitialized) { this.useAutoCorrelation(this._isAutoCorrelating); this._initialize(); } }; AutoCollectHttpRequests.prototype.useAutoCorrelation = function (isEnabled, forceClsHooked) { if (isEnabled && !this._isAutoCorrelating) { CorrelationContextManager_1.CorrelationContextManager.enable(forceClsHooked); } else if (!isEnabled && this._isAutoCorrelating) { CorrelationContextManager_1.CorrelationContextManager.disable(); } this._isAutoCorrelating = isEnabled; }; AutoCollectHttpRequests.prototype.isInitialized = function () { return this._isInitialized; }; AutoCollectHttpRequests.prototype.isAutoCorrelating = function () { return this._isAutoCorrelating; }; AutoCollectHttpRequests.prototype._generateCorrelationContext = function (requestParser) { if (!this._isAutoCorrelating) { return; } return CorrelationContextManager_1.CorrelationContextManager.generateContextObject(requestParser.getOperationId(this._client.context.tags), requestParser.getRequestId(), requestParser.getOperationName(this._client.context.tags), requestParser.getCorrelationContextHeader(), requestParser.getTraceparent(), requestParser.getTracestate()); }; AutoCollectHttpRequests.prototype._initialize = function () { var _this = this; this._isInitialized = true; var wrapOnRequestHandler = function (onRequest) { if (!onRequest) { return undefined; } if (typeof onRequest !== 'function') { throw new Error('onRequest handler must be a function'); } return function (request, response) { CorrelationContextManager_1.CorrelationContextManager.wrapEmitter(request); CorrelationContextManager_1.CorrelationContextManager.wrapEmitter(response); var shouldCollect = request && !request[AutoCollectHttpRequests.alreadyAutoCollectedFlag]; if (request && shouldCollect) { // Set up correlation context var requestParser_1 = new HttpRequestParser(request); var correlationContext = _this._generateCorrelationContext(requestParser_1); // Note: Check for if correlation is enabled happens within this method. // If not enabled, function will directly call the callback. CorrelationContextManager_1.CorrelationContextManager.runWithContext(correlationContext, function () { if (_this._isEnabled) { // Mark as auto collected request[AutoCollectHttpRequests.alreadyAutoCollectedFlag] = true; // Auto collect request AutoCollectHttpRequests.trackRequest(_this._client, { request: request, response: response }, requestParser_1); } if (typeof onRequest === "function") { onRequest(request, response); } }); } else { if (typeof onRequest === "function") { onRequest(request, response); } } }; }; // The `http.createServer` function will instantiate a new http.Server object. // Inside the Server's constructor, it is using addListener to register the // onRequest handler. So there are two ways to inject the wrapped onRequest handler: // 1) Overwrite Server.prototype.addListener (and .on()) globally and not patching // the http.createServer call. Or // 2) Overwrite the http.createServer method and add a patched addListener to the // fresh server instance. This seems more stable for possible future changes as // it also covers the case where the Server might not use addListener to manage // the callback internally. // And also as long as the constructor uses addListener to add the handle, it is // ok to patch the addListener after construction only. Because if we would patch // the prototype one and the createServer method, we would wrap the handler twice // in case of the constructor call. var wrapServerEventHandler = function (server) { var originalAddListener = server.addListener.bind(server); server.addListener = function (eventType, eventHandler) { switch (eventType) { case 'request': case 'checkContinue': return originalAddListener(eventType, wrapOnRequestHandler(eventHandler)); default: return originalAddListener(eventType, eventHandler); } }; // on is an alias to addListener only server.on = server.addListener; }; var originalHttpServer = http.createServer; http.createServer = function (onRequest) { // todo: get a pointer to the server so the IP address can be read from server.address var server = originalHttpServer(wrapOnRequestHandler(onRequest)); wrapServerEventHandler(server); return server; }; var originalHttpsServer = https.createServer; https.createServer = function (options, onRequest) { var server = originalHttpsServer(options, wrapOnRequestHandler(onRequest)); wrapServerEventHandler(server); return server; }; }; /** * Tracks a request synchronously (doesn't wait for response 'finish' event) */ AutoCollectHttpRequests.trackRequestSync = function (client, telemetry) { if (!telemetry.request || !telemetry.response || !client) { Logging.info("AutoCollectHttpRequests.trackRequestSync was called with invalid parameters: ", !telemetry.request, !telemetry.response, !client); return; } AutoCollectHttpRequests.addResponseCorrelationIdHeader(client, telemetry.response); // store data about the request var correlationContext = CorrelationContextManager_1.CorrelationContextManager.getCurrentContext(); var requestParser = new HttpRequestParser(telemetry.request, (correlationContext && correlationContext.operation.parentId)); // Overwrite correlation context with request parser results if (correlationContext) { correlationContext.operation.id = requestParser.getOperationId(client.context.tags) || correlationContext.operation.id; correlationContext.operation.name = requestParser.getOperationName(client.context.tags) || correlationContext.operation.name; correlationContext.operation.parentId = requestParser.getRequestId() || correlationContext.operation.parentId; correlationContext.customProperties.addHeaderData(requestParser.getCorrelationContextHeader()); } AutoCollectHttpRequests.endRequest(client, requestParser, telemetry, telemetry.duration, telemetry.error); }; /** * Tracks a request by listening to the response 'finish' event */ AutoCollectHttpRequests.trackRequest = function (client, telemetry, _requestParser) { if (!telemetry.request || !telemetry.response || !client) { Logging.info("AutoCollectHttpRequests.trackRequest was called with invalid parameters: ", !telemetry.request, !telemetry.response, !client); return; } // store data about the request var correlationContext = CorrelationContextManager_1.CorrelationContextManager.getCurrentContext(); var requestParser = _requestParser || new HttpRequestParser(telemetry.request, correlationContext && correlationContext.operation.parentId); if (Util.canIncludeCorrelationHeader(client, requestParser.getUrl())) { AutoCollectHttpRequests.addResponseCorrelationIdHeader(client, telemetry.response); } // Overwrite correlation context with request parser results (if not an automatic track. we've already precalculated the correlation context in that case) if (correlationContext && !_requestParser) { correlationContext.operation.id = requestParser.getOperationId(client.context.tags) || correlationContext.operation.id; correlationContext.operation.name = requestParser.getOperationName(client.context.tags) || correlationContext.operation.name; correlationContext.operation.parentId = requestParser.getOperationParentId(client.context.tags) || correlationContext.operation.parentId; correlationContext.customProperties.addHeaderData(requestParser.getCorrelationContextHeader()); } // response listeners if (telemetry.response.once) { telemetry.response.once("finish", function () { AutoCollectHttpRequests.endRequest(client, requestParser, telemetry, null, null); }); } // track a failed request if an error is emitted if (telemetry.request.on) { telemetry.request.on("error", function (error) { AutoCollectHttpRequests.endRequest(client, requestParser, telemetry, null, error); }); } }; /** * Add the target correlationId to the response headers, if not already provided. */ AutoCollectHttpRequests.addResponseCorrelationIdHeader = function (client, response) { if (client.config && client.config.correlationId && response.getHeader && response.setHeader && !response.headersSent) { var correlationHeader = response.getHeader(RequestResponseHeaders.requestContextHeader); Util.safeIncludeCorrelationHeader(client, response, correlationHeader); } }; AutoCollectHttpRequests.endRequest = function (client, requestParser, telemetry, ellapsedMilliseconds, error) { if (error) { requestParser.onError(error, ellapsedMilliseconds); } else { requestParser.onResponse(telemetry.response, ellapsedMilliseconds); } var requestTelemetry = requestParser.getRequestTelemetry(telemetry); requestTelemetry.tagOverrides = requestParser.getRequestTags(client.context.tags); if (telemetry.tagOverrides) { for (var key in telemetry.tagOverrides) { requestTelemetry.tagOverrides[key] = telemetry.tagOverrides[key]; } } var legacyRootId = requestParser.getLegacyRootId(); if (legacyRootId) { requestTelemetry.properties["ai_legacyRootId"] = legacyRootId; } requestTelemetry.contextObjects = requestTelemetry.contextObjects || {}; requestTelemetry.contextObjects["http.ServerRequest"] = telemetry.request; requestTelemetry.contextObjects["http.ServerResponse"] = telemetry.response; client.trackRequest(requestTelemetry); }; AutoCollectHttpRequests.prototype.dispose = function () { AutoCollectHttpRequests.INSTANCE = null; this.enable(false); this._isInitialized = false; CorrelationContextManager_1.CorrelationContextManager.disable(); this._isAutoCorrelating = false; }; AutoCollectHttpRequests.alreadyAutoCollectedFlag = '_appInsightsAutoCollected'; return AutoCollectHttpRequests; }()); module.exports = AutoCollectHttpRequests; //# sourceMappingURL=HttpRequests.js.map /***/ }), /***/ 6759: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; Object.defineProperty(exports, "__esModule", ({ value: true })); var Config = __webpack_require__(105); var Context = __webpack_require__(9989); var Logging = __webpack_require__(4798); var AutoCollectNativePerformance = (function () { function AutoCollectNativePerformance(client) { this._disabledMetrics = {}; // Note: Only 1 instance of this can exist. So when we reconstruct this object, // just disable old native instance and reset JS member variables if (AutoCollectNativePerformance.INSTANCE) { AutoCollectNativePerformance.INSTANCE.dispose(); } AutoCollectNativePerformance.INSTANCE = this; this._client = client; } /** * Reports if NativePerformance is able to run in this environment */ AutoCollectNativePerformance.isNodeVersionCompatible = function () { var nodeVer = process.versions.node.split("."); return parseInt(nodeVer[0]) >= 6; }; /** * Start instance of native metrics agent. * * @param {boolean} isEnabled * @param {number} [collectionInterval=60000] * @memberof AutoCollectNativePerformance */ AutoCollectNativePerformance.prototype.enable = function (isEnabled, disabledMetrics, collectionInterval) { var _this = this; if (disabledMetrics === void 0) { disabledMetrics = {}; } if (collectionInterval === void 0) { collectionInterval = 60000; } if (!AutoCollectNativePerformance.isNodeVersionCompatible()) { return; } if (AutoCollectNativePerformance._metricsAvailable == undefined && isEnabled && !this._isInitialized) { // Try to require in the native-metrics library. If it's found initialize it, else do nothing and never try again. try { var NativeMetricsEmitters = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module 'applicationinsights-native-metrics'"); e.code = 'MODULE_NOT_FOUND'; throw e; }())); AutoCollectNativePerformance._emitter = new NativeMetricsEmitters(); AutoCollectNativePerformance._metricsAvailable = true; Logging.info("Native metrics module successfully loaded!"); } catch (err) { // Package not available. Never try again AutoCollectNativePerformance._metricsAvailable = false; return; } } this._isEnabled = isEnabled; this._disabledMetrics = disabledMetrics; if (this._isEnabled && !this._isInitialized) { this._isInitialized = true; } // Enable the emitter if we were able to construct one if (this._isEnabled && AutoCollectNativePerformance._emitter) { // enable self AutoCollectNativePerformance._emitter.enable(true, collectionInterval); this._handle = setInterval(function () { return _this._trackNativeMetrics(); }, collectionInterval); this._handle.unref(); } else if (AutoCollectNativePerformance._emitter) { // disable self AutoCollectNativePerformance._emitter.enable(false); if (this._handle) { clearInterval(this._handle); this._handle = undefined; } } }; /** * Cleanup this instance of AutoCollectNativePerformance * * @memberof AutoCollectNativePerformance */ AutoCollectNativePerformance.prototype.dispose = function () { this.enable(false); }; /** * Parse environment variable and overwrite isEnabled based on respective fields being set * * @private * @static * @param {(boolean | IDisabledExtendedMetrics)} collectExtendedMetrics * @returns {(boolean | IDisabledExtendedMetrics)} * @memberof AutoCollectNativePerformance */ AutoCollectNativePerformance.parseEnabled = function (collectExtendedMetrics) { var disableAll = process.env[Config.ENV_nativeMetricsDisableAll]; var individualOptOuts = process.env[Config.ENV_nativeMetricsDisablers]; // case 1: disable all env var set, RETURN with isEnabled=false if (disableAll) { return { isEnabled: false, disabledMetrics: {} }; } // case 2: individual env vars set, RETURN with isEnabled=true, disabledMetrics={...} if (individualOptOuts) { var optOutsArr = individualOptOuts.split(","); var disabledMetrics = {}; if (optOutsArr.length > 0) { for (var _i = 0, optOutsArr_1 = optOutsArr; _i < optOutsArr_1.length; _i++) { var opt = optOutsArr_1[_i]; disabledMetrics[opt] = true; } } // case 2a: collectExtendedMetrics is an object, overwrite existing ones if they exist if (typeof collectExtendedMetrics === "object") { return { isEnabled: true, disabledMetrics: __assign({}, collectExtendedMetrics, disabledMetrics) }; } // case 2b: collectExtendedMetrics is a boolean, set disabledMetrics as is return { isEnabled: collectExtendedMetrics, disabledMetrics: disabledMetrics }; } // case 4: no env vars set, input arg is a boolean, RETURN with isEnabled=collectExtendedMetrics, disabledMetrics={} if (typeof collectExtendedMetrics === "boolean") { return { isEnabled: collectExtendedMetrics, disabledMetrics: {} }; } else { // case 5: no env vars set, input arg is object, RETURN with isEnabled=true, disabledMetrics=collectExtendedMetrics return { isEnabled: true, disabledMetrics: collectExtendedMetrics }; } }; /** * Trigger an iteration of native metrics collection * * @private * @memberof AutoCollectNativePerformance */ AutoCollectNativePerformance.prototype._trackNativeMetrics = function () { var shouldSendAll = true; if (typeof this._isEnabled !== "object") { shouldSendAll = this._isEnabled; } if (shouldSendAll) { this._trackGarbageCollection(); this._trackEventLoop(); this._trackHeapUsage(); } }; /** * Tracks garbage collection stats for this interval. One custom metric is sent per type of garbage * collection that occurred during this collection interval. * * @private * @memberof AutoCollectNativePerformance */ AutoCollectNativePerformance.prototype._trackGarbageCollection = function () { if (this._disabledMetrics.gc) { return; } var gcData = AutoCollectNativePerformance._emitter.getGCData(); for (var gc in gcData) { var metrics = gcData[gc].metrics; var name_1 = gc + " Garbage Collection Duration"; var stdDev = Math.sqrt(metrics.sumSquares / metrics.count - Math.pow(metrics.total / metrics.count, 2)) || 0; this._client.trackMetric({ name: name_1, value: metrics.total, count: metrics.count, max: metrics.max, min: metrics.min, stdDev: stdDev, tagOverrides: (_a = {}, _a[this._client.context.keys.internalSdkVersion] = "node-nativeperf:" + Context.sdkVersion, _a) }); } var _a; }; /** * Tracks event loop ticks per interval as a custom metric. Also included in the metric is min/max/avg * time spent in event loop for this interval. * * @private * @returns {void} * @memberof AutoCollectNativePerformance */ AutoCollectNativePerformance.prototype._trackEventLoop = function () { if (this._disabledMetrics.loop) { return; } var loopData = AutoCollectNativePerformance._emitter.getLoopData(); var metrics = loopData.loopUsage; if (metrics.count == 0) { return; } var name = "Event Loop CPU Time"; var stdDev = Math.sqrt(metrics.sumSquares / metrics.count - Math.pow(metrics.total / metrics.count, 2)) || 0; this._client.trackMetric({ name: name, value: metrics.total, count: metrics.count, min: metrics.min, max: metrics.max, stdDev: stdDev, tagOverrides: (_a = {}, _a[this._client.context.keys.internalSdkVersion] = "node-nativeperf:" + Context.sdkVersion, _a) }); var _a; }; /** * Track heap memory usage metrics as a custom metric. * * @private * @memberof AutoCollectNativePerformance */ AutoCollectNativePerformance.prototype._trackHeapUsage = function () { if (this._disabledMetrics.heap) { return; } var memoryUsage = process.memoryUsage(); var heapUsed = memoryUsage.heapUsed, heapTotal = memoryUsage.heapTotal, rss = memoryUsage.rss; this._client.trackMetric({ name: "Memory Usage (Heap)", value: heapUsed, count: 1, tagOverrides: (_a = {}, _a[this._client.context.keys.internalSdkVersion] = "node-nativeperf:" + Context.sdkVersion, _a) }); this._client.trackMetric({ name: "Memory Total (Heap)", value: heapTotal, count: 1, tagOverrides: (_b = {}, _b[this._client.context.keys.internalSdkVersion] = "node-nativeperf:" + Context.sdkVersion, _b) }); this._client.trackMetric({ name: "Memory Usage (Non-Heap)", value: rss - heapTotal, count: 1, tagOverrides: (_c = {}, _c[this._client.context.keys.internalSdkVersion] = "node-nativeperf:" + Context.sdkVersion, _c) }); var _a, _b, _c; }; return AutoCollectNativePerformance; }()); exports.AutoCollectNativePerformance = AutoCollectNativePerformance; //# sourceMappingURL=NativePerformance.js.map /***/ }), /***/ 9270: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var os = __webpack_require__(2087); var Constants = __webpack_require__(3498); var AutoCollectPerformance = (function () { /** * @param enableLiveMetricsCounters - enable sending additional live metrics information (dependency metrics, exception metrics, committed memory) */ function AutoCollectPerformance(client, collectionInterval, enableLiveMetricsCounters) { if (collectionInterval === void 0) { collectionInterval = 60000; } if (enableLiveMetricsCounters === void 0) { enableLiveMetricsCounters = false; } this._lastIntervalRequestExecutionTime = 0; // the sum of durations which took place during from app start until last interval this._lastIntervalDependencyExecutionTime = 0; if (!AutoCollectPerformance.INSTANCE) { AutoCollectPerformance.INSTANCE = this; } this._isInitialized = false; this._client = client; this._collectionInterval = collectionInterval; this._enableLiveMetricsCounters = enableLiveMetricsCounters; } AutoCollectPerformance.prototype.enable = function (isEnabled, collectionInterval) { var _this = this; this._isEnabled = isEnabled; if (this._isEnabled && !this._isInitialized) { this._isInitialized = true; } if (isEnabled) { if (!this._handle) { this._lastCpus = os.cpus(); this._lastRequests = { totalRequestCount: AutoCollectPerformance._totalRequestCount, totalFailedRequestCount: AutoCollectPerformance._totalFailedRequestCount, time: +new Date }; this._lastDependencies = { totalDependencyCount: AutoCollectPerformance._totalDependencyCount, totalFailedDependencyCount: AutoCollectPerformance._totalFailedDependencyCount, time: +new Date }; this._lastExceptions = { totalExceptionCount: AutoCollectPerformance._totalExceptionCount, time: +new Date }; if (typeof process.cpuUsage === 'function') { this._lastAppCpuUsage = process.cpuUsage(); } this._lastHrtime = process.hrtime(); this._collectionInterval = collectionInterval || this._collectionInterval; this._handle = setInterval(function () { return _this.trackPerformance(); }, this._collectionInterval); this._handle.unref(); // Allow the app to terminate even while this loop is going on } } else { if (this._handle) { clearInterval(this._handle); this._handle = undefined; } } }; AutoCollectPerformance.countRequest = function (duration, success) { var durationMs; if (!AutoCollectPerformance.isEnabled()) { return; } if (typeof duration === 'string') { // dependency duration is passed in as "00:00:00.123" by autocollectors durationMs = +new Date('1970-01-01T' + duration + 'Z'); // convert to num ms, returns NaN if wrong } else if (typeof duration === 'number') { durationMs = duration; } else { return; } AutoCollectPerformance._intervalRequestExecutionTime += durationMs; if (success === false) { AutoCollectPerformance._totalFailedRequestCount++; } AutoCollectPerformance._totalRequestCount++; }; AutoCollectPerformance.countException = function () { AutoCollectPerformance._totalExceptionCount++; }; AutoCollectPerformance.countDependency = function (duration, success) { var durationMs; if (!AutoCollectPerformance.isEnabled()) { return; } if (typeof duration === 'string') { // dependency duration is passed in as "00:00:00.123" by autocollectors durationMs = +new Date('1970-01-01T' + duration + 'Z'); // convert to num ms, returns NaN if wrong } else if (typeof duration === 'number') { durationMs = duration; } else { return; } AutoCollectPerformance._intervalDependencyExecutionTime += durationMs; if (success === false) { AutoCollectPerformance._totalFailedDependencyCount++; } AutoCollectPerformance._totalDependencyCount++; }; AutoCollectPerformance.prototype.isInitialized = function () { return this._isInitialized; }; AutoCollectPerformance.isEnabled = function () { return AutoCollectPerformance.INSTANCE && AutoCollectPerformance.INSTANCE._isEnabled; }; AutoCollectPerformance.prototype.trackPerformance = function () { this._trackCpu(); this._trackMemory(); this._trackNetwork(); this._trackDependencyRate(); this._trackExceptionRate(); }; AutoCollectPerformance.prototype._trackCpu = function () { // this reports total ms spent in each category since the OS was booted, to calculate percent it is necessary // to find the delta since the last measurement var cpus = os.cpus(); if (cpus && cpus.length && this._lastCpus && cpus.length === this._lastCpus.length) { var totalUser = 0; var totalSys = 0; var totalNice = 0; var totalIdle = 0; var totalIrq = 0; for (var i = 0; !!cpus && i < cpus.length; i++) { var cpu = cpus[i]; var lastCpu = this._lastCpus[i]; var name = "% cpu(" + i + ") "; var model = cpu.model; var speed = cpu.speed; var times = cpu.times; var lastTimes = lastCpu.times; // user cpu time (or) % CPU time spent in user space var user = (times.user - lastTimes.user) || 0; totalUser += user; // system cpu time (or) % CPU time spent in kernel space var sys = (times.sys - lastTimes.sys) || 0; totalSys += sys; // user nice cpu time (or) % CPU time spent on low priority processes var nice = (times.nice - lastTimes.nice) || 0; totalNice += nice; // idle cpu time (or) % CPU time spent idle var idle = (times.idle - lastTimes.idle) || 0; totalIdle += idle; // irq (or) % CPU time spent servicing/handling hardware interrupts var irq = (times.irq - lastTimes.irq) || 0; totalIrq += irq; } // Calculate % of total cpu time (user + system) this App Process used (Only supported by node v6.1.0+) var appCpuPercent = undefined; if (typeof process.cpuUsage === 'function') { var appCpuUsage = process.cpuUsage(); var hrtime = process.hrtime(); var totalApp = ((appCpuUsage.user - this._lastAppCpuUsage.user) + (appCpuUsage.system - this._lastAppCpuUsage.system)) || 0; if (typeof this._lastHrtime !== 'undefined' && this._lastHrtime.length === 2) { var elapsedTime = ((hrtime[0] - this._lastHrtime[0]) * 1e6 + (hrtime[1] - this._lastHrtime[1]) / 1e3) || 0; // convert to microseconds appCpuPercent = 100 * totalApp / (elapsedTime * cpus.length); } // Set previous this._lastAppCpuUsage = appCpuUsage; this._lastHrtime = hrtime; } var combinedTotal = (totalUser + totalSys + totalNice + totalIdle + totalIrq) || 1; this._client.trackMetric({ name: Constants.PerformanceCounter.PROCESSOR_TIME, value: ((combinedTotal - totalIdle) / combinedTotal) * 100 }); this._client.trackMetric({ name: Constants.PerformanceCounter.PROCESS_TIME, value: appCpuPercent || ((totalUser / combinedTotal) * 100) }); } this._lastCpus = cpus; }; AutoCollectPerformance.prototype._trackMemory = function () { var freeMem = os.freemem(); var usedMem = process.memoryUsage().rss; var committedMemory = os.totalmem() - freeMem; this._client.trackMetric({ name: Constants.PerformanceCounter.PRIVATE_BYTES, value: usedMem }); this._client.trackMetric({ name: Constants.PerformanceCounter.AVAILABLE_BYTES, value: freeMem }); // Only supported by quickpulse service if (this._enableLiveMetricsCounters) { this._client.trackMetric({ name: Constants.QuickPulseCounter.COMMITTED_BYTES, value: committedMemory }); } }; AutoCollectPerformance.prototype._trackNetwork = function () { // track total request counters var lastRequests = this._lastRequests; var requests = { totalRequestCount: AutoCollectPerformance._totalRequestCount, totalFailedRequestCount: AutoCollectPerformance._totalFailedRequestCount, time: +new Date }; var intervalRequests = (requests.totalRequestCount - lastRequests.totalRequestCount) || 0; var intervalFailedRequests = (requests.totalFailedRequestCount - lastRequests.totalFailedRequestCount) || 0; var elapsedMs = requests.time - lastRequests.time; var elapsedSeconds = elapsedMs / 1000; var averageRequestExecutionTime = ((AutoCollectPerformance._intervalRequestExecutionTime - this._lastIntervalRequestExecutionTime) / intervalRequests) || 0; // default to 0 in case no requests in this interval this._lastIntervalRequestExecutionTime = AutoCollectPerformance._intervalRequestExecutionTime; // reset if (elapsedMs > 0) { var requestsPerSec = intervalRequests / elapsedSeconds; var failedRequestsPerSec = intervalFailedRequests / elapsedSeconds; this._client.trackMetric({ name: Constants.PerformanceCounter.REQUEST_RATE, value: requestsPerSec }); // Only send duration to live metrics if it has been updated! if (!this._enableLiveMetricsCounters || intervalRequests > 0) { this._client.trackMetric({ name: Constants.PerformanceCounter.REQUEST_DURATION, value: averageRequestExecutionTime }); } // Only supported by quickpulse service if (this._enableLiveMetricsCounters) { this._client.trackMetric({ name: Constants.QuickPulseCounter.REQUEST_FAILURE_RATE, value: failedRequestsPerSec }); } } this._lastRequests = requests; }; // Static counter is accumulated externally. Report the rate to client here // Note: This is currently only used with QuickPulse client AutoCollectPerformance.prototype._trackDependencyRate = function () { if (this._enableLiveMetricsCounters) { var lastDependencies = this._lastDependencies; var dependencies = { totalDependencyCount: AutoCollectPerformance._totalDependencyCount, totalFailedDependencyCount: AutoCollectPerformance._totalFailedDependencyCount, time: +new Date }; var intervalDependencies = (dependencies.totalDependencyCount - lastDependencies.totalDependencyCount) || 0; var intervalFailedDependencies = (dependencies.totalFailedDependencyCount - lastDependencies.totalFailedDependencyCount) || 0; var elapsedMs = dependencies.time - lastDependencies.time; var elapsedSeconds = elapsedMs / 1000; var averageDependencyExecutionTime = ((AutoCollectPerformance._intervalDependencyExecutionTime - this._lastIntervalDependencyExecutionTime) / intervalDependencies) || 0; this._lastIntervalDependencyExecutionTime = AutoCollectPerformance._intervalDependencyExecutionTime; // reset if (elapsedMs > 0) { var dependenciesPerSec = intervalDependencies / elapsedSeconds; var failedDependenciesPerSec = intervalFailedDependencies / elapsedSeconds; this._client.trackMetric({ name: Constants.QuickPulseCounter.DEPENDENCY_RATE, value: dependenciesPerSec }); this._client.trackMetric({ name: Constants.QuickPulseCounter.DEPENDENCY_FAILURE_RATE, value: failedDependenciesPerSec }); // redundant check for livemetrics, but kept for consistency w/ requests // Only send duration to live metrics if it has been updated! if (!this._enableLiveMetricsCounters || intervalDependencies > 0) { this._client.trackMetric({ name: Constants.QuickPulseCounter.DEPENDENCY_DURATION, value: averageDependencyExecutionTime }); } } this._lastDependencies = dependencies; } }; // Static counter is accumulated externally. Report the rate to client here // Note: This is currently only used with QuickPulse client AutoCollectPerformance.prototype._trackExceptionRate = function () { if (this._enableLiveMetricsCounters) { var lastExceptions = this._lastExceptions; var exceptions = { totalExceptionCount: AutoCollectPerformance._totalExceptionCount, time: +new Date }; var intervalExceptions = (exceptions.totalExceptionCount - lastExceptions.totalExceptionCount) || 0; var elapsedMs = exceptions.time - lastExceptions.time; var elapsedSeconds = elapsedMs / 1000; if (elapsedMs > 0) { var exceptionsPerSec = intervalExceptions / elapsedSeconds; this._client.trackMetric({ name: Constants.QuickPulseCounter.EXCEPTION_RATE, value: exceptionsPerSec }); } this._lastExceptions = exceptions; } }; AutoCollectPerformance.prototype.dispose = function () { AutoCollectPerformance.INSTANCE = null; this.enable(false); this._isInitialized = false; }; AutoCollectPerformance._totalRequestCount = 0; AutoCollectPerformance._totalFailedRequestCount = 0; AutoCollectPerformance._lastRequestExecutionTime = 0; AutoCollectPerformance._totalDependencyCount = 0; AutoCollectPerformance._totalFailedDependencyCount = 0; AutoCollectPerformance._lastDependencyExecutionTime = 0; AutoCollectPerformance._totalExceptionCount = 0; AutoCollectPerformance._intervalDependencyExecutionTime = 0; AutoCollectPerformance._intervalRequestExecutionTime = 0; return AutoCollectPerformance; }()); module.exports = AutoCollectPerformance; //# sourceMappingURL=Performance.js.map /***/ }), /***/ 1399: /***/ ((module) => { "use strict"; /** * Base class for helpers that read data from HTTP requst/response objects and convert them * into the telemetry contract objects. */ var RequestParser = (function () { function RequestParser() { } /** * Gets a url parsed out from request options */ RequestParser.prototype.getUrl = function () { return this.url; }; RequestParser.prototype.RequestParser = function () { this.startTime = +new Date(); }; RequestParser.prototype._setStatus = function (status, error) { var endTime = +new Date(); this.duration = endTime - this.startTime; this.statusCode = status; var properties = this.properties || {}; if (error) { if (typeof error === "string") { properties["error"] = error; } else if (error instanceof Error) { properties["error"] = error.message; } else if (typeof error === "object") { for (var key in error) { properties[key] = error[key] && error[key].toString && error[key].toString(); } } } this.properties = properties; }; RequestParser.prototype._isSuccess = function () { return (0 < this.statusCode) && (this.statusCode < 400); }; return RequestParser; }()); module.exports = RequestParser; //# sourceMappingURL=RequestParser.js.map /***/ }), /***/ 4751: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); var Contracts_1 = __webpack_require__(6812); var diagnostic_channel_1 = __webpack_require__(8262); var clients = []; // Mapping from bunyan levels defined at https://github.com/trentm/node-bunyan/blob/master/lib/bunyan.js#L256 var bunyanToAILevelMap = { 10: Contracts_1.SeverityLevel.Verbose, 20: Contracts_1.SeverityLevel.Verbose, 30: Contracts_1.SeverityLevel.Information, 40: Contracts_1.SeverityLevel.Warning, 50: Contracts_1.SeverityLevel.Error, 60: Contracts_1.SeverityLevel.Critical, }; var subscriber = function (event) { var message = event.data.result; clients.forEach(function (client) { var AIlevel = bunyanToAILevelMap[event.data.level]; if (message instanceof Error) { client.trackException({ exception: (message) }); } else { client.trackTrace({ message: message, severity: AIlevel }); } }); }; function enable(enabled, client) { if (enabled) { if (clients.length === 0) { diagnostic_channel_1.channel.subscribe("bunyan", subscriber); } ; clients.push(client); } else { clients = clients.filter(function (c) { return c != client; }); if (clients.length === 0) { diagnostic_channel_1.channel.unsubscribe("bunyan", subscriber); } } } exports.wp = enable; function dispose() { diagnostic_channel_1.channel.unsubscribe("bunyan", subscriber); clients = []; } __webpack_unused_export__ = dispose; //# sourceMappingURL=bunyan.sub.js.map /***/ }), /***/ 7308: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); var Contracts_1 = __webpack_require__(6812); var diagnostic_channel_1 = __webpack_require__(8262); var clients = []; var subscriber = function (event) { var message = event.data.message; clients.forEach(function (client) { if (message instanceof Error) { client.trackException({ exception: message }); } else { // Message can have a trailing newline if (message.lastIndexOf("\n") == message.length - 1) { message = message.substring(0, message.length - 1); } client.trackTrace({ message: message, severity: (event.data.stderr ? Contracts_1.SeverityLevel.Warning : Contracts_1.SeverityLevel.Information) }); } }); }; function enable(enabled, client) { if (enabled) { if (clients.length === 0) { diagnostic_channel_1.channel.subscribe("console", subscriber); } ; clients.push(client); } else { clients = clients.filter(function (c) { return c != client; }); if (clients.length === 0) { diagnostic_channel_1.channel.unsubscribe("console", subscriber); } } } exports.wp = enable; function dispose() { diagnostic_channel_1.channel.unsubscribe("console", subscriber); clients = []; } __webpack_unused_export__ = dispose; //# sourceMappingURL=console.sub.js.map /***/ }), /***/ 5026: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. Object.defineProperty(exports, "__esModule", ({ value: true })); var Logging = __webpack_require__(4798); exports.IsInitialized = !process.env["APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL"]; var TAG = "DiagnosticChannel"; if (exports.IsInitialized) { var publishers = __webpack_require__(431); var individualOptOuts = process.env["APPLICATION_INSIGHTS_NO_PATCH_MODULES"] || ""; var unpatchedModules = individualOptOuts.split(","); var modules = { bunyan: publishers.bunyan, console: publishers.console, mongodb: publishers.mongodb, mongodbCore: publishers.mongodbCore, mysql: publishers.mysql, redis: publishers.redis, pg: publishers.pg, pgPool: publishers.pgPool, winston: publishers.winston }; for (var mod in modules) { if (unpatchedModules.indexOf(mod) === -1) { modules[mod].enable(); Logging.info(TAG, "Subscribed to " + mod + " events"); } } if (unpatchedModules.length > 0) { Logging.info(TAG, "Some modules will not be patched", unpatchedModules); } } else { Logging.info(TAG, "Not subscribing to dependency autocollection because APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL was set"); } function registerContextPreservation(cb) { if (!exports.IsInitialized) { return; } __webpack_require__(8262).channel.addContextPreservation(cb); } exports.registerContextPreservation = registerContextPreservation; //# sourceMappingURL=initialization.js.map /***/ }), /***/ 7275: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); var diagnostic_channel_1 = __webpack_require__(8262); var clients = []; exports.qP = function (event) { if (event.data.event.commandName === "ismaster") { // suppress noisy ismaster commands } clients.forEach(function (client) { var dbName = (event.data.startedData && event.data.startedData.databaseName) || "Unknown database"; client.trackDependency({ target: dbName, data: event.data.event.commandName, name: event.data.event.commandName, duration: event.data.event.duration, success: event.data.succeeded, /* TODO: transmit result code from mongo */ resultCode: event.data.succeeded ? "0" : "1", dependencyTypeName: 'mongodb' }); }); }; function enable(enabled, client) { if (enabled) { if (clients.length === 0) { diagnostic_channel_1.channel.subscribe("mongodb", exports.qP); } ; clients.push(client); } else { clients = clients.filter(function (c) { return c != client; }); if (clients.length === 0) { diagnostic_channel_1.channel.unsubscribe("mongodb", exports.qP); } } } exports.wp = enable; //# sourceMappingURL=mongodb.sub.js.map /***/ }), /***/ 1614: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); var diagnostic_channel_1 = __webpack_require__(8262); var clients = []; exports.qP = function (event) { clients.forEach(function (client) { var queryObj = event.data.query || {}; var sqlString = queryObj.sql || "Unknown query"; var success = !event.data.err; var connection = queryObj._connection || {}; var connectionConfig = connection.config || {}; var dbName = connectionConfig.socketPath ? connectionConfig.socketPath : (connectionConfig.host || "localhost") + ":" + connectionConfig.port; client.trackDependency({ target: dbName, data: sqlString, name: sqlString, duration: event.data.duration, success: success, /* TODO: transmit result code from mysql */ resultCode: success ? "0" : "1", dependencyTypeName: "mysql" }); }); }; function enable(enabled, client) { if (enabled) { if (clients.length === 0) { diagnostic_channel_1.channel.subscribe("mysql", exports.qP); } ; clients.push(client); } else { clients = clients.filter(function (c) { return c != client; }); if (clients.length === 0) { diagnostic_channel_1.channel.unsubscribe("mysql", exports.qP); } } } exports.wp = enable; //# sourceMappingURL=mysql.sub.js.map /***/ }), /***/ 6174: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); var diagnostic_channel_1 = __webpack_require__(8262); var clients = []; exports.qP = function (event) { clients.forEach(function (client) { var q = event.data.query; var sql = (q.preparable && q.preparable.text) || q.plan || q.text || "unknown query"; var success = !event.data.error; var conn = event.data.database.host + ":" + event.data.database.port; client.trackDependency({ target: conn, data: sql, name: sql, duration: event.data.duration, success: success, resultCode: success ? "0" : "1", dependencyTypeName: "postgres" }); }); }; function enable(enabled, client) { if (enabled) { if (clients.length === 0) { diagnostic_channel_1.channel.subscribe("postgres", exports.qP); } ; clients.push(client); } else { clients = clients.filter(function (c) { return c != client; }); if (clients.length === 0) { diagnostic_channel_1.channel.unsubscribe("postgres", exports.qP); } } } exports.wp = enable; //# sourceMappingURL=postgres.sub.js.map /***/ }), /***/ 1953: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); var diagnostic_channel_1 = __webpack_require__(8262); var clients = []; exports.qP = function (event) { clients.forEach(function (client) { if (event.data.commandObj.command === "info") { // We don't want to report 'info', it's irrelevant return; } client.trackDependency({ target: event.data.address, name: event.data.commandObj.command, data: event.data.commandObj.command, duration: event.data.duration, success: !event.data.err, /* TODO: transmit result code from redis */ resultCode: event.data.err ? "1" : "0", dependencyTypeName: "redis" }); }); }; function enable(enabled, client) { if (enabled) { if (clients.length === 0) { diagnostic_channel_1.channel.subscribe("redis", exports.qP); } ; clients.push(client); } else { clients = clients.filter(function (c) { return c != client; }); if (clients.length === 0) { diagnostic_channel_1.channel.unsubscribe("redis", exports.qP); } } } exports.wp = enable; //# sourceMappingURL=redis.sub.js.map /***/ }), /***/ 2641: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); var Contracts_1 = __webpack_require__(6812); var diagnostic_channel_1 = __webpack_require__(8262); var clients = []; var winstonToAILevelMap = { syslog: function (og) { var map = { emerg: Contracts_1.SeverityLevel.Critical, alert: Contracts_1.SeverityLevel.Critical, crit: Contracts_1.SeverityLevel.Critical, error: Contracts_1.SeverityLevel.Error, warning: Contracts_1.SeverityLevel.Warning, notice: Contracts_1.SeverityLevel.Information, info: Contracts_1.SeverityLevel.Information, debug: Contracts_1.SeverityLevel.Verbose }; return map[og] === undefined ? Contracts_1.SeverityLevel.Information : map[og]; }, npm: function (og) { var map = { error: Contracts_1.SeverityLevel.Error, warn: Contracts_1.SeverityLevel.Warning, info: Contracts_1.SeverityLevel.Information, verbose: Contracts_1.SeverityLevel.Verbose, debug: Contracts_1.SeverityLevel.Verbose, silly: Contracts_1.SeverityLevel.Verbose }; return map[og] === undefined ? Contracts_1.SeverityLevel.Information : map[og]; }, unknown: function (og) { return Contracts_1.SeverityLevel.Information; } }; var subscriber = function (event) { var message = event.data.message; clients.forEach(function (client) { if (message instanceof Error) { client.trackException({ exception: message, properties: event.data.meta }); } else { var AIlevel = winstonToAILevelMap[event.data.levelKind](event.data.level); client.trackTrace({ message: message, severity: AIlevel, properties: event.data.meta }); } }); }; function enable(enabled, client) { if (enabled) { if (clients.length === 0) { diagnostic_channel_1.channel.subscribe("winston", subscriber); } ; clients.push(client); } else { clients = clients.filter(function (c) { return c != client; }); if (clients.length === 0) { diagnostic_channel_1.channel.unsubscribe("winston", subscriber); } } } exports.wp = enable; function dispose() { diagnostic_channel_1.channel.unsubscribe("winston", subscriber); clients = []; } __webpack_unused_export__ = dispose; //# sourceMappingURL=winston.sub.js.map /***/ }), /***/ 3498: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DEFAULT_BREEZE_ENDPOINT = "https://dc.services.visualstudio.com"; exports.DEFAULT_LIVEMETRICS_ENDPOINT = "https://rt.services.visualstudio.com"; exports.DEFAULT_LIVEMETRICS_HOST = "rt.services.visualstudio.com"; var QuickPulseCounter; (function (QuickPulseCounter) { // Memory QuickPulseCounter["COMMITTED_BYTES"] = "\\Memory\\Committed Bytes"; // CPU QuickPulseCounter["PROCESSOR_TIME"] = "\\Processor(_Total)\\% Processor Time"; // Request QuickPulseCounter["REQUEST_RATE"] = "\\ApplicationInsights\\Requests/Sec"; QuickPulseCounter["REQUEST_FAILURE_RATE"] = "\\ApplicationInsights\\Requests Failed/Sec"; QuickPulseCounter["REQUEST_DURATION"] = "\\ApplicationInsights\\Request Duration"; // Dependency QuickPulseCounter["DEPENDENCY_RATE"] = "\\ApplicationInsights\\Dependency Calls/Sec"; QuickPulseCounter["DEPENDENCY_FAILURE_RATE"] = "\\ApplicationInsights\\Dependency Calls Failed/Sec"; QuickPulseCounter["DEPENDENCY_DURATION"] = "\\ApplicationInsights\\Dependency Call Duration"; // Exception QuickPulseCounter["EXCEPTION_RATE"] = "\\ApplicationInsights\\Exceptions/Sec"; })(QuickPulseCounter = exports.QuickPulseCounter || (exports.QuickPulseCounter = {})); var PerformanceCounter; (function (PerformanceCounter) { // Memory PerformanceCounter["PRIVATE_BYTES"] = "\\Process(??APP_WIN32_PROC??)\\Private Bytes"; PerformanceCounter["AVAILABLE_BYTES"] = "\\Memory\\Available Bytes"; // CPU PerformanceCounter["PROCESSOR_TIME"] = "\\Processor(_Total)\\% Processor Time"; PerformanceCounter["PROCESS_TIME"] = "\\Process(??APP_WIN32_PROC??)\\% Processor Time"; // Requests PerformanceCounter["REQUEST_RATE"] = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Requests/Sec"; PerformanceCounter["REQUEST_DURATION"] = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Request Execution Time"; })(PerformanceCounter = exports.PerformanceCounter || (exports.PerformanceCounter = {})); ; /** * Map a PerformanceCounter/QuickPulseCounter to a QuickPulseCounter. If no mapping exists, mapping is *undefined* */ exports.PerformanceToQuickPulseCounter = (_a = {}, _a[PerformanceCounter.PROCESSOR_TIME] = QuickPulseCounter.PROCESSOR_TIME, _a[PerformanceCounter.REQUEST_RATE] = QuickPulseCounter.REQUEST_RATE, _a[PerformanceCounter.REQUEST_DURATION] = QuickPulseCounter.REQUEST_DURATION, // Remap quick pulse only counters _a[QuickPulseCounter.COMMITTED_BYTES] = QuickPulseCounter.COMMITTED_BYTES, _a[QuickPulseCounter.REQUEST_FAILURE_RATE] = QuickPulseCounter.REQUEST_FAILURE_RATE, _a[QuickPulseCounter.DEPENDENCY_RATE] = QuickPulseCounter.DEPENDENCY_RATE, _a[QuickPulseCounter.DEPENDENCY_FAILURE_RATE] = QuickPulseCounter.DEPENDENCY_FAILURE_RATE, _a[QuickPulseCounter.DEPENDENCY_DURATION] = QuickPulseCounter.DEPENDENCY_DURATION, _a[QuickPulseCounter.EXCEPTION_RATE] = QuickPulseCounter.EXCEPTION_RATE, _a); exports.QuickPulseDocumentType = { Event: "Event", Exception: "Exception", Trace: "Trace", Metric: "Metric", Request: "Request", Dependency: "RemoteDependency", Availability: "Availability" }; exports.QuickPulseType = { Event: "EventTelemetryDocument", Exception: "ExceptionTelemetryDocument", Trace: "TraceTelemetryDocument", Metric: "MetricTelemetryDocument", Request: "RequestTelemetryDocument", Dependency: "DependencyTelemetryDocument", Availability: "AvailabilityTelemetryDocument" }; exports.TelemetryTypeStringToQuickPulseType = { EventData: exports.QuickPulseType.Event, ExceptionData: exports.QuickPulseType.Exception, MessageData: exports.QuickPulseType.Trace, MetricData: exports.QuickPulseType.Metric, RequestData: exports.QuickPulseType.Request, RemoteDependencyData: exports.QuickPulseType.Dependency, AvailabilityData: exports.QuickPulseType.Availability }; exports.TelemetryTypeStringToQuickPulseDocumentType = { EventData: exports.QuickPulseDocumentType.Event, ExceptionData: exports.QuickPulseDocumentType.Exception, MessageData: exports.QuickPulseDocumentType.Trace, MetricData: exports.QuickPulseDocumentType.Metric, RequestData: exports.QuickPulseDocumentType.Request, RemoteDependencyData: exports.QuickPulseDocumentType.Dependency, AvailabilityData: exports.QuickPulseDocumentType.Availability }; var _a; //# sourceMappingURL=Constants.js.map /***/ }), /***/ 966: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var Generated_1 = __webpack_require__(5096); var RemoteDependencyDataConstants = (function () { function RemoteDependencyDataConstants() { } RemoteDependencyDataConstants.TYPE_HTTP = "Http"; RemoteDependencyDataConstants.TYPE_AI = "Http (tracked component)"; return RemoteDependencyDataConstants; }()); exports.RemoteDependencyDataConstants = RemoteDependencyDataConstants; function domainSupportsProperties(domain) { return "properties" in domain || domain instanceof Generated_1.EventData || domain instanceof Generated_1.ExceptionData || domain instanceof Generated_1.MessageData || domain instanceof Generated_1.MetricData || domain instanceof Generated_1.PageViewData || domain instanceof Generated_1.RemoteDependencyData || domain instanceof Generated_1.RequestData; } exports.domainSupportsProperties = domainSupportsProperties; //# sourceMappingURL=Constants.js.map /***/ }), /***/ 1932: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // THIS FILE WAS AUTOGENERATED var Domain = __webpack_require__(8778); "use strict"; /** * Instances of AvailabilityData represent the result of executing an availability test. */ var AvailabilityData = (function (_super) { __extends(AvailabilityData, _super); function AvailabilityData() { var _this = _super.call(this) || this; _this.ver = 2; _this.properties = {}; _this.measurements = {}; return _this; } return AvailabilityData; }(Domain)); module.exports = AvailabilityData; //# sourceMappingURL=AvailabilityData.js.map /***/ }), /***/ 3108: /***/ ((module) => { "use strict"; // THIS FILE WAS AUTOGENERATED /** * Data struct to contain only C section with custom fields. */ var Base = (function () { function Base() { } return Base; }()); module.exports = Base; //# sourceMappingURL=Base.js.map /***/ }), /***/ 5834: /***/ ((module) => { "use strict"; // THIS FILE WAS AUTOGENERATED var ContextTagKeys = (function () { function ContextTagKeys() { this.applicationVersion = "ai.application.ver"; this.deviceId = "ai.device.id"; this.deviceLocale = "ai.device.locale"; this.deviceModel = "ai.device.model"; this.deviceOEMName = "ai.device.oemName"; this.deviceOSVersion = "ai.device.osVersion"; this.deviceType = "ai.device.type"; this.locationIp = "ai.location.ip"; this.operationId = "ai.operation.id"; this.operationName = "ai.operation.name"; this.operationParentId = "ai.operation.parentId"; this.operationSyntheticSource = "ai.operation.syntheticSource"; this.operationCorrelationVector = "ai.operation.correlationVector"; this.sessionId = "ai.session.id"; this.sessionIsFirst = "ai.session.isFirst"; this.userAccountId = "ai.user.accountId"; this.userId = "ai.user.id"; this.userAuthUserId = "ai.user.authUserId"; this.cloudRole = "ai.cloud.role"; this.cloudRoleInstance = "ai.cloud.roleInstance"; this.internalSdkVersion = "ai.internal.sdkVersion"; this.internalAgentVersion = "ai.internal.agentVersion"; this.internalNodeName = "ai.internal.nodeName"; } return ContextTagKeys; }()); module.exports = ContextTagKeys; //# sourceMappingURL=ContextTagKeys.js.map /***/ }), /***/ 6794: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // THIS FILE WAS AUTOGENERATED var Base = __webpack_require__(3108); "use strict"; /** * Data struct to contain both B and C sections. */ var Data = (function (_super) { __extends(Data, _super); function Data() { return _super.call(this) || this; } return Data; }(Base)); module.exports = Data; //# sourceMappingURL=Data.js.map /***/ }), /***/ 4906: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // THIS FILE WAS AUTOGENERATED var DataPointType = __webpack_require__(7050); "use strict"; /** * Metric data single measurement. */ var DataPoint = (function () { function DataPoint() { this.kind = DataPointType.Measurement; } return DataPoint; }()); module.exports = DataPoint; //# sourceMappingURL=DataPoint.js.map /***/ }), /***/ 7050: /***/ ((module) => { "use strict"; // THIS FILE WAS AUTOGENERATED /** * Type of the metric data measurement. */ var DataPointType; (function (DataPointType) { DataPointType[DataPointType["Measurement"] = 0] = "Measurement"; DataPointType[DataPointType["Aggregation"] = 1] = "Aggregation"; })(DataPointType || (DataPointType = {})); module.exports = DataPointType; //# sourceMappingURL=DataPointType.js.map /***/ }), /***/ 8778: /***/ ((module) => { "use strict"; // THIS FILE WAS AUTOGENERATED /** * The abstract common base of all domains. */ var Domain = (function () { function Domain() { } return Domain; }()); module.exports = Domain; //# sourceMappingURL=Domain.js.map /***/ }), /***/ 1831: /***/ ((module) => { "use strict"; /** * System variables for a telemetry item. */ var Envelope = (function () { function Envelope() { this.ver = 1; this.sampleRate = 100.0; this.tags = {}; } return Envelope; }()); module.exports = Envelope; //# sourceMappingURL=Envelope.js.map /***/ }), /***/ 4161: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // THIS FILE WAS AUTOGENERATED var Domain = __webpack_require__(8778); "use strict"; /** * Instances of Event represent structured event records that can be grouped and searched by their properties. Event data item also creates a metric of event count by name. */ var EventData = (function (_super) { __extends(EventData, _super); function EventData() { var _this = _super.call(this) || this; _this.ver = 2; _this.properties = {}; _this.measurements = {}; return _this; } return EventData; }(Domain)); module.exports = EventData; //# sourceMappingURL=EventData.js.map /***/ }), /***/ 1926: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // THIS FILE WAS AUTOGENERATED var Domain = __webpack_require__(8778); "use strict"; /** * An instance of Exception represents a handled or unhandled exception that occurred during execution of the monitored application. */ var ExceptionData = (function (_super) { __extends(ExceptionData, _super); function ExceptionData() { var _this = _super.call(this) || this; _this.ver = 2; _this.exceptions = []; _this.properties = {}; _this.measurements = {}; return _this; } return ExceptionData; }(Domain)); module.exports = ExceptionData; //# sourceMappingURL=ExceptionData.js.map /***/ }), /***/ 3590: /***/ ((module) => { "use strict"; /** * Exception details of the exception in a chain. */ var ExceptionDetails = (function () { function ExceptionDetails() { this.hasFullStack = true; this.parsedStack = []; } return ExceptionDetails; }()); module.exports = ExceptionDetails; //# sourceMappingURL=ExceptionDetails.js.map /***/ }), /***/ 9549: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // THIS FILE WAS AUTOGENERATED var Domain = __webpack_require__(8778); "use strict"; /** * Instances of Message represent printf-like trace statements that are text-searched. Log4Net, NLog and other text-based log file entries are translated into intances of this type. The message does not have measurements. */ var MessageData = (function (_super) { __extends(MessageData, _super); function MessageData() { var _this = _super.call(this) || this; _this.ver = 2; _this.properties = {}; return _this; } return MessageData; }(Domain)); module.exports = MessageData; //# sourceMappingURL=MessageData.js.map /***/ }), /***/ 2381: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // THIS FILE WAS AUTOGENERATED var Domain = __webpack_require__(8778); "use strict"; /** * An instance of the Metric item is a list of measurements (single data points) and/or aggregations. */ var MetricData = (function (_super) { __extends(MetricData, _super); function MetricData() { var _this = _super.call(this) || this; _this.ver = 2; _this.metrics = []; _this.properties = {}; return _this; } return MetricData; }(Domain)); module.exports = MetricData; //# sourceMappingURL=MetricData.js.map /***/ }), /***/ 5050: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // THIS FILE WAS AUTOGENERATED var EventData = __webpack_require__(4161); "use strict"; /** * An instance of PageView represents a generic action on a page like a button click. It is also the base type for PageView. */ var PageViewData = (function (_super) { __extends(PageViewData, _super); function PageViewData() { var _this = _super.call(this) || this; _this.ver = 2; _this.properties = {}; _this.measurements = {}; return _this; } return PageViewData; }(EventData)); module.exports = PageViewData; //# sourceMappingURL=PageViewData.js.map /***/ }), /***/ 7884: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // THIS FILE WAS AUTOGENERATED var Domain = __webpack_require__(8778); "use strict"; /** * An instance of Remote Dependency represents an interaction of the monitored component with a remote component/service like SQL or an HTTP endpoint. */ var RemoteDependencyData = (function (_super) { __extends(RemoteDependencyData, _super); function RemoteDependencyData() { var _this = _super.call(this) || this; _this.ver = 2; _this.success = true; _this.properties = {}; _this.measurements = {}; return _this; } return RemoteDependencyData; }(Domain)); module.exports = RemoteDependencyData; //# sourceMappingURL=RemoteDependencyData.js.map /***/ }), /***/ 7208: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // THIS FILE WAS AUTOGENERATED var Domain = __webpack_require__(8778); "use strict"; /** * An instance of Request represents completion of an external request to the application to do work and contains a summary of that request execution and the results. */ var RequestData = (function (_super) { __extends(RequestData, _super); function RequestData() { var _this = _super.call(this) || this; _this.ver = 2; _this.properties = {}; _this.measurements = {}; return _this; } return RequestData; }(Domain)); module.exports = RequestData; //# sourceMappingURL=RequestData.js.map /***/ }), /***/ 6833: /***/ ((module) => { "use strict"; // THIS FILE WAS AUTOGENERATED /** * Defines the level of severity for the event. */ var SeverityLevel; (function (SeverityLevel) { SeverityLevel[SeverityLevel["Verbose"] = 0] = "Verbose"; SeverityLevel[SeverityLevel["Information"] = 1] = "Information"; SeverityLevel[SeverityLevel["Warning"] = 2] = "Warning"; SeverityLevel[SeverityLevel["Error"] = 3] = "Error"; SeverityLevel[SeverityLevel["Critical"] = 4] = "Critical"; })(SeverityLevel || (SeverityLevel = {})); module.exports = SeverityLevel; //# sourceMappingURL=SeverityLevel.js.map /***/ }), /***/ 2062: /***/ ((module) => { "use strict"; // THIS FILE WAS AUTOGENERATED /** * Stack frame information. */ var StackFrame = (function () { function StackFrame() { } return StackFrame; }()); module.exports = StackFrame; //# sourceMappingURL=StackFrame.js.map /***/ }), /***/ 5096: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // THIS FILE WAS AUTOGENERATED Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AvailabilityData = __webpack_require__(1932); exports.Base = __webpack_require__(3108); exports.ContextTagKeys = __webpack_require__(5834); exports.Data = __webpack_require__(6794); exports.DataPoint = __webpack_require__(4906); exports.DataPointType = __webpack_require__(7050); exports.Domain = __webpack_require__(8778); exports.Envelope = __webpack_require__(1831); exports.EventData = __webpack_require__(4161); exports.ExceptionData = __webpack_require__(1926); exports.ExceptionDetails = __webpack_require__(3590); exports.MessageData = __webpack_require__(9549); exports.MetricData = __webpack_require__(2381); exports.PageViewData = __webpack_require__(5050); exports.RemoteDependencyData = __webpack_require__(7884); exports.RequestData = __webpack_require__(7208); exports.SeverityLevel = __webpack_require__(6833); exports.StackFrame = __webpack_require__(2062); //# sourceMappingURL=index.js.map /***/ }), /***/ 8240: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /** * Converts the user-friendly enumeration TelemetryType to the underlying schema baseType value * @param type Type to convert to BaseData string */ function telemetryTypeToBaseType(type) { switch (type) { case TelemetryType.Event: return "EventData"; case TelemetryType.Exception: return "ExceptionData"; case TelemetryType.Trace: return "MessageData"; case TelemetryType.Metric: return "MetricData"; case TelemetryType.Request: return "RequestData"; case TelemetryType.Dependency: return "RemoteDependencyData"; case TelemetryType.Availability: return "AvailabilityData"; } return undefined; } exports.telemetryTypeToBaseType = telemetryTypeToBaseType; /** * Converts the schema baseType value to the user-friendly enumeration TelemetryType * @param baseType BaseData string to convert to TelemetryType */ function baseTypeToTelemetryType(baseType) { switch (baseType) { case "EventData": return TelemetryType.Event; case "ExceptionData": return TelemetryType.Exception; case "MessageData": return TelemetryType.Trace; case "MetricData": return TelemetryType.Metric; case "RequestData": return TelemetryType.Request; case "RemoteDependencyData": return TelemetryType.Dependency; case "AvailabilityData": return TelemetryType.Availability; } return undefined; } exports.baseTypeToTelemetryType = baseTypeToTelemetryType; exports.TelemetryTypeString = { Event: "EventData", Exception: "ExceptionData", Trace: "MessageData", Metric: "MetricData", Request: "RequestData", Dependency: "RemoteDependencyData", Availability: "AvailabilityData" }; /** * Telemetry types supported by this SDK */ var TelemetryType; (function (TelemetryType) { TelemetryType[TelemetryType["Event"] = 0] = "Event"; TelemetryType[TelemetryType["Exception"] = 1] = "Exception"; TelemetryType[TelemetryType["Trace"] = 2] = "Trace"; TelemetryType[TelemetryType["Metric"] = 3] = "Metric"; TelemetryType[TelemetryType["Request"] = 4] = "Request"; TelemetryType[TelemetryType["Dependency"] = 5] = "Dependency"; TelemetryType[TelemetryType["Availability"] = 6] = "Availability"; })(TelemetryType = exports.TelemetryType || (exports.TelemetryType = {})); //# sourceMappingURL=TelemetryType.js.map /***/ }), /***/ 8974: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", ({ value: true })); __export(__webpack_require__(8240)); //# sourceMappingURL=index.js.map /***/ }), /***/ 6812: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", ({ value: true })); __export(__webpack_require__(966)); __export(__webpack_require__(5096)); __export(__webpack_require__(8974)); //# sourceMappingURL=index.js.map /***/ }), /***/ 8560: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Logging = __webpack_require__(4798); var Channel = (function () { function Channel(isDisabled, getBatchSize, getBatchIntervalMs, sender) { this._buffer = []; this._lastSend = 0; this._isDisabled = isDisabled; this._getBatchSize = getBatchSize; this._getBatchIntervalMs = getBatchIntervalMs; this._sender = sender; } /** * Enable or disable disk-backed retry caching to cache events when client is offline (enabled by default) * These cached events are stored in your system or user's temporary directory and access restricted to your user when possible. * @param value if true events that occured while client is offline will be cached on disk * @param resendInterval The wait interval for resending cached events. * @param maxBytesOnDisk The maximum size (in bytes) that the created temporary directory for cache events can grow to, before caching is disabled. * @returns {Configuration} this class */ Channel.prototype.setUseDiskRetryCaching = function (value, resendInterval, maxBytesOnDisk) { this._sender.setDiskRetryMode(value, resendInterval, maxBytesOnDisk); }; /** * Add a telemetry item to the send buffer */ Channel.prototype.send = function (envelope) { var _this = this; // if master off switch is set, don't send any data if (this._isDisabled()) { // Do not send/save data return; } // validate input if (!envelope) { Logging.warn("Cannot send null/undefined telemetry"); return; } // check if the incoming payload is too large, truncate if necessary var payload = this._stringify(envelope); if (typeof payload !== "string") { return; } // enqueue the payload this._buffer.push(payload); // flush if we would exceed the max-size limit by adding this item if (this._buffer.length >= this._getBatchSize()) { this.triggerSend(false); return; } // ensure an invocation timeout is set if anything is in the buffer if (!this._timeoutHandle && this._buffer.length > 0) { this._timeoutHandle = setTimeout(function () { _this._timeoutHandle = null; _this.triggerSend(false); }, this._getBatchIntervalMs()); } }; /** * Immediately send buffered data */ Channel.prototype.triggerSend = function (isNodeCrashing, callback) { var bufferIsEmpty = this._buffer.length < 1; if (!bufferIsEmpty) { // compose an array of payloads var batch = this._buffer.join("\n"); // invoke send if (isNodeCrashing) { this._sender.saveOnCrash(batch); if (typeof callback === "function") { callback("data saved on crash"); } } else { this._sender.send(Buffer.from ? Buffer.from(batch) : new Buffer(batch), callback); } } // update lastSend time to enable throttling this._lastSend = +new Date; // clear buffer this._buffer.length = 0; clearTimeout(this._timeoutHandle); this._timeoutHandle = null; if (bufferIsEmpty && typeof callback === "function") { callback("no data to send"); } }; Channel.prototype._stringify = function (envelope) { try { return JSON.stringify(envelope); } catch (error) { Logging.warn("Failed to serialize payload", error, envelope); } }; return Channel; }()); module.exports = Channel; //# sourceMappingURL=Channel.js.map /***/ }), /***/ 105: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var CorrelationIdManager = __webpack_require__(7892); var ConnectionStringParser = __webpack_require__(8152); var Constants = __webpack_require__(3498); var url = __webpack_require__(8835); var Config = (function () { function Config(setupString) { var _this = this; this.endpointBase = Constants.DEFAULT_BREEZE_ENDPOINT; var connectionStringEnv = process.env[Config.ENV_connectionString]; var csCode = ConnectionStringParser.parse(setupString); var csEnv = ConnectionStringParser.parse(connectionStringEnv); var iKeyCode = !csCode.instrumentationkey && Object.keys(csCode).length > 0 ? null // CS was valid but instrumentation key was not provided, null and grab from env var : setupString; // CS was invalid, so it must be an ikey this.instrumentationKey = csCode.instrumentationkey || iKeyCode /* === instrumentationKey */ || csEnv.instrumentationkey || Config._getInstrumentationKey(); this.endpointUrl = (csCode.ingestionendpoint || csEnv.ingestionendpoint || this.endpointBase) + "/v2/track"; this.maxBatchSize = 250; this.maxBatchIntervalMs = 15000; this.disableAppInsights = false; this.samplingPercentage = 100; this.correlationIdRetryIntervalMs = 30 * 1000; this.correlationHeaderExcludedDomains = [ "*.core.windows.net", "*.core.chinacloudapi.cn", "*.core.cloudapi.de", "*.core.usgovcloudapi.net", "*.core.microsoft.scloud", "*.core.eaglex.ic.gov" ]; this.setCorrelationId = function (correlationId) { return _this.correlationId = correlationId; }; this.proxyHttpUrl = process.env[Config.ENV_http_proxy] || undefined; this.proxyHttpsUrl = process.env[Config.ENV_https_proxy] || undefined; this.httpAgent = undefined; this.httpsAgent = undefined; this.profileQueryEndpoint = csCode.ingestionendpoint || csEnv.ingestionendpoint || process.env[Config.ENV_profileQueryEndpoint] || this.endpointBase; this._quickPulseHost = csCode.liveendpoint || csEnv.liveendpoint || process.env[Config.ENV_quickPulseHost] || Constants.DEFAULT_LIVEMETRICS_HOST; // Parse quickPulseHost if it startswith http(s):// if (this._quickPulseHost.match(/^https?:\/\//)) { this._quickPulseHost = url.parse(this._quickPulseHost).host; } } Object.defineProperty(Config.prototype, "profileQueryEndpoint", { get: function () { return this._profileQueryEndpoint; }, set: function (endpoint) { CorrelationIdManager.cancelCorrelationIdQuery(this, this.setCorrelationId); this._profileQueryEndpoint = endpoint; this.correlationId = CorrelationIdManager.correlationIdPrefix; // Reset the correlationId while we wait for the new query CorrelationIdManager.queryCorrelationId(this, this.setCorrelationId); }, enumerable: true, configurable: true }); Object.defineProperty(Config.prototype, "quickPulseHost", { get: function () { return this._quickPulseHost; }, set: function (host) { this._quickPulseHost = host; }, enumerable: true, configurable: true }); Config._getInstrumentationKey = function () { // check for both the documented env variable and the azure-prefixed variable var iKey = process.env[Config.ENV_iKey] || process.env[Config.ENV_azurePrefix + Config.ENV_iKey] || process.env[Config.legacy_ENV_iKey] || process.env[Config.ENV_azurePrefix + Config.legacy_ENV_iKey]; if (!iKey || iKey == "") { throw new Error("Instrumentation key not found, pass the key in the config to this method or set the key in the environment variable APPINSIGHTS_INSTRUMENTATIONKEY before starting the server"); } return iKey; }; // Azure adds this prefix to all environment variables Config.ENV_azurePrefix = "APPSETTING_"; // This key is provided in the readme Config.ENV_iKey = "APPINSIGHTS_INSTRUMENTATIONKEY"; Config.legacy_ENV_iKey = "APPINSIGHTS_INSTRUMENTATION_KEY"; Config.ENV_profileQueryEndpoint = "APPINSIGHTS_PROFILE_QUERY_ENDPOINT"; Config.ENV_quickPulseHost = "APPINSIGHTS_QUICKPULSE_HOST"; // Azure Connection String Config.ENV_connectionString = "APPLICATIONINSIGHTS_CONNECTION_STRING"; // Native Metrics Opt Outs Config.ENV_nativeMetricsDisablers = "APPLICATION_INSIGHTS_DISABLE_EXTENDED_METRIC"; Config.ENV_nativeMetricsDisableAll = "APPLICATION_INSIGHTS_DISABLE_ALL_EXTENDED_METRICS"; Config.ENV_http_proxy = "http_proxy"; Config.ENV_https_proxy = "https_proxy"; return Config; }()); module.exports = Config; //# sourceMappingURL=Config.js.map /***/ }), /***/ 8152: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Constants = __webpack_require__(3498); var ConnectionStringParser = (function () { function ConnectionStringParser() { } ConnectionStringParser.parse = function (connectionString) { if (!connectionString) { return {}; } var kvPairs = connectionString.split(ConnectionStringParser._FIELDS_SEPARATOR); var result = kvPairs.reduce(function (fields, kv) { var kvParts = kv.split(ConnectionStringParser._FIELD_KEY_VALUE_SEPARATOR); if (kvParts.length === 2) { var key = kvParts[0].toLowerCase(); var value = kvParts[1]; fields[key] = value; } return fields; }, {}); if (Object.keys(result).length > 0) { // this is a valid connection string, so parse the results if (result.endpointsuffix) { // use endpoint suffix where overrides are not provided var locationPrefix = result.location ? result.location + "." : ""; result.ingestionendpoint = result.ingestionendpoint || ("https://" + locationPrefix + "dc." + result.endpointsuffix); result.liveendpoint = result.liveendpoint || ("https://" + locationPrefix + "live." + result.endpointsuffix); } // apply the default endpoints result.ingestionendpoint = result.ingestionendpoint || Constants.DEFAULT_BREEZE_ENDPOINT; result.liveendpoint = result.liveendpoint || Constants.DEFAULT_LIVEMETRICS_ENDPOINT; } return result; }; ConnectionStringParser._FIELDS_SEPARATOR = ";"; ConnectionStringParser._FIELD_KEY_VALUE_SEPARATOR = "="; return ConnectionStringParser; }()); module.exports = ConnectionStringParser; //# sourceMappingURL=ConnectionStringParser.js.map /***/ }), /***/ 9989: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var os = __webpack_require__(2087); var fs = __webpack_require__(5747); var path = __webpack_require__(5622); var Contracts = __webpack_require__(6812); var Logging = __webpack_require__(4798); var Context = (function () { function Context(packageJsonPath) { this.keys = new Contracts.ContextTagKeys(); this.tags = {}; this._loadApplicationContext(); this._loadDeviceContext(); this._loadInternalContext(); } Context.prototype._loadApplicationContext = function (packageJsonPath) { // note: this should return the host package.json packageJsonPath = packageJsonPath || path.resolve(__dirname, "../../../../package.json"); if (!Context.appVersion[packageJsonPath]) { Context.appVersion[packageJsonPath] = "unknown"; try { var packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8")); if (packageJson && typeof packageJson.version === "string") { Context.appVersion[packageJsonPath] = packageJson.version; } } catch (exception) { Logging.info("unable to read app version: ", exception); } } this.tags[this.keys.applicationVersion] = Context.appVersion[packageJsonPath]; }; Context.prototype._loadDeviceContext = function () { this.tags[this.keys.deviceId] = ""; this.tags[this.keys.cloudRoleInstance] = os && os.hostname(); this.tags[this.keys.deviceOSVersion] = os && (os.type() + " " + os.release()); this.tags[this.keys.cloudRole] = Context.DefaultRoleName; // not yet supported tags this.tags["ai.device.osArchitecture"] = os && os.arch(); this.tags["ai.device.osPlatform"] = os && os.platform(); }; Context.prototype._loadInternalContext = function () { // note: this should return the sdk package.json var packageJsonPath = path.resolve(__dirname, "../../package.json"); if (!Context.sdkVersion) { Context.sdkVersion = "unknown"; try { var packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8")); if (packageJson && typeof packageJson.version === "string") { Context.sdkVersion = packageJson.version; } } catch (exception) { Logging.info("unable to read app version: ", exception); } } this.tags[this.keys.internalSdkVersion] = "node:" + Context.sdkVersion; }; Context.DefaultRoleName = "Web"; Context.appVersion = {}; Context.sdkVersion = null; return Context; }()); module.exports = Context; //# sourceMappingURL=Context.js.map /***/ }), /***/ 7892: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Util = __webpack_require__(604); var Logging = __webpack_require__(4798); var CorrelationIdManager = (function () { function CorrelationIdManager() { } CorrelationIdManager.queryCorrelationId = function (config, callback) { // GET request to `${this.endpointBase}/api/profiles/${this.instrumentationKey}/appId` // If it 404s, the iKey is bad and we should give up // If it fails otherwise, try again later var appIdUrlString = config.profileQueryEndpoint + "/api/profiles/" + config.instrumentationKey + "/appId"; if (CorrelationIdManager.completedLookups.hasOwnProperty(appIdUrlString)) { callback(CorrelationIdManager.completedLookups[appIdUrlString]); return; } else if (CorrelationIdManager.pendingLookups[appIdUrlString]) { CorrelationIdManager.pendingLookups[appIdUrlString].push(callback); return; } CorrelationIdManager.pendingLookups[appIdUrlString] = [callback]; var fetchAppId = function () { if (!CorrelationIdManager.pendingLookups[appIdUrlString]) { // This query has been cancelled. return; } var requestOptions = { method: 'GET', // Ensure this request is not captured by auto-collection. // Note: we don't refer to the property in HttpDependencyParser because that would cause a cyclical dependency disableAppInsightsAutoCollection: true }; Logging.info(CorrelationIdManager.TAG, requestOptions); var req = Util.makeRequest(config, appIdUrlString, requestOptions, function (res) { if (res.statusCode === 200) { // Success; extract the appId from the body var appId_1 = ""; res.setEncoding("utf-8"); res.on('data', function (data) { appId_1 += data; }); res.on('end', function () { Logging.info(CorrelationIdManager.TAG, appId_1); var result = CorrelationIdManager.correlationIdPrefix + appId_1; CorrelationIdManager.completedLookups[appIdUrlString] = result; if (CorrelationIdManager.pendingLookups[appIdUrlString]) { CorrelationIdManager.pendingLookups[appIdUrlString].forEach(function (cb) { return cb(result); }); } delete CorrelationIdManager.pendingLookups[appIdUrlString]; }); } else if (res.statusCode >= 400 && res.statusCode < 500) { // Not found, probably a bad key. Do not try again. CorrelationIdManager.completedLookups[appIdUrlString] = undefined; delete CorrelationIdManager.pendingLookups[appIdUrlString]; } else { // Retry after timeout. setTimeout(fetchAppId, config.correlationIdRetryIntervalMs); } }); if (req) { req.on('error', function (error) { // Unable to contact endpoint. // Do nothing for now. Logging.warn(CorrelationIdManager.TAG, error); }); req.end(); } }; setTimeout(fetchAppId, 0); }; CorrelationIdManager.cancelCorrelationIdQuery = function (config, callback) { var appIdUrlString = config.profileQueryEndpoint + "/api/profiles/" + config.instrumentationKey + "/appId"; var pendingLookups = CorrelationIdManager.pendingLookups[appIdUrlString]; if (pendingLookups) { CorrelationIdManager.pendingLookups[appIdUrlString] = pendingLookups.filter(function (cb) { return cb != callback; }); if (CorrelationIdManager.pendingLookups[appIdUrlString].length == 0) { delete CorrelationIdManager.pendingLookups[appIdUrlString]; } } }; /** * Generate a request Id according to https://github.com/lmolkova/correlation/blob/master/hierarchical_request_id.md * @param parentId */ CorrelationIdManager.generateRequestId = function (parentId) { if (parentId) { parentId = parentId[0] == '|' ? parentId : '|' + parentId; if (parentId[parentId.length - 1] !== '.') { parentId += '.'; } var suffix = (CorrelationIdManager.currentRootId++).toString(16); return CorrelationIdManager.appendSuffix(parentId, suffix, '_'); } else { return CorrelationIdManager.generateRootId(); } }; /** * Given a hierarchical identifier of the form |X.* * return the root identifier X * @param id */ CorrelationIdManager.getRootId = function (id) { var endIndex = id.indexOf('.'); if (endIndex < 0) { endIndex = id.length; } var startIndex = id[0] === '|' ? 1 : 0; return id.substring(startIndex, endIndex); }; CorrelationIdManager.generateRootId = function () { return '|' + Util.w3cTraceId() + '.'; }; CorrelationIdManager.appendSuffix = function (parentId, suffix, delimiter) { if (parentId.length + suffix.length < CorrelationIdManager.requestIdMaxLength) { return parentId + suffix + delimiter; } // Combined identifier would be too long, so we must truncate it. // We need 9 characters of space: 8 for the overflow ID, 1 for the // overflow delimiter '#' var trimPosition = CorrelationIdManager.requestIdMaxLength - 9; if (parentId.length > trimPosition) { for (; trimPosition > 1; --trimPosition) { var c = parentId[trimPosition - 1]; if (c === '.' || c === '_') { break; } } } if (trimPosition <= 1) { // parentId is not a valid ID return CorrelationIdManager.generateRootId(); } suffix = Util.randomu32().toString(16); while (suffix.length < 8) { suffix = '0' + suffix; } return parentId.substring(0, trimPosition) + suffix + '#'; }; CorrelationIdManager.TAG = "CorrelationIdManager"; CorrelationIdManager.correlationIdPrefix = "cid-v1:"; CorrelationIdManager.w3cEnabled = false; // To avoid extraneous HTTP requests, we maintain a queue of callbacks waiting on a particular appId lookup, // as well as a cache of completed lookups so future requests can be resolved immediately. CorrelationIdManager.pendingLookups = {}; CorrelationIdManager.completedLookups = {}; CorrelationIdManager.requestIdMaxLength = 1024; CorrelationIdManager.currentRootId = Util.randomu32(); return CorrelationIdManager; }()); module.exports = CorrelationIdManager; //# sourceMappingURL=CorrelationIdManager.js.map /***/ }), /***/ 2656: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Contracts = __webpack_require__(6812); var Util = __webpack_require__(604); var CorrelationContextManager_1 = __webpack_require__(7602); /** * Manages the logic of creating envelopes from Telemetry objects */ var EnvelopeFactory = (function () { function EnvelopeFactory() { } /** * Creates envelope ready to be sent by Channel * @param telemetry Telemetry data * @param telemetryType Type of telemetry * @param commonProperties Bag of custom common properties to be added to the envelope * @param context Client context * @param config Client configuration */ EnvelopeFactory.createEnvelope = function (telemetry, telemetryType, commonProperties, context, config) { var data = null; switch (telemetryType) { case Contracts.TelemetryType.Trace: data = EnvelopeFactory.createTraceData(telemetry); break; case Contracts.TelemetryType.Dependency: data = EnvelopeFactory.createDependencyData(telemetry); break; case Contracts.TelemetryType.Event: data = EnvelopeFactory.createEventData(telemetry); break; case Contracts.TelemetryType.Exception: data = EnvelopeFactory.createExceptionData(telemetry); break; case Contracts.TelemetryType.Request: data = EnvelopeFactory.createRequestData(telemetry); break; case Contracts.TelemetryType.Metric: data = EnvelopeFactory.createMetricData(telemetry); break; case Contracts.TelemetryType.Availability: data = EnvelopeFactory.createAvailabilityData(telemetry); break; } if (commonProperties && Contracts.domainSupportsProperties(data.baseData)) { if (data && data.baseData) { // if no properties are specified just add the common ones if (!data.baseData.properties) { data.baseData.properties = commonProperties; } else { // otherwise, check each of the common ones for (var name in commonProperties) { // only override if the property `name` has not been set on this item if (!data.baseData.properties[name]) { data.baseData.properties[name] = commonProperties[name]; } } } } // sanitize properties data.baseData.properties = Util.validateStringMap(data.baseData.properties); } var iKey = config ? config.instrumentationKey || "" : ""; var envelope = new Contracts.Envelope(); envelope.data = data; envelope.iKey = iKey; // this is kind of a hack, but the envelope name is always the same as the data name sans the chars "data" envelope.name = "Microsoft.ApplicationInsights." + iKey.replace(/-/g, "") + "." + data.baseType.substr(0, data.baseType.length - 4); envelope.tags = this.getTags(context, telemetry.tagOverrides); envelope.time = (new Date()).toISOString(); envelope.ver = 1; envelope.sampleRate = config ? config.samplingPercentage : 100; // Exclude metrics from sampling by default if (telemetryType === Contracts.TelemetryType.Metric) { envelope.sampleRate = 100; } return envelope; }; EnvelopeFactory.createTraceData = function (telemetry) { var trace = new Contracts.MessageData(); trace.message = telemetry.message; trace.properties = telemetry.properties; if (!isNaN(telemetry.severity)) { trace.severityLevel = telemetry.severity; } else { trace.severityLevel = Contracts.SeverityLevel.Information; } var data = new Contracts.Data(); data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Trace); data.baseData = trace; return data; }; EnvelopeFactory.createDependencyData = function (telemetry) { var remoteDependency = new Contracts.RemoteDependencyData(); if (typeof telemetry.name === "string") { remoteDependency.name = telemetry.name.length > 1024 ? telemetry.name.slice(0, 1021) + '...' : telemetry.name; } remoteDependency.data = telemetry.data; remoteDependency.target = telemetry.target; remoteDependency.duration = Util.msToTimeSpan(telemetry.duration); remoteDependency.success = telemetry.success; remoteDependency.type = telemetry.dependencyTypeName; remoteDependency.properties = telemetry.properties; remoteDependency.resultCode = (telemetry.resultCode ? telemetry.resultCode + '' : ''); if (telemetry.id) { remoteDependency.id = telemetry.id; } else { remoteDependency.id = Util.w3cTraceId(); } var data = new Contracts.Data(); data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Dependency); data.baseData = remoteDependency; return data; }; EnvelopeFactory.createEventData = function (telemetry) { var event = new Contracts.EventData(); event.name = telemetry.name; event.properties = telemetry.properties; event.measurements = telemetry.measurements; var data = new Contracts.Data(); data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Event); data.baseData = event; return data; }; EnvelopeFactory.createExceptionData = function (telemetry) { var exception = new Contracts.ExceptionData(); exception.properties = telemetry.properties; if (!isNaN(telemetry.severity)) { exception.severityLevel = telemetry.severity; } else { exception.severityLevel = Contracts.SeverityLevel.Error; } exception.measurements = telemetry.measurements; exception.exceptions = []; var stack = telemetry.exception["stack"]; var exceptionDetails = new Contracts.ExceptionDetails(); exceptionDetails.message = telemetry.exception.message; exceptionDetails.typeName = telemetry.exception.name; exceptionDetails.parsedStack = this.parseStack(stack); exceptionDetails.hasFullStack = Util.isArray(exceptionDetails.parsedStack) && exceptionDetails.parsedStack.length > 0; exception.exceptions.push(exceptionDetails); var data = new Contracts.Data(); data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Exception); data.baseData = exception; return data; }; EnvelopeFactory.createRequestData = function (telemetry) { var requestData = new Contracts.RequestData(); if (telemetry.id) { requestData.id = telemetry.id; } else { requestData.id = Util.w3cTraceId(); } requestData.name = telemetry.name; requestData.url = telemetry.url; requestData.source = telemetry.source; requestData.duration = Util.msToTimeSpan(telemetry.duration); requestData.responseCode = (telemetry.resultCode ? telemetry.resultCode + '' : ''); requestData.success = telemetry.success; requestData.properties = telemetry.properties; var data = new Contracts.Data(); data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Request); data.baseData = requestData; return data; }; EnvelopeFactory.createMetricData = function (telemetry) { var metrics = new Contracts.MetricData(); // todo: enable client-batching of these metrics.metrics = []; var metric = new Contracts.DataPoint(); metric.count = !isNaN(telemetry.count) ? telemetry.count : 1; metric.kind = Contracts.DataPointType.Aggregation; metric.max = !isNaN(telemetry.max) ? telemetry.max : telemetry.value; metric.min = !isNaN(telemetry.min) ? telemetry.min : telemetry.value; metric.name = telemetry.name; metric.stdDev = !isNaN(telemetry.stdDev) ? telemetry.stdDev : 0; metric.value = telemetry.value; metrics.metrics.push(metric); metrics.properties = telemetry.properties; var data = new Contracts.Data(); data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Metric); data.baseData = metrics; return data; }; EnvelopeFactory.createAvailabilityData = function (telemetry) { var availabilityData = new Contracts.AvailabilityData(); if (telemetry.id) { availabilityData.id = telemetry.id; } else { availabilityData.id = Util.w3cTraceId(); } availabilityData.name = telemetry.name; availabilityData.duration = Util.msToTimeSpan(telemetry.duration); availabilityData.success = telemetry.success; availabilityData.runLocation = telemetry.runLocation; availabilityData.message = telemetry.message; availabilityData.measurements = telemetry.measurements; availabilityData.properties = telemetry.properties; var data = new Contracts.Data(); data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Availability); data.baseData = availabilityData; return data; }; EnvelopeFactory.getTags = function (context, tagOverrides) { var correlationContext = CorrelationContextManager_1.CorrelationContextManager.getCurrentContext(); // Make a copy of context tags so we don't alter the actual object // Also perform tag overriding var newTags = {}; if (context && context.tags) { for (var key in context.tags) { newTags[key] = context.tags[key]; } } if (tagOverrides) { for (var key in tagOverrides) { newTags[key] = tagOverrides[key]; } } // Fill in internally-populated values if not already set if (correlationContext) { newTags[context.keys.operationId] = newTags[context.keys.operationId] || correlationContext.operation.id; newTags[context.keys.operationName] = newTags[context.keys.operationName] || correlationContext.operation.name; newTags[context.keys.operationParentId] = newTags[context.keys.operationParentId] || correlationContext.operation.parentId; } return newTags; }; EnvelopeFactory.parseStack = function (stack) { var parsedStack = undefined; if (typeof stack === "string") { var frames = stack.split("\n"); parsedStack = []; var level = 0; var totalSizeInBytes = 0; for (var i = 0; i <= frames.length; i++) { var frame = frames[i]; if (_StackFrame.regex.test(frame)) { var parsedFrame = new _StackFrame(frames[i], level++); totalSizeInBytes += parsedFrame.sizeInBytes; parsedStack.push(parsedFrame); } } // DP Constraint - exception parsed stack must be < 32KB // remove frames from the middle to meet the threshold var exceptionParsedStackThreshold = 32 * 1024; if (totalSizeInBytes > exceptionParsedStackThreshold) { var left = 0; var right = parsedStack.length - 1; var size = 0; var acceptedLeft = left; var acceptedRight = right; while (left < right) { // check size var lSize = parsedStack[left].sizeInBytes; var rSize = parsedStack[right].sizeInBytes; size += lSize + rSize; if (size > exceptionParsedStackThreshold) { // remove extra frames from the middle var howMany = acceptedRight - acceptedLeft + 1; parsedStack.splice(acceptedLeft, howMany); break; } // update pointers acceptedLeft = left; acceptedRight = right; left++; right--; } } } return parsedStack; }; return EnvelopeFactory; }()); var _StackFrame = (function () { function _StackFrame(frame, level) { this.sizeInBytes = 0; this.level = level; this.method = ""; this.assembly = Util.trim(frame); var matches = frame.match(_StackFrame.regex); if (matches && matches.length >= 5) { this.method = Util.trim(matches[2]) || this.method; this.fileName = Util.trim(matches[4]) || ""; this.line = parseInt(matches[5]) || 0; } this.sizeInBytes += this.method.length; this.sizeInBytes += this.fileName.length; this.sizeInBytes += this.assembly.length; // todo: these might need to be removed depending on how the back-end settles on their size calculation this.sizeInBytes += _StackFrame.baseSize; this.sizeInBytes += this.level.toString().length; this.sizeInBytes += this.line.toString().length; } // regex to match stack frames from ie/chrome/ff // methodName=$2, fileName=$4, lineNo=$5, column=$6 _StackFrame.regex = /^([\s]+at)?(.*?)(\@|\s\(|\s)([^\(\@\n]+):([0-9]+):([0-9]+)(\)?)$/; _StackFrame.baseSize = 58; //'{"method":"","level":,"assembly":"","fileName":"","line":}'.length return _StackFrame; }()); module.exports = EnvelopeFactory; //# sourceMappingURL=EnvelopeFactory.js.map /***/ }), /***/ 4798: /***/ ((module) => { "use strict"; var Logging = (function () { function Logging() { } Logging.info = function (message) { var optionalParams = []; for (var _i = 1; _i < arguments.length; _i++) { optionalParams[_i - 1] = arguments[_i]; } if (Logging.enableDebug) { console.info(Logging.TAG + message, optionalParams); } }; Logging.warn = function (message) { var optionalParams = []; for (var _i = 1; _i < arguments.length; _i++) { optionalParams[_i - 1] = arguments[_i]; } if (!Logging.disableWarnings) { console.warn(Logging.TAG + message, optionalParams); } }; Logging.enableDebug = false; Logging.disableWarnings = false; Logging.disableErrors = false; Logging.TAG = "ApplicationInsights:"; return Logging; }()); module.exports = Logging; //# sourceMappingURL=Logging.js.map /***/ }), /***/ 7264: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var TelemetryClient = __webpack_require__(1199); var ServerRequestTracking = __webpack_require__(4784); var ClientRequestTracking = __webpack_require__(4665); var Logging = __webpack_require__(4798); /** * Application Insights Telemetry Client for Node.JS. Provides the Application Insights TelemetryClient API * in addition to Node-specific helper functions. * Construct a new TelemetryClient to have an instance with a different configuration than the default client. * In most cases, `appInsights.defaultClient` should be used instead. */ var NodeClient = (function (_super) { __extends(NodeClient, _super); function NodeClient() { return _super !== null && _super.apply(this, arguments) || this; } /** * Log RequestTelemetry from HTTP request and response. This method will log immediately without waitng for request completion * and it requires duration parameter to be specified on NodeHttpRequestTelemetry object. * Use trackNodeHttpRequest function to log the telemetry after request completion * @param telemetry Object encapsulating incoming request, response and duration information */ NodeClient.prototype.trackNodeHttpRequestSync = function (telemetry) { if (telemetry && telemetry.request && telemetry.response && telemetry.duration) { ServerRequestTracking.trackRequestSync(this, telemetry); } else { Logging.warn("trackNodeHttpRequestSync requires NodeHttpRequestTelemetry object with request, response and duration specified."); } }; /** * Log RequestTelemetry from HTTP request and response. This method will `follow` the request to completion. * Use trackNodeHttpRequestSync function to log telemetry immediately without waiting for request completion * @param telemetry Object encapsulating incoming request and response information */ NodeClient.prototype.trackNodeHttpRequest = function (telemetry) { if (telemetry.duration || telemetry.error) { Logging.warn("trackNodeHttpRequest will ignore supplied duration and error parameters. These values are collected from the request and response objects."); } if (telemetry && telemetry.request && telemetry.response) { ServerRequestTracking.trackRequest(this, telemetry); } else { Logging.warn("trackNodeHttpRequest requires NodeHttpRequestTelemetry object with request and response specified."); } }; /** * Log DependencyTelemetry from outgoing HTTP request. This method will instrument the outgoing request and append * the specified headers and will log the telemetry when outgoing request is complete * @param telemetry Object encapsulating outgoing request information */ NodeClient.prototype.trackNodeHttpDependency = function (telemetry) { if (telemetry && telemetry.request) { ClientRequestTracking.trackRequest(this, telemetry); } else { Logging.warn("trackNodeHttpDependency requires NodeHttpDependencyTelemetry object with request specified."); } }; return NodeClient; }(TelemetryClient)); module.exports = NodeClient; //# sourceMappingURL=NodeClient.js.map /***/ }), /***/ 6165: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; var os = __webpack_require__(2087); var Contracts = __webpack_require__(6812); var Constants = __webpack_require__(3498); var Util = __webpack_require__(604); var Logging = __webpack_require__(4798); var StreamId = Util.w3cTraceId(); // Create a guid var QuickPulseEnvelopeFactory = (function () { function QuickPulseEnvelopeFactory() { } QuickPulseEnvelopeFactory.createQuickPulseEnvelope = function (metrics, documents, config, context) { var machineName = (os && typeof os.hostname === "function" && os.hostname()) || "Unknown"; // Note: os.hostname() was added in node v0.3.3 var instance = (context.tags && context.keys && context.keys.cloudRoleInstance && context.tags[context.keys.cloudRoleInstance]) || machineName; var envelope = { Documents: documents.length > 0 ? documents : null, InstrumentationKey: config.instrumentationKey || "", Metrics: metrics.length > 0 ? metrics : null, InvariantVersion: 1, Timestamp: "/Date(" + Date.now() + ")/", Version: context.tags[context.keys.internalSdkVersion], StreamId: StreamId, MachineName: machineName, Instance: instance }; return envelope; }; QuickPulseEnvelopeFactory.createQuickPulseMetric = function (telemetry) { var data; data = { Name: telemetry.name, Value: telemetry.value, Weight: telemetry.count || 1 }; return data; }; QuickPulseEnvelopeFactory.telemetryEnvelopeToQuickPulseDocument = function (envelope) { switch (envelope.data.baseType) { case Contracts.TelemetryTypeString.Event: return QuickPulseEnvelopeFactory.createQuickPulseEventDocument(envelope); case Contracts.TelemetryTypeString.Exception: return QuickPulseEnvelopeFactory.createQuickPulseExceptionDocument(envelope); case Contracts.TelemetryTypeString.Trace: return QuickPulseEnvelopeFactory.createQuickPulseTraceDocument(envelope); case Contracts.TelemetryTypeString.Dependency: return QuickPulseEnvelopeFactory.createQuickPulseDependencyDocument(envelope); case Contracts.TelemetryTypeString.Request: return QuickPulseEnvelopeFactory.createQuickPulseRequestDocument(envelope); } return null; }; QuickPulseEnvelopeFactory.createQuickPulseEventDocument = function (envelope) { var document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope); var name = envelope.data.baseData.name; var eventDocument = __assign({}, document, { Name: name }); return eventDocument; }; QuickPulseEnvelopeFactory.createQuickPulseTraceDocument = function (envelope) { var document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope); var severityLevel = envelope.data.baseData.severityLevel || 0; var traceDocument = __assign({}, document, { Message: envelope.data.baseData.message, SeverityLevel: Contracts.SeverityLevel[severityLevel] }); return traceDocument; }; QuickPulseEnvelopeFactory.createQuickPulseExceptionDocument = function (envelope) { var document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope); var exceptionDetails = envelope.data.baseData.exceptions; var exception = ''; var exceptionMessage = ''; var exceptionType = ''; // Try to fill exception information from first error only if (exceptionDetails && exceptionDetails.length > 0) { // Try to grab the stack from parsedStack or stack if (exceptionDetails[0].parsedStack && exceptionDetails[0].parsedStack.length > 0) { exceptionDetails[0].parsedStack.forEach(function (err) { exception += err.assembly + "\n"; }); } else if (exceptionDetails[0].stack && exceptionDetails[0].stack.length > 0) { exception = exceptionDetails[0].stack; } exceptionMessage = exceptionDetails[0].message; exceptionType = exceptionDetails[0].typeName; } var exceptionDocument = __assign({}, document, { Exception: exception, ExceptionMessage: exceptionMessage, ExceptionType: exceptionType }); return exceptionDocument; }; QuickPulseEnvelopeFactory.createQuickPulseRequestDocument = function (envelope) { var document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope); var baseData = envelope.data.baseData; var requestDocument = __assign({}, document, { Name: baseData.name, Success: baseData.success, Duration: baseData.duration, ResponseCode: baseData.responseCode, OperationName: baseData.name // TODO: is this correct? }); return requestDocument; }; QuickPulseEnvelopeFactory.createQuickPulseDependencyDocument = function (envelope) { var document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope); var baseData = envelope.data.baseData; var dependencyDocument = __assign({}, document, { Name: baseData.name, Target: baseData.target, Success: baseData.success, Duration: baseData.duration, ResultCode: baseData.resultCode, CommandName: baseData.data, OperationName: document.OperationId, DependencyTypeName: baseData.type }); return dependencyDocument; }; QuickPulseEnvelopeFactory.createQuickPulseDocument = function (envelope) { var documentType; var __type; var operationId, properties; if (envelope.data.baseType) { __type = Constants.TelemetryTypeStringToQuickPulseType[envelope.data.baseType]; documentType = Constants.TelemetryTypeStringToQuickPulseDocumentType[envelope.data.baseType]; } else { // Remark: This should never be hit because createQuickPulseDocument is only called within // valid baseType values Logging.warn("Document type invalid; not sending live metric document", envelope.data.baseType); } operationId = envelope.tags[QuickPulseEnvelopeFactory.keys.operationId]; properties = QuickPulseEnvelopeFactory.aggregateProperties(envelope); var document = { DocumentType: documentType, __type: __type, OperationId: operationId, Version: "1.0", Properties: properties }; return document; }; QuickPulseEnvelopeFactory.aggregateProperties = function (envelope) { var properties = []; // Collect measurements var meas = (envelope.data.baseData).measurements || {}; for (var key in meas) { if (meas.hasOwnProperty(key)) { var value = meas[key]; var property = { key: key, value: value }; properties.push(property); } } // Collect properties var props = (envelope.data.baseData).properties || {}; for (var key in props) { if (props.hasOwnProperty(key)) { var value = props[key]; var property = { key: key, value: value }; properties.push(property); } } return properties; }; QuickPulseEnvelopeFactory.keys = new Contracts.ContextTagKeys(); return QuickPulseEnvelopeFactory; }()); module.exports = QuickPulseEnvelopeFactory; //# sourceMappingURL=QuickPulseEnvelopeFactory.js.map /***/ }), /***/ 5808: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var https = __webpack_require__(7211); var AutoCollectHttpDependencies = __webpack_require__(4665); var Logging = __webpack_require__(4798); var QuickPulseConfig = { method: "POST", time: "x-ms-qps-transmission-time", subscribed: "x-ms-qps-subscribed" }; var QuickPulseSender = (function () { function QuickPulseSender(config) { this._config = config; this._consecutiveErrors = 0; } QuickPulseSender.prototype.ping = function (envelope, done) { this._submitData(envelope, done, "ping"); }; QuickPulseSender.prototype.post = function (envelope, done) { // Important: When POSTing data, envelope must be an array this._submitData([envelope], done, "post"); }; QuickPulseSender.prototype._submitData = function (envelope, done, postOrPing) { var _this = this; var payload = JSON.stringify(envelope); var options = (_a = {}, _a[AutoCollectHttpDependencies.disableCollectionRequestOption] = true, _a.host = this._config.quickPulseHost, _a.method = QuickPulseConfig.method, _a.path = "/QuickPulseService.svc/" + postOrPing + "?ikey=" + this._config.instrumentationKey, _a.headers = (_b = { 'Expect': '100-continue' }, _b[QuickPulseConfig.time] = 10000 * Date.now(), _b['Content-Type'] = 'application\/json', _b['Content-Length'] = Buffer.byteLength(payload), _b), _a); var req = https.request(options, function (res) { var shouldPOSTData = res.headers[QuickPulseConfig.subscribed] === "true"; _this._consecutiveErrors = 0; done(shouldPOSTData, res); }); req.on("error", function (error) { // Unable to contact qps endpoint. // Do nothing for now. _this._consecutiveErrors++; // LOG every error, but WARN instead when X number of consecutive errors occur var notice = "Transient error connecting to the Live Metrics endpoint. This packet will not appear in your Live Metrics Stream. Error:"; if (_this._consecutiveErrors % QuickPulseSender.MAX_QPS_FAILURES_BEFORE_WARN === 0) { notice = "Live Metrics endpoint could not be reached " + _this._consecutiveErrors + " consecutive times. Most recent error:"; Logging.warn(QuickPulseSender.TAG, notice, error); } else { // Potentially transient error, do not change the ping/post state yet. Logging.info(QuickPulseSender.TAG, notice, error); } done(); }); req.write(payload); req.end(); var _a, _b; }; QuickPulseSender.TAG = "QuickPulseSender"; QuickPulseSender.MAX_QPS_FAILURES_BEFORE_WARN = 25; return QuickPulseSender; }()); module.exports = QuickPulseSender; //# sourceMappingURL=QuickPulseSender.js.map /***/ }), /***/ 6836: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Logging = __webpack_require__(4798); var Config = __webpack_require__(105); var QuickPulseEnvelopeFactory = __webpack_require__(6165); var QuickPulseSender = __webpack_require__(5808); var Constants = __webpack_require__(3498); var Context = __webpack_require__(9989); /** State Container for sending to the QuickPulse Service */ var QuickPulseStateManager = (function () { function QuickPulseStateManager(iKey, context) { this._isCollectingData = false; this._lastSuccessTime = Date.now(); this._lastSendSucceeded = true; this._metrics = {}; this._documents = []; this._collectors = []; this.config = new Config(iKey); this.context = context || new Context(); this._sender = new QuickPulseSender(this.config); this._isEnabled = false; } /** * * @param collector */ QuickPulseStateManager.prototype.addCollector = function (collector) { this._collectors.push(collector); }; /** * Override of TelemetryClient.trackMetric */ QuickPulseStateManager.prototype.trackMetric = function (telemetry) { this._addMetric(telemetry); }; /** * Add a document to the current buffer * @param envelope */ QuickPulseStateManager.prototype.addDocument = function (envelope) { var document = QuickPulseEnvelopeFactory.telemetryEnvelopeToQuickPulseDocument(envelope); if (document) { this._documents.push(document); } }; /** * Enable or disable communication with QuickPulseService * @param isEnabled */ QuickPulseStateManager.prototype.enable = function (isEnabled) { if (isEnabled && !this._isEnabled) { this._isEnabled = true; this._goQuickPulse(); } else if (!isEnabled && this._isEnabled) { this._isEnabled = false; clearTimeout(this._handle); this._handle = undefined; } }; /** * Enable or disable all collectors in this instance * @param enable */ QuickPulseStateManager.prototype.enableCollectors = function (enable) { this._collectors.forEach(function (collector) { collector.enable(enable); }); }; /** * Add the metric to this buffer. If same metric already exists in this buffer, add weight to it * @param telemetry */ QuickPulseStateManager.prototype._addMetric = function (telemetry) { var value = telemetry.value; var count = telemetry.count || 1; var name = Constants.PerformanceToQuickPulseCounter[telemetry.name]; if (name) { if (this._metrics[name]) { this._metrics[name].Value = (this._metrics[name].Value * this._metrics[name].Weight + value * count) / (this._metrics[name].Weight + count); this._metrics[name].Weight += count; } else { this._metrics[name] = QuickPulseEnvelopeFactory.createQuickPulseMetric(telemetry); this._metrics[name].Name = name; this._metrics[name].Weight = 1; } } }; QuickPulseStateManager.prototype._resetQuickPulseBuffer = function () { delete this._metrics; this._metrics = {}; this._documents.length = 0; }; QuickPulseStateManager.prototype._goQuickPulse = function () { var _this = this; // Create envelope from Documents and Metrics var metrics = Object.keys(this._metrics).map(function (k) { return _this._metrics[k]; }); var envelope = QuickPulseEnvelopeFactory.createQuickPulseEnvelope(metrics, this._documents.slice(), this.config, this.context); // Clear this document, metric buffer this._resetQuickPulseBuffer(); // Send it to QuickPulseService, if collecting if (this._isCollectingData) { this._post(envelope); } else { this._ping(envelope); } var currentTimeout = this._isCollectingData ? QuickPulseStateManager.POST_INTERVAL : QuickPulseStateManager.PING_INTERVAL; if (this._isCollectingData && Date.now() - this._lastSuccessTime >= QuickPulseStateManager.MAX_POST_WAIT_TIME && !this._lastSendSucceeded) { // Haven't posted successfully in 20 seconds, so wait 60 seconds and ping this._isCollectingData = false; currentTimeout = QuickPulseStateManager.FALLBACK_INTERVAL; } else if (!this._isCollectingData && Date.now() - this._lastSuccessTime >= QuickPulseStateManager.MAX_PING_WAIT_TIME && !this._lastSendSucceeded) { // Haven't pinged successfully in 60 seconds, so wait another 60 seconds currentTimeout = QuickPulseStateManager.FALLBACK_INTERVAL; } this._lastSendSucceeded = null; this._handle = setTimeout(this._goQuickPulse.bind(this), currentTimeout); this._handle.unref(); // Don't block apps from terminating }; QuickPulseStateManager.prototype._ping = function (envelope) { this._sender.ping(envelope, this._quickPulseDone.bind(this)); }; QuickPulseStateManager.prototype._post = function (envelope) { this._sender.post(envelope, this._quickPulseDone.bind(this)); }; /** * Change the current QPS send state. (shouldPOST == undefined) --> error, but do not change the state yet. */ QuickPulseStateManager.prototype._quickPulseDone = function (shouldPOST, res) { if (shouldPOST != undefined) { if (this._isCollectingData !== shouldPOST) { Logging.info("Live Metrics sending data", shouldPOST); this.enableCollectors(shouldPOST); } this._isCollectingData = shouldPOST; if (res && res.statusCode < 300 && res.statusCode >= 200) { this._lastSuccessTime = Date.now(); this._lastSendSucceeded = true; } else { this._lastSendSucceeded = false; } } else { // Received an error, keep the state as is this._lastSendSucceeded = false; } }; QuickPulseStateManager.MAX_POST_WAIT_TIME = 20000; QuickPulseStateManager.MAX_PING_WAIT_TIME = 60000; QuickPulseStateManager.FALLBACK_INTERVAL = 60000; QuickPulseStateManager.PING_INTERVAL = 5000; QuickPulseStateManager.POST_INTERVAL = 1000; return QuickPulseStateManager; }()); module.exports = QuickPulseStateManager; //# sourceMappingURL=QuickPulseStateManager.js.map /***/ }), /***/ 3918: /***/ ((module) => { "use strict"; module.exports = { /** * Request-Context header */ requestContextHeader: "request-context", /** * Source instrumentation header that is added by an application while making http * requests and retrieved by the other application when processing incoming requests. */ requestContextSourceKey: "appId", /** * Target instrumentation header that is added to the response and retrieved by the * calling application when processing incoming responses. */ requestContextTargetKey: "appId", /** * Request-Id header */ requestIdHeader: "request-id", /** * Legacy Header containing the id of the immidiate caller */ parentIdHeader: "x-ms-request-id", /** * Legacy Header containing the correlation id that kept the same for every telemetry item * accross transactions */ rootIdHeader: "x-ms-request-root-id", /** * Correlation-Context header * * Not currently actively used, but the contents should be passed from incoming to outgoing requests */ correlationContextHeader: "correlation-context", /** * W3C distributed tracing protocol header */ traceparentHeader: "traceparent", /** * W3C distributed tracing protocol state header */ traceStateHeader: "tracestate" }; //# sourceMappingURL=RequestResponseHeaders.js.map /***/ }), /***/ 3819: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var fs = __webpack_require__(5747); var os = __webpack_require__(2087); var path = __webpack_require__(5622); var zlib = __webpack_require__(8761); var child_process = __webpack_require__(3129); var Logging = __webpack_require__(4798); var AutoCollectHttpDependencies = __webpack_require__(4665); var Util = __webpack_require__(604); var Sender = (function () { function Sender(config, onSuccess, onError) { this._config = config; this._onSuccess = onSuccess; this._onError = onError; this._enableDiskRetryMode = false; this._resendInterval = Sender.WAIT_BETWEEN_RESEND; this._maxBytesOnDisk = Sender.MAX_BYTES_ON_DISK; this._numConsecutiveFailures = 0; if (!Sender.OS_PROVIDES_FILE_PROTECTION) { // Node's chmod levels do not appropriately restrict file access on Windows // Use the built-in command line tool ICACLS on Windows to properly restrict // access to the temporary directory used for disk retry mode. if (Sender.USE_ICACLS) { // This should be async - but it's currently safer to have this synchronous // This guarantees we can immediately fail setDiskRetryMode if we need to try { Sender.OS_PROVIDES_FILE_PROTECTION = fs.existsSync(Sender.ICACLS_PATH); } catch (e) { } if (!Sender.OS_PROVIDES_FILE_PROTECTION) { Logging.warn(Sender.TAG, "Could not find ICACLS in expected location! This is necessary to use disk retry mode on Windows."); } } else { // chmod works everywhere else Sender.OS_PROVIDES_FILE_PROTECTION = true; } } } /** * Enable or disable offline mode */ Sender.prototype.setDiskRetryMode = function (value, resendInterval, maxBytesOnDisk) { this._enableDiskRetryMode = Sender.OS_PROVIDES_FILE_PROTECTION && value; if (typeof resendInterval === 'number' && resendInterval >= 0) { this._resendInterval = Math.floor(resendInterval); } if (typeof maxBytesOnDisk === 'number' && maxBytesOnDisk >= 0) { this._maxBytesOnDisk = Math.floor(maxBytesOnDisk); } if (value && !Sender.OS_PROVIDES_FILE_PROTECTION) { this._enableDiskRetryMode = false; Logging.warn(Sender.TAG, "Ignoring request to enable disk retry mode. Sufficient file protection capabilities were not detected."); } }; Sender.prototype.send = function (payload, callback) { var _this = this; var endpointUrl = this._config.endpointUrl; // todo: investigate specifying an agent here: https://nodejs.org/api/http.html#http_class_http_agent var options = { method: "POST", withCredentials: false, headers: { "Content-Type": "application/x-json-stream" } }; zlib.gzip(payload, function (err, buffer) { var dataToSend = buffer; if (err) { Logging.warn(err); dataToSend = payload; // something went wrong so send without gzip options.headers["Content-Length"] = payload.length.toString(); } else { options.headers["Content-Encoding"] = "gzip"; options.headers["Content-Length"] = buffer.length; } Logging.info(Sender.TAG, options); // Ensure this request is not captured by auto-collection. options[AutoCollectHttpDependencies.disableCollectionRequestOption] = true; var requestCallback = function (res) { res.setEncoding("utf-8"); //returns empty if the data is accepted var responseString = ""; res.on("data", function (data) { responseString += data; }); res.on("end", function () { _this._numConsecutiveFailures = 0; Logging.info(Sender.TAG, responseString); if (typeof _this._onSuccess === "function") { _this._onSuccess(responseString); } if (typeof callback === "function") { callback(responseString); } if (_this._enableDiskRetryMode) { // try to send any cached events if the user is back online if (res.statusCode === 200) { setTimeout(function () { return _this._sendFirstFileOnDisk(); }, _this._resendInterval).unref(); // store to disk in case of burst throttling } else if (res.statusCode === 408 || res.statusCode === 429 || res.statusCode === 439 || res.statusCode === 500 || res.statusCode === 503) { // TODO: Do not support partial success (206) until _sendFirstFileOnDisk checks payload age _this._storeToDisk(payload); } } }); }; var req = Util.makeRequest(_this._config, endpointUrl, options, requestCallback); req.on("error", function (error) { // todo: handle error codes better (group to recoverable/non-recoverable and persist) _this._numConsecutiveFailures++; // Only use warn level if retries are disabled or we've had some number of consecutive failures sending data // This is because warn level is printed in the console by default, and we don't want to be noisy for transient and self-recovering errors // Continue informing on each failure if verbose logging is being used if (!_this._enableDiskRetryMode || _this._numConsecutiveFailures > 0 && _this._numConsecutiveFailures % Sender.MAX_CONNECTION_FAILURES_BEFORE_WARN === 0) { var notice = "Ingestion endpoint could not be reached. This batch of telemetry items has been lost. Use Disk Retry Caching to enable resending of failed telemetry. Error:"; if (_this._enableDiskRetryMode) { notice = "Ingestion endpoint could not be reached " + _this._numConsecutiveFailures + " consecutive times. There may be resulting telemetry loss. Most recent error:"; } Logging.warn(Sender.TAG, notice, error); } else { var notice = "Transient failure to reach ingestion endpoint. This batch of telemetry items will be retried. Error:"; Logging.info(Sender.TAG, notice, error); } _this._onErrorHelper(error); if (typeof callback === "function") { var errorMessage = "error sending telemetry"; if (error && (typeof error.toString === "function")) { errorMessage = error.toString(); } callback(errorMessage); } if (_this._enableDiskRetryMode) { _this._storeToDisk(payload); } }); req.write(dataToSend); req.end(); }); }; Sender.prototype.saveOnCrash = function (payload) { if (this._enableDiskRetryMode) { this._storeToDiskSync(payload); } }; Sender.prototype._runICACLS = function (args, callback) { var aclProc = child_process.spawn(Sender.ICACLS_PATH, args, { windowsHide: true }); aclProc.on("error", function (e) { return callback(e); }); aclProc.on("close", function (code, signal) { return callback(code === 0 ? null : new Error("Setting ACL restrictions did not succeed (ICACLS returned code " + code + ")")); }); }; Sender.prototype._runICACLSSync = function (args) { // Some very old versions of Node (< 0.11) don't have this if (child_process.spawnSync) { var aclProc = child_process.spawnSync(Sender.ICACLS_PATH, args, { windowsHide: true }); if (aclProc.error) { throw aclProc.error; } else if (aclProc.status !== 0) { throw new Error("Setting ACL restrictions did not succeed (ICACLS returned code " + aclProc.status + ")"); } } else { throw new Error("Could not synchronously call ICACLS under current version of Node.js"); } }; Sender.prototype._getACLIdentity = function (callback) { if (Sender.ACL_IDENTITY) { return callback(null, Sender.ACL_IDENTITY); } var psProc = child_process.spawn(Sender.POWERSHELL_PATH, ["-Command", "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name"], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] // Needed to prevent hanging on Win 7 }); var data = ""; psProc.stdout.on("data", function (d) { return data += d; }); psProc.on("error", function (e) { return callback(e, null); }); psProc.on("close", function (code, signal) { Sender.ACL_IDENTITY = data && data.trim(); return callback(code === 0 ? null : new Error("Getting ACL identity did not succeed (PS returned code " + code + ")"), Sender.ACL_IDENTITY); }); }; Sender.prototype._getACLIdentitySync = function () { if (Sender.ACL_IDENTITY) { return Sender.ACL_IDENTITY; } // Some very old versions of Node (< 0.11) don't have this if (child_process.spawnSync) { var psProc = child_process.spawnSync(Sender.POWERSHELL_PATH, ["-Command", "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name"], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] // Needed to prevent hanging on Win 7 }); if (psProc.error) { throw psProc.error; } else if (psProc.status !== 0) { throw new Error("Getting ACL identity did not succeed (PS returned code " + psProc.status + ")"); } Sender.ACL_IDENTITY = psProc.stdout && psProc.stdout.toString().trim(); return Sender.ACL_IDENTITY; } else { throw new Error("Could not synchronously get ACL identity under current version of Node.js"); } }; Sender.prototype._getACLArguments = function (directory, identity) { return [directory, "/grant", "*S-1-5-32-544:(OI)(CI)F", "/grant", identity + ":(OI)(CI)F", "/inheritance:r"]; // Remove all inherited permissions }; Sender.prototype._applyACLRules = function (directory, callback) { var _this = this; if (!Sender.USE_ICACLS) { return callback(null); } // For performance, only run ACL rules if we haven't already during this session if (Sender.ACLED_DIRECTORIES[directory] === undefined) { // Avoid multiple calls race condition by setting ACLED_DIRECTORIES to false for this directory immediately // If batches are being failed faster than the processes spawned below return, some data won't be stored to disk // This is better than the alternative of potentially infinitely spawned processes Sender.ACLED_DIRECTORIES[directory] = false; // Restrict this directory to only current user and administrator access this._getACLIdentity(function (err, identity) { if (err) { Sender.ACLED_DIRECTORIES[directory] = false; // false is used to cache failed (vs undefined which is "not yet tried") return callback(err); } else { _this._runICACLS(_this._getACLArguments(directory, identity), function (err) { Sender.ACLED_DIRECTORIES[directory] = !err; return callback(err); }); } }); } else { return callback(Sender.ACLED_DIRECTORIES[directory] ? null : new Error("Setting ACL restrictions did not succeed (cached result)")); } }; Sender.prototype._applyACLRulesSync = function (directory) { if (Sender.USE_ICACLS) { // For performance, only run ACL rules if we haven't already during this session if (Sender.ACLED_DIRECTORIES[directory] === undefined) { this._runICACLSSync(this._getACLArguments(directory, this._getACLIdentitySync())); Sender.ACLED_DIRECTORIES[directory] = true; // If we get here, it succeeded. _runIACLSSync will throw on failures return; } else if (!Sender.ACLED_DIRECTORIES[directory]) { throw new Error("Setting ACL restrictions did not succeed (cached result)"); } } }; Sender.prototype._confirmDirExists = function (directory, callback) { var _this = this; fs.lstat(directory, function (err, stats) { if (err && err.code === 'ENOENT') { fs.mkdir(directory, function (err) { if (err && err.code !== 'EEXIST') { callback(err); } else { _this._applyACLRules(directory, callback); } }); } else if (!err && stats.isDirectory()) { _this._applyACLRules(directory, callback); } else { callback(err || new Error("Path existed but was not a directory")); } }); }; /** * Computes the size (in bytes) of all files in a directory at the root level. Asynchronously. */ Sender.prototype._getShallowDirectorySize = function (directory, callback) { // Get the directory listing fs.readdir(directory, function (err, files) { if (err) { return callback(err, -1); } var error = null; var totalSize = 0; var count = 0; if (files.length === 0) { callback(null, 0); return; } // Query all file sizes for (var i = 0; i < files.length; i++) { fs.stat(path.join(directory, files[i]), function (err, fileStats) { count++; if (err) { error = err; } else { if (fileStats.isFile()) { totalSize += fileStats.size; } } if (count === files.length) { // Did we get an error? if (error) { callback(error, -1); } else { callback(error, totalSize); } } }); } }); }; /** * Computes the size (in bytes) of all files in a directory at the root level. Synchronously. */ Sender.prototype._getShallowDirectorySizeSync = function (directory) { var files = fs.readdirSync(directory); var totalSize = 0; for (var i = 0; i < files.length; i++) { totalSize += fs.statSync(path.join(directory, files[i])).size; } return totalSize; }; /** * Stores the payload as a json file on disk in the temp directory */ Sender.prototype._storeToDisk = function (payload) { var _this = this; // tmpdir is /tmp for *nix and USERDIR/AppData/Local/Temp for Windows var directory = path.join(os.tmpdir(), Sender.TEMPDIR_PREFIX + this._config.instrumentationKey); // This will create the dir if it does not exist // Default permissions on *nix are directory listing from other users but no file creations Logging.info(Sender.TAG, "Checking existance of data storage directory: " + directory); this._confirmDirExists(directory, function (error) { if (error) { Logging.warn(Sender.TAG, "Error while checking/creating directory: " + (error && error.message)); _this._onErrorHelper(error); return; } _this._getShallowDirectorySize(directory, function (err, size) { if (err || size < 0) { Logging.warn(Sender.TAG, "Error while checking directory size: " + (err && err.message)); _this._onErrorHelper(err); return; } else if (size > _this._maxBytesOnDisk) { Logging.warn(Sender.TAG, "Not saving data due to max size limit being met. Directory size in bytes is: " + size); return; } //create file - file name for now is the timestamp, a better approach would be a UUID but that //would require an external dependency var fileName = new Date().getTime() + ".ai.json"; var fileFullPath = path.join(directory, fileName); // Mode 600 is w/r for creator and no read access for others (only applies on *nix) // For Windows, ACL rules are applied to the entire directory (see logic in _confirmDirExists and _applyACLRules) Logging.info(Sender.TAG, "saving data to disk at: " + fileFullPath); fs.writeFile(fileFullPath, payload, { mode: 384 }, function (error) { return _this._onErrorHelper(error); }); }); }); }; /** * Stores the payload as a json file on disk using sync file operations * this is used when storing data before crashes */ Sender.prototype._storeToDiskSync = function (payload) { // tmpdir is /tmp for *nix and USERDIR/AppData/Local/Temp for Windows var directory = path.join(os.tmpdir(), Sender.TEMPDIR_PREFIX + this._config.instrumentationKey); try { Logging.info(Sender.TAG, "Checking existance of data storage directory: " + directory); if (!fs.existsSync(directory)) { fs.mkdirSync(directory); } // Make sure permissions are valid this._applyACLRulesSync(directory); var dirSize = this._getShallowDirectorySizeSync(directory); if (dirSize > this._maxBytesOnDisk) { Logging.info(Sender.TAG, "Not saving data due to max size limit being met. Directory size in bytes is: " + dirSize); return; } //create file - file name for now is the timestamp, a better approach would be a UUID but that //would require an external dependency var fileName = new Date().getTime() + ".ai.json"; var fileFullPath = path.join(directory, fileName); // Mode 600 is w/r for creator and no access for anyone else (only applies on *nix) Logging.info(Sender.TAG, "saving data before crash to disk at: " + fileFullPath); fs.writeFileSync(fileFullPath, payload, { mode: 384 }); } catch (error) { Logging.warn(Sender.TAG, "Error while saving data to disk: " + (error && error.message)); this._onErrorHelper(error); } }; /** * Check for temp telemetry files * reads the first file if exist, deletes it and tries to send its load */ Sender.prototype._sendFirstFileOnDisk = function () { var _this = this; var tempDir = path.join(os.tmpdir(), Sender.TEMPDIR_PREFIX + this._config.instrumentationKey); fs.exists(tempDir, function (exists) { if (exists) { fs.readdir(tempDir, function (error, files) { if (!error) { files = files.filter(function (f) { return path.basename(f).indexOf(".ai.json") > -1; }); if (files.length > 0) { var firstFile = files[0]; var filePath = path.join(tempDir, firstFile); fs.readFile(filePath, function (error, payload) { if (!error) { // delete the file first to prevent double sending fs.unlink(filePath, function (error) { if (!error) { _this.send(payload); } else { _this._onErrorHelper(error); } }); } else { _this._onErrorHelper(error); } }); } } else { _this._onErrorHelper(error); } }); } }); }; Sender.prototype._onErrorHelper = function (error) { if (typeof this._onError === "function") { this._onError(error); } }; Sender.TAG = "Sender"; Sender.ICACLS_PATH = process.env.systemdrive + "/windows/system32/icacls.exe"; Sender.POWERSHELL_PATH = process.env.systemdrive + "/windows/system32/windowspowershell/v1.0/powershell.exe"; Sender.ACLED_DIRECTORIES = {}; Sender.ACL_IDENTITY = null; // the amount of time the SDK will wait between resending cached data, this buffer is to avoid any throtelling from the service side Sender.WAIT_BETWEEN_RESEND = 60 * 1000; Sender.MAX_BYTES_ON_DISK = 50 * 1000 * 1000; Sender.MAX_CONNECTION_FAILURES_BEFORE_WARN = 5; Sender.TEMPDIR_PREFIX = "appInsights-node"; Sender.OS_PROVIDES_FILE_PROTECTION = false; Sender.USE_ICACLS = os.type() === "Windows_NT"; return Sender; }()); module.exports = Sender; //# sourceMappingURL=Sender.js.map /***/ }), /***/ 1199: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var url = __webpack_require__(8835); var Config = __webpack_require__(105); var Context = __webpack_require__(9989); var Contracts = __webpack_require__(6812); var Channel = __webpack_require__(8560); var TelemetryProcessors = __webpack_require__(2564); var CorrelationContextManager_1 = __webpack_require__(7602); var Sender = __webpack_require__(3819); var Util = __webpack_require__(604); var Logging = __webpack_require__(4798); var EnvelopeFactory = __webpack_require__(2656); /** * Application Insights telemetry client provides interface to track telemetry items, register telemetry initializers and * and manually trigger immediate sending (flushing) */ var TelemetryClient = (function () { /** * Constructs a new client of the client * @param setupString the Connection String or Instrumentation Key to use (read from environment variable if not specified) */ function TelemetryClient(setupString) { this._telemetryProcessors = []; var config = new Config(setupString); this.config = config; this.context = new Context(); this.commonProperties = {}; var sender = new Sender(this.config); this.channel = new Channel(function () { return config.disableAppInsights; }, function () { return config.maxBatchSize; }, function () { return config.maxBatchIntervalMs; }, sender); } /** * Log information about availability of an application * @param telemetry Object encapsulating tracking options */ TelemetryClient.prototype.trackAvailability = function (telemetry) { this.track(telemetry, Contracts.TelemetryType.Availability); }; /** * Log a trace message * @param telemetry Object encapsulating tracking options */ TelemetryClient.prototype.trackTrace = function (telemetry) { this.track(telemetry, Contracts.TelemetryType.Trace); }; /** * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators. * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the * telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals. * @param telemetry Object encapsulating tracking options */ TelemetryClient.prototype.trackMetric = function (telemetry) { this.track(telemetry, Contracts.TelemetryType.Metric); }; /** * Log an exception * @param telemetry Object encapsulating tracking options */ TelemetryClient.prototype.trackException = function (telemetry) { if (telemetry && telemetry.exception && !Util.isError(telemetry.exception)) { telemetry.exception = new Error(telemetry.exception.toString()); } this.track(telemetry, Contracts.TelemetryType.Exception); }; /** * Log a user action or other occurrence. * @param telemetry Object encapsulating tracking options */ TelemetryClient.prototype.trackEvent = function (telemetry) { this.track(telemetry, Contracts.TelemetryType.Event); }; /** * Log a request. Note that the default client will attempt to collect HTTP requests automatically so only use this for requests * that aren't automatically captured or if you've disabled automatic request collection. * * @param telemetry Object encapsulating tracking options */ TelemetryClient.prototype.trackRequest = function (telemetry) { this.track(telemetry, Contracts.TelemetryType.Request); }; /** * Log a dependency. Note that the default client will attempt to collect dependencies automatically so only use this for dependencies * that aren't automatically captured or if you've disabled automatic dependency collection. * * @param telemetry Object encapsulating tracking option * */ TelemetryClient.prototype.trackDependency = function (telemetry) { if (telemetry && !telemetry.target && telemetry.data) { // url.parse().host returns null for non-urls, // making this essentially a no-op in those cases // If this logic is moved, update jsdoc in DependencyTelemetry.target telemetry.target = url.parse(telemetry.data).host; } this.track(telemetry, Contracts.TelemetryType.Dependency); }; /** * Immediately send all queued telemetry. * @param options Flush options, including indicator whether app is crashing and callback */ TelemetryClient.prototype.flush = function (options) { this.channel.triggerSend(options ? !!options.isAppCrashing : false, options ? options.callback : undefined); }; /** * Generic track method for all telemetry types * @param data the telemetry to send * @param telemetryType specify the type of telemetry you are tracking from the list of Contracts.DataTypes */ TelemetryClient.prototype.track = function (telemetry, telemetryType) { if (telemetry && Contracts.telemetryTypeToBaseType(telemetryType)) { var envelope = EnvelopeFactory.createEnvelope(telemetry, telemetryType, this.commonProperties, this.context, this.config); // Set time on the envelope if it was set on the telemetry item if (telemetry.time) { envelope.time = telemetry.time.toISOString(); } var accepted = this.runTelemetryProcessors(envelope, telemetry.contextObjects); // Ideally we would have a central place for "internal" telemetry processors and users can configure which ones are in use. // This will do for now. Otherwise clearTelemetryProcessors() would be problematic. accepted = accepted && TelemetryProcessors.samplingTelemetryProcessor(envelope, { correlationContext: CorrelationContextManager_1.CorrelationContextManager.getCurrentContext() }); TelemetryProcessors.performanceMetricsTelemetryProcessor(envelope, this.quickPulseClient); if (accepted) { this.channel.send(envelope); } } else { Logging.warn("track() requires telemetry object and telemetryType to be specified."); } }; /** * Adds telemetry processor to the collection. Telemetry processors will be called one by one * before telemetry item is pushed for sending and in the order they were added. * * @param telemetryProcessor function, takes Envelope, and optional context object and returns boolean */ TelemetryClient.prototype.addTelemetryProcessor = function (telemetryProcessor) { this._telemetryProcessors.push(telemetryProcessor); }; /* * Removes all telemetry processors */ TelemetryClient.prototype.clearTelemetryProcessors = function () { this._telemetryProcessors = []; }; TelemetryClient.prototype.runTelemetryProcessors = function (envelope, contextObjects) { var accepted = true; var telemetryProcessorsCount = this._telemetryProcessors.length; if (telemetryProcessorsCount === 0) { return accepted; } contextObjects = contextObjects || {}; contextObjects['correlationContext'] = CorrelationContextManager_1.CorrelationContextManager.getCurrentContext(); for (var i = 0; i < telemetryProcessorsCount; ++i) { try { var processor = this._telemetryProcessors[i]; if (processor) { if (processor.apply(null, [envelope, contextObjects]) === false) { accepted = false; break; } } } catch (error) { accepted = true; Logging.warn("One of telemetry processors failed, telemetry item will be sent.", error, envelope); } } return accepted; }; return TelemetryClient; }()); module.exports = TelemetryClient; //# sourceMappingURL=TelemetryClient.js.map /***/ }), /***/ 4553: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Util = __webpack_require__(604); var CorrelationIdManager = __webpack_require__(7892); /** * Helper class to manage parsing and validation of traceparent header. Also handles hierarchical * back-compatibility headers generated from traceparent. W3C traceparent spec is documented at * https://www.w3.org/TR/trace-context/#traceparent-field */ var Traceparent = (function () { function Traceparent(traceparent, parentId) { this.traceFlag = Traceparent.DEFAULT_TRACE_FLAG; this.version = Traceparent.DEFAULT_VERSION; if (traceparent && typeof traceparent === "string") { // If incoming request contains traceparent: parse it, set operation, parent and telemetry id accordingly. traceparent should be injected into outgoing requests. request-id should be injected in back-compat format |traceId.spanId. so that older SDKs could understand it. if (traceparent.split(",").length > 1) { this.traceId = Util.w3cTraceId(); this.spanId = Util.w3cTraceId().substr(0, 16); } else { var traceparentArr = traceparent.trim().split("-"); var len = traceparentArr.length; if (len >= 4) { this.version = traceparentArr[0]; this.traceId = traceparentArr[1]; this.spanId = traceparentArr[2]; this.traceFlag = traceparentArr[3]; } else { this.traceId = Util.w3cTraceId(); this.spanId = Util.w3cTraceId().substr(0, 16); } // Version validation if (!this.version.match(/^[0-9a-f]{2}$/g)) { this.version = Traceparent.DEFAULT_VERSION; this.traceId = Util.w3cTraceId(); } if (this.version === "00" && len !== 4) { this.traceId = Util.w3cTraceId(); this.spanId = Util.w3cTraceId().substr(0, 16); } if (this.version === "ff") { this.version = Traceparent.DEFAULT_VERSION; this.traceId = Util.w3cTraceId(); this.spanId = Util.w3cTraceId().substr(0, 16); } if (!this.version.match(/^0[0-9a-f]$/g)) { this.version = Traceparent.DEFAULT_VERSION; } // TraceFlag validation if (!this.traceFlag.match(/^[0-9a-f]{2}$/g)) { this.traceFlag = Traceparent.DEFAULT_TRACE_FLAG; this.traceId = Util.w3cTraceId(); } // Validate TraceId, regenerate new traceid if invalid if (!Traceparent.isValidTraceId(this.traceId)) { this.traceId = Util.w3cTraceId(); } // Validate Span Id, discard entire traceparent if invalid if (!Traceparent.isValidSpanId(this.spanId)) { this.spanId = Util.w3cTraceId().substr(0, 16); this.traceId = Util.w3cTraceId(); } // Save backCompat parentId this.parentId = this.getBackCompatRequestId(); } } else if (parentId) { // If incoming request contains only request-id, new traceid and spanid should be started, request-id value should be used as a parent. Root part of request-id should be stored in custom dimension on the request telemetry if root part is different from traceid. On the outgoing request side, request-id should be emitted in the |traceId.spanId. format. this.parentId = parentId.slice(); // copy var operationId = CorrelationIdManager.getRootId(parentId); if (!Traceparent.isValidTraceId(operationId)) { this.legacyRootId = operationId; operationId = Util.w3cTraceId(); } if (parentId.indexOf("|") !== -1) { parentId = parentId.substring(1 + parentId.substring(0, parentId.length - 1).lastIndexOf("."), parentId.length - 1); } this.traceId = operationId; this.spanId = parentId; } else { // Fallback default constructor // if request does not contain any correlation headers, see case p2 this.traceId = Util.w3cTraceId(); this.spanId = Util.w3cTraceId().substr(0, 16); } } Traceparent.isValidTraceId = function (id) { return id.match(/^[0-9a-f]{32}$/) && id !== "00000000000000000000000000000000"; }; Traceparent.isValidSpanId = function (id) { return id.match(/^[0-9a-f]{16}$/) && id !== "0000000000000000"; }; Traceparent.prototype.getBackCompatRequestId = function () { return "|" + this.traceId + "." + this.spanId + "."; }; Traceparent.prototype.toString = function () { return this.version + "-" + this.traceId + "-" + this.spanId + "-" + this.traceFlag; }; Traceparent.prototype.updateSpanId = function () { this.spanId = Util.w3cTraceId().substr(0, 16); }; Traceparent.DEFAULT_TRACE_FLAG = "01"; Traceparent.DEFAULT_VERSION = "00"; return Traceparent; }()); module.exports = Traceparent; //# sourceMappingURL=Traceparent.js.map /***/ }), /***/ 1566: /***/ ((module) => { "use strict"; /** * Helper class to manage parsing and strict-validation of tracestate header. W3C tracestate spec * is documented at https://www.w3.org/TR/trace-context/#header-value * @class Tracestate */ var Tracestate = (function () { // if true, performs strict tracestate header checking, else just passes it along function Tracestate(id) { this.fieldmap = []; if (!id) { return; } this.fieldmap = this.parseHeader(id); } Tracestate.prototype.toString = function () { var fieldarr = this.fieldmap; if (!fieldarr || fieldarr.length == 0) { return null; } return fieldarr.join(", "); }; Tracestate.validateKeyChars = function (key) { var keyParts = key.split("@"); if (keyParts.length == 2) { // Parse for tenant@vendor format var tenant = keyParts[0].trim(); var vendor = keyParts[1].trim(); var tenantValid = Boolean(tenant.match(/^[\ ]?[a-z0-9\*\-\_/]{1,241}$/)); var vendorValid = Boolean(vendor.match(/^[\ ]?[a-z0-9\*\-\_/]{1,14}$/)); return tenantValid && vendorValid; } else if (keyParts.length == 1) { // Parse for standard key format return Boolean(key.match(/^[\ ]?[a-z0-9\*\-\_/]{1,256}$/)); } return false; }; Tracestate.prototype.parseHeader = function (id) { var res = []; var keydeduper = {}; var parts = id.split(","); if (parts.length > 32) return null; for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { var rawPart = parts_1[_i]; var part = rawPart.trim(); // trim out whitespace if (part.length === 0) { continue; // Discard empty pairs, but keep the rest of this tracestate } var pair = part.split("="); // pair should contain exactly one "=" if (pair.length !== 2) { return null; // invalid pair: discard entire tracestate } // Validate length and charset of this key if (!Tracestate.validateKeyChars(pair[0])) { return null; } // Assert uniqueness of this key if (keydeduper[pair[0]]) { return null; // duplicate key: discard entire tracestate } else { keydeduper[pair[0]] = true; } // All checks passed -- add this part res.push(part); } return res; }; Tracestate.strict = true; return Tracestate; }()); module.exports = Tracestate; //# sourceMappingURL=Tracestate.js.map /***/ }), /***/ 604: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; var http = __webpack_require__(8605); var https = __webpack_require__(7211); var url = __webpack_require__(8835); var constants = __webpack_require__(7619); var Logging = __webpack_require__(4798); var RequestResponseHeaders = __webpack_require__(3918); var Util = (function () { function Util() { } /** * helper method to access userId and sessionId cookie */ Util.getCookie = function (name, cookie) { var value = ""; if (name && name.length && typeof cookie === "string") { var cookieName = name + "="; var cookies = cookie.split(";"); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i]; cookie = Util.trim(cookie); if (cookie && cookie.indexOf(cookieName) === 0) { value = cookie.substring(cookieName.length, cookies[i].length); break; } } } return value; }; /** * helper method to trim strings (IE8 does not implement String.prototype.trim) */ Util.trim = function (str) { if (typeof str === "string") { return str.replace(/^\s+|\s+$/g, ""); } else { return ""; } }; /** * Convert an array of int32 to Base64 (no '==' at the end). * MSB first. */ Util.int32ArrayToBase64 = function (array) { var toChar = function (v, i) { return String.fromCharCode((v >> i) & 0xFF); }; var int32AsString = function (v) { return toChar(v, 24) + toChar(v, 16) + toChar(v, 8) + toChar(v, 0); }; var x = array.map(int32AsString).join(""); var b = Buffer.from ? Buffer.from(x, "binary") : new Buffer(x, "binary"); var s = b.toString("base64"); return s.substr(0, s.indexOf("=")); }; /** * generate a random 32bit number (-0x80000000..0x7FFFFFFF). */ Util.random32 = function () { return (0x100000000 * Math.random()) | 0; }; /** * generate a random 32bit number (0x00000000..0xFFFFFFFF). */ Util.randomu32 = function () { return Util.random32() + 0x80000000; }; /** * generate W3C-compatible trace id * https://github.com/w3c/distributed-tracing/blob/master/trace_context/HTTP_HEADER_FORMAT.md#trace-id */ Util.w3cTraceId = function () { var hexValues = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; // rfc4122 version 4 UUID without dashes and with lowercase letters var oct = "", tmp; for (var a = 0; a < 4; a++) { tmp = Util.random32(); oct += hexValues[tmp & 0xF] + hexValues[tmp >> 4 & 0xF] + hexValues[tmp >> 8 & 0xF] + hexValues[tmp >> 12 & 0xF] + hexValues[tmp >> 16 & 0xF] + hexValues[tmp >> 20 & 0xF] + hexValues[tmp >> 24 & 0xF] + hexValues[tmp >> 28 & 0xF]; } // "Set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively" var clockSequenceHi = hexValues[8 + (Math.random() * 4) | 0]; return oct.substr(0, 8) + oct.substr(9, 4) + "4" + oct.substr(13, 3) + clockSequenceHi + oct.substr(16, 3) + oct.substr(19, 12); }; Util.isValidW3CId = function (id) { return id.length === 32 && id !== "00000000000000000000000000000000"; }; /** * Check if an object is of type Array */ Util.isArray = function (obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }; /** * Check if an object is of type Error */ Util.isError = function (obj) { return obj instanceof Error; }; Util.isPrimitive = function (input) { var propType = typeof input; return propType === "string" || propType === "number" || propType === "boolean"; }; /** * Check if an object is of type Date */ Util.isDate = function (obj) { return Object.prototype.toString.call(obj) === "[object Date]"; }; /** * Convert ms to c# time span format */ Util.msToTimeSpan = function (totalms) { if (isNaN(totalms) || totalms < 0) { totalms = 0; } var sec = ((totalms / 1000) % 60).toFixed(7).replace(/0{0,4}$/, ""); var min = "" + Math.floor(totalms / (1000 * 60)) % 60; var hour = "" + Math.floor(totalms / (1000 * 60 * 60)) % 24; var days = Math.floor(totalms / (1000 * 60 * 60 * 24)); sec = sec.indexOf(".") < 2 ? "0" + sec : sec; min = min.length < 2 ? "0" + min : min; hour = hour.length < 2 ? "0" + hour : hour; var daysText = days > 0 ? days + "." : ""; return daysText + hour + ":" + min + ":" + sec; }; /** * Using JSON.stringify, by default Errors do not serialize to something useful: * Simplify a generic Node Error into a simpler map for customDimensions * Custom errors can still implement toJSON to override this functionality */ Util.extractError = function (err) { // Error is often subclassed so may have code OR id properties: // https://nodejs.org/api/errors.html#errors_error_code var looseError = err; return { message: err.message, code: looseError.code || looseError.id || "", }; }; /** * Manually call toJSON if available to pre-convert the value. * If a primitive is returned, then the consumer of this function can skip JSON.stringify. * This avoids double escaping of quotes for Date objects, for example. */ Util.extractObject = function (origProperty) { if (origProperty instanceof Error) { return Util.extractError(origProperty); } if (typeof origProperty.toJSON === "function") { return origProperty.toJSON(); } return origProperty; }; /** * Validate that an object is of type { [key: string]: string } */ Util.validateStringMap = function (obj) { if (typeof obj !== "object") { Logging.info("Invalid properties dropped from payload"); return; } var map = {}; for (var field in obj) { var property = ''; var origProperty = obj[field]; var propType = typeof origProperty; if (Util.isPrimitive(origProperty)) { property = origProperty.toString(); } else if (origProperty === null || propType === "undefined") { property = ""; } else if (propType === "function") { Logging.info("key: " + field + " was function; will not serialize"); continue; } else { var stringTarget = Util.isArray(origProperty) ? origProperty : Util.extractObject(origProperty); try { if (Util.isPrimitive(stringTarget)) { property = stringTarget; } else { property = JSON.stringify(stringTarget); } } catch (e) { property = origProperty.constructor.name.toString() + " (Error: " + e.message + ")"; Logging.info("key: " + field + ", could not be serialized"); } } map[field] = property.substring(0, Util.MAX_PROPERTY_LENGTH); } return map; }; /** * Checks if a request url is not on a excluded domain list * and if it is safe to add correlation headers */ Util.canIncludeCorrelationHeader = function (client, requestUrl) { var excludedDomains = client && client.config && client.config.correlationHeaderExcludedDomains; if (!excludedDomains || excludedDomains.length == 0 || !requestUrl) { return true; } for (var i = 0; i < excludedDomains.length; i++) { var regex = new RegExp(excludedDomains[i].replace(/\./g, "\.").replace(/\*/g, ".*")); if (regex.test(url.parse(requestUrl).hostname)) { return false; } } return true; }; Util.getCorrelationContextTarget = function (response, key) { var contextHeaders = response.headers && response.headers[RequestResponseHeaders.requestContextHeader]; if (contextHeaders) { var keyValues = contextHeaders.split(","); for (var i = 0; i < keyValues.length; ++i) { var keyValue = keyValues[i].split("="); if (keyValue.length == 2 && keyValue[0] == key) { return keyValue[1]; } } } }; /** * Generate request * * Proxify the request creation to handle proxy http * * @param {string} requestUrl url endpoint * @param {Object} requestOptions Request option * @param {Function} requestCallback callback on request * @returns {http.ClientRequest} request object */ Util.makeRequest = function (config, requestUrl, requestOptions, requestCallback) { if (requestUrl && requestUrl.indexOf('//') === 0) { requestUrl = 'https:' + requestUrl; } var requestUrlParsed = url.parse(requestUrl); var options = __assign({}, requestOptions, { host: requestUrlParsed.hostname, port: requestUrlParsed.port, path: requestUrlParsed.pathname }); var proxyUrl = undefined; if (requestUrlParsed.protocol === 'https:') { proxyUrl = config.proxyHttpsUrl || undefined; } if (requestUrlParsed.protocol === 'http:') { proxyUrl = config.proxyHttpUrl || undefined; } if (proxyUrl) { if (proxyUrl.indexOf('//') === 0) { proxyUrl = 'http:' + proxyUrl; } var proxyUrlParsed = url.parse(proxyUrl); // https is not supported at the moment if (proxyUrlParsed.protocol === 'https:') { Logging.info("Proxies that use HTTPS are not supported"); proxyUrl = undefined; } else { options = __assign({}, options, { host: proxyUrlParsed.hostname, port: proxyUrlParsed.port || "80", path: requestUrl, headers: __assign({}, options.headers, { Host: requestUrlParsed.hostname }) }); } } var isHttps = requestUrlParsed.protocol === 'https:' && !proxyUrl; if (isHttps && config.httpsAgent !== undefined) { options.agent = config.httpsAgent; } else if (!isHttps && config.httpAgent !== undefined) { options.agent = config.httpAgent; } else if (isHttps) { // HTTPS without a passed in agent. Use one that enforces our TLS rules options.agent = Util.tlsRestrictedAgent; } if (isHttps) { return https.request(options, requestCallback); } else { return http.request(options, requestCallback); } }; ; /** * Parse standard request-context header */ Util.safeIncludeCorrelationHeader = function (client, request, correlationHeader) { var header; // attempt to cast correlationHeader to string if (typeof correlationHeader === "string") { header = correlationHeader; } else if (correlationHeader instanceof Array) { header = correlationHeader.join(","); } else if (correlationHeader && typeof correlationHeader.toString === "function") { // best effort attempt: requires well-defined toString try { header = correlationHeader.toString(); } catch (err) { Logging.warn("Outgoing request-context header could not be read. Correlation of requests may be lost.", err, correlationHeader); } } if (header) { Util.addCorrelationIdHeaderFromString(client, request, header); } else { request.setHeader(RequestResponseHeaders.requestContextHeader, RequestResponseHeaders.requestContextSourceKey + "=" + client.config.correlationId); } }; Util.addCorrelationIdHeaderFromString = function (client, response, correlationHeader) { var components = correlationHeader.split(","); var key = RequestResponseHeaders.requestContextSourceKey + "="; var found = components.some(function (value) { return value.substring(0, key.length) === key; }); if (!found) { response.setHeader(RequestResponseHeaders.requestContextHeader, correlationHeader + "," + RequestResponseHeaders.requestContextSourceKey + "=" + client.config.correlationId); } }; Util.MAX_PROPERTY_LENGTH = 8192; Util.tlsRestrictedAgent = new https.Agent({ secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_TLSv1 | constants.SSL_OP_NO_TLSv1_1 }); return Util; }()); module.exports = Util; //# sourceMappingURL=Util.js.map /***/ }), /***/ 4292: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var AutoCollectPerformance = __webpack_require__(9270); var TelemetryType = __webpack_require__(6812); function performanceMetricsTelemetryProcessor(envelope, client) { // If live metrics is enabled, forward all telemetry there if (client) { client.addDocument(envelope); } // Increment rate counters (for standard metrics and live metrics) switch (envelope.data.baseType) { case TelemetryType.TelemetryTypeString.Exception: AutoCollectPerformance.countException(); break; case TelemetryType.TelemetryTypeString.Request: var requestData = envelope.data.baseData; AutoCollectPerformance.countRequest(requestData.duration, requestData.success); break; case TelemetryType.TelemetryTypeString.Dependency: var remoteDependencyData = envelope.data.baseData; AutoCollectPerformance.countDependency(remoteDependencyData.duration, remoteDependencyData.success); break; } return true; } exports.performanceMetricsTelemetryProcessor = performanceMetricsTelemetryProcessor; //# sourceMappingURL=PerformanceMetricsTelemetryProcessor.js.map /***/ }), /***/ 9836: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var Contracts = __webpack_require__(6812); /** * A telemetry processor that handles sampling. */ function samplingTelemetryProcessor(envelope, contextObjects) { var samplingPercentage = envelope.sampleRate; // Set for us in Client.getEnvelope var isSampledIn = false; if (samplingPercentage === null || samplingPercentage === undefined || samplingPercentage >= 100) { return true; } else if (envelope.data && Contracts.TelemetryType.Metric === Contracts.baseTypeToTelemetryType(envelope.data.baseType)) { // Exclude MetricData telemetry from sampling return true; } else if (contextObjects.correlationContext && contextObjects.correlationContext.operation) { // If we're using dependency correlation, sampling should retain all telemetry from a given request isSampledIn = getSamplingHashCode(contextObjects.correlationContext.operation.id) < samplingPercentage; } else { // If we're not using dependency correlation, sampling should use a random distribution on each item isSampledIn = (Math.random() * 100) < samplingPercentage; } return isSampledIn; } exports.samplingTelemetryProcessor = samplingTelemetryProcessor; /** Ported from AI .NET SDK */ function getSamplingHashCode(input) { var csharpMin = -2147483648; var csharpMax = 2147483647; var hash = 5381; if (!input) { return 0; } while (input.length < 8) { input = input + input; } for (var i = 0; i < input.length; i++) { // JS doesn't respond to integer overflow by wrapping around. Simulate it with bitwise operators ( | 0) hash = ((((hash << 5) + hash) | 0) + input.charCodeAt(i) | 0); } hash = hash <= csharpMin ? csharpMax : Math.abs(hash); return (hash / csharpMax) * 100; } exports.getSamplingHashCode = getSamplingHashCode; //# sourceMappingURL=SamplingTelemetryProcessor.js.map /***/ }), /***/ 2564: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", ({ value: true })); __export(__webpack_require__(9836)); __export(__webpack_require__(4292)); //# sourceMappingURL=index.js.map /***/ }), /***/ 4310: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var CorrelationContextManager = __webpack_require__(7602); // Keep this first var AutoCollectConsole = __webpack_require__(7326); var AutoCollectExceptions = __webpack_require__(8103); var AutoCollectPerformance = __webpack_require__(9270); var AutoCollectHttpDependencies = __webpack_require__(4665); var AutoCollectHttpRequests = __webpack_require__(4784); var CorrelationIdManager = __webpack_require__(7892); var Logging = __webpack_require__(4798); var QuickPulseClient = __webpack_require__(6836); var NativePerformance_1 = __webpack_require__(6759); // We export these imports so that SDK users may use these classes directly. // They're exposed using "export import" so that types are passed along as expected exports.TelemetryClient = __webpack_require__(7264); exports.Contracts = __webpack_require__(6812); var DistributedTracingModes; (function (DistributedTracingModes) { /** * (Default) Send Application Insights correlation headers */ DistributedTracingModes[DistributedTracingModes["AI"] = 0] = "AI"; /** * Send both W3C Trace Context headers and back-compatibility Application Insights headers */ DistributedTracingModes[DistributedTracingModes["AI_AND_W3C"] = 1] = "AI_AND_W3C"; })(DistributedTracingModes = exports.DistributedTracingModes || (exports.DistributedTracingModes = {})); // Default autocollection configuration var _isConsole = true; var _isConsoleLog = false; var _isExceptions = true; var _isPerformance = true; var _isRequests = true; var _isDependencies = true; var _isDiskRetry = true; var _isCorrelating = true; var _forceClsHooked; var _isSendingLiveMetrics = false; // Off by default var _isNativePerformance = true; var _disabledExtendedMetrics; var _diskRetryInterval = undefined; var _diskRetryMaxBytes = undefined; var _console; var _exceptions; var _performance; var _nativePerformance; var _serverRequests; var _clientRequests; var _isStarted = false; var _performanceLiveMetrics; /** * Initializes the default client. Should be called after setting * configuration options. * * @param setupString the Connection String or Instrumentation Key to use. Optional, if * this is not specified, the value will be read from the environment * variable APPLICATIONINSIGHTS_CONNECTION_STRING or APPINSIGHTS_INSTRUMENTATIONKEY. * @returns {Configuration} the configuration class to initialize * and start the SDK. */ function setup(setupString) { if (!exports.defaultClient) { exports.defaultClient = new exports.TelemetryClient(setupString); _console = new AutoCollectConsole(exports.defaultClient); _exceptions = new AutoCollectExceptions(exports.defaultClient); _performance = new AutoCollectPerformance(exports.defaultClient); _serverRequests = new AutoCollectHttpRequests(exports.defaultClient); _clientRequests = new AutoCollectHttpDependencies(exports.defaultClient); if (!_nativePerformance) { _nativePerformance = new NativePerformance_1.AutoCollectNativePerformance(exports.defaultClient); } } else { Logging.info("The default client is already setup"); } if (exports.defaultClient && exports.defaultClient.channel) { exports.defaultClient.channel.setUseDiskRetryCaching(_isDiskRetry, _diskRetryInterval, _diskRetryMaxBytes); } return Configuration; } exports.setup = setup; /** * Starts automatic collection of telemetry. Prior to calling start no * telemetry will be *automatically* collected, though manual collection * is enabled. * @returns {ApplicationInsights} this class */ function start() { if (!!exports.defaultClient) { _isStarted = true; _console.enable(_isConsole, _isConsoleLog); _exceptions.enable(_isExceptions); _performance.enable(_isPerformance); _nativePerformance.enable(_isNativePerformance, _disabledExtendedMetrics); _serverRequests.useAutoCorrelation(_isCorrelating, _forceClsHooked); _serverRequests.enable(_isRequests); _clientRequests.enable(_isDependencies); if (exports.liveMetricsClient && _isSendingLiveMetrics) { exports.liveMetricsClient.enable(_isSendingLiveMetrics); } } else { Logging.warn("Start cannot be called before setup"); } return Configuration; } exports.start = start; /** * Returns an object that is shared across all code handling a given request. * This can be used similarly to thread-local storage in other languages. * Properties set on this object will be available to telemetry processors. * * Do not store sensitive information here. * Custom properties set on this object can be exposed in a future SDK * release via outgoing HTTP headers. * This is to allow for correlating data cross-component. * * This method will return null if automatic dependency correlation is disabled. * @returns A plain object for request storage or null if automatic dependency correlation is disabled. */ function getCorrelationContext() { if (_isCorrelating) { return CorrelationContextManager.CorrelationContextManager.getCurrentContext(); } return null; } exports.getCorrelationContext = getCorrelationContext; /** * Returns a function that will get the same correlation context within its * function body as the code executing this function. * Use this method if automatic dependency correlation is not propagating * correctly to an asynchronous callback. */ function wrapWithCorrelationContext(fn) { return CorrelationContextManager.CorrelationContextManager.wrapCallback(fn); } exports.wrapWithCorrelationContext = wrapWithCorrelationContext; /** * The active configuration for global SDK behaviors, such as autocollection. */ var Configuration = (function () { function Configuration() { } /** * Sets the distributed tracing modes. If W3C mode is enabled, W3C trace context * headers (traceparent/tracestate) will be parsed in all incoming requests, and included in outgoing * requests. In W3C mode, existing back-compatibility AI headers will also be parsed and included. * Enabling W3C mode will not break existing correlation with other Application Insights instrumented * services. Default=AI */ Configuration.setDistributedTracingMode = function (value) { CorrelationIdManager.w3cEnabled = value === DistributedTracingModes.AI_AND_W3C; return Configuration; }; /** * Sets the state of console and logger tracking (enabled by default for third-party loggers only) * @param value if true logger activity will be sent to Application Insights * @param collectConsoleLog if true, logger autocollection will include console.log calls (default false) * @returns {Configuration} this class */ Configuration.setAutoCollectConsole = function (value, collectConsoleLog) { if (collectConsoleLog === void 0) { collectConsoleLog = false; } _isConsole = value; _isConsoleLog = collectConsoleLog; if (_isStarted) { _console.enable(value, collectConsoleLog); } return Configuration; }; /** * Sets the state of exception tracking (enabled by default) * @param value if true uncaught exceptions will be sent to Application Insights * @returns {Configuration} this class */ Configuration.setAutoCollectExceptions = function (value) { _isExceptions = value; if (_isStarted) { _exceptions.enable(value); } return Configuration; }; /** * Sets the state of performance tracking (enabled by default) * @param value if true performance counters will be collected every second and sent to Application Insights * @param collectExtendedMetrics if true, extended metrics counters will be collected every minute and sent to Application Insights * @returns {Configuration} this class */ Configuration.setAutoCollectPerformance = function (value, collectExtendedMetrics) { if (collectExtendedMetrics === void 0) { collectExtendedMetrics = true; } _isPerformance = value; var extendedMetricsConfig = NativePerformance_1.AutoCollectNativePerformance.parseEnabled(collectExtendedMetrics); _isNativePerformance = extendedMetricsConfig.isEnabled; _disabledExtendedMetrics = extendedMetricsConfig.disabledMetrics; if (_isStarted) { _performance.enable(value); _nativePerformance.enable(extendedMetricsConfig.isEnabled, extendedMetricsConfig.disabledMetrics); } return Configuration; }; /** * Sets the state of request tracking (enabled by default) * @param value if true requests will be sent to Application Insights * @returns {Configuration} this class */ Configuration.setAutoCollectRequests = function (value) { _isRequests = value; if (_isStarted) { _serverRequests.enable(value); } return Configuration; }; /** * Sets the state of dependency tracking (enabled by default) * @param value if true dependencies will be sent to Application Insights * @returns {Configuration} this class */ Configuration.setAutoCollectDependencies = function (value) { _isDependencies = value; if (_isStarted) { _clientRequests.enable(value); } return Configuration; }; /** * Sets the state of automatic dependency correlation (enabled by default) * @param value if true dependencies will be correlated with requests * @param useAsyncHooks if true, forces use of experimental async_hooks module to provide correlation. If false, instead uses only patching-based techniques. If left blank, the best option is chosen for you based on your version of Node.js. * @returns {Configuration} this class */ Configuration.setAutoDependencyCorrelation = function (value, useAsyncHooks) { _isCorrelating = value; _forceClsHooked = useAsyncHooks; if (_isStarted) { _serverRequests.useAutoCorrelation(value, useAsyncHooks); } return Configuration; }; /** * Enable or disable disk-backed retry caching to cache events when client is offline (enabled by default) * Note that this method only applies to the default client. Disk-backed retry caching is disabled by default for additional clients. * For enable for additional clients, use client.channel.setUseDiskRetryCaching(true). * These cached events are stored in your system or user's temporary directory and access restricted to your user when possible. * @param value if true events that occured while client is offline will be cached on disk * @param resendInterval The wait interval for resending cached events. * @param maxBytesOnDisk The maximum size (in bytes) that the created temporary directory for cache events can grow to, before caching is disabled. * @returns {Configuration} this class */ Configuration.setUseDiskRetryCaching = function (value, resendInterval, maxBytesOnDisk) { _isDiskRetry = value; _diskRetryInterval = resendInterval; _diskRetryMaxBytes = maxBytesOnDisk; if (exports.defaultClient && exports.defaultClient.channel) { exports.defaultClient.channel.setUseDiskRetryCaching(value, resendInterval, maxBytesOnDisk); } return Configuration; }; /** * Enables debug and warning logging for AppInsights itself. * @param enableDebugLogging if true, enables debug logging * @param enableWarningLogging if true, enables warning logging * @returns {Configuration} this class */ Configuration.setInternalLogging = function (enableDebugLogging, enableWarningLogging) { if (enableDebugLogging === void 0) { enableDebugLogging = false; } if (enableWarningLogging === void 0) { enableWarningLogging = true; } Logging.enableDebug = enableDebugLogging; Logging.disableWarnings = !enableWarningLogging; return Configuration; }; /** * Enables communication with Application Insights Live Metrics. * @param enable if true, enables communication with the live metrics service */ Configuration.setSendLiveMetrics = function (enable) { if (enable === void 0) { enable = false; } if (!exports.defaultClient) { // Need a defaultClient so that we can add the QPS telemetry processor to it Logging.warn("Live metrics client cannot be setup without the default client"); return Configuration; } if (!exports.liveMetricsClient && enable) { // No qps client exists. Create one and prepare it to be enabled at .start() exports.liveMetricsClient = new QuickPulseClient(exports.defaultClient.config.instrumentationKey); _performanceLiveMetrics = new AutoCollectPerformance(exports.liveMetricsClient, 1000, true); exports.liveMetricsClient.addCollector(_performanceLiveMetrics); exports.defaultClient.quickPulseClient = exports.liveMetricsClient; // Need this so we can forward all manual tracks to live metrics via PerformanceMetricsTelemetryProcessor } else if (exports.liveMetricsClient) { // qps client already exists; enable/disable it exports.liveMetricsClient.enable(enable); } _isSendingLiveMetrics = enable; return Configuration; }; // Convenience shortcut to ApplicationInsights.start Configuration.start = start; return Configuration; }()); exports.Configuration = Configuration; /** * Disposes the default client and all the auto collectors so they can be reinitialized with different configuration */ function dispose() { exports.defaultClient = null; _isStarted = false; if (_console) { _console.dispose(); } if (_exceptions) { _exceptions.dispose(); } if (_performance) { _performance.dispose(); } if (_nativePerformance) { _nativePerformance.dispose(); } if (_serverRequests) { _serverRequests.dispose(); } if (_clientRequests) { _clientRequests.dispose(); } if (exports.liveMetricsClient) { exports.liveMetricsClient.enable(false); _isSendingLiveMetrics = false; exports.liveMetricsClient = undefined; } } exports.dispose = dispose; //# sourceMappingURL=applicationinsights.js.map /***/ }), /***/ 5655: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const asyncWrap = process.binding('async_wrap'); const TIMERWRAP = asyncWrap.Providers.TIMERWRAP; const patchs = { 'nextTick': __webpack_require__(1337), 'promise': __webpack_require__(9527), 'timers': __webpack_require__(2123) }; const ignoreUIDs = new Set(); function State() { this.enabled = false; this.counter = 0; } function Hooks() { const initFns = this.initFns = []; const preFns = this.preFns = []; const postFns = this.postFns = []; const destroyFns = this.destroyFns = []; this.init = function (uid, provider, parentUid, parentHandle) { // Ignore TIMERWRAP, since setTimeout etc. is monkey patched if (provider === TIMERWRAP) { ignoreUIDs.add(uid); return; } // call hooks for (const hook of initFns) { hook(uid, this, provider, parentUid, parentHandle); } }; this.pre = function (uid) { if (ignoreUIDs.has(uid)) return; // call hooks for (const hook of preFns) { hook(uid, this); } }; this.post = function (uid, didThrow) { if (ignoreUIDs.has(uid)) return; // call hooks for (const hook of postFns) { hook(uid, this, didThrow); } }; this.destroy = function (uid) { // Cleanup the ignore list if this uid should be ignored if (ignoreUIDs.has(uid)) { ignoreUIDs.delete(uid); return; } // call hooks for (const hook of destroyFns) { hook(uid); } }; } Hooks.prototype.add = function (hooks) { if (hooks.init) this.initFns.push(hooks.init); if (hooks.pre) this.preFns.push(hooks.pre); if (hooks.post) this.postFns.push(hooks.post); if (hooks.destroy) this.destroyFns.push(hooks.destroy); }; function removeElement(array, item) { const index = array.indexOf(item); if (index === -1) return; array.splice(index, 1); } Hooks.prototype.remove = function (hooks) { if (hooks.init) removeElement(this.initFns, hooks.init); if (hooks.pre) removeElement(this.preFns, hooks.pre); if (hooks.post) removeElement(this.postFns, hooks.post); if (hooks.destroy) removeElement(this.destroyFns, hooks.destroy); }; function AsyncHook() { this._state = new State(); this._hooks = new Hooks(); // expose version for conflict detection this.version = __webpack_require__(8155)/* .version */ .i8; // expose the Providers map this.providers = asyncWrap.Providers; // apply patches for (const key of Object.keys(patchs)) { patchs[key].call(this); } // setup async wrap if (process.env.hasOwnProperty('NODE_ASYNC_HOOK_WARNING')) { console.warn('warning: you are using async-hook-jl which is unstable.'); } asyncWrap.setupHooks({ init: this._hooks.init, pre: this._hooks.pre, post: this._hooks.post, destroy: this._hooks.destroy }); } module.exports = AsyncHook; AsyncHook.prototype.addHooks = function (hooks) { this._hooks.add(hooks); }; AsyncHook.prototype.removeHooks = function (hooks) { this._hooks.remove(hooks); }; AsyncHook.prototype.enable = function () { this._state.enabled = true; asyncWrap.enable(); }; AsyncHook.prototype.disable = function () { this._state.enabled = false; asyncWrap.disable(); }; /***/ }), /***/ 7608: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const AsyncHook = __webpack_require__(5655); // If a another copy (same version or not) of stack-chain exists it will result // in wrong stack traces (most likely dublicate callSites). if (global._asyncHook) { // In case the version match, we can simply return the first initialized copy if (global._asyncHook.version === __webpack_require__(8155)/* .version */ .i8) { module.exports = global._asyncHook; } // The version don't match, this is really bad. Lets just throw else { throw new Error('Conflicting version of async-hook-jl found'); } } else { const stackChain = __webpack_require__(6056); // Remove callSites from this module. AsyncWrap doesn't have any callSites // and the hooks are expected to be completely transparent. stackChain.filter.attach(function (error, frames) { return frames.filter(function (callSite) { const filename = callSite.getFileName(); // filename is not always a string, for example in case of eval it is // undefined. So check if the filename is defined. return !(filename && filename.slice(0, __dirname.length) === __dirname); }); }); module.exports = global._asyncHook = new AsyncHook(); } /***/ }), /***/ 8155: /***/ ((module) => { "use strict"; module.exports = {"i8":"1.7.6"}; /***/ }), /***/ 1337: /***/ ((module) => { "use strict"; function NextTickWrap() {} module.exports = function patch() { const hooks = this._hooks; const state = this._state; const oldNextTick = process.nextTick; process.nextTick = function () { if (!state.enabled) return oldNextTick.apply(process, arguments); const args = new Array(arguments.length); for (let i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } const callback = args[0]; if (typeof callback !== 'function') { throw new TypeError('callback is not a function'); } const handle = new NextTickWrap(); const uid = --state.counter; // call the init hook hooks.init.call(handle, uid, 0, null, null); // overwrite callback args[0] = function () { // call the pre hook hooks.pre.call(handle, uid); let didThrow = true; try { callback.apply(this, arguments); didThrow = false; } finally { // If `callback` threw and there is an uncaughtException handler // then call the `post` and `destroy` hook after the uncaughtException // user handlers have been invoked. if(didThrow && process.listenerCount('uncaughtException') > 0) { process.once('uncaughtException', function () { hooks.post.call(handle, uid, true); hooks.destroy.call(null, uid); }); } } // callback done successfully hooks.post.call(handle, uid, false); hooks.destroy.call(null, uid); }; return oldNextTick.apply(process, args); }; } /***/ }), /***/ 9527: /***/ ((module) => { "use strict"; function PromiseWrap() {} module.exports = function patchPromise() { const hooks = this._hooks; const state = this._state; const Promise = global.Promise; /* As per ECMAScript 2015, .catch must be implemented by calling .then, as * such we need needn't patch .catch as well. see: * http://www.ecma-international.org/ecma-262/6.0/#sec-promise.prototype.catch */ const oldThen = Promise.prototype.then; Promise.prototype.then = wrappedThen; function makeWrappedHandler(fn, handle, uid, isOnFulfilled) { if ('function' !== typeof fn) { return isOnFulfilled ? makeUnhandledResolutionHandler(uid) : makeUnhandledRejectionHandler(uid); } return function wrappedHandler() { hooks.pre.call(handle, uid); try { return fn.apply(this, arguments); } finally { hooks.post.call(handle, uid, false); hooks.destroy.call(null, uid); } }; } function makeUnhandledResolutionHandler(uid) { return function unhandledResolutionHandler(val) { hooks.destroy.call(null, uid); return val; }; } function makeUnhandledRejectionHandler(uid) { return function unhandledRejectedHandler(val) { hooks.destroy.call(null, uid); throw val; }; } function wrappedThen(onFulfilled, onRejected) { if (!state.enabled) return oldThen.call(this, onFulfilled, onRejected); const handle = new PromiseWrap(); const uid = --state.counter; hooks.init.call(handle, uid, 0, null, null); return oldThen.call( this, makeWrappedHandler(onFulfilled, handle, uid, true), makeWrappedHandler(onRejected, handle, uid, false) ); } }; /***/ }), /***/ 2123: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const timers = __webpack_require__(8213); function TimeoutWrap() {} function IntervalWrap() {} function ImmediateWrap() {} const timeoutMap = new Map(); const intervalMap = new Map(); const ImmediateMap = new Map(); let activeCallback = null; let clearedInCallback = false; module.exports = function patch() { patchTimer(this._hooks, this._state, 'setTimeout', 'clearTimeout', TimeoutWrap, timeoutMap, true); patchTimer(this._hooks, this._state, 'setInterval', 'clearInterval', IntervalWrap, intervalMap, false); patchTimer(this._hooks, this._state, 'setImmediate', 'clearImmediate', ImmediateWrap, ImmediateMap, true); global.setTimeout = timers.setTimeout; global.setInterval = timers.setInterval; global.setImmediate = timers.setImmediate; global.clearTimeout = timers.clearTimeout; global.clearInterval = timers.clearInterval; global.clearImmediate = timers.clearImmediate; }; function patchTimer(hooks, state, setFn, clearFn, Handle, timerMap, singleCall) { const oldSetFn = timers[setFn]; const oldClearFn = timers[clearFn]; // overwrite set[Timeout] timers[setFn] = function () { if (!state.enabled) return oldSetFn.apply(timers, arguments); const args = new Array(arguments.length); for (let i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } const callback = args[0]; if (typeof callback !== 'function') { throw new TypeError('"callback" argument must be a function'); } const handle = new Handle(); const uid = --state.counter; let timerId = undefined; // call the init hook hooks.init.call(handle, uid, 0, null, null); // overwrite callback args[0] = function () { // call the pre hook activeCallback = timerId; hooks.pre.call(handle, uid); let didThrow = true; try { callback.apply(this, arguments); didThrow = false; } finally { // If `callback` threw and there is an uncaughtException handler // then call the `post` and `destroy` hook after the uncaughtException // user handlers have been invoked. if (didThrow && process.listenerCount('uncaughtException') > 0) { process.once('uncaughtException', function () { // call the post hook hooks.post.call(handle, uid, true); // setInterval won't continue timerMap.delete(timerId); hooks.destroy.call(null, uid); }); } } // callback done successfully hooks.post.call(handle, uid, false); activeCallback = null; // call the destroy hook if the callback will only be called once if (singleCall || clearedInCallback) { clearedInCallback = false; timerMap.delete(timerId); hooks.destroy.call(null, uid); } }; timerId = oldSetFn.apply(timers, args); // Bind the timerId and uid for later use, in case the clear* function is // called. timerMap.set(timerId, uid); return timerId; }; // overwrite clear[Timeout] timers[clearFn] = function (timerId) { // If clear* was called within the timer callback, then delay the destroy // event to after the post event has been called. if (activeCallback === timerId && timerId !== null) { clearedInCallback = true; } // clear should call the destroy hook. Note if timerId doesn't exists // it is because asyncWrap wasn't enabled at the time. else if (timerMap.has(timerId)) { const uid = timerMap.get(timerId); timerMap.delete(timerId); hooks.destroy.call(null, uid); } oldClearFn.apply(timers, arguments); }; } /***/ }), /***/ 5907: /***/ ((module) => { "use strict"; module.exports = (Promise, ensureAslWrapper) => { // Updates to this class should also be applied to the the ES3 version // in index.js. return class WrappedPromise extends Promise { constructor(executor) { var context, args; super(wrappedExecutor); var promise = this; try { executor.apply(context, args); } catch (err) { args[1](err); } return promise; function wrappedExecutor(resolve, reject) { context = this; args = [wrappedResolve, wrappedReject]; // These wrappers create a function that can be passed a function and an argument to // call as a continuation from the resolve or reject. function wrappedResolve(val) { ensureAslWrapper(promise, false); return resolve(val); } function wrappedReject(val) { ensureAslWrapper(promise, false); return reject(val); } } } } }; /***/ }), /***/ 5213: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var wrap = __webpack_require__(1938).wrap; /* * * CONSTANTS * */ var HAS_CREATE_AL = 1 << 0; var HAS_BEFORE_AL = 1 << 1; var HAS_AFTER_AL = 1 << 2; var HAS_ERROR_AL = 1 << 3; /** * There is one list of currently active listeners that is mutated in place by * addAsyncListener and removeAsyncListener. This complicates error-handling, * for reasons that are discussed below. */ var listeners = []; /** * There can be multiple listeners with the same properties, so disambiguate * them by assigning them an ID at creation time. */ var uid = 0; /** * Ensure that errors coming from within listeners are handed off to domains, * process._fatalException, or uncaughtException without being treated like * user errors. */ var inAsyncTick = false; /** * Because asynchronous contexts can be nested, and errors can come from anywhere * in the stack, a little extra work is required to keep track of where in the * nesting we are. Because JS arrays are frequently mutated in place */ var listenerStack = []; /** * The error handler on a listener can capture errors thrown during synchronous * execution immediately after the listener is added. To capture both * synchronous and asynchronous errors, the error handler just uses the * "global" list of active listeners, and the rest of the code ensures that the * listener list is correct by using a stack of listener lists during * asynchronous execution. */ var asyncCatcher; /** * The guts of the system -- called each time an asynchronous event happens * while one or more listeners are active. */ var asyncWrap; /** * Simple helper function that's probably faster than using Array * filter methods and can be inlined. */ function union(dest, added) { var destLength = dest.length; var addedLength = added.length; var returned = []; if (destLength === 0 && addedLength === 0) return returned; for (var j = 0; j < destLength; j++) returned[j] = dest[j]; if (addedLength === 0) return returned; for (var i = 0; i < addedLength; i++) { var missing = true; for (j = 0; j < destLength; j++) { if (dest[j].uid === added[i].uid) { missing = false; break; } } if (missing) returned.push(added[i]); } return returned; } /* * For performance, split error-handlers and asyncCatcher up into two separate * code paths. */ // 0.9+ if (process._fatalException) { /** * Error handlers on listeners can throw, the catcher needs to be able to * discriminate between exceptions thrown by user code, and exceptions coming * from within the catcher itself. Use a global to keep track of which state * the catcher is currently in. */ var inErrorTick = false; /** * Throwing always happens synchronously. If the current array of values for * the current list of asyncListeners is put in a module-scoped variable right * before a call that can throw, it will always be correct when the error * handlers are run. */ var errorValues; asyncCatcher = function asyncCatcher(er) { var length = listeners.length; if (inErrorTick || length === 0) return false; var handled = false; /* * error handlers */ inErrorTick = true; for (var i = 0; i < length; ++i) { var listener = listeners[i]; if ((listener.flags & HAS_ERROR_AL) === 0) continue; var value = errorValues && errorValues[listener.uid]; handled = listener.error(value, er) || handled; } inErrorTick = false; /* Test whether there are any listener arrays on the stack. In the case of * synchronous throws when the listener is active, there may have been * none pushed yet. */ if (listenerStack.length > 0) listeners = listenerStack.pop(); errorValues = undefined; return handled && !inAsyncTick; }; asyncWrap = function asyncWrap(original, list, length) { var values = []; /* * listeners */ inAsyncTick = true; for (var i = 0; i < length; ++i) { var listener = list[i]; values[listener.uid] = listener.data; if ((listener.flags & HAS_CREATE_AL) === 0) continue; var value = listener.create(listener.data); if (value !== undefined) values[listener.uid] = value; } inAsyncTick = false; /* One of the main differences between this polyfill and the core * asyncListener support is that core avoids creating closures by putting a * lot of the state managemnt on the C++ side of Node (and of course also it * bakes support for async listeners into the Node C++ API through the * AsyncWrap class, which means that it doesn't monkeypatch basically every * async method like this does). */ return function () { // put the current values where the catcher can see them errorValues = values; /* More than one listener can end up inside these closures, so save the * current listeners on a stack. */ listenerStack.push(listeners); /* Activate both the listeners that were active when the closure was * created and the listeners that were previously active. */ listeners = union(list, listeners); /* * before handlers */ inAsyncTick = true; for (var i = 0; i < length; ++i) { if ((list[i].flags & HAS_BEFORE_AL) > 0) { list[i].before(this, values[list[i].uid]); } } inAsyncTick = false; // save the return value to pass to the after callbacks var returned = original.apply(this, arguments); /* * after handlers (not run if original throws) */ inAsyncTick = true; for (i = 0; i < length; ++i) { if ((list[i].flags & HAS_AFTER_AL) > 0) { list[i].after(this, values[list[i].uid]); } } inAsyncTick = false; // back to the previous listener list on the stack listeners = listenerStack.pop(); errorValues = undefined; return returned; }; }; wrap(process, '_fatalException', function (_fatalException) { return function _asyncFatalException(er) { return asyncCatcher(er) || _fatalException(er); }; }); } // 0.8 and below else { /** * If an error handler in asyncWrap throws, the process must die. Under 0.8 * and earlier the only way to put a bullet through the head of the process * is to rethrow from inside the exception handler, so rethrow and set * errorThrew to tell the uncaughtHandler what to do. */ var errorThrew = false; /** * Under Node 0.8, this handler *only* handles synchronously thrown errors. * This simplifies it, which almost but not quite makes up for the hit taken * by putting everything in a try-catch. */ asyncCatcher = function uncaughtCatcher(er) { // going down hard if (errorThrew) throw er; var handled = false; /* * error handlers */ var length = listeners.length; for (var i = 0; i < length; ++i) { var listener = listeners[i]; if ((listener.flags & HAS_ERROR_AL) === 0) continue; handled = listener.error(null, er) || handled; } /* Rethrow if one of the before / after handlers fire, which will bring the * process down immediately. */ if (!handled && inAsyncTick) throw er; }; asyncWrap = function asyncWrap(original, list, length) { var values = []; /* * listeners */ inAsyncTick = true; for (var i = 0; i < length; ++i) { var listener = list[i]; values[listener.uid] = listener.data; if ((listener.flags & HAS_CREATE_AL) === 0) continue; var value = listener.create(listener.data); if (value !== undefined) values[listener.uid] = value; } inAsyncTick = false; /* One of the main differences between this polyfill and the core * asyncListener support is that core avoids creating closures by putting a * lot of the state managemnt on the C++ side of Node (and of course also it * bakes support for async listeners into the Node C++ API through the * AsyncWrap class, which means that it doesn't monkeypatch basically every * async method like this does). */ return function () { /*jshint maxdepth:4*/ // after() handlers don't run if threw var threw = false; // ...unless the error is handled var handled = false; /* More than one listener can end up inside these closures, so save the * current listeners on a stack. */ listenerStack.push(listeners); /* Activate both the listeners that were active when the closure was * created and the listeners that were previously active. */ listeners = union(list, listeners); /* * before handlers */ inAsyncTick = true; for (var i = 0; i < length; ++i) { if ((list[i].flags & HAS_BEFORE_AL) > 0) { list[i].before(this, values[list[i].uid]); } } inAsyncTick = false; // save the return value to pass to the after callbacks var returned; try { returned = original.apply(this, arguments); } catch (er) { threw = true; for (var i = 0; i < length; ++i) { if ((listeners[i].flags & HAS_ERROR_AL) == 0) continue; try { handled = listeners[i].error(values[list[i].uid], er) || handled; } catch (x) { errorThrew = true; throw x; } } if (!handled) { // having an uncaughtException handler here alters crash semantics process.removeListener('uncaughtException', asyncCatcher); process._originalNextTick(function () { process.addListener('uncaughtException', asyncCatcher); }); throw er; } } finally { /* * after handlers (not run if original throws) */ if (!threw || handled) { inAsyncTick = true; for (i = 0; i < length; ++i) { if ((list[i].flags & HAS_AFTER_AL) > 0) { list[i].after(this, values[list[i].uid]); } } inAsyncTick = false; } // back to the previous listener list on the stack listeners = listenerStack.pop(); } return returned; }; }; // will be the first to fire if async-listener is the first module loaded process.addListener('uncaughtException', asyncCatcher); } // for performance in the case where there are no handlers, just the listener function simpleWrap(original, list, length) { inAsyncTick = true; for (var i = 0; i < length; ++i) { var listener = list[i]; if (listener.create) listener.create(listener.data); } inAsyncTick = false; // still need to make sure nested async calls are made in the context // of the listeners active at their creation return function () { listenerStack.push(listeners); listeners = union(list, listeners); var returned = original.apply(this, arguments); listeners = listenerStack.pop(); return returned; }; } /** * Called each time an asynchronous function that's been monkeypatched in * index.js is called. If there are no listeners, return the function * unwrapped. If there are any asyncListeners and any of them have callbacks, * pass them off to asyncWrap for later use, otherwise just call the listener. */ function wrapCallback(original) { var length = listeners.length; // no context to capture, so avoid closure creation if (length === 0) return original; // capture the active listeners as of when the wrapped function was called var list = listeners.slice(); for (var i = 0; i < length; ++i) { if (list[i].flags > 0) return asyncWrap(original, list, length); } return simpleWrap(original, list, length); } function AsyncListener(callbacks, data) { if (typeof callbacks.create === 'function') { this.create = callbacks.create; this.flags |= HAS_CREATE_AL; } if (typeof callbacks.before === 'function') { this.before = callbacks.before; this.flags |= HAS_BEFORE_AL; } if (typeof callbacks.after === 'function') { this.after = callbacks.after; this.flags |= HAS_AFTER_AL; } if (typeof callbacks.error === 'function') { this.error = callbacks.error; this.flags |= HAS_ERROR_AL; } this.uid = ++uid; this.data = data === undefined ? null : data; } AsyncListener.prototype.create = undefined; AsyncListener.prototype.before = undefined; AsyncListener.prototype.after = undefined; AsyncListener.prototype.error = undefined; AsyncListener.prototype.data = undefined; AsyncListener.prototype.uid = 0; AsyncListener.prototype.flags = 0; function createAsyncListener(callbacks, data) { if (typeof callbacks !== 'object' || !callbacks) { throw new TypeError('callbacks argument must be an object'); } if (callbacks instanceof AsyncListener) { return callbacks; } else { return new AsyncListener(callbacks, data); } } function addAsyncListener(callbacks, data) { var listener; if (!(callbacks instanceof AsyncListener)) { listener = createAsyncListener(callbacks, data); } else { listener = callbacks; } // Make sure the listener isn't already in the list. var registered = false; for (var i = 0; i < listeners.length; i++) { if (listener === listeners[i]) { registered = true; break; } } if (!registered) listeners.push(listener); return listener; } function removeAsyncListener(listener) { for (var i = 0; i < listeners.length; i++) { if (listener === listeners[i]) { listeners.splice(i, 1); break; } } } process.createAsyncListener = createAsyncListener; process.addAsyncListener = addAsyncListener; process.removeAsyncListener = removeAsyncListener; module.exports = wrapCallback; /***/ }), /***/ 4559: /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; if (process.addAsyncListener) throw new Error("Don't require polyfill unless needed"); var shimmer = __webpack_require__(1938) , semver = __webpack_require__(2751) , wrap = shimmer.wrap , massWrap = shimmer.massWrap , wrapCallback = __webpack_require__(5213) , util = __webpack_require__(1669) ; var v6plus = semver.gte(process.version, '6.0.0'); var v7plus = semver.gte(process.version, '7.0.0'); var v8plus = semver.gte(process.version, '8.0.0'); var v11plus = semver.gte(process.version, '11.0.0'); var net = __webpack_require__(1631); // From Node.js v7.0.0, net._normalizeConnectArgs have been renamed net._normalizeArgs if (v7plus && !net._normalizeArgs) { // a polyfill in our polyfill etc so forth -- taken from node master on 2017/03/09 net._normalizeArgs = function (args) { if (args.length === 0) { return [{}, null]; } var arg0 = args[0]; var options = {}; if (typeof arg0 === 'object' && arg0 !== null) { // (options[...][, cb]) options = arg0; } else if (isPipeName(arg0)) { // (path[...][, cb]) options.path = arg0; } else { // ([port][, host][...][, cb]) options.port = arg0; if (args.length > 1 && typeof args[1] === 'string') { options.host = args[1]; } } var cb = args[args.length - 1]; if (typeof cb !== 'function') return [options, null]; else return [options, cb]; } } else if (!v7plus && !net._normalizeConnectArgs) { // a polyfill in our polyfill etc so forth -- taken from node master on 2013/10/30 net._normalizeConnectArgs = function (args) { var options = {}; function toNumber(x) { return (x = Number(x)) >= 0 ? x : false; } if (typeof args[0] === 'object' && args[0] !== null) { // connect(options, [cb]) options = args[0]; } else if (typeof args[0] === 'string' && toNumber(args[0]) === false) { // connect(path, [cb]); options.path = args[0]; } else { // connect(port, [host], [cb]) options.port = args[0]; if (typeof args[1] === 'string') { options.host = args[1]; } } var cb = args[args.length - 1]; return typeof cb === 'function' ? [options, cb] : [options]; }; } // In https://github.com/nodejs/node/pull/11796 `_listen2` was renamed // `_setUpListenHandle`. It's still aliased as `_listen2`, and currently the // Node internals still call the alias - but who knows for how long. So better // make sure we use the new name instead if available. if ('_setUpListenHandle' in net.Server.prototype) { wrap(net.Server.prototype, '_setUpListenHandle', wrapSetUpListenHandle); } else { wrap(net.Server.prototype, '_listen2', wrapSetUpListenHandle); } function wrapSetUpListenHandle(original) { return function () { this.on('connection', function (socket) { if (socket._handle) { socket._handle.onread = wrapCallback(socket._handle.onread); } }); try { return original.apply(this, arguments); } finally { // the handle will only not be set in cases where there has been an error if (this._handle && this._handle.onconnection) { this._handle.onconnection = wrapCallback(this._handle.onconnection); } } }; } function patchOnRead(ctx) { if (ctx && ctx._handle) { var handle = ctx._handle; if (!handle._originalOnread) { handle._originalOnread = handle.onread; } handle.onread = wrapCallback(handle._originalOnread); } } wrap(net.Socket.prototype, 'connect', function (original) { return function () { var args; // Node core uses an internal Symbol here to guard against the edge-case // where the user accidentally passes in an array. As we don't have access // to this Symbol we resort to this hack where we just detect if there is a // symbol or not. Checking for the number of Symbols is by no means a fool // proof solution, but it catches the most basic cases. if (v8plus && Array.isArray(arguments[0]) && Object.getOwnPropertySymbols(arguments[0]).length > 0) { // already normalized args = arguments[0]; } else { // From Node.js v7.0.0, net._normalizeConnectArgs have been renamed net._normalizeArgs args = v7plus ? net._normalizeArgs(arguments) : net._normalizeConnectArgs(arguments); } if (args[1]) args[1] = wrapCallback(args[1]); var result = original.apply(this, args); patchOnRead(this); return result; }; }); var http = __webpack_require__(8605); // NOTE: A rewrite occurred in 0.11 that changed the addRequest signature // from (req, host, port, localAddress) to (req, options) // Here, I use the longer signature to maintain 0.10 support, even though // the rest of the arguments aren't actually used wrap(http.Agent.prototype, 'addRequest', function (original) { return function (req) { var onSocket = req.onSocket; req.onSocket = wrapCallback(function (socket) { patchOnRead(socket); return onSocket.apply(this, arguments); }); return original.apply(this, arguments); }; }); var childProcess = __webpack_require__(3129); function wrapChildProcess(child) { if (Array.isArray(child.stdio)) { child.stdio.forEach(function (socket) { if (socket && socket._handle) { socket._handle.onread = wrapCallback(socket._handle.onread); wrap(socket._handle, 'close', activatorFirst); } }); } if (child._handle) { child._handle.onexit = wrapCallback(child._handle.onexit); } } // iojs v2.0.0+ if (childProcess.ChildProcess) { wrap(childProcess.ChildProcess.prototype, 'spawn', function (original) { return function () { var result = original.apply(this, arguments); wrapChildProcess(this); return result; }; }); } else { massWrap(childProcess, [ 'execFile', // exec is implemented in terms of execFile 'fork', 'spawn' ], function (original) { return function () { var result = original.apply(this, arguments); wrapChildProcess(result); return result; }; }); } // need unwrapped nextTick for use within < 0.9 async error handling if (!process._fatalException) { process._originalNextTick = process.nextTick; } var processors = []; if (process._nextDomainTick) processors.push('_nextDomainTick'); if (process._tickDomainCallback) processors.push('_tickDomainCallback'); massWrap( process, processors, activator ); wrap(process, 'nextTick', activatorFirst); var asynchronizers = [ 'setTimeout', 'setInterval' ]; if (global.setImmediate) asynchronizers.push('setImmediate'); var timers = __webpack_require__(8213); var patchGlobalTimers = global.setTimeout === timers.setTimeout; massWrap( timers, asynchronizers, activatorFirst ); if (patchGlobalTimers) { massWrap( global, asynchronizers, activatorFirst ); } var dns = __webpack_require__(881); massWrap( dns, [ 'lookup', 'resolve', 'resolve4', 'resolve6', 'resolveCname', 'resolveMx', 'resolveNs', 'resolveTxt', 'resolveSrv', 'reverse' ], activator ); if (dns.resolveNaptr) wrap(dns, 'resolveNaptr', activator); var fs = __webpack_require__(5747); massWrap( fs, [ 'watch', 'rename', 'truncate', 'chown', 'fchown', 'chmod', 'fchmod', 'stat', 'lstat', 'fstat', 'link', 'symlink', 'readlink', 'realpath', 'unlink', 'rmdir', 'mkdir', 'readdir', 'close', 'open', 'utimes', 'futimes', 'fsync', 'write', 'read', 'readFile', 'writeFile', 'appendFile', 'watchFile', 'unwatchFile', "exists", ], activator ); // only wrap lchown and lchmod on systems that have them. if (fs.lchown) wrap(fs, 'lchown', activator); if (fs.lchmod) wrap(fs, 'lchmod', activator); // only wrap ftruncate in versions of node that have it if (fs.ftruncate) wrap(fs, 'ftruncate', activator); // Wrap zlib streams var zlib; try { zlib = __webpack_require__(8761); } catch (err) { } if (zlib && zlib.Deflate && zlib.Deflate.prototype) { var proto = Object.getPrototypeOf(zlib.Deflate.prototype); if (proto._transform) { // streams2 wrap(proto, "_transform", activator); } else if (proto.write && proto.flush && proto.end) { // plain ol' streams massWrap( proto, [ 'write', 'flush', 'end' ], activator ); } } // Wrap Crypto var crypto; try { crypto = __webpack_require__(6417); } catch (err) { } if (crypto) { var toWrap = [ 'pbkdf2', 'randomBytes', ]; if (!v11plus) { toWrap.push('pseudoRandomBytes'); } massWrap(crypto, toWrap, activator); } // It is unlikely that any userspace promise implementations have a native // implementation of both Promise and Promise.toString. var instrumentPromise = !!global.Promise && Promise.toString() === 'function Promise() { [native code] }' && Promise.toString.toString() === 'function toString() { [native code] }'; // Check that global Promise is native if (instrumentPromise) { // shoult not use any methods that have already been wrapped var promiseListener = process.addAsyncListener({ create: function create() { instrumentPromise = false; } }); // should not resolve synchronously global.Promise.resolve(true).then(function notSync() { instrumentPromise = false; }); process.removeAsyncListener(promiseListener); } /* * Native promises use the microtask queue to make all callbacks run * asynchronously to avoid Zalgo issues. Since the microtask queue is not * exposed externally, promises need to be modified in a fairly invasive and * complex way. * * The async boundary in promises that must be patched is between the * fulfillment of the promise and the execution of any callback that is waiting * for that fulfillment to happen. This means that we need to trigger a create * when resolve or reject is called and trigger before, after and error handlers * around the callback execution. There may be multiple callbacks for each * fulfilled promise, so handlers will behave similar to setInterval where * there may be multiple before after and error calls for each create call. * * async-listener monkeypatching has one basic entry point: `wrapCallback`. * `wrapCallback` should be called when create should be triggered and be * passed a function to wrap, which will execute the body of the async work. * The resolve and reject calls can be modified fairly easily to call * `wrapCallback`, but at the time of resolve and reject all the work to be done * on fulfillment may not be defined, since a call to then, chain or fetch can * be made even after the promise has been fulfilled. To get around this, we * create a placeholder function which will call a function passed into it, * since the call to the main work is being made from within the wrapped * function, async-listener will work correctly. * * There is another complication with monkeypatching Promises. Calls to then, * chain and catch each create new Promises that are fulfilled internally in * different ways depending on the return value of the callback. When the * callback return a Promise, the new Promise is resolved asynchronously after * the returned Promise has been also been resolved. When something other than * a promise is resolved the resolve call for the new Promise is put in the * microtask queue and asynchronously resolved. * * Then must be wrapped so that its returned promise has a wrapper that can be * used to invoke further continuations. This wrapper cannot be created until * after the callback has run, since the callback may return either a promise * or another value. Fortunately we already have a wrapper function around the * callback we can use (the wrapper created by resolve or reject). * * By adding an additional argument to this wrapper, we can pass in the * returned promise so it can have its own wrapper appended. the wrapper * function can the call the callback, and take action based on the return * value. If a promise is returned, the new Promise can proxy the returned * Promise's wrapper (this wrapper may not exist yet, but will by the time the * wrapper needs to be invoked). Otherwise, a new wrapper can be create the * same way as in resolve and reject. Since this wrapper is created * synchronously within another wrapper, it will properly appear as a * continuation from within the callback. */ if (instrumentPromise) { wrapPromise(); } function wrapPromise() { var Promise = global.Promise; // Updates to this class should also be applied to the the ES6 version // in es6-wrapped-promise.js. function wrappedPromise(executor) { if (!(this instanceof wrappedPromise)) { return Promise(executor); } if (typeof executor !== 'function') { return new Promise(executor); } var context, args; var promise = new Promise(wrappedExecutor); promise.__proto__ = wrappedPromise.prototype; try { executor.apply(context, args); } catch (err) { args[1](err); } return promise; function wrappedExecutor(resolve, reject) { context = this; args = [wrappedResolve, wrappedReject]; // These wrappers create a function that can be passed a function and an argument to // call as a continuation from the resolve or reject. function wrappedResolve(val) { ensureAslWrapper(promise, false); return resolve(val); } function wrappedReject(val) { ensureAslWrapper(promise, false); return reject(val); } } } util.inherits(wrappedPromise, Promise); wrap(Promise.prototype, 'then', wrapThen); // Node.js = 0 ? x : false; } // taken from node master on 2017/03/09 function isPipeName(s) { return typeof s === 'string' && toNumber(s) === false; } /***/ }), /***/ 1240: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = __webpack_require__(1310); /***/ }), /***/ 5956: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); var settle = __webpack_require__(6969); var buildFullPath = __webpack_require__(3866); var buildURL = __webpack_require__(2485); var http = __webpack_require__(8605); var https = __webpack_require__(7211); var httpFollow = __webpack_require__(6874).http; var httpsFollow = __webpack_require__(6874).https; var url = __webpack_require__(8835); var zlib = __webpack_require__(8761); var pkg = __webpack_require__(4551); var createError = __webpack_require__(7407); var enhanceError = __webpack_require__(9119); var isHttps = /https:?/; /** * * @param {http.ClientRequestArgs} options * @param {AxiosProxyConfig} proxy * @param {string} location */ function setProxy(options, proxy, location) { options.hostname = proxy.host; options.host = proxy.host; options.port = proxy.port; options.path = location; // Basic proxy authorization if (proxy.auth) { var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); options.headers['Proxy-Authorization'] = 'Basic ' + base64; } // If a proxy is used, any redirects must also pass through the proxy options.beforeRedirect = function beforeRedirect(redirection) { redirection.headers.host = redirection.host; setProxy(redirection, proxy, redirection.href); }; } /*eslint consistent-return:0*/ module.exports = function httpAdapter(config) { return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { var resolve = function resolve(value) { resolvePromise(value); }; var reject = function reject(value) { rejectPromise(value); }; var data = config.data; var headers = config.headers; // Set User-Agent (required by some servers) // Only set header if it hasn't been set in config // See https://github.com/axios/axios/issues/69 if (!headers['User-Agent'] && !headers['user-agent']) { headers['User-Agent'] = 'axios/' + pkg.version; } if (data && !utils.isStream(data)) { if (Buffer.isBuffer(data)) { // Nothing to do... } else if (utils.isArrayBuffer(data)) { data = Buffer.from(new Uint8Array(data)); } else if (utils.isString(data)) { data = Buffer.from(data, 'utf-8'); } else { return reject(createError( 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', config )); } // Add Content-Length header if data exists headers['Content-Length'] = data.length; } // HTTP basic authentication var auth = undefined; if (config.auth) { var username = config.auth.username || ''; var password = config.auth.password || ''; auth = username + ':' + password; } // Parse url var fullPath = buildFullPath(config.baseURL, config.url); var parsed = url.parse(fullPath); var protocol = parsed.protocol || 'http:'; if (!auth && parsed.auth) { var urlAuth = parsed.auth.split(':'); var urlUsername = urlAuth[0] || ''; var urlPassword = urlAuth[1] || ''; auth = urlUsername + ':' + urlPassword; } if (auth) { delete headers.Authorization; } var isHttpsRequest = isHttps.test(protocol); var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; var options = { path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), method: config.method.toUpperCase(), headers: headers, agent: agent, agents: { http: config.httpAgent, https: config.httpsAgent }, auth: auth }; if (config.socketPath) { options.socketPath = config.socketPath; } else { options.hostname = parsed.hostname; options.port = parsed.port; } var proxy = config.proxy; if (!proxy && proxy !== false) { var proxyEnv = protocol.slice(0, -1) + '_proxy'; var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; if (proxyUrl) { var parsedProxyUrl = url.parse(proxyUrl); var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; var shouldProxy = true; if (noProxyEnv) { var noProxy = noProxyEnv.split(',').map(function trim(s) { return s.trim(); }); shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { if (!proxyElement) { return false; } if (proxyElement === '*') { return true; } if (proxyElement[0] === '.' && parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { return true; } return parsed.hostname === proxyElement; }); } if (shouldProxy) { proxy = { host: parsedProxyUrl.hostname, port: parsedProxyUrl.port, protocol: parsedProxyUrl.protocol }; if (parsedProxyUrl.auth) { var proxyUrlAuth = parsedProxyUrl.auth.split(':'); proxy.auth = { username: proxyUrlAuth[0], password: proxyUrlAuth[1] }; } } } } if (proxy) { options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); } var transport; var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); if (config.transport) { transport = config.transport; } else if (config.maxRedirects === 0) { transport = isHttpsProxy ? https : http; } else { if (config.maxRedirects) { options.maxRedirects = config.maxRedirects; } transport = isHttpsProxy ? httpsFollow : httpFollow; } if (config.maxBodyLength > -1) { options.maxBodyLength = config.maxBodyLength; } // Create the request var req = transport.request(options, function handleResponse(res) { if (req.aborted) return; // uncompress the response body transparently if required var stream = res; // return the last request in case of redirects var lastRequest = res.req || req; // if no content, is HEAD request or decompress disabled we should not decompress if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) { switch (res.headers['content-encoding']) { /*eslint default-case:0*/ case 'gzip': case 'compress': case 'deflate': // add the unzipper to the body stream processing pipeline stream = stream.pipe(zlib.createUnzip()); // remove the content-encoding in order to not confuse downstream operations delete res.headers['content-encoding']; break; } } var response = { status: res.statusCode, statusText: res.statusMessage, headers: res.headers, config: config, request: lastRequest }; if (config.responseType === 'stream') { response.data = stream; settle(resolve, reject, response); } else { var responseBuffer = []; stream.on('data', function handleStreamData(chunk) { responseBuffer.push(chunk); // make sure the content length is not over the maxContentLength if specified if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) { stream.destroy(); reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded', config, null, lastRequest)); } }); stream.on('error', function handleStreamError(err) { if (req.aborted) return; reject(enhanceError(err, config, null, lastRequest)); }); stream.on('end', function handleStreamEnd() { var responseData = Buffer.concat(responseBuffer); if (config.responseType !== 'arraybuffer') { responseData = responseData.toString(config.responseEncoding); if (!config.responseEncoding || config.responseEncoding === 'utf8') { responseData = utils.stripBOM(responseData); } } response.data = responseData; settle(resolve, reject, response); }); } }); // Handle errors req.on('error', function handleRequestError(err) { if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return; reject(enhanceError(err, config, null, req)); }); // Handle request timeout if (config.timeout) { // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. // And then these socket which be hang up will devoring CPU little by little. // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. req.setTimeout(config.timeout, function handleRequestTimeout() { req.abort(); reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req)); }); } if (config.cancelToken) { // Handle cancellation config.cancelToken.promise.then(function onCanceled(cancel) { if (req.aborted) return; req.abort(); reject(cancel); }); } // Send the request if (utils.isStream(data)) { data.on('error', function handleStreamError(err) { reject(enhanceError(err, config, null, req)); }).pipe(req); } else { req.end(data); } }); }; /***/ }), /***/ 9888: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); var settle = __webpack_require__(6969); var cookies = __webpack_require__(9355); var buildURL = __webpack_require__(2485); var buildFullPath = __webpack_require__(3866); var parseHeaders = __webpack_require__(9235); var isURLSameOrigin = __webpack_require__(6330); var createError = __webpack_require__(7407); module.exports = function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { var requestData = config.data; var requestHeaders = config.headers; if (utils.isFormData(requestData)) { delete requestHeaders['Content-Type']; // Let the browser set it } var request = new XMLHttpRequest(); // HTTP basic authentication if (config.auth) { var username = config.auth.username || ''; var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); } var fullPath = buildFullPath(config.baseURL, config.url); request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); // Set the request timeout in MS request.timeout = config.timeout; // Listen for ready state request.onreadystatechange = function handleLoad() { if (!request || request.readyState !== 4) { return; } // The request errored out and we didn't get a response, this will be // handled by onerror instead // With one exception: request that using file: protocol, most browsers // will return status as 0 even though it's a successful request if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { return; } // Prepare the response var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // Clean up request request = null; }; // Handle browser request cancellation (as opposed to a manual cancellation) request.onabort = function handleAbort() { if (!request) { return; } reject(createError('Request aborted', config, 'ECONNABORTED', request)); // Clean up request request = null; }; // Handle low level network errors request.onerror = function handleError() { // Real errors are hidden from us by the browser // onerror should only fire if it's a network error reject(createError('Network Error', config, null, request)); // Clean up request request = null; }; // Handle timeout request.ontimeout = function handleTimeout() { var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; if (config.timeoutErrorMessage) { timeoutErrorMessage = config.timeoutErrorMessage; } reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', request)); // Clean up request request = null; }; // Add xsrf header // This is only done if running in a standard browser environment. // Specifically not if we're in a web worker, or react-native. if (utils.isStandardBrowserEnv()) { // Add xsrf header var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName] = xsrfValue; } } // Add headers to the request if ('setRequestHeader' in request) { utils.forEach(requestHeaders, function setRequestHeader(val, key) { if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { // Remove Content-Type if data is undefined delete requestHeaders[key]; } else { // Otherwise add header to the request request.setRequestHeader(key, val); } }); } // Add withCredentials to request if needed if (!utils.isUndefined(config.withCredentials)) { request.withCredentials = !!config.withCredentials; } // Add responseType to request if needed if (config.responseType) { try { request.responseType = config.responseType; } catch (e) { // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. if (config.responseType !== 'json') { throw e; } } } // Handle progress if needed if (typeof config.onDownloadProgress === 'function') { request.addEventListener('progress', config.onDownloadProgress); } // Not all browsers support upload events if (typeof config.onUploadProgress === 'function' && request.upload) { request.upload.addEventListener('progress', config.onUploadProgress); } if (config.cancelToken) { // Handle cancellation config.cancelToken.promise.then(function onCanceled(cancel) { if (!request) { return; } request.abort(); reject(cancel); // Clean up request request = null; }); } if (!requestData) { requestData = null; } // Send the request request.send(requestData); }); }; /***/ }), /***/ 1310: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); var bind = __webpack_require__(6395); var Axios = __webpack_require__(2507); var mergeConfig = __webpack_require__(4338); var defaults = __webpack_require__(551); /** * Create an instance of Axios * * @param {Object} defaultConfig The default config for the instance * @return {Axios} A new instance of Axios */ function createInstance(defaultConfig) { var context = new Axios(defaultConfig); var instance = bind(Axios.prototype.request, context); // Copy axios.prototype to instance utils.extend(instance, Axios.prototype, context); // Copy context to instance utils.extend(instance, context); return instance; } // Create the default instance to be exported var axios = createInstance(defaults); // Expose Axios class to allow class inheritance axios.Axios = Axios; // Factory for creating new instances axios.create = function create(instanceConfig) { return createInstance(mergeConfig(axios.defaults, instanceConfig)); }; // Expose Cancel & CancelToken axios.Cancel = __webpack_require__(8773); axios.CancelToken = __webpack_require__(2676); axios.isCancel = __webpack_require__(5934); // Expose all/spread axios.all = function all(promises) { return Promise.all(promises); }; axios.spread = __webpack_require__(9682); // Expose isAxiosError axios.isAxiosError = __webpack_require__(6711); module.exports = axios; // Allow use of default import syntax in TypeScript module.exports.default = axios; /***/ }), /***/ 8773: /***/ ((module) => { "use strict"; /** * A `Cancel` is an object that is thrown when an operation is canceled. * * @class * @param {string=} message The message. */ function Cancel(message) { this.message = message; } Cancel.prototype.toString = function toString() { return 'Cancel' + (this.message ? ': ' + this.message : ''); }; Cancel.prototype.__CANCEL__ = true; module.exports = Cancel; /***/ }), /***/ 2676: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Cancel = __webpack_require__(8773); /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * * @class * @param {Function} executor The executor function. */ function CancelToken(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); } var resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); var token = this; executor(function cancel(message) { if (token.reason) { // Cancellation has already been requested return; } token.reason = new Cancel(message); resolvePromise(token.reason); }); } /** * Throws a `Cancel` if cancellation has been requested. */ CancelToken.prototype.throwIfRequested = function throwIfRequested() { if (this.reason) { throw this.reason; } }; /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. */ CancelToken.source = function source() { var cancel; var token = new CancelToken(function executor(c) { cancel = c; }); return { token: token, cancel: cancel }; }; module.exports = CancelToken; /***/ }), /***/ 5934: /***/ ((module) => { "use strict"; module.exports = function isCancel(value) { return !!(value && value.__CANCEL__); }; /***/ }), /***/ 2507: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); var buildURL = __webpack_require__(2485); var InterceptorManager = __webpack_require__(7263); var dispatchRequest = __webpack_require__(6348); var mergeConfig = __webpack_require__(4338); /** * Create a new instance of Axios * * @param {Object} instanceConfig The default config for the instance */ function Axios(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; } /** * Dispatch a request * * @param {Object} config The config specific for this request (merged with this.defaults) */ Axios.prototype.request = function request(config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof config === 'string') { config = arguments[1] || {}; config.url = arguments[0]; } else { config = config || {}; } config = mergeConfig(this.defaults, config); // Set config.method if (config.method) { config.method = config.method.toLowerCase(); } else if (this.defaults.method) { config.method = this.defaults.method.toLowerCase(); } else { config.method = 'get'; } // Hook up interceptors middleware var chain = [dispatchRequest, undefined]; var promise = Promise.resolve(config); this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { chain.unshift(interceptor.fulfilled, interceptor.rejected); }); this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { chain.push(interceptor.fulfilled, interceptor.rejected); }); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; }; Axios.prototype.getUri = function getUri(config) { config = mergeConfig(this.defaults, config); return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); }; // Provide aliases for supported request methods utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { return this.request(mergeConfig(config || {}, { method: method, url: url, data: (config || {}).data })); }; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, data, config) { return this.request(mergeConfig(config || {}, { method: method, url: url, data: data })); }; }); module.exports = Axios; /***/ }), /***/ 7263: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); function InterceptorManager() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ InterceptorManager.prototype.use = function use(fulfilled, rejected) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected }); return this.handlers.length - 1; }; /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` */ InterceptorManager.prototype.eject = function eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } }; /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `eject`. * * @param {Function} fn The function to call for each interceptor */ InterceptorManager.prototype.forEach = function forEach(fn) { utils.forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } }); }; module.exports = InterceptorManager; /***/ }), /***/ 3866: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isAbsoluteURL = __webpack_require__(3103); var combineURLs = __webpack_require__(6426); /** * Creates a new URL by combining the baseURL with the requestedURL, * only when the requestedURL is not already an absolute URL. * If the requestURL is absolute, this function returns the requestedURL untouched. * * @param {string} baseURL The base URL * @param {string} requestedURL Absolute or relative URL to combine * @returns {string} The combined full path */ module.exports = function buildFullPath(baseURL, requestedURL) { if (baseURL && !isAbsoluteURL(requestedURL)) { return combineURLs(baseURL, requestedURL); } return requestedURL; }; /***/ }), /***/ 7407: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var enhanceError = __webpack_require__(9119); /** * Create an Error with the specified message, config, error code, request and response. * * @param {string} message The error message. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The created error. */ module.exports = function createError(message, config, code, request, response) { var error = new Error(message); return enhanceError(error, config, code, request, response); }; /***/ }), /***/ 6348: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); var transformData = __webpack_require__(3757); var isCancel = __webpack_require__(5934); var defaults = __webpack_require__(551); /** * Throws a `Cancel` if cancellation has been requested. */ function throwIfCancellationRequested(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } } /** * Dispatch a request to the server using the configured adapter. * * @param {object} config The config that is to be used for the request * @returns {Promise} The Promise to be fulfilled */ module.exports = function dispatchRequest(config) { throwIfCancellationRequested(config); // Ensure headers exist config.headers = config.headers || {}; // Transform request data config.data = transformData( config.data, config.headers, config.transformRequest ); // Flatten headers config.headers = utils.merge( config.headers.common || {}, config.headers[config.method] || {}, config.headers ); utils.forEach( ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { delete config.headers[method]; } ); var adapter = config.adapter || defaults.adapter; return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); // Transform response data response.data = transformData( response.data, response.headers, config.transformResponse ); return response; }, function onAdapterRejection(reason) { if (!isCancel(reason)) { throwIfCancellationRequested(config); // Transform response data if (reason && reason.response) { reason.response.data = transformData( reason.response.data, reason.response.headers, config.transformResponse ); } } return Promise.reject(reason); }); }; /***/ }), /***/ 9119: /***/ ((module) => { "use strict"; /** * Update an Error with the specified config, error code, and response. * * @param {Error} error The error to update. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The error. */ module.exports = function enhanceError(error, config, code, request, response) { error.config = config; if (code) { error.code = code; } error.request = request; error.response = response; error.isAxiosError = true; error.toJSON = function toJSON() { return { // Standard message: this.message, name: this.name, // Microsoft description: this.description, number: this.number, // Mozilla fileName: this.fileName, lineNumber: this.lineNumber, columnNumber: this.columnNumber, stack: this.stack, // Axios config: this.config, code: this.code }; }; return error; }; /***/ }), /***/ 4338: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); /** * Config-specific merge-function which creates a new config-object * by merging two configuration objects together. * * @param {Object} config1 * @param {Object} config2 * @returns {Object} New object resulting from merging config2 to config1 */ module.exports = function mergeConfig(config1, config2) { // eslint-disable-next-line no-param-reassign config2 = config2 || {}; var config = {}; var valueFromConfig2Keys = ['url', 'method', 'data']; var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; var defaultToConfig2Keys = [ 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' ]; var directMergeKeys = ['validateStatus']; function getMergedValue(target, source) { if (utils.isPlainObject(target) && utils.isPlainObject(source)) { return utils.merge(target, source); } else if (utils.isPlainObject(source)) { return utils.merge({}, source); } else if (utils.isArray(source)) { return source.slice(); } return source; } function mergeDeepProperties(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(config1[prop], config2[prop]); } else if (!utils.isUndefined(config1[prop])) { config[prop] = getMergedValue(undefined, config1[prop]); } } utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(undefined, config2[prop]); } }); utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(undefined, config2[prop]); } else if (!utils.isUndefined(config1[prop])) { config[prop] = getMergedValue(undefined, config1[prop]); } }); utils.forEach(directMergeKeys, function merge(prop) { if (prop in config2) { config[prop] = getMergedValue(config1[prop], config2[prop]); } else if (prop in config1) { config[prop] = getMergedValue(undefined, config1[prop]); } }); var axiosKeys = valueFromConfig2Keys .concat(mergeDeepPropertiesKeys) .concat(defaultToConfig2Keys) .concat(directMergeKeys); var otherKeys = Object .keys(config1) .concat(Object.keys(config2)) .filter(function filterAxiosKeys(key) { return axiosKeys.indexOf(key) === -1; }); utils.forEach(otherKeys, mergeDeepProperties); return config; }; /***/ }), /***/ 6969: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var createError = __webpack_require__(7407); /** * Resolve or reject a Promise based on response status. * * @param {Function} resolve A function that resolves the promise. * @param {Function} reject A function that rejects the promise. * @param {object} response The response. */ module.exports = function settle(resolve, reject, response) { var validateStatus = response.config.validateStatus; if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { reject(createError( 'Request failed with status code ' + response.status, response.config, null, response.request, response )); } }; /***/ }), /***/ 3757: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); /** * Transform the data for a request or a response * * @param {Object|String} data The data to be transformed * @param {Array} headers The headers for the request or response * @param {Array|Function} fns A single function or Array of functions * @returns {*} The resulting transformed data */ module.exports = function transformData(data, headers, fns) { /*eslint no-param-reassign:0*/ utils.forEach(fns, function transform(fn) { data = fn(data, headers); }); return data; }; /***/ }), /***/ 551: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); var normalizeHeaderName = __webpack_require__(6950); var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } function getDefaultAdapter() { var adapter; if (typeof XMLHttpRequest !== 'undefined') { // For browsers use XHR adapter adapter = __webpack_require__(9888); } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { // For node use HTTP adapter adapter = __webpack_require__(5956); } return adapter; } var defaults = { adapter: getDefaultAdapter(), transformRequest: [function transformRequest(data, headers) { normalizeHeaderName(headers, 'Accept'); normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } if (utils.isObject(data)) { setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); return JSON.stringify(data); } return data; }], transformResponse: [function transformResponse(data) { /*eslint no-param-reassign:0*/ if (typeof data === 'string') { try { data = JSON.parse(data); } catch (e) { /* Ignore */ } } return data; }], /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, maxBodyLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; } }; defaults.headers = { common: { 'Accept': 'application/json, text/plain, */*' } }; utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { defaults.headers[method] = {}; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); }); module.exports = defaults; /***/ }), /***/ 6395: /***/ ((module) => { "use strict"; module.exports = function bind(fn, thisArg) { return function wrap() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; }; /***/ }), /***/ 2485: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); function encode(val) { return encodeURIComponent(val). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, '+'). replace(/%5B/gi, '['). replace(/%5D/gi, ']'); } /** * Build a URL by appending params to the end * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended * @returns {string} The formatted url */ module.exports = function buildURL(url, params, paramsSerializer) { /*eslint no-param-reassign:0*/ if (!params) { return url; } var serializedParams; if (paramsSerializer) { serializedParams = paramsSerializer(params); } else if (utils.isURLSearchParams(params)) { serializedParams = params.toString(); } else { var parts = []; utils.forEach(params, function serialize(val, key) { if (val === null || typeof val === 'undefined') { return; } if (utils.isArray(val)) { key = key + '[]'; } else { val = [val]; } utils.forEach(val, function parseValue(v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); } parts.push(encode(key) + '=' + encode(v)); }); }); serializedParams = parts.join('&'); } if (serializedParams) { var hashmarkIndex = url.indexOf('#'); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } return url; }; /***/ }), /***/ 6426: /***/ ((module) => { "use strict"; /** * Creates a new URL by combining the specified URLs * * @param {string} baseURL The base URL * @param {string} relativeURL The relative URL * @returns {string} The combined URL */ module.exports = function combineURLs(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; }; /***/ }), /***/ 9355: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs support document.cookie (function standardBrowserEnv() { return { write: function write(name, value, expires, path, domain, secure) { var cookie = []; cookie.push(name + '=' + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push('expires=' + new Date(expires).toGMTString()); } if (utils.isString(path)) { cookie.push('path=' + path); } if (utils.isString(domain)) { cookie.push('domain=' + domain); } if (secure === true) { cookie.push('secure'); } document.cookie = cookie.join('; '); }, read: function read(name) { var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); return (match ? decodeURIComponent(match[3]) : null); }, remove: function remove(name) { this.write(name, '', Date.now() - 86400000); } }; })() : // Non standard browser env (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return { write: function write() {}, read: function read() { return null; }, remove: function remove() {} }; })() ); /***/ }), /***/ 3103: /***/ ((module) => { "use strict"; /** * Determines whether the specified URL is absolute * * @param {string} url The URL to test * @returns {boolean} True if the specified URL is absolute, otherwise false */ module.exports = function isAbsoluteURL(url) { // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed // by any combination of letters, digits, plus, period, or hyphen. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); }; /***/ }), /***/ 6711: /***/ ((module) => { "use strict"; /** * Determines whether the payload is an error thrown by Axios * * @param {*} payload The value to test * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false */ module.exports = function isAxiosError(payload) { return (typeof payload === 'object') && (payload.isAxiosError === true); }; /***/ }), /***/ 6330: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. (function standardBrowserEnv() { var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement('a'); var originURL; /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ function resolveURL(url) { var href = url; if (msie) { // IE needs attribute set twice to normalize properties urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); /** * Determine if a URL shares the same origin as the current location * * @param {String} requestURL The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ return function isURLSameOrigin(requestURL) { var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); }; })() : // Non standard browser envs (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return function isURLSameOrigin() { return true; }; })() ); /***/ }), /***/ 6950: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); module.exports = function normalizeHeaderName(headers, normalizedName) { utils.forEach(headers, function processHeader(value, name) { if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { headers[normalizedName] = value; delete headers[name]; } }); }; /***/ }), /***/ 9235: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(3114); // Headers whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers var ignoreDuplicateOf = [ 'age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent' ]; /** * Parse headers into an object * * ``` * Date: Wed, 27 Aug 2014 08:58:49 GMT * Content-Type: application/json * Connection: keep-alive * Transfer-Encoding: chunked * ``` * * @param {String} headers Headers needing to be parsed * @returns {Object} Headers parsed into an object */ module.exports = function parseHeaders(headers) { var parsed = {}; var key; var val; var i; if (!headers) { return parsed; } utils.forEach(headers.split('\n'), function parser(line) { i = line.indexOf(':'); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { return; } if (key === 'set-cookie') { parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); } else { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } } }); return parsed; }; /***/ }), /***/ 9682: /***/ ((module) => { "use strict"; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ module.exports = function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; }; /***/ }), /***/ 3114: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var bind = __webpack_require__(6395); /*global toString:true*/ // utils is a library of generic helper functions non-specific to axios var toString = Object.prototype.toString; /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray(val) { return toString.call(val) === '[object Array]'; } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined(val) { return typeof val === 'undefined'; } /** * Determine if a value is a Buffer * * @param {Object} val The value to test * @returns {boolean} True if value is a Buffer, otherwise false */ function isBuffer(val) { return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); } /** * Determine if a value is an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ function isArrayBuffer(val) { return toString.call(val) === '[object ArrayBuffer]'; } /** * Determine if a value is a FormData * * @param {Object} val The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(val) { return (typeof FormData !== 'undefined') && (val instanceof FormData); } /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { var result; if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { result = ArrayBuffer.isView(val); } else { result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); } return result; } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber(val) { return typeof val === 'number'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a plain Object * * @param {Object} val The value to test * @return {boolean} True if value is a plain Object, otherwise false */ function isPlainObject(val) { if (toString.call(val) !== '[object Object]') { return false; } var prototype = Object.getPrototypeOf(val); return prototype === null || prototype === Object.prototype; } /** * Determine if a value is a Date * * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ function isDate(val) { return toString.call(val) === '[object Date]'; } /** * Determine if a value is a File * * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ function isFile(val) { return toString.call(val) === '[object File]'; } /** * Determine if a value is a Blob * * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ function isBlob(val) { return toString.call(val) === '[object Blob]'; } /** * Determine if a value is a Function * * @param {Object} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ function isFunction(val) { return toString.call(val) === '[object Function]'; } /** * Determine if a value is a Stream * * @param {Object} val The value to test * @returns {boolean} True if value is a Stream, otherwise false */ function isStream(val) { return isObject(val) && isFunction(val.pipe); } /** * Determine if a value is a URLSearchParams object * * @param {Object} val The value to test * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ function isURLSearchParams(val) { return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; } /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim(str) { return str.replace(/^\s*/, '').replace(/\s*$/, ''); } /** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: * typeof window -> undefined * typeof document -> undefined * * react-native: * navigator.product -> 'ReactNative' * nativescript * navigator.product -> 'NativeScript' or 'NS' */ function isStandardBrowserEnv() { if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { return false; } return ( typeof window !== 'undefined' && typeof document !== 'undefined' ); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object') { /*eslint no-param-reassign:0*/ obj = [obj]; } if (isArray(obj)) { // Iterate over array values for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (isPlainObject(result[key]) && isPlainObject(val)) { result[key] = merge(result[key], val); } else if (isPlainObject(val)) { result[key] = merge({}, val); } else if (isArray(val)) { result[key] = val.slice(); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } /** * Extends object a by mutably adding to it the properties of object b. * * @param {Object} a The object to be extended * @param {Object} b The object to copy properties from * @param {Object} thisArg The object to bind function to * @return {Object} The resulting value of object a */ function extend(a, b, thisArg) { forEach(b, function assignValue(val, key) { if (thisArg && typeof val === 'function') { a[key] = bind(val, thisArg); } else { a[key] = val; } }); return a; } /** * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) * * @param {string} content with BOM * @return {string} content value without BOM */ function stripBOM(content) { if (content.charCodeAt(0) === 0xFEFF) { content = content.slice(1); } return content; } module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, isBuffer: isBuffer, isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString, isNumber: isNumber, isObject: isObject, isPlainObject: isPlainObject, isUndefined: isUndefined, isDate: isDate, isFile: isFile, isBlob: isBlob, isFunction: isFunction, isStream: isStream, isURLSearchParams: isURLSearchParams, isStandardBrowserEnv: isStandardBrowserEnv, forEach: forEach, merge: merge, extend: extend, trim: trim, stripBOM: stripBOM }; /***/ }), /***/ 4551: /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"name":"axios","version":"0.21.1","description":"Promise based HTTP client for the browser and node.js","main":"index.js","scripts":{"test":"grunt test && bundlesize","start":"node ./sandbox/server.js","build":"NODE_ENV=production grunt build","preversion":"npm test","version":"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json","postversion":"git push && git push --tags","examples":"node ./examples/server.js","coveralls":"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js","fix":"eslint --fix lib/**/*.js"},"repository":{"type":"git","url":"https://github.com/axios/axios.git"},"keywords":["xhr","http","ajax","promise","node"],"author":"Matt Zabriskie","license":"MIT","bugs":{"url":"https://github.com/axios/axios/issues"},"homepage":"https://github.com/axios/axios","devDependencies":{"bundlesize":"^0.17.0","coveralls":"^3.0.0","es6-promise":"^4.2.4","grunt":"^1.0.2","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^20.1.0","grunt-karma":"^2.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^1.0.18","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1","karma":"^1.3.0","karma-chrome-launcher":"^2.2.0","karma-coverage":"^1.1.1","karma-firefox-launcher":"^1.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-opera-launcher":"^1.0.0","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^1.2.0","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.7","karma-webpack":"^1.7.0","load-grunt-tasks":"^3.5.2","minimist":"^1.2.0","mocha":"^5.2.0","sinon":"^4.5.0","typescript":"^2.8.1","url-search-params":"^0.10.0","webpack":"^1.13.1","webpack-dev-server":"^1.14.1"},"browser":{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},"jsdelivr":"dist/axios.min.js","unpkg":"dist/axios.min.js","typings":"./index.d.ts","dependencies":{"follow-redirects":"^1.10.0"},"bundlesize":[{"path":"./dist/axios.min.js","threshold":"5kB"}]}'); /***/ }), /***/ 8053: /***/ ((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) { 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; } /***/ }), /***/ 1759: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function getLens (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('=') if (validLen === -1) validLen = len var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4) return [validLen, placeHoldersLen] } // base64 is 4/3 + up to two characters of the original data function byteLength (b64) { var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function _byteLength (b64, validLen, placeHoldersLen) { return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function toByteArray (b64) { var tmp var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) var curByte = 0 // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen var i for (i = 0; i < len; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[curByte++] = (tmp >> 16) & 0xFF arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] parts.push( lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3F] + '==' ) } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1] parts.push( lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3F] + lookup[(tmp << 2) & 0x3F] + '=' ) } return parts.join('') } /***/ }), /***/ 9158: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var concatMap = __webpack_require__(1897); var balanced = __webpack_require__(8053); 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; } /***/ }), /***/ 7791: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Buffer = __webpack_require__(4293).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; /***/ }), /***/ 3697: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const util = __webpack_require__(1669); const assert = __webpack_require__(2357); const wrapEmitter = __webpack_require__(3584); const asyncHook = __webpack_require__(7608); const CONTEXTS_SYMBOL = 'cls@contexts'; const ERROR_SYMBOL = 'error@context'; //const trace = []; const invertedProviders = []; for (let key in asyncHook.providers) { invertedProviders[asyncHook.providers[key]] = key; } const DEBUG_CLS_HOOKED = process.env.DEBUG_CLS_HOOKED; let currentUid = -1; module.exports = { getNamespace: getNamespace, createNamespace: createNamespace, destroyNamespace: destroyNamespace, reset: reset, //trace: trace, ERROR_SYMBOL: ERROR_SYMBOL }; function Namespace(name) { this.name = name; // changed in 2.7: no default context this.active = null; this._set = []; this.id = null; this._contexts = new Map(); } Namespace.prototype.set = function set(key, value) { if (!this.active) { throw new Error('No context available. ns.run() or ns.bind() must be called first.'); } if (DEBUG_CLS_HOOKED) { debug2(' SETTING KEY:' + key + '=' + value + ' in ns:' + this.name + ' uid:' + currentUid + ' active:' + util.inspect(this.active, true)); } this.active[key] = value; return value; }; Namespace.prototype.get = function get(key) { if (!this.active) { if (DEBUG_CLS_HOOKED) { debug2(' GETTING KEY:' + key + '=undefined' + ' ' + this.name + ' uid:' + currentUid + ' active:' + util.inspect(this.active, true)); } return undefined; } if (DEBUG_CLS_HOOKED) { debug2(' GETTING KEY:' + key + '=' + this.active[key] + ' ' + this.name + ' uid:' + currentUid + ' active:' + util.inspect(this.active, true)); } return this.active[key]; }; Namespace.prototype.createContext = function createContext() { if (DEBUG_CLS_HOOKED) { debug2(' CREATING Context: ' + this.name + ' uid:' + currentUid + ' len:' + this._set.length + ' ' + ' active:' + util.inspect(this.active, true, 2, true)); } let context = Object.create(this.active ? this.active : Object.prototype); context._ns_name = this.name; context.id = currentUid; if (DEBUG_CLS_HOOKED) { debug2(' CREATED Context: ' + this.name + ' uid:' + currentUid + ' len:' + this._set.length + ' ' + ' context:' + util.inspect(context, true, 2, true)); } return context; }; Namespace.prototype.run = function run(fn) { let context = this.createContext(); this.enter(context); try { if (DEBUG_CLS_HOOKED) { debug2(' BEFORE RUN: ' + this.name + ' uid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context)); } fn(context); return context; } catch (exception) { if (exception) { exception[ERROR_SYMBOL] = context; } throw exception; } finally { if (DEBUG_CLS_HOOKED) { debug2(' AFTER RUN: ' + this.name + ' uid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context)); } this.exit(context); } }; Namespace.prototype.runAndReturn = function runAndReturn(fn) { var value; this.run(function (context) { value = fn(context); }); return value; }; /** * Uses global Promise and assumes Promise is cls friendly or wrapped already. * @param {function} fn * @returns {*} */ Namespace.prototype.runPromise = function runPromise(fn) { let context = this.createContext(); this.enter(context); let promise = fn(context); if (!promise || !promise.then || !promise.catch) { throw new Error('fn must return a promise.'); } if (DEBUG_CLS_HOOKED) { debug2(' BEFORE runPromise: ' + this.name + ' uid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context)); } return promise .then(result => { if (DEBUG_CLS_HOOKED) { debug2(' AFTER runPromise: ' + this.name + ' uid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context)); } this.exit(context); return result; }) .catch(err => { err[ERROR_SYMBOL] = context; if (DEBUG_CLS_HOOKED) { debug2(' AFTER runPromise: ' + this.name + ' uid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context)); } this.exit(context); throw err; }); }; Namespace.prototype.bind = function bindFactory(fn, context) { if (!context) { if (!this.active) { context = this.createContext(); } else { context = this.active; } } let self = this; return function clsBind() { self.enter(context); try { return fn.apply(this, arguments); } catch (exception) { if (exception) { exception[ERROR_SYMBOL] = context; } throw exception; } finally { self.exit(context); } }; }; Namespace.prototype.enter = function enter(context) { assert.ok(context, 'context must be provided for entering'); if (DEBUG_CLS_HOOKED) { debug2(' ENTER ' + this.name + ' uid:' + currentUid + ' len:' + this._set.length + ' context: ' + util.inspect(context)); } this._set.push(this.active); this.active = context; }; Namespace.prototype.exit = function exit(context) { assert.ok(context, 'context must be provided for exiting'); if (DEBUG_CLS_HOOKED) { debug2(' EXIT ' + this.name + ' uid:' + currentUid + ' len:' + this._set.length + ' context: ' + util.inspect(context)); } // Fast path for most exits that are at the top of the stack if (this.active === context) { assert.ok(this._set.length, 'can\'t remove top context'); this.active = this._set.pop(); return; } // Fast search in the stack using lastIndexOf let index = this._set.lastIndexOf(context); if (index < 0) { if (DEBUG_CLS_HOOKED) { debug2('??ERROR?? context exiting but not entered - ignoring: ' + util.inspect(context)); } assert.ok(index >= 0, 'context not currently entered; can\'t exit. \n' + util.inspect(this) + '\n' + util.inspect(context)); } else { assert.ok(index, 'can\'t remove top context'); this._set.splice(index, 1); } }; Namespace.prototype.bindEmitter = function bindEmitter(emitter) { assert.ok(emitter.on && emitter.addListener && emitter.emit, 'can only bind real EEs'); let namespace = this; let thisSymbol = 'context@' + this.name; // Capture the context active at the time the emitter is bound. function attach(listener) { if (!listener) { return; } if (!listener[CONTEXTS_SYMBOL]) { listener[CONTEXTS_SYMBOL] = Object.create(null); } listener[CONTEXTS_SYMBOL][thisSymbol] = { namespace: namespace, context: namespace.active }; } // At emit time, bind the listener within the correct context. function bind(unwrapped) { if (!(unwrapped && unwrapped[CONTEXTS_SYMBOL])) { return unwrapped; } let wrapped = unwrapped; let unwrappedContexts = unwrapped[CONTEXTS_SYMBOL]; Object.keys(unwrappedContexts).forEach(function (name) { let thunk = unwrappedContexts[name]; wrapped = thunk.namespace.bind(wrapped, thunk.context); }); return wrapped; } wrapEmitter(emitter, attach, bind); }; /** * If an error comes out of a namespace, it will have a context attached to it. * This function knows how to find it. * * @param {Error} exception Possibly annotated error. */ Namespace.prototype.fromException = function fromException(exception) { return exception[ERROR_SYMBOL]; }; function getNamespace(name) { return process.namespaces[name]; } function createNamespace(name) { assert.ok(name, 'namespace must be given a name.'); if (DEBUG_CLS_HOOKED) { debug2('CREATING NAMESPACE ' + name); } let namespace = new Namespace(name); namespace.id = currentUid; asyncHook.addHooks({ init(uid, handle, provider, parentUid, parentHandle) { //parentUid = parentUid || currentUid; // Suggested usage but appears to work better for tracing modules. currentUid = uid; //CHAIN Parent's Context onto child if none exists. This is needed to pass net-events.spec if (parentUid) { namespace._contexts.set(uid, namespace._contexts.get(parentUid)); if (DEBUG_CLS_HOOKED) { debug2('PARENTID: ' + name + ' uid:' + uid + ' parent:' + parentUid + ' provider:' + provider); } } else { namespace._contexts.set(currentUid, namespace.active); } if (DEBUG_CLS_HOOKED) { debug2('INIT ' + name + ' uid:' + uid + ' parent:' + parentUid + ' provider:' + invertedProviders[provider] + ' active:' + util.inspect(namespace.active, true)); } }, pre(uid, handle) { currentUid = uid; let context = namespace._contexts.get(uid); if (context) { if (DEBUG_CLS_HOOKED) { debug2(' PRE ' + name + ' uid:' + uid + ' handle:' + getFunctionName(handle) + ' context:' + util.inspect(context)); } namespace.enter(context); } else { if (DEBUG_CLS_HOOKED) { debug2(' PRE MISSING CONTEXT ' + name + ' uid:' + uid + ' handle:' + getFunctionName(handle)); } } }, post(uid, handle) { currentUid = uid; let context = namespace._contexts.get(uid); if (context) { if (DEBUG_CLS_HOOKED) { debug2(' POST ' + name + ' uid:' + uid + ' handle:' + getFunctionName(handle) + ' context:' + util.inspect(context)); } namespace.exit(context); } else { if (DEBUG_CLS_HOOKED) { debug2(' POST MISSING CONTEXT ' + name + ' uid:' + uid + ' handle:' + getFunctionName(handle)); } } }, destroy(uid) { currentUid = uid; if (DEBUG_CLS_HOOKED) { debug2('DESTROY ' + name + ' uid:' + uid + ' context:' + util.inspect(namespace._contexts.get(currentUid)) + ' active:' + util.inspect(namespace.active, true)); } namespace._contexts.delete(uid); } }); process.namespaces[name] = namespace; return namespace; } function destroyNamespace(name) { let namespace = getNamespace(name); assert.ok(namespace, 'can\'t delete nonexistent namespace! "' + name + '"'); assert.ok(namespace.id, 'don\'t assign to process.namespaces directly! ' + util.inspect(namespace)); process.namespaces[name] = null; } function reset() { // must unregister async listeners if (process.namespaces) { Object.keys(process.namespaces).forEach(function (name) { destroyNamespace(name); }); } process.namespaces = Object.create(null); } process.namespaces = {}; if (asyncHook._state && !asyncHook._state.enabled) { asyncHook.enable(); } function debug2(msg) { if (process.env.DEBUG) { process._rawDebug(msg); } } /*function debug(from, ns) { process._rawDebug('DEBUG: ' + util.inspect({ from: from, currentUid: currentUid, context: ns ? ns._contexts.get(currentUid) : 'no ns' }, true, 2, true)); }*/ function getFunctionName(fn) { if (!fn) { return fn; } if (typeof fn === 'function') { if (fn.name) { return fn.name; } return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1]; } else if (fn.constructor && fn.constructor.name) { return fn.constructor.name; } } // Add back to callstack if (DEBUG_CLS_HOOKED) { var stackChain = __webpack_require__(6056); for (var modifier in stackChain.filter._modifiers) { stackChain.filter.deattach(modifier); } } /***/ }), /***/ 9213: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* eslint-disable max-len */ const util = __webpack_require__(1669); const assert = __webpack_require__(2357); const wrapEmitter = __webpack_require__(3584); const async_hooks = __webpack_require__(7303); const CONTEXTS_SYMBOL = 'cls@contexts'; const ERROR_SYMBOL = 'error@context'; const DEBUG_CLS_HOOKED = process.env.DEBUG_CLS_HOOKED; let currentUid = -1; module.exports = { getNamespace: getNamespace, createNamespace: createNamespace, destroyNamespace: destroyNamespace, reset: reset, ERROR_SYMBOL: ERROR_SYMBOL }; function Namespace(name) { this.name = name; // changed in 2.7: no default context this.active = null; this._set = []; this.id = null; this._contexts = new Map(); this._indent = 0; } Namespace.prototype.set = function set(key, value) { if (!this.active) { throw new Error('No context available. ns.run() or ns.bind() must be called first.'); } this.active[key] = value; if (DEBUG_CLS_HOOKED) { const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent); debug2(indentStr + 'CONTEXT-SET KEY:' + key + '=' + value + ' in ns:' + this.name + ' currentUid:' + currentUid + ' active:' + util.inspect(this.active, {showHidden:true, depth:2, colors:true})); } return value; }; Namespace.prototype.get = function get(key) { if (!this.active) { if (DEBUG_CLS_HOOKED) { const asyncHooksCurrentId = async_hooks.currentId(); const triggerId = async_hooks.triggerAsyncId(); const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent); //debug2(indentStr + 'CONTEXT-GETTING KEY NO ACTIVE NS:' + key + '=undefined' + ' (' + this.name + ') currentUid:' + currentUid + ' active:' + util.inspect(this.active, {showHidden:true, depth:2, colors:true})); debug2(`${indentStr}CONTEXT-GETTING KEY NO ACTIVE NS: (${this.name}) ${key}=undefined currentUid:${currentUid} asyncHooksCurrentId:${asyncHooksCurrentId} triggerId:${triggerId} len:${this._set.length}`); } return undefined; } if (DEBUG_CLS_HOOKED) { const asyncHooksCurrentId = async_hooks.executionAsyncId(); const triggerId = async_hooks.triggerAsyncId(); const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent); debug2(indentStr + 'CONTEXT-GETTING KEY:' + key + '=' + this.active[key] + ' (' + this.name + ') currentUid:' + currentUid + ' active:' + util.inspect(this.active, {showHidden:true, depth:2, colors:true})); debug2(`${indentStr}CONTEXT-GETTING KEY: (${this.name}) ${key}=${this.active[key]} currentUid:${currentUid} asyncHooksCurrentId:${asyncHooksCurrentId} triggerId:${triggerId} len:${this._set.length} active:${util.inspect(this.active)}`); } return this.active[key]; }; Namespace.prototype.createContext = function createContext() { // Prototype inherit existing context if created a new child context within existing context. let context = Object.create(this.active ? this.active : Object.prototype); context._ns_name = this.name; context.id = currentUid; if (DEBUG_CLS_HOOKED) { const asyncHooksCurrentId = async_hooks.executionAsyncId(); const triggerId = async_hooks.triggerAsyncId(); const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent); debug2(`${indentStr}CONTEXT-CREATED Context: (${this.name}) currentUid:${currentUid} asyncHooksCurrentId:${asyncHooksCurrentId} triggerId:${triggerId} len:${this._set.length} context:${util.inspect(context, {showHidden:true, depth:2, colors:true})}`); } return context; }; Namespace.prototype.run = function run(fn) { let context = this.createContext(); this.enter(context); try { if (DEBUG_CLS_HOOKED) { const triggerId = async_hooks.triggerAsyncId(); const asyncHooksCurrentId = async_hooks.executionAsyncId(); const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent); debug2(`${indentStr}CONTEXT-RUN BEGIN: (${this.name}) currentUid:${currentUid} triggerId:${triggerId} asyncHooksCurrentId:${asyncHooksCurrentId} len:${this._set.length} context:${util.inspect(context)}`); } fn(context); return context; } catch (exception) { if (exception) { exception[ERROR_SYMBOL] = context; } throw exception; } finally { if (DEBUG_CLS_HOOKED) { const triggerId = async_hooks.triggerAsyncId(); const asyncHooksCurrentId = async_hooks.executionAsyncId(); const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent); debug2(`${indentStr}CONTEXT-RUN END: (${this.name}) currentUid:${currentUid} triggerId:${triggerId} asyncHooksCurrentId:${asyncHooksCurrentId} len:${this._set.length} ${util.inspect(context)}`); } this.exit(context); } }; Namespace.prototype.runAndReturn = function runAndReturn(fn) { let value; this.run(function (context) { value = fn(context); }); return value; }; /** * Uses global Promise and assumes Promise is cls friendly or wrapped already. * @param {function} fn * @returns {*} */ Namespace.prototype.runPromise = function runPromise(fn) { let context = this.createContext(); this.enter(context); let promise = fn(context); if (!promise || !promise.then || !promise.catch) { throw new Error('fn must return a promise.'); } if (DEBUG_CLS_HOOKED) { debug2('CONTEXT-runPromise BEFORE: (' + this.name + ') currentUid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context)); } return promise .then(result => { if (DEBUG_CLS_HOOKED) { debug2('CONTEXT-runPromise AFTER then: (' + this.name + ') currentUid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context)); } this.exit(context); return result; }) .catch(err => { err[ERROR_SYMBOL] = context; if (DEBUG_CLS_HOOKED) { debug2('CONTEXT-runPromise AFTER catch: (' + this.name + ') currentUid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context)); } this.exit(context); throw err; }); }; Namespace.prototype.bind = function bindFactory(fn, context) { if (!context) { if (!this.active) { context = this.createContext(); } else { context = this.active; } } let self = this; return function clsBind() { self.enter(context); try { return fn.apply(this, arguments); } catch (exception) { if (exception) { exception[ERROR_SYMBOL] = context; } throw exception; } finally { self.exit(context); } }; }; Namespace.prototype.enter = function enter(context) { assert.ok(context, 'context must be provided for entering'); if (DEBUG_CLS_HOOKED) { const asyncHooksCurrentId = async_hooks.executionAsyncId(); const triggerId = async_hooks.triggerAsyncId(); const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent); debug2(`${indentStr}CONTEXT-ENTER: (${this.name}) currentUid:${currentUid} triggerId:${triggerId} asyncHooksCurrentId:${asyncHooksCurrentId} len:${this._set.length} ${util.inspect(context)}`); } this._set.push(this.active); this.active = context; }; Namespace.prototype.exit = function exit(context) { assert.ok(context, 'context must be provided for exiting'); if (DEBUG_CLS_HOOKED) { const asyncHooksCurrentId = async_hooks.executionAsyncId(); const triggerId = async_hooks.triggerAsyncId(); const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent); debug2(`${indentStr}CONTEXT-EXIT: (${this.name}) currentUid:${currentUid} triggerId:${triggerId} asyncHooksCurrentId:${asyncHooksCurrentId} len:${this._set.length} ${util.inspect(context)}`); } // Fast path for most exits that are at the top of the stack if (this.active === context) { assert.ok(this._set.length, 'can\'t remove top context'); this.active = this._set.pop(); return; } // Fast search in the stack using lastIndexOf let index = this._set.lastIndexOf(context); if (index < 0) { if (DEBUG_CLS_HOOKED) { debug2('??ERROR?? context exiting but not entered - ignoring: ' + util.inspect(context)); } assert.ok(index >= 0, 'context not currently entered; can\'t exit. \n' + util.inspect(this) + '\n' + util.inspect(context)); } else { assert.ok(index, 'can\'t remove top context'); this._set.splice(index, 1); } }; Namespace.prototype.bindEmitter = function bindEmitter(emitter) { assert.ok(emitter.on && emitter.addListener && emitter.emit, 'can only bind real EEs'); let namespace = this; let thisSymbol = 'context@' + this.name; // Capture the context active at the time the emitter is bound. function attach(listener) { if (!listener) { return; } if (!listener[CONTEXTS_SYMBOL]) { listener[CONTEXTS_SYMBOL] = Object.create(null); } listener[CONTEXTS_SYMBOL][thisSymbol] = { namespace: namespace, context: namespace.active }; } // At emit time, bind the listener within the correct context. function bind(unwrapped) { if (!(unwrapped && unwrapped[CONTEXTS_SYMBOL])) { return unwrapped; } let wrapped = unwrapped; let unwrappedContexts = unwrapped[CONTEXTS_SYMBOL]; Object.keys(unwrappedContexts).forEach(function (name) { let thunk = unwrappedContexts[name]; wrapped = thunk.namespace.bind(wrapped, thunk.context); }); return wrapped; } wrapEmitter(emitter, attach, bind); }; /** * If an error comes out of a namespace, it will have a context attached to it. * This function knows how to find it. * * @param {Error} exception Possibly annotated error. */ Namespace.prototype.fromException = function fromException(exception) { return exception[ERROR_SYMBOL]; }; function getNamespace(name) { return process.namespaces[name]; } function createNamespace(name) { assert.ok(name, 'namespace must be given a name.'); if (DEBUG_CLS_HOOKED) { debug2(`NS-CREATING NAMESPACE (${name})`); } let namespace = new Namespace(name); namespace.id = currentUid; const hook = async_hooks.createHook({ init(asyncId, type, triggerId, resource) { currentUid = async_hooks.executionAsyncId(); //CHAIN Parent's Context onto child if none exists. This is needed to pass net-events.spec // let initContext = namespace.active; // if(!initContext && triggerId) { // let parentContext = namespace._contexts.get(triggerId); // if (parentContext) { // namespace.active = parentContext; // namespace._contexts.set(currentUid, parentContext); // if (DEBUG_CLS_HOOKED) { // const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent); // debug2(`${indentStr}INIT [${type}] (${name}) WITH PARENT CONTEXT asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, true)} resource:${resource}`); // } // } else if (DEBUG_CLS_HOOKED) { // const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent); // debug2(`${indentStr}INIT [${type}] (${name}) MISSING CONTEXT asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, true)} resource:${resource}`); // } // }else { // namespace._contexts.set(currentUid, namespace.active); // if (DEBUG_CLS_HOOKED) { // const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent); // debug2(`${indentStr}INIT [${type}] (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, true)} resource:${resource}`); // } // } if(namespace.active) { namespace._contexts.set(asyncId, namespace.active); if (DEBUG_CLS_HOOKED) { const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent); debug2(`${indentStr}INIT [${type}] (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} resource:${resource}`); } }else if(currentUid === 0){ // CurrentId will be 0 when triggered from C++. Promise events // https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md#triggerid const triggerId = async_hooks.triggerAsyncId(); const triggerIdContext = namespace._contexts.get(triggerId); if (triggerIdContext) { namespace._contexts.set(asyncId, triggerIdContext); if (DEBUG_CLS_HOOKED) { const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent); debug2(`${indentStr}INIT USING CONTEXT FROM TRIGGERID [${type}] (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, { showHidden: true, depth: 2, colors: true })} resource:${resource}`); } } else if (DEBUG_CLS_HOOKED) { const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent); debug2(`${indentStr}INIT MISSING CONTEXT [${type}] (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, { showHidden: true, depth: 2, colors: true })} resource:${resource}`); } } if(DEBUG_CLS_HOOKED && type === 'PROMISE'){ debug2(util.inspect(resource, {showHidden: true})); const parentId = resource.parentId; const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent); debug2(`${indentStr}INIT RESOURCE-PROMISE [${type}] (${name}) parentId:${parentId} asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} resource:${resource}`); } }, before(asyncId) { currentUid = async_hooks.executionAsyncId(); let context; /* if(currentUid === 0){ // CurrentId will be 0 when triggered from C++. Promise events // https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md#triggerid //const triggerId = async_hooks.triggerAsyncId(); context = namespace._contexts.get(asyncId); // || namespace._contexts.get(triggerId); }else{ context = namespace._contexts.get(currentUid); } */ //HACK to work with promises until they are fixed in node > 8.1.1 context = namespace._contexts.get(asyncId) || namespace._contexts.get(currentUid); if (context) { if (DEBUG_CLS_HOOKED) { const triggerId = async_hooks.triggerAsyncId(); const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent); debug2(`${indentStr}BEFORE (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} context:${util.inspect(context)}`); namespace._indent += 2; } namespace.enter(context); } else if (DEBUG_CLS_HOOKED) { const triggerId = async_hooks.triggerAsyncId(); const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent); debug2(`${indentStr}BEFORE MISSING CONTEXT (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} namespace._contexts:${util.inspect(namespace._contexts, {showHidden:true, depth:2, colors:true})}`); namespace._indent += 2; } }, after(asyncId) { currentUid = async_hooks.executionAsyncId(); let context; // = namespace._contexts.get(currentUid); /* if(currentUid === 0){ // CurrentId will be 0 when triggered from C++. Promise events // https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md#triggerid //const triggerId = async_hooks.triggerAsyncId(); context = namespace._contexts.get(asyncId); // || namespace._contexts.get(triggerId); }else{ context = namespace._contexts.get(currentUid); } */ //HACK to work with promises until they are fixed in node > 8.1.1 context = namespace._contexts.get(asyncId) || namespace._contexts.get(currentUid); if (context) { if (DEBUG_CLS_HOOKED) { const triggerId = async_hooks.triggerAsyncId(); namespace._indent -= 2; const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent); debug2(`${indentStr}AFTER (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} context:${util.inspect(context)}`); } namespace.exit(context); } else if (DEBUG_CLS_HOOKED) { const triggerId = async_hooks.triggerAsyncId(); namespace._indent -= 2; const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent); debug2(`${indentStr}AFTER MISSING CONTEXT (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} context:${util.inspect(context)}`); } }, destroy(asyncId) { currentUid = async_hooks.executionAsyncId(); if (DEBUG_CLS_HOOKED) { const triggerId = async_hooks.triggerAsyncId(); const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent); debug2(`${indentStr}DESTROY (${name}) currentUid:${currentUid} asyncId:${asyncId} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} context:${util.inspect(namespace._contexts.get(currentUid))}`); } namespace._contexts.delete(asyncId); } }); hook.enable(); process.namespaces[name] = namespace; return namespace; } function destroyNamespace(name) { let namespace = getNamespace(name); assert.ok(namespace, 'can\'t delete nonexistent namespace! "' + name + '"'); assert.ok(namespace.id, 'don\'t assign to process.namespaces directly! ' + util.inspect(namespace)); process.namespaces[name] = null; } function reset() { // must unregister async listeners if (process.namespaces) { Object.keys(process.namespaces).forEach(function (name) { destroyNamespace(name); }); } process.namespaces = Object.create(null); } process.namespaces = {}; //const fs = require('fs'); function debug2(...args) { if (DEBUG_CLS_HOOKED) { //fs.writeSync(1, `${util.format(...args)}\n`); process._rawDebug(`${util.format(...args)}`); } } /*function getFunctionName(fn) { if (!fn) { return fn; } if (typeof fn === 'function') { if (fn.name) { return fn.name; } return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1]; } else if (fn.constructor && fn.constructor.name) { return fn.constructor.name; } }*/ /***/ }), /***/ 1006: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const semver = __webpack_require__(2751); /** * In order to increase node version support, this loads the version of context * that is appropriate for the version of on nodejs that is running. * Node < v8 - uses AsyncWrap and async-hooks-jl * Node >= v8 - uses native async-hooks */ if(process && semver.gte(process.versions.node, '8.0.0')){ module.exports = __webpack_require__(9213); }else{ module.exports = __webpack_require__(3697); } /***/ }), /***/ 3422: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const hasOwnProperty = __webpack_require__(1714) const {isObject, isArray} = __webpack_require__(1276) const PREFIX_BEFORE = 'before' const PREFIX_AFTER_PROP = 'after-prop' const PREFIX_AFTER_COLON = 'after-colon' const PREFIX_AFTER_VALUE = 'after-value' const PREFIX_AFTER_COMMA = 'after-comma' const SYMBOL_PREFIXES = [ PREFIX_BEFORE, PREFIX_AFTER_PROP, PREFIX_AFTER_COLON, PREFIX_AFTER_VALUE, PREFIX_AFTER_COMMA ] const COLON = ':' const UNDEFINED = undefined const symbol = (prefix, key) => Symbol.for(prefix + COLON + key) const assign_comments = ( target, source, target_key, source_key, prefix, remove_source ) => { const source_prop = symbol(prefix, source_key) if (!hasOwnProperty(source, source_prop)) { return } const target_prop = target_key === source_key ? source_prop : symbol(prefix, target_key) target[target_prop] = source[source_prop] if (remove_source) { delete source[source_prop] } } // Assign keys and comments const assign = (target, source, keys) => { keys.forEach(key => { if (!hasOwnProperty(source, key)) { return } target[key] = source[key] SYMBOL_PREFIXES.forEach(prefix => { assign_comments(target, source, key, key, prefix) }) }) return target } const swap_comments = (array, from, to) => { if (from === to) { return } SYMBOL_PREFIXES.forEach(prefix => { const target_prop = symbol(prefix, to) if (!hasOwnProperty(array, target_prop)) { assign_comments(array, array, to, from, prefix) return } const comments = array[target_prop] assign_comments(array, array, to, from, prefix) array[symbol(prefix, from)] = comments }) } const reverse_comments = array => { const {length} = array let i = 0 const max = length / 2 for (; i < max; i ++) { swap_comments(array, i, length - i - 1) } } const move_comment = (target, source, i, offset, remove) => { SYMBOL_PREFIXES.forEach(prefix => { assign_comments(target, source, i + offset, i, prefix, remove) }) } const move_comments = ( // `Array` target array target, // `Array` source array source, // `number` start index start, // `number` number of indexes to move count, // `number` offset to move offset, // `boolean` whether should remove the comments from source remove ) => { if (offset > 0) { let i = count // | count | offset | // source: ------------- // target: ------------- // | remove | // => remove === offset // From [count - 1, 0] while (i -- > 0) { move_comment(target, source, start + i, offset, remove && i < offset) } return } let i = 0 const min_remove = count + offset // | remove | count | // ------------- // ------------- // | offset | // From [0, count - 1] while (i < count) { const ii = i ++ move_comment(target, source, start + ii, offset, remove && i >= min_remove) } } class CommentArray extends Array { // - deleteCount + items.length // We should avoid `splice(begin, deleteCount, ...items)`, // because `splice(0, undefined)` is not equivalent to `splice(0)`, // as well as: // - slice splice (...args) { const {length} = this const ret = super.splice(...args) // #16 // If no element removed, we might still need to move comments, // because splice could add new items // if (!ret.length) { // return ret // } // JavaScript syntax is silly // eslint-disable-next-line prefer-const let [begin, deleteCount, ...items] = args if (begin < 0) { begin += length } if (arguments.length === 1) { deleteCount = length - begin } else { deleteCount = Math.min(length - begin, deleteCount) } const { length: item_length } = items // itemsToDelete: - // itemsToAdd: + // | dc | count | // =======-------------============ // =======++++++============ // | il | const offset = item_length - deleteCount const start = begin + deleteCount const count = length - start move_comments(this, this, start, count, offset, true) return ret } slice (...args) { const {length} = this const array = super.slice(...args) if (!array.length) { return new CommentArray() } let [begin, before] = args // Ref: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice if (before === UNDEFINED) { before = length } else if (before < 0) { before += length } if (begin < 0) { begin += length } else if (begin === UNDEFINED) { begin = 0 } move_comments(array, this, begin, before - begin, - begin) return array } unshift (...items) { const {length} = this const ret = super.unshift(...items) const { length: items_length } = items if (items_length > 0) { move_comments(this, this, 0, length, items_length, true) } return ret } shift () { const ret = super.shift() const {length} = this move_comments(this, this, 1, length, - 1, true) return ret } reverse () { super.reverse() reverse_comments(this) return this } pop () { const ret = super.pop() // Removes comments const {length} = this SYMBOL_PREFIXES.forEach(prefix => { const prop = symbol(prefix, length) delete this[prop] }) return ret } concat (...items) { let {length} = this const ret = super.concat(...items) if (!items.length) { return ret } items.forEach(item => { const prev = length length += isArray(item) ? item.length : 1 if (!(item instanceof CommentArray)) { return } move_comments(ret, item, 0, item.length, prev) }) return ret } } module.exports = { CommentArray, assign (target, source, keys) { if (!isObject(target)) { throw new TypeError('Cannot convert undefined or null to object') } if (!isObject(source)) { return target } if (keys === UNDEFINED) { keys = Object.keys(source) } else if (!isArray(keys)) { throw new TypeError('keys must be array or undefined') } return assign(target, source, keys) }, PREFIX_BEFORE, PREFIX_AFTER_PROP, PREFIX_AFTER_COLON, PREFIX_AFTER_VALUE, PREFIX_AFTER_COMMA, COLON, UNDEFINED } /***/ }), /***/ 634: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const {parse, tokenize} = __webpack_require__(2677) const stringify = __webpack_require__(5415) const {CommentArray, assign} = __webpack_require__(3422) module.exports = { parse, stringify, tokenize, CommentArray, assign } /***/ }), /***/ 2677: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // JSON formatting const esprima = __webpack_require__(2058) const { CommentArray, PREFIX_BEFORE, PREFIX_AFTER_PROP, PREFIX_AFTER_COLON, PREFIX_AFTER_VALUE, PREFIX_AFTER_COMMA, COLON, UNDEFINED } = __webpack_require__(3422) const tokenize = code => esprima.tokenize(code, { comment: true, loc: true }) const previous_hosts = [] let comments_host = null let unassigned_comments = null const previous_props = [] let last_prop let remove_comments = false let inline = false let tokens = null let last = null let current = null let index let reviver = null const clean = () => { previous_props.length = previous_hosts.length = 0 last = null last_prop = UNDEFINED } const free = () => { clean() tokens.length = 0 unassigned_comments = comments_host = tokens = last = current = reviver = null } const PREFIX_BEFORE_ALL = 'before-all' const PREFIX_AFTER = 'after' const PREFIX_AFTER_ALL = 'after-all' const BRACKET_OPEN = '[' const BRACKET_CLOSE = ']' const CURLY_BRACKET_OPEN = '{' const CURLY_BRACKET_CLOSE = '}' const COMMA = ',' const EMPTY = '' const MINUS = '-' const symbolFor = prefix => Symbol.for( last_prop !== UNDEFINED ? `${prefix}:${last_prop}` : prefix ) const transform = (k, v) => reviver ? reviver(k, v) : v const unexpected = () => { const error = new SyntaxError(`Unexpected token ${current.value.slice(0, 1)}`) Object.assign(error, current.loc.start) throw error } const unexpected_end = () => { const error = new SyntaxError('Unexpected end of JSON input') Object.assign(error, last ? last.loc.end // Empty string : { line: 1, column: 0 }) throw error } // Move the reader to the next const next = () => { const new_token = tokens[++ index] inline = current && new_token && current.loc.end.line === new_token.loc.start.line || false last = current current = new_token } const type = () => { if (!current) { unexpected_end() } return current.type === 'Punctuator' ? current.value : current.type } const is = t => type() === t const expect = a => { if (!is(a)) { unexpected() } } const set_comments_host = new_host => { previous_hosts.push(comments_host) comments_host = new_host } const restore_comments_host = () => { comments_host = previous_hosts.pop() } const assign_after_comma_comments = () => { if (!unassigned_comments) { return } const after_comma_comments = [] for (const comment of unassigned_comments) { // If the comment is inline, then it is an after-comma comment if (comment.inline) { after_comma_comments.push(comment) // Otherwise, all comments are before: comment } else { break } } const {length} = after_comma_comments if (!length) { return } if (length === unassigned_comments.length) { // If unassigned_comments are all consumed unassigned_comments = null } else { unassigned_comments.splice(0, length) } comments_host[symbolFor(PREFIX_AFTER_COMMA)] = after_comma_comments } const assign_comments = prefix => { if (!unassigned_comments) { return } comments_host[symbolFor(prefix)] = unassigned_comments unassigned_comments = null } const parse_comments = prefix => { const comments = [] while ( current && ( is('LineComment') || is('BlockComment') ) ) { const comment = { ...current, inline } // delete comment.loc comments.push(comment) next() } if (remove_comments) { return } if (!comments.length) { return } if (prefix) { comments_host[symbolFor(prefix)] = comments return } unassigned_comments = comments } const set_prop = (prop, push) => { if (push) { previous_props.push(last_prop) } last_prop = prop } const restore_prop = () => { last_prop = previous_props.pop() } const parse_object = () => { const obj = {} set_comments_host(obj) set_prop(UNDEFINED, true) let started = false let name parse_comments() while (!is(CURLY_BRACKET_CLOSE)) { if (started) { // key-value pair delimiter expect(COMMA) next() parse_comments() assign_after_comma_comments() // If there is a trailing comma, we might reach the end // ``` // { // "a": 1, // } // ``` if (is(CURLY_BRACKET_CLOSE)) { break } } started = true expect('String') name = JSON.parse(current.value) set_prop(name) assign_comments(PREFIX_BEFORE) next() parse_comments(PREFIX_AFTER_PROP) expect(COLON) next() parse_comments(PREFIX_AFTER_COLON) obj[name] = transform(name, walk()) parse_comments(PREFIX_AFTER_VALUE) } // bypass } next() last_prop = undefined // If there is no properties in the object, // try to save unassigned comments assign_comments( started ? PREFIX_AFTER : PREFIX_BEFORE ) restore_comments_host() restore_prop() return obj } const parse_array = () => { const array = new CommentArray() set_comments_host(array) set_prop(UNDEFINED, true) let started = false let i = 0 parse_comments() while (!is(BRACKET_CLOSE)) { if (started) { expect(COMMA) next() parse_comments() assign_after_comma_comments() if (is(BRACKET_CLOSE)) { break } } started = true set_prop(i) assign_comments(PREFIX_BEFORE) array[i] = transform(i, walk()) parse_comments(PREFIX_AFTER_VALUE) i ++ } next() last_prop = undefined assign_comments( started ? PREFIX_AFTER : PREFIX_BEFORE ) restore_comments_host() restore_prop() return array } function walk () { let tt = type() if (tt === CURLY_BRACKET_OPEN) { next() return parse_object() } if (tt === BRACKET_OPEN) { next() return parse_array() } let negative = EMPTY // -1 if (tt === MINUS) { next() tt = type() negative = MINUS } let v switch (tt) { case 'String': case 'Boolean': case 'Null': case 'Numeric': v = current.value next() return JSON.parse(negative + v) default: } } const isObject = subject => Object(subject) === subject const parse = (code, rev, no_comments) => { // Clean variables in closure clean() tokens = tokenize(code) reviver = rev remove_comments = no_comments if (!tokens.length) { unexpected_end() } index = - 1 next() set_comments_host({}) parse_comments(PREFIX_BEFORE_ALL) let result = walk() parse_comments(PREFIX_AFTER_ALL) if (current) { unexpected() } if (!no_comments && result !== null) { if (!isObject(result)) { // 1 -> new Number(1) // true -> new Boolean(1) // "foo" -> new String("foo") // eslint-disable-next-line no-new-object result = new Object(result) } Object.assign(result, comments_host) } restore_comments_host() // reviver result = transform('', result) free() return result } module.exports = { parse, tokenize, PREFIX_BEFORE, PREFIX_BEFORE_ALL, PREFIX_AFTER_PROP, PREFIX_AFTER_COLON, PREFIX_AFTER_VALUE, PREFIX_AFTER_COMMA, PREFIX_AFTER, PREFIX_AFTER_ALL, BRACKET_OPEN, BRACKET_CLOSE, CURLY_BRACKET_OPEN, CURLY_BRACKET_CLOSE, COLON, COMMA, EMPTY, UNDEFINED } /***/ }), /***/ 5415: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { isArray, isObject, isFunction, isNumber, isString } = __webpack_require__(1276) const repeat = __webpack_require__(652) const { PREFIX_BEFORE_ALL, PREFIX_BEFORE, PREFIX_AFTER_PROP, PREFIX_AFTER_COLON, PREFIX_AFTER_VALUE, PREFIX_AFTER_COMMA, PREFIX_AFTER, PREFIX_AFTER_ALL, BRACKET_OPEN, BRACKET_CLOSE, CURLY_BRACKET_OPEN, CURLY_BRACKET_CLOSE, COLON, COMMA, EMPTY, UNDEFINED } = __webpack_require__(2677) // eslint-disable-next-line no-control-regex, no-misleading-character-class const ESCAPABLE = /[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g // String constants const SPACE = ' ' const LF = '\n' const STR_NULL = 'null' // Symbol tags const BEFORE = prop => `${PREFIX_BEFORE}:${prop}` const AFTER_PROP = prop => `${PREFIX_AFTER_PROP}:${prop}` const AFTER_COLON = prop => `${PREFIX_AFTER_COLON}:${prop}` const AFTER_VALUE = prop => `${PREFIX_AFTER_VALUE}:${prop}` const AFTER_COMMA = prop => `${PREFIX_AFTER_COMMA}:${prop}` // table of character substitutions const meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' } const escape = string => { ESCAPABLE.lastIndex = 0 if (!ESCAPABLE.test(string)) { return string } return string.replace(ESCAPABLE, a => { const c = meta[a] return typeof c === 'string' ? c : a }) } // Escape no control characters, no quote characters, // and no backslash characters, // then we can safely slap some quotes around it. const quote = string => `"${escape(string)}"` const comment_stringify = (value, line) => line ? `//${value}` : `/*${value}*/` // display_block `boolean` whether the // WHOLE block of comments is always a block group const process_comments = (host, symbol_tag, deeper_gap, display_block) => { const comments = host[Symbol.for(symbol_tag)] if (!comments || !comments.length) { return EMPTY } let is_line_comment = false const str = comments.reduce((prev, { inline, type, value }) => { const delimiter = inline ? SPACE : LF + deeper_gap is_line_comment = type === 'LineComment' return prev + delimiter + comment_stringify(value, is_line_comment) }, EMPTY) return display_block // line comment should always end with a LF || is_line_comment ? str + LF + deeper_gap : str } let replacer = null let indent = EMPTY const clean = () => { replacer = null indent = EMPTY } const join = (one, two, gap) => one ? two // Symbol.for('before') and Symbol.for('before:prop') // might both exist if user mannually add comments to the object // and make a mistake. // SO, we are not to only trimRight but trim for both sides ? one + two.trim() + LF + gap : one.trimRight() + LF + gap : two ? two.trimRight() + LF + gap : EMPTY const join_content = (inside, value, gap) => { const comment = process_comments(value, PREFIX_BEFORE, gap + indent, true) return join(comment, inside, gap) } // | deeper_gap | // | gap | indent | // [ // "foo", // "bar" // ] const array_stringify = (value, gap) => { const deeper_gap = gap + indent const {length} = value // From the item to before close let inside = EMPTY let after_comma = EMPTY // Never use Array.prototype.forEach, // that we should iterate all items for (let i = 0; i < length; i ++) { if (i !== 0) { inside += COMMA } const before = join( after_comma, process_comments(value, BEFORE(i), deeper_gap), deeper_gap ) inside += before || (LF + deeper_gap) // JSON.stringify([undefined]) => [null] inside += stringify(i, value, deeper_gap) || STR_NULL inside += process_comments(value, AFTER_VALUE(i), deeper_gap) after_comma = process_comments(value, AFTER_COMMA(i), deeper_gap) } inside += join( after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap ) return BRACKET_OPEN + join_content(inside, value, gap) + BRACKET_CLOSE } // | deeper_gap | // | gap | indent | // { // "foo": 1, // "bar": 2 // } const object_stringify = (value, gap) => { // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null' } const deeper_gap = gap + indent // From the first element to before close let inside = EMPTY let after_comma = EMPTY let first = true const keys = isArray(replacer) ? replacer : Object.keys(value) const iteratee = key => { // Stringified value const sv = stringify(key, value, deeper_gap) // If a value is undefined, then the key-value pair should be ignored if (sv === UNDEFINED) { return } // The treat ment if (!first) { inside += COMMA } first = false const before = join( after_comma, process_comments(value, BEFORE(key), deeper_gap), deeper_gap ) inside += before || (LF + deeper_gap) inside += quote(key) + process_comments(value, AFTER_PROP(key), deeper_gap) + COLON + process_comments(value, AFTER_COLON(key), deeper_gap) + SPACE + sv + process_comments(value, AFTER_VALUE(key), deeper_gap) after_comma = process_comments(value, AFTER_COMMA(key), deeper_gap) } keys.forEach(iteratee) // if (after_comma) { // inside += COMMA // } inside += join( after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap ) return CURLY_BRACKET_OPEN + join_content(inside, value, gap) + CURLY_BRACKET_CLOSE } // @param {string} key // @param {Object} holder // @param {function()|Array} replacer // @param {string} indent // @param {string} gap function stringify (key, holder, gap) { let value = holder[key] // If the value has a toJSON method, call it to obtain a replacement value. if (isObject(value) && isFunction(value.toJSON)) { value = value.toJSON(key) } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (isFunction(replacer)) { value = replacer.call(holder, key, value) } switch (typeof value) { case 'string': return quote(value) case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return Number.isFinite(value) ? String(value) : STR_NULL case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value) // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': return isArray(value) ? array_stringify(value, gap) : object_stringify(value, gap) // undefined default: // JSON.stringify(undefined) === undefined // JSON.stringify('foo', () => undefined) === undefined } } const get_indent = space => isString(space) // If the space parameter is a string, it will be used as the indent string. ? space : isNumber(space) ? repeat(SPACE, space) : EMPTY const {toString} = Object.prototype const PRIMITIVE_OBJECT_TYPES = [ '[object Number]', '[object String]', '[object Boolean]' ] const is_primitive_object = subject => { if (typeof subject !== 'object') { return false } const str = toString.call(subject) return PRIMITIVE_OBJECT_TYPES.includes(str) } // @param {function()|Array} replacer // @param {string|number} space module.exports = (value, replacer_, space) => { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. // If the space parameter is a number, make an indent string containing that // many spaces. const indent_ = get_indent(space) if (!indent_) { return JSON.stringify(value, replacer_) } // vanilla `JSON.parse` allow invalid replacer if (!isFunction(replacer_) && !isArray(replacer_)) { replacer_ = null } replacer = replacer_ indent = indent_ const str = is_primitive_object(value) ? JSON.stringify(value) : stringify('', {'': value}, EMPTY) clean() return isObject(value) ? process_comments(value, PREFIX_BEFORE_ALL, EMPTY).trimLeft() + str + process_comments(value, PREFIX_AFTER_ALL, EMPTY).trimRight() : str } /***/ }), /***/ 1897: /***/ ((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]'; }; /***/ }), /***/ 1710: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var assert = __webpack_require__(2357); var wrapEmitter = __webpack_require__(3584); /* * * CONSTANTS * */ var CONTEXTS_SYMBOL = 'cls@contexts'; var ERROR_SYMBOL = 'error@context'; // load polyfill if native support is unavailable if (!process.addAsyncListener) __webpack_require__(4559); function Namespace(name) { this.name = name; // changed in 2.7: no default context this.active = null; this._set = []; this.id = null; } Namespace.prototype.set = function (key, value) { if (!this.active) { throw new Error("No context available. ns.run() or ns.bind() must be called first."); } this.active[key] = value; return value; }; Namespace.prototype.get = function (key) { if (!this.active) return undefined; return this.active[key]; }; Namespace.prototype.createContext = function () { return Object.create(this.active); }; Namespace.prototype.run = function (fn) { var context = this.createContext(); this.enter(context); try { fn(context); return context; } catch (exception) { if (exception) { exception[ERROR_SYMBOL] = context; } throw exception; } finally { this.exit(context); } }; Namespace.prototype.runAndReturn = function (fn) { var value; this.run(function (context) { value = fn(context); }); return value; }; Namespace.prototype.bind = function (fn, context) { if (!context) { if (!this.active) { context = this.createContext(); } else { context = this.active; } } var self = this; return function () { self.enter(context); try { return fn.apply(this, arguments); } catch (exception) { if (exception) { exception[ERROR_SYMBOL] = context; } throw exception; } finally { self.exit(context); } }; }; Namespace.prototype.enter = function (context) { assert.ok(context, "context must be provided for entering"); this._set.push(this.active); this.active = context; }; Namespace.prototype.exit = function (context) { assert.ok(context, "context must be provided for exiting"); // Fast path for most exits that are at the top of the stack if (this.active === context) { assert.ok(this._set.length, "can't remove top context"); this.active = this._set.pop(); return; } // Fast search in the stack using lastIndexOf var index = this._set.lastIndexOf(context); assert.ok(index >= 0, "context not currently entered; can't exit"); assert.ok(index, "can't remove top context"); this._set.splice(index, 1); }; Namespace.prototype.bindEmitter = function (emitter) { assert.ok(emitter.on && emitter.addListener && emitter.emit, "can only bind real EEs"); var namespace = this; var thisSymbol = 'context@' + this.name; // Capture the context active at the time the emitter is bound. function attach(listener) { if (!listener) return; if (!listener[CONTEXTS_SYMBOL]) listener[CONTEXTS_SYMBOL] = Object.create(null); listener[CONTEXTS_SYMBOL][thisSymbol] = { namespace : namespace, context : namespace.active }; } // At emit time, bind the listener within the correct context. function bind(unwrapped) { if (!(unwrapped && unwrapped[CONTEXTS_SYMBOL])) return unwrapped; var wrapped = unwrapped; var contexts = unwrapped[CONTEXTS_SYMBOL]; Object.keys(contexts).forEach(function (name) { var thunk = contexts[name]; wrapped = thunk.namespace.bind(wrapped, thunk.context); }); return wrapped; } wrapEmitter(emitter, attach, bind); }; /** * If an error comes out of a namespace, it will have a context attached to it. * This function knows how to find it. * * @param {Error} exception Possibly annotated error. */ Namespace.prototype.fromException = function (exception) { return exception[ERROR_SYMBOL]; }; function get(name) { return process.namespaces[name]; } function create(name) { assert.ok(name, "namespace must be given a name!"); var namespace = new Namespace(name); namespace.id = process.addAsyncListener({ create : function () { return namespace.active; }, before : function (context, storage) { if (storage) namespace.enter(storage); }, after : function (context, storage) { if (storage) namespace.exit(storage); }, error : function (storage) { if (storage) namespace.exit(storage); } }); process.namespaces[name] = namespace; return namespace; } function destroy(name) { var namespace = get(name); assert.ok(namespace, "can't delete nonexistent namespace!"); assert.ok(namespace.id, "don't assign to process.namespaces directly!"); process.removeAsyncListener(namespace.id); process.namespaces[name] = null; } function reset() { // must unregister async listeners if (process.namespaces) { Object.keys(process.namespaces).forEach(function (name) { destroy(name); }); } process.namespaces = Object.create(null); } if (!process.namespaces) reset(); // call immediately to set up module.exports = { getNamespace : get, createNamespace : create, destroyNamespace : destroy, reset : reset }; /***/ }), /***/ 1276: /***/ ((__unused_webpack_module, exports) => { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } /***/ }), /***/ 2708: /***/ ((module, exports, __webpack_require__) => { /* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); /** * 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.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log(...args) { // This hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return typeof console === 'object' && console.log && console.log(...args); } /** * 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__(347)(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; } }; /***/ }), /***/ 347: /***/ ((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__(8632); Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * Active `debug` instances. */ createDebug.instances = []; /** * 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 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; 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 match; } 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.enabled = createDebug.enabled(namespace); debug.useColors = createDebug.useColors(); debug.color = selectColor(namespace); debug.destroy = destroy; debug.extend = extend; // Debug.formatArgs = formatArgs; // debug.rawLog = rawLog; // env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } createDebug.instances.push(debug); return debug; } function destroy() { const index = createDebug.instances.indexOf(this); if (index !== -1) { createDebug.instances.splice(index, 1); return true; } return false; } 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.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 + '$')); } } for (i = 0; i < createDebug.instances.length; i++) { const instance = createDebug.instances[i]; instance.enabled = createDebug.enabled(instance.namespace); } } /** * 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; } createDebug.enable(createDebug.load()); return createDebug; } module.exports = setup; /***/ }), /***/ 5514: /***/ ((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__(2708); } else { module.exports = __webpack_require__(3018); } /***/ }), /***/ 3018: /***/ ((module, exports, __webpack_require__) => { /** * Module dependencies. */ const tty = __webpack_require__(3867); const util = __webpack_require__(1669); /** * 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; /** * 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__(7581); 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__(347)(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) .replace(/\s*\n\s*/g, ' '); }; /** * 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); }; /***/ }), /***/ 5866: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; Object.defineProperty(exports, "__esModule", ({ value: true })); var diagnostic_channel_1 = __webpack_require__(8262); exports.AzureMonitorSymbol = "Azure_Monitor_Tracer"; /** * By default, @azure/core-tracing default tracer is a NoopTracer. * This patching changes the default tracer to a patched BasicTracer * which emits ended spans as diag-channel events. * * The @opentelemetry/tracing package must be installed to use these patches * https://www.npmjs.com/package/@opentelemetry/tracing * @param coreTracing */ var azureCoreTracingPatchFunction = function (coreTracing) { try { var BasicTracer = Object(function webpackMissingModule() { var e = new Error("Cannot find module '@opentelemetry/tracing'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()).BasicTracer; var tracerConfig = diagnostic_channel_1.channel.spanContextPropagator ? { scopeManager: diagnostic_channel_1.channel.spanContextPropagator } : undefined; var tracer_1 = new BasicTracer(tracerConfig); // Patch startSpan instead of using spanProcessor.onStart because parentSpan must be // set while the span is constructed var startSpanOriginal_1 = tracer_1.startSpan; tracer_1.startSpan = function (name, options) { // if no parent span was provided, apply the current context if (!options || !options.parent) { var parentOperation = tracer_1.getCurrentSpan(); if (parentOperation && parentOperation.operation && parentOperation.operation.traceparent) { options = __assign({}, options, { parent: { traceId: parentOperation.operation.traceparent.traceId, spanId: parentOperation.operation.traceparent.spanId, } }); } } var span = startSpanOriginal_1.call(this, name, options); span.addEvent("Application Insights Integration enabled"); return span; }; tracer_1.addSpanProcessor(new AzureMonitorSpanProcessor()); tracer_1[exports.AzureMonitorSymbol] = true; coreTracing.setTracer(tracer_1); // recordSpanData is not present on BasicTracer - cast to any } catch (e) { /* squash errors */ } return coreTracing; }; var AzureMonitorSpanProcessor = /** @class */ (function () { function AzureMonitorSpanProcessor() { } AzureMonitorSpanProcessor.prototype.onStart = function (span) { // noop since startSpan is already patched }; AzureMonitorSpanProcessor.prototype.onEnd = function (span) { diagnostic_channel_1.channel.publish("azure-coretracing", span); }; AzureMonitorSpanProcessor.prototype.shutdown = function () { // noop }; return AzureMonitorSpanProcessor; }()); exports.azureCoreTracing = { versionSpecifier: ">= 1.0.0 < 2.0.0", patch: azureCoreTracingPatchFunction, }; function enable() { diagnostic_channel_1.channel.registerMonkeyPatch("@azure/core-tracing", exports.azureCoreTracing); } exports.enable = enable; //# sourceMappingURL=azure-coretracing.pub.js.map /***/ }), /***/ 7943: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. var diagnostic_channel_1 = __webpack_require__(8262); var bunyanPatchFunction = function (originalBunyan) { var originalEmit = originalBunyan.prototype._emit; originalBunyan.prototype._emit = function (rec, noemit) { var ret = originalEmit.apply(this, arguments); if (!noemit) { var str = ret; if (!str) { str = originalEmit.call(this, rec, true); } diagnostic_channel_1.channel.publish("bunyan", { level: rec.level, result: str }); } return ret; }; return originalBunyan; }; exports.bunyan = { versionSpecifier: ">= 1.0.0 < 2.0.0", patch: bunyanPatchFunction, }; function enable() { diagnostic_channel_1.channel.registerMonkeyPatch("bunyan", exports.bunyan); } exports.enable = enable; //# sourceMappingURL=bunyan.pub.js.map /***/ }), /***/ 3657: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. var diagnostic_channel_1 = __webpack_require__(8262); var stream_1 = __webpack_require__(2413); var consolePatchFunction = function (originalConsole) { var aiLoggingOutStream = new stream_1.Writable(); var aiLoggingErrStream = new stream_1.Writable(); // Default console is roughly equivalent to `new Console(process.stdout, process.stderr)` // We create a version which publishes to the channel and also to stdout/stderr aiLoggingOutStream.write = function (chunk) { if (!chunk) { return true; } var message = chunk.toString(); diagnostic_channel_1.channel.publish("console", { message: message }); return true; }; aiLoggingErrStream.write = function (chunk) { if (!chunk) { return true; } var message = chunk.toString(); diagnostic_channel_1.channel.publish("console", { message: message, stderr: true }); return true; }; var aiLoggingConsole = new originalConsole.Console(aiLoggingOutStream, aiLoggingErrStream); var consoleMethods = ["log", "info", "warn", "error", "dir", "time", "timeEnd", "trace", "assert"]; var _loop_1 = function (method) { var originalMethod = originalConsole[method]; if (originalMethod) { originalConsole[method] = function () { if (aiLoggingConsole[method]) { try { aiLoggingConsole[method].apply(aiLoggingConsole, arguments); } catch (e) { // Ignore errors; allow the original method to throw if necessary } } return originalMethod.apply(originalConsole, arguments); }; } }; for (var _i = 0, consoleMethods_1 = consoleMethods; _i < consoleMethods_1.length; _i++) { var method = consoleMethods_1[_i]; _loop_1(method); } return originalConsole; }; exports.console = { versionSpecifier: ">= 4.0.0", patch: consolePatchFunction, }; function enable() { diagnostic_channel_1.channel.registerMonkeyPatch("console", exports.console); // Force patching of console /* tslint:disable-next-line:no-var-requires */ __webpack_require__(7082); } exports.enable = enable; //# sourceMappingURL=console.pub.js.map /***/ }), /***/ 431: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. Object.defineProperty(exports, "__esModule", ({ value: true })); var azuresdk = __webpack_require__(5866); exports.azuresdk = azuresdk; var bunyan = __webpack_require__(7943); exports.bunyan = bunyan; var consolePub = __webpack_require__(3657); exports.console = consolePub; var mongodbCore = __webpack_require__(5547); exports.mongodbCore = mongodbCore; var mongodb = __webpack_require__(7664); exports.mongodb = mongodb; var mysql = __webpack_require__(1838); exports.mysql = mysql; var pgPool = __webpack_require__(8836); exports.pgPool = pgPool; var pg = __webpack_require__(6921); exports.pg = pg; var redis = __webpack_require__(3230); exports.redis = redis; var tedious = __webpack_require__(452); exports.tedious = tedious; var winston = __webpack_require__(4087); exports.winston = winston; function enable() { bunyan.enable(); consolePub.enable(); mongodbCore.enable(); mongodb.enable(); mysql.enable(); pg.enable(); pgPool.enable(); redis.enable(); winston.enable(); azuresdk.enable(); tedious.enable(); } exports.enable = enable; //# sourceMappingURL=index.js.map /***/ }), /***/ 5547: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. var diagnostic_channel_1 = __webpack_require__(8262); var mongodbcorePatchFunction = function (originalMongoCore) { var originalConnect = originalMongoCore.Server.prototype.connect; originalMongoCore.Server.prototype.connect = function contextPreservingConnect() { var ret = originalConnect.apply(this, arguments); // Messages sent to mongo progress through a pool // This can result in context getting mixed between different responses // so we wrap the callbacks to restore appropriate state var originalWrite = this.s.pool.write; this.s.pool.write = function contextPreservingWrite() { var cbidx = typeof arguments[1] === "function" ? 1 : 2; if (typeof arguments[cbidx] === "function") { arguments[cbidx] = diagnostic_channel_1.channel.bindToContext(arguments[cbidx]); } return originalWrite.apply(this, arguments); }; // Logout is a special case, it doesn't call the write function but instead // directly calls into connection.write var originalLogout = this.s.pool.logout; this.s.pool.logout = function contextPreservingLogout() { if (typeof arguments[1] === "function") { arguments[1] = diagnostic_channel_1.channel.bindToContext(arguments[1]); } return originalLogout.apply(this, arguments); }; return ret; }; return originalMongoCore; }; exports.mongoCore = { versionSpecifier: ">= 2.0.0 < 4.0.0", patch: mongodbcorePatchFunction, }; function enable() { diagnostic_channel_1.channel.registerMonkeyPatch("mongodb-core", exports.mongoCore); } exports.enable = enable; //# sourceMappingURL=mongodb-core.pub.js.map /***/ }), /***/ 7664: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. var diagnostic_channel_1 = __webpack_require__(8262); var mongodbPatchFunction = function (originalMongo) { var listener = originalMongo.instrument({ operationIdGenerator: { next: function () { return diagnostic_channel_1.channel.bindToContext(function (cb) { return cb(); }); }, }, }); var eventMap = {}; listener.on("started", function (event) { if (eventMap[event.requestId]) { // Note: Mongo can generate 2 completely separate requests // which share the same requestId, if a certain race condition is triggered. // For now, we accept that this can happen and potentially miss or mislabel some events. return; } eventMap[event.requestId] = __assign({}, event, { time: new Date() }); }); listener.on("succeeded", function (event) { var startedData = eventMap[event.requestId]; if (startedData) { delete eventMap[event.requestId]; } if (typeof event.operationId === "function") { event.operationId(function () { return diagnostic_channel_1.channel.publish("mongodb", { startedData: startedData, event: event, succeeded: true }); }); } else { // fallback -- correlation will not work here diagnostic_channel_1.channel.publish("mongodb", { startedData: startedData, event: event, succeeded: true }); } }); listener.on("failed", function (event) { var startedData = eventMap[event.requestId]; if (startedData) { delete eventMap[event.requestId]; } if (typeof event.operationId === "function") { event.operationId(function () { return diagnostic_channel_1.channel.publish("mongodb", { startedData: startedData, event: event, succeeded: false }); }); } else { // fallback -- correlation will not work here diagnostic_channel_1.channel.publish("mongodb", { startedData: startedData, event: event, succeeded: false }); } }); return originalMongo; }; var mongodb3PatchFunction = function (originalMongo) { var listener = originalMongo.instrument(); var eventMap = {}; var contextMap = {}; listener.on("started", function (event) { if (eventMap[event.requestId]) { // Note: Mongo can generate 2 completely separate requests // which share the same requestId, if a certain race condition is triggered. // For now, we accept that this can happen and potentially miss or mislabel some events. return; } contextMap[event.requestId] = diagnostic_channel_1.channel.bindToContext(function (cb) { return cb(); }); eventMap[event.requestId] = __assign({}, event, { time: new Date() }); }); listener.on("succeeded", function (event) { var startedData = eventMap[event.requestId]; if (startedData) { delete eventMap[event.requestId]; } if (typeof event === "object" && typeof contextMap[event.requestId] === "function") { contextMap[event.requestId](function () { return diagnostic_channel_1.channel.publish("mongodb", { startedData: startedData, event: event, succeeded: true }); }); delete contextMap[event.requestId]; } }); listener.on("failed", function (event) { var startedData = eventMap[event.requestId]; if (startedData) { delete eventMap[event.requestId]; } if (typeof event === "object" && typeof contextMap[event.requestId] === "function") { contextMap[event.requestId](function () { return diagnostic_channel_1.channel.publish("mongodb", { startedData: startedData, event: event, succeeded: false }); }); delete contextMap[event.requestId]; } }); return originalMongo; }; // In mongodb 3.3.0, mongodb-core was merged into mongodb, so the same patching // can be used here. this.s.pool was changed to this.s.coreTopology.s.pool var mongodbcorePatchFunction = function (originalMongo) { var originalConnect = originalMongo.Server.prototype.connect; originalMongo.Server.prototype.connect = function contextPreservingConnect() { var ret = originalConnect.apply(this, arguments); // Messages sent to mongo progress through a pool // This can result in context getting mixed between different responses // so we wrap the callbacks to restore appropriate state var originalWrite = this.s.coreTopology.s.pool.write; this.s.coreTopology.s.pool.write = function contextPreservingWrite() { var cbidx = typeof arguments[1] === "function" ? 1 : 2; if (typeof arguments[cbidx] === "function") { arguments[cbidx] = diagnostic_channel_1.channel.bindToContext(arguments[cbidx]); } return originalWrite.apply(this, arguments); }; // Logout is a special case, it doesn't call the write function but instead // directly calls into connection.write var originalLogout = this.s.coreTopology.s.pool.logout; this.s.coreTopology.s.pool.logout = function contextPreservingLogout() { if (typeof arguments[1] === "function") { arguments[1] = diagnostic_channel_1.channel.bindToContext(arguments[1]); } return originalLogout.apply(this, arguments); }; return ret; }; return originalMongo; }; var mongodb330PatchFunction = function (originalMongo) { mongodbcorePatchFunction(originalMongo); // apply mongodb-core patches var listener = originalMongo.instrument(); var eventMap = {}; var contextMap = {}; listener.on("started", function (event) { if (eventMap[event.requestId]) { // Note: Mongo can generate 2 completely separate requests // which share the same requestId, if a certain race condition is triggered. // For now, we accept that this can happen and potentially miss or mislabel some events. return; } contextMap[event.requestId] = diagnostic_channel_1.channel.bindToContext(function (cb) { return cb(); }); eventMap[event.requestId] = event; }); listener.on("succeeded", function (event) { var startedData = eventMap[event.requestId]; if (startedData) { delete eventMap[event.requestId]; } if (typeof event === "object" && typeof contextMap[event.requestId] === "function") { contextMap[event.requestId](function () { return diagnostic_channel_1.channel.publish("mongodb", { startedData: startedData, event: event, succeeded: true }); }); delete contextMap[event.requestId]; } }); listener.on("failed", function (event) { var startedData = eventMap[event.requestId]; if (startedData) { delete eventMap[event.requestId]; } if (typeof event === "object" && typeof contextMap[event.requestId] === "function") { contextMap[event.requestId](function () { return diagnostic_channel_1.channel.publish("mongodb", { startedData: startedData, event: event, succeeded: false }); }); delete contextMap[event.requestId]; } }); return originalMongo; }; exports.mongo2 = { versionSpecifier: ">= 2.0.0 <= 3.0.5", patch: mongodbPatchFunction, }; exports.mongo3 = { versionSpecifier: "> 3.0.5 < 3.3.0", patch: mongodb3PatchFunction, }; exports.mongo330 = { versionSpecifier: ">= 3.3.0 < 4.0.0", patch: mongodb330PatchFunction, }; function enable() { diagnostic_channel_1.channel.registerMonkeyPatch("mongodb", exports.mongo2); diagnostic_channel_1.channel.registerMonkeyPatch("mongodb", exports.mongo3); diagnostic_channel_1.channel.registerMonkeyPatch("mongodb", exports.mongo330); } exports.enable = enable; //# sourceMappingURL=mongodb.pub.js.map /***/ }), /***/ 1838: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. var diagnostic_channel_1 = __webpack_require__(8262); var path = __webpack_require__(5622); var mysqlPatchFunction = function (originalMysql, originalMysqlPath) { // The `name` passed in here is for debugging purposes, // to help distinguish which object is being patched. var patchObjectFunction = function (obj, name) { return function (func, cbWrapper) { var originalFunc = obj[func]; if (originalFunc) { obj[func] = function mysqlContextPreserver() { // Find the callback, if there is one var cbidx = arguments.length - 1; for (var i = arguments.length - 1; i >= 0; --i) { if (typeof arguments[i] === "function") { cbidx = i; break; } else if (typeof arguments[i] !== "undefined") { break; } } var cb = arguments[cbidx]; var resultContainer = { result: null, startTime: null, startDate: null }; if (typeof cb === "function") { // Preserve context on the callback. // If this is one of the functions that we want to track, // then wrap the callback with the tracking wrapper if (cbWrapper) { resultContainer.startTime = process.hrtime(); resultContainer.startDate = new Date(); arguments[cbidx] = diagnostic_channel_1.channel.bindToContext(cbWrapper(resultContainer, cb)); } else { arguments[cbidx] = diagnostic_channel_1.channel.bindToContext(cb); } } var result = originalFunc.apply(this, arguments); resultContainer.result = result; return result; }; } }; }; var patchClassMemberFunction = function (classObject, name) { return patchObjectFunction(classObject.prototype, name + ".prototype"); }; var connectionCallbackFunctions = [ "connect", "changeUser", "ping", "statistics", "end", ]; var connectionClass = __webpack_require__(4694)(path.dirname(originalMysqlPath) + "/lib/Connection"); connectionCallbackFunctions.forEach(function (value) { return patchClassMemberFunction(connectionClass, "Connection")(value); }); // Connection.createQuery is a static method patchObjectFunction(connectionClass, "Connection")("createQuery", function (resultContainer, cb) { return function (err) { var hrDuration = process.hrtime(resultContainer.startTime); /* tslint:disable-next-line:no-bitwise */ var duration = (hrDuration[0] * 1e3 + hrDuration[1] / 1e6) | 0; diagnostic_channel_1.channel.publish("mysql", { query: resultContainer.result, callbackArgs: arguments, err: err, duration: duration, time: resultContainer.startDate }); cb.apply(this, arguments); }; }); var poolCallbackFunctions = [ "_enqueueCallback", ]; var poolClass = __webpack_require__(420)(path.dirname(originalMysqlPath) + "/lib/Pool"); poolCallbackFunctions.forEach(function (value) { return patchClassMemberFunction(poolClass, "Pool")(value); }); return originalMysql; }; exports.mysql = { versionSpecifier: ">= 2.0.0 < 3.0.0", patch: mysqlPatchFunction, }; function enable() { diagnostic_channel_1.channel.registerMonkeyPatch("mysql", exports.mysql); } exports.enable = enable; //# sourceMappingURL=mysql.pub.js.map /***/ }), /***/ 8836: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. var diagnostic_channel_1 = __webpack_require__(8262); function postgresPool1PatchFunction(originalPgPool) { var originalConnect = originalPgPool.prototype.connect; originalPgPool.prototype.connect = function connect(callback) { if (callback) { arguments[0] = diagnostic_channel_1.channel.bindToContext(callback); } return originalConnect.apply(this, arguments); }; return originalPgPool; } exports.postgresPool1 = { versionSpecifier: ">= 1.0.0 < 3.0.0", patch: postgresPool1PatchFunction, }; function enable() { diagnostic_channel_1.channel.registerMonkeyPatch("pg-pool", exports.postgresPool1); } exports.enable = enable; //# sourceMappingURL=pg-pool.pub.js.map /***/ }), /***/ 6921: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. var diagnostic_channel_1 = __webpack_require__(8262); var events_1 = __webpack_require__(8614); function postgres6PatchFunction(originalPg, originalPgPath) { var originalClientQuery = originalPg.Client.prototype.query; var diagnosticOriginalFunc = "__diagnosticOriginalFunc"; // wherever the callback is passed, find it, save it, and remove it from the call // to the the original .query() function originalPg.Client.prototype.query = function query(config, values, callback) { var data = { query: {}, database: { host: this.connectionParameters.host, port: this.connectionParameters.port, }, result: null, error: null, duration: 0, time: new Date(), }; var start = process.hrtime(); var queryResult; function patchCallback(cb) { if (cb && cb[diagnosticOriginalFunc]) { cb = cb[diagnosticOriginalFunc]; } var trackingCallback = diagnostic_channel_1.channel.bindToContext(function (err, res) { var end = process.hrtime(start); data.result = res && { rowCount: res.rowCount, command: res.command }; data.error = err; data.duration = Math.ceil((end[0] * 1e3) + (end[1] / 1e6)); diagnostic_channel_1.channel.publish("postgres", data); // emulate weird internal behavior in pg@6 // on success, the callback is called *before* query events are emitted // on failure, the callback is called *instead of* the query emitting events // with no events, that means no promises (since the promise is resolved/rejected in an event handler) // since we are always inserting ourselves as a callback, we have to restore the original // behavior if the user didn't provide one themselves if (err) { if (cb) { return cb.apply(this, arguments); } else if (queryResult && queryResult instanceof events_1.EventEmitter) { queryResult.emit("error", err); } } else if (cb) { cb.apply(this, arguments); } }); try { Object.defineProperty(trackingCallback, diagnosticOriginalFunc, { value: cb }); return trackingCallback; } catch (e) { // this should never happen, but bailout in case it does return cb; } } // this function takes too many variations of arguments. // this patches any provided callback or creates a new callback if one wasn't provided. // since the callback is always called (if provided) in addition to always having a Promisified // EventEmitter returned (well, sometimes -- see above), its safe to insert a callback if none was given try { if (typeof config === "string") { if (values instanceof Array) { data.query.preparable = { text: config, args: values, }; callback = patchCallback(callback); } else { data.query.text = config; // pg v6 will, for some reason, accept both // client.query("...", undefined, () => {...}) // **and** // client.query("...", () => {...}); // Internally, precedence is given to the callback argument if (callback) { callback = patchCallback(callback); } else { values = patchCallback(values); } } } else { if (typeof config.name === "string") { data.query.plan = config.name; } else if (config.values instanceof Array) { data.query.preparable = { text: config.text, args: config.values, }; } else { data.query.text = config.text; } if (callback) { callback = patchCallback(callback); } else if (values) { values = patchCallback(values); } else { config.callback = patchCallback(config.callback); } } } catch (e) { // if our logic here throws, bail out and just let pg do its thing return originalClientQuery.apply(this, arguments); } arguments[0] = config; arguments[1] = values; arguments[2] = callback; arguments.length = (arguments.length > 3) ? arguments.length : 3; queryResult = originalClientQuery.apply(this, arguments); return queryResult; }; return originalPg; } function postgres7PatchFunction(originalPg, originalPgPath) { var originalClientQuery = originalPg.Client.prototype.query; var diagnosticOriginalFunc = "__diagnosticOriginalFunc"; // wherever the callback is passed, find it, save it, and remove it from the call // to the the original .query() function originalPg.Client.prototype.query = function query(config, values, callback) { var _this = this; var callbackProvided = !!callback; // Starting in pg@7.x+, Promise is returned only if !callbackProvided var data = { query: {}, database: { host: this.connectionParameters.host, port: this.connectionParameters.port, }, result: null, error: null, duration: 0, time: new Date(), }; var start = process.hrtime(); var queryResult; function patchCallback(cb) { if (cb && cb[diagnosticOriginalFunc]) { cb = cb[diagnosticOriginalFunc]; } var trackingCallback = diagnostic_channel_1.channel.bindToContext(function (err, res) { var end = process.hrtime(start); data.result = res && { rowCount: res.rowCount, command: res.command }; data.error = err; data.duration = Math.ceil((end[0] * 1e3) + (end[1] / 1e6)); diagnostic_channel_1.channel.publish("postgres", data); if (err) { if (cb) { return cb.apply(this, arguments); } else if (queryResult && queryResult instanceof events_1.EventEmitter) { queryResult.emit("error", err); } } else if (cb) { cb.apply(this, arguments); } }); try { Object.defineProperty(trackingCallback, diagnosticOriginalFunc, { value: cb }); return trackingCallback; } catch (e) { // this should never happen, but bailout in case it does return cb; } } // Only try to wrap the callback if it is a function. We want to keep the same // behavior of returning a promise only if no callback is provided. Wrapping // a nonfunction makes it a function and pg will interpret it as a callback try { if (typeof config === "string") { if (values instanceof Array) { data.query.preparable = { text: config, args: values, }; callbackProvided = typeof callback === "function"; callback = callbackProvided ? patchCallback(callback) : callback; } else { data.query.text = config; if (callback) { callbackProvided = typeof callback === "function"; callback = callbackProvided ? patchCallback(callback) : callback; } else { callbackProvided = typeof values === "function"; values = callbackProvided ? patchCallback(values) : values; } } } else { if (typeof config.name === "string") { data.query.plan = config.name; } else if (config.values instanceof Array) { data.query.preparable = { text: config.text, args: config.values, }; } else { data.query.text = config.text; } if (callback) { callbackProvided = typeof callback === "function"; callback = patchCallback(callback); } else if (values) { callbackProvided = typeof values === "function"; values = callbackProvided ? patchCallback(values) : values; } else { callbackProvided = typeof config.callback === "function"; config.callback = callbackProvided ? patchCallback(config.callback) : config.callback; } } } catch (e) { // if our logic here throws, bail out and just let pg do its thing return originalClientQuery.apply(this, arguments); } arguments[0] = config; arguments[1] = values; arguments[2] = callback; arguments.length = (arguments.length > 3) ? arguments.length : 3; queryResult = originalClientQuery.apply(this, arguments); if (!callbackProvided) { // no callback, so create a pass along promise return queryResult // pass resolved promise after publishing the event .then(function (result) { patchCallback()(undefined, result); return new _this._Promise(function (resolve, reject) { resolve(result); }); }) // pass along rejected promise after publishing the error .catch(function (error) { patchCallback()(error, undefined); return new _this._Promise(function (resolve, reject) { reject(error); }); }); } return queryResult; }; return originalPg; } exports.postgres6 = { versionSpecifier: "6.*", patch: postgres6PatchFunction, }; exports.postgres7 = { versionSpecifier: ">=7.* <=8.*", patch: postgres7PatchFunction, }; function enable() { diagnostic_channel_1.channel.registerMonkeyPatch("pg", exports.postgres6); diagnostic_channel_1.channel.registerMonkeyPatch("pg", exports.postgres7); } exports.enable = enable; //# sourceMappingURL=pg.pub.js.map /***/ }), /***/ 3230: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. var diagnostic_channel_1 = __webpack_require__(8262); var redisPatchFunction = function (originalRedis) { var originalSend = originalRedis.RedisClient.prototype.internal_send_command; // Note: This is mixing together both context tracking and dependency tracking originalRedis.RedisClient.prototype.internal_send_command = function (commandObj) { if (commandObj) { var cb_1 = commandObj.callback; if (!cb_1 || !cb_1.pubsubBound) { var address_1 = this.address; var startTime_1 = process.hrtime(); var startDate_1 = new Date(); // Note: augmenting the callback on internal_send_command is correct for context // tracking, but may be too low-level for dependency tracking. There are some 'errors' // which higher levels expect in some cases // However, the only other option is to intercept every individual command. commandObj.callback = diagnostic_channel_1.channel.bindToContext(function (err, result) { var hrDuration = process.hrtime(startTime_1); /* tslint:disable-next-line:no-bitwise */ var duration = (hrDuration[0] * 1e3 + hrDuration[1] / 1e6) | 0; diagnostic_channel_1.channel.publish("redis", { duration: duration, address: address_1, commandObj: commandObj, err: err, result: result, time: startDate_1 }); if (typeof cb_1 === "function") { cb_1.apply(this, arguments); } }); commandObj.callback.pubsubBound = true; } } return originalSend.call(this, commandObj); }; return originalRedis; }; exports.redis = { versionSpecifier: ">= 2.0.0 < 4.0.0", patch: redisPatchFunction, }; function enable() { diagnostic_channel_1.channel.registerMonkeyPatch("redis", exports.redis); } exports.enable = enable; //# sourceMappingURL=redis.pub.js.map /***/ }), /***/ 452: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. var diagnostic_channel_1 = __webpack_require__(8262); var tediousPatchFunction = function (originalTedious) { var originalMakeRequest = originalTedious.Connection.prototype.makeRequest; originalTedious.Connection.prototype.makeRequest = function makeRequest() { function getPatchedCallback(origCallback) { var start = process.hrtime(); var data = { query: {}, database: { host: null, port: null, }, result: null, error: null, duration: 0, }; return diagnostic_channel_1.channel.bindToContext(function (err, rowCount, rows) { var end = process.hrtime(start); data = __assign({}, data, { database: { host: this.connection.config.server, port: this.connection.config.options.port, }, result: !err && { rowCount: rowCount, rows: rows }, query: { text: this.parametersByName.statement.value, }, error: err, duration: Math.ceil((end[0] * 1e3) + (end[1] / 1e6)) }); diagnostic_channel_1.channel.publish("tedious", data); origCallback.call(this, err, rowCount, rows); }); } var request = arguments[0]; arguments[0].callback = getPatchedCallback(request.callback); originalMakeRequest.apply(this, arguments); }; return originalTedious; }; exports.tedious = { versionSpecifier: ">= 6.0.0 < 9.0.0", patch: tediousPatchFunction, }; function enable() { diagnostic_channel_1.channel.registerMonkeyPatch("tedious", exports.tedious); } exports.enable = enable; //# sourceMappingURL=tedious.pub.js.map /***/ }), /***/ 4087: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; return t; }; Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. var diagnostic_channel_1 = __webpack_require__(8262); // register a "filter" with each logger that publishes the data about to be logged var winston2PatchFunction = function (originalWinston) { var originalLog = originalWinston.Logger.prototype.log; var curLevels; var loggingFilter = function (level, message, meta) { var levelKind; if (curLevels === originalWinston.config.npm.levels) { levelKind = "npm"; } else if (curLevels === originalWinston.config.syslog.levels) { levelKind = "syslog"; } else { levelKind = "unknown"; } diagnostic_channel_1.channel.publish("winston", { level: level, message: message, meta: meta, levelKind: levelKind }); return message; }; // whenever someone logs, ensure our filter comes last originalWinston.Logger.prototype.log = function log() { curLevels = this.levels; if (!this.filters || this.filters.length === 0) { this.filters = [loggingFilter]; } else if (this.filters[this.filters.length - 1] !== loggingFilter) { this.filters = this.filters.filter(function (f) { return f !== loggingFilter; }); this.filters.push(loggingFilter); } return originalLog.apply(this, arguments); }; return originalWinston; }; var winston3PatchFunction = function (originalWinston) { var mapLevelToKind = function (winston, level) { var levelKind; if (winston.config.npm.levels[level] != null) { levelKind = "npm"; } else if (winston.config.syslog.levels[level] != null) { levelKind = "syslog"; } else { levelKind = "unknown"; } return levelKind; }; var AppInsightsTransport = /** @class */ (function (_super) { __extends(AppInsightsTransport, _super); function AppInsightsTransport(winston, opts) { var _this = _super.call(this, opts) || this; _this.winston = winston; return _this; } AppInsightsTransport.prototype.log = function (info, callback) { // tslint:disable-next-line:prefer-const - try to obtain level from Symbol(level) afterwards var message = info.message, level = info.level, meta = info.meta, splat = __rest(info, ["message", "level", "meta"]); level = typeof Symbol["for"] === "function" ? info[Symbol["for"]("level")] : level; // Symbol(level) is uncolorized, so prefer getting it from here message = info instanceof Error ? info : message; // Winston places Errors at info, strings at info.message var levelKind = mapLevelToKind(this.winston, level); meta = meta || {}; // Winston _somtimes_ puts metadata inside meta, so start from here for (var key in splat) { if (splat.hasOwnProperty(key)) { meta[key] = splat[key]; } } diagnostic_channel_1.channel.publish("winston", { message: message, level: level, levelKind: levelKind, meta: meta }); callback(); }; return AppInsightsTransport; }(originalWinston.Transport)); // Patch this function function patchedConfigure() { // Grab highest sev logging level in case of custom logging levels var levels = arguments[0].levels || originalWinston.config.npm.levels; var lastLevel; for (var level in levels) { if (levels.hasOwnProperty(level)) { lastLevel = lastLevel === undefined || levels[level] > levels[lastLevel] ? level : lastLevel; } } this.add(new AppInsightsTransport(originalWinston, { level: lastLevel })); } var origCreate = originalWinston.createLogger; originalWinston.createLogger = function patchedCreate() { // Grab highest sev logging level in case of custom logging levels var levels = arguments[0].levels || originalWinston.config.npm.levels; var lastLevel; for (var level in levels) { if (levels.hasOwnProperty(level)) { lastLevel = lastLevel === undefined || levels[level] > levels[lastLevel] ? level : lastLevel; } } // Add custom app insights transport to the end // Remark: Configure is not available until after createLogger() // and the Logger prototype is not exported in winston 3.x, so // patch both createLogger and configure. Could also call configure // again after createLogger, but that would cause configure to be called // twice per create. var result = origCreate.apply(this, arguments); result.add(new AppInsightsTransport(originalWinston, { level: lastLevel })); var origConfigure = result.configure; result.configure = function () { origConfigure.apply(this, arguments); patchedConfigure.apply(this, arguments); }; return result; }; var origRootConfigure = originalWinston.createLogger; originalWinston.configure = function () { origRootConfigure.apply(this, arguments); patchedConfigure.apply(this, arguments); }; originalWinston.add(new AppInsightsTransport(originalWinston)); return originalWinston; }; exports.winston3 = { versionSpecifier: "3.x", patch: winston3PatchFunction, }; exports.winston2 = { versionSpecifier: "2.x", patch: winston2PatchFunction, }; function enable() { diagnostic_channel_1.channel.registerMonkeyPatch("winston", exports.winston2); diagnostic_channel_1.channel.registerMonkeyPatch("winston", exports.winston3); } exports.enable = enable; //# sourceMappingURL=winston.pub.js.map /***/ }), /***/ 8262: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. Object.defineProperty(exports, "__esModule", ({ value: true })); var patchRequire_1 = __webpack_require__(1440); var patchRequire_2 = __webpack_require__(1440); exports.makePatchingRequire = patchRequire_2.makePatchingRequire; var trueFilter = function (publishing) { return true; }; var ContextPreservingEventEmitter = (function () { function ContextPreservingEventEmitter() { this.version = __webpack_require__(3263)/* .version */ .i8; // Allow for future versions to replace things? this.subscribers = {}; this.contextPreservationFunction = function (cb) { return cb; }; this.knownPatches = {}; this.currentlyPublishing = false; } ContextPreservingEventEmitter.prototype.shouldPublish = function (name) { var listeners = this.subscribers[name]; if (listeners) { return listeners.some(function (_a) { var filter = _a.filter; return !filter || filter(false); }); } return false; }; ContextPreservingEventEmitter.prototype.publish = function (name, event) { if (this.currentlyPublishing) { return; // Avoid reentrancy } var listeners = this.subscribers[name]; // Note: Listeners called synchronously to preserve context if (listeners) { var standardEvent_1 = { timestamp: Date.now(), data: event, }; this.currentlyPublishing = true; listeners.forEach(function (_a) { var listener = _a.listener, filter = _a.filter; try { if (filter && filter(true)) { listener(standardEvent_1); } } catch (e) { // Subscriber threw an error } }); this.currentlyPublishing = false; } }; ContextPreservingEventEmitter.prototype.subscribe = function (name, listener, filter) { if (filter === void 0) { filter = trueFilter; } if (!this.subscribers[name]) { this.subscribers[name] = []; } this.subscribers[name].push({ listener: listener, filter: filter }); }; ContextPreservingEventEmitter.prototype.unsubscribe = function (name, listener, filter) { if (filter === void 0) { filter = trueFilter; } var listeners = this.subscribers[name]; if (listeners) { for (var index = 0; index < listeners.length; ++index) { if (listeners[index].listener === listener && listeners[index].filter === filter) { listeners.splice(index, 1); return true; } } } return false; }; // Used for tests ContextPreservingEventEmitter.prototype.reset = function () { var _this = this; this.subscribers = {}; this.contextPreservationFunction = function (cb) { return cb; }; // Modify the knownPatches object rather than replace, since a reference will be used in the require patcher Object.getOwnPropertyNames(this.knownPatches).forEach(function (prop) { return delete _this.knownPatches[prop]; }); }; ContextPreservingEventEmitter.prototype.bindToContext = function (cb) { return this.contextPreservationFunction(cb); }; ContextPreservingEventEmitter.prototype.addContextPreservation = function (preserver) { var previousPreservationStack = this.contextPreservationFunction; this.contextPreservationFunction = (function (cb) { return preserver(previousPreservationStack(cb)); }); }; ContextPreservingEventEmitter.prototype.registerMonkeyPatch = function (packageName, patcher) { if (!this.knownPatches[packageName]) { this.knownPatches[packageName] = []; } this.knownPatches[packageName].push(patcher); }; ContextPreservingEventEmitter.prototype.getPatchesObject = function () { return this.knownPatches; }; return ContextPreservingEventEmitter; }()); if (!global.diagnosticsSource) { global.diagnosticsSource = new ContextPreservingEventEmitter(); // TODO: should this only patch require after at least one monkey patch is registered? /* tslint:disable-next-line:no-var-requires */ var moduleModule = __webpack_require__(2282); // Note: We pass in the object now before any patches are registered, but the object is passed by reference // so any updates made to the object will be visible in the patcher. moduleModule.prototype.require = patchRequire_1.makePatchingRequire(global.diagnosticsSource.getPatchesObject()); } exports.channel = global.diagnosticsSource; //# sourceMappingURL=channel.js.map /***/ }), /***/ 1440: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. Object.defineProperty(exports, "__esModule", ({ value: true })); var path = __webpack_require__(5622); var semver = __webpack_require__(2751); /* tslint:disable-next-line:no-var-requires */ var moduleModule = __webpack_require__(2282); var nativeModules = Object.keys(process.binding("natives")); var originalRequire = moduleModule.prototype.require; function makePatchingRequire(knownPatches) { var patchedModules = {}; return function patchedRequire(moduleId) { var originalModule = originalRequire.apply(this, arguments); if (knownPatches[moduleId]) { // Fetch the specific path of the module var modulePath = moduleModule._resolveFilename(moduleId, this); if (patchedModules.hasOwnProperty(modulePath)) { // This module has already been patched, no need to reapply return patchedModules[modulePath]; } var moduleVersion = void 0; if (nativeModules.indexOf(moduleId) < 0) { try { moduleVersion = originalRequire.call(this, path.join(moduleId, "package.json")).version; } catch (e) { // This should only happen if moduleId is actually a path rather than a module // This is not a supported scenario return originalModule; } } else { // This module is implemented natively so we cannot find a package.json // Instead, take the version of node itself moduleVersion = process.version.substring(1); } var prereleaseTagIndex = moduleVersion.indexOf("-"); if (prereleaseTagIndex >= 0) { // We ignore prerelease tags to avoid impossible to fix gaps in support // e.g. supporting console in >= 4.0.0 would otherwise not include // 8.0.0-pre moduleVersion = moduleVersion.substring(0, prereleaseTagIndex); } var modifiedModule = originalModule; for (var _i = 0, _a = knownPatches[moduleId]; _i < _a.length; _i++) { var modulePatcher = _a[_i]; if (semver.satisfies(moduleVersion, modulePatcher.versionSpecifier)) { modifiedModule = modulePatcher.patch(modifiedModule, modulePath); } } return patchedModules[modulePath] = modifiedModule; } return originalModule; }; } exports.makePatchingRequire = makePatchingRequire; //# sourceMappingURL=patchRequire.js.map /***/ }), /***/ 3263: /***/ ((module) => { "use strict"; module.exports = {"i8":"0.2.0"}; /***/ }), /***/ 102: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = LRUCache // This will be a proper iterable 'Map' in engines that support it, // or a fakey-fake PseudoMap in older versions. var Map = __webpack_require__(5637) var util = __webpack_require__(1669) // A linked list to keep track of recently-used-ness var Yallist = __webpack_require__(1434) // use symbols if possible, otherwise just _props var hasSymbol = typeof Symbol === 'function' && process.env._nodeLRUCacheForceNoSymbol !== '1' var makeSymbol if (hasSymbol) { makeSymbol = function (key) { return Symbol(key) } } else { makeSymbol = function (key) { return '_' + key } } var MAX = makeSymbol('max') var LENGTH = makeSymbol('length') var LENGTH_CALCULATOR = makeSymbol('lengthCalculator') var ALLOW_STALE = makeSymbol('allowStale') var MAX_AGE = makeSymbol('maxAge') var DISPOSE = makeSymbol('dispose') var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet') var LRU_LIST = makeSymbol('lruList') var CACHE = makeSymbol('cache') function naiveLength () { return 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. function LRUCache (options) { if (!(this instanceof LRUCache)) { return new LRUCache(options) } if (typeof options === 'number') { options = { max: options } } if (!options) { options = {} } var max = this[MAX] = options.max // Kind of weird to have a default max of Infinity, but oh well. if (!max || !(typeof max === 'number') || max <= 0) { this[MAX] = Infinity } var lc = options.length || naiveLength if (typeof lc !== 'function') { lc = naiveLength } this[LENGTH_CALCULATOR] = lc this[ALLOW_STALE] = options.stale || false this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this.reset() } // resize the cache when the max changes. Object.defineProperty(LRUCache.prototype, 'max', { set: function (mL) { if (!mL || !(typeof mL === 'number') || mL <= 0) { mL = Infinity } this[MAX] = mL trim(this) }, get: function () { return this[MAX] }, enumerable: true }) Object.defineProperty(LRUCache.prototype, 'allowStale', { set: function (allowStale) { this[ALLOW_STALE] = !!allowStale }, get: function () { return this[ALLOW_STALE] }, enumerable: true }) Object.defineProperty(LRUCache.prototype, 'maxAge', { set: function (mA) { if (!mA || !(typeof mA === 'number') || mA < 0) { mA = 0 } this[MAX_AGE] = mA trim(this) }, get: function () { return this[MAX_AGE] }, enumerable: true }) // resize the cache when the lengthCalculator changes. Object.defineProperty(LRUCache.prototype, 'lengthCalculator', { set: function (lC) { if (typeof lC !== 'function') { lC = naiveLength } if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(function (hit) { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }, this) } trim(this) }, get: function () { return this[LENGTH_CALCULATOR] }, enumerable: true }) Object.defineProperty(LRUCache.prototype, 'length', { get: function () { return this[LENGTH] }, enumerable: true }) Object.defineProperty(LRUCache.prototype, 'itemCount', { get: function () { return this[LRU_LIST].length }, enumerable: true }) LRUCache.prototype.rforEach = function (fn, thisp) { thisp = thisp || this for (var walker = this[LRU_LIST].tail; walker !== null;) { var prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } function forEachStep (self, fn, node, thisp) { var hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) { hit = undefined } } if (hit) { fn.call(thisp, hit.value, hit.key, self) } } LRUCache.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this[LRU_LIST].head; walker !== null;) { var next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } LRUCache.prototype.keys = function () { return this[LRU_LIST].toArray().map(function (k) { return k.key }, this) } LRUCache.prototype.values = function () { return this[LRU_LIST].toArray().map(function (k) { return k.value }, this) } LRUCache.prototype.reset = function () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(function (hit) { this[DISPOSE](hit.key, hit.value) }, this) } 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 } LRUCache.prototype.dump = function () { return this[LRU_LIST].map(function (hit) { if (!isStale(this, hit)) { return { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) } } }, this).toArray().filter(function (h) { return h }) } LRUCache.prototype.dumpLru = function () { return this[LRU_LIST] } /* istanbul ignore next */ LRUCache.prototype.inspect = function (n, opts) { var str = 'LRUCache {' var extras = false var as = this[ALLOW_STALE] if (as) { str += '\n allowStale: true' extras = true } var max = this[MAX] if (max && max !== Infinity) { if (extras) { str += ',' } str += '\n max: ' + util.inspect(max, opts) extras = true } var maxAge = this[MAX_AGE] if (maxAge) { if (extras) { str += ',' } str += '\n maxAge: ' + util.inspect(maxAge, opts) extras = true } var lc = this[LENGTH_CALCULATOR] if (lc && lc !== naiveLength) { if (extras) { str += ',' } str += '\n length: ' + util.inspect(this[LENGTH], opts) extras = true } var didFirst = false this[LRU_LIST].forEach(function (item) { if (didFirst) { str += ',\n ' } else { if (extras) { str += ',\n' } didFirst = true str += '\n ' } var key = util.inspect(item.key).split('\n').join('\n ') var val = { value: item.value } if (item.maxAge !== maxAge) { val.maxAge = item.maxAge } if (lc !== naiveLength) { val.length = item.length } if (isStale(this, item)) { val.stale = true } val = util.inspect(val, opts).split('\n').join('\n ') str += key + ' => ' + val }) if (didFirst || extras) { str += '\n' } str += '}' return str } LRUCache.prototype.set = function (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] var now = maxAge ? Date.now() : 0 var len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } var node = this[CACHE].get(key) var 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 } var 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 } LRUCache.prototype.has = function (key) { if (!this[CACHE].has(key)) return false var hit = this[CACHE].get(key).value if (isStale(this, hit)) { return false } return true } LRUCache.prototype.get = function (key) { return get(this, key, true) } LRUCache.prototype.peek = function (key) { return get(this, key, false) } LRUCache.prototype.pop = function () { var node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } LRUCache.prototype.del = function (key) { del(this, this[CACHE].get(key)) } LRUCache.prototype.load = function (arr) { // reset the cache this.reset() var now = Date.now() // A previous serialized cache has the most recent items first for (var l = arr.length - 1; l >= 0; l--) { var hit = arr[l] var 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 { var maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } LRUCache.prototype.prune = function () { var self = this this[CACHE].forEach(function (value, key) { get(self, key, false) }) } function get (self, key, doUse) { var node = self[CACHE].get(key) if (node) { var hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } else { if (doUse) { self[LRU_LIST].unshiftNode(node) } } if (hit) hit = hit.value } return hit } function isStale (self, hit) { if (!hit || (!hit.maxAge && !self[MAX_AGE])) { return false } var stale = false var diff = Date.now() - hit.now if (hit.maxAge) { stale = diff > hit.maxAge } else { stale = self[MAX_AGE] && (diff > self[MAX_AGE]) } return stale } function trim (self) { if (self[LENGTH] > self[MAX]) { for (var 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. var prev = walker.prev del(self, walker) walker = prev } } } function del (self, node) { if (node) { var 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) } } // classy, since V8 prefers predictable objects. function Entry (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } /***/ }), /***/ 1434: /***/ ((module) => { 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 } 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.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 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 } } /***/ }), /***/ 4650: /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"name":"editorconfig","version":"0.15.3","description":"EditorConfig File Locator and Interpreter for Node.js","keywords":["editorconfig","core"],"main":"src/index.js","contributors":["Hong Xu (topbug.net)","Jed Mao (https://github.com/jedmao/)","Trey Hunner (http://treyhunner.com)"],"directories":{"bin":"./bin","lib":"./lib"},"scripts":{"clean":"rimraf dist","prebuild":"npm run clean","build":"tsc","pretest":"npm run lint && npm run build && npm run copy && cmake .","test":"ctest .","pretest:ci":"npm run pretest","test:ci":"ctest -VV --output-on-failure .","lint":"npm run eclint && npm run tslint","eclint":"eclint check --indent_size ignore \\"src/**\\"","tslint":"tslint --project tsconfig.json --exclude package.json","copy":"cpy .npmignore LICENSE README.md CHANGELOG.md dist && cpy bin/* dist/bin && cpy src/lib/fnmatch*.* dist/src/lib","prepub":"npm run lint && npm run build && npm run copy","pub":"npm publish ./dist"},"repository":{"type":"git","url":"git://github.com/editorconfig/editorconfig-core-js.git"},"bugs":"https://github.com/editorconfig/editorconfig-core-js/issues","author":"EditorConfig Team","license":"MIT","dependencies":{"commander":"^2.19.0","lru-cache":"^4.1.5","semver":"^5.6.0","sigmund":"^1.0.1"},"devDependencies":{"@types/mocha":"^5.2.6","@types/node":"^10.12.29","@types/semver":"^5.5.0","cpy-cli":"^2.0.0","eclint":"^2.8.1","mocha":"^5.2.0","rimraf":"^2.6.3","should":"^13.2.3","tslint":"^5.13.1","typescript":"^3.3.3333"}}'); /***/ }), /***/ 9138: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); var fs = __importStar(__webpack_require__(5747)); var path = __importStar(__webpack_require__(5622)); var semver = __importStar(__webpack_require__(2751)); var fnmatch_1 = __importDefault(__webpack_require__(8582)); var ini_1 = __webpack_require__(5345); exports.parseString = ini_1.parseString; var package_json_1 = __importDefault(__webpack_require__(4650)); var knownProps = { end_of_line: true, indent_style: true, indent_size: true, insert_final_newline: true, trim_trailing_whitespace: true, charset: true, }; function fnmatch(filepath, glob) { var matchOptions = { matchBase: true, dot: true, noext: true }; glob = glob.replace(/\*\*/g, '{*,**/**/**}'); return fnmatch_1.default(filepath, glob, matchOptions); } function getConfigFileNames(filepath, options) { var paths = []; do { filepath = path.dirname(filepath); paths.push(path.join(filepath, options.config)); } while (filepath !== options.root); return paths; } function processMatches(matches, version) { // Set indent_size to 'tab' if indent_size is unspecified and // indent_style is set to 'tab'. if ('indent_style' in matches && matches.indent_style === 'tab' && !('indent_size' in matches) && semver.gte(version, '0.10.0')) { matches.indent_size = 'tab'; } // Set tab_width to indent_size if indent_size is specified and // tab_width is unspecified if ('indent_size' in matches && !('tab_width' in matches) && matches.indent_size !== 'tab') { matches.tab_width = matches.indent_size; } // Set indent_size to tab_width if indent_size is 'tab' if ('indent_size' in matches && 'tab_width' in matches && matches.indent_size === 'tab') { matches.indent_size = matches.tab_width; } return matches; } function processOptions(options, filepath) { if (options === void 0) { options = {}; } return { config: options.config || '.editorconfig', version: options.version || package_json_1.default.version, root: path.resolve(options.root || path.parse(filepath).root), }; } function buildFullGlob(pathPrefix, glob) { switch (glob.indexOf('/')) { case -1: glob = '**/' + glob; break; case 0: glob = glob.substring(1); break; default: break; } return path.join(pathPrefix, glob); } function extendProps(props, options) { if (props === void 0) { props = {}; } if (options === void 0) { options = {}; } for (var key in options) { if (options.hasOwnProperty(key)) { var value = options[key]; var key2 = key.toLowerCase(); var value2 = value; if (knownProps[key2]) { value2 = value.toLowerCase(); } try { value2 = JSON.parse(value); } catch (e) { } if (typeof value === 'undefined' || value === null) { // null and undefined are values specific to JSON (no special meaning // in editorconfig) & should just be returned as regular strings. value2 = String(value); } props[key2] = value2; } } return props; } function parseFromConfigs(configs, filepath, options) { return processMatches(configs .reverse() .reduce(function (matches, file) { var pathPrefix = path.dirname(file.name); file.contents.forEach(function (section) { var glob = section[0]; var options2 = section[1]; if (!glob) { return; } var fullGlob = buildFullGlob(pathPrefix, glob); if (!fnmatch(filepath, fullGlob)) { return; } matches = extendProps(matches, options2); }); return matches; }, {}), options.version); } function getConfigsForFiles(files) { var configs = []; for (var i in files) { if (files.hasOwnProperty(i)) { var file = files[i]; var contents = ini_1.parseString(file.contents); configs.push({ name: file.name, contents: contents, }); if ((contents[0][1].root || '').toLowerCase() === 'true') { break; } } } return configs; } function readConfigFiles(filepaths) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, Promise.all(filepaths.map(function (name) { return new Promise(function (resolve) { fs.readFile(name, 'utf8', function (err, data) { resolve({ name: name, contents: err ? '' : data, }); }); }); }))]; }); }); } function readConfigFilesSync(filepaths) { var files = []; var file; filepaths.forEach(function (filepath) { try { file = fs.readFileSync(filepath, 'utf8'); } catch (e) { file = ''; } files.push({ name: filepath, contents: file, }); }); return files; } function opts(filepath, options) { if (options === void 0) { options = {}; } var resolvedFilePath = path.resolve(filepath); return [ resolvedFilePath, processOptions(options, resolvedFilePath), ]; } function parseFromFiles(filepath, files, options) { if (options === void 0) { options = {}; } return __awaiter(this, void 0, void 0, function () { var _a, resolvedFilePath, processedOptions; return __generator(this, function (_b) { _a = opts(filepath, options), resolvedFilePath = _a[0], processedOptions = _a[1]; return [2 /*return*/, files.then(getConfigsForFiles) .then(function (configs) { return parseFromConfigs(configs, resolvedFilePath, processedOptions); })]; }); }); } exports.parseFromFiles = parseFromFiles; function parseFromFilesSync(filepath, files, options) { if (options === void 0) { options = {}; } var _a = opts(filepath, options), resolvedFilePath = _a[0], processedOptions = _a[1]; return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions); } exports.parseFromFilesSync = parseFromFilesSync; function parse(_filepath, _options) { if (_options === void 0) { _options = {}; } return __awaiter(this, void 0, void 0, function () { var _a, resolvedFilePath, processedOptions, filepaths; return __generator(this, function (_b) { _a = opts(_filepath, _options), resolvedFilePath = _a[0], processedOptions = _a[1]; filepaths = getConfigFileNames(resolvedFilePath, processedOptions); return [2 /*return*/, readConfigFiles(filepaths) .then(getConfigsForFiles) .then(function (configs) { return parseFromConfigs(configs, resolvedFilePath, processedOptions); })]; }); }); } exports.parse = parse; function parseSync(_filepath, _options) { if (_options === void 0) { _options = {}; } var _a = opts(_filepath, _options), resolvedFilePath = _a[0], processedOptions = _a[1]; var filepaths = getConfigFileNames(resolvedFilePath, processedOptions); var files = readConfigFilesSync(filepaths); return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions); } exports.parseSync = parseSync; /***/ }), /***/ 8582: /***/ ((module, exports, __webpack_require__) => { /* module decorator */ module = __webpack_require__.nmd(module); // Based on minimatch.js by isaacs var platform = typeof process === "object" ? process.platform : "win32" if (module) module.exports = minimatch else exports.minimatch = minimatch minimatch.Minimatch = Minimatch var LRU = __webpack_require__(102) , cache = minimatch.cache = new LRU({max: 100}) , GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} , sigmund = __webpack_require__(2462) var path = __webpack_require__(5622) // any single thing other than / // don't need to escape / when using new RegExp() , qmark = "[^/]" // * => any number of characters , 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. , twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" // not a ^ or / followed by a dot, // followed by anything, any number of times. , twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" // characters that need to be escaped in RegExp. , 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.monkeyPatch = monkeyPatch function monkeyPatch () { var desc = Object.getOwnPropertyDescriptor(String.prototype, "match") var orig = desc.value desc.value = function (p) { if (p instanceof Minimatch) return p.match(this) return orig.call(this, p) } Object.defineProperty(String.prototype, desc) } 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, cache) } if (typeof pattern !== "string") { throw new TypeError("glob pattern string required") } if (!options) options = {} // windows: need to use /, not \ // On other platforms, \ is a valid (albeit bad) filename char. if (platform === "win32") { pattern = pattern.split("\\").join("/") } // lru storage. // these things aren't particularly big, but walking down the string // and turning it into a regexp can get pretty costly. var cacheKey = pattern + "\n" + sigmund(options) var cached = minimatch.cache.get(cacheKey) if (cached) return cached minimatch.cache.set(cacheKey, this) 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.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) console.error(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) }) if (options.debug) console.error(this.pattern, set) // glob --> regexps set = set.map(function (s, si, set) { return s.map(this.parse, this) }, this) if (options.debug) console.error(this.pattern, set) // filter out everything that didn't compile properly. set = set.filter(function (s) { return -1 === s.indexOf(false) }) if (options.debug) console.error(this.pattern, set) this.set = set } Minimatch.prototype.parseNegate = parseNegate function parseNegate () { var pattern = this.pattern , negate = false , options = this.options , 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 new Minimatch(pattern, options).braceExpand() } Minimatch.prototype.braceExpand = braceExpand function braceExpand (pattern, options) { options = options || this.options pattern = typeof pattern === "undefined" ? this.pattern : pattern if (typeof pattern === "undefined") { throw new Error("undefined pattern") } if (options.nobrace || !pattern.match(/\{.*\}/)) { // shortcut. no need to expand. return [pattern] } var escaping = false // examples and comments refer to this crazy pattern: // a{b,c{d,e},{f,g}h}x{y,z} // expected: // abxy // abxz // acdxy // acdxz // acexy // acexz // afhxy // afhxz // aghxy // aghxz // everything before the first \{ is just a prefix. // So, we pluck that off, and work with the rest, // and then prepend it to everything we find. if (pattern.charAt(0) !== "{") { // console.error(pattern) var prefix = null for (var i = 0, l = pattern.length; i < l; i ++) { var c = pattern.charAt(i) // console.error(i, c) if (c === "\\") { escaping = !escaping } else if (c === "{" && !escaping) { prefix = pattern.substr(0, i) break } } // actually no sets, all { were escaped. if (prefix === null) { // console.error("no sets") return [pattern] } var tail = braceExpand(pattern.substr(i), options) return tail.map(function (t) { return prefix + t }) } // now we have something like: // {b,c{d,e},{f,g}h}x{y,z} // walk through the set, expanding each part, until // the set ends. then, we'll expand the suffix. // If the set only has a single member, then'll put the {} back // first, handle numeric sets, since they're easier var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/) if (numset) { // console.error("numset", numset[1], numset[2]) var suf = braceExpand(pattern.substr(numset[0].length), options) , start = +numset[1] , end = +numset[2] , inc = start > end ? -1 : 1 , set = [] for (var i = start; i != (end + inc); i += inc) { // append all the suffixes for (var ii = 0, ll = suf.length; ii < ll; ii ++) { set.push(i + suf[ii]) } } return set } // ok, walk through the set // We hope, somewhat optimistically, that there // will be a } at the end. // If the closing brace isn't found, then the pattern is // interpreted as braceExpand("\\" + pattern) so that // the leading \{ will be interpreted literally. var i = 1 // skip the \{ , depth = 1 , set = [] , member = "" , sawEnd = false , escaping = false function addMember () { set.push(member) member = "" } // console.error("Entering for") FOR: for (i = 1, l = pattern.length; i < l; i ++) { var c = pattern.charAt(i) // console.error("", i, c) if (escaping) { escaping = false member += "\\" + c } else { switch (c) { case "\\": escaping = true continue case "{": depth ++ member += "{" continue case "}": depth -- // if this closes the actual set, then we're done if (depth === 0) { addMember() // pluck off the close-brace i ++ break FOR } else { member += c continue } case ",": if (depth === 1) { addMember() } else { member += c } continue default: member += c continue } // switch } // else } // for // now we've either finished the set, and the suffix is // pattern.substr(i), or we have *not* closed the set, // and need to escape the leading brace if (depth !== 0) { // console.error("didn't close", pattern) return braceExpand("\\" + pattern, options) } // x{y,z} -> ["xy", "xz"] // console.error("set", set) // console.error("suffix", pattern.substr(i)) var suf = braceExpand(pattern.substr(i), options) // ["b", "c{d,e}","{f,g}h"] -> // [["b"], ["cd", "ce"], ["fh", "gh"]] var addBraces = set.length === 1 // console.error("set pre-expanded", set) set = set.map(function (p) { return braceExpand(p, options) }) // console.error("set expanded", set) // [["b"], ["cd", "ce"], ["fh", "gh"]] -> // ["b", "cd", "ce", "fh", "gh"] set = set.reduce(function (l, r) { return l.concat(r) }) if (addBraces) { set = set.map(function (s) { return "{" + s + "}" }) } // now attach the suffixes. var ret = [] for (var i = 0, l = set.length; i < l; i ++) { for (var ii = 0, ll = suf.length; ii < ll; ii ++) { ret.push(set[i] + suf[ii]) } } return ret } // 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) { var options = this.options // shortcuts if (!options.noglobstar && pattern === "**") return GLOBSTAR if (pattern === "") return "" var re = "" , hasMagic = !!options.nocase , escaping = false // ? => one single character , patternListStack = [] , plType , stateChar , inClass = false , reClassStart = -1 , classStart = -1 // . and .. never match anything that doesn't start with ., // even when options.dot is set. , patternStart = pattern.charAt(0) === "." ? "" // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)" 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 } stateChar = false } } for ( var i = 0, len = pattern.length, c ; (i < len) && (c = pattern.charAt(i)) ; i ++ ) { if (options.debug) { console.error("%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: 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 "!": if (options.debug) { console.error("%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) { 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. 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 } plType = stateChar patternListStack.push({ type: plType , start: i - 1 , reStart: re.length }) // negation is (?:(?!js)[^/]*) re += stateChar === "!" ? "(?:(?!" : "(?:" stateChar = false continue case ")": if (inClass || !patternListStack.length) { re += "\\)" continue } hasMagic = true re += ")" plType = patternListStack.pop().type // negation is (?:(?!js)[^/]*) // The others are (?:) switch (plType) { case "!": re += "[^/]*?)" break case "?": case "+": case "*": re += plType case "@": break // the default anyway } continue case "|": if (inClass || !patternListStack.length || escaping) { re += "\\|" escaping = false continue } 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 } // 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 var 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. var pl while (pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + 3) // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2})*)(\\?)\|/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 + "|" }) // console.error("tail=%j\n %s", tail, tail) 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 } // 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" : "" , regExp = new RegExp("^" + re + "$", flags) 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) return this.regexp = false var options = this.options var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot , 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 { return this.regexp = new RegExp(re, flags) } catch (ex) { return this.regexp = false } } minimatch.match = function (list, pattern, options) { var mm = new Minimatch(pattern, options) list = list.filter(function (f) { return mm.match(f) }) if (options.nonull && !list.length) { list.push(pattern) } return list } Minimatch.prototype.match = match function match (f, partial) { // console.error("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 \ // On other platforms, \ is a valid (albeit bad) filename char. if (platform === "win32") { f = f.split("\\").join("/") } // treat the test path as a set of pathparts. f = f.split(slashSplit) if (options.debug) { console.error(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 // console.error(this.pattern, "set", set) for (var i = 0, l = set.length; i < l; i ++) { var pattern = set[i] var hit = this.matchOne(f, 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 if (options.debug) { console.error("matchOne", { "this": this , file: file , pattern: pattern }) } if (options.matchBase && pattern.length === 1) { file = path.basename(file.join("/")).split("/") } if (options.debug) { console.error("matchOne", file.length, pattern.length) } for ( var fi = 0 , pi = 0 , fl = file.length , pl = pattern.length ; (fi < fl) && (pi < pl) ; fi ++, pi ++ ) { if (options.debug) { console.error("matchOne loop") } var p = pattern[pi] , f = file[fi] if (options.debug) { console.error(pattern, p, f) } // should be impossible. // some invalid regexp stuff in the set. if (p === false) return false if (p === GLOBSTAR) { if (options.debug) console.error('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 , pr = pi + 1 if (pr === pl) { if (options.debug) console.error('** 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: while (fr < fl) { var swallowee = file[fr] if (options.debug) { console.error('\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)) { if (options.debug) console.error('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) === ".")) { if (options.debug) console.error("dot detected!", file, fr, pattern, pr) break WHILE } // ** swallows a segment, and continue. if (options.debug) console.error('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 // console.error("\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 } if (options.debug) { console.error("string match", p, f, hit) } } else { hit = f.match(p) if (options.debug) { console.error("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, "\\$&") } /***/ }), /***/ 5345: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; // Based on iniparser by shockie var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); var fs = __importStar(__webpack_require__(5747)); /** * define the possible values: * section: [section] * param: key=value * comment: ;this is a comment */ var regex = { section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/, param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/, comment: /^\s*[#;].*$/, }; /** * Parses an .ini file * @param file The location of the .ini file */ function parse(file) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, new Promise(function (resolve, reject) { fs.readFile(file, 'utf8', function (err, data) { if (err) { reject(err); return; } resolve(parseString(data)); }); })]; }); }); } exports.parse = parse; function parseSync(file) { return parseString(fs.readFileSync(file, 'utf8')); } exports.parseSync = parseSync; function parseString(data) { var sectionBody = {}; var sectionName = null; var value = [[sectionName, sectionBody]]; var lines = data.split(/\r\n|\r|\n/); lines.forEach(function (line) { var match; if (regex.comment.test(line)) { return; } if (regex.param.test(line)) { match = line.match(regex.param); sectionBody[match[1]] = match[2]; } else if (regex.section.test(line)) { match = line.match(regex.section); sectionName = match[1]; sectionBody = {}; value.push([sectionName, sectionBody]); } }); return value; } exports.parseString = parseString; /***/ }), /***/ 3584: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var shimmer = __webpack_require__(1938); var wrap = shimmer.wrap; var unwrap = shimmer.unwrap; // Default to complaining loudly when things don't go according to plan. // dunderscores are boring var SYMBOL = 'wrap@before'; // Sets a property on an object, preserving its enumerability. // This function assumes that the property is already writable. function defineProperty(obj, name, value) { var enumerable = !!obj[name] && obj.propertyIsEnumerable(name); Object.defineProperty(obj, name, { configurable: true, enumerable: enumerable, writable: true, value: value }); } function _process(self, listeners) { var l = listeners.length; for (var p = 0; p < l; p++) { var listener = listeners[p]; // set up the listener so that onEmit can do whatever it needs var before = self[SYMBOL]; if (typeof before === 'function') { before(listener); } else if (Array.isArray(before)) { var length = before.length; for (var i = 0; i < length; i++) before[i](listener); } } } function _listeners(self, event) { var listeners; listeners = self._events && self._events[event]; if (!Array.isArray(listeners)) { if (listeners) { listeners = [listeners]; } else { listeners = []; } } return listeners; } function _findAndProcess(self, event, before) { var after = _listeners(self, event); var unprocessed = after.filter(function(fn) { return before.indexOf(fn) === -1; }); if (unprocessed.length > 0) _process(self, unprocessed); } function _wrap(unwrapped, visit) { if (!unwrapped) return; var wrapped = unwrapped; if (typeof unwrapped === 'function') { wrapped = visit(unwrapped); } else if (Array.isArray(unwrapped)) { wrapped = []; for (var i = 0; i < unwrapped.length; i++) { wrapped[i] = visit(unwrapped[i]); } } return wrapped; } module.exports = function wrapEmitter(emitter, onAddListener, onEmit) { if (!emitter || !emitter.on || !emitter.addListener || !emitter.removeListener || !emitter.emit) { throw new Error("can only wrap real EEs"); } if (!onAddListener) throw new Error("must have function to run on listener addition"); if (!onEmit) throw new Error("must have function to wrap listeners when emitting"); /* Attach a context to a listener, and make sure that this hook stays * attached to the emitter forevermore. */ function adding(on) { return function added(event, listener) { var existing = _listeners(this, event).slice(); try { var returned = on.call(this, event, listener); _findAndProcess(this, event, existing); return returned; } finally { // old-style streaming overwrites .on and .addListener, so rewrap if (!this.on.__wrapped) wrap(this, 'on', adding); if (!this.addListener.__wrapped) wrap(this, 'addListener', adding); } }; } function emitting(emit) { return function emitted(event) { if (!this._events || !this._events[event]) return emit.apply(this, arguments); var unwrapped = this._events[event]; /* Ensure that if removeListener gets called, it's working with the * unwrapped listeners. */ function remover(removeListener) { return function removed() { this._events[event] = unwrapped; try { return removeListener.apply(this, arguments); } finally { unwrapped = this._events[event]; this._events[event] = _wrap(unwrapped, onEmit); } }; } wrap(this, 'removeListener', remover); try { /* At emit time, ensure that whatever else is going on, removeListener will * still work while at the same time running whatever hooks are necessary to * make sure the listener is run in the correct context. */ this._events[event] = _wrap(unwrapped, onEmit); return emit.apply(this, arguments); } finally { /* Ensure that regardless of what happens when preparing and running the * listeners, the status quo ante is restored before continuing. */ unwrap(this, 'removeListener'); this._events[event] = unwrapped; } }; } // support multiple onAddListeners if (!emitter[SYMBOL]) { defineProperty(emitter, SYMBOL, onAddListener); } else if (typeof emitter[SYMBOL] === 'function') { defineProperty(emitter, SYMBOL, [emitter[SYMBOL], onAddListener]); } else if (Array.isArray(emitter[SYMBOL])) { emitter[SYMBOL].push(onAddListener); } // only wrap the core functions once if (!emitter.__wrapped) { wrap(emitter, 'addListener', adding); wrap(emitter, 'on', adding); wrap(emitter, 'emit', emitting); defineProperty(emitter, '__unwrap', function () { unwrap(emitter, 'addListener'); unwrap(emitter, 'on'); unwrap(emitter, 'emit'); delete emitter[SYMBOL]; delete emitter.__wrapped; }); defineProperty(emitter, '__wrapped', true); } }; /***/ }), /***/ 8531: /***/ (function(module) { /*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version v4.2.8+1e68dce6 */ (function (global, factory) { true ? module.exports = factory() : 0; }(this, (function () { 'use strict'; function objectOrFunction(x) { var type = typeof x; return x !== null && (type === 'object' || type === 'function'); } function isFunction(x) { return typeof x === 'function'; } var _isArray = void 0; if (Array.isArray) { _isArray = Array.isArray; } else { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } var isArray = _isArray; var len = 0; var vertxNext = void 0; var customSchedulerFn = void 0; var asap = function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { // If len is 2, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if (customSchedulerFn) { customSchedulerFn(flush); } else { scheduleFlush(); } } }; function setScheduler(scheduleFn) { customSchedulerFn = scheduleFn; } function setAsap(asapFn) { asap = asapFn; } var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; // test for web worker but not in IE10 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { // node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function () { return process.nextTick(flush); }; } // vertx function useVertxTimer() { if (typeof vertxNext !== 'undefined') { return function () { vertxNext(flush); }; } return useSetTimeout(); } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function () { node.data = iterations = ++iterations % 2; }; } // web worker function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function () { return channel.port2.postMessage(0); }; } function useSetTimeout() { // Store setTimeout reference so es6-promise will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var globalSetTimeout = setTimeout; return function () { return globalSetTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } function attemptVertx() { try { var vertx = Function('return this')().require('vertx'); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush = void 0; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else if (browserWindow === undefined && "function" === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); } function then(onFulfillment, onRejection) { var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { var callback = arguments[_state - 1]; asap(function () { return invokeCallback(_state, child, callback, parent._result); }); } else { subscribe(parent, child, onFulfillment, onRejection); } return child; } /** `Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {Any} value value that the returned promise will be resolved with Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve$1(object) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(noop); resolve(promise, object); return promise; } var PROMISE_ID = Math.random().toString(36).substring(2); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; function selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); } function cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.'); } function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { try { then$$1.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then$$1) { asap(function (promise) { var sealed = false; var error = tryThen(then$$1, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; reject(promise, error); } }, promise); } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result); } else if (thenable._state === REJECTED) { reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { return resolve(promise, value); }, function (reason) { return reject(promise, reason); }); } } function handleMaybeThenable(promise, maybeThenable, then$$1) { if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { handleOwnThenable(promise, maybeThenable); } else { if (then$$1 === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$1)) { handleForeignThenable(promise, maybeThenable, then$$1); } else { fulfill(promise, maybeThenable); } } } function resolve(promise, value) { if (promise === value) { reject(promise, selfFulfillment()); } else if (objectOrFunction(value)) { var then$$1 = void 0; try { then$$1 = value.then; } catch (error) { reject(promise, error); return; } handleMaybeThenable(promise, value, then$$1); } else { fulfill(promise, value); } } function publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length !== 0) { asap(publish, promise); } } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; asap(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; parent._onerror = null; _subscribers[length] = child; _subscribers[length + FULFILLED] = onFulfillment; _subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { asap(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child = void 0, callback = void 0, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value = void 0, error = void 0, succeeded = true; if (hasCallback) { try { value = callback(detail); } catch (e) { succeeded = false; error = e; } if (promise === value) { reject(promise, cannotReturnOwn()); return; } } else { value = detail; } if (promise._state !== PENDING) { // noop } else if (hasCallback && succeeded) { resolve(promise, value); } else if (succeeded === false) { reject(promise, error); } else if (settled === FULFILLED) { fulfill(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } function initializePromise(promise, resolver) { try { resolver(function resolvePromise(value) { resolve(promise, value); }, function rejectPromise(reason) { reject(promise, reason); }); } catch (e) { reject(promise, e); } } var id = 0; function nextId() { return id++; } function makePromise(promise) { promise[PROMISE_ID] = id++; promise._state = undefined; promise._result = undefined; promise._subscribers = []; } function validationError() { return new Error('Array Methods must be provided an Array'); } var Enumerator = function () { function Enumerator(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise); } if (isArray(input)) { this.length = input.length; this._remaining = input.length; this._result = new Array(this.length); if (this.length === 0) { fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(input); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { reject(this.promise, validationError()); } } Enumerator.prototype._enumerate = function _enumerate(input) { for (var i = 0; this._state === PENDING && i < input.length; i++) { this._eachEntry(input[i], i); } }; Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { var c = this._instanceConstructor; var resolve$$1 = c.resolve; if (resolve$$1 === resolve$1) { var _then = void 0; var error = void 0; var didError = false; try { _then = entry.then; } catch (e) { didError = true; error = e; } if (_then === then && entry._state !== PENDING) { this._settledAt(entry._state, i, entry._result); } else if (typeof _then !== 'function') { this._remaining--; this._result[i] = entry; } else if (c === Promise$1) { var promise = new c(noop); if (didError) { reject(promise, error); } else { handleMaybeThenable(promise, entry, _then); } this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$1) { return resolve$$1(entry); }), i); } } else { this._willSettleAt(resolve$$1(entry), i); } }; Enumerator.prototype._settledAt = function _settledAt(state, i, value) { var promise = this.promise; if (promise._state === PENDING) { this._remaining--; if (state === REJECTED) { reject(promise, value); } else { this._result[i] = value; } } if (this._remaining === 0) { fulfill(promise, this._result); } }; Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; return Enumerator; }(); /** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript let promise1 = resolve(1); let promise2 = resolve(2); let promise3 = resolve(3); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript let promise1 = resolve(1); let promise2 = reject(new Error("2")); let promise3 = reject(new Error("3")); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all(entries) { return new Enumerator(this, entries).promise; } /** `Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} promises array of promises to observe Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ function race(entries) { /*jshint validthis:true */ var Constructor = this; if (!isArray(entries)) { return new Constructor(function (_, reject) { return reject(new TypeError('You must pass an array to race.')); }); } else { return new Constructor(function (resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject); } }); } } /** `Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {Any} reason value that the returned promise will be rejected with. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject$1(reason) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(noop); reject(promise, reason); return promise; } function needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js let promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {Function} resolver Useful for tooling. @constructor */ var Promise$1 = function () { function Promise(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise ? initializePromise(this, resolver) : needsNew(); } } /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript let result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript let author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ Promise.prototype.catch = function _catch(onRejection) { return this.then(null, onRejection); }; /** `finally` will be invoked regardless of the promise's fate just as native try/catch/finally behaves Synchronous example: ```js findAuthor() { if (Math.random() > 0.5) { throw new Error(); } return new Author(); } try { return findAuthor(); // succeed or fail } catch(error) { return findOtherAuther(); } finally { // always runs // doesn't affect the return value } ``` Asynchronous example: ```js findAuthor().catch(function(reason){ return findOtherAuther(); }).finally(function(){ // author was either found, or not }); ``` @method finally @param {Function} callback @return {Promise} */ Promise.prototype.finally = function _finally(callback) { var promise = this; var constructor = promise.constructor; if (isFunction(callback)) { return promise.then(function (value) { return constructor.resolve(callback()).then(function () { return value; }); }, function (reason) { return constructor.resolve(callback()).then(function () { throw reason; }); }); } return promise.then(callback, callback); }; return Promise; }(); Promise$1.prototype.then = then; Promise$1.all = all; Promise$1.race = race; Promise$1.resolve = resolve$1; Promise$1.reject = reject$1; Promise$1._setScheduler = setScheduler; Promise$1._setAsap = setAsap; Promise$1._asap = asap; /*global self*/ function polyfill() { var local = void 0; if (typeof global !== 'undefined') { local = global; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } var P = local.Promise; if (P) { var promiseToString = null; try { promiseToString = Object.prototype.toString.call(P.resolve()); } catch (e) { // silently ignored } if (promiseToString === '[object Promise]' && !P.cast) { return; } } local.Promise = Promise$1; } // Strange compat.. Promise$1.polyfill = polyfill; Promise$1.Promise = Promise$1; return Promise$1; }))); //# sourceMappingURL=es6-promise.map /***/ }), /***/ 1295: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* global self, window, module, global, require */ module.exports = function () { "use strict"; var globalObject = void 0; function isFunction(x) { return typeof x === "function"; } // Seek the global object if (global !== undefined) { globalObject = global; } else if (window !== undefined && window.document) { globalObject = window; } else { globalObject = self; } // Test for any native promise implementation, and if that // implementation appears to conform to the specificaton. // This code mostly nicked from the es6-promise module polyfill // and then fooled with. var hasPromiseSupport = function () { // No promise object at all, and it's a non-starter if (!globalObject.hasOwnProperty("Promise")) { return false; } // There is a Promise object. Does it conform to the spec? var P = globalObject.Promise; // Some of these methods are missing from // Firefox/Chrome experimental implementations if (!P.hasOwnProperty("resolve") || !P.hasOwnProperty("reject")) { return false; } if (!P.hasOwnProperty("all") || !P.hasOwnProperty("race")) { return false; } // Older version of the spec had a resolver object // as the arg rather than a function return function () { var resolve = void 0; var p = new globalObject.Promise(function (r) { resolve = r; }); if (p) { return isFunction(resolve); } return false; }(); }(); // Export the native Promise implementation if it // looks like it matches the spec if (hasPromiseSupport) { return globalObject.Promise; } // Otherwise, return the es6-promise polyfill by @jaffathecake. return __webpack_require__(8531).Promise; }(); /***/ }), /***/ 930: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* global module, require */ module.exports = function () { "use strict"; // Get a promise object. This may be native, or it may be polyfilled var ES6Promise = __webpack_require__(1295); /** * thatLooksLikeAPromiseToMe() * * Duck-types a promise. * * @param {object} o * @return {bool} True if this resembles a promise */ function thatLooksLikeAPromiseToMe(o) { return o && typeof o.then === "function" && typeof o.catch === "function"; } /** * promisify() * * Transforms callback-based function -- func(arg1, arg2 .. argN, callback) -- into * an ES6-compatible Promise. Promisify provides a default callback of the form (error, result) * and rejects when `error` is truthy. You can also supply settings object as the second argument. * * @param {function} original - The function to promisify * @param {object} settings - Settings object * @param {object} settings.thisArg - A `this` context to use. If not set, assume `settings` _is_ `thisArg` * @param {bool} settings.multiArgs - Should multiple arguments be returned as an array? * @return {function} A promisified version of `original` */ return function promisify(original, settings) { return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var returnMultipleArguments = settings && settings.multiArgs; var target = void 0; if (settings && settings.thisArg) { target = settings.thisArg; } else if (settings) { target = settings; } // Return the promisified function return new ES6Promise(function (resolve, reject) { // Append the callback bound to the context args.push(function callback(err) { if (err) { return reject(err); } for (var _len2 = arguments.length, values = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { values[_key2 - 1] = arguments[_key2]; } if (false === !!returnMultipleArguments) { return resolve(values[0]); } resolve(values); }); // Call the function var response = original.apply(target, args); // If it looks like original already returns a promise, // then just resolve with that promise. Hopefully, the callback function we added will just be ignored. if (thatLooksLikeAPromiseToMe(response)) { resolve(response); } }); }; }; }(); /***/ }), /***/ 4419: /***/ ((module) => { "use strict"; const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g; module.exports = string => { if (typeof string !== 'string') { throw new TypeError('Expected a string'); } return string.replace(matchOperatorsRegex, '\\$&'); }; /***/ }), /***/ 2058: /***/ (function(module) { (function webpackUniversalModuleDefinition(root, factory) { /* istanbul ignore next */ if(true) module.exports = factory(); else {} })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __nested_webpack_require_583__(moduleId) { /******/ // Check if module is in cache /* istanbul ignore if */ /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_583__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __nested_webpack_require_583__.m = modules; /******/ // expose the module cache /******/ __nested_webpack_require_583__.c = installedModules; /******/ // __webpack_public_path__ /******/ __nested_webpack_require_583__.p = ""; /******/ // Load entry module and return exports /******/ return __nested_webpack_require_583__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __nested_webpack_require_1808__) { "use strict"; /* Copyright JS Foundation and other contributors, https://js.foundation/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ Object.defineProperty(exports, "__esModule", { value: true }); var comment_handler_1 = __nested_webpack_require_1808__(1); var jsx_parser_1 = __nested_webpack_require_1808__(3); var parser_1 = __nested_webpack_require_1808__(8); var tokenizer_1 = __nested_webpack_require_1808__(15); function parse(code, options, delegate) { var commentHandler = null; var proxyDelegate = function (node, metadata) { if (delegate) { delegate(node, metadata); } if (commentHandler) { commentHandler.visit(node, metadata); } }; var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null; var collectComment = false; if (options) { collectComment = (typeof options.comment === 'boolean' && options.comment); var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment); if (collectComment || attachComment) { commentHandler = new comment_handler_1.CommentHandler(); commentHandler.attach = attachComment; options.comment = true; parserDelegate = proxyDelegate; } } var isModule = false; if (options && typeof options.sourceType === 'string') { isModule = (options.sourceType === 'module'); } var parser; if (options && typeof options.jsx === 'boolean' && options.jsx) { parser = new jsx_parser_1.JSXParser(code, options, parserDelegate); } else { parser = new parser_1.Parser(code, options, parserDelegate); } var program = isModule ? parser.parseModule() : parser.parseScript(); var ast = program; if (collectComment && commentHandler) { ast.comments = commentHandler.comments; } if (parser.config.tokens) { ast.tokens = parser.tokens; } if (parser.config.tolerant) { ast.errors = parser.errorHandler.errors; } return ast; } exports.parse = parse; function parseModule(code, options, delegate) { var parsingOptions = options || {}; parsingOptions.sourceType = 'module'; return parse(code, parsingOptions, delegate); } exports.parseModule = parseModule; function parseScript(code, options, delegate) { var parsingOptions = options || {}; parsingOptions.sourceType = 'script'; return parse(code, parsingOptions, delegate); } exports.parseScript = parseScript; function tokenize(code, options, delegate) { var tokenizer = new tokenizer_1.Tokenizer(code, options); var tokens; tokens = []; try { while (true) { var token = tokenizer.getNextToken(); if (!token) { break; } if (delegate) { token = delegate(token); } tokens.push(token); } } catch (e) { tokenizer.errorHandler.tolerate(e); } if (tokenizer.errorHandler.tolerant) { tokens.errors = tokenizer.errors(); } return tokens; } exports.tokenize = tokenize; var syntax_1 = __nested_webpack_require_1808__(2); exports.Syntax = syntax_1.Syntax; // Sync with *.json manifests. exports.version = '4.0.1'; /***/ }, /* 1 */ /***/ function(module, exports, __nested_webpack_require_6456__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var syntax_1 = __nested_webpack_require_6456__(2); var CommentHandler = (function () { function CommentHandler() { this.attach = false; this.comments = []; this.stack = []; this.leading = []; this.trailing = []; } CommentHandler.prototype.insertInnerComments = function (node, metadata) { // innnerComments for properties empty block // `function a() {/** comments **\/}` if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) { var innerComments = []; for (var i = this.leading.length - 1; i >= 0; --i) { var entry = this.leading[i]; if (metadata.end.offset >= entry.start) { innerComments.unshift(entry.comment); this.leading.splice(i, 1); this.trailing.splice(i, 1); } } if (innerComments.length) { node.innerComments = innerComments; } } }; CommentHandler.prototype.findTrailingComments = function (metadata) { var trailingComments = []; if (this.trailing.length > 0) { for (var i = this.trailing.length - 1; i >= 0; --i) { var entry_1 = this.trailing[i]; if (entry_1.start >= metadata.end.offset) { trailingComments.unshift(entry_1.comment); } } this.trailing.length = 0; return trailingComments; } var entry = this.stack[this.stack.length - 1]; if (entry && entry.node.trailingComments) { var firstComment = entry.node.trailingComments[0]; if (firstComment && firstComment.range[0] >= metadata.end.offset) { trailingComments = entry.node.trailingComments; delete entry.node.trailingComments; } } return trailingComments; }; CommentHandler.prototype.findLeadingComments = function (metadata) { var leadingComments = []; var target; while (this.stack.length > 0) { var entry = this.stack[this.stack.length - 1]; if (entry && entry.start >= metadata.start.offset) { target = entry.node; this.stack.pop(); } else { break; } } if (target) { var count = target.leadingComments ? target.leadingComments.length : 0; for (var i = count - 1; i >= 0; --i) { var comment = target.leadingComments[i]; if (comment.range[1] <= metadata.start.offset) { leadingComments.unshift(comment); target.leadingComments.splice(i, 1); } } if (target.leadingComments && target.leadingComments.length === 0) { delete target.leadingComments; } return leadingComments; } for (var i = this.leading.length - 1; i >= 0; --i) { var entry = this.leading[i]; if (entry.start <= metadata.start.offset) { leadingComments.unshift(entry.comment); this.leading.splice(i, 1); } } return leadingComments; }; CommentHandler.prototype.visitNode = function (node, metadata) { if (node.type === syntax_1.Syntax.Program && node.body.length > 0) { return; } this.insertInnerComments(node, metadata); var trailingComments = this.findTrailingComments(metadata); var leadingComments = this.findLeadingComments(metadata); if (leadingComments.length > 0) { node.leadingComments = leadingComments; } if (trailingComments.length > 0) { node.trailingComments = trailingComments; } this.stack.push({ node: node, start: metadata.start.offset }); }; CommentHandler.prototype.visitComment = function (node, metadata) { var type = (node.type[0] === 'L') ? 'Line' : 'Block'; var comment = { type: type, value: node.value }; if (node.range) { comment.range = node.range; } if (node.loc) { comment.loc = node.loc; } this.comments.push(comment); if (this.attach) { var entry = { comment: { type: type, value: node.value, range: [metadata.start.offset, metadata.end.offset] }, start: metadata.start.offset }; if (node.loc) { entry.comment.loc = node.loc; } node.type = type; this.leading.push(entry); this.trailing.push(entry); } }; CommentHandler.prototype.visit = function (node, metadata) { if (node.type === 'LineComment') { this.visitComment(node, metadata); } else if (node.type === 'BlockComment') { this.visitComment(node, metadata); } else if (this.attach) { this.visitNode(node, metadata); } }; return CommentHandler; }()); exports.CommentHandler = CommentHandler; /***/ }, /* 2 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Syntax = { AssignmentExpression: 'AssignmentExpression', AssignmentPattern: 'AssignmentPattern', ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrowFunctionExpression: 'ArrowFunctionExpression', AwaitExpression: 'AwaitExpression', BlockStatement: 'BlockStatement', BinaryExpression: 'BinaryExpression', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DoWhileStatement: 'DoWhileStatement', DebuggerStatement: 'DebuggerStatement', EmptyStatement: 'EmptyStatement', ExportAllDeclaration: 'ExportAllDeclaration', ExportDefaultDeclaration: 'ExportDefaultDeclaration', ExportNamedDeclaration: 'ExportNamedDeclaration', ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', ForStatement: 'ForStatement', ForOfStatement: 'ForOfStatement', ForInStatement: 'ForInStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', Identifier: 'Identifier', IfStatement: 'IfStatement', ImportDeclaration: 'ImportDeclaration', ImportDefaultSpecifier: 'ImportDefaultSpecifier', ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', ImportSpecifier: 'ImportSpecifier', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MetaProperty: 'MetaProperty', MethodDefinition: 'MethodDefinition', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', Program: 'Program', Property: 'Property', RestElement: 'RestElement', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', Super: 'Super', SwitchCase: 'SwitchCase', SwitchStatement: 'SwitchStatement', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', UnaryExpression: 'UnaryExpression', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement', YieldExpression: 'YieldExpression' }; /***/ }, /* 3 */ /***/ function(module, exports, __nested_webpack_require_15019__) { "use strict"; /* istanbul ignore next */ var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var character_1 = __nested_webpack_require_15019__(4); var JSXNode = __nested_webpack_require_15019__(5); var jsx_syntax_1 = __nested_webpack_require_15019__(6); var Node = __nested_webpack_require_15019__(7); var parser_1 = __nested_webpack_require_15019__(8); var token_1 = __nested_webpack_require_15019__(13); var xhtml_entities_1 = __nested_webpack_require_15019__(14); token_1.TokenName[100 /* Identifier */] = 'JSXIdentifier'; token_1.TokenName[101 /* Text */] = 'JSXText'; // Fully qualified element name, e.g. returns "svg:path" function getQualifiedElementName(elementName) { var qualifiedName; switch (elementName.type) { case jsx_syntax_1.JSXSyntax.JSXIdentifier: var id = elementName; qualifiedName = id.name; break; case jsx_syntax_1.JSXSyntax.JSXNamespacedName: var ns = elementName; qualifiedName = getQualifiedElementName(ns.namespace) + ':' + getQualifiedElementName(ns.name); break; case jsx_syntax_1.JSXSyntax.JSXMemberExpression: var expr = elementName; qualifiedName = getQualifiedElementName(expr.object) + '.' + getQualifiedElementName(expr.property); break; /* istanbul ignore next */ default: break; } return qualifiedName; } var JSXParser = (function (_super) { __extends(JSXParser, _super); function JSXParser(code, options, delegate) { return _super.call(this, code, options, delegate) || this; } JSXParser.prototype.parsePrimaryExpression = function () { return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this); }; JSXParser.prototype.startJSX = function () { // Unwind the scanner before the lookahead token. this.scanner.index = this.startMarker.index; this.scanner.lineNumber = this.startMarker.line; this.scanner.lineStart = this.startMarker.index - this.startMarker.column; }; JSXParser.prototype.finishJSX = function () { // Prime the next lookahead. this.nextToken(); }; JSXParser.prototype.reenterJSX = function () { this.startJSX(); this.expectJSX('}'); // Pop the closing '}' added from the lookahead. if (this.config.tokens) { this.tokens.pop(); } }; JSXParser.prototype.createJSXNode = function () { this.collectComments(); return { index: this.scanner.index, line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; }; JSXParser.prototype.createJSXChildNode = function () { return { index: this.scanner.index, line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; }; JSXParser.prototype.scanXHTMLEntity = function (quote) { var result = '&'; var valid = true; var terminated = false; var numeric = false; var hex = false; while (!this.scanner.eof() && valid && !terminated) { var ch = this.scanner.source[this.scanner.index]; if (ch === quote) { break; } terminated = (ch === ';'); result += ch; ++this.scanner.index; if (!terminated) { switch (result.length) { case 2: // e.g. '{' numeric = (ch === '#'); break; case 3: if (numeric) { // e.g. 'A' hex = (ch === 'x'); valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0)); numeric = numeric && !hex; } break; default: valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0))); valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0))); break; } } } if (valid && terminated && result.length > 2) { // e.g. 'A' becomes just '#x41' var str = result.substr(1, result.length - 2); if (numeric && str.length > 1) { result = String.fromCharCode(parseInt(str.substr(1), 10)); } else if (hex && str.length > 2) { result = String.fromCharCode(parseInt('0' + str.substr(1), 16)); } else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) { result = xhtml_entities_1.XHTMLEntities[str]; } } return result; }; // Scan the next JSX token. This replaces Scanner#lex when in JSX mode. JSXParser.prototype.lexJSX = function () { var cp = this.scanner.source.charCodeAt(this.scanner.index); // < > / : = { } if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) { var value = this.scanner.source[this.scanner.index++]; return { type: 7 /* Punctuator */, value: value, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: this.scanner.index - 1, end: this.scanner.index }; } // " ' if (cp === 34 || cp === 39) { var start = this.scanner.index; var quote = this.scanner.source[this.scanner.index++]; var str = ''; while (!this.scanner.eof()) { var ch = this.scanner.source[this.scanner.index++]; if (ch === quote) { break; } else if (ch === '&') { str += this.scanXHTMLEntity(quote); } else { str += ch; } } return { type: 8 /* StringLiteral */, value: str, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: start, end: this.scanner.index }; } // ... or . if (cp === 46) { var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1); var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2); var value = (n1 === 46 && n2 === 46) ? '...' : '.'; var start = this.scanner.index; this.scanner.index += value.length; return { type: 7 /* Punctuator */, value: value, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: start, end: this.scanner.index }; } // ` if (cp === 96) { // Only placeholder, since it will be rescanned as a real assignment expression. return { type: 10 /* Template */, value: '', lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: this.scanner.index, end: this.scanner.index }; } // Identifer can not contain backslash (char code 92). if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) { var start = this.scanner.index; ++this.scanner.index; while (!this.scanner.eof()) { var ch = this.scanner.source.charCodeAt(this.scanner.index); if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) { ++this.scanner.index; } else if (ch === 45) { // Hyphen (char code 45) can be part of an identifier. ++this.scanner.index; } else { break; } } var id = this.scanner.source.slice(start, this.scanner.index); return { type: 100 /* Identifier */, value: id, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: start, end: this.scanner.index }; } return this.scanner.lex(); }; JSXParser.prototype.nextJSXToken = function () { this.collectComments(); this.startMarker.index = this.scanner.index; this.startMarker.line = this.scanner.lineNumber; this.startMarker.column = this.scanner.index - this.scanner.lineStart; var token = this.lexJSX(); this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; if (this.config.tokens) { this.tokens.push(this.convertToken(token)); } return token; }; JSXParser.prototype.nextJSXText = function () { this.startMarker.index = this.scanner.index; this.startMarker.line = this.scanner.lineNumber; this.startMarker.column = this.scanner.index - this.scanner.lineStart; var start = this.scanner.index; var text = ''; while (!this.scanner.eof()) { var ch = this.scanner.source[this.scanner.index]; if (ch === '{' || ch === '<') { break; } ++this.scanner.index; text += ch; if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { ++this.scanner.lineNumber; if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') { ++this.scanner.index; } this.scanner.lineStart = this.scanner.index; } } this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; var token = { type: 101 /* Text */, value: text, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: start, end: this.scanner.index }; if ((text.length > 0) && this.config.tokens) { this.tokens.push(this.convertToken(token)); } return token; }; JSXParser.prototype.peekJSXToken = function () { var state = this.scanner.saveState(); this.scanner.scanComments(); var next = this.lexJSX(); this.scanner.restoreState(state); return next; }; // Expect the next JSX token to match the specified punctuator. // If not, an exception will be thrown. JSXParser.prototype.expectJSX = function (value) { var token = this.nextJSXToken(); if (token.type !== 7 /* Punctuator */ || token.value !== value) { this.throwUnexpectedToken(token); } }; // Return true if the next JSX token matches the specified punctuator. JSXParser.prototype.matchJSX = function (value) { var next = this.peekJSXToken(); return next.type === 7 /* Punctuator */ && next.value === value; }; JSXParser.prototype.parseJSXIdentifier = function () { var node = this.createJSXNode(); var token = this.nextJSXToken(); if (token.type !== 100 /* Identifier */) { this.throwUnexpectedToken(token); } return this.finalize(node, new JSXNode.JSXIdentifier(token.value)); }; JSXParser.prototype.parseJSXElementName = function () { var node = this.createJSXNode(); var elementName = this.parseJSXIdentifier(); if (this.matchJSX(':')) { var namespace = elementName; this.expectJSX(':'); var name_1 = this.parseJSXIdentifier(); elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1)); } else if (this.matchJSX('.')) { while (this.matchJSX('.')) { var object = elementName; this.expectJSX('.'); var property = this.parseJSXIdentifier(); elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property)); } } return elementName; }; JSXParser.prototype.parseJSXAttributeName = function () { var node = this.createJSXNode(); var attributeName; var identifier = this.parseJSXIdentifier(); if (this.matchJSX(':')) { var namespace = identifier; this.expectJSX(':'); var name_2 = this.parseJSXIdentifier(); attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2)); } else { attributeName = identifier; } return attributeName; }; JSXParser.prototype.parseJSXStringLiteralAttribute = function () { var node = this.createJSXNode(); var token = this.nextJSXToken(); if (token.type !== 8 /* StringLiteral */) { this.throwUnexpectedToken(token); } var raw = this.getTokenRaw(token); return this.finalize(node, new Node.Literal(token.value, raw)); }; JSXParser.prototype.parseJSXExpressionAttribute = function () { var node = this.createJSXNode(); this.expectJSX('{'); this.finishJSX(); if (this.match('}')) { this.tolerateError('JSX attributes must only be assigned a non-empty expression'); } var expression = this.parseAssignmentExpression(); this.reenterJSX(); return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); }; JSXParser.prototype.parseJSXAttributeValue = function () { return this.matchJSX('{') ? this.parseJSXExpressionAttribute() : this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute(); }; JSXParser.prototype.parseJSXNameValueAttribute = function () { var node = this.createJSXNode(); var name = this.parseJSXAttributeName(); var value = null; if (this.matchJSX('=')) { this.expectJSX('='); value = this.parseJSXAttributeValue(); } return this.finalize(node, new JSXNode.JSXAttribute(name, value)); }; JSXParser.prototype.parseJSXSpreadAttribute = function () { var node = this.createJSXNode(); this.expectJSX('{'); this.expectJSX('...'); this.finishJSX(); var argument = this.parseAssignmentExpression(); this.reenterJSX(); return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument)); }; JSXParser.prototype.parseJSXAttributes = function () { var attributes = []; while (!this.matchJSX('/') && !this.matchJSX('>')) { var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() : this.parseJSXNameValueAttribute(); attributes.push(attribute); } return attributes; }; JSXParser.prototype.parseJSXOpeningElement = function () { var node = this.createJSXNode(); this.expectJSX('<'); var name = this.parseJSXElementName(); var attributes = this.parseJSXAttributes(); var selfClosing = this.matchJSX('/'); if (selfClosing) { this.expectJSX('/'); } this.expectJSX('>'); return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); }; JSXParser.prototype.parseJSXBoundaryElement = function () { var node = this.createJSXNode(); this.expectJSX('<'); if (this.matchJSX('/')) { this.expectJSX('/'); var name_3 = this.parseJSXElementName(); this.expectJSX('>'); return this.finalize(node, new JSXNode.JSXClosingElement(name_3)); } var name = this.parseJSXElementName(); var attributes = this.parseJSXAttributes(); var selfClosing = this.matchJSX('/'); if (selfClosing) { this.expectJSX('/'); } this.expectJSX('>'); return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); }; JSXParser.prototype.parseJSXEmptyExpression = function () { var node = this.createJSXChildNode(); this.collectComments(); this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; return this.finalize(node, new JSXNode.JSXEmptyExpression()); }; JSXParser.prototype.parseJSXExpressionContainer = function () { var node = this.createJSXNode(); this.expectJSX('{'); var expression; if (this.matchJSX('}')) { expression = this.parseJSXEmptyExpression(); this.expectJSX('}'); } else { this.finishJSX(); expression = this.parseAssignmentExpression(); this.reenterJSX(); } return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); }; JSXParser.prototype.parseJSXChildren = function () { var children = []; while (!this.scanner.eof()) { var node = this.createJSXChildNode(); var token = this.nextJSXText(); if (token.start < token.end) { var raw = this.getTokenRaw(token); var child = this.finalize(node, new JSXNode.JSXText(token.value, raw)); children.push(child); } if (this.scanner.source[this.scanner.index] === '{') { var container = this.parseJSXExpressionContainer(); children.push(container); } else { break; } } return children; }; JSXParser.prototype.parseComplexJSXElement = function (el) { var stack = []; while (!this.scanner.eof()) { el.children = el.children.concat(this.parseJSXChildren()); var node = this.createJSXChildNode(); var element = this.parseJSXBoundaryElement(); if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) { var opening = element; if (opening.selfClosing) { var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null)); el.children.push(child); } else { stack.push(el); el = { node: node, opening: opening, closing: null, children: [] }; } } if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) { el.closing = element; var open_1 = getQualifiedElementName(el.opening.name); var close_1 = getQualifiedElementName(el.closing.name); if (open_1 !== close_1) { this.tolerateError('Expected corresponding JSX closing tag for %0', open_1); } if (stack.length > 0) { var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing)); el = stack[stack.length - 1]; el.children.push(child); stack.pop(); } else { break; } } } return el; }; JSXParser.prototype.parseJSXElement = function () { var node = this.createJSXNode(); var opening = this.parseJSXOpeningElement(); var children = []; var closing = null; if (!opening.selfClosing) { var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children }); children = el.children; closing = el.closing; } return this.finalize(node, new JSXNode.JSXElement(opening, children, closing)); }; JSXParser.prototype.parseJSXRoot = function () { // Pop the opening '<' added from the lookahead. if (this.config.tokens) { this.tokens.pop(); } this.startJSX(); var element = this.parseJSXElement(); this.finishJSX(); return element; }; JSXParser.prototype.isStartOfExpression = function () { return _super.prototype.isStartOfExpression.call(this) || this.match('<'); }; return JSXParser; }(parser_1.Parser)); exports.JSXParser = JSXParser; /***/ }, /* 4 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // See also tools/generate-unicode-regex.js. var Regex = { // Unicode v8.0.0 NonAsciiIdentifierStart: NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, // Unicode v8.0.0 NonAsciiIdentifierPart: NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ }; exports.Character = { /* tslint:disable:no-bitwise */ fromCodePoint: function (cp) { return (cp < 0x10000) ? String.fromCharCode(cp) : String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) + String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023)); }, // https://tc39.github.io/ecma262/#sec-white-space isWhiteSpace: function (cp) { return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) || (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0); }, // https://tc39.github.io/ecma262/#sec-line-terminators isLineTerminator: function (cp) { return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029); }, // https://tc39.github.io/ecma262/#sec-names-and-keywords isIdentifierStart: function (cp) { return (cp === 0x24) || (cp === 0x5F) || (cp >= 0x41 && cp <= 0x5A) || (cp >= 0x61 && cp <= 0x7A) || (cp === 0x5C) || ((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp))); }, isIdentifierPart: function (cp) { return (cp === 0x24) || (cp === 0x5F) || (cp >= 0x41 && cp <= 0x5A) || (cp >= 0x61 && cp <= 0x7A) || (cp >= 0x30 && cp <= 0x39) || (cp === 0x5C) || ((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp))); }, // https://tc39.github.io/ecma262/#sec-literals-numeric-literals isDecimalDigit: function (cp) { return (cp >= 0x30 && cp <= 0x39); // 0..9 }, isHexDigit: function (cp) { return (cp >= 0x30 && cp <= 0x39) || (cp >= 0x41 && cp <= 0x46) || (cp >= 0x61 && cp <= 0x66); // a..f }, isOctalDigit: function (cp) { return (cp >= 0x30 && cp <= 0x37); // 0..7 } }; /***/ }, /* 5 */ /***/ function(module, exports, __nested_webpack_require_54354__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var jsx_syntax_1 = __nested_webpack_require_54354__(6); /* tslint:disable:max-classes-per-file */ var JSXClosingElement = (function () { function JSXClosingElement(name) { this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement; this.name = name; } return JSXClosingElement; }()); exports.JSXClosingElement = JSXClosingElement; var JSXElement = (function () { function JSXElement(openingElement, children, closingElement) { this.type = jsx_syntax_1.JSXSyntax.JSXElement; this.openingElement = openingElement; this.children = children; this.closingElement = closingElement; } return JSXElement; }()); exports.JSXElement = JSXElement; var JSXEmptyExpression = (function () { function JSXEmptyExpression() { this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression; } return JSXEmptyExpression; }()); exports.JSXEmptyExpression = JSXEmptyExpression; var JSXExpressionContainer = (function () { function JSXExpressionContainer(expression) { this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer; this.expression = expression; } return JSXExpressionContainer; }()); exports.JSXExpressionContainer = JSXExpressionContainer; var JSXIdentifier = (function () { function JSXIdentifier(name) { this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier; this.name = name; } return JSXIdentifier; }()); exports.JSXIdentifier = JSXIdentifier; var JSXMemberExpression = (function () { function JSXMemberExpression(object, property) { this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression; this.object = object; this.property = property; } return JSXMemberExpression; }()); exports.JSXMemberExpression = JSXMemberExpression; var JSXAttribute = (function () { function JSXAttribute(name, value) { this.type = jsx_syntax_1.JSXSyntax.JSXAttribute; this.name = name; this.value = value; } return JSXAttribute; }()); exports.JSXAttribute = JSXAttribute; var JSXNamespacedName = (function () { function JSXNamespacedName(namespace, name) { this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName; this.namespace = namespace; this.name = name; } return JSXNamespacedName; }()); exports.JSXNamespacedName = JSXNamespacedName; var JSXOpeningElement = (function () { function JSXOpeningElement(name, selfClosing, attributes) { this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement; this.name = name; this.selfClosing = selfClosing; this.attributes = attributes; } return JSXOpeningElement; }()); exports.JSXOpeningElement = JSXOpeningElement; var JSXSpreadAttribute = (function () { function JSXSpreadAttribute(argument) { this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute; this.argument = argument; } return JSXSpreadAttribute; }()); exports.JSXSpreadAttribute = JSXSpreadAttribute; var JSXText = (function () { function JSXText(value, raw) { this.type = jsx_syntax_1.JSXSyntax.JSXText; this.value = value; this.raw = raw; } return JSXText; }()); exports.JSXText = JSXText; /***/ }, /* 6 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.JSXSyntax = { JSXAttribute: 'JSXAttribute', JSXClosingElement: 'JSXClosingElement', JSXElement: 'JSXElement', JSXEmptyExpression: 'JSXEmptyExpression', JSXExpressionContainer: 'JSXExpressionContainer', JSXIdentifier: 'JSXIdentifier', JSXMemberExpression: 'JSXMemberExpression', JSXNamespacedName: 'JSXNamespacedName', JSXOpeningElement: 'JSXOpeningElement', JSXSpreadAttribute: 'JSXSpreadAttribute', JSXText: 'JSXText' }; /***/ }, /* 7 */ /***/ function(module, exports, __nested_webpack_require_58416__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var syntax_1 = __nested_webpack_require_58416__(2); /* tslint:disable:max-classes-per-file */ var ArrayExpression = (function () { function ArrayExpression(elements) { this.type = syntax_1.Syntax.ArrayExpression; this.elements = elements; } return ArrayExpression; }()); exports.ArrayExpression = ArrayExpression; var ArrayPattern = (function () { function ArrayPattern(elements) { this.type = syntax_1.Syntax.ArrayPattern; this.elements = elements; } return ArrayPattern; }()); exports.ArrayPattern = ArrayPattern; var ArrowFunctionExpression = (function () { function ArrowFunctionExpression(params, body, expression) { this.type = syntax_1.Syntax.ArrowFunctionExpression; this.id = null; this.params = params; this.body = body; this.generator = false; this.expression = expression; this.async = false; } return ArrowFunctionExpression; }()); exports.ArrowFunctionExpression = ArrowFunctionExpression; var AssignmentExpression = (function () { function AssignmentExpression(operator, left, right) { this.type = syntax_1.Syntax.AssignmentExpression; this.operator = operator; this.left = left; this.right = right; } return AssignmentExpression; }()); exports.AssignmentExpression = AssignmentExpression; var AssignmentPattern = (function () { function AssignmentPattern(left, right) { this.type = syntax_1.Syntax.AssignmentPattern; this.left = left; this.right = right; } return AssignmentPattern; }()); exports.AssignmentPattern = AssignmentPattern; var AsyncArrowFunctionExpression = (function () { function AsyncArrowFunctionExpression(params, body, expression) { this.type = syntax_1.Syntax.ArrowFunctionExpression; this.id = null; this.params = params; this.body = body; this.generator = false; this.expression = expression; this.async = true; } return AsyncArrowFunctionExpression; }()); exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression; var AsyncFunctionDeclaration = (function () { function AsyncFunctionDeclaration(id, params, body) { this.type = syntax_1.Syntax.FunctionDeclaration; this.id = id; this.params = params; this.body = body; this.generator = false; this.expression = false; this.async = true; } return AsyncFunctionDeclaration; }()); exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration; var AsyncFunctionExpression = (function () { function AsyncFunctionExpression(id, params, body) { this.type = syntax_1.Syntax.FunctionExpression; this.id = id; this.params = params; this.body = body; this.generator = false; this.expression = false; this.async = true; } return AsyncFunctionExpression; }()); exports.AsyncFunctionExpression = AsyncFunctionExpression; var AwaitExpression = (function () { function AwaitExpression(argument) { this.type = syntax_1.Syntax.AwaitExpression; this.argument = argument; } return AwaitExpression; }()); exports.AwaitExpression = AwaitExpression; var BinaryExpression = (function () { function BinaryExpression(operator, left, right) { var logical = (operator === '||' || operator === '&&'); this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression; this.operator = operator; this.left = left; this.right = right; } return BinaryExpression; }()); exports.BinaryExpression = BinaryExpression; var BlockStatement = (function () { function BlockStatement(body) { this.type = syntax_1.Syntax.BlockStatement; this.body = body; } return BlockStatement; }()); exports.BlockStatement = BlockStatement; var BreakStatement = (function () { function BreakStatement(label) { this.type = syntax_1.Syntax.BreakStatement; this.label = label; } return BreakStatement; }()); exports.BreakStatement = BreakStatement; var CallExpression = (function () { function CallExpression(callee, args) { this.type = syntax_1.Syntax.CallExpression; this.callee = callee; this.arguments = args; } return CallExpression; }()); exports.CallExpression = CallExpression; var CatchClause = (function () { function CatchClause(param, body) { this.type = syntax_1.Syntax.CatchClause; this.param = param; this.body = body; } return CatchClause; }()); exports.CatchClause = CatchClause; var ClassBody = (function () { function ClassBody(body) { this.type = syntax_1.Syntax.ClassBody; this.body = body; } return ClassBody; }()); exports.ClassBody = ClassBody; var ClassDeclaration = (function () { function ClassDeclaration(id, superClass, body) { this.type = syntax_1.Syntax.ClassDeclaration; this.id = id; this.superClass = superClass; this.body = body; } return ClassDeclaration; }()); exports.ClassDeclaration = ClassDeclaration; var ClassExpression = (function () { function ClassExpression(id, superClass, body) { this.type = syntax_1.Syntax.ClassExpression; this.id = id; this.superClass = superClass; this.body = body; } return ClassExpression; }()); exports.ClassExpression = ClassExpression; var ComputedMemberExpression = (function () { function ComputedMemberExpression(object, property) { this.type = syntax_1.Syntax.MemberExpression; this.computed = true; this.object = object; this.property = property; } return ComputedMemberExpression; }()); exports.ComputedMemberExpression = ComputedMemberExpression; var ConditionalExpression = (function () { function ConditionalExpression(test, consequent, alternate) { this.type = syntax_1.Syntax.ConditionalExpression; this.test = test; this.consequent = consequent; this.alternate = alternate; } return ConditionalExpression; }()); exports.ConditionalExpression = ConditionalExpression; var ContinueStatement = (function () { function ContinueStatement(label) { this.type = syntax_1.Syntax.ContinueStatement; this.label = label; } return ContinueStatement; }()); exports.ContinueStatement = ContinueStatement; var DebuggerStatement = (function () { function DebuggerStatement() { this.type = syntax_1.Syntax.DebuggerStatement; } return DebuggerStatement; }()); exports.DebuggerStatement = DebuggerStatement; var Directive = (function () { function Directive(expression, directive) { this.type = syntax_1.Syntax.ExpressionStatement; this.expression = expression; this.directive = directive; } return Directive; }()); exports.Directive = Directive; var DoWhileStatement = (function () { function DoWhileStatement(body, test) { this.type = syntax_1.Syntax.DoWhileStatement; this.body = body; this.test = test; } return DoWhileStatement; }()); exports.DoWhileStatement = DoWhileStatement; var EmptyStatement = (function () { function EmptyStatement() { this.type = syntax_1.Syntax.EmptyStatement; } return EmptyStatement; }()); exports.EmptyStatement = EmptyStatement; var ExportAllDeclaration = (function () { function ExportAllDeclaration(source) { this.type = syntax_1.Syntax.ExportAllDeclaration; this.source = source; } return ExportAllDeclaration; }()); exports.ExportAllDeclaration = ExportAllDeclaration; var ExportDefaultDeclaration = (function () { function ExportDefaultDeclaration(declaration) { this.type = syntax_1.Syntax.ExportDefaultDeclaration; this.declaration = declaration; } return ExportDefaultDeclaration; }()); exports.ExportDefaultDeclaration = ExportDefaultDeclaration; var ExportNamedDeclaration = (function () { function ExportNamedDeclaration(declaration, specifiers, source) { this.type = syntax_1.Syntax.ExportNamedDeclaration; this.declaration = declaration; this.specifiers = specifiers; this.source = source; } return ExportNamedDeclaration; }()); exports.ExportNamedDeclaration = ExportNamedDeclaration; var ExportSpecifier = (function () { function ExportSpecifier(local, exported) { this.type = syntax_1.Syntax.ExportSpecifier; this.exported = exported; this.local = local; } return ExportSpecifier; }()); exports.ExportSpecifier = ExportSpecifier; var ExpressionStatement = (function () { function ExpressionStatement(expression) { this.type = syntax_1.Syntax.ExpressionStatement; this.expression = expression; } return ExpressionStatement; }()); exports.ExpressionStatement = ExpressionStatement; var ForInStatement = (function () { function ForInStatement(left, right, body) { this.type = syntax_1.Syntax.ForInStatement; this.left = left; this.right = right; this.body = body; this.each = false; } return ForInStatement; }()); exports.ForInStatement = ForInStatement; var ForOfStatement = (function () { function ForOfStatement(left, right, body) { this.type = syntax_1.Syntax.ForOfStatement; this.left = left; this.right = right; this.body = body; } return ForOfStatement; }()); exports.ForOfStatement = ForOfStatement; var ForStatement = (function () { function ForStatement(init, test, update, body) { this.type = syntax_1.Syntax.ForStatement; this.init = init; this.test = test; this.update = update; this.body = body; } return ForStatement; }()); exports.ForStatement = ForStatement; var FunctionDeclaration = (function () { function FunctionDeclaration(id, params, body, generator) { this.type = syntax_1.Syntax.FunctionDeclaration; this.id = id; this.params = params; this.body = body; this.generator = generator; this.expression = false; this.async = false; } return FunctionDeclaration; }()); exports.FunctionDeclaration = FunctionDeclaration; var FunctionExpression = (function () { function FunctionExpression(id, params, body, generator) { this.type = syntax_1.Syntax.FunctionExpression; this.id = id; this.params = params; this.body = body; this.generator = generator; this.expression = false; this.async = false; } return FunctionExpression; }()); exports.FunctionExpression = FunctionExpression; var Identifier = (function () { function Identifier(name) { this.type = syntax_1.Syntax.Identifier; this.name = name; } return Identifier; }()); exports.Identifier = Identifier; var IfStatement = (function () { function IfStatement(test, consequent, alternate) { this.type = syntax_1.Syntax.IfStatement; this.test = test; this.consequent = consequent; this.alternate = alternate; } return IfStatement; }()); exports.IfStatement = IfStatement; var ImportDeclaration = (function () { function ImportDeclaration(specifiers, source) { this.type = syntax_1.Syntax.ImportDeclaration; this.specifiers = specifiers; this.source = source; } return ImportDeclaration; }()); exports.ImportDeclaration = ImportDeclaration; var ImportDefaultSpecifier = (function () { function ImportDefaultSpecifier(local) { this.type = syntax_1.Syntax.ImportDefaultSpecifier; this.local = local; } return ImportDefaultSpecifier; }()); exports.ImportDefaultSpecifier = ImportDefaultSpecifier; var ImportNamespaceSpecifier = (function () { function ImportNamespaceSpecifier(local) { this.type = syntax_1.Syntax.ImportNamespaceSpecifier; this.local = local; } return ImportNamespaceSpecifier; }()); exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; var ImportSpecifier = (function () { function ImportSpecifier(local, imported) { this.type = syntax_1.Syntax.ImportSpecifier; this.local = local; this.imported = imported; } return ImportSpecifier; }()); exports.ImportSpecifier = ImportSpecifier; var LabeledStatement = (function () { function LabeledStatement(label, body) { this.type = syntax_1.Syntax.LabeledStatement; this.label = label; this.body = body; } return LabeledStatement; }()); exports.LabeledStatement = LabeledStatement; var Literal = (function () { function Literal(value, raw) { this.type = syntax_1.Syntax.Literal; this.value = value; this.raw = raw; } return Literal; }()); exports.Literal = Literal; var MetaProperty = (function () { function MetaProperty(meta, property) { this.type = syntax_1.Syntax.MetaProperty; this.meta = meta; this.property = property; } return MetaProperty; }()); exports.MetaProperty = MetaProperty; var MethodDefinition = (function () { function MethodDefinition(key, computed, value, kind, isStatic) { this.type = syntax_1.Syntax.MethodDefinition; this.key = key; this.computed = computed; this.value = value; this.kind = kind; this.static = isStatic; } return MethodDefinition; }()); exports.MethodDefinition = MethodDefinition; var Module = (function () { function Module(body) { this.type = syntax_1.Syntax.Program; this.body = body; this.sourceType = 'module'; } return Module; }()); exports.Module = Module; var NewExpression = (function () { function NewExpression(callee, args) { this.type = syntax_1.Syntax.NewExpression; this.callee = callee; this.arguments = args; } return NewExpression; }()); exports.NewExpression = NewExpression; var ObjectExpression = (function () { function ObjectExpression(properties) { this.type = syntax_1.Syntax.ObjectExpression; this.properties = properties; } return ObjectExpression; }()); exports.ObjectExpression = ObjectExpression; var ObjectPattern = (function () { function ObjectPattern(properties) { this.type = syntax_1.Syntax.ObjectPattern; this.properties = properties; } return ObjectPattern; }()); exports.ObjectPattern = ObjectPattern; var Property = (function () { function Property(kind, key, computed, value, method, shorthand) { this.type = syntax_1.Syntax.Property; this.key = key; this.computed = computed; this.value = value; this.kind = kind; this.method = method; this.shorthand = shorthand; } return Property; }()); exports.Property = Property; var RegexLiteral = (function () { function RegexLiteral(value, raw, pattern, flags) { this.type = syntax_1.Syntax.Literal; this.value = value; this.raw = raw; this.regex = { pattern: pattern, flags: flags }; } return RegexLiteral; }()); exports.RegexLiteral = RegexLiteral; var RestElement = (function () { function RestElement(argument) { this.type = syntax_1.Syntax.RestElement; this.argument = argument; } return RestElement; }()); exports.RestElement = RestElement; var ReturnStatement = (function () { function ReturnStatement(argument) { this.type = syntax_1.Syntax.ReturnStatement; this.argument = argument; } return ReturnStatement; }()); exports.ReturnStatement = ReturnStatement; var Script = (function () { function Script(body) { this.type = syntax_1.Syntax.Program; this.body = body; this.sourceType = 'script'; } return Script; }()); exports.Script = Script; var SequenceExpression = (function () { function SequenceExpression(expressions) { this.type = syntax_1.Syntax.SequenceExpression; this.expressions = expressions; } return SequenceExpression; }()); exports.SequenceExpression = SequenceExpression; var SpreadElement = (function () { function SpreadElement(argument) { this.type = syntax_1.Syntax.SpreadElement; this.argument = argument; } return SpreadElement; }()); exports.SpreadElement = SpreadElement; var StaticMemberExpression = (function () { function StaticMemberExpression(object, property) { this.type = syntax_1.Syntax.MemberExpression; this.computed = false; this.object = object; this.property = property; } return StaticMemberExpression; }()); exports.StaticMemberExpression = StaticMemberExpression; var Super = (function () { function Super() { this.type = syntax_1.Syntax.Super; } return Super; }()); exports.Super = Super; var SwitchCase = (function () { function SwitchCase(test, consequent) { this.type = syntax_1.Syntax.SwitchCase; this.test = test; this.consequent = consequent; } return SwitchCase; }()); exports.SwitchCase = SwitchCase; var SwitchStatement = (function () { function SwitchStatement(discriminant, cases) { this.type = syntax_1.Syntax.SwitchStatement; this.discriminant = discriminant; this.cases = cases; } return SwitchStatement; }()); exports.SwitchStatement = SwitchStatement; var TaggedTemplateExpression = (function () { function TaggedTemplateExpression(tag, quasi) { this.type = syntax_1.Syntax.TaggedTemplateExpression; this.tag = tag; this.quasi = quasi; } return TaggedTemplateExpression; }()); exports.TaggedTemplateExpression = TaggedTemplateExpression; var TemplateElement = (function () { function TemplateElement(value, tail) { this.type = syntax_1.Syntax.TemplateElement; this.value = value; this.tail = tail; } return TemplateElement; }()); exports.TemplateElement = TemplateElement; var TemplateLiteral = (function () { function TemplateLiteral(quasis, expressions) { this.type = syntax_1.Syntax.TemplateLiteral; this.quasis = quasis; this.expressions = expressions; } return TemplateLiteral; }()); exports.TemplateLiteral = TemplateLiteral; var ThisExpression = (function () { function ThisExpression() { this.type = syntax_1.Syntax.ThisExpression; } return ThisExpression; }()); exports.ThisExpression = ThisExpression; var ThrowStatement = (function () { function ThrowStatement(argument) { this.type = syntax_1.Syntax.ThrowStatement; this.argument = argument; } return ThrowStatement; }()); exports.ThrowStatement = ThrowStatement; var TryStatement = (function () { function TryStatement(block, handler, finalizer) { this.type = syntax_1.Syntax.TryStatement; this.block = block; this.handler = handler; this.finalizer = finalizer; } return TryStatement; }()); exports.TryStatement = TryStatement; var UnaryExpression = (function () { function UnaryExpression(operator, argument) { this.type = syntax_1.Syntax.UnaryExpression; this.operator = operator; this.argument = argument; this.prefix = true; } return UnaryExpression; }()); exports.UnaryExpression = UnaryExpression; var UpdateExpression = (function () { function UpdateExpression(operator, argument, prefix) { this.type = syntax_1.Syntax.UpdateExpression; this.operator = operator; this.argument = argument; this.prefix = prefix; } return UpdateExpression; }()); exports.UpdateExpression = UpdateExpression; var VariableDeclaration = (function () { function VariableDeclaration(declarations, kind) { this.type = syntax_1.Syntax.VariableDeclaration; this.declarations = declarations; this.kind = kind; } return VariableDeclaration; }()); exports.VariableDeclaration = VariableDeclaration; var VariableDeclarator = (function () { function VariableDeclarator(id, init) { this.type = syntax_1.Syntax.VariableDeclarator; this.id = id; this.init = init; } return VariableDeclarator; }()); exports.VariableDeclarator = VariableDeclarator; var WhileStatement = (function () { function WhileStatement(test, body) { this.type = syntax_1.Syntax.WhileStatement; this.test = test; this.body = body; } return WhileStatement; }()); exports.WhileStatement = WhileStatement; var WithStatement = (function () { function WithStatement(object, body) { this.type = syntax_1.Syntax.WithStatement; this.object = object; this.body = body; } return WithStatement; }()); exports.WithStatement = WithStatement; var YieldExpression = (function () { function YieldExpression(argument, delegate) { this.type = syntax_1.Syntax.YieldExpression; this.argument = argument; this.delegate = delegate; } return YieldExpression; }()); exports.YieldExpression = YieldExpression; /***/ }, /* 8 */ /***/ function(module, exports, __nested_webpack_require_80491__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var assert_1 = __nested_webpack_require_80491__(9); var error_handler_1 = __nested_webpack_require_80491__(10); var messages_1 = __nested_webpack_require_80491__(11); var Node = __nested_webpack_require_80491__(7); var scanner_1 = __nested_webpack_require_80491__(12); var syntax_1 = __nested_webpack_require_80491__(2); var token_1 = __nested_webpack_require_80491__(13); var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder'; var Parser = (function () { function Parser(code, options, delegate) { if (options === void 0) { options = {}; } this.config = { range: (typeof options.range === 'boolean') && options.range, loc: (typeof options.loc === 'boolean') && options.loc, source: null, tokens: (typeof options.tokens === 'boolean') && options.tokens, comment: (typeof options.comment === 'boolean') && options.comment, tolerant: (typeof options.tolerant === 'boolean') && options.tolerant }; if (this.config.loc && options.source && options.source !== null) { this.config.source = String(options.source); } this.delegate = delegate; this.errorHandler = new error_handler_1.ErrorHandler(); this.errorHandler.tolerant = this.config.tolerant; this.scanner = new scanner_1.Scanner(code, this.errorHandler); this.scanner.trackComment = this.config.comment; this.operatorPrecedence = { ')': 0, ';': 0, ',': 0, '=': 0, ']': 0, '||': 1, '&&': 2, '|': 3, '^': 4, '&': 5, '==': 6, '!=': 6, '===': 6, '!==': 6, '<': 7, '>': 7, '<=': 7, '>=': 7, '<<': 8, '>>': 8, '>>>': 8, '+': 9, '-': 9, '*': 11, '/': 11, '%': 11 }; this.lookahead = { type: 2 /* EOF */, value: '', lineNumber: this.scanner.lineNumber, lineStart: 0, start: 0, end: 0 }; this.hasLineTerminator = false; this.context = { isModule: false, await: false, allowIn: true, allowStrictDirective: true, allowYield: true, firstCoverInitializedNameError: null, isAssignmentTarget: false, isBindingElement: false, inFunctionBody: false, inIteration: false, inSwitch: false, labelSet: {}, strict: false }; this.tokens = []; this.startMarker = { index: 0, line: this.scanner.lineNumber, column: 0 }; this.lastMarker = { index: 0, line: this.scanner.lineNumber, column: 0 }; this.nextToken(); this.lastMarker = { index: this.scanner.index, line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; } Parser.prototype.throwError = function (messageFormat) { var values = []; for (var _i = 1; _i < arguments.length; _i++) { values[_i - 1] = arguments[_i]; } var args = Array.prototype.slice.call(arguments, 1); var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { assert_1.assert(idx < args.length, 'Message reference must be in range'); return args[idx]; }); var index = this.lastMarker.index; var line = this.lastMarker.line; var column = this.lastMarker.column + 1; throw this.errorHandler.createError(index, line, column, msg); }; Parser.prototype.tolerateError = function (messageFormat) { var values = []; for (var _i = 1; _i < arguments.length; _i++) { values[_i - 1] = arguments[_i]; } var args = Array.prototype.slice.call(arguments, 1); var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { assert_1.assert(idx < args.length, 'Message reference must be in range'); return args[idx]; }); var index = this.lastMarker.index; var line = this.scanner.lineNumber; var column = this.lastMarker.column + 1; this.errorHandler.tolerateError(index, line, column, msg); }; // Throw an exception because of the token. Parser.prototype.unexpectedTokenError = function (token, message) { var msg = message || messages_1.Messages.UnexpectedToken; var value; if (token) { if (!message) { msg = (token.type === 2 /* EOF */) ? messages_1.Messages.UnexpectedEOS : (token.type === 3 /* Identifier */) ? messages_1.Messages.UnexpectedIdentifier : (token.type === 6 /* NumericLiteral */) ? messages_1.Messages.UnexpectedNumber : (token.type === 8 /* StringLiteral */) ? messages_1.Messages.UnexpectedString : (token.type === 10 /* Template */) ? messages_1.Messages.UnexpectedTemplate : messages_1.Messages.UnexpectedToken; if (token.type === 4 /* Keyword */) { if (this.scanner.isFutureReservedWord(token.value)) { msg = messages_1.Messages.UnexpectedReserved; } else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) { msg = messages_1.Messages.StrictReservedWord; } } } value = token.value; } else { value = 'ILLEGAL'; } msg = msg.replace('%0', value); if (token && typeof token.lineNumber === 'number') { var index = token.start; var line = token.lineNumber; var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column; var column = token.start - lastMarkerLineStart + 1; return this.errorHandler.createError(index, line, column, msg); } else { var index = this.lastMarker.index; var line = this.lastMarker.line; var column = this.lastMarker.column + 1; return this.errorHandler.createError(index, line, column, msg); } }; Parser.prototype.throwUnexpectedToken = function (token, message) { throw this.unexpectedTokenError(token, message); }; Parser.prototype.tolerateUnexpectedToken = function (token, message) { this.errorHandler.tolerate(this.unexpectedTokenError(token, message)); }; Parser.prototype.collectComments = function () { if (!this.config.comment) { this.scanner.scanComments(); } else { var comments = this.scanner.scanComments(); if (comments.length > 0 && this.delegate) { for (var i = 0; i < comments.length; ++i) { var e = comments[i]; var node = void 0; node = { type: e.multiLine ? 'BlockComment' : 'LineComment', value: this.scanner.source.slice(e.slice[0], e.slice[1]) }; if (this.config.range) { node.range = e.range; } if (this.config.loc) { node.loc = e.loc; } var metadata = { start: { line: e.loc.start.line, column: e.loc.start.column, offset: e.range[0] }, end: { line: e.loc.end.line, column: e.loc.end.column, offset: e.range[1] } }; this.delegate(node, metadata); } } } }; // From internal representation to an external structure Parser.prototype.getTokenRaw = function (token) { return this.scanner.source.slice(token.start, token.end); }; Parser.prototype.convertToken = function (token) { var t = { type: token_1.TokenName[token.type], value: this.getTokenRaw(token) }; if (this.config.range) { t.range = [token.start, token.end]; } if (this.config.loc) { t.loc = { start: { line: this.startMarker.line, column: this.startMarker.column }, end: { line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart } }; } if (token.type === 9 /* RegularExpression */) { var pattern = token.pattern; var flags = token.flags; t.regex = { pattern: pattern, flags: flags }; } return t; }; Parser.prototype.nextToken = function () { var token = this.lookahead; this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; this.collectComments(); if (this.scanner.index !== this.startMarker.index) { this.startMarker.index = this.scanner.index; this.startMarker.line = this.scanner.lineNumber; this.startMarker.column = this.scanner.index - this.scanner.lineStart; } var next = this.scanner.lex(); this.hasLineTerminator = (token.lineNumber !== next.lineNumber); if (next && this.context.strict && next.type === 3 /* Identifier */) { if (this.scanner.isStrictModeReservedWord(next.value)) { next.type = 4 /* Keyword */; } } this.lookahead = next; if (this.config.tokens && next.type !== 2 /* EOF */) { this.tokens.push(this.convertToken(next)); } return token; }; Parser.prototype.nextRegexToken = function () { this.collectComments(); var token = this.scanner.scanRegExp(); if (this.config.tokens) { // Pop the previous token, '/' or '/=' // This is added from the lookahead token. this.tokens.pop(); this.tokens.push(this.convertToken(token)); } // Prime the next lookahead. this.lookahead = token; this.nextToken(); return token; }; Parser.prototype.createNode = function () { return { index: this.startMarker.index, line: this.startMarker.line, column: this.startMarker.column }; }; Parser.prototype.startNode = function (token, lastLineStart) { if (lastLineStart === void 0) { lastLineStart = 0; } var column = token.start - token.lineStart; var line = token.lineNumber; if (column < 0) { column += lastLineStart; line--; } return { index: token.start, line: line, column: column }; }; Parser.prototype.finalize = function (marker, node) { if (this.config.range) { node.range = [marker.index, this.lastMarker.index]; } if (this.config.loc) { node.loc = { start: { line: marker.line, column: marker.column, }, end: { line: this.lastMarker.line, column: this.lastMarker.column } }; if (this.config.source) { node.loc.source = this.config.source; } } if (this.delegate) { var metadata = { start: { line: marker.line, column: marker.column, offset: marker.index }, end: { line: this.lastMarker.line, column: this.lastMarker.column, offset: this.lastMarker.index } }; this.delegate(node, metadata); } return node; }; // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. Parser.prototype.expect = function (value) { var token = this.nextToken(); if (token.type !== 7 /* Punctuator */ || token.value !== value) { this.throwUnexpectedToken(token); } }; // Quietly expect a comma when in tolerant mode, otherwise delegates to expect(). Parser.prototype.expectCommaSeparator = function () { if (this.config.tolerant) { var token = this.lookahead; if (token.type === 7 /* Punctuator */ && token.value === ',') { this.nextToken(); } else if (token.type === 7 /* Punctuator */ && token.value === ';') { this.nextToken(); this.tolerateUnexpectedToken(token); } else { this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken); } } else { this.expect(','); } }; // Expect the next token to match the specified keyword. // If not, an exception will be thrown. Parser.prototype.expectKeyword = function (keyword) { var token = this.nextToken(); if (token.type !== 4 /* Keyword */ || token.value !== keyword) { this.throwUnexpectedToken(token); } }; // Return true if the next token matches the specified punctuator. Parser.prototype.match = function (value) { return this.lookahead.type === 7 /* Punctuator */ && this.lookahead.value === value; }; // Return true if the next token matches the specified keyword Parser.prototype.matchKeyword = function (keyword) { return this.lookahead.type === 4 /* Keyword */ && this.lookahead.value === keyword; }; // Return true if the next token matches the specified contextual keyword // (where an identifier is sometimes a keyword depending on the context) Parser.prototype.matchContextualKeyword = function (keyword) { return this.lookahead.type === 3 /* Identifier */ && this.lookahead.value === keyword; }; // Return true if the next token is an assignment operator Parser.prototype.matchAssign = function () { if (this.lookahead.type !== 7 /* Punctuator */) { return false; } var op = this.lookahead.value; return op === '=' || op === '*=' || op === '**=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|='; }; // Cover grammar support. // // When an assignment expression position starts with an left parenthesis, the determination of the type // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead) // or the first comma. This situation also defers the determination of all the expressions nested in the pair. // // There are three productions that can be parsed in a parentheses pair that needs to be determined // after the outermost pair is closed. They are: // // 1. AssignmentExpression // 2. BindingElements // 3. AssignmentTargets // // In order to avoid exponential backtracking, we use two flags to denote if the production can be // binding element or assignment target. // // The three productions have the relationship: // // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression // // with a single exception that CoverInitializedName when used directly in an Expression, generates // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair. // // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not // effect the current flags. This means the production the parser parses is only used as an expression. Therefore // the CoverInitializedName check is conducted. // // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates // the flags outside of the parser. This means the production the parser parses is used as a part of a potential // pattern. The CoverInitializedName check is deferred. Parser.prototype.isolateCoverGrammar = function (parseFunction) { var previousIsBindingElement = this.context.isBindingElement; var previousIsAssignmentTarget = this.context.isAssignmentTarget; var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; this.context.isBindingElement = true; this.context.isAssignmentTarget = true; this.context.firstCoverInitializedNameError = null; var result = parseFunction.call(this); if (this.context.firstCoverInitializedNameError !== null) { this.throwUnexpectedToken(this.context.firstCoverInitializedNameError); } this.context.isBindingElement = previousIsBindingElement; this.context.isAssignmentTarget = previousIsAssignmentTarget; this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError; return result; }; Parser.prototype.inheritCoverGrammar = function (parseFunction) { var previousIsBindingElement = this.context.isBindingElement; var previousIsAssignmentTarget = this.context.isAssignmentTarget; var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; this.context.isBindingElement = true; this.context.isAssignmentTarget = true; this.context.firstCoverInitializedNameError = null; var result = parseFunction.call(this); this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement; this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget; this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError; return result; }; Parser.prototype.consumeSemicolon = function () { if (this.match(';')) { this.nextToken(); } else if (!this.hasLineTerminator) { if (this.lookahead.type !== 2 /* EOF */ && !this.match('}')) { this.throwUnexpectedToken(this.lookahead); } this.lastMarker.index = this.startMarker.index; this.lastMarker.line = this.startMarker.line; this.lastMarker.column = this.startMarker.column; } }; // https://tc39.github.io/ecma262/#sec-primary-expression Parser.prototype.parsePrimaryExpression = function () { var node = this.createNode(); var expr; var token, raw; switch (this.lookahead.type) { case 3 /* Identifier */: if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') { this.tolerateUnexpectedToken(this.lookahead); } expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value)); break; case 6 /* NumericLiteral */: case 8 /* StringLiteral */: if (this.context.strict && this.lookahead.octal) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral); } this.context.isAssignmentTarget = false; this.context.isBindingElement = false; token = this.nextToken(); raw = this.getTokenRaw(token); expr = this.finalize(node, new Node.Literal(token.value, raw)); break; case 1 /* BooleanLiteral */: this.context.isAssignmentTarget = false; this.context.isBindingElement = false; token = this.nextToken(); raw = this.getTokenRaw(token); expr = this.finalize(node, new Node.Literal(token.value === 'true', raw)); break; case 5 /* NullLiteral */: this.context.isAssignmentTarget = false; this.context.isBindingElement = false; token = this.nextToken(); raw = this.getTokenRaw(token); expr = this.finalize(node, new Node.Literal(null, raw)); break; case 10 /* Template */: expr = this.parseTemplateLiteral(); break; case 7 /* Punctuator */: switch (this.lookahead.value) { case '(': this.context.isBindingElement = false; expr = this.inheritCoverGrammar(this.parseGroupExpression); break; case '[': expr = this.inheritCoverGrammar(this.parseArrayInitializer); break; case '{': expr = this.inheritCoverGrammar(this.parseObjectInitializer); break; case '/': case '/=': this.context.isAssignmentTarget = false; this.context.isBindingElement = false; this.scanner.index = this.startMarker.index; token = this.nextRegexToken(); raw = this.getTokenRaw(token); expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags)); break; default: expr = this.throwUnexpectedToken(this.nextToken()); } break; case 4 /* Keyword */: if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) { expr = this.parseIdentifierName(); } else if (!this.context.strict && this.matchKeyword('let')) { expr = this.finalize(node, new Node.Identifier(this.nextToken().value)); } else { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; if (this.matchKeyword('function')) { expr = this.parseFunctionExpression(); } else if (this.matchKeyword('this')) { this.nextToken(); expr = this.finalize(node, new Node.ThisExpression()); } else if (this.matchKeyword('class')) { expr = this.parseClassExpression(); } else { expr = this.throwUnexpectedToken(this.nextToken()); } } break; default: expr = this.throwUnexpectedToken(this.nextToken()); } return expr; }; // https://tc39.github.io/ecma262/#sec-array-initializer Parser.prototype.parseSpreadElement = function () { var node = this.createNode(); this.expect('...'); var arg = this.inheritCoverGrammar(this.parseAssignmentExpression); return this.finalize(node, new Node.SpreadElement(arg)); }; Parser.prototype.parseArrayInitializer = function () { var node = this.createNode(); var elements = []; this.expect('['); while (!this.match(']')) { if (this.match(',')) { this.nextToken(); elements.push(null); } else if (this.match('...')) { var element = this.parseSpreadElement(); if (!this.match(']')) { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; this.expect(','); } elements.push(element); } else { elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); if (!this.match(']')) { this.expect(','); } } } this.expect(']'); return this.finalize(node, new Node.ArrayExpression(elements)); }; // https://tc39.github.io/ecma262/#sec-object-initializer Parser.prototype.parsePropertyMethod = function (params) { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = params.simple; var body = this.isolateCoverGrammar(this.parseFunctionSourceElements); if (this.context.strict && params.firstRestricted) { this.tolerateUnexpectedToken(params.firstRestricted, params.message); } if (this.context.strict && params.stricted) { this.tolerateUnexpectedToken(params.stricted, params.message); } this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; return body; }; Parser.prototype.parsePropertyMethodFunction = function () { var isGenerator = false; var node = this.createNode(); var previousAllowYield = this.context.allowYield; this.context.allowYield = true; var params = this.parseFormalParameters(); var method = this.parsePropertyMethod(params); this.context.allowYield = previousAllowYield; return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); }; Parser.prototype.parsePropertyMethodAsyncFunction = function () { var node = this.createNode(); var previousAllowYield = this.context.allowYield; var previousAwait = this.context.await; this.context.allowYield = false; this.context.await = true; var params = this.parseFormalParameters(); var method = this.parsePropertyMethod(params); this.context.allowYield = previousAllowYield; this.context.await = previousAwait; return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method)); }; Parser.prototype.parseObjectPropertyKey = function () { var node = this.createNode(); var token = this.nextToken(); var key; switch (token.type) { case 8 /* StringLiteral */: case 6 /* NumericLiteral */: if (this.context.strict && token.octal) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral); } var raw = this.getTokenRaw(token); key = this.finalize(node, new Node.Literal(token.value, raw)); break; case 3 /* Identifier */: case 1 /* BooleanLiteral */: case 5 /* NullLiteral */: case 4 /* Keyword */: key = this.finalize(node, new Node.Identifier(token.value)); break; case 7 /* Punctuator */: if (token.value === '[') { key = this.isolateCoverGrammar(this.parseAssignmentExpression); this.expect(']'); } else { key = this.throwUnexpectedToken(token); } break; default: key = this.throwUnexpectedToken(token); } return key; }; Parser.prototype.isPropertyKey = function (key, value) { return (key.type === syntax_1.Syntax.Identifier && key.name === value) || (key.type === syntax_1.Syntax.Literal && key.value === value); }; Parser.prototype.parseObjectProperty = function (hasProto) { var node = this.createNode(); var token = this.lookahead; var kind; var key = null; var value = null; var computed = false; var method = false; var shorthand = false; var isAsync = false; if (token.type === 3 /* Identifier */) { var id = token.value; this.nextToken(); computed = this.match('['); isAsync = !this.hasLineTerminator && (id === 'async') && !this.match(':') && !this.match('(') && !this.match('*') && !this.match(','); key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id)); } else if (this.match('*')) { this.nextToken(); } else { computed = this.match('['); key = this.parseObjectPropertyKey(); } var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'get' && lookaheadPropertyKey) { kind = 'get'; computed = this.match('['); key = this.parseObjectPropertyKey(); this.context.allowYield = false; value = this.parseGetterMethod(); } else if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'set' && lookaheadPropertyKey) { kind = 'set'; computed = this.match('['); key = this.parseObjectPropertyKey(); value = this.parseSetterMethod(); } else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { kind = 'init'; computed = this.match('['); key = this.parseObjectPropertyKey(); value = this.parseGeneratorMethod(); method = true; } else { if (!key) { this.throwUnexpectedToken(this.lookahead); } kind = 'init'; if (this.match(':') && !isAsync) { if (!computed && this.isPropertyKey(key, '__proto__')) { if (hasProto.value) { this.tolerateError(messages_1.Messages.DuplicateProtoProperty); } hasProto.value = true; } this.nextToken(); value = this.inheritCoverGrammar(this.parseAssignmentExpression); } else if (this.match('(')) { value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); method = true; } else if (token.type === 3 /* Identifier */) { var id = this.finalize(node, new Node.Identifier(token.value)); if (this.match('=')) { this.context.firstCoverInitializedNameError = this.lookahead; this.nextToken(); shorthand = true; var init = this.isolateCoverGrammar(this.parseAssignmentExpression); value = this.finalize(node, new Node.AssignmentPattern(id, init)); } else { shorthand = true; value = id; } } else { this.throwUnexpectedToken(this.nextToken()); } } return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand)); }; Parser.prototype.parseObjectInitializer = function () { var node = this.createNode(); this.expect('{'); var properties = []; var hasProto = { value: false }; while (!this.match('}')) { properties.push(this.parseObjectProperty(hasProto)); if (!this.match('}')) { this.expectCommaSeparator(); } } this.expect('}'); return this.finalize(node, new Node.ObjectExpression(properties)); }; // https://tc39.github.io/ecma262/#sec-template-literals Parser.prototype.parseTemplateHead = function () { assert_1.assert(this.lookahead.head, 'Template literal must start with a template head'); var node = this.createNode(); var token = this.nextToken(); var raw = token.value; var cooked = token.cooked; return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); }; Parser.prototype.parseTemplateElement = function () { if (this.lookahead.type !== 10 /* Template */) { this.throwUnexpectedToken(); } var node = this.createNode(); var token = this.nextToken(); var raw = token.value; var cooked = token.cooked; return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); }; Parser.prototype.parseTemplateLiteral = function () { var node = this.createNode(); var expressions = []; var quasis = []; var quasi = this.parseTemplateHead(); quasis.push(quasi); while (!quasi.tail) { expressions.push(this.parseExpression()); quasi = this.parseTemplateElement(); quasis.push(quasi); } return this.finalize(node, new Node.TemplateLiteral(quasis, expressions)); }; // https://tc39.github.io/ecma262/#sec-grouping-operator Parser.prototype.reinterpretExpressionAsPattern = function (expr) { switch (expr.type) { case syntax_1.Syntax.Identifier: case syntax_1.Syntax.MemberExpression: case syntax_1.Syntax.RestElement: case syntax_1.Syntax.AssignmentPattern: break; case syntax_1.Syntax.SpreadElement: expr.type = syntax_1.Syntax.RestElement; this.reinterpretExpressionAsPattern(expr.argument); break; case syntax_1.Syntax.ArrayExpression: expr.type = syntax_1.Syntax.ArrayPattern; for (var i = 0; i < expr.elements.length; i++) { if (expr.elements[i] !== null) { this.reinterpretExpressionAsPattern(expr.elements[i]); } } break; case syntax_1.Syntax.ObjectExpression: expr.type = syntax_1.Syntax.ObjectPattern; for (var i = 0; i < expr.properties.length; i++) { this.reinterpretExpressionAsPattern(expr.properties[i].value); } break; case syntax_1.Syntax.AssignmentExpression: expr.type = syntax_1.Syntax.AssignmentPattern; delete expr.operator; this.reinterpretExpressionAsPattern(expr.left); break; default: // Allow other node type for tolerant parsing. break; } }; Parser.prototype.parseGroupExpression = function () { var expr; this.expect('('); if (this.match(')')) { this.nextToken(); if (!this.match('=>')) { this.expect('=>'); } expr = { type: ArrowParameterPlaceHolder, params: [], async: false }; } else { var startToken = this.lookahead; var params = []; if (this.match('...')) { expr = this.parseRestElement(params); this.expect(')'); if (!this.match('=>')) { this.expect('=>'); } expr = { type: ArrowParameterPlaceHolder, params: [expr], async: false }; } else { var arrow = false; this.context.isBindingElement = true; expr = this.inheritCoverGrammar(this.parseAssignmentExpression); if (this.match(',')) { var expressions = []; this.context.isAssignmentTarget = false; expressions.push(expr); while (this.lookahead.type !== 2 /* EOF */) { if (!this.match(',')) { break; } this.nextToken(); if (this.match(')')) { this.nextToken(); for (var i = 0; i < expressions.length; i++) { this.reinterpretExpressionAsPattern(expressions[i]); } arrow = true; expr = { type: ArrowParameterPlaceHolder, params: expressions, async: false }; } else if (this.match('...')) { if (!this.context.isBindingElement) { this.throwUnexpectedToken(this.lookahead); } expressions.push(this.parseRestElement(params)); this.expect(')'); if (!this.match('=>')) { this.expect('=>'); } this.context.isBindingElement = false; for (var i = 0; i < expressions.length; i++) { this.reinterpretExpressionAsPattern(expressions[i]); } arrow = true; expr = { type: ArrowParameterPlaceHolder, params: expressions, async: false }; } else { expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); } if (arrow) { break; } } if (!arrow) { expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); } } if (!arrow) { this.expect(')'); if (this.match('=>')) { if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') { arrow = true; expr = { type: ArrowParameterPlaceHolder, params: [expr], async: false }; } if (!arrow) { if (!this.context.isBindingElement) { this.throwUnexpectedToken(this.lookahead); } if (expr.type === syntax_1.Syntax.SequenceExpression) { for (var i = 0; i < expr.expressions.length; i++) { this.reinterpretExpressionAsPattern(expr.expressions[i]); } } else { this.reinterpretExpressionAsPattern(expr); } var parameters = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]); expr = { type: ArrowParameterPlaceHolder, params: parameters, async: false }; } } this.context.isBindingElement = false; } } } return expr; }; // https://tc39.github.io/ecma262/#sec-left-hand-side-expressions Parser.prototype.parseArguments = function () { this.expect('('); var args = []; if (!this.match(')')) { while (true) { var expr = this.match('...') ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAssignmentExpression); args.push(expr); if (this.match(')')) { break; } this.expectCommaSeparator(); if (this.match(')')) { break; } } } this.expect(')'); return args; }; Parser.prototype.isIdentifierName = function (token) { return token.type === 3 /* Identifier */ || token.type === 4 /* Keyword */ || token.type === 1 /* BooleanLiteral */ || token.type === 5 /* NullLiteral */; }; Parser.prototype.parseIdentifierName = function () { var node = this.createNode(); var token = this.nextToken(); if (!this.isIdentifierName(token)) { this.throwUnexpectedToken(token); } return this.finalize(node, new Node.Identifier(token.value)); }; Parser.prototype.parseNewExpression = function () { var node = this.createNode(); var id = this.parseIdentifierName(); assert_1.assert(id.name === 'new', 'New expression must start with `new`'); var expr; if (this.match('.')) { this.nextToken(); if (this.lookahead.type === 3 /* Identifier */ && this.context.inFunctionBody && this.lookahead.value === 'target') { var property = this.parseIdentifierName(); expr = new Node.MetaProperty(id, property); } else { this.throwUnexpectedToken(this.lookahead); } } else { var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression); var args = this.match('(') ? this.parseArguments() : []; expr = new Node.NewExpression(callee, args); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } return this.finalize(node, expr); }; Parser.prototype.parseAsyncArgument = function () { var arg = this.parseAssignmentExpression(); this.context.firstCoverInitializedNameError = null; return arg; }; Parser.prototype.parseAsyncArguments = function () { this.expect('('); var args = []; if (!this.match(')')) { while (true) { var expr = this.match('...') ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAsyncArgument); args.push(expr); if (this.match(')')) { break; } this.expectCommaSeparator(); if (this.match(')')) { break; } } } this.expect(')'); return args; }; Parser.prototype.parseLeftHandSideExpressionAllowCall = function () { var startToken = this.lookahead; var maybeAsync = this.matchContextualKeyword('async'); var previousAllowIn = this.context.allowIn; this.context.allowIn = true; var expr; if (this.matchKeyword('super') && this.context.inFunctionBody) { expr = this.createNode(); this.nextToken(); expr = this.finalize(expr, new Node.Super()); if (!this.match('(') && !this.match('.') && !this.match('[')) { this.throwUnexpectedToken(this.lookahead); } } else { expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); } while (true) { if (this.match('.')) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect('.'); var property = this.parseIdentifierName(); expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property)); } else if (this.match('(')) { var asyncArrow = maybeAsync && (startToken.lineNumber === this.lookahead.lineNumber); this.context.isBindingElement = false; this.context.isAssignmentTarget = false; var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments(); expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args)); if (asyncArrow && this.match('=>')) { for (var i = 0; i < args.length; ++i) { this.reinterpretExpressionAsPattern(args[i]); } expr = { type: ArrowParameterPlaceHolder, params: args, async: true }; } } else if (this.match('[')) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect('['); var property = this.isolateCoverGrammar(this.parseExpression); this.expect(']'); expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property)); } else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { var quasi = this.parseTemplateLiteral(); expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi)); } else { break; } } this.context.allowIn = previousAllowIn; return expr; }; Parser.prototype.parseSuper = function () { var node = this.createNode(); this.expectKeyword('super'); if (!this.match('[') && !this.match('.')) { this.throwUnexpectedToken(this.lookahead); } return this.finalize(node, new Node.Super()); }; Parser.prototype.parseLeftHandSideExpression = function () { assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.'); var node = this.startNode(this.lookahead); var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() : this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); while (true) { if (this.match('[')) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect('['); var property = this.isolateCoverGrammar(this.parseExpression); this.expect(']'); expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property)); } else if (this.match('.')) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect('.'); var property = this.parseIdentifierName(); expr = this.finalize(node, new Node.StaticMemberExpression(expr, property)); } else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { var quasi = this.parseTemplateLiteral(); expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi)); } else { break; } } return expr; }; // https://tc39.github.io/ecma262/#sec-update-expressions Parser.prototype.parseUpdateExpression = function () { var expr; var startToken = this.lookahead; if (this.match('++') || this.match('--')) { var node = this.startNode(startToken); var token = this.nextToken(); expr = this.inheritCoverGrammar(this.parseUnaryExpression); if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { this.tolerateError(messages_1.Messages.StrictLHSPrefix); } if (!this.context.isAssignmentTarget) { this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); } var prefix = true; expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix)); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } else { expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall); if (!this.hasLineTerminator && this.lookahead.type === 7 /* Punctuator */) { if (this.match('++') || this.match('--')) { if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { this.tolerateError(messages_1.Messages.StrictLHSPostfix); } if (!this.context.isAssignmentTarget) { this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); } this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var operator = this.nextToken().value; var prefix = false; expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix)); } } } return expr; }; // https://tc39.github.io/ecma262/#sec-unary-operators Parser.prototype.parseAwaitExpression = function () { var node = this.createNode(); this.nextToken(); var argument = this.parseUnaryExpression(); return this.finalize(node, new Node.AwaitExpression(argument)); }; Parser.prototype.parseUnaryExpression = function () { var expr; if (this.match('+') || this.match('-') || this.match('~') || this.match('!') || this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) { var node = this.startNode(this.lookahead); var token = this.nextToken(); expr = this.inheritCoverGrammar(this.parseUnaryExpression); expr = this.finalize(node, new Node.UnaryExpression(token.value, expr)); if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) { this.tolerateError(messages_1.Messages.StrictDelete); } this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } else if (this.context.await && this.matchContextualKeyword('await')) { expr = this.parseAwaitExpression(); } else { expr = this.parseUpdateExpression(); } return expr; }; Parser.prototype.parseExponentiationExpression = function () { var startToken = this.lookahead; var expr = this.inheritCoverGrammar(this.parseUnaryExpression); if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) { this.nextToken(); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var left = expr; var right = this.isolateCoverGrammar(this.parseExponentiationExpression); expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right)); } return expr; }; // https://tc39.github.io/ecma262/#sec-exp-operator // https://tc39.github.io/ecma262/#sec-multiplicative-operators // https://tc39.github.io/ecma262/#sec-additive-operators // https://tc39.github.io/ecma262/#sec-bitwise-shift-operators // https://tc39.github.io/ecma262/#sec-relational-operators // https://tc39.github.io/ecma262/#sec-equality-operators // https://tc39.github.io/ecma262/#sec-binary-bitwise-operators // https://tc39.github.io/ecma262/#sec-binary-logical-operators Parser.prototype.binaryPrecedence = function (token) { var op = token.value; var precedence; if (token.type === 7 /* Punctuator */) { precedence = this.operatorPrecedence[op] || 0; } else if (token.type === 4 /* Keyword */) { precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0; } else { precedence = 0; } return precedence; }; Parser.prototype.parseBinaryExpression = function () { var startToken = this.lookahead; var expr = this.inheritCoverGrammar(this.parseExponentiationExpression); var token = this.lookahead; var prec = this.binaryPrecedence(token); if (prec > 0) { this.nextToken(); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var markers = [startToken, this.lookahead]; var left = expr; var right = this.isolateCoverGrammar(this.parseExponentiationExpression); var stack = [left, token.value, right]; var precedences = [prec]; while (true) { prec = this.binaryPrecedence(this.lookahead); if (prec <= 0) { break; } // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= precedences[precedences.length - 1])) { right = stack.pop(); var operator = stack.pop(); precedences.pop(); left = stack.pop(); markers.pop(); var node = this.startNode(markers[markers.length - 1]); stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right))); } // Shift. stack.push(this.nextToken().value); precedences.push(prec); markers.push(this.lookahead); stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression)); } // Final reduce to clean-up the stack. var i = stack.length - 1; expr = stack[i]; var lastMarker = markers.pop(); while (i > 1) { var marker = markers.pop(); var lastLineStart = lastMarker && lastMarker.lineStart; var node = this.startNode(marker, lastLineStart); var operator = stack[i - 1]; expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr)); i -= 2; lastMarker = marker; } } return expr; }; // https://tc39.github.io/ecma262/#sec-conditional-operator Parser.prototype.parseConditionalExpression = function () { var startToken = this.lookahead; var expr = this.inheritCoverGrammar(this.parseBinaryExpression); if (this.match('?')) { this.nextToken(); var previousAllowIn = this.context.allowIn; this.context.allowIn = true; var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression); this.context.allowIn = previousAllowIn; this.expect(':'); var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression); expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate)); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } return expr; }; // https://tc39.github.io/ecma262/#sec-assignment-operators Parser.prototype.checkPatternParam = function (options, param) { switch (param.type) { case syntax_1.Syntax.Identifier: this.validateParam(options, param, param.name); break; case syntax_1.Syntax.RestElement: this.checkPatternParam(options, param.argument); break; case syntax_1.Syntax.AssignmentPattern: this.checkPatternParam(options, param.left); break; case syntax_1.Syntax.ArrayPattern: for (var i = 0; i < param.elements.length; i++) { if (param.elements[i] !== null) { this.checkPatternParam(options, param.elements[i]); } } break; case syntax_1.Syntax.ObjectPattern: for (var i = 0; i < param.properties.length; i++) { this.checkPatternParam(options, param.properties[i].value); } break; default: break; } options.simple = options.simple && (param instanceof Node.Identifier); }; Parser.prototype.reinterpretAsCoverFormalsList = function (expr) { var params = [expr]; var options; var asyncArrow = false; switch (expr.type) { case syntax_1.Syntax.Identifier: break; case ArrowParameterPlaceHolder: params = expr.params; asyncArrow = expr.async; break; default: return null; } options = { simple: true, paramSet: {} }; for (var i = 0; i < params.length; ++i) { var param = params[i]; if (param.type === syntax_1.Syntax.AssignmentPattern) { if (param.right.type === syntax_1.Syntax.YieldExpression) { if (param.right.argument) { this.throwUnexpectedToken(this.lookahead); } param.right.type = syntax_1.Syntax.Identifier; param.right.name = 'yield'; delete param.right.argument; delete param.right.delegate; } } else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') { this.throwUnexpectedToken(this.lookahead); } this.checkPatternParam(options, param); params[i] = param; } if (this.context.strict || !this.context.allowYield) { for (var i = 0; i < params.length; ++i) { var param = params[i]; if (param.type === syntax_1.Syntax.YieldExpression) { this.throwUnexpectedToken(this.lookahead); } } } if (options.message === messages_1.Messages.StrictParamDupe) { var token = this.context.strict ? options.stricted : options.firstRestricted; this.throwUnexpectedToken(token, options.message); } return { simple: options.simple, params: params, stricted: options.stricted, firstRestricted: options.firstRestricted, message: options.message }; }; Parser.prototype.parseAssignmentExpression = function () { var expr; if (!this.context.allowYield && this.matchKeyword('yield')) { expr = this.parseYieldExpression(); } else { var startToken = this.lookahead; var token = startToken; expr = this.parseConditionalExpression(); if (token.type === 3 /* Identifier */ && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async') { if (this.lookahead.type === 3 /* Identifier */ || this.matchKeyword('yield')) { var arg = this.parsePrimaryExpression(); this.reinterpretExpressionAsPattern(arg); expr = { type: ArrowParameterPlaceHolder, params: [arg], async: true }; } } if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) { // https://tc39.github.io/ecma262/#sec-arrow-function-definitions this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var isAsync = expr.async; var list = this.reinterpretAsCoverFormalsList(expr); if (list) { if (this.hasLineTerminator) { this.tolerateUnexpectedToken(this.lookahead); } this.context.firstCoverInitializedNameError = null; var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = list.simple; var previousAllowYield = this.context.allowYield; var previousAwait = this.context.await; this.context.allowYield = true; this.context.await = isAsync; var node = this.startNode(startToken); this.expect('=>'); var body = void 0; if (this.match('{')) { var previousAllowIn = this.context.allowIn; this.context.allowIn = true; body = this.parseFunctionSourceElements(); this.context.allowIn = previousAllowIn; } else { body = this.isolateCoverGrammar(this.parseAssignmentExpression); } var expression = body.type !== syntax_1.Syntax.BlockStatement; if (this.context.strict && list.firstRestricted) { this.throwUnexpectedToken(list.firstRestricted, list.message); } if (this.context.strict && list.stricted) { this.tolerateUnexpectedToken(list.stricted, list.message); } expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) : this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression)); this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; this.context.allowYield = previousAllowYield; this.context.await = previousAwait; } } else { if (this.matchAssign()) { if (!this.context.isAssignmentTarget) { this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); } if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) { var id = expr; if (this.scanner.isRestrictedWord(id.name)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment); } if (this.scanner.isStrictModeReservedWord(id.name)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); } } if (!this.match('=')) { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } else { this.reinterpretExpressionAsPattern(expr); } token = this.nextToken(); var operator = token.value; var right = this.isolateCoverGrammar(this.parseAssignmentExpression); expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right)); this.context.firstCoverInitializedNameError = null; } } } return expr; }; // https://tc39.github.io/ecma262/#sec-comma-operator Parser.prototype.parseExpression = function () { var startToken = this.lookahead; var expr = this.isolateCoverGrammar(this.parseAssignmentExpression); if (this.match(',')) { var expressions = []; expressions.push(expr); while (this.lookahead.type !== 2 /* EOF */) { if (!this.match(',')) { break; } this.nextToken(); expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); } expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); } return expr; }; // https://tc39.github.io/ecma262/#sec-block Parser.prototype.parseStatementListItem = function () { var statement; this.context.isAssignmentTarget = true; this.context.isBindingElement = true; if (this.lookahead.type === 4 /* Keyword */) { switch (this.lookahead.value) { case 'export': if (!this.context.isModule) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration); } statement = this.parseExportDeclaration(); break; case 'import': if (!this.context.isModule) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration); } statement = this.parseImportDeclaration(); break; case 'const': statement = this.parseLexicalDeclaration({ inFor: false }); break; case 'function': statement = this.parseFunctionDeclaration(); break; case 'class': statement = this.parseClassDeclaration(); break; case 'let': statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement(); break; default: statement = this.parseStatement(); break; } } else { statement = this.parseStatement(); } return statement; }; Parser.prototype.parseBlock = function () { var node = this.createNode(); this.expect('{'); var block = []; while (true) { if (this.match('}')) { break; } block.push(this.parseStatementListItem()); } this.expect('}'); return this.finalize(node, new Node.BlockStatement(block)); }; // https://tc39.github.io/ecma262/#sec-let-and-const-declarations Parser.prototype.parseLexicalBinding = function (kind, options) { var node = this.createNode(); var params = []; var id = this.parsePattern(params, kind); if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { if (this.scanner.isRestrictedWord(id.name)) { this.tolerateError(messages_1.Messages.StrictVarName); } } var init = null; if (kind === 'const') { if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) { if (this.match('=')) { this.nextToken(); init = this.isolateCoverGrammar(this.parseAssignmentExpression); } else { this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const'); } } } else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) { this.expect('='); init = this.isolateCoverGrammar(this.parseAssignmentExpression); } return this.finalize(node, new Node.VariableDeclarator(id, init)); }; Parser.prototype.parseBindingList = function (kind, options) { var list = [this.parseLexicalBinding(kind, options)]; while (this.match(',')) { this.nextToken(); list.push(this.parseLexicalBinding(kind, options)); } return list; }; Parser.prototype.isLexicalDeclaration = function () { var state = this.scanner.saveState(); this.scanner.scanComments(); var next = this.scanner.lex(); this.scanner.restoreState(state); return (next.type === 3 /* Identifier */) || (next.type === 7 /* Punctuator */ && next.value === '[') || (next.type === 7 /* Punctuator */ && next.value === '{') || (next.type === 4 /* Keyword */ && next.value === 'let') || (next.type === 4 /* Keyword */ && next.value === 'yield'); }; Parser.prototype.parseLexicalDeclaration = function (options) { var node = this.createNode(); var kind = this.nextToken().value; assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const'); var declarations = this.parseBindingList(kind, options); this.consumeSemicolon(); return this.finalize(node, new Node.VariableDeclaration(declarations, kind)); }; // https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns Parser.prototype.parseBindingRestElement = function (params, kind) { var node = this.createNode(); this.expect('...'); var arg = this.parsePattern(params, kind); return this.finalize(node, new Node.RestElement(arg)); }; Parser.prototype.parseArrayPattern = function (params, kind) { var node = this.createNode(); this.expect('['); var elements = []; while (!this.match(']')) { if (this.match(',')) { this.nextToken(); elements.push(null); } else { if (this.match('...')) { elements.push(this.parseBindingRestElement(params, kind)); break; } else { elements.push(this.parsePatternWithDefault(params, kind)); } if (!this.match(']')) { this.expect(','); } } } this.expect(']'); return this.finalize(node, new Node.ArrayPattern(elements)); }; Parser.prototype.parsePropertyPattern = function (params, kind) { var node = this.createNode(); var computed = false; var shorthand = false; var method = false; var key; var value; if (this.lookahead.type === 3 /* Identifier */) { var keyToken = this.lookahead; key = this.parseVariableIdentifier(); var init = this.finalize(node, new Node.Identifier(keyToken.value)); if (this.match('=')) { params.push(keyToken); shorthand = true; this.nextToken(); var expr = this.parseAssignmentExpression(); value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr)); } else if (!this.match(':')) { params.push(keyToken); shorthand = true; value = init; } else { this.expect(':'); value = this.parsePatternWithDefault(params, kind); } } else { computed = this.match('['); key = this.parseObjectPropertyKey(); this.expect(':'); value = this.parsePatternWithDefault(params, kind); } return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand)); }; Parser.prototype.parseObjectPattern = function (params, kind) { var node = this.createNode(); var properties = []; this.expect('{'); while (!this.match('}')) { properties.push(this.parsePropertyPattern(params, kind)); if (!this.match('}')) { this.expect(','); } } this.expect('}'); return this.finalize(node, new Node.ObjectPattern(properties)); }; Parser.prototype.parsePattern = function (params, kind) { var pattern; if (this.match('[')) { pattern = this.parseArrayPattern(params, kind); } else if (this.match('{')) { pattern = this.parseObjectPattern(params, kind); } else { if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding); } params.push(this.lookahead); pattern = this.parseVariableIdentifier(kind); } return pattern; }; Parser.prototype.parsePatternWithDefault = function (params, kind) { var startToken = this.lookahead; var pattern = this.parsePattern(params, kind); if (this.match('=')) { this.nextToken(); var previousAllowYield = this.context.allowYield; this.context.allowYield = true; var right = this.isolateCoverGrammar(this.parseAssignmentExpression); this.context.allowYield = previousAllowYield; pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right)); } return pattern; }; // https://tc39.github.io/ecma262/#sec-variable-statement Parser.prototype.parseVariableIdentifier = function (kind) { var node = this.createNode(); var token = this.nextToken(); if (token.type === 4 /* Keyword */ && token.value === 'yield') { if (this.context.strict) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); } else if (!this.context.allowYield) { this.throwUnexpectedToken(token); } } else if (token.type !== 3 /* Identifier */) { if (this.context.strict && token.type === 4 /* Keyword */ && this.scanner.isStrictModeReservedWord(token.value)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); } else { if (this.context.strict || token.value !== 'let' || kind !== 'var') { this.throwUnexpectedToken(token); } } } else if ((this.context.isModule || this.context.await) && token.type === 3 /* Identifier */ && token.value === 'await') { this.tolerateUnexpectedToken(token); } return this.finalize(node, new Node.Identifier(token.value)); }; Parser.prototype.parseVariableDeclaration = function (options) { var node = this.createNode(); var params = []; var id = this.parsePattern(params, 'var'); if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { if (this.scanner.isRestrictedWord(id.name)) { this.tolerateError(messages_1.Messages.StrictVarName); } } var init = null; if (this.match('=')) { this.nextToken(); init = this.isolateCoverGrammar(this.parseAssignmentExpression); } else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) { this.expect('='); } return this.finalize(node, new Node.VariableDeclarator(id, init)); }; Parser.prototype.parseVariableDeclarationList = function (options) { var opt = { inFor: options.inFor }; var list = []; list.push(this.parseVariableDeclaration(opt)); while (this.match(',')) { this.nextToken(); list.push(this.parseVariableDeclaration(opt)); } return list; }; Parser.prototype.parseVariableStatement = function () { var node = this.createNode(); this.expectKeyword('var'); var declarations = this.parseVariableDeclarationList({ inFor: false }); this.consumeSemicolon(); return this.finalize(node, new Node.VariableDeclaration(declarations, 'var')); }; // https://tc39.github.io/ecma262/#sec-empty-statement Parser.prototype.parseEmptyStatement = function () { var node = this.createNode(); this.expect(';'); return this.finalize(node, new Node.EmptyStatement()); }; // https://tc39.github.io/ecma262/#sec-expression-statement Parser.prototype.parseExpressionStatement = function () { var node = this.createNode(); var expr = this.parseExpression(); this.consumeSemicolon(); return this.finalize(node, new Node.ExpressionStatement(expr)); }; // https://tc39.github.io/ecma262/#sec-if-statement Parser.prototype.parseIfClause = function () { if (this.context.strict && this.matchKeyword('function')) { this.tolerateError(messages_1.Messages.StrictFunction); } return this.parseStatement(); }; Parser.prototype.parseIfStatement = function () { var node = this.createNode(); var consequent; var alternate = null; this.expectKeyword('if'); this.expect('('); var test = this.parseExpression(); if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); consequent = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(')'); consequent = this.parseIfClause(); if (this.matchKeyword('else')) { this.nextToken(); alternate = this.parseIfClause(); } } return this.finalize(node, new Node.IfStatement(test, consequent, alternate)); }; // https://tc39.github.io/ecma262/#sec-do-while-statement Parser.prototype.parseDoWhileStatement = function () { var node = this.createNode(); this.expectKeyword('do'); var previousInIteration = this.context.inIteration; this.context.inIteration = true; var body = this.parseStatement(); this.context.inIteration = previousInIteration; this.expectKeyword('while'); this.expect('('); var test = this.parseExpression(); if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); } else { this.expect(')'); if (this.match(';')) { this.nextToken(); } } return this.finalize(node, new Node.DoWhileStatement(body, test)); }; // https://tc39.github.io/ecma262/#sec-while-statement Parser.prototype.parseWhileStatement = function () { var node = this.createNode(); var body; this.expectKeyword('while'); this.expect('('); var test = this.parseExpression(); if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); body = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(')'); var previousInIteration = this.context.inIteration; this.context.inIteration = true; body = this.parseStatement(); this.context.inIteration = previousInIteration; } return this.finalize(node, new Node.WhileStatement(test, body)); }; // https://tc39.github.io/ecma262/#sec-for-statement // https://tc39.github.io/ecma262/#sec-for-in-and-for-of-statements Parser.prototype.parseForStatement = function () { var init = null; var test = null; var update = null; var forIn = true; var left, right; var node = this.createNode(); this.expectKeyword('for'); this.expect('('); if (this.match(';')) { this.nextToken(); } else { if (this.matchKeyword('var')) { init = this.createNode(); this.nextToken(); var previousAllowIn = this.context.allowIn; this.context.allowIn = false; var declarations = this.parseVariableDeclarationList({ inFor: true }); this.context.allowIn = previousAllowIn; if (declarations.length === 1 && this.matchKeyword('in')) { var decl = declarations[0]; if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) { this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in'); } init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); this.nextToken(); left = init; right = this.parseExpression(); init = null; } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); this.nextToken(); left = init; right = this.parseAssignmentExpression(); init = null; forIn = false; } else { init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); this.expect(';'); } } else if (this.matchKeyword('const') || this.matchKeyword('let')) { init = this.createNode(); var kind = this.nextToken().value; if (!this.context.strict && this.lookahead.value === 'in') { init = this.finalize(init, new Node.Identifier(kind)); this.nextToken(); left = init; right = this.parseExpression(); init = null; } else { var previousAllowIn = this.context.allowIn; this.context.allowIn = false; var declarations = this.parseBindingList(kind, { inFor: true }); this.context.allowIn = previousAllowIn; if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) { init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); this.nextToken(); left = init; right = this.parseExpression(); init = null; } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); this.nextToken(); left = init; right = this.parseAssignmentExpression(); init = null; forIn = false; } else { this.consumeSemicolon(); init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); } } } else { var initStartToken = this.lookahead; var previousAllowIn = this.context.allowIn; this.context.allowIn = false; init = this.inheritCoverGrammar(this.parseAssignmentExpression); this.context.allowIn = previousAllowIn; if (this.matchKeyword('in')) { if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { this.tolerateError(messages_1.Messages.InvalidLHSInForIn); } this.nextToken(); this.reinterpretExpressionAsPattern(init); left = init; right = this.parseExpression(); init = null; } else if (this.matchContextualKeyword('of')) { if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { this.tolerateError(messages_1.Messages.InvalidLHSInForLoop); } this.nextToken(); this.reinterpretExpressionAsPattern(init); left = init; right = this.parseAssignmentExpression(); init = null; forIn = false; } else { if (this.match(',')) { var initSeq = [init]; while (this.match(',')) { this.nextToken(); initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); } init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq)); } this.expect(';'); } } } if (typeof left === 'undefined') { if (!this.match(';')) { test = this.parseExpression(); } this.expect(';'); if (!this.match(')')) { update = this.parseExpression(); } } var body; if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); body = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(')'); var previousInIteration = this.context.inIteration; this.context.inIteration = true; body = this.isolateCoverGrammar(this.parseStatement); this.context.inIteration = previousInIteration; } return (typeof left === 'undefined') ? this.finalize(node, new Node.ForStatement(init, test, update, body)) : forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) : this.finalize(node, new Node.ForOfStatement(left, right, body)); }; // https://tc39.github.io/ecma262/#sec-continue-statement Parser.prototype.parseContinueStatement = function () { var node = this.createNode(); this.expectKeyword('continue'); var label = null; if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { var id = this.parseVariableIdentifier(); label = id; var key = '$' + id.name; if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { this.throwError(messages_1.Messages.UnknownLabel, id.name); } } this.consumeSemicolon(); if (label === null && !this.context.inIteration) { this.throwError(messages_1.Messages.IllegalContinue); } return this.finalize(node, new Node.ContinueStatement(label)); }; // https://tc39.github.io/ecma262/#sec-break-statement Parser.prototype.parseBreakStatement = function () { var node = this.createNode(); this.expectKeyword('break'); var label = null; if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { var id = this.parseVariableIdentifier(); var key = '$' + id.name; if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { this.throwError(messages_1.Messages.UnknownLabel, id.name); } label = id; } this.consumeSemicolon(); if (label === null && !this.context.inIteration && !this.context.inSwitch) { this.throwError(messages_1.Messages.IllegalBreak); } return this.finalize(node, new Node.BreakStatement(label)); }; // https://tc39.github.io/ecma262/#sec-return-statement Parser.prototype.parseReturnStatement = function () { if (!this.context.inFunctionBody) { this.tolerateError(messages_1.Messages.IllegalReturn); } var node = this.createNode(); this.expectKeyword('return'); var hasArgument = (!this.match(';') && !this.match('}') && !this.hasLineTerminator && this.lookahead.type !== 2 /* EOF */) || this.lookahead.type === 8 /* StringLiteral */ || this.lookahead.type === 10 /* Template */; var argument = hasArgument ? this.parseExpression() : null; this.consumeSemicolon(); return this.finalize(node, new Node.ReturnStatement(argument)); }; // https://tc39.github.io/ecma262/#sec-with-statement Parser.prototype.parseWithStatement = function () { if (this.context.strict) { this.tolerateError(messages_1.Messages.StrictModeWith); } var node = this.createNode(); var body; this.expectKeyword('with'); this.expect('('); var object = this.parseExpression(); if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); body = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(')'); body = this.parseStatement(); } return this.finalize(node, new Node.WithStatement(object, body)); }; // https://tc39.github.io/ecma262/#sec-switch-statement Parser.prototype.parseSwitchCase = function () { var node = this.createNode(); var test; if (this.matchKeyword('default')) { this.nextToken(); test = null; } else { this.expectKeyword('case'); test = this.parseExpression(); } this.expect(':'); var consequent = []; while (true) { if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) { break; } consequent.push(this.parseStatementListItem()); } return this.finalize(node, new Node.SwitchCase(test, consequent)); }; Parser.prototype.parseSwitchStatement = function () { var node = this.createNode(); this.expectKeyword('switch'); this.expect('('); var discriminant = this.parseExpression(); this.expect(')'); var previousInSwitch = this.context.inSwitch; this.context.inSwitch = true; var cases = []; var defaultFound = false; this.expect('{'); while (true) { if (this.match('}')) { break; } var clause = this.parseSwitchCase(); if (clause.test === null) { if (defaultFound) { this.throwError(messages_1.Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } this.expect('}'); this.context.inSwitch = previousInSwitch; return this.finalize(node, new Node.SwitchStatement(discriminant, cases)); }; // https://tc39.github.io/ecma262/#sec-labelled-statements Parser.prototype.parseLabelledStatement = function () { var node = this.createNode(); var expr = this.parseExpression(); var statement; if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) { this.nextToken(); var id = expr; var key = '$' + id.name; if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name); } this.context.labelSet[key] = true; var body = void 0; if (this.matchKeyword('class')) { this.tolerateUnexpectedToken(this.lookahead); body = this.parseClassDeclaration(); } else if (this.matchKeyword('function')) { var token = this.lookahead; var declaration = this.parseFunctionDeclaration(); if (this.context.strict) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction); } else if (declaration.generator) { this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext); } body = declaration; } else { body = this.parseStatement(); } delete this.context.labelSet[key]; statement = new Node.LabeledStatement(id, body); } else { this.consumeSemicolon(); statement = new Node.ExpressionStatement(expr); } return this.finalize(node, statement); }; // https://tc39.github.io/ecma262/#sec-throw-statement Parser.prototype.parseThrowStatement = function () { var node = this.createNode(); this.expectKeyword('throw'); if (this.hasLineTerminator) { this.throwError(messages_1.Messages.NewlineAfterThrow); } var argument = this.parseExpression(); this.consumeSemicolon(); return this.finalize(node, new Node.ThrowStatement(argument)); }; // https://tc39.github.io/ecma262/#sec-try-statement Parser.prototype.parseCatchClause = function () { var node = this.createNode(); this.expectKeyword('catch'); this.expect('('); if (this.match(')')) { this.throwUnexpectedToken(this.lookahead); } var params = []; var param = this.parsePattern(params); var paramMap = {}; for (var i = 0; i < params.length; i++) { var key = '$' + params[i].value; if (Object.prototype.hasOwnProperty.call(paramMap, key)) { this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value); } paramMap[key] = true; } if (this.context.strict && param.type === syntax_1.Syntax.Identifier) { if (this.scanner.isRestrictedWord(param.name)) { this.tolerateError(messages_1.Messages.StrictCatchVariable); } } this.expect(')'); var body = this.parseBlock(); return this.finalize(node, new Node.CatchClause(param, body)); }; Parser.prototype.parseFinallyClause = function () { this.expectKeyword('finally'); return this.parseBlock(); }; Parser.prototype.parseTryStatement = function () { var node = this.createNode(); this.expectKeyword('try'); var block = this.parseBlock(); var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null; var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null; if (!handler && !finalizer) { this.throwError(messages_1.Messages.NoCatchOrFinally); } return this.finalize(node, new Node.TryStatement(block, handler, finalizer)); }; // https://tc39.github.io/ecma262/#sec-debugger-statement Parser.prototype.parseDebuggerStatement = function () { var node = this.createNode(); this.expectKeyword('debugger'); this.consumeSemicolon(); return this.finalize(node, new Node.DebuggerStatement()); }; // https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations Parser.prototype.parseStatement = function () { var statement; switch (this.lookahead.type) { case 1 /* BooleanLiteral */: case 5 /* NullLiteral */: case 6 /* NumericLiteral */: case 8 /* StringLiteral */: case 10 /* Template */: case 9 /* RegularExpression */: statement = this.parseExpressionStatement(); break; case 7 /* Punctuator */: var value = this.lookahead.value; if (value === '{') { statement = this.parseBlock(); } else if (value === '(') { statement = this.parseExpressionStatement(); } else if (value === ';') { statement = this.parseEmptyStatement(); } else { statement = this.parseExpressionStatement(); } break; case 3 /* Identifier */: statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement(); break; case 4 /* Keyword */: switch (this.lookahead.value) { case 'break': statement = this.parseBreakStatement(); break; case 'continue': statement = this.parseContinueStatement(); break; case 'debugger': statement = this.parseDebuggerStatement(); break; case 'do': statement = this.parseDoWhileStatement(); break; case 'for': statement = this.parseForStatement(); break; case 'function': statement = this.parseFunctionDeclaration(); break; case 'if': statement = this.parseIfStatement(); break; case 'return': statement = this.parseReturnStatement(); break; case 'switch': statement = this.parseSwitchStatement(); break; case 'throw': statement = this.parseThrowStatement(); break; case 'try': statement = this.parseTryStatement(); break; case 'var': statement = this.parseVariableStatement(); break; case 'while': statement = this.parseWhileStatement(); break; case 'with': statement = this.parseWithStatement(); break; default: statement = this.parseExpressionStatement(); break; } break; default: statement = this.throwUnexpectedToken(this.lookahead); } return statement; }; // https://tc39.github.io/ecma262/#sec-function-definitions Parser.prototype.parseFunctionSourceElements = function () { var node = this.createNode(); this.expect('{'); var body = this.parseDirectivePrologues(); var previousLabelSet = this.context.labelSet; var previousInIteration = this.context.inIteration; var previousInSwitch = this.context.inSwitch; var previousInFunctionBody = this.context.inFunctionBody; this.context.labelSet = {}; this.context.inIteration = false; this.context.inSwitch = false; this.context.inFunctionBody = true; while (this.lookahead.type !== 2 /* EOF */) { if (this.match('}')) { break; } body.push(this.parseStatementListItem()); } this.expect('}'); this.context.labelSet = previousLabelSet; this.context.inIteration = previousInIteration; this.context.inSwitch = previousInSwitch; this.context.inFunctionBody = previousInFunctionBody; return this.finalize(node, new Node.BlockStatement(body)); }; Parser.prototype.validateParam = function (options, param, name) { var key = '$' + name; if (this.context.strict) { if (this.scanner.isRestrictedWord(name)) { options.stricted = param; options.message = messages_1.Messages.StrictParamName; } if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.stricted = param; options.message = messages_1.Messages.StrictParamDupe; } } else if (!options.firstRestricted) { if (this.scanner.isRestrictedWord(name)) { options.firstRestricted = param; options.message = messages_1.Messages.StrictParamName; } else if (this.scanner.isStrictModeReservedWord(name)) { options.firstRestricted = param; options.message = messages_1.Messages.StrictReservedWord; } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.stricted = param; options.message = messages_1.Messages.StrictParamDupe; } } /* istanbul ignore next */ if (typeof Object.defineProperty === 'function') { Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true }); } else { options.paramSet[key] = true; } }; Parser.prototype.parseRestElement = function (params) { var node = this.createNode(); this.expect('...'); var arg = this.parsePattern(params); if (this.match('=')) { this.throwError(messages_1.Messages.DefaultRestParameter); } if (!this.match(')')) { this.throwError(messages_1.Messages.ParameterAfterRestParameter); } return this.finalize(node, new Node.RestElement(arg)); }; Parser.prototype.parseFormalParameter = function (options) { var params = []; var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params); for (var i = 0; i < params.length; i++) { this.validateParam(options, params[i], params[i].value); } options.simple = options.simple && (param instanceof Node.Identifier); options.params.push(param); }; Parser.prototype.parseFormalParameters = function (firstRestricted) { var options; options = { simple: true, params: [], firstRestricted: firstRestricted }; this.expect('('); if (!this.match(')')) { options.paramSet = {}; while (this.lookahead.type !== 2 /* EOF */) { this.parseFormalParameter(options); if (this.match(')')) { break; } this.expect(','); if (this.match(')')) { break; } } } this.expect(')'); return { simple: options.simple, params: options.params, stricted: options.stricted, firstRestricted: options.firstRestricted, message: options.message }; }; Parser.prototype.matchAsyncFunction = function () { var match = this.matchContextualKeyword('async'); if (match) { var state = this.scanner.saveState(); this.scanner.scanComments(); var next = this.scanner.lex(); this.scanner.restoreState(state); match = (state.lineNumber === next.lineNumber) && (next.type === 4 /* Keyword */) && (next.value === 'function'); } return match; }; Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) { var node = this.createNode(); var isAsync = this.matchContextualKeyword('async'); if (isAsync) { this.nextToken(); } this.expectKeyword('function'); var isGenerator = isAsync ? false : this.match('*'); if (isGenerator) { this.nextToken(); } var message; var id = null; var firstRestricted = null; if (!identifierIsOptional || !this.match('(')) { var token = this.lookahead; id = this.parseVariableIdentifier(); if (this.context.strict) { if (this.scanner.isRestrictedWord(token.value)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); } } else { if (this.scanner.isRestrictedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictFunctionName; } else if (this.scanner.isStrictModeReservedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictReservedWord; } } } var previousAllowAwait = this.context.await; var previousAllowYield = this.context.allowYield; this.context.await = isAsync; this.context.allowYield = !isGenerator; var formalParameters = this.parseFormalParameters(firstRestricted); var params = formalParameters.params; var stricted = formalParameters.stricted; firstRestricted = formalParameters.firstRestricted; if (formalParameters.message) { message = formalParameters.message; } var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = formalParameters.simple; var body = this.parseFunctionSourceElements(); if (this.context.strict && firstRestricted) { this.throwUnexpectedToken(firstRestricted, message); } if (this.context.strict && stricted) { this.tolerateUnexpectedToken(stricted, message); } this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; this.context.await = previousAllowAwait; this.context.allowYield = previousAllowYield; return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) : this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator)); }; Parser.prototype.parseFunctionExpression = function () { var node = this.createNode(); var isAsync = this.matchContextualKeyword('async'); if (isAsync) { this.nextToken(); } this.expectKeyword('function'); var isGenerator = isAsync ? false : this.match('*'); if (isGenerator) { this.nextToken(); } var message; var id = null; var firstRestricted; var previousAllowAwait = this.context.await; var previousAllowYield = this.context.allowYield; this.context.await = isAsync; this.context.allowYield = !isGenerator; if (!this.match('(')) { var token = this.lookahead; id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier(); if (this.context.strict) { if (this.scanner.isRestrictedWord(token.value)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); } } else { if (this.scanner.isRestrictedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictFunctionName; } else if (this.scanner.isStrictModeReservedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictReservedWord; } } } var formalParameters = this.parseFormalParameters(firstRestricted); var params = formalParameters.params; var stricted = formalParameters.stricted; firstRestricted = formalParameters.firstRestricted; if (formalParameters.message) { message = formalParameters.message; } var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = formalParameters.simple; var body = this.parseFunctionSourceElements(); if (this.context.strict && firstRestricted) { this.throwUnexpectedToken(firstRestricted, message); } if (this.context.strict && stricted) { this.tolerateUnexpectedToken(stricted, message); } this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; this.context.await = previousAllowAwait; this.context.allowYield = previousAllowYield; return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) : this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator)); }; // https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive Parser.prototype.parseDirective = function () { var token = this.lookahead; var node = this.createNode(); var expr = this.parseExpression(); var directive = (expr.type === syntax_1.Syntax.Literal) ? this.getTokenRaw(token).slice(1, -1) : null; this.consumeSemicolon(); return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr)); }; Parser.prototype.parseDirectivePrologues = function () { var firstRestricted = null; var body = []; while (true) { var token = this.lookahead; if (token.type !== 8 /* StringLiteral */) { break; } var statement = this.parseDirective(); body.push(statement); var directive = statement.directive; if (typeof directive !== 'string') { break; } if (directive === 'use strict') { this.context.strict = true; if (firstRestricted) { this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral); } if (!this.context.allowStrictDirective) { this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } return body; }; // https://tc39.github.io/ecma262/#sec-method-definitions Parser.prototype.qualifiedPropertyName = function (token) { switch (token.type) { case 3 /* Identifier */: case 8 /* StringLiteral */: case 1 /* BooleanLiteral */: case 5 /* NullLiteral */: case 6 /* NumericLiteral */: case 4 /* Keyword */: return true; case 7 /* Punctuator */: return token.value === '['; default: break; } return false; }; Parser.prototype.parseGetterMethod = function () { var node = this.createNode(); var isGenerator = false; var previousAllowYield = this.context.allowYield; this.context.allowYield = !isGenerator; var formalParameters = this.parseFormalParameters(); if (formalParameters.params.length > 0) { this.tolerateError(messages_1.Messages.BadGetterArity); } var method = this.parsePropertyMethod(formalParameters); this.context.allowYield = previousAllowYield; return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); }; Parser.prototype.parseSetterMethod = function () { var node = this.createNode(); var isGenerator = false; var previousAllowYield = this.context.allowYield; this.context.allowYield = !isGenerator; var formalParameters = this.parseFormalParameters(); if (formalParameters.params.length !== 1) { this.tolerateError(messages_1.Messages.BadSetterArity); } else if (formalParameters.params[0] instanceof Node.RestElement) { this.tolerateError(messages_1.Messages.BadSetterRestParameter); } var method = this.parsePropertyMethod(formalParameters); this.context.allowYield = previousAllowYield; return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); }; Parser.prototype.parseGeneratorMethod = function () { var node = this.createNode(); var isGenerator = true; var previousAllowYield = this.context.allowYield; this.context.allowYield = true; var params = this.parseFormalParameters(); this.context.allowYield = false; var method = this.parsePropertyMethod(params); this.context.allowYield = previousAllowYield; return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); }; // https://tc39.github.io/ecma262/#sec-generator-function-definitions Parser.prototype.isStartOfExpression = function () { var start = true; var value = this.lookahead.value; switch (this.lookahead.type) { case 7 /* Punctuator */: start = (value === '[') || (value === '(') || (value === '{') || (value === '+') || (value === '-') || (value === '!') || (value === '~') || (value === '++') || (value === '--') || (value === '/') || (value === '/='); // regular expression literal break; case 4 /* Keyword */: start = (value === 'class') || (value === 'delete') || (value === 'function') || (value === 'let') || (value === 'new') || (value === 'super') || (value === 'this') || (value === 'typeof') || (value === 'void') || (value === 'yield'); break; default: break; } return start; }; Parser.prototype.parseYieldExpression = function () { var node = this.createNode(); this.expectKeyword('yield'); var argument = null; var delegate = false; if (!this.hasLineTerminator) { var previousAllowYield = this.context.allowYield; this.context.allowYield = false; delegate = this.match('*'); if (delegate) { this.nextToken(); argument = this.parseAssignmentExpression(); } else if (this.isStartOfExpression()) { argument = this.parseAssignmentExpression(); } this.context.allowYield = previousAllowYield; } return this.finalize(node, new Node.YieldExpression(argument, delegate)); }; // https://tc39.github.io/ecma262/#sec-class-definitions Parser.prototype.parseClassElement = function (hasConstructor) { var token = this.lookahead; var node = this.createNode(); var kind = ''; var key = null; var value = null; var computed = false; var method = false; var isStatic = false; var isAsync = false; if (this.match('*')) { this.nextToken(); } else { computed = this.match('['); key = this.parseObjectPropertyKey(); var id = key; if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) { token = this.lookahead; isStatic = true; computed = this.match('['); if (this.match('*')) { this.nextToken(); } else { key = this.parseObjectPropertyKey(); } } if ((token.type === 3 /* Identifier */) && !this.hasLineTerminator && (token.value === 'async')) { var punctuator = this.lookahead.value; if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') { isAsync = true; token = this.lookahead; key = this.parseObjectPropertyKey(); if (token.type === 3 /* Identifier */ && token.value === 'constructor') { this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync); } } } } var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); if (token.type === 3 /* Identifier */) { if (token.value === 'get' && lookaheadPropertyKey) { kind = 'get'; computed = this.match('['); key = this.parseObjectPropertyKey(); this.context.allowYield = false; value = this.parseGetterMethod(); } else if (token.value === 'set' && lookaheadPropertyKey) { kind = 'set'; computed = this.match('['); key = this.parseObjectPropertyKey(); value = this.parseSetterMethod(); } } else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { kind = 'init'; computed = this.match('['); key = this.parseObjectPropertyKey(); value = this.parseGeneratorMethod(); method = true; } if (!kind && key && this.match('(')) { kind = 'init'; value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); method = true; } if (!kind) { this.throwUnexpectedToken(this.lookahead); } if (kind === 'init') { kind = 'method'; } if (!computed) { if (isStatic && this.isPropertyKey(key, 'prototype')) { this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype); } if (!isStatic && this.isPropertyKey(key, 'constructor')) { if (kind !== 'method' || !method || (value && value.generator)) { this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod); } if (hasConstructor.value) { this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor); } else { hasConstructor.value = true; } kind = 'constructor'; } } return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic)); }; Parser.prototype.parseClassElementList = function () { var body = []; var hasConstructor = { value: false }; this.expect('{'); while (!this.match('}')) { if (this.match(';')) { this.nextToken(); } else { body.push(this.parseClassElement(hasConstructor)); } } this.expect('}'); return body; }; Parser.prototype.parseClassBody = function () { var node = this.createNode(); var elementList = this.parseClassElementList(); return this.finalize(node, new Node.ClassBody(elementList)); }; Parser.prototype.parseClassDeclaration = function (identifierIsOptional) { var node = this.createNode(); var previousStrict = this.context.strict; this.context.strict = true; this.expectKeyword('class'); var id = (identifierIsOptional && (this.lookahead.type !== 3 /* Identifier */)) ? null : this.parseVariableIdentifier(); var superClass = null; if (this.matchKeyword('extends')) { this.nextToken(); superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); } var classBody = this.parseClassBody(); this.context.strict = previousStrict; return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody)); }; Parser.prototype.parseClassExpression = function () { var node = this.createNode(); var previousStrict = this.context.strict; this.context.strict = true; this.expectKeyword('class'); var id = (this.lookahead.type === 3 /* Identifier */) ? this.parseVariableIdentifier() : null; var superClass = null; if (this.matchKeyword('extends')) { this.nextToken(); superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); } var classBody = this.parseClassBody(); this.context.strict = previousStrict; return this.finalize(node, new Node.ClassExpression(id, superClass, classBody)); }; // https://tc39.github.io/ecma262/#sec-scripts // https://tc39.github.io/ecma262/#sec-modules Parser.prototype.parseModule = function () { this.context.strict = true; this.context.isModule = true; this.scanner.isModule = true; var node = this.createNode(); var body = this.parseDirectivePrologues(); while (this.lookahead.type !== 2 /* EOF */) { body.push(this.parseStatementListItem()); } return this.finalize(node, new Node.Module(body)); }; Parser.prototype.parseScript = function () { var node = this.createNode(); var body = this.parseDirectivePrologues(); while (this.lookahead.type !== 2 /* EOF */) { body.push(this.parseStatementListItem()); } return this.finalize(node, new Node.Script(body)); }; // https://tc39.github.io/ecma262/#sec-imports Parser.prototype.parseModuleSpecifier = function () { var node = this.createNode(); if (this.lookahead.type !== 8 /* StringLiteral */) { this.throwError(messages_1.Messages.InvalidModuleSpecifier); } var token = this.nextToken(); var raw = this.getTokenRaw(token); return this.finalize(node, new Node.Literal(token.value, raw)); }; // import {} ...; Parser.prototype.parseImportSpecifier = function () { var node = this.createNode(); var imported; var local; if (this.lookahead.type === 3 /* Identifier */) { imported = this.parseVariableIdentifier(); local = imported; if (this.matchContextualKeyword('as')) { this.nextToken(); local = this.parseVariableIdentifier(); } } else { imported = this.parseIdentifierName(); local = imported; if (this.matchContextualKeyword('as')) { this.nextToken(); local = this.parseVariableIdentifier(); } else { this.throwUnexpectedToken(this.nextToken()); } } return this.finalize(node, new Node.ImportSpecifier(local, imported)); }; // {foo, bar as bas} Parser.prototype.parseNamedImports = function () { this.expect('{'); var specifiers = []; while (!this.match('}')) { specifiers.push(this.parseImportSpecifier()); if (!this.match('}')) { this.expect(','); } } this.expect('}'); return specifiers; }; // import ...; Parser.prototype.parseImportDefaultSpecifier = function () { var node = this.createNode(); var local = this.parseIdentifierName(); return this.finalize(node, new Node.ImportDefaultSpecifier(local)); }; // import <* as foo> ...; Parser.prototype.parseImportNamespaceSpecifier = function () { var node = this.createNode(); this.expect('*'); if (!this.matchContextualKeyword('as')) { this.throwError(messages_1.Messages.NoAsAfterImportNamespace); } this.nextToken(); var local = this.parseIdentifierName(); return this.finalize(node, new Node.ImportNamespaceSpecifier(local)); }; Parser.prototype.parseImportDeclaration = function () { if (this.context.inFunctionBody) { this.throwError(messages_1.Messages.IllegalImportDeclaration); } var node = this.createNode(); this.expectKeyword('import'); var src; var specifiers = []; if (this.lookahead.type === 8 /* StringLiteral */) { // import 'foo'; src = this.parseModuleSpecifier(); } else { if (this.match('{')) { // import {bar} specifiers = specifiers.concat(this.parseNamedImports()); } else if (this.match('*')) { // import * as foo specifiers.push(this.parseImportNamespaceSpecifier()); } else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) { // import foo specifiers.push(this.parseImportDefaultSpecifier()); if (this.match(',')) { this.nextToken(); if (this.match('*')) { // import foo, * as foo specifiers.push(this.parseImportNamespaceSpecifier()); } else if (this.match('{')) { // import foo, {bar} specifiers = specifiers.concat(this.parseNamedImports()); } else { this.throwUnexpectedToken(this.lookahead); } } } else { this.throwUnexpectedToken(this.nextToken()); } if (!this.matchContextualKeyword('from')) { var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; this.throwError(message, this.lookahead.value); } this.nextToken(); src = this.parseModuleSpecifier(); } this.consumeSemicolon(); return this.finalize(node, new Node.ImportDeclaration(specifiers, src)); }; // https://tc39.github.io/ecma262/#sec-exports Parser.prototype.parseExportSpecifier = function () { var node = this.createNode(); var local = this.parseIdentifierName(); var exported = local; if (this.matchContextualKeyword('as')) { this.nextToken(); exported = this.parseIdentifierName(); } return this.finalize(node, new Node.ExportSpecifier(local, exported)); }; Parser.prototype.parseExportDeclaration = function () { if (this.context.inFunctionBody) { this.throwError(messages_1.Messages.IllegalExportDeclaration); } var node = this.createNode(); this.expectKeyword('export'); var exportDeclaration; if (this.matchKeyword('default')) { // export default ... this.nextToken(); if (this.matchKeyword('function')) { // export default function foo () {} // export default function () {} var declaration = this.parseFunctionDeclaration(true); exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); } else if (this.matchKeyword('class')) { // export default class foo {} var declaration = this.parseClassDeclaration(true); exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); } else if (this.matchContextualKeyword('async')) { // export default async function f () {} // export default async function () {} // export default async x => x var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression(); exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); } else { if (this.matchContextualKeyword('from')) { this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value); } // export default {}; // export default []; // export default (1 + 2); var declaration = this.match('{') ? this.parseObjectInitializer() : this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression(); this.consumeSemicolon(); exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); } } else if (this.match('*')) { // export * from 'foo'; this.nextToken(); if (!this.matchContextualKeyword('from')) { var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; this.throwError(message, this.lookahead.value); } this.nextToken(); var src = this.parseModuleSpecifier(); this.consumeSemicolon(); exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src)); } else if (this.lookahead.type === 4 /* Keyword */) { // export var f = 1; var declaration = void 0; switch (this.lookahead.value) { case 'let': case 'const': declaration = this.parseLexicalDeclaration({ inFor: false }); break; case 'var': case 'class': case 'function': declaration = this.parseStatementListItem(); break; default: this.throwUnexpectedToken(this.lookahead); } exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); } else if (this.matchAsyncFunction()) { var declaration = this.parseFunctionDeclaration(); exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); } else { var specifiers = []; var source = null; var isExportFromIdentifier = false; this.expect('{'); while (!this.match('}')) { isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default'); specifiers.push(this.parseExportSpecifier()); if (!this.match('}')) { this.expect(','); } } this.expect('}'); if (this.matchContextualKeyword('from')) { // export {default} from 'foo'; // export {foo} from 'foo'; this.nextToken(); source = this.parseModuleSpecifier(); this.consumeSemicolon(); } else if (isExportFromIdentifier) { // export {default}; // missing fromClause var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; this.throwError(message, this.lookahead.value); } else { // export {foo}; this.consumeSemicolon(); } exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source)); } return exportDeclaration; }; return Parser; }()); exports.Parser = Parser; /***/ }, /* 9 */ /***/ function(module, exports) { "use strict"; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. Object.defineProperty(exports, "__esModule", { value: true }); function assert(condition, message) { /* istanbul ignore if */ if (!condition) { throw new Error('ASSERT: ' + message); } } exports.assert = assert; /***/ }, /* 10 */ /***/ function(module, exports) { "use strict"; /* tslint:disable:max-classes-per-file */ Object.defineProperty(exports, "__esModule", { value: true }); var ErrorHandler = (function () { function ErrorHandler() { this.errors = []; this.tolerant = false; } ErrorHandler.prototype.recordError = function (error) { this.errors.push(error); }; ErrorHandler.prototype.tolerate = function (error) { if (this.tolerant) { this.recordError(error); } else { throw error; } }; ErrorHandler.prototype.constructError = function (msg, column) { var error = new Error(msg); try { throw error; } catch (base) { /* istanbul ignore else */ if (Object.create && Object.defineProperty) { error = Object.create(base); Object.defineProperty(error, 'column', { value: column }); } } /* istanbul ignore next */ return error; }; ErrorHandler.prototype.createError = function (index, line, col, description) { var msg = 'Line ' + line + ': ' + description; var error = this.constructError(msg, col); error.index = index; error.lineNumber = line; error.description = description; return error; }; ErrorHandler.prototype.throwError = function (index, line, col, description) { throw this.createError(index, line, col, description); }; ErrorHandler.prototype.tolerateError = function (index, line, col, description) { var error = this.createError(index, line, col, description); if (this.tolerant) { this.recordError(error); } else { throw error; } }; return ErrorHandler; }()); exports.ErrorHandler = ErrorHandler; /***/ }, /* 11 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // Error messages should be identical to V8. exports.Messages = { BadGetterArity: 'Getter must not have any formal parameters', BadSetterArity: 'Setter must have exactly one formal parameter', BadSetterRestParameter: 'Setter function argument must not be a rest parameter', ConstructorIsAsync: 'Class constructor may not be an async method', ConstructorSpecialMethod: 'Class constructor may not be an accessor', DeclarationMissingInitializer: 'Missing initializer in %0 declaration', DefaultRestParameter: 'Unexpected token =', DuplicateBinding: 'Duplicate binding %0', DuplicateConstructor: 'A class may only have one constructor', DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals', ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer', GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts', IllegalBreak: 'Illegal break statement', IllegalContinue: 'Illegal continue statement', IllegalExportDeclaration: 'Unexpected token', IllegalImportDeclaration: 'Unexpected token', IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list', IllegalReturn: 'Illegal return statement', InvalidEscapedReservedWord: 'Keyword must not contain escaped characters', InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence', InvalidLHSInAssignment: 'Invalid left-hand side in assignment', InvalidLHSInForIn: 'Invalid left-hand side in for-in', InvalidLHSInForLoop: 'Invalid left-hand side in for-loop', InvalidModuleSpecifier: 'Unexpected token', InvalidRegExp: 'Invalid regular expression', LetInLexicalBinding: 'let is disallowed as a lexically bound name', MissingFromClause: 'Unexpected token', MultipleDefaultsInSwitch: 'More than one default clause in switch statement', NewlineAfterThrow: 'Illegal newline after throw', NoAsAfterImportNamespace: 'Unexpected token', NoCatchOrFinally: 'Missing catch or finally after try', ParameterAfterRestParameter: 'Rest parameter must be last formal parameter', Redeclaration: '%0 \'%1\' has already been declared', StaticPrototype: 'Classes may not have static property named prototype', StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', StrictDelete: 'Delete of an unqualified identifier in strict mode.', StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block', StrictFunctionName: 'Function name may not be eval or arguments in strict mode', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictModeWith: 'Strict mode code may not include a with statement', StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', StrictParamDupe: 'Strict mode function may not have duplicate parameter names', StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode', StrictVarName: 'Variable name may not be eval or arguments in strict mode', TemplateOctalLiteral: 'Octal literals are not allowed in template strings.', UnexpectedEOS: 'Unexpected end of input', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedNumber: 'Unexpected number', UnexpectedReserved: 'Unexpected reserved word', UnexpectedString: 'Unexpected string', UnexpectedTemplate: 'Unexpected quasi %0', UnexpectedToken: 'Unexpected token %0', UnexpectedTokenIllegal: 'Unexpected token ILLEGAL', UnknownLabel: 'Undefined label \'%0\'', UnterminatedRegExp: 'Invalid regular expression: missing /' }; /***/ }, /* 12 */ /***/ function(module, exports, __nested_webpack_require_226595__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var assert_1 = __nested_webpack_require_226595__(9); var character_1 = __nested_webpack_require_226595__(4); var messages_1 = __nested_webpack_require_226595__(11); function hexValue(ch) { return '0123456789abcdef'.indexOf(ch.toLowerCase()); } function octalValue(ch) { return '01234567'.indexOf(ch); } var Scanner = (function () { function Scanner(code, handler) { this.source = code; this.errorHandler = handler; this.trackComment = false; this.isModule = false; this.length = code.length; this.index = 0; this.lineNumber = (code.length > 0) ? 1 : 0; this.lineStart = 0; this.curlyStack = []; } Scanner.prototype.saveState = function () { return { index: this.index, lineNumber: this.lineNumber, lineStart: this.lineStart }; }; Scanner.prototype.restoreState = function (state) { this.index = state.index; this.lineNumber = state.lineNumber; this.lineStart = state.lineStart; }; Scanner.prototype.eof = function () { return this.index >= this.length; }; Scanner.prototype.throwUnexpectedToken = function (message) { if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); }; Scanner.prototype.tolerateUnexpectedToken = function (message) { if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); }; // https://tc39.github.io/ecma262/#sec-comments Scanner.prototype.skipSingleLineComment = function (offset) { var comments = []; var start, loc; if (this.trackComment) { comments = []; start = this.index - offset; loc = { start: { line: this.lineNumber, column: this.index - this.lineStart - offset }, end: {} }; } while (!this.eof()) { var ch = this.source.charCodeAt(this.index); ++this.index; if (character_1.Character.isLineTerminator(ch)) { if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart - 1 }; var entry = { multiLine: false, slice: [start + offset, this.index - 1], range: [start, this.index - 1], loc: loc }; comments.push(entry); } if (ch === 13 && this.source.charCodeAt(this.index) === 10) { ++this.index; } ++this.lineNumber; this.lineStart = this.index; return comments; } } if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart }; var entry = { multiLine: false, slice: [start + offset, this.index], range: [start, this.index], loc: loc }; comments.push(entry); } return comments; }; Scanner.prototype.skipMultiLineComment = function () { var comments = []; var start, loc; if (this.trackComment) { comments = []; start = this.index - 2; loc = { start: { line: this.lineNumber, column: this.index - this.lineStart - 2 }, end: {} }; } while (!this.eof()) { var ch = this.source.charCodeAt(this.index); if (character_1.Character.isLineTerminator(ch)) { if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) { ++this.index; } ++this.lineNumber; ++this.index; this.lineStart = this.index; } else if (ch === 0x2A) { // Block comment ends with '*/'. if (this.source.charCodeAt(this.index + 1) === 0x2F) { this.index += 2; if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart }; var entry = { multiLine: true, slice: [start + 2, this.index - 2], range: [start, this.index], loc: loc }; comments.push(entry); } return comments; } ++this.index; } else { ++this.index; } } // Ran off the end of the file - the whole thing is a comment if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart }; var entry = { multiLine: true, slice: [start + 2, this.index], range: [start, this.index], loc: loc }; comments.push(entry); } this.tolerateUnexpectedToken(); return comments; }; Scanner.prototype.scanComments = function () { var comments; if (this.trackComment) { comments = []; } var start = (this.index === 0); while (!this.eof()) { var ch = this.source.charCodeAt(this.index); if (character_1.Character.isWhiteSpace(ch)) { ++this.index; } else if (character_1.Character.isLineTerminator(ch)) { ++this.index; if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) { ++this.index; } ++this.lineNumber; this.lineStart = this.index; start = true; } else if (ch === 0x2F) { ch = this.source.charCodeAt(this.index + 1); if (ch === 0x2F) { this.index += 2; var comment = this.skipSingleLineComment(2); if (this.trackComment) { comments = comments.concat(comment); } start = true; } else if (ch === 0x2A) { this.index += 2; var comment = this.skipMultiLineComment(); if (this.trackComment) { comments = comments.concat(comment); } } else { break; } } else if (start && ch === 0x2D) { // U+003E is '>' if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) { // '-->' is a single-line comment this.index += 3; var comment = this.skipSingleLineComment(3); if (this.trackComment) { comments = comments.concat(comment); } } else { break; } } else if (ch === 0x3C && !this.isModule) { if (this.source.slice(this.index + 1, this.index + 4) === '!--') { this.index += 4; // ` 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, '\\$&') } /***/ }), /***/ 596: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var path = __webpack_require__(5622); var fs = __webpack_require__(5747); var _0777 = parseInt('0777', 8); module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; function mkdirP (p, opts, f, made) { if (typeof opts === 'function') { f = opts; opts = {}; } else if (!opts || typeof opts !== 'object') { opts = { mode: opts }; } var mode = opts.mode; var xfs = opts.fs || fs; if (mode === undefined) { mode = _0777 & (~process.umask()); } if (!made) made = null; var cb = f || function () {}; p = path.resolve(p); xfs.mkdir(p, mode, function (er) { if (!er) { made = made || p; return cb(null, made); } switch (er.code) { case 'ENOENT': mkdirP(path.dirname(p), opts, function (er, made) { if (er) cb(er, made); else mkdirP(p, opts, cb, made); }); break; // In the case of any other error, just see if there's a dir // there already. If so, then hooray! If not, then something // is borked. default: xfs.stat(p, function (er2, stat) { // if the stat fails, then that's super weird. // let the original error be the failure reason. if (er2 || !stat.isDirectory()) cb(er, made) else cb(null, made); }); break; } }); } mkdirP.sync = function sync (p, opts, made) { if (!opts || typeof opts !== 'object') { opts = { mode: opts }; } var mode = opts.mode; var xfs = opts.fs || fs; if (mode === undefined) { mode = _0777 & (~process.umask()); } if (!made) made = null; p = path.resolve(p); try { xfs.mkdirSync(p, mode); made = made || p; } catch (err0) { switch (err0.code) { case 'ENOENT' : made = sync(path.dirname(p), opts, made); sync(p, opts, made); break; // In the case of any other error, just see if there's a dir // there already. If so, then hooray! If not, then something // is borked. default: var stat; try { stat = xfs.statSync(p); } catch (err1) { throw err0; } if (!stat.isDirectory()) throw err0; break; } } return made; }; /***/ }), /***/ 8632: /***/ ((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' : ''); } /***/ }), /***/ 8034: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var wrappy = __webpack_require__(7534) 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 } /***/ }), /***/ 9991: /***/ ((module) => { "use strict"; function posix(path) { return path.charAt(0) === '/'; } function win32(path) { // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; var result = splitDeviceRe.exec(path); var device = result[1] || ''; var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute return Boolean(result[2] || isUnc); } module.exports = process.platform === 'win32' ? win32 : posix; module.exports.posix = posix; module.exports.win32 = win32; /***/ }), /***/ 277: /***/ ((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)); } /***/ }), /***/ 6540: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /** * Parser functions. */ var parserFunctions = __webpack_require__(2307); Object.keys(parserFunctions).forEach(function (k) { exports[k] = parserFunctions[k]; }); /** * Builder functions. */ var builderFunctions = __webpack_require__(4473); Object.keys(builderFunctions).forEach(function (k) { exports[k] = builderFunctions[k]; }); /***/ }), /***/ 4473: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /** * Module dependencies. */ var base64 = __webpack_require__(1759); var xmlbuilder = __webpack_require__(2066); /** * Module exports. */ exports.build = build; /** * Accepts a `Date` instance and returns an ISO date string. * * @param {Date} d - Date instance to serialize * @returns {String} ISO date string representation of `d` * @api private */ function ISODateString(d){ function pad(n){ return n < 10 ? '0' + n : n; } return d.getUTCFullYear()+'-' + pad(d.getUTCMonth()+1)+'-' + pad(d.getUTCDate())+'T' + pad(d.getUTCHours())+':' + pad(d.getUTCMinutes())+':' + pad(d.getUTCSeconds())+'Z'; } /** * Returns the internal "type" of `obj` via the * `Object.prototype.toString()` trick. * * @param {Mixed} obj - any value * @returns {String} the internal "type" name * @api private */ var toString = Object.prototype.toString; function type (obj) { var m = toString.call(obj).match(/\[object (.*)\]/); return m ? m[1] : m; } /** * Generate an XML plist string from the input object `obj`. * * @param {Object} obj - the object to convert * @param {Object} [opts] - optional options object * @returns {String} converted plist XML string * @api public */ function build (obj, opts) { var XMLHDR = { version: '1.0', encoding: 'UTF-8' }; var XMLDTD = { pubid: '-//Apple//DTD PLIST 1.0//EN', sysid: 'http://www.apple.com/DTDs/PropertyList-1.0.dtd' }; var doc = xmlbuilder.create('plist'); doc.dec(XMLHDR.version, XMLHDR.encoding, XMLHDR.standalone); doc.dtd(XMLDTD.pubid, XMLDTD.sysid); doc.att('version', '1.0'); walk_obj(obj, doc); if (!opts) opts = {}; // default `pretty` to `true` opts.pretty = opts.pretty !== false; return doc.end(opts); } /** * depth first, recursive traversal of a javascript object. when complete, * next_child contains a reference to the build XML object. * * @api private */ function walk_obj(next, next_child) { var tag_type, i, prop; var name = type(next); if ('Undefined' == name) { return; } else if (Array.isArray(next)) { next_child = next_child.ele('array'); for (i = 0; i < next.length; i++) { walk_obj(next[i], next_child); } } else if (Buffer.isBuffer(next)) { next_child.ele('data').raw(next.toString('base64')); } else if ('Object' == name) { next_child = next_child.ele('dict'); for (prop in next) { if (next.hasOwnProperty(prop)) { next_child.ele('key').txt(prop); walk_obj(next[prop], next_child); } } } else if ('Number' == name) { // detect if this is an integer or real // TODO: add an ability to force one way or another via a "cast" tag_type = (next % 1 === 0) ? 'integer' : 'real'; next_child.ele(tag_type).txt(next.toString()); } else if ('Date' == name) { next_child.ele('date').txt(ISODateString(new Date(next))); } else if ('Boolean' == name) { next_child.ele(next ? 'true' : 'false'); } else if ('String' == name) { next_child.ele('string').txt(next); } else if ('ArrayBuffer' == name) { next_child.ele('data').raw(base64.fromByteArray(next)); } else if (next && next.buffer && 'ArrayBuffer' == type(next.buffer)) { // a typed array next_child.ele('data').raw(base64.fromByteArray(new Uint8Array(next.buffer), next_child)); } } /***/ }), /***/ 2307: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /** * Module dependencies. */ var DOMParser = __webpack_require__(4753)/* .DOMParser */ .a; /** * Module exports. */ exports.parse = parse; var TEXT_NODE = 3; var CDATA_NODE = 4; var COMMENT_NODE = 8; /** * We ignore raw text (usually whitespace), , * and raw CDATA nodes. * * @param {Element} node * @returns {Boolean} * @api private */ function shouldIgnoreNode (node) { return node.nodeType === TEXT_NODE || node.nodeType === COMMENT_NODE || node.nodeType === CDATA_NODE; } /** * Check if the node is empty. Some plist file has such node: * * this node shoud be ignored. * * @see https://github.com/TooTallNate/plist.js/issues/66 * @param {Element} node * @returns {Boolean} * @api private */ function isEmptyNode(node){ if(!node.childNodes || node.childNodes.length === 0) { return true; } else { return false; } } function invariant(test, message) { if (!test) { throw new Error(message); } } /** * Parses a Plist XML string. Returns an Object. * * @param {String} xml - the XML String to decode * @returns {Mixed} the decoded value from the Plist XML * @api public */ function parse (xml) { var doc = new DOMParser().parseFromString(xml); invariant( doc.documentElement.nodeName === 'plist', 'malformed document. First element should be ' ); var plist = parsePlistXML(doc.documentElement); // the root node gets interpreted as an Array, // so pull out the inner data first if (plist.length == 1) plist = plist[0]; return plist; } /** * Convert an XML based plist document into a JSON representation. * * @param {Object} xml_node - current XML node in the plist * @returns {Mixed} built up JSON object * @api private */ function parsePlistXML (node) { var i, new_obj, key, val, new_arr, res, counter, type; if (!node) return null; if (node.nodeName === 'plist') { new_arr = []; if (isEmptyNode(node)) { return new_arr; } for (i=0; i < node.childNodes.length; i++) { if (!shouldIgnoreNode(node.childNodes[i])) { new_arr.push( parsePlistXML(node.childNodes[i])); } } return new_arr; } else if (node.nodeName === 'dict') { new_obj = {}; key = null; counter = 0; if (isEmptyNode(node)) { return new_obj; } for (i=0; i < node.childNodes.length; i++) { if (shouldIgnoreNode(node.childNodes[i])) continue; if (counter % 2 === 0) { invariant( node.childNodes[i].nodeName === 'key', 'Missing key while parsing .' ); key = parsePlistXML(node.childNodes[i]); } else { invariant( node.childNodes[i].nodeName !== 'key', 'Unexpected key "' + parsePlistXML(node.childNodes[i]) + '" while parsing .' ); new_obj[key] = parsePlistXML(node.childNodes[i]); } counter += 1; } if (counter % 2 === 1) { throw new Error('Missing value for "' + key + '" while parsing '); } return new_obj; } else if (node.nodeName === 'array') { new_arr = []; if (isEmptyNode(node)) { return new_arr; } for (i=0; i < node.childNodes.length; i++) { if (!shouldIgnoreNode(node.childNodes[i])) { res = parsePlistXML(node.childNodes[i]); if (null != res) new_arr.push(res); } } return new_arr; } else if (node.nodeName === '#text') { // TODO: what should we do with text types? (CDATA sections) } else if (node.nodeName === 'key') { if (isEmptyNode(node)) { return ''; } return node.childNodes[0].nodeValue; } else if (node.nodeName === 'string') { res = ''; if (isEmptyNode(node)) { return res; } for (i=0; i < node.childNodes.length; i++) { var type = node.childNodes[i].nodeType; if (type === TEXT_NODE || type === CDATA_NODE) { res += node.childNodes[i].nodeValue; } } return res; } else if (node.nodeName === 'integer') { invariant( !isEmptyNode(node), 'Cannot parse "" as integer.' ); return parseInt(node.childNodes[0].nodeValue, 10); } else if (node.nodeName === 'real') { invariant( !isEmptyNode(node), 'Cannot parse "" as real.' ); res = ''; for (i=0; i < node.childNodes.length; i++) { if (node.childNodes[i].nodeType === TEXT_NODE) { res += node.childNodes[i].nodeValue; } } return parseFloat(res); } else if (node.nodeName === 'data') { res = ''; if (isEmptyNode(node)) { return Buffer.from(res, 'base64'); } for (i=0; i < node.childNodes.length; i++) { if (node.childNodes[i].nodeType === TEXT_NODE) { res += node.childNodes[i].nodeValue.replace(/\s+/g, ''); } } return Buffer.from(res, 'base64'); } else if (node.nodeName === 'date') { invariant( !isEmptyNode(node), 'Cannot parse "" as Date.' ) return new Date(node.childNodes[0].nodeValue); } else if (node.nodeName === 'true') { return true; } else if (node.nodeName === 'false') { return false; } } /***/ }), /***/ 8318: /***/ (function(module) { // Generated by CoffeeScript 1.12.7 (function() { var assign, isArray, isEmpty, isFunction, isObject, isPlainObject, slice = [].slice, hasProp = {}.hasOwnProperty; assign = function() { var i, key, len, source, sources, target; target = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : []; if (isFunction(Object.assign)) { Object.assign.apply(null, arguments); } else { for (i = 0, len = sources.length; i < len; i++) { source = sources[i]; if (source != null) { for (key in source) { if (!hasProp.call(source, key)) continue; target[key] = source[key]; } } } } return target; }; isFunction = function(val) { return !!val && Object.prototype.toString.call(val) === '[object Function]'; }; isObject = function(val) { var ref; return !!val && ((ref = typeof val) === 'function' || ref === 'object'); }; isArray = function(val) { if (isFunction(Array.isArray)) { return Array.isArray(val); } else { return Object.prototype.toString.call(val) === '[object Array]'; } }; isEmpty = function(val) { var key; if (isArray(val)) { return !val.length; } else { for (key in val) { if (!hasProp.call(val, key)) continue; return false; } return true; } }; isPlainObject = function(val) { var ctor, proto; return isObject(val) && (proto = Object.getPrototypeOf(val)) && (ctor = proto.constructor) && (typeof ctor === 'function') && (ctor instanceof ctor) && (Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object)); }; module.exports.assign = assign; module.exports.isFunction = isFunction; module.exports.isObject = isObject; module.exports.isArray = isArray; module.exports.isEmpty = isEmpty; module.exports.isPlainObject = isPlainObject; }).call(this); /***/ }), /***/ 8311: /***/ (function(module) { // Generated by CoffeeScript 1.12.7 (function() { var XMLAttribute; module.exports = XMLAttribute = (function() { function XMLAttribute(parent, name, value) { this.options = parent.options; this.stringify = parent.stringify; if (name == null) { throw new Error("Missing attribute name of element " + parent.name); } if (value == null) { throw new Error("Missing attribute value for attribute " + name + " of element " + parent.name); } this.name = this.stringify.attName(name); this.value = this.stringify.attValue(value); } XMLAttribute.prototype.clone = function() { return Object.create(this); }; XMLAttribute.prototype.toString = function(options) { return this.options.writer.set(options).attribute(this); }; return XMLAttribute; })(); }).call(this); /***/ }), /***/ 5851: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLCData, XMLNode, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = __webpack_require__(94); module.exports = XMLCData = (function(superClass) { extend(XMLCData, superClass); function XMLCData(parent, text) { XMLCData.__super__.constructor.call(this, parent); if (text == null) { throw new Error("Missing CDATA text"); } this.text = this.stringify.cdata(text); } XMLCData.prototype.clone = function() { return Object.create(this); }; XMLCData.prototype.toString = function(options) { return this.options.writer.set(options).cdata(this); }; return XMLCData; })(XMLNode); }).call(this); /***/ }), /***/ 1989: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLComment, XMLNode, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = __webpack_require__(94); module.exports = XMLComment = (function(superClass) { extend(XMLComment, superClass); function XMLComment(parent, text) { XMLComment.__super__.constructor.call(this, parent); if (text == null) { throw new Error("Missing comment text"); } this.text = this.stringify.comment(text); } XMLComment.prototype.clone = function() { return Object.create(this); }; XMLComment.prototype.toString = function(options) { return this.options.writer.set(options).comment(this); }; return XMLComment; })(XMLNode); }).call(this); /***/ }), /***/ 1586: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLDTDAttList, XMLNode, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = __webpack_require__(94); module.exports = XMLDTDAttList = (function(superClass) { extend(XMLDTDAttList, superClass); function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) { XMLDTDAttList.__super__.constructor.call(this, parent); if (elementName == null) { throw new Error("Missing DTD element name"); } if (attributeName == null) { throw new Error("Missing DTD attribute name"); } if (!attributeType) { throw new Error("Missing DTD attribute type"); } if (!defaultValueType) { throw new Error("Missing DTD attribute default"); } if (defaultValueType.indexOf('#') !== 0) { defaultValueType = '#' + defaultValueType; } if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) { throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT"); } if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) { throw new Error("Default value only applies to #FIXED or #DEFAULT"); } this.elementName = this.stringify.eleName(elementName); this.attributeName = this.stringify.attName(attributeName); this.attributeType = this.stringify.dtdAttType(attributeType); this.defaultValue = this.stringify.dtdAttDefault(defaultValue); this.defaultValueType = defaultValueType; } XMLDTDAttList.prototype.toString = function(options) { return this.options.writer.set(options).dtdAttList(this); }; return XMLDTDAttList; })(XMLNode); }).call(this); /***/ }), /***/ 1800: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLDTDElement, XMLNode, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = __webpack_require__(94); module.exports = XMLDTDElement = (function(superClass) { extend(XMLDTDElement, superClass); function XMLDTDElement(parent, name, value) { XMLDTDElement.__super__.constructor.call(this, parent); if (name == null) { throw new Error("Missing DTD element name"); } if (!value) { value = '(#PCDATA)'; } if (Array.isArray(value)) { value = '(' + value.join(',') + ')'; } this.name = this.stringify.eleName(name); this.value = this.stringify.dtdElementValue(value); } XMLDTDElement.prototype.toString = function(options) { return this.options.writer.set(options).dtdElement(this); }; return XMLDTDElement; })(XMLNode); }).call(this); /***/ }), /***/ 3252: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLDTDEntity, XMLNode, isObject, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; isObject = __webpack_require__(8318).isObject; XMLNode = __webpack_require__(94); module.exports = XMLDTDEntity = (function(superClass) { extend(XMLDTDEntity, superClass); function XMLDTDEntity(parent, pe, name, value) { XMLDTDEntity.__super__.constructor.call(this, parent); if (name == null) { throw new Error("Missing entity name"); } if (value == null) { throw new Error("Missing entity value"); } this.pe = !!pe; this.name = this.stringify.eleName(name); if (!isObject(value)) { this.value = this.stringify.dtdEntityValue(value); } else { if (!value.pubID && !value.sysID) { throw new Error("Public and/or system identifiers are required for an external entity"); } if (value.pubID && !value.sysID) { throw new Error("System identifier is required for a public external entity"); } if (value.pubID != null) { this.pubID = this.stringify.dtdPubID(value.pubID); } if (value.sysID != null) { this.sysID = this.stringify.dtdSysID(value.sysID); } if (value.nData != null) { this.nData = this.stringify.dtdNData(value.nData); } if (this.pe && this.nData) { throw new Error("Notation declaration is not allowed in a parameter entity"); } } } XMLDTDEntity.prototype.toString = function(options) { return this.options.writer.set(options).dtdEntity(this); }; return XMLDTDEntity; })(XMLNode); }).call(this); /***/ }), /***/ 5360: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLDTDNotation, XMLNode, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = __webpack_require__(94); module.exports = XMLDTDNotation = (function(superClass) { extend(XMLDTDNotation, superClass); function XMLDTDNotation(parent, name, value) { XMLDTDNotation.__super__.constructor.call(this, parent); if (name == null) { throw new Error("Missing notation name"); } if (!value.pubID && !value.sysID) { throw new Error("Public or system identifiers are required for an external entity"); } this.name = this.stringify.eleName(name); if (value.pubID != null) { this.pubID = this.stringify.dtdPubID(value.pubID); } if (value.sysID != null) { this.sysID = this.stringify.dtdSysID(value.sysID); } } XMLDTDNotation.prototype.toString = function(options) { return this.options.writer.set(options).dtdNotation(this); }; return XMLDTDNotation; })(XMLNode); }).call(this); /***/ }), /***/ 7365: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLDeclaration, XMLNode, isObject, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; isObject = __webpack_require__(8318).isObject; XMLNode = __webpack_require__(94); module.exports = XMLDeclaration = (function(superClass) { extend(XMLDeclaration, superClass); function XMLDeclaration(parent, version, encoding, standalone) { var ref; XMLDeclaration.__super__.constructor.call(this, parent); if (isObject(version)) { ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone; } if (!version) { version = '1.0'; } this.version = this.stringify.xmlVersion(version); if (encoding != null) { this.encoding = this.stringify.xmlEncoding(encoding); } if (standalone != null) { this.standalone = this.stringify.xmlStandalone(standalone); } } XMLDeclaration.prototype.toString = function(options) { return this.options.writer.set(options).declaration(this); }; return XMLDeclaration; })(XMLNode); }).call(this); /***/ }), /***/ 1479: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLNode, isObject, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; isObject = __webpack_require__(8318).isObject; XMLNode = __webpack_require__(94); XMLDTDAttList = __webpack_require__(1586); XMLDTDEntity = __webpack_require__(3252); XMLDTDElement = __webpack_require__(1800); XMLDTDNotation = __webpack_require__(5360); module.exports = XMLDocType = (function(superClass) { extend(XMLDocType, superClass); function XMLDocType(parent, pubID, sysID) { var ref, ref1; XMLDocType.__super__.constructor.call(this, parent); this.documentObject = parent; if (isObject(pubID)) { ref = pubID, pubID = ref.pubID, sysID = ref.sysID; } if (sysID == null) { ref1 = [pubID, sysID], sysID = ref1[0], pubID = ref1[1]; } if (pubID != null) { this.pubID = this.stringify.dtdPubID(pubID); } if (sysID != null) { this.sysID = this.stringify.dtdSysID(sysID); } } XMLDocType.prototype.element = function(name, value) { var child; child = new XMLDTDElement(this, name, value); this.children.push(child); return this; }; XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { var child; child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue); this.children.push(child); return this; }; XMLDocType.prototype.entity = function(name, value) { var child; child = new XMLDTDEntity(this, false, name, value); this.children.push(child); return this; }; XMLDocType.prototype.pEntity = function(name, value) { var child; child = new XMLDTDEntity(this, true, name, value); this.children.push(child); return this; }; XMLDocType.prototype.notation = function(name, value) { var child; child = new XMLDTDNotation(this, name, value); this.children.push(child); return this; }; XMLDocType.prototype.toString = function(options) { return this.options.writer.set(options).docType(this); }; XMLDocType.prototype.ele = function(name, value) { return this.element(name, value); }; XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue); }; XMLDocType.prototype.ent = function(name, value) { return this.entity(name, value); }; XMLDocType.prototype.pent = function(name, value) { return this.pEntity(name, value); }; XMLDocType.prototype.not = function(name, value) { return this.notation(name, value); }; XMLDocType.prototype.up = function() { return this.root() || this.documentObject; }; return XMLDocType; })(XMLNode); }).call(this); /***/ }), /***/ 5255: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLDocument, XMLNode, XMLStringWriter, XMLStringifier, isPlainObject, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; isPlainObject = __webpack_require__(8318).isPlainObject; XMLNode = __webpack_require__(94); XMLStringifier = __webpack_require__(926); XMLStringWriter = __webpack_require__(7155); module.exports = XMLDocument = (function(superClass) { extend(XMLDocument, superClass); function XMLDocument(options) { XMLDocument.__super__.constructor.call(this, null); options || (options = {}); if (!options.writer) { options.writer = new XMLStringWriter(); } this.options = options; this.stringify = new XMLStringifier(options); this.isDocument = true; } XMLDocument.prototype.end = function(writer) { var writerOptions; if (!writer) { writer = this.options.writer; } else if (isPlainObject(writer)) { writerOptions = writer; writer = this.options.writer.set(writerOptions); } return writer.document(this); }; XMLDocument.prototype.toString = function(options) { return this.options.writer.set(options).document(this); }; return XMLDocument; })(XMLNode); }).call(this); /***/ }), /***/ 9587: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLAttribute, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDocumentCB, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLStringifier, XMLText, isFunction, isObject, isPlainObject, ref, hasProp = {}.hasOwnProperty; ref = __webpack_require__(8318), isObject = ref.isObject, isFunction = ref.isFunction, isPlainObject = ref.isPlainObject; XMLElement = __webpack_require__(2433); XMLCData = __webpack_require__(5851); XMLComment = __webpack_require__(1989); XMLRaw = __webpack_require__(1785); XMLText = __webpack_require__(1879); XMLProcessingInstruction = __webpack_require__(7055); XMLDeclaration = __webpack_require__(7365); XMLDocType = __webpack_require__(1479); XMLDTDAttList = __webpack_require__(1586); XMLDTDEntity = __webpack_require__(3252); XMLDTDElement = __webpack_require__(1800); XMLDTDNotation = __webpack_require__(5360); XMLAttribute = __webpack_require__(8311); XMLStringifier = __webpack_require__(926); XMLStringWriter = __webpack_require__(7155); module.exports = XMLDocumentCB = (function() { function XMLDocumentCB(options, onData, onEnd) { var writerOptions; options || (options = {}); if (!options.writer) { options.writer = new XMLStringWriter(options); } else if (isPlainObject(options.writer)) { writerOptions = options.writer; options.writer = new XMLStringWriter(writerOptions); } this.options = options; this.writer = options.writer; this.stringify = new XMLStringifier(options); this.onDataCallback = onData || function() {}; this.onEndCallback = onEnd || function() {}; this.currentNode = null; this.currentLevel = -1; this.openTags = {}; this.documentStarted = false; this.documentCompleted = false; this.root = null; } XMLDocumentCB.prototype.node = function(name, attributes, text) { var ref1; if (name == null) { throw new Error("Missing node name"); } if (this.root && this.currentLevel === -1) { throw new Error("Document can only have one root node"); } this.openCurrent(); name = name.valueOf(); if (attributes == null) { attributes = {}; } attributes = attributes.valueOf(); if (!isObject(attributes)) { ref1 = [attributes, text], text = ref1[0], attributes = ref1[1]; } this.currentNode = new XMLElement(this, name, attributes); this.currentNode.children = false; this.currentLevel++; this.openTags[this.currentLevel] = this.currentNode; if (text != null) { this.text(text); } return this; }; XMLDocumentCB.prototype.element = function(name, attributes, text) { if (this.currentNode && this.currentNode instanceof XMLDocType) { return this.dtdElement.apply(this, arguments); } else { return this.node(name, attributes, text); } }; XMLDocumentCB.prototype.attribute = function(name, value) { var attName, attValue; if (!this.currentNode || this.currentNode.children) { throw new Error("att() can only be used immediately after an ele() call in callback mode"); } if (name != null) { name = name.valueOf(); } if (isObject(name)) { for (attName in name) { if (!hasProp.call(name, attName)) continue; attValue = name[attName]; this.attribute(attName, attValue); } } else { if (isFunction(value)) { value = value.apply(); } if (!this.options.skipNullAttributes || (value != null)) { this.currentNode.attributes[name] = new XMLAttribute(this, name, value); } } return this; }; XMLDocumentCB.prototype.text = function(value) { var node; this.openCurrent(); node = new XMLText(this, value); this.onData(this.writer.text(node, this.currentLevel + 1)); return this; }; XMLDocumentCB.prototype.cdata = function(value) { var node; this.openCurrent(); node = new XMLCData(this, value); this.onData(this.writer.cdata(node, this.currentLevel + 1)); return this; }; XMLDocumentCB.prototype.comment = function(value) { var node; this.openCurrent(); node = new XMLComment(this, value); this.onData(this.writer.comment(node, this.currentLevel + 1)); return this; }; XMLDocumentCB.prototype.raw = function(value) { var node; this.openCurrent(); node = new XMLRaw(this, value); this.onData(this.writer.raw(node, this.currentLevel + 1)); return this; }; XMLDocumentCB.prototype.instruction = function(target, value) { var i, insTarget, insValue, len, node; this.openCurrent(); if (target != null) { target = target.valueOf(); } if (value != null) { value = value.valueOf(); } if (Array.isArray(target)) { for (i = 0, len = target.length; i < len; i++) { insTarget = target[i]; this.instruction(insTarget); } } else if (isObject(target)) { for (insTarget in target) { if (!hasProp.call(target, insTarget)) continue; insValue = target[insTarget]; this.instruction(insTarget, insValue); } } else { if (isFunction(value)) { value = value.apply(); } node = new XMLProcessingInstruction(this, target, value); this.onData(this.writer.processingInstruction(node, this.currentLevel + 1)); } return this; }; XMLDocumentCB.prototype.declaration = function(version, encoding, standalone) { var node; this.openCurrent(); if (this.documentStarted) { throw new Error("declaration() must be the first node"); } node = new XMLDeclaration(this, version, encoding, standalone); this.onData(this.writer.declaration(node, this.currentLevel + 1)); return this; }; XMLDocumentCB.prototype.doctype = function(root, pubID, sysID) { this.openCurrent(); if (root == null) { throw new Error("Missing root node name"); } if (this.root) { throw new Error("dtd() must come before the root node"); } this.currentNode = new XMLDocType(this, pubID, sysID); this.currentNode.rootNodeName = root; this.currentNode.children = false; this.currentLevel++; this.openTags[this.currentLevel] = this.currentNode; return this; }; XMLDocumentCB.prototype.dtdElement = function(name, value) { var node; this.openCurrent(); node = new XMLDTDElement(this, name, value); this.onData(this.writer.dtdElement(node, this.currentLevel + 1)); return this; }; XMLDocumentCB.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { var node; this.openCurrent(); node = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue); this.onData(this.writer.dtdAttList(node, this.currentLevel + 1)); return this; }; XMLDocumentCB.prototype.entity = function(name, value) { var node; this.openCurrent(); node = new XMLDTDEntity(this, false, name, value); this.onData(this.writer.dtdEntity(node, this.currentLevel + 1)); return this; }; XMLDocumentCB.prototype.pEntity = function(name, value) { var node; this.openCurrent(); node = new XMLDTDEntity(this, true, name, value); this.onData(this.writer.dtdEntity(node, this.currentLevel + 1)); return this; }; XMLDocumentCB.prototype.notation = function(name, value) { var node; this.openCurrent(); node = new XMLDTDNotation(this, name, value); this.onData(this.writer.dtdNotation(node, this.currentLevel + 1)); return this; }; XMLDocumentCB.prototype.up = function() { if (this.currentLevel < 0) { throw new Error("The document node has no parent"); } if (this.currentNode) { if (this.currentNode.children) { this.closeNode(this.currentNode); } else { this.openNode(this.currentNode); } this.currentNode = null; } else { this.closeNode(this.openTags[this.currentLevel]); } delete this.openTags[this.currentLevel]; this.currentLevel--; return this; }; XMLDocumentCB.prototype.end = function() { while (this.currentLevel >= 0) { this.up(); } return this.onEnd(); }; XMLDocumentCB.prototype.openCurrent = function() { if (this.currentNode) { this.currentNode.children = true; return this.openNode(this.currentNode); } }; XMLDocumentCB.prototype.openNode = function(node) { if (!node.isOpen) { if (!this.root && this.currentLevel === 0 && node instanceof XMLElement) { this.root = node; } this.onData(this.writer.openNode(node, this.currentLevel)); return node.isOpen = true; } }; XMLDocumentCB.prototype.closeNode = function(node) { if (!node.isClosed) { this.onData(this.writer.closeNode(node, this.currentLevel)); return node.isClosed = true; } }; XMLDocumentCB.prototype.onData = function(chunk) { this.documentStarted = true; return this.onDataCallback(chunk); }; XMLDocumentCB.prototype.onEnd = function() { this.documentCompleted = true; return this.onEndCallback(); }; XMLDocumentCB.prototype.ele = function() { return this.element.apply(this, arguments); }; XMLDocumentCB.prototype.nod = function(name, attributes, text) { return this.node(name, attributes, text); }; XMLDocumentCB.prototype.txt = function(value) { return this.text(value); }; XMLDocumentCB.prototype.dat = function(value) { return this.cdata(value); }; XMLDocumentCB.prototype.com = function(value) { return this.comment(value); }; XMLDocumentCB.prototype.ins = function(target, value) { return this.instruction(target, value); }; XMLDocumentCB.prototype.dec = function(version, encoding, standalone) { return this.declaration(version, encoding, standalone); }; XMLDocumentCB.prototype.dtd = function(root, pubID, sysID) { return this.doctype(root, pubID, sysID); }; XMLDocumentCB.prototype.e = function(name, attributes, text) { return this.element(name, attributes, text); }; XMLDocumentCB.prototype.n = function(name, attributes, text) { return this.node(name, attributes, text); }; XMLDocumentCB.prototype.t = function(value) { return this.text(value); }; XMLDocumentCB.prototype.d = function(value) { return this.cdata(value); }; XMLDocumentCB.prototype.c = function(value) { return this.comment(value); }; XMLDocumentCB.prototype.r = function(value) { return this.raw(value); }; XMLDocumentCB.prototype.i = function(target, value) { return this.instruction(target, value); }; XMLDocumentCB.prototype.att = function() { if (this.currentNode && this.currentNode instanceof XMLDocType) { return this.attList.apply(this, arguments); } else { return this.attribute.apply(this, arguments); } }; XMLDocumentCB.prototype.a = function() { if (this.currentNode && this.currentNode instanceof XMLDocType) { return this.attList.apply(this, arguments); } else { return this.attribute.apply(this, arguments); } }; XMLDocumentCB.prototype.ent = function(name, value) { return this.entity(name, value); }; XMLDocumentCB.prototype.pent = function(name, value) { return this.pEntity(name, value); }; XMLDocumentCB.prototype.not = function(name, value) { return this.notation(name, value); }; return XMLDocumentCB; })(); }).call(this); /***/ }), /***/ 2433: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLAttribute, XMLElement, XMLNode, isFunction, isObject, ref, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ref = __webpack_require__(8318), isObject = ref.isObject, isFunction = ref.isFunction; XMLNode = __webpack_require__(94); XMLAttribute = __webpack_require__(8311); module.exports = XMLElement = (function(superClass) { extend(XMLElement, superClass); function XMLElement(parent, name, attributes) { XMLElement.__super__.constructor.call(this, parent); if (name == null) { throw new Error("Missing element name"); } this.name = this.stringify.eleName(name); this.attributes = {}; if (attributes != null) { this.attribute(attributes); } if (parent.isDocument) { this.isRoot = true; this.documentObject = parent; parent.rootObject = this; } } XMLElement.prototype.clone = function() { var att, attName, clonedSelf, ref1; clonedSelf = Object.create(this); if (clonedSelf.isRoot) { clonedSelf.documentObject = null; } clonedSelf.attributes = {}; ref1 = this.attributes; for (attName in ref1) { if (!hasProp.call(ref1, attName)) continue; att = ref1[attName]; clonedSelf.attributes[attName] = att.clone(); } clonedSelf.children = []; this.children.forEach(function(child) { var clonedChild; clonedChild = child.clone(); clonedChild.parent = clonedSelf; return clonedSelf.children.push(clonedChild); }); return clonedSelf; }; XMLElement.prototype.attribute = function(name, value) { var attName, attValue; if (name != null) { name = name.valueOf(); } if (isObject(name)) { for (attName in name) { if (!hasProp.call(name, attName)) continue; attValue = name[attName]; this.attribute(attName, attValue); } } else { if (isFunction(value)) { value = value.apply(); } if (!this.options.skipNullAttributes || (value != null)) { this.attributes[name] = new XMLAttribute(this, name, value); } } return this; }; XMLElement.prototype.removeAttribute = function(name) { var attName, i, len; if (name == null) { throw new Error("Missing attribute name"); } name = name.valueOf(); if (Array.isArray(name)) { for (i = 0, len = name.length; i < len; i++) { attName = name[i]; delete this.attributes[attName]; } } else { delete this.attributes[name]; } return this; }; XMLElement.prototype.toString = function(options) { return this.options.writer.set(options).element(this); }; XMLElement.prototype.att = function(name, value) { return this.attribute(name, value); }; XMLElement.prototype.a = function(name, value) { return this.attribute(name, value); }; return XMLElement; })(XMLNode); }).call(this); /***/ }), /***/ 94: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLElement, XMLNode, XMLProcessingInstruction, XMLRaw, XMLText, isEmpty, isFunction, isObject, ref, hasProp = {}.hasOwnProperty; ref = __webpack_require__(8318), isObject = ref.isObject, isFunction = ref.isFunction, isEmpty = ref.isEmpty; XMLElement = null; XMLCData = null; XMLComment = null; XMLDeclaration = null; XMLDocType = null; XMLRaw = null; XMLText = null; XMLProcessingInstruction = null; module.exports = XMLNode = (function() { function XMLNode(parent) { this.parent = parent; if (this.parent) { this.options = this.parent.options; this.stringify = this.parent.stringify; } this.children = []; if (!XMLElement) { XMLElement = __webpack_require__(2433); XMLCData = __webpack_require__(5851); XMLComment = __webpack_require__(1989); XMLDeclaration = __webpack_require__(7365); XMLDocType = __webpack_require__(1479); XMLRaw = __webpack_require__(1785); XMLText = __webpack_require__(1879); XMLProcessingInstruction = __webpack_require__(7055); } } XMLNode.prototype.element = function(name, attributes, text) { var childNode, item, j, k, key, lastChild, len, len1, ref1, val; lastChild = null; if (attributes == null) { attributes = {}; } attributes = attributes.valueOf(); if (!isObject(attributes)) { ref1 = [attributes, text], text = ref1[0], attributes = ref1[1]; } if (name != null) { name = name.valueOf(); } if (Array.isArray(name)) { for (j = 0, len = name.length; j < len; j++) { item = name[j]; lastChild = this.element(item); } } else if (isFunction(name)) { lastChild = this.element(name.apply()); } else if (isObject(name)) { for (key in name) { if (!hasProp.call(name, key)) continue; val = name[key]; if (isFunction(val)) { val = val.apply(); } if ((isObject(val)) && (isEmpty(val))) { val = null; } if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) { lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val); } else if (!this.options.separateArrayItems && Array.isArray(val)) { for (k = 0, len1 = val.length; k < len1; k++) { item = val[k]; childNode = {}; childNode[key] = item; lastChild = this.element(childNode); } } else if (isObject(val)) { lastChild = this.element(key); lastChild.element(val); } else { lastChild = this.element(key, val); } } } else { if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) { lastChild = this.text(text); } else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) { lastChild = this.cdata(text); } else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) { lastChild = this.comment(text); } else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) { lastChild = this.raw(text); } else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && name.indexOf(this.stringify.convertPIKey) === 0) { lastChild = this.instruction(name.substr(this.stringify.convertPIKey.length), text); } else { lastChild = this.node(name, attributes, text); } } if (lastChild == null) { throw new Error("Could not create any elements with: " + name); } return lastChild; }; XMLNode.prototype.insertBefore = function(name, attributes, text) { var child, i, removed; if (this.isRoot) { throw new Error("Cannot insert elements at root level"); } i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i); child = this.parent.element(name, attributes, text); Array.prototype.push.apply(this.parent.children, removed); return child; }; XMLNode.prototype.insertAfter = function(name, attributes, text) { var child, i, removed; if (this.isRoot) { throw new Error("Cannot insert elements at root level"); } i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i + 1); child = this.parent.element(name, attributes, text); Array.prototype.push.apply(this.parent.children, removed); return child; }; XMLNode.prototype.remove = function() { var i, ref1; if (this.isRoot) { throw new Error("Cannot remove the root element"); } i = this.parent.children.indexOf(this); [].splice.apply(this.parent.children, [i, i - i + 1].concat(ref1 = [])), ref1; return this.parent; }; XMLNode.prototype.node = function(name, attributes, text) { var child, ref1; if (name != null) { name = name.valueOf(); } attributes || (attributes = {}); attributes = attributes.valueOf(); if (!isObject(attributes)) { ref1 = [attributes, text], text = ref1[0], attributes = ref1[1]; } child = new XMLElement(this, name, attributes); if (text != null) { child.text(text); } this.children.push(child); return child; }; XMLNode.prototype.text = function(value) { var child; child = new XMLText(this, value); this.children.push(child); return this; }; XMLNode.prototype.cdata = function(value) { var child; child = new XMLCData(this, value); this.children.push(child); return this; }; XMLNode.prototype.comment = function(value) { var child; child = new XMLComment(this, value); this.children.push(child); return this; }; XMLNode.prototype.commentBefore = function(value) { var child, i, removed; i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i); child = this.parent.comment(value); Array.prototype.push.apply(this.parent.children, removed); return this; }; XMLNode.prototype.commentAfter = function(value) { var child, i, removed; i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i + 1); child = this.parent.comment(value); Array.prototype.push.apply(this.parent.children, removed); return this; }; XMLNode.prototype.raw = function(value) { var child; child = new XMLRaw(this, value); this.children.push(child); return this; }; XMLNode.prototype.instruction = function(target, value) { var insTarget, insValue, instruction, j, len; if (target != null) { target = target.valueOf(); } if (value != null) { value = value.valueOf(); } if (Array.isArray(target)) { for (j = 0, len = target.length; j < len; j++) { insTarget = target[j]; this.instruction(insTarget); } } else if (isObject(target)) { for (insTarget in target) { if (!hasProp.call(target, insTarget)) continue; insValue = target[insTarget]; this.instruction(insTarget, insValue); } } else { if (isFunction(value)) { value = value.apply(); } instruction = new XMLProcessingInstruction(this, target, value); this.children.push(instruction); } return this; }; XMLNode.prototype.instructionBefore = function(target, value) { var child, i, removed; i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i); child = this.parent.instruction(target, value); Array.prototype.push.apply(this.parent.children, removed); return this; }; XMLNode.prototype.instructionAfter = function(target, value) { var child, i, removed; i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i + 1); child = this.parent.instruction(target, value); Array.prototype.push.apply(this.parent.children, removed); return this; }; XMLNode.prototype.declaration = function(version, encoding, standalone) { var doc, xmldec; doc = this.document(); xmldec = new XMLDeclaration(doc, version, encoding, standalone); if (doc.children[0] instanceof XMLDeclaration) { doc.children[0] = xmldec; } else { doc.children.unshift(xmldec); } return doc.root() || doc; }; XMLNode.prototype.doctype = function(pubID, sysID) { var child, doc, doctype, i, j, k, len, len1, ref1, ref2; doc = this.document(); doctype = new XMLDocType(doc, pubID, sysID); ref1 = doc.children; for (i = j = 0, len = ref1.length; j < len; i = ++j) { child = ref1[i]; if (child instanceof XMLDocType) { doc.children[i] = doctype; return doctype; } } ref2 = doc.children; for (i = k = 0, len1 = ref2.length; k < len1; i = ++k) { child = ref2[i]; if (child.isRoot) { doc.children.splice(i, 0, doctype); return doctype; } } doc.children.push(doctype); return doctype; }; XMLNode.prototype.up = function() { if (this.isRoot) { throw new Error("The root node has no parent. Use doc() if you need to get the document object."); } return this.parent; }; XMLNode.prototype.root = function() { var node; node = this; while (node) { if (node.isDocument) { return node.rootObject; } else if (node.isRoot) { return node; } else { node = node.parent; } } }; XMLNode.prototype.document = function() { var node; node = this; while (node) { if (node.isDocument) { return node; } else { node = node.parent; } } }; XMLNode.prototype.end = function(options) { return this.document().end(options); }; XMLNode.prototype.prev = function() { var i; i = this.parent.children.indexOf(this); if (i < 1) { throw new Error("Already at the first node"); } return this.parent.children[i - 1]; }; XMLNode.prototype.next = function() { var i; i = this.parent.children.indexOf(this); if (i === -1 || i === this.parent.children.length - 1) { throw new Error("Already at the last node"); } return this.parent.children[i + 1]; }; XMLNode.prototype.importDocument = function(doc) { var clonedRoot; clonedRoot = doc.root().clone(); clonedRoot.parent = this; clonedRoot.isRoot = false; this.children.push(clonedRoot); return this; }; XMLNode.prototype.ele = function(name, attributes, text) { return this.element(name, attributes, text); }; XMLNode.prototype.nod = function(name, attributes, text) { return this.node(name, attributes, text); }; XMLNode.prototype.txt = function(value) { return this.text(value); }; XMLNode.prototype.dat = function(value) { return this.cdata(value); }; XMLNode.prototype.com = function(value) { return this.comment(value); }; XMLNode.prototype.ins = function(target, value) { return this.instruction(target, value); }; XMLNode.prototype.doc = function() { return this.document(); }; XMLNode.prototype.dec = function(version, encoding, standalone) { return this.declaration(version, encoding, standalone); }; XMLNode.prototype.dtd = function(pubID, sysID) { return this.doctype(pubID, sysID); }; XMLNode.prototype.e = function(name, attributes, text) { return this.element(name, attributes, text); }; XMLNode.prototype.n = function(name, attributes, text) { return this.node(name, attributes, text); }; XMLNode.prototype.t = function(value) { return this.text(value); }; XMLNode.prototype.d = function(value) { return this.cdata(value); }; XMLNode.prototype.c = function(value) { return this.comment(value); }; XMLNode.prototype.r = function(value) { return this.raw(value); }; XMLNode.prototype.i = function(target, value) { return this.instruction(target, value); }; XMLNode.prototype.u = function() { return this.up(); }; XMLNode.prototype.importXMLBuilder = function(doc) { return this.importDocument(doc); }; return XMLNode; })(); }).call(this); /***/ }), /***/ 7055: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLNode, XMLProcessingInstruction, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = __webpack_require__(94); module.exports = XMLProcessingInstruction = (function(superClass) { extend(XMLProcessingInstruction, superClass); function XMLProcessingInstruction(parent, target, value) { XMLProcessingInstruction.__super__.constructor.call(this, parent); if (target == null) { throw new Error("Missing instruction target"); } this.target = this.stringify.insTarget(target); if (value) { this.value = this.stringify.insValue(value); } } XMLProcessingInstruction.prototype.clone = function() { return Object.create(this); }; XMLProcessingInstruction.prototype.toString = function(options) { return this.options.writer.set(options).processingInstruction(this); }; return XMLProcessingInstruction; })(XMLNode); }).call(this); /***/ }), /***/ 1785: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLNode, XMLRaw, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = __webpack_require__(94); module.exports = XMLRaw = (function(superClass) { extend(XMLRaw, superClass); function XMLRaw(parent, text) { XMLRaw.__super__.constructor.call(this, parent); if (text == null) { throw new Error("Missing raw text"); } this.value = this.stringify.raw(text); } XMLRaw.prototype.clone = function() { return Object.create(this); }; XMLRaw.prototype.toString = function(options) { return this.options.writer.set(options).raw(this); }; return XMLRaw; })(XMLNode); }).call(this); /***/ }), /***/ 9427: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStreamWriter, XMLText, XMLWriterBase, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLDeclaration = __webpack_require__(7365); XMLDocType = __webpack_require__(1479); XMLCData = __webpack_require__(5851); XMLComment = __webpack_require__(1989); XMLElement = __webpack_require__(2433); XMLRaw = __webpack_require__(1785); XMLText = __webpack_require__(1879); XMLProcessingInstruction = __webpack_require__(7055); XMLDTDAttList = __webpack_require__(1586); XMLDTDElement = __webpack_require__(1800); XMLDTDEntity = __webpack_require__(3252); XMLDTDNotation = __webpack_require__(5360); XMLWriterBase = __webpack_require__(3935); module.exports = XMLStreamWriter = (function(superClass) { extend(XMLStreamWriter, superClass); function XMLStreamWriter(stream, options) { XMLStreamWriter.__super__.constructor.call(this, options); this.stream = stream; } XMLStreamWriter.prototype.document = function(doc) { var child, i, j, len, len1, ref, ref1, results; ref = doc.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; child.isLastRootNode = false; } doc.children[doc.children.length - 1].isLastRootNode = true; ref1 = doc.children; results = []; for (j = 0, len1 = ref1.length; j < len1; j++) { child = ref1[j]; switch (false) { case !(child instanceof XMLDeclaration): results.push(this.declaration(child)); break; case !(child instanceof XMLDocType): results.push(this.docType(child)); break; case !(child instanceof XMLComment): results.push(this.comment(child)); break; case !(child instanceof XMLProcessingInstruction): results.push(this.processingInstruction(child)); break; default: results.push(this.element(child)); } } return results; }; XMLStreamWriter.prototype.attribute = function(att) { return this.stream.write(' ' + att.name + '="' + att.value + '"'); }; XMLStreamWriter.prototype.cdata = function(node, level) { return this.stream.write(this.space(level) + '' + this.endline(node)); }; XMLStreamWriter.prototype.comment = function(node, level) { return this.stream.write(this.space(level) + '' + this.endline(node)); }; XMLStreamWriter.prototype.declaration = function(node, level) { this.stream.write(this.space(level)); this.stream.write(''); return this.stream.write(this.endline(node)); }; XMLStreamWriter.prototype.docType = function(node, level) { var child, i, len, ref; level || (level = 0); this.stream.write(this.space(level)); this.stream.write(' 0) { this.stream.write(' ['); this.stream.write(this.endline(node)); ref = node.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; switch (false) { case !(child instanceof XMLDTDAttList): this.dtdAttList(child, level + 1); break; case !(child instanceof XMLDTDElement): this.dtdElement(child, level + 1); break; case !(child instanceof XMLDTDEntity): this.dtdEntity(child, level + 1); break; case !(child instanceof XMLDTDNotation): this.dtdNotation(child, level + 1); break; case !(child instanceof XMLCData): this.cdata(child, level + 1); break; case !(child instanceof XMLComment): this.comment(child, level + 1); break; case !(child instanceof XMLProcessingInstruction): this.processingInstruction(child, level + 1); break; default: throw new Error("Unknown DTD node type: " + child.constructor.name); } } this.stream.write(']'); } this.stream.write(this.spacebeforeslash + '>'); return this.stream.write(this.endline(node)); }; XMLStreamWriter.prototype.element = function(node, level) { var att, child, i, len, name, ref, ref1, space; level || (level = 0); space = this.space(level); this.stream.write(space + '<' + node.name); ref = node.attributes; for (name in ref) { if (!hasProp.call(ref, name)) continue; att = ref[name]; this.attribute(att); } if (node.children.length === 0 || node.children.every(function(e) { return e.value === ''; })) { if (this.allowEmpty) { this.stream.write('>'); } else { this.stream.write(this.spacebeforeslash + '/>'); } } else if (this.pretty && node.children.length === 1 && (node.children[0].value != null)) { this.stream.write('>'); this.stream.write(node.children[0].value); this.stream.write(''); } else { this.stream.write('>' + this.newline); ref1 = node.children; for (i = 0, len = ref1.length; i < len; i++) { child = ref1[i]; switch (false) { case !(child instanceof XMLCData): this.cdata(child, level + 1); break; case !(child instanceof XMLComment): this.comment(child, level + 1); break; case !(child instanceof XMLElement): this.element(child, level + 1); break; case !(child instanceof XMLRaw): this.raw(child, level + 1); break; case !(child instanceof XMLText): this.text(child, level + 1); break; case !(child instanceof XMLProcessingInstruction): this.processingInstruction(child, level + 1); break; default: throw new Error("Unknown XML node type: " + child.constructor.name); } } this.stream.write(space + ''); } return this.stream.write(this.endline(node)); }; XMLStreamWriter.prototype.processingInstruction = function(node, level) { this.stream.write(this.space(level) + '' + this.endline(node)); }; XMLStreamWriter.prototype.raw = function(node, level) { return this.stream.write(this.space(level) + node.value + this.endline(node)); }; XMLStreamWriter.prototype.text = function(node, level) { return this.stream.write(this.space(level) + node.value + this.endline(node)); }; XMLStreamWriter.prototype.dtdAttList = function(node, level) { this.stream.write(this.space(level) + '' + this.endline(node)); }; XMLStreamWriter.prototype.dtdElement = function(node, level) { this.stream.write(this.space(level) + '' + this.endline(node)); }; XMLStreamWriter.prototype.dtdEntity = function(node, level) { this.stream.write(this.space(level) + '' + this.endline(node)); }; XMLStreamWriter.prototype.dtdNotation = function(node, level) { this.stream.write(this.space(level) + '' + this.endline(node)); }; XMLStreamWriter.prototype.endline = function(node) { if (!node.isLastRootNode) { return this.newline; } else { return ''; } }; return XMLStreamWriter; })(XMLWriterBase); }).call(this); /***/ }), /***/ 7155: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLText, XMLWriterBase, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLDeclaration = __webpack_require__(7365); XMLDocType = __webpack_require__(1479); XMLCData = __webpack_require__(5851); XMLComment = __webpack_require__(1989); XMLElement = __webpack_require__(2433); XMLRaw = __webpack_require__(1785); XMLText = __webpack_require__(1879); XMLProcessingInstruction = __webpack_require__(7055); XMLDTDAttList = __webpack_require__(1586); XMLDTDElement = __webpack_require__(1800); XMLDTDEntity = __webpack_require__(3252); XMLDTDNotation = __webpack_require__(5360); XMLWriterBase = __webpack_require__(3935); module.exports = XMLStringWriter = (function(superClass) { extend(XMLStringWriter, superClass); function XMLStringWriter(options) { XMLStringWriter.__super__.constructor.call(this, options); } XMLStringWriter.prototype.document = function(doc) { var child, i, len, r, ref; this.textispresent = false; r = ''; ref = doc.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; r += (function() { switch (false) { case !(child instanceof XMLDeclaration): return this.declaration(child); case !(child instanceof XMLDocType): return this.docType(child); case !(child instanceof XMLComment): return this.comment(child); case !(child instanceof XMLProcessingInstruction): return this.processingInstruction(child); default: return this.element(child, 0); } }).call(this); } if (this.pretty && r.slice(-this.newline.length) === this.newline) { r = r.slice(0, -this.newline.length); } return r; }; XMLStringWriter.prototype.attribute = function(att) { return ' ' + att.name + '="' + att.value + '"'; }; XMLStringWriter.prototype.cdata = function(node, level) { return this.space(level) + '' + this.newline; }; XMLStringWriter.prototype.comment = function(node, level) { return this.space(level) + '' + this.newline; }; XMLStringWriter.prototype.declaration = function(node, level) { var r; r = this.space(level); r += ''; r += this.newline; return r; }; XMLStringWriter.prototype.docType = function(node, level) { var child, i, len, r, ref; level || (level = 0); r = this.space(level); r += ' 0) { r += ' ['; r += this.newline; ref = node.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; r += (function() { switch (false) { case !(child instanceof XMLDTDAttList): return this.dtdAttList(child, level + 1); case !(child instanceof XMLDTDElement): return this.dtdElement(child, level + 1); case !(child instanceof XMLDTDEntity): return this.dtdEntity(child, level + 1); case !(child instanceof XMLDTDNotation): return this.dtdNotation(child, level + 1); case !(child instanceof XMLCData): return this.cdata(child, level + 1); case !(child instanceof XMLComment): return this.comment(child, level + 1); case !(child instanceof XMLProcessingInstruction): return this.processingInstruction(child, level + 1); default: throw new Error("Unknown DTD node type: " + child.constructor.name); } }).call(this); } r += ']'; } r += this.spacebeforeslash + '>'; r += this.newline; return r; }; XMLStringWriter.prototype.element = function(node, level) { var att, child, i, j, len, len1, name, r, ref, ref1, ref2, space, textispresentwasset; level || (level = 0); textispresentwasset = false; if (this.textispresent) { this.newline = ''; this.pretty = false; } else { this.newline = this.newlinedefault; this.pretty = this.prettydefault; } space = this.space(level); r = ''; r += space + '<' + node.name; ref = node.attributes; for (name in ref) { if (!hasProp.call(ref, name)) continue; att = ref[name]; r += this.attribute(att); } if (node.children.length === 0 || node.children.every(function(e) { return e.value === ''; })) { if (this.allowEmpty) { r += '>' + this.newline; } else { r += this.spacebeforeslash + '/>' + this.newline; } } else if (this.pretty && node.children.length === 1 && (node.children[0].value != null)) { r += '>'; r += node.children[0].value; r += '' + this.newline; } else { if (this.dontprettytextnodes) { ref1 = node.children; for (i = 0, len = ref1.length; i < len; i++) { child = ref1[i]; if (child.value != null) { this.textispresent++; textispresentwasset = true; break; } } } if (this.textispresent) { this.newline = ''; this.pretty = false; space = this.space(level); } r += '>' + this.newline; ref2 = node.children; for (j = 0, len1 = ref2.length; j < len1; j++) { child = ref2[j]; r += (function() { switch (false) { case !(child instanceof XMLCData): return this.cdata(child, level + 1); case !(child instanceof XMLComment): return this.comment(child, level + 1); case !(child instanceof XMLElement): return this.element(child, level + 1); case !(child instanceof XMLRaw): return this.raw(child, level + 1); case !(child instanceof XMLText): return this.text(child, level + 1); case !(child instanceof XMLProcessingInstruction): return this.processingInstruction(child, level + 1); default: throw new Error("Unknown XML node type: " + child.constructor.name); } }).call(this); } if (textispresentwasset) { this.textispresent--; } if (!this.textispresent) { this.newline = this.newlinedefault; this.pretty = this.prettydefault; } r += space + '' + this.newline; } return r; }; XMLStringWriter.prototype.processingInstruction = function(node, level) { var r; r = this.space(level) + '' + this.newline; return r; }; XMLStringWriter.prototype.raw = function(node, level) { return this.space(level) + node.value + this.newline; }; XMLStringWriter.prototype.text = function(node, level) { return this.space(level) + node.value + this.newline; }; XMLStringWriter.prototype.dtdAttList = function(node, level) { var r; r = this.space(level) + '' + this.newline; return r; }; XMLStringWriter.prototype.dtdElement = function(node, level) { return this.space(level) + '' + this.newline; }; XMLStringWriter.prototype.dtdEntity = function(node, level) { var r; r = this.space(level) + '' + this.newline; return r; }; XMLStringWriter.prototype.dtdNotation = function(node, level) { var r; r = this.space(level) + '' + this.newline; return r; }; XMLStringWriter.prototype.openNode = function(node, level) { var att, name, r, ref; level || (level = 0); if (node instanceof XMLElement) { r = this.space(level) + '<' + node.name; ref = node.attributes; for (name in ref) { if (!hasProp.call(ref, name)) continue; att = ref[name]; r += this.attribute(att); } r += (node.children ? '>' : '/>') + this.newline; return r; } else { r = this.space(level) + '') + this.newline; return r; } }; XMLStringWriter.prototype.closeNode = function(node, level) { level || (level = 0); switch (false) { case !(node instanceof XMLElement): return this.space(level) + '' + this.newline; case !(node instanceof XMLDocType): return this.space(level) + ']>' + this.newline; } }; return XMLStringWriter; })(XMLWriterBase); }).call(this); /***/ }), /***/ 926: /***/ (function(module) { // Generated by CoffeeScript 1.12.7 (function() { var XMLStringifier, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, hasProp = {}.hasOwnProperty; module.exports = XMLStringifier = (function() { function XMLStringifier(options) { this.assertLegalChar = bind(this.assertLegalChar, this); var key, ref, value; options || (options = {}); this.noDoubleEncoding = options.noDoubleEncoding; ref = options.stringify || {}; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; this[key] = value; } } XMLStringifier.prototype.eleName = function(val) { val = '' + val || ''; return this.assertLegalChar(val); }; XMLStringifier.prototype.eleText = function(val) { val = '' + val || ''; return this.assertLegalChar(this.elEscape(val)); }; XMLStringifier.prototype.cdata = function(val) { val = '' + val || ''; val = val.replace(']]>', ']]]]>'); return this.assertLegalChar(val); }; XMLStringifier.prototype.comment = function(val) { val = '' + val || ''; if (val.match(/--/)) { throw new Error("Comment text cannot contain double-hypen: " + val); } return this.assertLegalChar(val); }; XMLStringifier.prototype.raw = function(val) { return '' + val || ''; }; XMLStringifier.prototype.attName = function(val) { return val = '' + val || ''; }; XMLStringifier.prototype.attValue = function(val) { val = '' + val || ''; return this.attEscape(val); }; XMLStringifier.prototype.insTarget = function(val) { return '' + val || ''; }; XMLStringifier.prototype.insValue = function(val) { val = '' + val || ''; if (val.match(/\?>/)) { throw new Error("Invalid processing instruction value: " + val); } return val; }; XMLStringifier.prototype.xmlVersion = function(val) { val = '' + val || ''; if (!val.match(/1\.[0-9]+/)) { throw new Error("Invalid version number: " + val); } return val; }; XMLStringifier.prototype.xmlEncoding = function(val) { val = '' + val || ''; if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) { throw new Error("Invalid encoding: " + val); } return val; }; XMLStringifier.prototype.xmlStandalone = function(val) { if (val) { return "yes"; } else { return "no"; } }; XMLStringifier.prototype.dtdPubID = function(val) { return '' + val || ''; }; XMLStringifier.prototype.dtdSysID = function(val) { return '' + val || ''; }; XMLStringifier.prototype.dtdElementValue = function(val) { return '' + val || ''; }; XMLStringifier.prototype.dtdAttType = function(val) { return '' + val || ''; }; XMLStringifier.prototype.dtdAttDefault = function(val) { if (val != null) { return '' + val || ''; } else { return val; } }; XMLStringifier.prototype.dtdEntityValue = function(val) { return '' + val || ''; }; XMLStringifier.prototype.dtdNData = function(val) { return '' + val || ''; }; XMLStringifier.prototype.convertAttKey = '@'; XMLStringifier.prototype.convertPIKey = '?'; XMLStringifier.prototype.convertTextKey = '#text'; XMLStringifier.prototype.convertCDataKey = '#cdata'; XMLStringifier.prototype.convertCommentKey = '#comment'; XMLStringifier.prototype.convertRawKey = '#raw'; XMLStringifier.prototype.assertLegalChar = function(str) { var res; res = str.match(/[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/); if (res) { throw new Error("Invalid character in string: " + str + " at index " + res.index); } return str; }; XMLStringifier.prototype.elEscape = function(str) { var ampregex; ampregex = this.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g; return str.replace(ampregex, '&').replace(//g, '>').replace(/\r/g, ' '); }; XMLStringifier.prototype.attEscape = function(str) { var ampregex; ampregex = this.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g; return str.replace(ampregex, '&').replace(/ 0) { return new Array(indent).join(this.indent); } else { return ''; } } else { return ''; } }; return XMLWriterBase; })(); }).call(this); /***/ }), /***/ 2066: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref; ref = __webpack_require__(8318), assign = ref.assign, isFunction = ref.isFunction; XMLDocument = __webpack_require__(5255); XMLDocumentCB = __webpack_require__(9587); XMLStringWriter = __webpack_require__(7155); XMLStreamWriter = __webpack_require__(9427); module.exports.create = function(name, xmldec, doctype, options) { var doc, root; if (name == null) { throw new Error("Root element needs a name"); } options = assign({}, xmldec, doctype, options); doc = new XMLDocument(options); root = doc.element(name); if (!options.headless) { doc.declaration(options); if ((options.pubID != null) || (options.sysID != null)) { doc.doctype(options); } } return root; }; module.exports.begin = function(options, onData, onEnd) { var ref1; if (isFunction(options)) { ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1]; options = {}; } if (onData) { return new XMLDocumentCB(options, onData, onEnd); } else { return new XMLDocument(options); } }; module.exports.stringWriter = function(options) { return new XMLStringWriter(options); }; module.exports.streamWriter = function(stream, options) { return new XMLStreamWriter(stream, options); }; }).call(this); /***/ }), /***/ 5637: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { if (process.env.npm_package_name === 'pseudomap' && process.env.npm_lifecycle_script === 'test') process.env.TEST_PSEUDOMAP = 'true' if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) { module.exports = Map } else { module.exports = __webpack_require__(5411) } /***/ }), /***/ 5411: /***/ ((module) => { var hasOwnProperty = Object.prototype.hasOwnProperty module.exports = PseudoMap function PseudoMap (set) { if (!(this instanceof PseudoMap)) // whyyyyyyy throw new TypeError("Constructor PseudoMap requires 'new'") this.clear() if (set) { if ((set instanceof PseudoMap) || (typeof Map === 'function' && set instanceof Map)) set.forEach(function (value, key) { this.set(key, value) }, this) else if (Array.isArray(set)) set.forEach(function (kv) { this.set(kv[0], kv[1]) }, this) else throw new TypeError('invalid argument') } } PseudoMap.prototype.forEach = function (fn, thisp) { thisp = thisp || this Object.keys(this._data).forEach(function (k) { if (k !== 'size') fn.call(thisp, this._data[k].value, this._data[k].key) }, this) } PseudoMap.prototype.has = function (k) { return !!find(this._data, k) } PseudoMap.prototype.get = function (k) { var res = find(this._data, k) return res && res.value } PseudoMap.prototype.set = function (k, v) { set(this._data, k, v) } PseudoMap.prototype.delete = function (k) { var res = find(this._data, k) if (res) { delete this._data[res._index] this._data.size-- } } PseudoMap.prototype.clear = function () { var data = Object.create(null) data.size = 0 Object.defineProperty(this, '_data', { value: data, enumerable: false, configurable: true, writable: false }) } Object.defineProperty(PseudoMap.prototype, 'size', { get: function () { return this._data.size }, set: function (n) {}, enumerable: true, configurable: true }) PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function () { throw new Error('iterators are not implemented in this version') } // Either identical, or both NaN function same (a, b) { return a === b || a !== a && b !== b } function Entry (k, v, i) { this.key = k this.value = v this._index = i } function find (data, k) { for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) { if (same(data[key].key, k)) return data[key] } } function set (data, k, v) { for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) { if (same(data[key].key, k)) { data[key].value = v return } } data.size++ data[key] = new Entry(k, v, key) } /***/ }), /***/ 652: /***/ ((module) => { "use strict"; /*! * repeat-string * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ /** * Results cache */ var res = ''; var cache; /** * Expose `repeat` */ module.exports = repeat; /** * Repeat the given `string` the specified `number` * of times. * * **Example:** * * ```js * var repeat = require('repeat-string'); * repeat('A', 5); * //=> AAAAA * ``` * * @param {String} `string` The string to repeat * @param {Number} `number` The number of times to repeat the string * @return {String} Repeated string * @api public */ function repeat(str, num) { if (typeof str !== 'string') { throw new TypeError('expected a string'); } // cover common, quick use cases if (num === 1) return str; if (num === 2) return str + str; var max = str.length * num; if (cache !== str || typeof cache === 'undefined') { cache = str; res = ''; } else if (res.length >= max) { return res.substr(0, max); } while (max > res.length && num > 1) { if (num & 1) { res += str; } num >>= 1; str += str; } res += str; res = res.substr(0, max); return res; } /***/ }), /***/ 3844: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = rimraf rimraf.sync = rimrafSync var assert = __webpack_require__(2357) var path = __webpack_require__(5622) var fs = __webpack_require__(5747) var glob = undefined try { glob = __webpack_require__(6825) } catch (_err) { // treat glob as optional. } var _0666 = parseInt('666', 8) var defaultGlobOpts = { nosort: true, silent: true } // for EMFILE handling var timeout = 0 var isWindows = (process.platform === "win32") function defaults (options) { var methods = [ 'unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir' ] methods.forEach(function(m) { options[m] = options[m] || fs[m] m = m + 'Sync' options[m] = options[m] || fs[m] }) options.maxBusyTries = options.maxBusyTries || 3 options.emfileWait = options.emfileWait || 1000 if (options.glob === false) { options.disableGlob = true } if (options.disableGlob !== true && glob === undefined) { throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') } options.disableGlob = options.disableGlob || false options.glob = options.glob || defaultGlobOpts } function rimraf (p, options, cb) { if (typeof options === 'function') { cb = options options = {} } assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert.equal(typeof cb, 'function', 'rimraf: callback function required') assert(options, 'rimraf: invalid options argument provided') assert.equal(typeof options, 'object', 'rimraf: options should be object') defaults(options) var busyTries = 0 var errState = null var n = 0 if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]) options.lstat(p, function (er, stat) { if (!er) return afterGlob(null, [p]) glob(p, options.glob, afterGlob) }) function next (er) { errState = errState || er if (--n === 0) cb(errState) } function afterGlob (er, results) { if (er) return cb(er) n = results.length if (n === 0) return cb() results.forEach(function (p) { rimraf_(p, options, function CB (er) { if (er) { if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { busyTries ++ var time = busyTries * 100 // try again, with the same exact callback as this one. return setTimeout(function () { rimraf_(p, options, CB) }, time) } // this one won't happen if graceful-fs is used. if (er.code === "EMFILE" && timeout < options.emfileWait) { return setTimeout(function () { rimraf_(p, options, CB) }, timeout ++) } // already gone if (er.code === "ENOENT") er = null } timeout = 0 next(er) }) }) } } // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. function rimraf_ (p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, function (er, st) { if (er && er.code === "ENOENT") return cb(null) // Windows can EPERM on stat. Life is suffering. if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb) if (st && st.isDirectory()) return rmdir(p, options, er, cb) options.unlink(p, function (er) { if (er) { if (er.code === "ENOENT") return cb(null) if (er.code === "EPERM") return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) if (er.code === "EISDIR") return rmdir(p, options, er, cb) } return cb(er) }) }) } function fixWinEPERM (p, options, er, cb) { assert(p) assert(options) assert(typeof cb === 'function') if (er) assert(er instanceof Error) options.chmod(p, _0666, function (er2) { if (er2) cb(er2.code === "ENOENT" ? null : er) else options.stat(p, function(er3, stats) { if (er3) cb(er3.code === "ENOENT" ? null : er) else if (stats.isDirectory()) rmdir(p, options, er, cb) else options.unlink(p, cb) }) }) } function fixWinEPERMSync (p, options, er) { assert(p) assert(options) if (er) assert(er instanceof Error) try { options.chmodSync(p, _0666) } catch (er2) { if (er2.code === "ENOENT") return else throw er } try { var stats = options.statSync(p) } catch (er3) { if (er3.code === "ENOENT") return else throw er } if (stats.isDirectory()) rmdirSync(p, options, er) else options.unlinkSync(p) } function rmdir (p, options, originalEr, cb) { assert(p) assert(options) if (originalEr) assert(originalEr instanceof Error) assert(typeof cb === 'function') // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) // if we guessed wrong, and it's not a directory, then // raise the original error. options.rmdir(p, function (er) { if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb) else if (er && er.code === "ENOTDIR") cb(originalEr) else cb(er) }) } function rmkids(p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') options.readdir(p, function (er, files) { if (er) return cb(er) var n = files.length if (n === 0) return options.rmdir(p, cb) var errState files.forEach(function (f) { rimraf(path.join(p, f), options, function (er) { if (errState) return if (er) return cb(errState = er) if (--n === 0) options.rmdir(p, cb) }) }) }) } // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. function rimrafSync (p, options) { options = options || {} defaults(options) assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert(options, 'rimraf: missing options') assert.equal(typeof options, 'object', 'rimraf: options should be object') var results if (options.disableGlob || !glob.hasMagic(p)) { results = [p] } else { try { options.lstatSync(p) results = [p] } catch (er) { results = glob.sync(p, options.glob) } } if (!results.length) return for (var i = 0; i < results.length; i++) { var p = results[i] try { var st = options.lstatSync(p) } catch (er) { if (er.code === "ENOENT") return // Windows can EPERM on stat. Life is suffering. if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er) } try { // sunos lets the root user unlink directories, which is... weird. if (st && st.isDirectory()) rmdirSync(p, options, null) else options.unlinkSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) if (er.code !== "EISDIR") throw er rmdirSync(p, options, er) } } } function rmdirSync (p, options, originalEr) { assert(p) assert(options) if (originalEr) assert(originalEr instanceof Error) try { options.rmdirSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "ENOTDIR") throw originalEr if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options) } } function rmkidsSync (p, options) { assert(p) assert(options) options.readdirSync(p).forEach(function (f) { rimrafSync(path.join(p, f), options) }) // We only end up here once we got ENOTEMPTY at least once, and // at this point, we are guaranteed to have removed all the kids. // So, we know that it won't be ENOENT or ENOTDIR or anything else. // try really hard to delete stuff on windows, because it has a // PROFOUNDLY annoying habit of not closing handles promptly when // files are deleted, resulting in spurious ENOTEMPTY errors. var retries = isWindows ? 100 : 1 var i = 0 do { var threw = true try { var ret = options.rmdirSync(p, options) threw = false return ret } finally { if (++i < retries && threw) continue } } while (true) } /***/ }), /***/ 2751: /***/ ((module, exports) => { exports = module.exports = SemVer var debug /* istanbul ignore next */ if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) { debug = function () { var args = Array.prototype.slice.call(arguments, 0) args.unshift('SEMVER') console.log.apply(console, args) } } else { debug = function () {} } // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. exports.SEMVER_SPEC_VERSION = '2.0.0' var MAX_LENGTH = 256 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. var MAX_SAFE_COMPONENT_LENGTH = 16 // The actual regexps go on exports.re var re = exports.re = [] var src = exports.src = [] var R = 0 // 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. var NUMERICIDENTIFIER = R++ src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' var NUMERICIDENTIFIERLOOSE = R++ src[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. var NONNUMERICIDENTIFIER = R++ src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' // ## Main Version // Three dot-separated numeric identifiers. var MAINVERSION = R++ src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')' var MAINVERSIONLOOSE = R++ src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. var PRERELEASEIDENTIFIER = R++ src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')' var PRERELEASEIDENTIFIERLOOSE = R++ src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')' // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. var PRERELEASE = R++ src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' var PRERELEASELOOSE = R++ src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. var BUILDIDENTIFIER = R++ src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. var BUILD = R++ src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[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. var FULL = R++ var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?' src[FULL] = '^' + 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. var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?' var LOOSE = R++ src[LOOSE] = '^' + LOOSEPLAIN + '$' var GTLT = R++ src[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. var XRANGEIDENTIFIERLOOSE = R++ src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' var XRANGEIDENTIFIER = R++ src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' var XRANGEPLAIN = R++ src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?' var XRANGEPLAINLOOSE = R++ src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?' var XRANGE = R++ src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' var XRANGELOOSE = R++ src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' // Coercion. // Extract anything that could conceivably be a part of a valid semver var COERCE = R++ src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])' // Tilde ranges. // Meaning is "reasonably at or greater than" var LONETILDE = R++ src[LONETILDE] = '(?:~>?)' var TILDETRIM = R++ src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') var tildeTrimReplace = '$1~' var TILDE = R++ src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' var TILDELOOSE = R++ src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' // Caret ranges. // Meaning is "at least and backwards compatible with" var LONECARET = R++ src[LONECARET] = '(?:\\^)' var CARETTRIM = R++ src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') var caretTrimReplace = '$1^' var CARET = R++ src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' var CARETLOOSE = R++ src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' // A simple gt/lt/eq thing, or just "" to indicate "any version" var COMPARATORLOOSE = R++ src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' var COMPARATOR = R++ src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` var COMPARATORTRIM = R++ src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' // this one has to use the /g flag re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') var 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. var HYPHENRANGE = R++ src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$' var HYPHENRANGELOOSE = R++ src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$' // Star ranges basically just allow anything at all. var STAR = R++ src[STAR] = '(<|>)?=?\\s*\\*' // Compile to actual regexp objects. // All are flag-free, unless they were created above with a flag. for (var i = 0; i < R; i++) { debug(i, src[i]) if (!re[i]) { re[i] = new RegExp(src[i]) } } exports.parse = parse function parse (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { return version } if (typeof version !== 'string') { return null } if (version.length > MAX_LENGTH) { return null } var r = options.loose ? re[LOOSE] : re[FULL] if (!r.test(version)) { return null } try { return new SemVer(version, options) } catch (er) { return null } } exports.valid = valid function valid (version, options) { var v = parse(version, options) return v ? v.version : null } exports.clean = clean function clean (version, options) { var s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } exports.SemVer = SemVer function SemVer (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { if (version.loose === options.loose) { 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') } if (!(this instanceof SemVer)) { return new SemVer(version, options) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose var m = version.trim().match(options.loose ? re[LOOSE] : re[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(function (id) { if (/^[0-9]+$/.test(id)) { var num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } SemVer.prototype.format = function () { this.version = this.major + '.' + this.minor + '.' + this.patch if (this.prerelease.length) { this.version += '-' + this.prerelease.join('.') } return this.version } SemVer.prototype.toString = function () { return this.version } SemVer.prototype.compare = function (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return this.compareMain(other) || this.comparePre(other) } SemVer.prototype.compareMain = function (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) } SemVer.prototype.comparePre = function (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 } var i = 0 do { var a = this.prerelease[i] var 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) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. SemVer.prototype.inc = function (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 { var 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 } exports.inc = inc function inc (version, release, loose, identifier) { if (typeof (loose) === 'string') { identifier = loose loose = undefined } try { return new SemVer(version, loose).inc(release, identifier).version } catch (er) { return null } } exports.diff = diff function diff (version1, version2) { if (eq(version1, version2)) { return null } else { var v1 = parse(version1) var v2 = parse(version2) var prefix = '' if (v1.prerelease.length || v2.prerelease.length) { prefix = 'pre' var defaultResult = 'prerelease' } for (var key in v1) { if (key === 'major' || key === 'minor' || key === 'patch') { if (v1[key] !== v2[key]) { return prefix + key } } } return defaultResult // may be undefined } } exports.compareIdentifiers = compareIdentifiers var numeric = /^[0-9]+$/ function compareIdentifiers (a, b) { var anum = numeric.test(a) var 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 } exports.rcompareIdentifiers = rcompareIdentifiers function rcompareIdentifiers (a, b) { return compareIdentifiers(b, a) } exports.major = major function major (a, loose) { return new SemVer(a, loose).major } exports.minor = minor function minor (a, loose) { return new SemVer(a, loose).minor } exports.patch = patch function patch (a, loose) { return new SemVer(a, loose).patch } exports.compare = compare function compare (a, b, loose) { return new SemVer(a, loose).compare(new SemVer(b, loose)) } exports.compareLoose = compareLoose function compareLoose (a, b) { return compare(a, b, true) } exports.rcompare = rcompare function rcompare (a, b, loose) { return compare(b, a, loose) } exports.sort = sort function sort (list, loose) { return list.sort(function (a, b) { return exports.compare(a, b, loose) }) } exports.rsort = rsort function rsort (list, loose) { return list.sort(function (a, b) { return exports.rcompare(a, b, loose) }) } exports.gt = gt function gt (a, b, loose) { return compare(a, b, loose) > 0 } exports.lt = lt function lt (a, b, loose) { return compare(a, b, loose) < 0 } exports.eq = eq function eq (a, b, loose) { return compare(a, b, loose) === 0 } exports.neq = neq function neq (a, b, loose) { return compare(a, b, loose) !== 0 } exports.gte = gte function gte (a, b, loose) { return compare(a, b, loose) >= 0 } exports.lte = lte function lte (a, b, loose) { return compare(a, b, loose) <= 0 } exports.cmp = cmp function 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) } } exports.Comparator = Comparator function Comparator (comp, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } if (!(this instanceof Comparator)) { return new Comparator(comp, options) } 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) } var ANY = {} Comparator.prototype.parse = function (comp) { var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] var m = comp.match(r) if (!m) { throw new TypeError('Invalid comparator: ' + comp) } this.operator = 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) } } Comparator.prototype.toString = function () { return this.value } Comparator.prototype.test = function (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY) { return true } if (typeof version === 'string') { version = new SemVer(version, this.options) } return cmp(version, this.operator, this.semver, this.options) } Comparator.prototype.intersects = function (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } var rangeTmp if (this.operator === '') { rangeTmp = new Range(comp.value, options) return satisfies(this.value, rangeTmp, options) } else if (comp.operator === '') { rangeTmp = new Range(this.value, options) return satisfies(comp.semver, rangeTmp, options) } var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>') var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<') var sameSemVer = this.semver.version === comp.semver.version var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=') var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && ((this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<')) var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && ((this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>')) return sameDirectionIncreasing || sameDirectionDecreasing || (sameSemVer && differentDirectionsInclusive) || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan } exports.Range = Range function Range (range, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } 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) { return new Range(range.value, options) } if (!(this instanceof Range)) { return new Range(range, options) } 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(function (range) { return this.parseRange(range.trim()) }, this).filter(function (c) { // throw out any that are not relevant for whatever reason return c.length }) if (!this.set.length) { throw new TypeError('Invalid SemVer Range: ' + range) } this.format() } Range.prototype.format = function () { this.range = this.set.map(function (comps) { return comps.join(' ').trim() }).join('||').trim() return this.range } Range.prototype.toString = function () { return this.range } Range.prototype.parseRange = function (range) { var loose = this.options.loose range = range.trim() // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] range = range.replace(hr, hyphenReplace) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range, re[COMPARATORTRIM]) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[TILDETRIM], tildeTrimReplace) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[CARETTRIM], caretTrimReplace) // normalize spaces range = range.split(/\s+/).join(' ') // At this point, the range is completely trimmed and // ready to be split into comparators. var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] var set = range.split(' ').map(function (comp) { return parseComparator(comp, this.options) }, this).join(' ').split(/\s+/) if (this.options.loose) { // in loose mode, throw out any that are not valid comparators set = set.filter(function (comp) { return !!comp.match(compRe) }) } set = set.map(function (comp) { return new Comparator(comp, this.options) }, this) return set } Range.prototype.intersects = function (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some(function (thisComparators) { return thisComparators.every(function (thisComparator) { return range.set.some(function (rangeComparators) { return rangeComparators.every(function (rangeComparator) { return thisComparator.intersects(rangeComparator, options) }) }) }) }) } // Mostly just for testing and legacy API reasons exports.toComparators = toComparators function toComparators (range, options) { return new Range(range, options).set.map(function (comp) { return comp.map(function (c) { return c.value }).join(' ').trim().split(' ') }) } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. function 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 } function isX (id) { return !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 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 function replaceTildes (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceTilde(comp, options) }).join(' ') } function replaceTilde (comp, options) { var r = options.loose ? re[TILDELOOSE] : re[TILDE] return comp.replace(r, function (_, M, m, p, pr) { debug('tilde', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else if (pr) { debug('replaceTilde pr', pr) ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } else { // ~1.2.3 == >=1.2.3 <1.3.0 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 // ^1.2.3 --> >=1.2.3 <2.0.0 // ^1.2.0 --> >=1.2.0 <2.0.0 function replaceCarets (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceCaret(comp, options) }).join(' ') } function replaceCaret (comp, options) { debug('caret', comp, options) var r = options.loose ? re[CARETLOOSE] : re[CARET] return comp.replace(r, function (_, M, m, p, pr) { debug('caret', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { if (M === '0') { ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else { ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0' } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0' } } debug('caret return', ret) return ret }) } function replaceXRanges (comp, options) { debug('replaceXRanges', comp, options) return comp.split(/\s+/).map(function (comp) { return replaceXRange(comp, options) }).join(' ') } function replaceXRange (comp, options) { comp = comp.trim() var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] return comp.replace(r, function (ret, gtlt, M, m, p, pr) { debug('xRange', comp, ret, gtlt, M, m, p, pr) var xM = isX(M) var xm = xM || isX(m) var xp = xm || isX(p) var anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<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 // >1.2.3 => >= 1.2.4 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 } } ret = gtlt + M + '.' + m + '.' + p } else if (xm) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (xp) { ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.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. function replaceStars (comp, options) { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp.trim().replace(re[STAR], '') } // This function is passed to string.replace(re[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 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0 function hyphenReplace ($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' } else if (isX(fp)) { from = '>=' + fM + '.' + fm + '.0' } else { from = '>=' + from } if (isX(tM)) { to = '' } else if (isX(tm)) { to = '<' + (+tM + 1) + '.0.0' } else if (isX(tp)) { to = '<' + tM + '.' + (+tm + 1) + '.0' } else if (tpr) { to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr } else { to = '<=' + to } return (from + ' ' + to).trim() } // if ANY of the sets match ALL of its comparators, then pass Range.prototype.test = function (version) { if (!version) { return false } if (typeof version === 'string') { version = new SemVer(version, this.options) } for (var i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } function testSet (set, version, options) { for (var 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 (i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === ANY) { continue } if (set[i].semver.prerelease.length > 0) { var 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 } exports.satisfies = satisfies function satisfies (version, range, options) { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } exports.maxSatisfying = maxSatisfying function maxSatisfying (versions, range, options) { var max = null var maxSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (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 } exports.minSatisfying = minSatisfying function minSatisfying (versions, range, options) { var min = null var minSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (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 } exports.minVersion = minVersion function minVersion (range, loose) { range = new Range(range, loose) var 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 (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] comparators.forEach(function (comparator) { // Clone to avoid manipulating the comparator's semver object. var 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 (!minver || gt(minver, compver)) { minver = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error('Unexpected operation: ' + comparator.operator) } }) } if (minver && range.test(minver)) { return minver } return null } exports.validRange = validRange function 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 } } // Determine if version is less than all the versions possible in the range exports.ltr = ltr function ltr (version, range, options) { return outside(version, range, '<', options) } // Determine if version is greater than all the versions possible in the range. exports.gtr = gtr function gtr (version, range, options) { return outside(version, range, '>', options) } exports.outside = outside function outside (version, range, hilo, options) { version = new SemVer(version, options) range = new Range(range, options) var 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 satisifes 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 (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] var high = null var low = null comparators.forEach(function (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 } exports.prerelease = prerelease function prerelease (version, options) { var parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } exports.intersects = intersects function intersects (r1, r2, options) { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2) } exports.coerce = coerce function coerce (version) { if (version instanceof SemVer) { return version } if (typeof version !== 'string') { return null } var match = version.match(re[COERCE]) if (match == null) { return null } return parse(match[1] + '.' + (match[2] || '0') + '.' + (match[3] || '0')) } /***/ }), /***/ 1938: /***/ ((module) => { "use strict"; function isFunction (funktion) { return typeof funktion === 'function' } // Default to complaining loudly when things don't go according to plan. var logger = console.error.bind(console) // Sets a property on an object, preserving its enumerability. // This function assumes that the property is already writable. function defineProperty (obj, name, value) { var enumerable = !!obj[name] && obj.propertyIsEnumerable(name) Object.defineProperty(obj, name, { configurable: true, enumerable: enumerable, writable: true, value: value }) } // Keep initialization idempotent. function shimmer (options) { if (options && options.logger) { if (!isFunction(options.logger)) logger("new logger isn't a function, not replacing") else logger = options.logger } } function wrap (nodule, name, wrapper) { if (!nodule || !nodule[name]) { logger('no original function ' + name + ' to wrap') return } if (!wrapper) { logger('no wrapper function') logger((new Error()).stack) return } if (!isFunction(nodule[name]) || !isFunction(wrapper)) { logger('original object and wrapper must be functions') return } var original = nodule[name] var wrapped = wrapper(original, name) defineProperty(wrapped, '__original', original) defineProperty(wrapped, '__unwrap', function () { if (nodule[name] === wrapped) defineProperty(nodule, name, original) }) defineProperty(wrapped, '__wrapped', true) defineProperty(nodule, name, wrapped) return wrapped } function massWrap (nodules, names, wrapper) { if (!nodules) { logger('must provide one or more modules to patch') logger((new Error()).stack) return } else if (!Array.isArray(nodules)) { nodules = [nodules] } if (!(names && Array.isArray(names))) { logger('must provide one or more functions to wrap on modules') return } nodules.forEach(function (nodule) { names.forEach(function (name) { wrap(nodule, name, wrapper) }) }) } function unwrap (nodule, name) { if (!nodule || !nodule[name]) { logger('no function to unwrap.') logger((new Error()).stack) return } if (!nodule[name].__unwrap) { logger('no original to unwrap to -- has ' + name + ' already been unwrapped?') } else { return nodule[name].__unwrap() } } function massUnwrap (nodules, names) { if (!nodules) { logger('must provide one or more modules to patch') logger((new Error()).stack) return } else if (!Array.isArray(nodules)) { nodules = [nodules] } if (!(names && Array.isArray(names))) { logger('must provide one or more functions to unwrap on modules') return } nodules.forEach(function (nodule) { names.forEach(function (name) { unwrap(nodule, name) }) }) } shimmer.wrap = wrap shimmer.massWrap = massWrap shimmer.unwrap = unwrap shimmer.massUnwrap = massUnwrap module.exports = shimmer /***/ }), /***/ 2462: /***/ ((module) => { module.exports = sigmund function sigmund (subject, maxSessions) { maxSessions = maxSessions || 10; var notes = []; var analysis = ''; var RE = RegExp; function psychoAnalyze (subject, session) { if (session > maxSessions) return; if (typeof subject === 'function' || typeof subject === 'undefined') { return; } if (typeof subject !== 'object' || !subject || (subject instanceof RE)) { analysis += subject; return; } if (notes.indexOf(subject) !== -1 || session === maxSessions) return; notes.push(subject); analysis += '{'; Object.keys(subject).forEach(function (issue, _, __) { // pseudo-private values. skip those. if (issue.charAt(0) === '_') return; var to = typeof subject[issue]; if (to === 'function' || to === 'undefined') return; analysis += issue; psychoAnalyze(subject[issue], session + 1); }); } psychoAnalyze(subject, 0); return analysis; } // vim: set softtabstop=4 shiftwidth=4: /***/ }), /***/ 7054: /***/ ((module) => { // Copyright 2012 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. function FormatErrorString(error) { try { return Error.prototype.toString.call(error); } catch (e) { try { return ""; } catch (ee) { return ""; } } } module.exports = function FormatStackTrace(error, frames) { var lines = []; lines.push(FormatErrorString(error)); for (var i = 0; i < frames.length; i++) { var frame = frames[i]; var line; try { line = frame.toString(); } catch (e) { try { line = ""; } catch (ee) { // Any code that reaches this point is seriously nasty! line = ""; } } lines.push(" at " + line); } return lines.join("\n"); }; /***/ }), /***/ 6056: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // If a another copy (same version or not) of stack-chain exists it will result // in wrong stack traces (most likely dublicate callSites). if (global._stackChain) { // In case the version match, we can simply return the first initialized copy if (global._stackChain.version === __webpack_require__(2532)/* .version */ .i8) { module.exports = global._stackChain; } // The version don't match, this is really bad. Lets just throw else { throw new Error('Conflicting version of stack-chain found'); } } // Yay, no other stack-chain copy exists, yet :/ else { module.exports = global._stackChain = __webpack_require__(3005); } /***/ }), /***/ 2532: /***/ ((module) => { "use strict"; module.exports = {"i8":"1.3.7"}; /***/ }), /***/ 3005: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // use a already existing formater or fallback to the default v8 formater var defaultFormater = __webpack_require__(7054); // public define API function stackChain() { this.extend = new TraceModifier(); this.filter = new TraceModifier(); this.format = new StackFormater(); this.version = __webpack_require__(2532)/* .version */ .i8; } var SHORTCIRCUIT_CALLSITE = false; stackChain.prototype.callSite = function collectCallSites(options) { if (!options) options = {}; // Get CallSites SHORTCIRCUIT_CALLSITE = true; var obj = {}; Error.captureStackTrace(obj, collectCallSites); var callSites = obj.stack; SHORTCIRCUIT_CALLSITE = false; // Slice callSites = callSites.slice(options.slice || 0); // Modify CallSites if (options.extend) callSites = this.extend._modify(obj, callSites); if (options.filter) callSites = this.filter._modify(obj, callSites); // Done return callSites; }; var chain = new stackChain(); function TraceModifier() { this._modifiers = []; } TraceModifier.prototype._modify = function (error, frames) { for (var i = 0, l = this._modifiers.length; i < l; i++) { frames = this._modifiers[i](error, frames); } return frames; }; TraceModifier.prototype.attach = function (modifier) { this._modifiers.push(modifier); }; TraceModifier.prototype.deattach = function (modifier) { var index = this._modifiers.indexOf(modifier); if (index === -1) return false; this._modifiers.splice(index, 1); return true; }; function StackFormater() { this._formater = defaultFormater; this._previous = undefined; } StackFormater.prototype.replace = function (formater) { if (formater) { this._formater = formater; } else { this.restore(); } }; StackFormater.prototype.restore = function () { this._formater = defaultFormater; this._previous = undefined; }; StackFormater.prototype._backup = function () { this._previous = this._formater; }; StackFormater.prototype._roolback = function () { if (this._previous === defaultFormater) { this.replace(undefined); } else { this.replace(this._previous); } this._previous = undefined; }; // // Set Error.prepareStackTrace thus allowing stack-chain // to take control of the Error().stack formating. // // If there already is a custom stack formater, then set // that as the stack-chain formater. if (Error.prepareStackTrace) { chain.format.replace(Error.prepareStackTrace); } var SHORTCIRCUIT_FORMATER = false; function prepareStackTrace(error, originalFrames) { if (SHORTCIRCUIT_CALLSITE) return originalFrames; if (SHORTCIRCUIT_FORMATER) return defaultFormater(error, originalFrames); // Make a loss copy of originalFrames var frames = originalFrames.concat(); // extend frames frames = chain.extend._modify(error, frames); // filter frames frames = chain.filter._modify(error, frames); // reduce frames to match Error.stackTraceLimit frames = frames.slice(0, Error.stackTraceLimit); // Set the callSite property // But only if it hasn't been explicitly set, otherwise // error.stack would have unintended side effects. Check also for // non-extensible/sealed objects, such as those from Google's Closure Library if (Object.isExtensible(error) && (Object.getOwnPropertyDescriptor(error, "callSite") === undefined)) { error.callSite = { original: originalFrames, mutated: frames }; } // format frames SHORTCIRCUIT_FORMATER = true; var format = chain.format._formater(error, frames); SHORTCIRCUIT_FORMATER = false; return format; } // Replace the v8 stack trace creator Object.defineProperty(Error, 'prepareStackTrace', { 'get': function () { return prepareStackTrace; }, 'set': function (formater) { // If formater is prepareStackTrace it means that someone ran // var old = Error.prepareStackTrace; // Error.prepareStackTrace = custom // new Error().stack // Error.prepareStackTrace = old; // The effect of this, should be that the old behaviour is restored. if (formater === prepareStackTrace) { chain.format._roolback(); } // Error.prepareStackTrace was set, this means that someone is // trying to take control of the Error().stack format. Make // them belive they succeeded by setting them up as the stack-chain // formater. else { chain.format._backup(); chain.format.replace(formater); } } }); // // Manage call site storeage // function callSiteGetter() { // calculate call site object this.stack; // return call site object return this.callSite; } Object.defineProperty(Error.prototype, 'callSite', { 'get': callSiteGetter, 'set': function (frames) { // In case callSite was set before [[getter]], just set // the value Object.defineProperty(this, 'callSite', { value: frames, writable: true, configurable: true }); }, configurable: true }); module.exports = chain; /***/ }), /***/ 7581: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const os = __webpack_require__(2087); const tty = __webpack_require__(3867); const hasFlag = __webpack_require__(6275); const {env} = process; let flagForceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) { flagForceColor = 0; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { flagForceColor = 1; } function envForceColor() { if ('FORCE_COLOR' in env) { if (env.FORCE_COLOR === 'true') { return 1; } if (env.FORCE_COLOR === 'false') { return 0; } return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.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, sniffFlags = true} = {}) { const noFlagForceColor = envForceColor(); if (noFlagForceColor !== undefined) { flagForceColor = noFlagForceColor; } const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; if (forceColor === 0) { return 0; } if (sniffFlags) { 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', 'DRONE'].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 = Number.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, options = {}) { const level = supportsColor(stream, { streamIsTTY: stream && stream.isTTY, ...options }); return translateLevel(level); } module.exports = { supportsColor: getSupportLevel, stdout: getSupportLevel({isTTY: tty.isatty(1)}), stderr: getSupportLevel({isTTY: tty.isatty(2)}) }; /***/ }), /***/ 4248: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // // Copyright (c) Microsoft Corporation. All rights reserved. // Object.defineProperty(exports, "__esModule", ({ value: true })); var ExperimentationService_1 = __webpack_require__(9009); exports.ExperimentationService = ExperimentationService_1.ExperimentationService; //# sourceMappingURL=index.js.map /***/ }), /***/ 9009: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const TasApiFeatureProvider_1 = __webpack_require__(1392); const AxiosHttpClient_1 = __webpack_require__(4762); const ExperimentationServiceAutoPolling_1 = __webpack_require__(3043); /** * Experimentation service to provide functionality of A/B experiments: * - reading flights; * - caching current set of flights; * - get answer on if flights are enabled. */ class ExperimentationService extends ExperimentationServiceAutoPolling_1.ExperimentationServiceAutoPolling { constructor(options) { super(options.telemetry, options.filterProviders || [], // Defaulted to empty array. options.refetchInterval != null ? options.refetchInterval : // If no fetch interval is provided, refetch functionality is turned off. 0, options.featuresTelemetryPropertyName, options.assignmentContextTelemetryPropertyName, options.telemetryEventName, options.storageKey, options.keyValueStorage); this.options = options; this.invokeInit(); } init() { // set feature providers to be an empty array. this.featureProviders = []; // Add WebApi feature provider. this.addFeatureProvider(new TasApiFeatureProvider_1.TasApiFeatureProvider(new AxiosHttpClient_1.AxiosHttpClient(this.options.endpoint), this.telemetry, this.filterProviders)); // This will start polling the TAS. super.init(); } } exports.ExperimentationService = ExperimentationService; ExperimentationService.REFRESH_RATE_IN_MINUTES = 30; //# sourceMappingURL=ExperimentationService.js.map /***/ }), /***/ 3043: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const ExperimentationServiceBase_1 = __webpack_require__(9859); const PollingService_1 = __webpack_require__(3283); /** * Implementation of Feature provider that provides a polling feature, where the source can be re-fetched every x time given. */ class ExperimentationServiceAutoPolling extends ExperimentationServiceBase_1.ExperimentationServiceBase { constructor(telemetry, filterProviders, refreshRateMs, featuresTelemetryPropertyName, assignmentContextTelemetryPropertyName, telemetryEventName, storageKey, storage) { super(telemetry, featuresTelemetryPropertyName, assignmentContextTelemetryPropertyName, telemetryEventName, storageKey, storage); this.telemetry = telemetry; this.filterProviders = filterProviders; this.refreshRateMs = refreshRateMs; this.featuresTelemetryPropertyName = featuresTelemetryPropertyName; this.assignmentContextTelemetryPropertyName = assignmentContextTelemetryPropertyName; this.telemetryEventName = telemetryEventName; this.storageKey = storageKey; this.storage = storage; // Excluding 0 since it allows to turn off the auto polling. if (refreshRateMs < 1000 && refreshRateMs !== 0) { throw new Error('The minimum refresh rate for polling is 1000 ms (1 second). If you wish to deactivate this auto-polling use value of 0.'); } if (refreshRateMs > 0) { this.pollingService = new PollingService_1.PollingService(refreshRateMs); this.pollingService.OnPollTick(async () => { await super.getFeaturesAsync(); }); } } init() { if (this.pollingService) { this.pollingService.StartPolling(true); } else { super.getFeaturesAsync(); } } /** * Wrapper that will reset the polling intervals whenever the feature data is fetched manually. */ async getFeaturesAsync(overrideInMemoryFeatures = false) { if (!this.pollingService) { return await super.getFeaturesAsync(overrideInMemoryFeatures); } else { this.pollingService.StopPolling(); let result = await super.getFeaturesAsync(overrideInMemoryFeatures); this.pollingService.StartPolling(); return result; } } } exports.ExperimentationServiceAutoPolling = ExperimentationServiceAutoPolling; //# sourceMappingURL=ExperimentationServiceAutoPolling.js.map /***/ }), /***/ 9859: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const MemoryKeyValueStorage_1 = __webpack_require__(350); /** * Experimentation service to provide functionality of A/B experiments: * - reading flights; * - caching current set of flights; * - get answer on if flights are enabled. */ class ExperimentationServiceBase { constructor(telemetry, featuresTelemetryPropertyName, assignmentContextTelemetryPropertyName, telemetryEventName, storageKey, storage) { this.telemetry = telemetry; this.featuresTelemetryPropertyName = featuresTelemetryPropertyName; this.assignmentContextTelemetryPropertyName = assignmentContextTelemetryPropertyName; this.telemetryEventName = telemetryEventName; this.storageKey = storageKey; this.storage = storage; this.featuresConsumed = false; this.cachedTelemetryEvents = []; this._features = { features: [], assignmentContext: '', configs: [] }; if (!this.storageKey) { this.storageKey = 'ABExp.Features'; } if (!this.storage) { storage = new MemoryKeyValueStorage_1.MemoryKeyValueStorage(); } this.loadCachePromise = this.loadCachedFeatureData(); this.initializePromise = this.loadCachePromise; this.initialFetch = new Promise((resolve, reject) => { this.resolveInitialFetchPromise = resolve; }); } get features() { return this._features; } set features(value) { this._features = value; /** * If an implementation of telemetry exists, we set the shared property. */ if (this.telemetry) { this.telemetry.setSharedProperty(this.featuresTelemetryPropertyName, this.features.features.join(';')); this.telemetry.setSharedProperty(this.assignmentContextTelemetryPropertyName, this.features.assignmentContext); } } /** * Gets all the features from the provider sources (not cache). * It returns these features and will also update the providers to have the latest features cached. */ async getFeaturesAsync(overrideInMemoryFeatures = false) { /** * If there's already a fetching promise, there's no need to call it again. * We return that as result. */ if (this.fetchPromise != null) { try { await this.fetchPromise; } catch (_a) { // Fetching features threw. Can happen if not connected to the internet, e.g } return this.features; } if (!this.featureProviders || this.featureProviders.length === 0) { return Promise.resolve({ features: [], assignmentContext: '', configs: [] }); } /** * Fetch all from providers. */ this.fetchPromise = Promise.all(this.featureProviders.map(async (provider) => { return await provider.getFeatures(); })); try { const featureResults = await this.fetchPromise; this.updateFeatures(featureResults, overrideInMemoryFeatures); } catch (_b) { // Fetching features threw. Can happen if not connected to the internet, e.g. } this.fetchPromise = undefined; if (this.resolveInitialFetchPromise) { this.resolveInitialFetchPromise(); this.resolveInitialFetchPromise = undefined; } /** * At this point all features have been re-fetched and cache has been updated. * We return the cached features. */ return this.features; } /** * * @param featureResults The feature results obtained from all the feature providers. */ updateFeatures(featureResults, overrideInMemoryFeatures = false) { /** * if features comes as a null value, that is taken as if there aren't any features active, * so an empty array is defaulted. */ let features = { features: [], assignmentContext: '', configs: [] }; for (let result of featureResults) { for (let feature of result.features) { if (!features.features.includes(feature)) { features.features.push(feature); } } for (let config of result.configs) { const existingConfig = features.configs.find(c => c.Id === config.Id); if (existingConfig) { existingConfig.Parameters = Object.assign(Object.assign({}, existingConfig.Parameters), config.Parameters); } else { features.configs.push(config); } } features.assignmentContext += result.assignmentContext; } /** * Set the obtained feature values to the global features variable. This stores them in memory. */ if (overrideInMemoryFeatures || !this.featuresConsumed) { this.features = features; } /** * If we have storage, we cache the latest results into the storage. */ if (this.storage) { this.storage.setValue(this.storageKey, features); } } async loadCachedFeatureData() { let cachedFeatureData; if (this.storage) { cachedFeatureData = await this.storage.getValue(this.storageKey); // When updating from an older version of tas-client, configs may be undefined if (cachedFeatureData !== undefined && cachedFeatureData.configs === undefined) { cachedFeatureData.configs = []; } } if (this.features.features.length === 0) { this.features = cachedFeatureData || { features: [], assignmentContext: '', configs: [] }; } } /** * Returns a value indicating whether the given flight is enabled. * It uses the in-memory cache. * @param flight The flight to check. */ isFlightEnabled(flight) { this.featuresConsumed = true; this.PostEventToTelemetry(flight); return this.features.features.includes(flight); } /** * Returns a value indicating whether the given flight is enabled. * It uses the values currently on cache. * @param flight The flight to check. */ async isCachedFlightEnabled(flight) { await this.loadCachePromise; this.featuresConsumed = true; this.PostEventToTelemetry(flight); return this.features.features.includes(flight); } /** * Returns a value indicating whether the given flight is enabled. * It re-fetches values from the server. * @param flight the flight to check. */ async isFlightEnabledAsync(flight) { const features = await this.getFeaturesAsync(true); this.featuresConsumed = true; this.PostEventToTelemetry(flight); return features.features.includes(flight); } /** * Returns the value of the treatment variable, or undefined if not found. * It uses the values currently in memory, so the experimentation service * must be initialized before calling. * @param config name of the config to check. * @param name name of the treatment variable. */ getTreatmentVariable(configId, name) { var _a; this.featuresConsumed = true; this.PostEventToTelemetry(`${configId}.${name}`); const config = this.features.configs.find(c => c.Id === configId); return (_a = config) === null || _a === void 0 ? void 0 : _a.Parameters[name]; } /** * Returns the value of the treatment variable, or undefined if not found. * It re-fetches values from the server. If checkCache is set to true and the value exists * in the cache, the Treatment Assignment Service is not called. * @param config name of the config to check. * @param name name of the treatment variable. * @param checkCache check the cache for the variable before calling the TAS. */ async getTreatmentVariableAsync(configId, name, checkCache) { if (checkCache) { const _featuresConsumed = this.featuresConsumed; const cachedValue = this.getTreatmentVariable(configId, name); if (cachedValue === undefined) { this.featuresConsumed = _featuresConsumed; } else { return cachedValue; } } await this.getFeaturesAsync(true); return this.getTreatmentVariable(configId, name); } PostEventToTelemetry(flight) { /** * If this event has already been posted, we omit from posting it again. */ if (this.cachedTelemetryEvents.includes(flight)) { return; } this.telemetry.postEvent(this.telemetryEventName, new Map([['ABExp.queriedFeature', flight]])); /** * We cache the flight so we don't post it again. */ this.cachedTelemetryEvents.push(flight); } invokeInit() { this.init(); } addFeatureProvider(...providers) { if (providers == null || this.featureProviders == null) { return; } for (let provider of providers) { this.featureProviders.push(provider); } } } exports.ExperimentationServiceBase = ExperimentationServiceBase; //# sourceMappingURL=ExperimentationServiceBase.js.map /***/ }), /***/ 433: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /** * Abstract class for Feature Provider Implementation. */ class BaseFeatureProvider { /** * @param telemetry The telemetry implementation. */ constructor(telemetry) { this.telemetry = telemetry; this.isFetching = false; } /** * Method that wraps the fetch method in order to re-use the fetch promise if needed. * @param headers The headers to be used on the fetch method. */ async getFeatures() { if (this.isFetching && this.fetchPromise) { return this.fetchPromise; } this.fetchPromise = this.fetch(); let features = await this.fetchPromise; this.isFetching = false; this.fetchPromise = undefined; return features; } } exports.BaseFeatureProvider = BaseFeatureProvider; //# sourceMappingURL=BaseFeatureProvider.js.map /***/ }), /***/ 2958: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const BaseFeatureProvider_1 = __webpack_require__(433); /** * Feature provider implementation that handles filters. */ class FilteredFeatureProvider extends BaseFeatureProvider_1.BaseFeatureProvider { constructor(telemetry, filterProviders) { super(telemetry); this.telemetry = telemetry; this.filterProviders = filterProviders; this.cachedTelemetryEvents = []; } getFilters() { // We get the filters that will be sent as headers. let filters = new Map(); for (let filter of this.filterProviders) { let filterHeaders = filter.getFilters(); for (let key of filterHeaders.keys()) { // Headers can be overridden by custom filters. // That's why a check isn't done to see if the header already exists, the value is just set. let filterValue = filterHeaders.get(key); filters.set(key, filterValue); } } return filters; } PostEventToTelemetry(headers) { /** * If these headers have already been posted, we skip from posting them again.. */ if (this.cachedTelemetryEvents.includes(headers)) { return; } const jsonHeaders = JSON.stringify(headers); this.telemetry.postEvent('report-headers', new Map([['ABExp.headers', jsonHeaders]])); /** * We cache the flight so we don't post it again. */ this.cachedTelemetryEvents.push(headers); } } exports.FilteredFeatureProvider = FilteredFeatureProvider; //# sourceMappingURL=FilteredFeatureProvider.js.map /***/ }), /***/ 1392: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const FilteredFeatureProvider_1 = __webpack_require__(2958); /** * Feature provider implementation that calls the TAS web service to get the most recent active features. */ class TasApiFeatureProvider extends FilteredFeatureProvider_1.FilteredFeatureProvider { constructor(httpClient, telemetry, filterProviders) { super(telemetry, filterProviders); this.httpClient = httpClient; this.telemetry = telemetry; this.filterProviders = filterProviders; } /** * Method that handles fetching of latest data (in this case, flights) from the provider. */ async fetch() { // We get the filters that will be sent as headers. let filters = this.getFilters(); let headers = {}; // Filters are handled using Map therefore we need to // convert these filters into something axios can take as headers. for (let key of filters.keys()) { const filterValue = filters.get(key); headers[key] = filterValue; } //axios webservice call. let response = await this.httpClient.get({ headers: headers }); // If we have at least one filter, we post it to telemetry event. if (filters.keys.length > 0) { this.PostEventToTelemetry(headers); } // Read the response data from the server. let responseData = response.data; let configs = responseData.Configs; let features = []; for (let c of configs) { if (!c.Parameters) { continue; } for (let key of Object.keys(c.Parameters)) { const featureName = key + (c.Parameters[key] ? '' : 'cf'); if (!features.includes(featureName)) { features.push(featureName); } } } return { features, assignmentContext: responseData.AssignmentContext, configs }; } } exports.TasApiFeatureProvider = TasApiFeatureProvider; //# sourceMappingURL=TasApiFeatureProvider.js.map /***/ }), /***/ 4762: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const axios_1 = __webpack_require__(1240); class AxiosHttpClient { constructor(endpoint) { this.endpoint = endpoint; } get(config) { return axios_1.default.get(this.endpoint, Object.assign(Object.assign({}, config), { proxy: false })); } } exports.AxiosHttpClient = AxiosHttpClient; //# sourceMappingURL=AxiosHttpClient.js.map /***/ }), /***/ 350: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class MemoryKeyValueStorage { constructor() { this.storage = new Map(); } async getValue(key, defaultValue) { if (this.storage.has(key)) { return await Promise.resolve(this.storage.get(key)); } return await Promise.resolve(defaultValue || undefined); } setValue(key, value) { this.storage.set(key, value); } } exports.MemoryKeyValueStorage = MemoryKeyValueStorage; //# sourceMappingURL=MemoryKeyValueStorage.js.map /***/ }), /***/ 3283: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class PollingService { constructor(fetchInterval) { this.fetchInterval = fetchInterval; } StopPolling() { clearInterval(this.intervalHandle); this.intervalHandle = undefined; } OnPollTick(callback) { this.onTick = callback; } StartPolling(pollImmediately = false) { if (this.intervalHandle) { this.StopPolling(); } // If there's no callback, there's no point to start polling. if (this.onTick == null) { return; } if (pollImmediately) { this.onTick().then(() => { return; }).catch(() => { return; }); } /** * Set the interval to start running. */ this.intervalHandle = setInterval(async () => { await this.onTick(); }, this.fetchInterval); if (this.intervalHandle.unref) { // unref is only available in Node, not the web this.intervalHandle.unref(); // unref is used to avoid keeping node.js alive only because of these timeouts. } } } exports.PollingService = PollingService; //# sourceMappingURL=PollingService.js.map /***/ }), /***/ 7010: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /*! * Tmp * * Copyright (c) 2011-2017 KARASZI Istvan * * MIT Licensed */ /* * Module dependencies. */ const fs = __webpack_require__(5747); const os = __webpack_require__(2087); const path = __webpack_require__(5622); const crypto = __webpack_require__(6417); const _c = fs.constants && os.constants ? { fs: fs.constants, os: os.constants } : process.binding('constants'); const rimraf = __webpack_require__(3844); /* * The working inner variables. */ const // the random characters to choose from RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', TEMPLATE_PATTERN = /XXXXXX/, DEFAULT_TRIES = 3, CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), EBADF = _c.EBADF || _c.os.errno.EBADF, ENOENT = _c.ENOENT || _c.os.errno.ENOENT, DIR_MODE = 448 /* 0o700 */, FILE_MODE = 384 /* 0o600 */, EXIT = 'exit', SIGINT = 'SIGINT', // this will hold the objects need to be removed on exit _removeObjects = []; var _gracefulCleanup = false; /** * Random name generator based on crypto. * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript * * @param {number} howMany * @returns {string} the generated random name * @private */ function _randomChars(howMany) { var value = [], rnd = null; // make sure that we do not fail because we ran out of entropy try { rnd = crypto.randomBytes(howMany); } catch (e) { rnd = crypto.pseudoRandomBytes(howMany); } for (var i = 0; i < howMany; i++) { value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); } return value.join(''); } /** * Checks whether the `obj` parameter is defined or not. * * @param {Object} obj * @returns {boolean} true if the object is undefined * @private */ function _isUndefined(obj) { return typeof obj === 'undefined'; } /** * Parses the function arguments. * * This function helps to have optional arguments. * * @param {(Options|Function)} options * @param {Function} callback * @returns {Array} parsed arguments * @private */ function _parseArguments(options, callback) { /* istanbul ignore else */ if (typeof options === 'function') { return [{}, options]; } /* istanbul ignore else */ if (_isUndefined(options)) { return [{}, callback]; } return [options, callback]; } /** * Generates a new temporary name. * * @param {Object} opts * @returns {string} the new random name according to opts * @private */ function _generateTmpName(opts) { const tmpDir = _getTmpDir(); // fail early on missing tmp dir if (isBlank(opts.dir) && isBlank(tmpDir)) { throw new Error('No tmp dir specified'); } /* istanbul ignore else */ if (!isBlank(opts.name)) { return path.join(opts.dir || tmpDir, opts.name); } // mkstemps like template // opts.template has already been guarded in tmpName() below /* istanbul ignore else */ if (opts.template) { var template = opts.template; // make sure that we prepend the tmp path if none was given /* istanbul ignore else */ if (path.basename(template) === template) template = path.join(opts.dir || tmpDir, template); return template.replace(TEMPLATE_PATTERN, _randomChars(6)); } // prefix and postfix const name = [ (isBlank(opts.prefix) ? 'tmp-' : opts.prefix), process.pid, _randomChars(12), (opts.postfix ? opts.postfix : '') ].join(''); return path.join(opts.dir || tmpDir, name); } /** * Gets a temporary file name. * * @param {(Options|tmpNameCallback)} options options or callback * @param {?tmpNameCallback} callback the callback function */ function tmpName(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1], tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES; /* istanbul ignore else */ if (isNaN(tries) || tries < 0) return cb(new Error('Invalid tries')); /* istanbul ignore else */ if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) return cb(new Error('Invalid template provided')); (function _getUniqueName() { try { const name = _generateTmpName(opts); // check whether the path exists then retry if needed fs.stat(name, function (err) { /* istanbul ignore else */ if (!err) { /* istanbul ignore else */ if (tries-- > 0) return _getUniqueName(); return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); } cb(null, name); }); } catch (err) { cb(err); } }()); } /** * Synchronous version of tmpName. * * @param {Object} options * @returns {string} the generated random name * @throws {Error} if the options are invalid or could not generate a filename */ function tmpNameSync(options) { var args = _parseArguments(options), opts = args[0], tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES; /* istanbul ignore else */ if (isNaN(tries) || tries < 0) throw new Error('Invalid tries'); /* istanbul ignore else */ if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) throw new Error('Invalid template provided'); do { const name = _generateTmpName(opts); try { fs.statSync(name); } catch (e) { return name; } } while (tries-- > 0); throw new Error('Could not get a unique tmp filename, max tries reached'); } /** * Creates and opens a temporary file. * * @param {(Options|fileCallback)} options the config options or the callback function * @param {?fileCallback} callback */ function file(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create and open the file fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { /* istanbul ignore else */ if (err) return cb(err); if (opts.discardDescriptor) { return fs.close(fd, function _discardCallback(err) { /* istanbul ignore else */ if (err) { // Low probability, and the file exists, so this could be // ignored. If it isn't we certainly need to unlink the // file, and if that fails too its error is more // important. try { fs.unlinkSync(name); } catch (e) { if (!isENOENT(e)) { err = e; } } return cb(err); } cb(null, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts)); }); } /* istanbul ignore else */ if (opts.detachDescriptor) { return cb(null, name, fd, _prepareTmpFileRemoveCallback(name, -1, opts)); } cb(null, name, fd, _prepareTmpFileRemoveCallback(name, fd, opts)); }); }); } /** * Synchronous version of file. * * @param {Options} options * @returns {FileSyncObject} object consists of name, fd and removeCallback * @throws {Error} if cannot create a file */ function fileSync(options) { var args = _parseArguments(options), opts = args[0]; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); /* istanbul ignore else */ if (opts.discardDescriptor) { fs.closeSync(fd); fd = undefined; } return { name: name, fd: fd, removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts) }; } /** * Creates a temporary directory. * * @param {(Options|dirCallback)} options the options or the callback function * @param {?dirCallback} callback */ function dir(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create the directory fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { /* istanbul ignore else */ if (err) return cb(err); cb(null, name, _prepareTmpDirRemoveCallback(name, opts)); }); }); } /** * Synchronous version of dir. * * @param {Options} options * @returns {DirSyncObject} object consists of name and removeCallback * @throws {Error} if it cannot create a directory */ function dirSync(options) { var args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); fs.mkdirSync(name, opts.mode || DIR_MODE); return { name: name, removeCallback: _prepareTmpDirRemoveCallback(name, opts) }; } /** * Removes files asynchronously. * * @param {Object} fdPath * @param {Function} next * @private */ function _removeFileAsync(fdPath, next) { const _handler = function (err) { if (err && !isENOENT(err)) { // reraise any unanticipated error return next(err); } next(); } if (0 <= fdPath[0]) fs.close(fdPath[0], function (err) { fs.unlink(fdPath[1], _handler); }); else fs.unlink(fdPath[1], _handler); } /** * Removes files synchronously. * * @param {Object} fdPath * @private */ function _removeFileSync(fdPath) { try { if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); } catch (e) { // reraise any unanticipated error if (!isEBADF(e) && !isENOENT(e)) throw e; } finally { try { fs.unlinkSync(fdPath[1]); } catch (e) { // reraise any unanticipated error if (!isENOENT(e)) throw e; } } } /** * Prepares the callback for removal of the temporary file. * * @param {string} name the path of the file * @param {number} fd file descriptor * @param {Object} opts * @returns {fileCallback} * @private */ function _prepareTmpFileRemoveCallback(name, fd, opts) { const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name]); const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return removeCallback; } /** * Simple wrapper for rimraf. * * @param {string} dirPath * @param {Function} next * @private */ function _rimrafRemoveDirWrapper(dirPath, next) { rimraf(dirPath, next); } /** * Simple wrapper for rimraf.sync. * * @param {string} dirPath * @private */ function _rimrafRemoveDirSyncWrapper(dirPath, next) { try { return next(null, rimraf.sync(dirPath)); } catch (err) { return next(err); } } /** * Prepares the callback for removal of the temporary directory. * * @param {string} name * @param {Object} opts * @returns {Function} the callback * @private */ function _prepareTmpDirRemoveCallback(name, opts) { const removeFunction = opts.unsafeCleanup ? _rimrafRemoveDirWrapper : fs.rmdir.bind(fs); const removeFunctionSync = opts.unsafeCleanup ? _rimrafRemoveDirSyncWrapper : fs.rmdirSync.bind(fs); const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name); const removeCallback = _prepareRemoveCallback(removeFunction, name, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return removeCallback; } /** * Creates a guarded function wrapping the removeFunction call. * * @param {Function} removeFunction * @param {Object} arg * @returns {Function} * @private */ function _prepareRemoveCallback(removeFunction, arg, cleanupCallbackSync) { var called = false; return function _cleanupCallback(next) { next = next || function () {}; if (!called) { const toRemove = cleanupCallbackSync || _cleanupCallback; const index = _removeObjects.indexOf(toRemove); /* istanbul ignore else */ if (index >= 0) _removeObjects.splice(index, 1); called = true; // sync? if (removeFunction.length === 1) { try { removeFunction(arg); return next(null); } catch (err) { // if no next is provided and since we are // in silent cleanup mode on process exit, // we will ignore the error return next(err); } } else return removeFunction(arg, next); } else return next(new Error('cleanup callback has already been called')); }; } /** * The garbage collector. * * @private */ function _garbageCollector() { /* istanbul ignore else */ if (!_gracefulCleanup) return; // the function being called removes itself from _removeObjects, // loop until _removeObjects is empty while (_removeObjects.length) { try { _removeObjects[0](); } catch (e) { // already removed? } } } /** * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. */ function isEBADF(error) { return isExpectedError(error, -EBADF, 'EBADF'); } /** * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. */ function isENOENT(error) { return isExpectedError(error, -ENOENT, 'ENOENT'); } /** * Helper to determine whether the expected error code matches the actual code and errno, * which will differ between the supported node versions. * * - Node >= 7.0: * error.code {string} * error.errno {string|number} any numerical value will be negated * * - Node >= 6.0 < 7.0: * error.code {string} * error.errno {number} negated * * - Node >= 4.0 < 6.0: introduces SystemError * error.code {string} * error.errno {number} negated * * - Node >= 0.10 < 4.0: * error.code {number} negated * error.errno n/a */ function isExpectedError(error, code, errno) { return error.code === code || error.code === errno; } /** * Helper which determines whether a string s is blank, that is undefined, or empty or null. * * @private * @param {string} s * @returns {Boolean} true whether the string s is blank, false otherwise */ function isBlank(s) { return s === null || s === undefined || !s.trim(); } /** * Sets the graceful cleanup. */ function setGracefulCleanup() { _gracefulCleanup = true; } /** * Returns the currently configured tmp dir from os.tmpdir(). * * @private * @returns {string} the currently configured tmp dir */ function _getTmpDir() { return os.tmpdir(); } /** * If there are multiple different versions of tmp in place, make sure that * we recognize the old listeners. * * @param {Function} listener * @private * @returns {Boolean} true whether listener is a legacy listener */ function _is_legacy_listener(listener) { return (listener.name === '_exit' || listener.name === '_uncaughtExceptionThrown') && listener.toString().indexOf('_garbageCollector();') > -1; } /** * Safely install SIGINT listener. * * NOTE: this will only work on OSX and Linux. * * @private */ function _safely_install_sigint_listener() { const listeners = process.listeners(SIGINT); const existingListeners = []; for (let i = 0, length = listeners.length; i < length; i++) { const lstnr = listeners[i]; /* istanbul ignore else */ if (lstnr.name === '_tmp$sigint_listener') { existingListeners.push(lstnr); process.removeListener(SIGINT, lstnr); } } process.on(SIGINT, function _tmp$sigint_listener(doExit) { for (let i = 0, length = existingListeners.length; i < length; i++) { // let the existing listener do the garbage collection (e.g. jest sandbox) try { existingListeners[i](false); } catch (err) { // ignore } } try { // force the garbage collector even it is called again in the exit listener _garbageCollector(); } finally { if (!!doExit) { process.exit(0); } } }); } /** * Safely install process exit listener. * * @private */ function _safely_install_exit_listener() { const listeners = process.listeners(EXIT); // collect any existing listeners const existingListeners = []; for (let i = 0, length = listeners.length; i < length; i++) { const lstnr = listeners[i]; /* istanbul ignore else */ // TODO: remove support for legacy listeners once release 1.0.0 is out if (lstnr.name === '_tmp$safe_listener' || _is_legacy_listener(lstnr)) { // we must forget about the uncaughtException listener, hopefully it is ours if (lstnr.name !== '_uncaughtExceptionThrown') { existingListeners.push(lstnr); } process.removeListener(EXIT, lstnr); } } // TODO: what was the data parameter good for? process.addListener(EXIT, function _tmp$safe_listener(data) { for (let i = 0, length = existingListeners.length; i < length; i++) { // let the existing listener do the garbage collection (e.g. jest sandbox) try { existingListeners[i](data); } catch (err) { // ignore } } _garbageCollector(); }); } _safely_install_exit_listener(); _safely_install_sigint_listener(); /** * Configuration options. * * @typedef {Object} Options * @property {?number} tries the number of tries before give up the name generation * @property {?string} template the "mkstemp" like filename template * @property {?string} name fix name * @property {?string} dir the tmp directory to use * @property {?string} prefix prefix for the generated name * @property {?string} postfix postfix for the generated name * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty */ /** * @typedef {Object} FileSyncObject * @property {string} name the name of the file * @property {string} fd the file descriptor * @property {fileCallback} removeCallback the callback function to remove the file */ /** * @typedef {Object} DirSyncObject * @property {string} name the name of the directory * @property {fileCallback} removeCallback the callback function to remove the directory */ /** * @callback tmpNameCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name */ /** * @callback fileCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback dirCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallback} fn the cleanup callback function */ /** * Removes the temporary created file or directory. * * @callback cleanupCallback * @param {simpleCallback} [next] function to call after entry was removed */ /** * Callback function for function composition. * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} * * @callback simpleCallback */ // exporting all the needed methods // evaluate os.tmpdir() lazily, mainly for simplifying testing but it also will // allow users to reconfigure the temporary directory Object.defineProperty(module.exports, "tmpdir", ({ enumerable: true, configurable: false, get: function () { return _getTmpDir(); } })); module.exports.dir = dir; module.exports.dirSync = dirSync; module.exports.file = file; module.exports.fileSync = fileSync; module.exports.tmpName = tmpName; module.exports.tmpNameSync = tmpNameSync; module.exports.setGracefulCleanup = setGracefulCleanup; /***/ }), /***/ 6893: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fs = __webpack_require__(5747); const nls = __webpack_require__(3612); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\ParsedEnvironmentFile.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\ParsedEnvironmentFile.ts')); class ParsedEnvironmentFile { constructor(env, warning) { this.Env = env; this.Warning = warning; } static CreateFromFile(envFile, initialEnv) { const content = fs.readFileSync(envFile, "utf8"); return this.CreateFromContent(content, envFile, initialEnv); } static CreateFromContent(content, envFile, initialEnv) { if (content.charAt(0) === '\uFEFF') { content = content.substr(1); } const parseErrors = []; const env = new Map(); if (initialEnv) { initialEnv.forEach((e) => { env.set(e.name, e.value); }); } content.split("\n").forEach(line => { var _a; const r = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/); if (r) { const key = r[1]; let value = (_a = r[2], (_a !== null && _a !== void 0 ? _a : "")); if ((value.length > 0) && (value.charAt(0) === '"') && (value.charAt(value.length - 1) === '"')) { value = value.replace(/\\n/gm, "\n"); } value = value.replace(/(^['"]|['"]$)/g, ""); env.set(key, value); } else { const comments = new RegExp(/^\s*(#|$)/); if (!comments.test(line)) { parseErrors.push(line); } } }); let warning; if (parseErrors.length !== 0) { warning = localize(0, null, "envFile", envFile); parseErrors.forEach(function (value, idx, array) { warning += "\"" + value + "\"" + ((idx !== array.length - 1) ? ", " : "."); }); } const arrayEnv = []; for (const key of env.keys()) { arrayEnv.push({ name: key, value: env.get(key) }); } return new ParsedEnvironmentFile(arrayEnv, warning); } } exports.ParsedEnvironmentFile = ParsedEnvironmentFile; /***/ }), /***/ 2931: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const util = __webpack_require__(5331); const vscode = __webpack_require__(7549); const nls = __webpack_require__(3612); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\attachQuickPick.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\attachQuickPick.ts')); class RefreshButton { get iconPath() { const refreshImagePathDark = util.getExtensionFilePath("assets/Refresh_inverse.svg"); const refreshImagePathLight = util.getExtensionFilePath("assets/Refresh.svg"); return { dark: vscode.Uri.file(refreshImagePathDark), light: vscode.Uri.file(refreshImagePathLight) }; } get tooltip() { return localize(0, null); } } function showQuickPick(getAttachItems) { return __awaiter(this, void 0, void 0, function* () { const processEntries = yield getAttachItems(); return new Promise((resolve, reject) => { const quickPick = vscode.window.createQuickPick(); quickPick.title = localize(1, null); quickPick.canSelectMany = false; quickPick.matchOnDescription = true; quickPick.matchOnDetail = true; quickPick.placeholder = localize(2, null); quickPick.buttons = [new RefreshButton()]; quickPick.items = processEntries; const disposables = []; quickPick.onDidTriggerButton(() => __awaiter(this, void 0, void 0, function* () { quickPick.items = yield getAttachItems(); }), undefined, disposables); quickPick.onDidAccept(() => { if (quickPick.selectedItems.length !== 1) { reject(new Error(localize(3, null))); } const selectedId = quickPick.selectedItems[0].id; disposables.forEach(item => item.dispose()); quickPick.dispose(); resolve(selectedId); }, undefined, disposables); quickPick.onDidHide(() => { disposables.forEach(item => item.dispose()); quickPick.dispose(); reject(new Error(localize(4, null))); }, undefined, disposables); quickPick.show(); }); }); } exports.showQuickPick = showQuickPick; /***/ }), /***/ 1191: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const nativeAttach_1 = __webpack_require__(1476); const attachQuickPick_1 = __webpack_require__(2931); const settings_1 = __webpack_require__(296); const debugUtils = __webpack_require__(1371); const os = __webpack_require__(2087); const path = __webpack_require__(5622); const util = __webpack_require__(5331); const vscode = __webpack_require__(7549); const nls = __webpack_require__(3612); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\attachToProcess.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\attachToProcess.ts')); class AttachPicker { constructor(attachItemsProvider) { this.attachItemsProvider = attachItemsProvider; } ShowAttachEntries() { return __awaiter(this, void 0, void 0, function* () { if (!(yield util.isExtensionReady())) { util.displayExtensionNotReadyPrompt(); } else { return attachQuickPick_1.showQuickPick(() => this.attachItemsProvider.getAttachItems()); } }); } } exports.AttachPicker = AttachPicker; class RemoteAttachPicker { constructor() { this._channel = vscode.window.createOutputChannel('remote-attach'); } ShowAttachEntries(config) { return __awaiter(this, void 0, void 0, function* () { if (!(yield util.isExtensionReady())) { util.displayExtensionNotReadyPrompt(); } else { this._channel.clear(); const pipeTransport = config ? config.pipeTransport : undefined; if (!pipeTransport) { throw new Error(localize(0, null, "pipeTransport")); } let pipeProgram; if (os.platform() === 'win32' && pipeTransport.pipeProgram && !(yield util.checkFileExists(pipeTransport.pipeProgram))) { const pipeProgramStr = pipeTransport.pipeProgram.toLowerCase().trim(); const expectedArch = debugUtils.ArchType[process.arch]; if (!(yield util.checkFileExists(config.pipeTransport.pipeProgram))) { pipeProgram = debugUtils.ArchitectureReplacer.checkAndReplaceWSLPipeProgram(pipeProgramStr, expectedArch); } if (!pipeProgram && config.pipeTransport.pipeCwd) { const pipeCwdStr = config.pipeTransport.pipeCwd.toLowerCase().trim(); const newPipeProgramStr = path.join(pipeCwdStr, pipeProgramStr); if (!(yield util.checkFileExists(newPipeProgramStr))) { pipeProgram = debugUtils.ArchitectureReplacer.checkAndReplaceWSLPipeProgram(newPipeProgramStr, expectedArch); } } } if (!pipeProgram) { pipeProgram = pipeTransport.pipeProgram; } const pipeArgs = pipeTransport.pipeArgs; const argList = RemoteAttachPicker.createArgumentList(pipeArgs); const pipeCmd = `"${pipeProgram}" ${argList}`; const processes = yield this.getRemoteOSAndProcesses(pipeCmd); const attachPickOptions = { matchOnDetail: true, matchOnDescription: true, placeHolder: localize(1, null) }; const item = yield vscode.window.showQuickPick(processes, attachPickOptions); if (item) { return item.id; } else { throw new Error(localize(2, null)); } } }); } getRemoteProcessCommand() { let innerQuote = `'`; let outerQuote = `"`; let parameterBegin = `$(`; let parameterEnd = `)`; let escapedQuote = `\\\"`; const settings = new settings_1.CppSettings(); if (settings.useBacktickCommandSubstitution) { parameterBegin = `\``; parameterEnd = `\``; escapedQuote = `\"`; } if (os.platform() !== "win32") { innerQuote = `"`; outerQuote = `'`; } return `${outerQuote}sh -c ${innerQuote}uname && if [ ${parameterBegin}uname${parameterEnd} = ${escapedQuote}Linux${escapedQuote} ] ; ` + `then ${nativeAttach_1.PsProcessParser.psLinuxCommand} ; elif [ ${parameterBegin}uname${parameterEnd} = ${escapedQuote}Darwin${escapedQuote} ] ; ` + `then ${nativeAttach_1.PsProcessParser.psDarwinCommand}; fi${innerQuote}${outerQuote}`; } getRemoteOSAndProcesses(pipeCmd) { return __awaiter(this, void 0, void 0, function* () { const execCommand = `${pipeCmd} ${this.getRemoteProcessCommand()}`; const output = yield util.execChildProcess(execCommand, undefined, this._channel); const lines = output.split(/\r?\n/); if (lines.length === 0) { throw new Error(localize(3, null)); } else { const remoteOS = lines[0].replace(/[\r\n]+/g, ''); if (remoteOS !== "Linux" && remoteOS !== "Darwin") { throw new Error(`Operating system "${remoteOS}" not supported.`); } if (lines.length === 1) { throw new Error(localize(4, null)); } else { const processes = lines.slice(1); return nativeAttach_1.PsProcessParser.ParseProcessFromPsArray(processes) .sort((a, b) => { if (a.name === undefined) { if (b.name === undefined) { return 0; } return 1; } if (b.name === undefined) { return -1; } const aLower = a.name.toLowerCase(); const bLower = b.name.toLowerCase(); if (aLower === bLower) { return 0; } return aLower < bLower ? -1 : 1; }) .map(p => p.toAttachItem()); } } }); } static createArgumentList(args) { let argsString = ""; for (const arg of args) { if (argsString) { argsString += " "; } argsString += `"${arg}"`; } return argsString; } } exports.RemoteAttachPicker = RemoteAttachPicker; /***/ }), /***/ 9042: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const debugUtils = __webpack_require__(1371); const os = __webpack_require__(2087); const path = __webpack_require__(5622); const vscode = __webpack_require__(7549); const util = __webpack_require__(5331); const fs = __webpack_require__(5747); const Telemetry = __webpack_require__(1818); const extension_1 = __webpack_require__(2763); const extension_2 = __webpack_require__(2973); const logger = __webpack_require__(5610); const nls = __webpack_require__(3612); const configurations_1 = __webpack_require__(134); const comment_json_1 = __webpack_require__(634); const platform_1 = __webpack_require__(3383); const ParsedEnvironmentFile_1 = __webpack_require__(6893); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\configurationProvider.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\configurationProvider.ts')); function isDebugLaunchStr(str) { return str.startsWith("(gdb) ") || str.startsWith("(lldb) ") || str.startsWith("(Windows) "); } class QuickPickConfigurationProvider { constructor(provider) { this.underlyingProvider = provider; } provideDebugConfigurations(folder, token) { return __awaiter(this, void 0, void 0, function* () { let configs = this.underlyingProvider.provideDebugConfigurations ? yield this.underlyingProvider.provideDebugConfigurations(folder, token) : undefined; if (!configs) { configs = []; } const defaultConfig = configs.find(config => isDebugLaunchStr(config.name) && config.request === "launch"); if (!defaultConfig) { throw new Error("Default config not found in provideDebugConfigurations()"); } const editor = vscode.window.activeTextEditor; if (!editor || !util.fileIsCOrCppSource(editor.document.fileName) || configs.length <= 1) { return [defaultConfig]; } const items = configs.map(config => { const noDetailConfig = Object.assign({}, config); noDetailConfig.detail = undefined; const menuItem = { label: config.name, configuration: noDetailConfig, description: config.detail }; if (isDebugLaunchStr(menuItem.label)) { menuItem.label = localize(0, null); } return menuItem; }); const selection = yield vscode.window.showQuickPick(items, { placeHolder: localize(1, null) }); if (!selection) { throw Error(localize(2, null)); } if (selection.label.startsWith("cl.exe")) { if (!process.env.DevEnvDir) { vscode.window.showErrorMessage(localize(3, null, "cl.exe")); return [selection.configuration]; } } if (selection.label.indexOf(extension_1.buildAndDebugActiveFileStr()) !== -1 && selection.configuration.preLaunchTask) { try { yield extension_2.cppBuildTaskProvider.ensureBuildTaskExists(selection.configuration.preLaunchTask); if (selection.configuration.miDebuggerPath) { if (!(yield util.checkFileExists(selection.configuration.miDebuggerPath))) { vscode.window.showErrorMessage(localize(4, null, selection.configuration.miDebuggerPath)); throw new Error(); } } yield vscode.debug.startDebugging(folder, selection.configuration); Telemetry.logDebuggerEvent("buildAndDebug", { "success": "true" }); } catch (e) { Telemetry.logDebuggerEvent("buildAndDebug", { "success": "false" }); } } return [selection.configuration]; }); } resolveDebugConfiguration(folder, config, token) { return this.underlyingProvider.resolveDebugConfiguration ? this.underlyingProvider.resolveDebugConfiguration(folder, config, token) : undefined; } resolveDebugConfigurationWithSubstitutedVariables(folder, config, token) { return this.underlyingProvider.resolveDebugConfigurationWithSubstitutedVariables ? this.underlyingProvider.resolveDebugConfigurationWithSubstitutedVariables(folder, config, token) : undefined; } } exports.QuickPickConfigurationProvider = QuickPickConfigurationProvider; class CppConfigurationProvider { constructor(provider, type) { this.provider = provider; this.type = type; } provideDebugConfigurations(folder, token) { return __awaiter(this, void 0, void 0, function* () { const defaultConfig = this.provider.getInitialConfigurations(this.type).find((config) => isDebugLaunchStr(config.name) && config.request === "launch"); console.assert(defaultConfig, "Could not find default debug configuration."); const platformInfo = yield platform_1.PlatformInformation.GetPlatformInformation(); const platform = platformInfo.platform; const buildTasksJson = yield extension_2.cppBuildTaskProvider.getJsonTasks(); const buildTasksDetected = yield extension_2.cppBuildTaskProvider.getTasks(true); const buildTasksDetectedRename = buildTasksDetected.map(taskDetected => { for (const taskJson of buildTasksJson) { if (taskDetected.definition.label === taskJson.definition.label) { taskDetected.name = extension_2.cppBuildTaskProvider.provideUniqueTaskLabel(taskJson.definition.label, buildTasksJson); taskDetected.definition.label = taskDetected.name; break; } } return taskDetected; }); let buildTasks = []; buildTasks = buildTasks.concat(buildTasksJson, buildTasksDetectedRename); if (buildTasks.length === 0) { return Promise.resolve(this.provider.getInitialConfigurations(this.type)); } if (buildTasks.length === 0) { return Promise.resolve(this.provider.getInitialConfigurations(this.type)); } buildTasks = buildTasks.filter((task) => { const command = task.definition.command; if (!command) { return false; } if (defaultConfig.name.startsWith("(Windows) ")) { if (command.startsWith("cl.exe")) { return true; } } else { if (!command.startsWith("cl.exe")) { return true; } } return false; }); const configs = yield Promise.all(buildTasks.map((task) => __awaiter(this, void 0, void 0, function* () { var _a; const definition = task.definition; const compilerPath = definition.command; const compilerName = path.basename(compilerPath); const newConfig = Object.assign({}, defaultConfig); newConfig.name = compilerName + extension_1.buildAndDebugActiveFileStr(); newConfig.preLaunchTask = task.name; if (newConfig.type === "cppdbg") { newConfig.externalConsole = false; } else { newConfig.console = "externalTerminal"; } const exeName = path.join("${fileDirname}", "${fileBasenameNoExtension}"); const isWindows = platform === 'win32'; newConfig.program = isWindows ? exeName + ".exe" : exeName; newConfig.detail = task.detail ? task.detail : definition.command; const isCl = compilerName === "cl.exe"; newConfig.cwd = isWindows && !isCl && !((_a = process.env.PATH) === null || _a === void 0 ? void 0 : _a.includes(path.dirname(compilerPath))) ? path.dirname(compilerPath) : "${fileDirname}"; return new Promise(resolve => { if (platform === "darwin") { return resolve(newConfig); } else { let debuggerName; if (compilerName.startsWith("clang")) { newConfig.MIMode = "lldb"; debuggerName = "lldb-mi"; if ((compilerName !== "clang-cl.exe") && (compilerName !== "clang-cpp.exe")) { const suffixIndex = compilerName.indexOf("-"); if (suffixIndex !== -1) { const suffix = compilerName.substr(suffixIndex); debuggerName += suffix; } } newConfig.type = "cppdbg"; } else if (compilerName === "cl.exe") { newConfig.miDebuggerPath = undefined; newConfig.type = "cppvsdbg"; return resolve(newConfig); } else { debuggerName = "gdb"; } if (isWindows) { debuggerName = debuggerName.endsWith(".exe") ? debuggerName : (debuggerName + ".exe"); } const compilerDirname = path.dirname(compilerPath); const debuggerPath = path.join(compilerDirname, debuggerName); if (isWindows) { newConfig.miDebuggerPath = debuggerPath; return resolve(newConfig); } else { fs.stat(debuggerPath, (err, stats) => { if (!err && stats && stats.isFile) { newConfig.miDebuggerPath = debuggerPath; } else { newConfig.miDebuggerPath = path.join("/usr", "bin", debuggerName); } return resolve(newConfig); }); } } }); }))); configs.push(defaultConfig); return configs; }); } resolveDebugConfiguration(folder, config, token) { if (!config || !config.type) { return null; } if (config.type === 'cppvsdbg') { if (config.hasOwnProperty("externalConsole")) { logger.getOutputChannelLogger().showWarningMessage(localize(5, null, "externalConsole", "console")); if (config.externalConsole && !config.console) { config.console = "externalTerminal"; } delete config.externalConsole; } if (os.platform() !== 'win32') { logger.getOutputChannelLogger().showWarningMessage(localize(6, null, "cppvsdbg", "cppdbg")); return undefined; } } return config; } resolveDebugConfigurationWithSubstitutedVariables(folder, config, token) { var _a, _b, _c, _d, _e; if (!config || !config.type) { return null; } if (config.type === 'cppvsdbg') { if (!config.enableDebugHeap) { const disableDebugHeapEnvSetting = { "name": "_NO_DEBUG_HEAP", "value": "1" }; if (config.environment && util.isArray(config.environment)) { config.environment.push(disableDebugHeapEnvSetting); } else { config.environment = [disableDebugHeapEnvSetting]; } } } this.resolveEnvFile(config, folder); this.resolveSourceFileMapVariables(config); if (os.platform() === 'win32' && config.pipeTransport && config.pipeTransport.pipeProgram) { let replacedPipeProgram; const pipeProgramStr = config.pipeTransport.pipeProgram.toLowerCase().trim(); replacedPipeProgram = debugUtils.ArchitectureReplacer.checkAndReplaceWSLPipeProgram(pipeProgramStr, debugUtils.ArchType.ia32); if (!replacedPipeProgram && !path.isAbsolute(pipeProgramStr) && config.pipeTransport.pipeCwd) { const pipeCwdStr = config.pipeTransport.pipeCwd.toLowerCase().trim(); const newPipeProgramStr = path.join(pipeCwdStr, pipeProgramStr); replacedPipeProgram = debugUtils.ArchitectureReplacer.checkAndReplaceWSLPipeProgram(newPipeProgramStr, debugUtils.ArchType.ia32); } if (replacedPipeProgram) { config.pipeTransport.pipeProgram = replacedPipeProgram; } } const macOSMIMode = (_b = (_a = config.osx) === null || _a === void 0 ? void 0 : _a.MIMode, (_b !== null && _b !== void 0 ? _b : config.MIMode)); const macOSMIDebuggerPath = (_d = (_c = config.osx) === null || _c === void 0 ? void 0 : _c.miDebuggerPath, (_d !== null && _d !== void 0 ? _d : config.miDebuggerPath)); const lldb_mi_10_x_path = path.join(util.extensionPath, "debugAdapters", "lldb-mi", "bin", "lldb-mi"); if (os.platform() === 'darwin' && fs.existsSync(lldb_mi_10_x_path) && (!macOSMIMode || macOSMIMode === 'lldb') && !macOSMIDebuggerPath) { const frameworkPath = this.getLLDBFrameworkPath(); if (!frameworkPath) { const moreInfoButton = localize(7, null); const LLDBFrameworkMissingMessage = localize(8, null); vscode.window.showErrorMessage(LLDBFrameworkMissingMessage, moreInfoButton) .then(value => { if (value === moreInfoButton) { const helpURL = "https://aka.ms/vscode-cpptools/LLDBFrameworkNotFound"; vscode.env.openExternal(vscode.Uri.parse(helpURL)); } }); return undefined; } } if ((_e = config.logging) === null || _e === void 0 ? void 0 : _e.engineLogging) { const outputChannel = logger.getOutputChannelLogger(); outputChannel.appendLine(localize(9, null)); outputChannel.appendLine(JSON.stringify(config, undefined, 2)); } return config; } getLLDBFrameworkPath() { const LLDBFramework = "LLDB.framework"; const searchPaths = [ "/Library/Developer/CommandLineTools/Library/PrivateFrameworks", "/Applications/Xcode.app/Contents/SharedFrameworks" ]; for (const searchPath of searchPaths) { if (fs.existsSync(path.join(searchPath, LLDBFramework))) { return searchPath; } } const outputChannel = logger.getOutputChannelLogger(); outputChannel.appendLine(localize(10, null, LLDBFramework)); outputChannel.appendLine(localize(11, null)); searchPaths.forEach(searchPath => { outputChannel.appendLine(`\t${searchPath}`); }); const xcodeCLIInstallCmd = "xcode-select --install"; outputChannel.appendLine(localize(12, null, xcodeCLIInstallCmd)); logger.showOutputChannel(); return undefined; } resolveEnvFile(config, folder) { if (config.envFile) { let envFilePath = util.resolveVariables(config.envFile, undefined); try { if (folder && folder.uri && folder.uri.fsPath) { envFilePath = envFilePath.replace(/(\${workspaceFolder}|\${workspaceRoot})/g, folder.uri.fsPath); } const parsedFile = ParsedEnvironmentFile_1.ParsedEnvironmentFile.CreateFromFile(envFilePath, config["environment"]); if (parsedFile.Warning) { CppConfigurationProvider.showFileWarningAsync(parsedFile.Warning, config.envFile); } config.environment = parsedFile.Env; delete config.envFile; } catch (e) { throw new Error(localize(13, null, "envFile", e.message)); } } } resolveSourceFileMapVariables(config) { const messages = []; if (config.sourceFileMap) { for (const sourceFileMapSource of Object.keys(config.sourceFileMap)) { let message = ""; const sourceFileMapTarget = config.sourceFileMap[sourceFileMapSource]; let source = sourceFileMapSource; let target = sourceFileMapTarget; const newSourceFileMapSource = util.resolveVariables(sourceFileMapSource, undefined); if (sourceFileMapSource !== newSourceFileMapSource) { message = "\t" + localize(14, null, "sourcePath", sourceFileMapSource, newSourceFileMapSource); delete config.sourceFileMap[sourceFileMapSource]; source = newSourceFileMapSource; } if (util.isString(sourceFileMapTarget)) { const newSourceFileMapTarget = util.resolveVariables(sourceFileMapTarget, undefined); if (sourceFileMapTarget !== newSourceFileMapTarget) { message += (message ? ' ' : '\t'); message += localize(15, null, "targetPath", sourceFileMapTarget, newSourceFileMapTarget); target = newSourceFileMapTarget; } } else if (util.isObject(sourceFileMapTarget)) { const newSourceFileMapTarget = sourceFileMapTarget; newSourceFileMapTarget["editorPath"] = util.resolveVariables(sourceFileMapTarget["editorPath"], undefined); if (sourceFileMapTarget !== newSourceFileMapTarget) { message += (message ? ' ' : '\t'); message += localize(16, null, "editorPath", sourceFileMapTarget, newSourceFileMapTarget["editorPath"]); target = newSourceFileMapTarget; } } if (message) { config.sourceFileMap[source] = target; messages.push(message); } } if (messages.length > 0) { logger.getOutputChannel().appendLine(localize(17, null, "sourceFileMap")); messages.forEach((message) => { logger.getOutputChannel().appendLine(message); }); logger.showOutputChannel(); } } } static showFileWarningAsync(message, fileName) { return __awaiter(this, void 0, void 0, function* () { const openItem = { title: localize(18, null, "envFile") }; const result = yield vscode.window.showWarningMessage(message, openItem); if (result && result.title === openItem.title) { const doc = yield vscode.workspace.openTextDocument(fileName); if (doc) { vscode.window.showTextDocument(doc); } } }); } } class CppVsDbgConfigurationProvider extends CppConfigurationProvider { constructor(provider) { super(provider, configurations_1.DebuggerType.cppvsdbg); } } exports.CppVsDbgConfigurationProvider = CppVsDbgConfigurationProvider; class CppDbgConfigurationProvider extends CppConfigurationProvider { constructor(provider) { super(provider, configurations_1.DebuggerType.cppdbg); } } exports.CppDbgConfigurationProvider = CppDbgConfigurationProvider; class ConfigurationAssetProviderFactory { static getConfigurationProvider() { switch (os.platform()) { case 'win32': return new WindowsConfigurationProvider(); case 'darwin': return new OSXConfigurationProvider(); case 'linux': return new LinuxConfigurationProvider(); default: throw new Error(localize(19, null)); } } } exports.ConfigurationAssetProviderFactory = ConfigurationAssetProviderFactory; class DefaultConfigurationProvider { constructor() { this.configurations = []; } getInitialConfigurations(debuggerType) { const configurationSnippet = []; this.configurations.forEach(configuration => { configurationSnippet.push(configuration.GetLaunchConfiguration()); }); const initialConfigurations = configurationSnippet.filter(snippet => snippet.debuggerType === debuggerType && snippet.isInitialConfiguration) .map(snippet => JSON.parse(snippet.bodyText)); return initialConfigurations; } getConfigurationSnippets() { const completionItems = []; this.configurations.forEach(configuration => { completionItems.push(convertConfigurationSnippetToCompetionItem(configuration.GetLaunchConfiguration())); completionItems.push(convertConfigurationSnippetToCompetionItem(configuration.GetAttachConfiguration())); }); return completionItems; } } class WindowsConfigurationProvider extends DefaultConfigurationProvider { constructor() { super(); this.executable = "a.exe"; this.pipeProgram = "<" + localize(20, null, "plink.exe").replace(/\"/g, "\\\"") + ">"; this.MIMode = 'gdb'; this.setupCommandsBlock = `"setupCommands": [ { "description": "${localize(21, null, "gdb").replace(/\"/g, "\\\"")}", "text": "-enable-pretty-printing", "ignoreFailures": true } ]`; this.configurations = [ new configurations_1.MIConfigurations(this.MIMode, this.executable, this.pipeProgram, this.setupCommandsBlock), new configurations_1.PipeTransportConfigurations(this.MIMode, this.executable, this.pipeProgram, this.setupCommandsBlock), new configurations_1.WindowsConfigurations(this.MIMode, this.executable, this.pipeProgram, this.setupCommandsBlock), new configurations_1.WSLConfigurations(this.MIMode, this.executable, this.pipeProgram, this.setupCommandsBlock) ]; } } class OSXConfigurationProvider extends DefaultConfigurationProvider { constructor() { super(); this.MIMode = 'lldb'; this.executable = "a.out"; this.pipeProgram = "/usr/bin/ssh"; this.configurations = [ new configurations_1.MIConfigurations(this.MIMode, this.executable, this.pipeProgram) ]; } } class LinuxConfigurationProvider extends DefaultConfigurationProvider { constructor() { super(); this.MIMode = 'gdb'; this.setupCommandsBlock = `"setupCommands": [ { "description": "${localize(22, null, "gdb").replace(/\"/g, "\\\"")}", "text": "-enable-pretty-printing", "ignoreFailures": true } ]`; this.executable = "a.out"; this.pipeProgram = "/usr/bin/ssh"; this.configurations = [ new configurations_1.MIConfigurations(this.MIMode, this.executable, this.pipeProgram, this.setupCommandsBlock), new configurations_1.PipeTransportConfigurations(this.MIMode, this.executable, this.pipeProgram, this.setupCommandsBlock) ]; } } function convertConfigurationSnippetToCompetionItem(snippet) { const item = new vscode.CompletionItem(snippet.label, vscode.CompletionItemKind.Snippet); item.insertText = snippet.bodyText; return item; } class ConfigurationSnippetProvider { constructor(provider) { this.provider = provider; this.snippets = this.provider.getConfigurationSnippets(); } resolveCompletionItem(item, token) { return Promise.resolve(item); } provideCompletionItems(document, position, token, context) { let items = this.snippets; const launch = comment_json_1.parse(document.getText()); if (launch.configurations.length !== 0) { items = []; this.snippets.forEach((item) => items.push(Object.assign({}, item))); items.map((item) => { item.insertText = item.insertText + ','; }); } return Promise.resolve(new vscode.CompletionList(items, true)); } } exports.ConfigurationSnippetProvider = ConfigurationSnippetProvider; /***/ }), /***/ 134: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const os = __webpack_require__(2087); const nls = __webpack_require__(3612); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\configurations.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\configurations.ts')); var DebuggerType; (function (DebuggerType) { DebuggerType[DebuggerType["cppvsdbg"] = 0] = "cppvsdbg"; DebuggerType[DebuggerType["cppdbg"] = 1] = "cppdbg"; })(DebuggerType = exports.DebuggerType || (exports.DebuggerType = {})); function indentJsonString(json, numTabs = 1) { return json.split('\n').map(line => '\t'.repeat(numTabs) + line).join('\n').trim(); } exports.indentJsonString = indentJsonString; function formatString(format, args) { for (const arg in args) { format = format.replace("{" + arg + "}", args[arg]); } return format; } function createLaunchString(name, type, executable) { return `"name": "${name}", "type": "${type}", "request": "launch", "program": "${localize(0, null, "$\{workspaceFolder\}" + "/" + executable).replace(/\"/g, "\\\"")}", "args": [], "stopAtEntry": false, "cwd": "$\{fileDirname\}", "environment": [], ${type === "cppdbg" ? `"externalConsole": false` : `"console": "externalTerminal"`} `; } function createAttachString(name, type, executable) { return formatString(` "name": "${name}", "type": "${type}", "request": "attach",{0} "processId": "$\{command:pickProcess\}" `, [type === "cppdbg" ? `${os.EOL}"program": "${localize(1, null, "$\{workspaceFolder\}" + "/" + executable).replace(/\"/g, "\\\"")}",` : ""]); } function createRemoteAttachString(name, type, executable) { return ` "name": "${name}", "type": "${type}", "request": "attach", "program": "${localize(2, null, "$\{workspaceFolder\}" + "/" + executable).replace(/\"/g, "\\\"")}", "processId": "$\{command:pickRemoteProcess\}" `; } function createPipeTransportString(pipeProgram, debuggerProgram, pipeArgs = []) { return ` "pipeTransport": { \t"debuggerPath": "/usr/bin/${debuggerProgram}", \t"pipeProgram": "${pipeProgram}", \t"pipeArgs": ${JSON.stringify(pipeArgs)}, \t"pipeCwd": "" }`; } class Configuration { constructor(MIMode, executable, pipeProgram, additionalProperties = "") { this.snippetPrefix = "C/C++: "; this.miDebugger = "cppdbg"; this.windowsDebugger = "cppvsdbg"; this.MIMode = MIMode; this.executable = executable; this.pipeProgram = pipeProgram; this.additionalProperties = additionalProperties; } } class MIConfigurations extends Configuration { GetLaunchConfiguration() { const name = `(${this.MIMode}) ${localize(3, null).replace(/\"/g, "\\\"")}`; const body = formatString(`{ \t${indentJsonString(createLaunchString(name, this.miDebugger, this.executable))}, \t"MIMode": "${this.MIMode}"{0}{1} }`, [this.miDebugger === "cppdbg" && os.platform() === "win32" ? `,${os.EOL}\t"miDebuggerPath": "/path/to/gdb"` : "", this.additionalProperties ? `,${os.EOL}\t${indentJsonString(this.additionalProperties)}` : ""]); return { "label": this.snippetPrefix + name, "description": localize(4, null, this.MIMode).replace(/\"/g, "\\\""), "bodyText": body.trim(), "isInitialConfiguration": true, "debuggerType": DebuggerType.cppdbg }; } GetAttachConfiguration() { const name = `(${this.MIMode}) ${localize(5, null).replace(/\"/g, "\\\"")}`; const body = formatString(`{ \t${indentJsonString(createAttachString(name, this.miDebugger, this.executable))}, \t"MIMode": "${this.MIMode}"{0}{1} }`, [this.miDebugger === "cppdbg" && os.platform() === "win32" ? `,${os.EOL}\t"miDebuggerPath": "/path/to/gdb"` : "", this.additionalProperties ? `,${os.EOL}\t${indentJsonString(this.additionalProperties)}` : ""]); return { "label": this.snippetPrefix + name, "description": localize(6, null, this.MIMode).replace(/\"/g, "\\\""), "bodyText": body.trim(), "debuggerType": DebuggerType.cppdbg }; } } exports.MIConfigurations = MIConfigurations; class PipeTransportConfigurations extends Configuration { GetLaunchConfiguration() { const name = `(${this.MIMode}) ${localize(7, null).replace(/\"/g, "\\\"")}`; const body = formatString(` { \t${indentJsonString(createLaunchString(name, this.miDebugger, this.executable))}, \t${indentJsonString(createPipeTransportString(this.pipeProgram, this.MIMode))}, \t"MIMode": "${this.MIMode}"{0} }`, [this.additionalProperties ? `,${os.EOL}\t${indentJsonString(this.additionalProperties)}` : ""]); return { "label": this.snippetPrefix + name, "description": localize(8, null, this.MIMode).replace(/\"/g, "\\\""), "bodyText": body.trim(), "debuggerType": DebuggerType.cppdbg }; } GetAttachConfiguration() { const name = `(${this.MIMode}) ${localize(9, null).replace(/\"/g, "\\\"")}`; const body = formatString(` { \t${indentJsonString(createRemoteAttachString(name, this.miDebugger, this.executable))}, \t${indentJsonString(createPipeTransportString(this.pipeProgram, this.MIMode))}, \t"MIMode": "${this.MIMode}"{0} }`, [this.additionalProperties ? `,${os.EOL}\t${indentJsonString(this.additionalProperties)}` : ""]); return { "label": this.snippetPrefix + name, "description": localize(10, null, this.MIMode).replace(/\"/g, "\\\""), "bodyText": body.trim(), "debuggerType": DebuggerType.cppdbg }; } } exports.PipeTransportConfigurations = PipeTransportConfigurations; class WindowsConfigurations extends Configuration { GetLaunchConfiguration() { const name = `(Windows) ${localize(11, null).replace(/\"/g, "\\\"")}`; const body = ` { \t${indentJsonString(createLaunchString(name, this.windowsDebugger, this.executable))} }`; return { "label": this.snippetPrefix + name, "description": localize(12, null).replace(/\"/g, "\\\""), "bodyText": body.trim(), "isInitialConfiguration": true, "debuggerType": DebuggerType.cppvsdbg }; } GetAttachConfiguration() { const name = `(Windows) ${localize(13, null).replace(/\"/g, "\\\"")}`; const body = ` { \t${indentJsonString(createAttachString(name, this.windowsDebugger, this.executable))} }`; return { "label": this.snippetPrefix + name, "description": localize(14, null).replace(/\"/g, "\\\""), "bodyText": body.trim(), "debuggerType": DebuggerType.cppvsdbg }; } } exports.WindowsConfigurations = WindowsConfigurations; class WSLConfigurations extends Configuration { constructor() { super(...arguments); this.bashPipeProgram = process.arch === 'ia32' ? "${env:windir}\\\\sysnative\\\\bash.exe" : "${env:windir}\\\\system32\\\\bash.exe"; } GetLaunchConfiguration() { const name = `(${this.MIMode}) ${localize(15, null).replace(/\"/g, "\\\"")}`; const body = formatString(` { \t${indentJsonString(createLaunchString(name, this.miDebugger, this.executable))}, \t${indentJsonString(createPipeTransportString(this.bashPipeProgram, this.MIMode, ["-c"]))}{0} }`, [this.additionalProperties ? `,${os.EOL}\t${indentJsonString(this.additionalProperties)}` : ""]); return { "label": this.snippetPrefix + name, "description": localize(16, null, this.MIMode).replace(/\"/g, "\\\""), "bodyText": body.trim(), "debuggerType": DebuggerType.cppdbg }; } GetAttachConfiguration() { const name = `(${this.MIMode}) ${localize(17, null).replace(/\"/g, "\\\"")}`; const body = formatString(` { \t${indentJsonString(createRemoteAttachString(name, this.miDebugger, this.executable))}, \t${indentJsonString(createPipeTransportString(this.bashPipeProgram, this.MIMode, ["-c"]))}{0} }`, [this.additionalProperties ? `,${os.EOL}\t${indentJsonString(this.additionalProperties)}` : ""]); return { "label": this.snippetPrefix + name, "description": localize(18, null, this.MIMode).replace(/\"/g, "\\\""), "bodyText": body.trim(), "debuggerType": DebuggerType.cppdbg }; } } exports.WSLConfigurations = WSLConfigurations; /***/ }), /***/ 4568: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const util = __webpack_require__(5331); const path = __webpack_require__(5622); const os = __webpack_require__(2087); const nls = __webpack_require__(3612); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\debugAdapterDescriptorFactory.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\debugAdapterDescriptorFactory.ts')); class AbstractDebugAdapterDescriptorFactory { constructor(context) { this.context = context; } } class CppdbgDebugAdapterDescriptorFactory extends AbstractDebugAdapterDescriptorFactory { constructor(context) { super(context); } createDebugAdapterDescriptor(session, executable) { return __awaiter(this, void 0, void 0, function* () { if (yield util.isExtensionReady()) { let command = path.join(this.context.extensionPath, './debugAdapters/OpenDebugAD7'); if (os.platform() === 'win32') { command = path.join(this.context.extensionPath, "./debugAdapters/bin/OpenDebugAD7.exe"); } return new vscode.DebugAdapterExecutable(command, []); } else { throw new Error(util.extensionNotReadyString); } }); } } exports.CppdbgDebugAdapterDescriptorFactory = CppdbgDebugAdapterDescriptorFactory; CppdbgDebugAdapterDescriptorFactory.DEBUG_TYPE = "cppdbg"; class CppvsdbgDebugAdapterDescriptorFactory extends AbstractDebugAdapterDescriptorFactory { constructor(context) { super(context); } createDebugAdapterDescriptor(session, executable) { return __awaiter(this, void 0, void 0, function* () { if (os.platform() !== 'win32') { vscode.window.showErrorMessage(localize(0, null, "cppvsdbg")); return null; } else { if (yield util.isExtensionReady()) { return new vscode.DebugAdapterExecutable(path.join(this.context.extensionPath, './debugAdapters/vsdbg/bin/vsdbg.exe'), ['--interpreter=vscode', '--extConfigDir=%USERPROFILE%\\.cppvsdbg\\extensions']); } else { throw new Error(util.extensionNotReadyString); } } }); } } exports.CppvsdbgDebugAdapterDescriptorFactory = CppvsdbgDebugAdapterDescriptorFactory; CppvsdbgDebugAdapterDescriptorFactory.DEBUG_TYPE = "cppvsdbg"; /***/ }), /***/ 2763: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const os = __webpack_require__(2087); const attachToProcess_1 = __webpack_require__(1191); const nativeAttach_1 = __webpack_require__(1476); const configurationProvider_1 = __webpack_require__(9042); const debugAdapterDescriptorFactory_1 = __webpack_require__(4568); const util = __webpack_require__(5331); const Telemetry = __webpack_require__(1818); const nls = __webpack_require__(3612); const extension_1 = __webpack_require__(2973); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\extension.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\extension.ts')); const disposables = []; function buildAndDebugActiveFileStr() { return ` - ${localize(0, null)}`; } exports.buildAndDebugActiveFileStr = buildAndDebugActiveFileStr; function initialize(context) { const attachItemsProvider = nativeAttach_1.NativeAttachItemsProviderFactory.Get(); const attacher = new attachToProcess_1.AttachPicker(attachItemsProvider); disposables.push(vscode.commands.registerCommand('extension.pickNativeProcess', () => attacher.ShowAttachEntries())); const remoteAttacher = new attachToProcess_1.RemoteAttachPicker(); disposables.push(vscode.commands.registerCommand('extension.pickRemoteNativeProcess', (any) => remoteAttacher.ShowAttachEntries(any))); const configurationProvider = configurationProvider_1.ConfigurationAssetProviderFactory.getConfigurationProvider(); let vsdbgProvider = null; if (os.platform() === 'win32') { vsdbgProvider = new configurationProvider_1.CppVsDbgConfigurationProvider(configurationProvider); disposables.push(vscode.debug.registerDebugConfigurationProvider('cppvsdbg', new configurationProvider_1.QuickPickConfigurationProvider(vsdbgProvider))); } const provider = new configurationProvider_1.CppDbgConfigurationProvider(configurationProvider); disposables.push(vscode.debug.registerDebugConfigurationProvider('cppdbg', new configurationProvider_1.QuickPickConfigurationProvider(provider))); disposables.push(vscode.commands.registerTextEditorCommand("C_Cpp.BuildAndDebugActiveFile", (textEditor, edit, ...args) => __awaiter(this, void 0, void 0, function* () { const folder = vscode.workspace.getWorkspaceFolder(textEditor.document.uri); if (!folder) { vscode.window.showErrorMessage(localize(1, null)); return Promise.resolve(); } if (!util.fileIsCOrCppSource(textEditor.document.uri.fsPath)) { vscode.window.showErrorMessage(localize(2, null)); return Promise.resolve(); } const configs = (yield provider.provideDebugConfigurations(folder)).filter(config => config.name.indexOf(buildAndDebugActiveFileStr()) !== -1); if (vsdbgProvider) { const vsdbgConfigs = (yield vsdbgProvider.provideDebugConfigurations(folder)).filter(config => config.name.indexOf(buildAndDebugActiveFileStr()) !== -1); if (vsdbgConfigs) { configs.push(...vsdbgConfigs); } } const items = configs.map(config => ({ label: config.name, configuration: config, description: config.detail })); const selection = yield vscode.window.showQuickPick(items, { placeHolder: (items.length === 0 ? localize(3, null) : localize(4, null)) }); if (!selection) { return; } if (selection.label.startsWith("cl.exe")) { if (!process.env.DevEnvDir || process.env.DevEnvDir.length === 0) { vscode.window.showErrorMessage(localize(5, null, "cl.exe")); return; } } if (selection.configuration.preLaunchTask) { if (folder) { try { yield extension_1.cppBuildTaskProvider.ensureBuildTaskExists(selection.configuration.preLaunchTask); Telemetry.logDebuggerEvent("buildAndDebug", { "success": "false" }); } catch (e) { if (e && e.message === util.failedToParseJson) { vscode.window.showErrorMessage(util.failedToParseJson); } return; } } else { return; } } try { yield extension_1.cppBuildTaskProvider.ensureDebugConfigExists(selection.configuration.name); try { yield vscode.debug.startDebugging(folder, selection.configuration.name); Telemetry.logDebuggerEvent("buildAndDebug", { "success": "true" }); } catch (e) { Telemetry.logDebuggerEvent("buildAndDebug", { "success": "false" }); } } catch (e) { try { yield vscode.debug.startDebugging(folder, selection.configuration); Telemetry.logDebuggerEvent("buildAndDebug", { "success": "true" }); } catch (e) { Telemetry.logDebuggerEvent("buildAndDebug", { "success": "false" }); } } }))); configurationProvider.getConfigurationSnippets(); const launchJsonDocumentSelector = [{ scheme: 'file', language: 'jsonc', pattern: '**/launch.json' }]; disposables.push(vscode.languages.registerCompletionItemProvider(launchJsonDocumentSelector, new configurationProvider_1.ConfigurationSnippetProvider(configurationProvider))); disposables.push(vscode.debug.registerDebugAdapterDescriptorFactory(debugAdapterDescriptorFactory_1.CppvsdbgDebugAdapterDescriptorFactory.DEBUG_TYPE, new debugAdapterDescriptorFactory_1.CppvsdbgDebugAdapterDescriptorFactory(context))); disposables.push(vscode.debug.registerDebugAdapterDescriptorFactory(debugAdapterDescriptorFactory_1.CppdbgDebugAdapterDescriptorFactory.DEBUG_TYPE, new debugAdapterDescriptorFactory_1.CppdbgDebugAdapterDescriptorFactory(context))); vscode.Disposable.from(...disposables); } exports.initialize = initialize; function dispose() { disposables.forEach(d => d.dispose()); } exports.dispose = dispose; /***/ }), /***/ 1476: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const child_process = __webpack_require__(3129); const os = __webpack_require__(2087); const nls = __webpack_require__(3612); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\nativeAttach.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\Debugger\\nativeAttach.ts')); class Process { constructor(name, pid, commandLine) { this.name = name; this.pid = pid; this.commandLine = commandLine; } toAttachItem() { return { label: this.name, description: this.pid, detail: this.commandLine, id: this.pid }; } } exports.Process = Process; class NativeAttachItemsProviderFactory { static Get() { if (os.platform() === 'win32') { return new WmicAttachItemsProvider(); } else { return new PsAttachItemsProvider(); } } } exports.NativeAttachItemsProviderFactory = NativeAttachItemsProviderFactory; class NativeAttachItemsProvider { getAttachItems() { return __awaiter(this, void 0, void 0, function* () { const processEntries = yield this.getInternalProcessEntries(); processEntries.sort((a, b) => { if (a.name === undefined) { if (b.name === undefined) { return 0; } return 1; } if (b.name === undefined) { return -1; } const aLower = a.name.toLowerCase(); const bLower = b.name.toLowerCase(); if (aLower === bLower) { return 0; } return aLower < bLower ? -1 : 1; }); const attachItems = processEntries.map(p => p.toAttachItem()); return attachItems; }); } } class PsAttachItemsProvider extends NativeAttachItemsProvider { getInternalProcessEntries() { return __awaiter(this, void 0, void 0, function* () { let processCmd = ''; switch (os.platform()) { case 'darwin': processCmd = PsProcessParser.psDarwinCommand; break; case 'linux': processCmd = PsProcessParser.psLinuxCommand; break; default: throw new Error(localize(0, null, os.platform())); } const processes = yield execChildProcess(processCmd, undefined); return PsProcessParser.ParseProcessFromPs(processes); }); } } exports.PsAttachItemsProvider = PsAttachItemsProvider; class PsProcessParser { static get secondColumnCharacters() { return 50; } static get commColumnTitle() { return Array(PsProcessParser.secondColumnCharacters).join("a"); } static get psLinuxCommand() { return `ps axww -o pid=,comm=${PsProcessParser.commColumnTitle},args=`; } static get psDarwinCommand() { return `ps axww -o pid=,comm=${PsProcessParser.commColumnTitle},args= -c`; } static ParseProcessFromPs(processes) { const lines = processes.split(os.EOL); return PsProcessParser.ParseProcessFromPsArray(lines); } static ParseProcessFromPsArray(processArray) { const processEntries = []; for (let i = 1; i < processArray.length; i++) { const line = processArray[i]; if (!line) { continue; } const processEntry = PsProcessParser.parseLineFromPs(line); if (processEntry) { processEntries.push(processEntry); } } return processEntries; } static parseLineFromPs(line) { const psEntry = new RegExp(`^\\s*([0-9]+)\\s+(.{${PsProcessParser.secondColumnCharacters - 1}})\\s+(.*)$`); const matches = psEntry.exec(line); if (matches && matches.length === 4) { const pid = matches[1].trim(); const executable = matches[2].trim(); const cmdline = matches[3].trim(); return new Process(executable, pid, cmdline); } } } exports.PsProcessParser = PsProcessParser; function execChildProcess(process, workingDirectory) { return new Promise((resolve, reject) => { child_process.exec(process, { cwd: workingDirectory, maxBuffer: 500 * 1024 }, (error, stdout, stderr) => { if (error) { reject(error); return; } if (stderr && stderr.length > 0) { if (stderr.indexOf('screen size is bogus') >= 0) { } else { reject(new Error(stderr)); return; } } resolve(stdout); }); }); } class WmicAttachItemsProvider extends NativeAttachItemsProvider { getInternalProcessEntries() { return __awaiter(this, void 0, void 0, function* () { const wmicCommand = 'wmic process get Name,ProcessId,CommandLine /FORMAT:list'; const processes = yield execChildProcess(wmicCommand, undefined); return WmicProcessParser.ParseProcessFromWmic(processes); }); } } exports.WmicAttachItemsProvider = WmicAttachItemsProvider; class WmicProcessParser { static get wmicNameTitle() { return 'Name'; } static get wmicCommandLineTitle() { return 'CommandLine'; } static get wmicPidTitle() { return 'ProcessId'; } static ParseProcessFromWmic(processes) { const lines = processes.split(os.EOL); let currentProcess = new Process("current process", undefined, undefined); const processEntries = []; for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (!line) { continue; } WmicProcessParser.parseLineFromWmic(line, currentProcess); if (line.lastIndexOf(WmicProcessParser.wmicPidTitle, 0) === 0) { processEntries.push(currentProcess); currentProcess = new Process("current process", undefined, undefined); } } return processEntries; } static parseLineFromWmic(line, process) { const splitter = line.indexOf('='); if (splitter >= 0) { const key = line.slice(0, line.indexOf('=')).trim(); let value = line.slice(line.indexOf('=') + 1).trim(); if (key === WmicProcessParser.wmicNameTitle) { process.name = value; } else if (key === WmicProcessParser.wmicPidTitle) { process.pid = value; } else if (key === WmicProcessParser.wmicCommandLineTitle) { const extendedLengthPath = '\\??\\'; if (value.lastIndexOf(extendedLengthPath, 0) === 0) { value = value.slice(extendedLengthPath.length); } process.commandLine = value; } } } } exports.WmicProcessParser = WmicProcessParser; /***/ }), /***/ 1371: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var ArchType; (function (ArchType) { ArchType[ArchType["ia32"] = 0] = "ia32"; ArchType[ArchType["x64"] = 1] = "x64"; })(ArchType = exports.ArchType || (exports.ArchType = {})); class ArchitectureReplacer { static checkAndReplaceWSLPipeProgram(pipeProgramStr, expectedArch) { let replacedPipeProgram; const winDir = process.env.WINDIR ? process.env.WINDIR.toLowerCase() : undefined; const winDirAltDirSep = process.env.WINDIR ? process.env.WINDIR.replace('\\', '/').toLowerCase() : undefined; const winDirEnv = "${env:windir}"; if (winDir && winDirAltDirSep && (pipeProgramStr.indexOf(winDir) === 0 || pipeProgramStr.indexOf(winDirAltDirSep) === 0 || pipeProgramStr.indexOf(winDirEnv) === 0)) { if (expectedArch === ArchType.x64) { const pathSep = ArchitectureReplacer.checkForFolderInPath(pipeProgramStr, "sysnative"); if (pathSep) { replacedPipeProgram = pipeProgramStr.replace(`${pathSep}sysnative${pathSep}`, `${pathSep}system32${pathSep}`); } } else if (expectedArch === ArchType.ia32) { const pathSep = ArchitectureReplacer.checkForFolderInPath(pipeProgramStr, "system32"); if (pathSep) { replacedPipeProgram = pipeProgramStr.replace(`${pathSep}system32${pathSep}`, `${pathSep}sysnative${pathSep}`); } } } return replacedPipeProgram; } static checkForFolderInPath(path, folder) { if (path.indexOf(`/${folder}/`) >= 0) { return '/'; } else if (path.indexOf(`\\${folder}\\`) >= 0) { return '\\'; } return ""; } } exports.ArchitectureReplacer = ArchitectureReplacer; /***/ }), /***/ 6790: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const client_1 = __webpack_require__(9325); const settings_1 = __webpack_require__(296); const editorConfig = __webpack_require__(9138); class DocumentFormattingEditProvider { constructor(client) { this.client = client; } provideDocumentFormattingEdits(document, options, token) { return __awaiter(this, void 0, void 0, function* () { yield this.client.awaitUntilLanguageClientReady(); const filePath = document.uri.fsPath; const configCallBack = (editorConfigSettings) => __awaiter(this, void 0, void 0, function* () { const params = { settings: Object.assign({}, editorConfigSettings), uri: document.uri.toString(), insertSpaces: options.insertSpaces, tabSize: options.tabSize, character: "", range: { start: { character: 0, line: 0 }, end: { character: 0, line: 0 } } }; const textEdits = yield this.client.languageClient.sendRequest(client_1.FormatDocumentRequest, params); const results = []; textEdits.forEach((textEdit) => { results.push({ range: new vscode.Range(textEdit.range.start.line, textEdit.range.start.character, textEdit.range.end.line, textEdit.range.end.character), newText: textEdit.newText }); }); return results; }); const settings = new settings_1.CppSettings(); if (settings.formattingEngine !== "vcFormat") { return configCallBack(undefined); } else { let editorConfigSettings = client_1.cachedEditorConfigSettings.get(filePath); if (!editorConfigSettings) { editorConfigSettings = yield editorConfig.parse(filePath); if (editorConfigSettings !== undefined) { client_1.cachedEditorConfigSettings.set(filePath, editorConfigSettings); } } return configCallBack(editorConfigSettings); } }); } } exports.DocumentFormattingEditProvider = DocumentFormattingEditProvider; /***/ }), /***/ 1438: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const client_1 = __webpack_require__(9325); const settings_1 = __webpack_require__(296); const editorConfig = __webpack_require__(9138); class DocumentRangeFormattingEditProvider { constructor(client) { this.client = client; } provideDocumentRangeFormattingEdits(document, range, options, token) { return __awaiter(this, void 0, void 0, function* () { yield this.client.awaitUntilLanguageClientReady(); const filePath = document.uri.fsPath; const configCallBack = (editorConfigSettings) => __awaiter(this, void 0, void 0, function* () { const params = { settings: Object.assign({}, editorConfigSettings), uri: document.uri.toString(), insertSpaces: options.insertSpaces, tabSize: options.tabSize, character: "", range: { start: { character: range.start.character, line: range.start.line }, end: { character: range.end.character, line: range.end.line } } }; const textEdits = yield this.client.languageClient.sendRequest(client_1.FormatRangeRequest, params); const result = []; textEdits.forEach((textEdit) => { result.push({ range: new vscode.Range(textEdit.range.start.line, textEdit.range.start.character, textEdit.range.end.line, textEdit.range.end.character), newText: textEdit.newText }); }); return result; }); const settings = new settings_1.CppSettings(); if (settings.formattingEngine !== "vcFormat") { return configCallBack(undefined); } else { let editorConfigSettings = client_1.cachedEditorConfigSettings.get(filePath); if (!editorConfigSettings) { editorConfigSettings = yield editorConfig.parse(filePath); if (editorConfigSettings !== undefined) { client_1.cachedEditorConfigSettings.set(filePath, editorConfigSettings); } } return configCallBack(editorConfigSettings); } }); } ; } exports.DocumentRangeFormattingEditProvider = DocumentRangeFormattingEditProvider; /***/ }), /***/ 4763: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const client_1 = __webpack_require__(9325); const util = __webpack_require__(5331); const extension_1 = __webpack_require__(2973); class DocumentSymbolProvider { constructor(client) { this.client = client; } getChildrenSymbols(symbols) { const documentSymbols = []; if (symbols) { symbols.forEach((symbol) => { let detail = util.getLocalizedString(symbol.detail); if (symbol.scope === client_1.SymbolScope.Private) { if (detail.length === 0) { detail = "private"; } else { detail = util.getLocalizedSymbolScope("private", detail); } } else if (symbol.scope === client_1.SymbolScope.Protected) { if (detail.length === 0) { detail = "protected"; } else { detail = util.getLocalizedSymbolScope("protected", detail); } } const r = new vscode.Range(symbol.range.start.line, symbol.range.start.character, symbol.range.end.line, symbol.range.end.character); const sr = new vscode.Range(symbol.selectionRange.start.line, symbol.selectionRange.start.character, symbol.selectionRange.end.line, symbol.selectionRange.end.character); const vscodeSymbol = new vscode.DocumentSymbol(symbol.name, detail, symbol.kind, r, sr); vscodeSymbol.children = this.getChildrenSymbols(symbol.children); documentSymbols.push(vscodeSymbol); }); } return documentSymbols; } provideDocumentSymbols(document) { return __awaiter(this, void 0, void 0, function* () { if (!this.client.TrackedDocuments.has(document)) { extension_1.processDelayedDidOpen(document); } return this.client.requestWhenReady(() => __awaiter(this, void 0, void 0, function* () { const params = { uri: document.uri.toString() }; const symbols = yield this.client.languageClient.sendRequest(client_1.GetDocumentSymbolRequest, params); const resultSymbols = this.getChildrenSymbols(symbols); return resultSymbols; })); }); } } exports.DocumentSymbolProvider = DocumentSymbolProvider; /***/ }), /***/ 676: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const client_1 = __webpack_require__(9325); const vscode_languageclient_1 = __webpack_require__(3094); const refs = __webpack_require__(2664); class FindAllReferencesProvider { constructor(client) { this.client = client; } provideReferences(document, position, context, token) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { const callback = () => __awaiter(this, void 0, void 0, function* () { const params = { position: vscode_languageclient_1.Position.create(position.line, position.character), textDocument: this.client.languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document) }; client_1.DefaultClient.referencesParams = params; yield this.client.awaitUntilLanguageClientReady(); if (params !== client_1.DefaultClient.referencesParams) { const locations = []; resolve(locations); return; } client_1.DefaultClient.referencesRequestPending = true; const resultCallback = (result, doResolve) => { client_1.DefaultClient.referencesRequestPending = false; const locations = []; if (result) { result.referenceInfos.forEach((referenceInfo) => { if (referenceInfo.type === refs.ReferenceType.Confirmed) { const uri = vscode.Uri.file(referenceInfo.file); const range = new vscode.Range(referenceInfo.position.line, referenceInfo.position.character, referenceInfo.position.line, referenceInfo.position.character + result.text.length); locations.push(new vscode.Location(uri, range)); } }); } if (doResolve) { resolve(locations); } if (client_1.DefaultClient.referencesPendingCancellations.length > 0) { while (client_1.DefaultClient.referencesPendingCancellations.length > 1) { const pendingCancel = client_1.DefaultClient.referencesPendingCancellations[0]; client_1.DefaultClient.referencesPendingCancellations.pop(); pendingCancel.reject(); } const pendingCancel = client_1.DefaultClient.referencesPendingCancellations[0]; client_1.DefaultClient.referencesPendingCancellations.pop(); pendingCancel.callback(); } }; if (!client_1.workspaceReferences.referencesRefreshPending) { client_1.workspaceReferences.setResultsCallback(resultCallback); client_1.workspaceReferences.startFindAllReferences(params); } else { client_1.workspaceReferences.referencesRefreshPending = false; if (client_1.workspaceReferences.lastResults) { const lastResults = client_1.workspaceReferences.lastResults; client_1.workspaceReferences.lastResults = null; resultCallback(lastResults, true); } else { client_1.workspaceReferences.referencesRequestPending = true; client_1.workspaceReferences.setResultsCallback(resultCallback); this.client.languageClient.sendNotification(client_1.RequestReferencesNotification, false); } } token.onCancellationRequested(e => { if (params === client_1.DefaultClient.referencesParams) { this.client.cancelReferences(); } }); }); if (client_1.DefaultClient.referencesRequestPending || (client_1.workspaceReferences.symbolSearchInProgress && !client_1.workspaceReferences.referencesRefreshPending)) { const cancelling = client_1.DefaultClient.referencesPendingCancellations.length > 0; client_1.DefaultClient.referencesPendingCancellations.push({ reject: () => { const locations = []; resolve(locations); }, callback }); if (!cancelling) { client_1.DefaultClient.renamePending = false; client_1.workspaceReferences.referencesCanceled = true; if (!client_1.DefaultClient.referencesRequestPending) { client_1.workspaceReferences.referencesCanceledWhilePreviewing = true; } this.client.languageClient.sendNotification(client_1.CancelReferencesNotification); } } else { callback(); } }); }); } } exports.FindAllReferencesProvider = FindAllReferencesProvider; /***/ }), /***/ 2042: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const client_1 = __webpack_require__(9325); class FoldingRangeProvider { constructor(client) { this.onDidChangeFoldingRangesEvent = new vscode.EventEmitter(); this.client = client; this.onDidChangeFoldingRanges = this.onDidChangeFoldingRangesEvent.event; } provideFoldingRanges(document, context, token) { return __awaiter(this, void 0, void 0, function* () { const id = ++client_1.DefaultClient.abortRequestId; const params = { id: id, uri: document.uri.toString() }; yield this.client.awaitUntilLanguageClientReady(); token.onCancellationRequested(e => this.client.abortRequest(id)); const ranges = yield this.client.languageClient.sendRequest(client_1.GetFoldingRangesRequest, params); if (ranges.canceled) { return undefined; } const result = []; ranges.ranges.forEach((r, index, array) => { let nextNonNestedIndex = index + 1; for (; nextNonNestedIndex < array.length; ++nextNonNestedIndex) { if (array[nextNonNestedIndex].range.start.line >= r.range.end.line) { break; } } const foldingRange = { start: r.range.start.line, end: r.range.end.line - (nextNonNestedIndex >= array.length ? 0 : (array[nextNonNestedIndex].range.start.line !== r.range.end.line ? 0 : 1)) }; switch (r.kind) { case client_1.FoldingRangeKind.Comment: foldingRange.kind = vscode.FoldingRangeKind.Comment; break; case client_1.FoldingRangeKind.Imports: foldingRange.kind = vscode.FoldingRangeKind.Imports; break; case client_1.FoldingRangeKind.Region: foldingRange.kind = vscode.FoldingRangeKind.Region; break; default: break; } result.push(foldingRange); }); return result; }); } refresh() { this.onDidChangeFoldingRangesEvent.fire(); } } exports.FoldingRangeProvider = FoldingRangeProvider; /***/ }), /***/ 1684: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const client_1 = __webpack_require__(9325); const settings_1 = __webpack_require__(296); const editorConfig = __webpack_require__(9138); class OnTypeFormattingEditProvider { constructor(client) { this.client = client; } provideOnTypeFormattingEdits(document, position, ch, options, token) { return __awaiter(this, void 0, void 0, function* () { yield this.client.awaitUntilLanguageClientReady(); const filePath = document.uri.fsPath; const configCallBack = (editorConfigSettings) => __awaiter(this, void 0, void 0, function* () { const params = { settings: Object.assign({}, editorConfigSettings), uri: document.uri.toString(), insertSpaces: options.insertSpaces, tabSize: options.tabSize, character: ch, range: { start: { character: position.character, line: position.line }, end: { character: 0, line: 0 } } }; const textEdits = yield this.client.languageClient.sendRequest(client_1.FormatOnTypeRequest, params); const result = []; textEdits.forEach((textEdit) => { result.push({ range: new vscode.Range(textEdit.range.start.line, textEdit.range.start.character, textEdit.range.end.line, textEdit.range.end.character), newText: textEdit.newText }); }); return result; }); const settings = new settings_1.CppSettings(); if (settings.formattingEngine !== "vcFormat") { if (ch !== ';') { const result = []; return result; } else { return configCallBack(undefined); } } else { let editorConfigSettings = client_1.cachedEditorConfigSettings.get(filePath); if (!editorConfigSettings) { editorConfigSettings = yield editorConfig.parse(filePath); if (editorConfigSettings !== undefined) { client_1.cachedEditorConfigSettings.set(filePath, editorConfigSettings); } } return configCallBack(editorConfigSettings); } }); } } exports.OnTypeFormattingEditProvider = OnTypeFormattingEditProvider; /***/ }), /***/ 2568: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const client_1 = __webpack_require__(9325); const refs = __webpack_require__(2664); const settings_1 = __webpack_require__(296); const vscode_languageclient_1 = __webpack_require__(3094); const nls = __webpack_require__(3612); const util = __webpack_require__(5331); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\Providers\\renameProvider.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\Providers\\renameProvider.ts')); class RenameProvider { constructor(client) { this.client = client; } provideRenameEdits(document, position, newName, token) { return __awaiter(this, void 0, void 0, function* () { const settings = new settings_1.CppSettings(); if (settings.renameRequiresIdentifier && !util.isValidIdentifier(newName)) { vscode.window.showErrorMessage(localize(0, null)); const workspaceEdit = new vscode.WorkspaceEdit(); return workspaceEdit; } client_1.DefaultClient.renamePending = true; ++client_1.DefaultClient.renameRequestsPending; return new Promise((resolve, reject) => { const callback = () => __awaiter(this, void 0, void 0, function* () { const params = { newName: newName, position: vscode_languageclient_1.Position.create(position.line, position.character), textDocument: this.client.languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document) }; client_1.DefaultClient.referencesParams = params; yield this.client.awaitUntilLanguageClientReady(); if (params !== client_1.DefaultClient.referencesParams) { if (--client_1.DefaultClient.renameRequestsPending === 0) { client_1.DefaultClient.renamePending = false; } const workspaceEdit = new vscode.WorkspaceEdit(); resolve(workspaceEdit); return; } client_1.DefaultClient.referencesRequestPending = true; client_1.workspaceReferences.setResultsCallback((referencesResult, doResolve) => { client_1.DefaultClient.referencesRequestPending = false; --client_1.DefaultClient.renameRequestsPending; const workspaceEdit = new vscode.WorkspaceEdit(); const cancelling = client_1.DefaultClient.referencesPendingCancellations.length > 0; if (cancelling) { while (client_1.DefaultClient.referencesPendingCancellations.length > 1) { const pendingCancel = client_1.DefaultClient.referencesPendingCancellations[0]; client_1.DefaultClient.referencesPendingCancellations.pop(); pendingCancel.reject(); } const pendingCancel = client_1.DefaultClient.referencesPendingCancellations[0]; client_1.DefaultClient.referencesPendingCancellations.pop(); pendingCancel.callback(); } else { if (client_1.DefaultClient.renameRequestsPending === 0) { client_1.DefaultClient.renamePending = false; } if (referencesResult) { for (const reference of referencesResult.referenceInfos) { const uri = vscode.Uri.file(reference.file); const range = new vscode.Range(reference.position.line, reference.position.character, reference.position.line, reference.position.character + referencesResult.text.length); const metadata = { needsConfirmation: reference.type !== refs.ReferenceType.Confirmed, label: refs.getReferenceTagString(reference.type, false, true), iconPath: refs.getReferenceItemIconPath(reference.type, false) }; workspaceEdit.replace(uri, range, newName, metadata); } } } if (referencesResult && (referencesResult.referenceInfos === null || referencesResult.referenceInfos.length === 0)) { vscode.window.showErrorMessage(localize(1, null)); } resolve(workspaceEdit); }); client_1.workspaceReferences.startRename(params); }); if (client_1.DefaultClient.referencesRequestPending || client_1.workspaceReferences.symbolSearchInProgress) { const cancelling = client_1.DefaultClient.referencesPendingCancellations.length > 0; client_1.DefaultClient.referencesPendingCancellations.push({ reject: () => { --client_1.DefaultClient.renameRequestsPending; const workspaceEdit = new vscode.WorkspaceEdit(); resolve(workspaceEdit); }, callback }); if (!cancelling) { client_1.workspaceReferences.referencesCanceled = true; if (!client_1.DefaultClient.referencesRequestPending) { client_1.workspaceReferences.referencesCanceledWhilePreviewing = true; } this.client.languageClient.sendNotification(client_1.CancelReferencesNotification); } } else { callback(); } }); }); } } exports.RenameProvider = RenameProvider; /***/ }), /***/ 6595: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const client_1 = __webpack_require__(9325); class SemanticTokensProvider { constructor(client) { this.onDidChangeSemanticTokensEvent = new vscode.EventEmitter(); this.tokenCaches = new Map(); this.client = client; this.onDidChangeSemanticTokens = this.onDidChangeSemanticTokensEvent.event; } provideDocumentSemanticTokens(document, token) { return __awaiter(this, void 0, void 0, function* () { yield this.client.awaitUntilLanguageClientReady(); const uriString = document.uri.toString(); const cache = this.tokenCaches.get(uriString); if (cache && cache[0] === document.version) { return cache[1]; } else { token.onCancellationRequested(_e => this.client.abortRequest(id)); const id = ++client_1.DefaultClient.abortRequestId; const params = { id: id, uri: uriString }; const tokensResult = yield this.client.languageClient.sendRequest(client_1.GetSemanticTokensRequest, params); if (tokensResult.canceled) { throw new vscode.CancellationError(); } else { if (tokensResult.fileVersion !== client_1.openFileVersions.get(uriString)) { throw new vscode.CancellationError(); } else { const builder = new vscode.SemanticTokensBuilder(this.client.semanticTokensLegend); tokensResult.tokens.forEach((token) => { builder.push(token.line, token.character, token.length, token.type, token.modifiers); }); const tokens = builder.build(); this.tokenCaches.set(uriString, [tokensResult.fileVersion, tokens]); return tokens; } } } }); } invalidateFile(uri) { this.tokenCaches.delete(uri); this.onDidChangeSemanticTokensEvent.fire(); } } exports.SemanticTokensProvider = SemanticTokensProvider; /***/ }), /***/ 4015: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const client_1 = __webpack_require__(9325); const util = __webpack_require__(5331); class WorkspaceSymbolProvider { constructor(client) { this.client = client; } provideWorkspaceSymbols(query, token) { return __awaiter(this, void 0, void 0, function* () { const params = { query: query }; const symbols = yield this.client.languageClient.sendRequest(client_1.GetSymbolInfoRequest, params); const resultSymbols = []; symbols.forEach((symbol) => { let suffix = util.getLocalizedString(symbol.suffix); let name = symbol.name; if (suffix.length) { if (symbol.scope === client_1.SymbolScope.Private) { suffix = util.getLocalizedSymbolScope("private", suffix); } else if (symbol.scope === client_1.SymbolScope.Protected) { suffix = util.getLocalizedSymbolScope("protected", suffix); } name = name + ' (' + suffix + ')'; } else { if (symbol.scope === client_1.SymbolScope.Private) { name = name + " (private)"; } else if (symbol.scope === client_1.SymbolScope.Protected) { name = name + " (protected)"; } } const range = new vscode.Range(symbol.location.range.start.line, symbol.location.range.start.character, symbol.location.range.end.line, symbol.location.range.end.character); const uri = vscode.Uri.parse(symbol.location.uri.toString()); const vscodeSymbol = new vscode.SymbolInformation(name, symbol.kind, symbol.containerName, new vscode.Location(uri, range)); resultSymbols.push(vscodeSymbol); }); return resultSymbols; }); } } exports.WorkspaceSymbolProvider = WorkspaceSymbolProvider; /***/ }), /***/ 9325: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __webpack_require__(5622); const vscode = __webpack_require__(7549); const onTypeFormattingEditProvider_1 = __webpack_require__(1684); const foldingRangeProvider_1 = __webpack_require__(2042); const semanticTokensProvider_1 = __webpack_require__(6595); const documentFormattingEditProvider_1 = __webpack_require__(6790); const documentRangeFormattingEditProvider_1 = __webpack_require__(1438); const documentSymbolProvider_1 = __webpack_require__(4763); const workspaceSymbolProvider_1 = __webpack_require__(4015); const renameProvider_1 = __webpack_require__(2568); const findAllReferencesProvider_1 = __webpack_require__(676); const vscode_languageclient_1 = __webpack_require__(3094); const vscode_cpptools_1 = __webpack_require__(3286); const testApi_1 = __webpack_require__(7373); const util = __webpack_require__(5331); const configs = __webpack_require__(6932); const settings_1 = __webpack_require__(296); const telemetry = __webpack_require__(1818); const persistentState_1 = __webpack_require__(1102); const ui_1 = __webpack_require__(6713); const protocolFilter_1 = __webpack_require__(9696); const dataBinding_1 = __webpack_require__(1748); const minimatch = __webpack_require__(5076); const logger = __webpack_require__(5610); const extension_1 = __webpack_require__(2973); const settingsTracker_1 = __webpack_require__(5313); const testHook_1 = __webpack_require__(5648); const customProviders_1 = __webpack_require__(4977); const fs = __webpack_require__(5747); const os = __webpack_require__(2087); const refs = __webpack_require__(2664); const nls = __webpack_require__(3612); const nativeStrings_1 = __webpack_require__(5391); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\client.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\client.ts')); let ui; let timeStamp = 0; const configProviderTimeout = 2000; let languageClient; let languageClientCrashedNeedsRestart = false; const languageClientCrashTimes = []; let clientCollection; let pendingTask; let compilerDefaults; let diagnosticsChannel; let outputChannel; let debugChannel; let warningChannel; let diagnosticsCollection; let workspaceDisposables = []; exports.openFileVersions = new Map(); exports.cachedEditorConfigSettings = new Map(); function disposeWorkspaceData() { workspaceDisposables.forEach((d) => d.dispose()); workspaceDisposables = []; } exports.disposeWorkspaceData = disposeWorkspaceData; function logTelemetry(notificationBody) { telemetry.logLanguageServerEvent(notificationBody.event, notificationBody.properties, notificationBody.metrics); } function setupOutputHandlers() { console.assert(languageClient !== undefined, "This method must not be called until this.languageClient is set in \"onReady\""); languageClient.onNotification(DebugProtocolNotification, (output) => { if (!debugChannel) { debugChannel = vscode.window.createOutputChannel(`${localize(0, null)}`); workspaceDisposables.push(debugChannel); } debugChannel.appendLine(""); debugChannel.appendLine("************************************************************************************************************************"); debugChannel.append(`${output}`); }); languageClient.onNotification(DebugLogNotification, logLocalized); } function log(output) { if (!outputChannel) { outputChannel = logger.getOutputChannel(); workspaceDisposables.push(outputChannel); } outputChannel.appendLine(`${output}`); } function logLocalized(params) { const output = util.getLocalizedString(params); log(output); } function showMessageWindow(params) { const message = util.getLocalizedString(params.localizeStringParams); switch (params.type) { case 1: vscode.window.showErrorMessage(message); break; case 2: vscode.window.showWarningMessage(message); break; case 3: vscode.window.showInformationMessage(message); break; default: console.assert("Unrecognized type for showMessageWindow"); break; } } function showWarning(params) { const message = util.getLocalizedString(params.localizeStringParams); let showChannel = false; if (!warningChannel) { warningChannel = vscode.window.createOutputChannel(`${localize(1, null)}`); workspaceDisposables.push(warningChannel); showChannel = true; } warningChannel.appendLine(`[${new Date().toLocaleString()}] ${message}`); if (showChannel) { warningChannel.show(true); } } function publishDiagnostics(params) { if (!diagnosticsCollection) { diagnosticsCollection = vscode.languages.createDiagnosticCollection("C/C++"); } const diagnostics = []; params.diagnostics.forEach((d) => { const message = util.getLocalizedString(d.localizeStringParams); const r = new vscode.Range(d.range.start.line, d.range.start.character, d.range.end.line, d.range.end.character); const diagnostic = new vscode.Diagnostic(r, message, d.severity); diagnostic.code = d.code; diagnostic.source = d.source; diagnostics.push(diagnostic); }); const realUri = vscode.Uri.parse(params.uri); diagnosticsCollection.set(realUri, diagnostics); clientCollection.timeTelemetryCollector.setUpdateRangeTime(realUri); } var SymbolScope; (function (SymbolScope) { SymbolScope[SymbolScope["Public"] = 0] = "Public"; SymbolScope[SymbolScope["Protected"] = 1] = "Protected"; SymbolScope[SymbolScope["Private"] = 2] = "Private"; })(SymbolScope = exports.SymbolScope || (exports.SymbolScope = {})); var FoldingRangeKind; (function (FoldingRangeKind) { FoldingRangeKind[FoldingRangeKind["None"] = 0] = "None"; FoldingRangeKind[FoldingRangeKind["Comment"] = 1] = "Comment"; FoldingRangeKind[FoldingRangeKind["Imports"] = 2] = "Imports"; FoldingRangeKind[FoldingRangeKind["Region"] = 3] = "Region"; })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {})); var SemanticTokenTypes; (function (SemanticTokenTypes) { SemanticTokenTypes[SemanticTokenTypes["macro"] = 0] = "macro"; SemanticTokenTypes[SemanticTokenTypes["enumMember"] = 1] = "enumMember"; SemanticTokenTypes[SemanticTokenTypes["variable"] = 2] = "variable"; SemanticTokenTypes[SemanticTokenTypes["parameter"] = 3] = "parameter"; SemanticTokenTypes[SemanticTokenTypes["type"] = 4] = "type"; SemanticTokenTypes[SemanticTokenTypes["referenceType"] = 5] = "referenceType"; SemanticTokenTypes[SemanticTokenTypes["valueType"] = 6] = "valueType"; SemanticTokenTypes[SemanticTokenTypes["function"] = 7] = "function"; SemanticTokenTypes[SemanticTokenTypes["method"] = 8] = "method"; SemanticTokenTypes[SemanticTokenTypes["property"] = 9] = "property"; SemanticTokenTypes[SemanticTokenTypes["cliProperty"] = 10] = "cliProperty"; SemanticTokenTypes[SemanticTokenTypes["event"] = 11] = "event"; SemanticTokenTypes[SemanticTokenTypes["genericType"] = 12] = "genericType"; SemanticTokenTypes[SemanticTokenTypes["templateFunction"] = 13] = "templateFunction"; SemanticTokenTypes[SemanticTokenTypes["templateType"] = 14] = "templateType"; SemanticTokenTypes[SemanticTokenTypes["namespace"] = 15] = "namespace"; SemanticTokenTypes[SemanticTokenTypes["label"] = 16] = "label"; SemanticTokenTypes[SemanticTokenTypes["customLiteral"] = 17] = "customLiteral"; SemanticTokenTypes[SemanticTokenTypes["numberLiteral"] = 18] = "numberLiteral"; SemanticTokenTypes[SemanticTokenTypes["stringLiteral"] = 19] = "stringLiteral"; SemanticTokenTypes[SemanticTokenTypes["operatorOverload"] = 20] = "operatorOverload"; SemanticTokenTypes[SemanticTokenTypes["memberOperatorOverload"] = 21] = "memberOperatorOverload"; SemanticTokenTypes[SemanticTokenTypes["newOperator"] = 22] = "newOperator"; })(SemanticTokenTypes || (SemanticTokenTypes = {})); var SemanticTokenModifiers; (function (SemanticTokenModifiers) { SemanticTokenModifiers[SemanticTokenModifiers["static"] = 1] = "static"; SemanticTokenModifiers[SemanticTokenModifiers["global"] = 2] = "global"; SemanticTokenModifiers[SemanticTokenModifiers["local"] = 4] = "local"; })(SemanticTokenModifiers || (SemanticTokenModifiers = {})); ; const QueryCompilerDefaultsRequest = new vscode_languageclient_1.RequestType('cpptools/queryCompilerDefaults'); const QueryTranslationUnitSourceRequest = new vscode_languageclient_1.RequestType('cpptools/queryTranslationUnitSource'); const SwitchHeaderSourceRequest = new vscode_languageclient_1.RequestType('cpptools/didSwitchHeaderSource'); const GetDiagnosticsRequest = new vscode_languageclient_1.RequestType('cpptools/getDiagnostics'); const GetCodeActionsRequest = new vscode_languageclient_1.RequestType('cpptools/getCodeActions'); exports.GetDocumentSymbolRequest = new vscode_languageclient_1.RequestType('cpptools/getDocumentSymbols'); exports.GetSymbolInfoRequest = new vscode_languageclient_1.RequestType('cpptools/getWorkspaceSymbols'); exports.GetFoldingRangesRequest = new vscode_languageclient_1.RequestType('cpptools/getFoldingRanges'); exports.GetSemanticTokensRequest = new vscode_languageclient_1.RequestType('cpptools/getSemanticTokens'); exports.FormatDocumentRequest = new vscode_languageclient_1.RequestType('cpptools/formatDocument'); exports.FormatRangeRequest = new vscode_languageclient_1.RequestType('cpptools/formatRange'); exports.FormatOnTypeRequest = new vscode_languageclient_1.RequestType('cpptools/formatOnType'); const GoToDirectiveInGroupRequest = new vscode_languageclient_1.RequestType('cpptools/goToDirectiveInGroup'); const DidOpenNotification = new vscode_languageclient_1.NotificationType('textDocument/didOpen'); const FileCreatedNotification = new vscode_languageclient_1.NotificationType('cpptools/fileCreated'); const FileChangedNotification = new vscode_languageclient_1.NotificationType('cpptools/fileChanged'); const FileDeletedNotification = new vscode_languageclient_1.NotificationType('cpptools/fileDeleted'); const ResetDatabaseNotification = new vscode_languageclient_1.NotificationType('cpptools/resetDatabase'); const PauseParsingNotification = new vscode_languageclient_1.NotificationType('cpptools/pauseParsing'); const ResumeParsingNotification = new vscode_languageclient_1.NotificationType('cpptools/resumeParsing'); const ActiveDocumentChangeNotification = new vscode_languageclient_1.NotificationType('cpptools/activeDocumentChange'); const TextEditorSelectionChangeNotification = new vscode_languageclient_1.NotificationType('cpptools/textEditorSelectionChange'); const ChangeCppPropertiesNotification = new vscode_languageclient_1.NotificationType('cpptools/didChangeCppProperties'); const ChangeCompileCommandsNotification = new vscode_languageclient_1.NotificationType('cpptools/didChangeCompileCommands'); const ChangeSelectedSettingNotification = new vscode_languageclient_1.NotificationType('cpptools/didChangeSelectedSetting'); const IntervalTimerNotification = new vscode_languageclient_1.NotificationType('cpptools/onIntervalTimer'); const CustomConfigurationNotification = new vscode_languageclient_1.NotificationType('cpptools/didChangeCustomConfiguration'); const CustomBrowseConfigurationNotification = new vscode_languageclient_1.NotificationType('cpptools/didChangeCustomBrowseConfiguration'); const ClearCustomConfigurationsNotification = new vscode_languageclient_1.NotificationType('cpptools/clearCustomConfigurations'); const ClearCustomBrowseConfigurationNotification = new vscode_languageclient_1.NotificationType('cpptools/clearCustomBrowseConfiguration'); const RescanFolderNotification = new vscode_languageclient_1.NotificationType('cpptools/rescanFolder'); exports.RequestReferencesNotification = new vscode_languageclient_1.NotificationType('cpptools/requestReferences'); exports.CancelReferencesNotification = new vscode_languageclient_1.NotificationType('cpptools/cancelReferences'); const FinishedRequestCustomConfig = new vscode_languageclient_1.NotificationType('cpptools/finishedRequestCustomConfig'); const FindAllReferencesNotification = new vscode_languageclient_1.NotificationType('cpptools/findAllReferences'); const RenameNotification = new vscode_languageclient_1.NotificationType('cpptools/rename'); const DidChangeSettingsNotification = new vscode_languageclient_1.NotificationType('cpptools/didChangeSettings'); const AbortRequestNotification = new vscode_languageclient_1.NotificationType('cpptools/abortRequest'); const ReloadWindowNotification = new vscode_languageclient_1.NotificationType('cpptools/reloadWindow'); const LogTelemetryNotification = new vscode_languageclient_1.NotificationType('cpptools/logTelemetry'); const ReportTagParseStatusNotification = new vscode_languageclient_1.NotificationType('cpptools/reportTagParseStatus'); const ReportStatusNotification = new vscode_languageclient_1.NotificationType('cpptools/reportStatus'); const DebugProtocolNotification = new vscode_languageclient_1.NotificationType('cpptools/debugProtocol'); const DebugLogNotification = new vscode_languageclient_1.NotificationType('cpptools/debugLog'); const InactiveRegionNotification = new vscode_languageclient_1.NotificationType('cpptools/inactiveRegions'); const CompileCommandsPathsNotification = new vscode_languageclient_1.NotificationType('cpptools/compileCommandsPaths'); const ReferencesNotification = new vscode_languageclient_1.NotificationType('cpptools/references'); const ReportReferencesProgressNotification = new vscode_languageclient_1.NotificationType('cpptools/reportReferencesProgress'); const RequestCustomConfig = new vscode_languageclient_1.NotificationType('cpptools/requestCustomConfig'); const PublishDiagnosticsNotification = new vscode_languageclient_1.NotificationType('cpptools/publishDiagnostics'); const ShowMessageWindowNotification = new vscode_languageclient_1.NotificationType('cpptools/showMessageWindow'); const ShowWarningNotification = new vscode_languageclient_1.NotificationType('cpptools/showWarning'); const ReportTextDocumentLanguage = new vscode_languageclient_1.NotificationType('cpptools/reportTextDocumentLanguage'); const SemanticTokensChanged = new vscode_languageclient_1.NotificationType('cpptools/semanticTokensChanged'); const IntelliSenseSetupNotification = new vscode_languageclient_1.NotificationType('cpptools/IntelliSenseSetup'); const SetTemporaryTextDocumentLanguageNotification = new vscode_languageclient_1.NotificationType('cpptools/setTemporaryTextDocumentLanguage'); let failureMessageShown = false; class ClientModel { constructor() { this.isTagParsing = new dataBinding_1.DataBinding(false); this.isUpdatingIntelliSense = new dataBinding_1.DataBinding(false); this.referencesCommandMode = new dataBinding_1.DataBinding(refs.ReferencesCommandMode.None); this.tagParserStatus = new dataBinding_1.DataBinding(""); this.activeConfigName = new dataBinding_1.DataBinding(""); } activate() { this.isTagParsing.activate(); this.isUpdatingIntelliSense.activate(); this.referencesCommandMode.activate(); this.tagParserStatus.activate(); this.activeConfigName.activate(); } deactivate() { this.isTagParsing.deactivate(); this.isUpdatingIntelliSense.deactivate(); this.referencesCommandMode.deactivate(); this.tagParserStatus.deactivate(); this.activeConfigName.deactivate(); } dispose() { this.isTagParsing.dispose(); this.isUpdatingIntelliSense.dispose(); this.referencesCommandMode.dispose(); this.tagParserStatus.dispose(); this.activeConfigName.dispose(); } } function createClient(allClients, workspaceFolder) { return new DefaultClient(allClients, workspaceFolder); } exports.createClient = createClient; function createNullClient() { return new NullClient(); } exports.createNullClient = createNullClient; class DefaultClient { constructor(allClients, workspaceFolder) { var _a; this.disposables = []; this.trackedDocuments = new Set(); this.isSupported = true; this.inactiveRegionsDecorations = new Map(); this.documentSelector = [ { scheme: 'file', language: 'c' }, { scheme: 'file', language: 'cpp' }, { scheme: 'file', language: 'cuda-cpp' } ]; this.model = new ClientModel(); this.registeredProviders = []; this.doneInitialCustomBrowseConfigurationCheck = false; this.browseConfigurationLogging = ""; this.configurationLogging = new Map(); this.rootFolder = workspaceFolder; this.rootRealPath = this.RootPath ? (fs.existsSync(this.RootPath) ? fs.realpathSync(this.RootPath) : this.RootPath) : ""; let storagePath; if (util.extensionContext) { const path = (_a = util.extensionContext.storageUri) === null || _a === void 0 ? void 0 : _a.fsPath; if (path) { storagePath = path; } } if (!storagePath) { storagePath = this.RootPath ? path.join(this.RootPath, "/.vscode") : ""; } if (workspaceFolder && vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) { storagePath = path.join(storagePath, util.getUniqueWorkspaceStorageName(workspaceFolder)); } this.storagePath = storagePath; const rootUri = this.RootUri; this.settingsTracker = settingsTracker_1.getTracker(rootUri); try { let firstClient = false; if (!languageClient || languageClientCrashedNeedsRestart) { if (languageClientCrashedNeedsRestart) { languageClientCrashedNeedsRestart = false; } languageClient = this.createLanguageClient(allClients); clientCollection = allClients; languageClient.registerProposedFeatures(); languageClient.start(); util.setProgress(util.getProgressExecutableStarted()); firstClient = true; } ui = ui_1.getUI(); ui.bind(this); this.queueBlockingTask(() => __awaiter(this, void 0, void 0, function* () { yield languageClient.onReady(); try { const workspaceFolder = this.rootFolder; this.innerConfiguration = new configs.CppProperties(rootUri, workspaceFolder); this.innerConfiguration.ConfigurationsChanged((e) => this.onConfigurationsChanged(e)); this.innerConfiguration.SelectionChanged((e) => this.onSelectedConfigurationChanged(e)); this.innerConfiguration.CompileCommandsChanged((e) => this.onCompileCommandsChanged(e)); this.disposables.push(this.innerConfiguration); this.innerLanguageClient = languageClient; telemetry.logLanguageServerEvent("NonDefaultInitialCppSettings", this.settingsTracker.getUserModifiedSettings()); failureMessageShown = false; class CodeActionProvider { constructor(client) { this.client = client; } provideCodeActions(document, range, context, token) { return __awaiter(this, void 0, void 0, function* () { return this.client.requestWhenReady(() => __awaiter(this, void 0, void 0, function* () { let r; if (range instanceof vscode.Selection) { if (range.active.isBefore(range.anchor)) { r = vscode_languageclient_1.Range.create(vscode_languageclient_1.Position.create(range.active.line, range.active.character), vscode_languageclient_1.Position.create(range.anchor.line, range.anchor.character)); } else { r = vscode_languageclient_1.Range.create(vscode_languageclient_1.Position.create(range.anchor.line, range.anchor.character), vscode_languageclient_1.Position.create(range.active.line, range.active.character)); } } else { r = vscode_languageclient_1.Range.create(vscode_languageclient_1.Position.create(range.start.line, range.start.character), vscode_languageclient_1.Position.create(range.end.line, range.end.character)); } const params = { range: r, uri: document.uri.toString() }; const commands = yield this.client.languageClient.sendRequest(GetCodeActionsRequest, params); const resultCodeActions = []; commands.forEach((command) => { const title = util.getLocalizedString(command.localizeStringParams); let edit; if (command.edit) { edit = new vscode.WorkspaceEdit(); edit.replace(document.uri, new vscode.Range(new vscode.Position(command.edit.range.start.line, command.edit.range.start.character), new vscode.Position(command.edit.range.end.line, command.edit.range.end.character)), command.edit.newText); } const vscodeCodeAction = { title: title, command: command.command === "edit" ? undefined : { title: title, command: command.command, arguments: command.arguments }, edit: edit, kind: edit === undefined ? vscode.CodeActionKind.QuickFix : vscode.CodeActionKind.RefactorInline }; resultCodeActions.push(vscodeCodeAction); }); return resultCodeActions; })); }); } } const tokenTypesLegend = []; for (const e in SemanticTokenTypes) { if (isNaN(Number(e))) { tokenTypesLegend.push(e); } } const tokenModifiersLegend = []; for (const e in SemanticTokenModifiers) { if (isNaN(Number(e))) { tokenModifiersLegend.push(e); } } this.semanticTokensLegend = new vscode.SemanticTokensLegend(tokenTypesLegend, tokenModifiersLegend); if (firstClient) { exports.workspaceReferences = new refs.ReferencesManager(this); const inputCompilerDefaults = yield languageClient.sendRequest(QueryCompilerDefaultsRequest, {}); compilerDefaults = inputCompilerDefaults; this.configuration.CompilerDefaults = compilerDefaults; extension_1.registerCommands(); this.registerFileWatcher(); this.disposables.push(vscode.languages.registerRenameProvider(this.documentSelector, new renameProvider_1.RenameProvider(this))); this.disposables.push(vscode.languages.registerReferenceProvider(this.documentSelector, new findAllReferencesProvider_1.FindAllReferencesProvider(this))); this.disposables.push(vscode.languages.registerWorkspaceSymbolProvider(new workspaceSymbolProvider_1.WorkspaceSymbolProvider(this))); this.disposables.push(vscode.languages.registerDocumentSymbolProvider(this.documentSelector, new documentSymbolProvider_1.DocumentSymbolProvider(this), undefined)); this.disposables.push(vscode.languages.registerCodeActionsProvider(this.documentSelector, new CodeActionProvider(this), undefined)); const settings = new settings_1.CppSettings(); if (settings.formattingEngine !== "Disabled") { this.documentFormattingProviderDisposable = vscode.languages.registerDocumentFormattingEditProvider(this.documentSelector, new documentFormattingEditProvider_1.DocumentFormattingEditProvider(this)); this.formattingRangeProviderDisposable = vscode.languages.registerDocumentRangeFormattingEditProvider(this.documentSelector, new documentRangeFormattingEditProvider_1.DocumentRangeFormattingEditProvider(this)); this.onTypeFormattingProviderDisposable = vscode.languages.registerOnTypeFormattingEditProvider(this.documentSelector, new onTypeFormattingEditProvider_1.OnTypeFormattingEditProvider(this), ";", "}", "\n"); } if (settings.codeFolding) { this.codeFoldingProvider = new foldingRangeProvider_1.FoldingRangeProvider(this); this.codeFoldingProviderDisposable = vscode.languages.registerFoldingRangeProvider(this.documentSelector, this.codeFoldingProvider); } if (settings.enhancedColorization && this.semanticTokensLegend) { this.semanticTokensProvider = new semanticTokensProvider_1.SemanticTokensProvider(this); this.semanticTokensProviderDisposable = vscode.languages.registerDocumentSemanticTokensProvider(this.documentSelector, this.semanticTokensProvider, this.semanticTokensLegend); } this.registerNotifications(); } else { this.configuration.CompilerDefaults = compilerDefaults; } } catch (err) { this.isSupported = false; if (!failureMessageShown) { failureMessageShown = true; vscode.window.showErrorMessage(localize(2, null, String(err))); } } })); } catch (err) { this.isSupported = false; if (!failureMessageShown) { failureMessageShown = true; let additionalInfo; if (err.code === "EPERM") { additionalInfo = localize(3, null, getLanguageServerFileName()); } else { additionalInfo = String(err); } vscode.window.showErrorMessage(localize(4, null, additionalInfo)); } } } get TagParsingChanged() { return this.model.isTagParsing.ValueChanged; } get IntelliSenseParsingChanged() { return this.model.isUpdatingIntelliSense.ValueChanged; } get ReferencesCommandModeChanged() { return this.model.referencesCommandMode.ValueChanged; } get TagParserStatusChanged() { return this.model.tagParserStatus.ValueChanged; } get ActiveConfigChanged() { return this.model.activeConfigName.ValueChanged; } get RootPath() { return (this.rootFolder) ? this.rootFolder.uri.fsPath : ""; } get RootRealPath() { return this.rootRealPath; } get RootUri() { return (this.rootFolder) ? this.rootFolder.uri : undefined; } get RootFolder() { return this.rootFolder; } get Name() { return this.getName(this.rootFolder); } get TrackedDocuments() { return this.trackedDocuments; } get IsTagParsing() { return this.model.isTagParsing.Value; } get ReferencesCommandMode() { return this.model.referencesCommandMode.Value; } get languageClient() { if (!this.innerLanguageClient) { throw new Error("Attempting to use languageClient before initialized"); } return this.innerLanguageClient; } get configuration() { if (!this.innerConfiguration) { throw new Error("Attempting to use configuration before initialized"); } return this.innerConfiguration; } get AdditionalEnvironment() { return { workspaceFolderBasename: this.Name, workspaceStorage: this.storagePath }; } getName(workspaceFolder) { return workspaceFolder ? workspaceFolder.name : "untitled"; } sendFindAllReferencesNotification(params) { this.languageClient.sendNotification(FindAllReferencesNotification, params); } sendRenameNofication(params) { this.languageClient.sendNotification(RenameNotification, params); } createLanguageClient(allClients) { const serverModule = getLanguageServerFileName(); const exeExists = fs.existsSync(serverModule); if (!exeExists) { telemetry.logLanguageServerEvent("missingLanguageServerBinary"); throw String('Missing binary at ' + serverModule); } const serverName = this.getName(this.rootFolder); const serverOptions = { run: { command: serverModule }, debug: { command: serverModule, args: [serverName] } }; const settings_clangFormatPath = []; const settings_clangFormatStyle = []; const settings_clangFormatFallbackStyle = []; const settings_clangFormatSortIncludes = []; const settings_filesEncoding = []; const settings_cppFilesExclude = []; const settings_filesExclude = []; const settings_searchExclude = []; const settings_editorAutoClosingBrackets = []; const settings_intelliSenseEngine = []; const settings_intelliSenseEngineFallback = []; const settings_errorSquiggles = []; const settings_dimInactiveRegions = []; const settings_enhancedColorization = []; const settings_suggestSnippets = []; const settings_exclusionPolicy = []; const settings_preferredPathSeparator = []; const settings_defaultSystemIncludePath = []; const settings_intelliSenseCachePath = []; const settings_intelliSenseCacheSize = []; const settings_intelliSenseMemoryLimit = []; const settings_autocomplete = []; const settings_autocompleteAddParentheses = []; const workspaceSettings = new settings_1.CppSettings(); const workspaceOtherSettings = new settings_1.OtherSettings(); const settings_indentBraces = []; const settings_indentMultiLine = []; const settings_indentWithinParentheses = []; const settings_indentPreserveWithinParentheses = []; const settings_indentCaseLabels = []; const settings_indentCaseContents = []; const settings_indentCaseContentsWhenBlock = []; const settings_indentLambdaBracesWhenParameter = []; const settings_indentGotoLabels = []; const settings_indentPreprocessor = []; const settings_indentAccessSpecifiers = []; const settings_indentNamespaceContents = []; const settings_indentPreserveComments = []; const settings_formattingEngine = []; const settings_newLineBeforeOpenBraceNamespace = []; const settings_newLineBeforeOpenBraceType = []; const settings_newLineBeforeOpenBraceFunction = []; const settings_newLineBeforeOpenBraceBlock = []; const settings_newLineBeforeOpenBraceLambda = []; const settings_newLineScopeBracesOnSeparateLines = []; const settings_newLineCloseBraceSameLineEmptyType = []; const settings_newLineCloseBraceSameLineEmptyFunction = []; const settings_newLineBeforeCatch = []; const settings_newLineBeforeElse = []; const settings_newLineBeforeWhileInDoWhile = []; const settings_spaceBeforeFunctionOpenParenthesis = []; const settings_spaceWithinParameterListParentheses = []; const settings_spaceBetweenEmptyParameterListParentheses = []; const settings_spaceAfterKeywordsInControlFlowStatements = []; const settings_spaceWithinControlFlowStatementParentheses = []; const settings_spaceBeforeLambdaOpenParenthesis = []; const settings_spaceWithinCastParentheses = []; const settings_spaceSpaceAfterCastCloseParenthesis = []; const settings_spaceWithinExpressionParentheses = []; const settings_spaceBeforeBlockOpenBrace = []; const settings_spaceBetweenEmptyBraces = []; const settings_spaceBeforeInitializerListOpenBrace = []; const settings_spaceWithinInitializerListBraces = []; const settings_spacePreserveInInitializerList = []; const settings_spaceBeforeOpenSquareBracket = []; const settings_spaceWithinSquareBrackets = []; const settings_spaceBeforeEmptySquareBrackets = []; const settings_spaceBetweenEmptySquareBrackets = []; const settings_spaceGroupSquareBrackets = []; const settings_spaceWithinLambdaBrackets = []; const settings_spaceBetweenEmptyLambdaBrackets = []; const settings_spaceBeforeComma = []; const settings_spaceAfterComma = []; const settings_spaceRemoveAroundMemberOperators = []; const settings_spaceBeforeInheritanceColon = []; const settings_spaceBeforeConstructorColon = []; const settings_spaceRemoveBeforeSemicolon = []; const settings_spaceInsertAfterSemicolon = []; const settings_spaceRemoveAroundUnaryOperator = []; const settings_spaceAroundBinaryOperator = []; const settings_spaceAroundAssignmentOperator = []; const settings_spacePointerReferenceAlignment = []; const settings_spaceAroundTernaryOperator = []; const settings_wrapPreserveBlocks = []; { const settings = []; const otherSettings = []; if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) { for (const workspaceFolder of vscode.workspace.workspaceFolders) { settings.push(new settings_1.CppSettings(workspaceFolder.uri)); otherSettings.push(new settings_1.OtherSettings(workspaceFolder.uri)); } } else { settings.push(workspaceSettings); otherSettings.push(workspaceOtherSettings); } for (const setting of settings) { settings_clangFormatPath.push(util.resolveVariables(setting.clangFormatPath, this.AdditionalEnvironment)); settings_formattingEngine.push(setting.formattingEngine); settings_indentBraces.push(setting.vcFormatIndentBraces); settings_indentWithinParentheses.push(setting.vcFormatIndentWithinParentheses); settings_indentPreserveWithinParentheses.push(setting.vcFormatIndentPreserveWithinParentheses); settings_indentMultiLine.push(setting.vcFormatIndentMultiLineRelativeTo); settings_indentCaseLabels.push(setting.vcFormatIndentCaseLabels); settings_indentCaseContents.push(setting.vcFormatIndentCaseContents); settings_indentCaseContentsWhenBlock.push(setting.vcFormatIndentCaseContentsWhenBlock); settings_indentLambdaBracesWhenParameter.push(setting.vcFormatIndentLambdaBracesWhenParameter); settings_indentGotoLabels.push(setting.vcFormatIndentGotoLables); settings_indentPreprocessor.push(setting.vcFormatIndentPreprocessor); settings_indentAccessSpecifiers.push(setting.vcFormatIndentAccessSpecifiers); settings_indentNamespaceContents.push(setting.vcFormatIndentNamespaceContents); settings_indentPreserveComments.push(setting.vcFormatIndentPreserveComments); settings_newLineBeforeOpenBraceNamespace.push(setting.vcFormatNewlineBeforeOpenBraceNamespace); settings_newLineBeforeOpenBraceType.push(setting.vcFormatNewlineBeforeOpenBraceType); settings_newLineBeforeOpenBraceFunction.push(setting.vcFormatNewlineBeforeOpenBraceFunction); settings_newLineBeforeOpenBraceBlock.push(setting.vcFormatNewlineBeforeOpenBraceBlock); settings_newLineScopeBracesOnSeparateLines.push(setting.vcFormatNewlineScopeBracesOnSeparateLines); settings_newLineBeforeOpenBraceLambda.push(setting.vcFormatNewlineBeforeOpenBraceLambda); settings_newLineCloseBraceSameLineEmptyType.push(setting.vcFormatNewlineCloseBraceSameLineEmptyType); settings_newLineCloseBraceSameLineEmptyFunction.push(setting.vcFormatNewlineCloseBraceSameLineEmptyFunction); settings_newLineBeforeCatch.push(setting.vcFormatNewlineBeforeCatch); settings_newLineBeforeElse.push(setting.vcFormatNewlineBeforeElse); settings_newLineBeforeWhileInDoWhile.push(setting.vcFormatNewlineBeforeWhileInDoWhile); settings_spaceBeforeFunctionOpenParenthesis.push(setting.vcFormatSpaceBeforeFunctionOpenParenthesis); settings_spaceWithinParameterListParentheses.push(setting.vcFormatSpaceWithinParameterListParentheses); settings_spaceBetweenEmptyParameterListParentheses.push(setting.vcFormatSpaceBetweenEmptyParameterListParentheses); settings_spaceAfterKeywordsInControlFlowStatements.push(setting.vcFormatSpaceAfterKeywordsInControlFlowStatements); settings_spaceWithinControlFlowStatementParentheses.push(setting.vcFormatSpaceWithinControlFlowStatementParentheses); settings_spaceBeforeLambdaOpenParenthesis.push(setting.vcFormatSpaceBeforeLambdaOpenParenthesis); settings_spaceWithinCastParentheses.push(setting.vcFormatSpaceWithinCastParentheses); settings_spaceSpaceAfterCastCloseParenthesis.push(setting.vcFormatSpaceAfterCastCloseParenthesis); settings_spaceWithinExpressionParentheses.push(setting.vcFormatSpaceWithinExpressionParentheses); settings_spaceBeforeBlockOpenBrace.push(setting.vcFormatSpaceBeforeBlockOpenBrace); settings_spaceBetweenEmptyBraces.push(setting.vcFormatSpaceBetweenEmptyBraces); settings_spaceBeforeInitializerListOpenBrace.push(setting.vcFormatSpaceBeforeInitializerListOpenBrace); settings_spaceWithinInitializerListBraces.push(setting.vcFormatSpaceWithinInitializerListBraces); settings_spacePreserveInInitializerList.push(setting.vcFormatSpacePreserveInInitializerList); settings_spaceBeforeOpenSquareBracket.push(setting.vcFormatSpaceBeforeOpenSquareBracket); settings_spaceWithinSquareBrackets.push(setting.vcFormatSpaceWithinSquareBrackets); settings_spaceBeforeEmptySquareBrackets.push(setting.vcFormatSpaceBeforeEmptySquareBrackets); settings_spaceBetweenEmptySquareBrackets.push(setting.vcFormatSpaceBetweenEmptySquareBrackets); settings_spaceGroupSquareBrackets.push(setting.vcFormatSpaceGroupSquareBrackets); settings_spaceWithinLambdaBrackets.push(setting.vcFormatSpaceWithinLambdaBrackets); settings_spaceBetweenEmptyLambdaBrackets.push(setting.vcFormatSpaceBetweenEmptyLambdaBrackets); settings_spaceBeforeComma.push(setting.vcFormatSpaceBeforeComma); settings_spaceAfterComma.push(setting.vcFormatSpaceAfterComma); settings_spaceRemoveAroundMemberOperators.push(setting.vcFormatSpaceRemoveAroundMemberOperators); settings_spaceBeforeInheritanceColon.push(setting.vcFormatSpaceBeforeInheritanceColon); settings_spaceBeforeConstructorColon.push(setting.vcFormatSpaceBeforeConstructorColon); settings_spaceRemoveBeforeSemicolon.push(setting.vcFormatSpaceRemoveBeforeSemicolon); settings_spaceInsertAfterSemicolon.push(setting.vcFormatSpaceInsertAfterSemicolon); settings_spaceRemoveAroundUnaryOperator.push(setting.vcFormatSpaceRemoveAroundUnaryOperator); settings_spaceAroundBinaryOperator.push(setting.vcFormatSpaceAroundBinaryOperator); settings_spaceAroundAssignmentOperator.push(setting.vcFormatSpaceAroundAssignmentOperator); settings_spacePointerReferenceAlignment.push(setting.vcFormatSpacePointerReferenceAlignment); settings_spaceAroundTernaryOperator.push(setting.vcFormatSpaceAroundTernaryOperator); settings_wrapPreserveBlocks.push(setting.vcFormatWrapPreserveBlocks); settings_clangFormatStyle.push(setting.clangFormatStyle); settings_clangFormatFallbackStyle.push(setting.clangFormatFallbackStyle); settings_clangFormatSortIncludes.push(setting.clangFormatSortIncludes); settings_intelliSenseEngine.push(setting.intelliSenseEngine); settings_intelliSenseEngineFallback.push(setting.intelliSenseEngineFallback); settings_errorSquiggles.push(setting.errorSquiggles); settings_dimInactiveRegions.push(setting.dimInactiveRegions); settings_enhancedColorization.push(setting.enhancedColorization ? "Enabled" : "Disabled"); settings_suggestSnippets.push(setting.suggestSnippets); settings_exclusionPolicy.push(setting.exclusionPolicy); settings_preferredPathSeparator.push(setting.preferredPathSeparator); settings_defaultSystemIncludePath.push(setting.defaultSystemIncludePath); settings_intelliSenseCachePath.push(util.resolveCachePath(setting.intelliSenseCachePath, this.AdditionalEnvironment)); settings_intelliSenseCacheSize.push(setting.intelliSenseCacheSize); settings_intelliSenseMemoryLimit.push(setting.intelliSenseMemoryLimit); settings_autocomplete.push(setting.autocomplete); settings_autocompleteAddParentheses.push(setting.autocompleteAddParentheses); settings_cppFilesExclude.push(setting.filesExclude); } for (const otherSetting of otherSettings) { settings_filesEncoding.push(otherSetting.filesEncoding); settings_filesExclude.push(otherSetting.filesExclude); settings_searchExclude.push(otherSetting.searchExclude); settings_editorAutoClosingBrackets.push(otherSetting.editorAutoClosingBrackets); } } let intelliSenseCacheDisabled = false; if (os.platform() === "darwin") { const releaseParts = os.release().split("."); if (releaseParts.length >= 1) { intelliSenseCacheDisabled = parseInt(releaseParts[0]) < 17; } } const localizedStrings = []; for (let i = 0; i < nativeStrings_1.localizedStringCount; i++) { localizedStrings.push(nativeStrings_1.lookupString(i)); } const clientOptions = { documentSelector: [ { scheme: 'file', language: 'c' }, { scheme: 'file', language: 'cpp' }, { scheme: 'file', language: 'cuda-cpp' } ], initializationOptions: { clang_format_path: settings_clangFormatPath, clang_format_style: settings_clangFormatStyle, formatting: settings_formattingEngine, vcFormat: { indent: { braces: settings_indentBraces, multiLineRelativeTo: settings_indentMultiLine, withinParentheses: settings_indentWithinParentheses, preserveWithinParentheses: settings_indentPreserveWithinParentheses, caseLabels: settings_indentCaseLabels, caseContents: settings_indentCaseContents, caseContentsWhenBlock: settings_indentCaseContentsWhenBlock, lambdaBracesWhenParameter: settings_indentLambdaBracesWhenParameter, gotoLabels: settings_indentGotoLabels, preprocessor: settings_indentPreprocessor, accesSpecifiers: settings_indentAccessSpecifiers, namespaceContents: settings_indentNamespaceContents, preserveComments: settings_indentPreserveComments }, newLine: { beforeOpenBrace: { namespace: settings_newLineBeforeOpenBraceNamespace, type: settings_newLineBeforeOpenBraceType, function: settings_newLineBeforeOpenBraceFunction, block: settings_newLineBeforeOpenBraceBlock, lambda: settings_newLineBeforeOpenBraceLambda }, scopeBracesOnSeparateLines: settings_newLineScopeBracesOnSeparateLines, closeBraceSameLine: { emptyType: settings_newLineCloseBraceSameLineEmptyType, emptyFunction: settings_newLineCloseBraceSameLineEmptyFunction }, beforeCatch: settings_newLineBeforeCatch, beforeElse: settings_newLineBeforeElse, beforeWhileInDoWhile: settings_newLineBeforeWhileInDoWhile }, space: { beforeFunctionOpenParenthesis: settings_spaceBeforeFunctionOpenParenthesis, withinParameterListParentheses: settings_spaceWithinParameterListParentheses, betweenEmptyParameterListParentheses: settings_spaceBetweenEmptyParameterListParentheses, afterKeywordsInControlFlowStatements: settings_spaceAfterKeywordsInControlFlowStatements, withinControlFlowStatementParentheses: settings_spaceWithinControlFlowStatementParentheses, beforeLambdaOpenParenthesis: settings_spaceBeforeLambdaOpenParenthesis, withinCastParentheses: settings_spaceWithinCastParentheses, afterCastCloseParenthesis: settings_spaceSpaceAfterCastCloseParenthesis, withinExpressionParentheses: settings_spaceWithinExpressionParentheses, beforeBlockOpenBrace: settings_spaceBeforeBlockOpenBrace, betweenEmptyBraces: settings_spaceBetweenEmptyBraces, beforeInitializerListOpenBrace: settings_spaceBeforeInitializerListOpenBrace, withinInitializerListBraces: settings_spaceWithinInitializerListBraces, preserveInInitializerList: settings_spacePreserveInInitializerList, beforeOpenSquareBracket: settings_spaceBeforeOpenSquareBracket, withinSquareBrackets: settings_spaceWithinSquareBrackets, beforeEmptySquareBrackets: settings_spaceBeforeEmptySquareBrackets, betweenEmptySquareBrackets: settings_spaceBetweenEmptySquareBrackets, groupSquareBrackets: settings_spaceGroupSquareBrackets, withinLambdaBrackets: settings_spaceWithinLambdaBrackets, betweenEmptyLambdaBrackets: settings_spaceBetweenEmptyLambdaBrackets, beforeComma: settings_spaceBeforeComma, afterComma: settings_spaceAfterComma, removeAroundMemberOperators: settings_spaceRemoveAroundMemberOperators, beforeInheritanceColon: settings_spaceBeforeInheritanceColon, beforeConstructorColon: settings_spaceBeforeConstructorColon, removeBeforeSemicolon: settings_spaceRemoveBeforeSemicolon, insertAfterSemicolon: settings_spaceInsertAfterSemicolon, removeAroundUnaryOperator: settings_spaceRemoveAroundUnaryOperator, aroundBinaryOperator: settings_spaceAroundBinaryOperator, aroundAssignmentOperator: settings_spaceAroundAssignmentOperator, pointerReferenceAlignment: settings_spacePointerReferenceAlignment, aroundTernaryOperator: settings_spaceAroundTernaryOperator }, wrap: { preserveBlocks: settings_wrapPreserveBlocks } }, clang_format_fallbackStyle: settings_clangFormatFallbackStyle, clang_format_sortIncludes: settings_clangFormatSortIncludes, extension_path: util.extensionPath, files: { encoding: settings_filesEncoding }, editor: { autoClosingBrackets: settings_editorAutoClosingBrackets }, workspace_fallback_encoding: workspaceOtherSettings.filesEncoding, cpp_exclude_files: settings_cppFilesExclude, exclude_files: settings_filesExclude, exclude_search: settings_searchExclude, associations: workspaceOtherSettings.filesAssociations, storage_path: this.storagePath, intelliSenseEngine: settings_intelliSenseEngine, intelliSenseEngineFallback: settings_intelliSenseEngineFallback, intelliSenseCacheDisabled: intelliSenseCacheDisabled, intelliSenseCachePath: settings_intelliSenseCachePath, intelliSenseCacheSize: settings_intelliSenseCacheSize, intelliSenseMemoryLimit: settings_intelliSenseMemoryLimit, intelliSenseUpdateDelay: workspaceSettings.intelliSenseUpdateDelay, autocomplete: settings_autocomplete, autocompleteAddParentheses: settings_autocompleteAddParentheses, errorSquiggles: settings_errorSquiggles, dimInactiveRegions: settings_dimInactiveRegions, enhancedColorization: settings_enhancedColorization, suggestSnippets: settings_suggestSnippets, simplifyStructuredComments: workspaceSettings.simplifyStructuredComments, loggingLevel: workspaceSettings.loggingLevel, workspaceParsingPriority: workspaceSettings.workspaceParsingPriority, workspaceSymbols: workspaceSettings.workspaceSymbols, exclusionPolicy: settings_exclusionPolicy, preferredPathSeparator: settings_preferredPathSeparator, default: { systemIncludePath: settings_defaultSystemIncludePath }, vcpkg_root: util.getVcpkgRoot(), experimentalFeatures: workspaceSettings.experimentalFeatures, edgeMessagesDirectory: path.join(util.getExtensionFilePath("bin"), "messages", util.getLocaleId()), localizedStrings: localizedStrings, supportCuda: util.supportCuda, packageVersion: util.packageJson.version }, middleware: protocolFilter_1.createProtocolFilter(allClients), errorHandler: { error: () => vscode_languageclient_1.ErrorAction.Continue, closed: () => { languageClientCrashTimes.push(Date.now()); languageClientCrashedNeedsRestart = true; telemetry.logLanguageServerEvent("languageClientCrash"); if (languageClientCrashTimes.length < 5) { allClients.forEach(client => { allClients.replace(client, true); }); } else { const elapsed = languageClientCrashTimes[languageClientCrashTimes.length - 1] - languageClientCrashTimes[0]; if (elapsed <= 3 * 60 * 1000) { vscode.window.showErrorMessage(localize(5, null)); allClients.forEach(client => { allClients.replace(client, false); }); } else { languageClientCrashTimes.shift(); allClients.forEach(client => { allClients.replace(client, true); }); } } return vscode_languageclient_1.CloseAction.DoNotRestart; } } }; return new vscode_languageclient_1.LanguageClient(`cpptools`, serverOptions, clientOptions); } sendAllSettings() { const cppSettingsScoped = {}; { const cppSettingsResourceScoped = vscode.workspace.getConfiguration("C_Cpp", this.RootUri); const cppSettingsNonScoped = vscode.workspace.getConfiguration("C_Cpp"); for (const key in cppSettingsResourceScoped) { const curSetting = util.packageJson.contributes.configuration.properties["C_Cpp." + key]; if (curSetting === undefined) { continue; } const settings = (curSetting.scope === "resource" || curSetting.scope === "machine-overridable") ? cppSettingsResourceScoped : cppSettingsNonScoped; cppSettingsScoped[key] = settings.get(key); } cppSettingsScoped["default"] = { systemIncludePath: cppSettingsResourceScoped.get("default.systemIncludePath") }; } const otherSettingsFolder = new settings_1.OtherSettings(this.RootUri); const otherSettingsWorkspace = new settings_1.OtherSettings(); const settings = { C_Cpp: Object.assign(Object.assign({}, cppSettingsScoped), { files: { exclude: vscode.workspace.getConfiguration("C_Cpp.files.exclude", this.RootUri) }, vcFormat: Object.assign(Object.assign({}, vscode.workspace.getConfiguration("C_Cpp.vcFormat", this.RootUri)), { indent: vscode.workspace.getConfiguration("C_Cpp.vcFormat.indent", this.RootUri), newLine: Object.assign(Object.assign({}, vscode.workspace.getConfiguration("C_Cpp.vcFormat.newLine", this.RootUri)), { beforeOpenBrace: vscode.workspace.getConfiguration("C_Cpp.vcFormat.newLine.beforeOpenBrace", this.RootUri), closeBraceSameLine: vscode.workspace.getConfiguration("C_Cpp.vcFormat.newLine.closeBraceSameLine", this.RootUri) }), space: vscode.workspace.getConfiguration("C_Cpp.vcFormat.space", this.RootUri), wrap: vscode.workspace.getConfiguration("C_Cpp.vcFormat.wrap", this.RootUri) }) }), editor: { autoClosingBrackets: otherSettingsFolder.editorAutoClosingBrackets }, files: { encoding: otherSettingsFolder.filesEncoding, exclude: vscode.workspace.getConfiguration("files.exclude", this.RootUri), associations: new settings_1.OtherSettings().filesAssociations }, workspace_fallback_encoding: otherSettingsWorkspace.filesEncoding, search: { exclude: vscode.workspace.getConfiguration("search.exclude", this.RootUri) } }; this.sendDidChangeSettings(settings); } sendDidChangeSettings(settings) { this.notifyWhenLanguageClientReady(() => { this.languageClient.sendNotification(DidChangeSettingsNotification, { settings, workspaceFolderUri: this.RootPath }); }); } onDidChangeSettings(event, isFirstClient) { this.sendAllSettings(); const changedSettings = this.settingsTracker.getChangedSettings(); this.notifyWhenLanguageClientReady(() => { if (Object.keys(changedSettings).length > 0) { if (isFirstClient) { if (changedSettings["commentContinuationPatterns"]) { extension_1.updateLanguageConfigurations(); } const settings = new settings_1.CppSettings(); if (changedSettings["formatting"]) { if (settings.formattingEngine !== "Disabled") { if (!this.documentFormattingProviderDisposable) { this.documentFormattingProviderDisposable = vscode.languages.registerDocumentFormattingEditProvider(this.documentSelector, new documentFormattingEditProvider_1.DocumentFormattingEditProvider(this)); } if (!this.formattingRangeProviderDisposable) { this.formattingRangeProviderDisposable = vscode.languages.registerDocumentRangeFormattingEditProvider(this.documentSelector, new documentRangeFormattingEditProvider_1.DocumentRangeFormattingEditProvider(this)); } if (!this.onTypeFormattingProviderDisposable) { this.onTypeFormattingProviderDisposable = vscode.languages.registerOnTypeFormattingEditProvider(this.documentSelector, new onTypeFormattingEditProvider_1.OnTypeFormattingEditProvider(this), ";", "}", "\n"); } } else { if (this.documentFormattingProviderDisposable) { this.documentFormattingProviderDisposable.dispose(); this.documentFormattingProviderDisposable = undefined; } if (this.formattingRangeProviderDisposable) { this.formattingRangeProviderDisposable.dispose(); this.formattingRangeProviderDisposable = undefined; } if (this.onTypeFormattingProviderDisposable) { this.onTypeFormattingProviderDisposable.dispose(); this.onTypeFormattingProviderDisposable = undefined; } } } if (changedSettings["codeFolding"]) { if (settings.codeFolding) { this.codeFoldingProvider = new foldingRangeProvider_1.FoldingRangeProvider(this); this.codeFoldingProviderDisposable = vscode.languages.registerFoldingRangeProvider(this.documentSelector, this.codeFoldingProvider); } else if (this.codeFoldingProviderDisposable) { this.codeFoldingProviderDisposable.dispose(); this.codeFoldingProviderDisposable = undefined; this.codeFoldingProvider = undefined; } } if (changedSettings["enhancedColorization"]) { if (settings.enhancedColorization && this.semanticTokensLegend) { this.semanticTokensProvider = new semanticTokensProvider_1.SemanticTokensProvider(this); this.semanticTokensProviderDisposable = vscode.languages.registerDocumentSemanticTokensProvider(this.documentSelector, this.semanticTokensProvider, this.semanticTokensLegend); } else if (this.semanticTokensProviderDisposable) { this.semanticTokensProviderDisposable.dispose(); this.semanticTokensProviderDisposable = undefined; this.semanticTokensProvider = undefined; } } if (changedSettings["addNodeAddonIncludePaths"] && settings.addNodeAddonIncludePaths && this.configuration.nodeAddonIncludesFound() === 0) { util.promptForReloadWindowDueToSettingsChange(); } } this.configuration.onDidChangeSettings(); telemetry.logLanguageServerEvent("CppSettingsChange", changedSettings, undefined); } }); return changedSettings; } onDidChangeVisibleTextEditors(editors) { const settings = new settings_1.CppSettings(this.RootUri); if (settings.dimInactiveRegions) { for (const e of editors) { const valuePair = this.inactiveRegionsDecorations.get(e.document.uri.toString()); if (valuePair) { e.setDecorations(valuePair.decoration, valuePair.ranges); } } } } onDidChangeTextDocument(textDocumentChangeEvent) { if (textDocumentChangeEvent.document.uri.scheme === "file") { if (textDocumentChangeEvent.document.languageId === "c" || textDocumentChangeEvent.document.languageId === "cpp" || textDocumentChangeEvent.document.languageId === "cuda-cpp") { if (DefaultClient.renamePending) { this.cancelReferences(); } const oldVersion = exports.openFileVersions.get(textDocumentChangeEvent.document.uri.toString()); const newVersion = textDocumentChangeEvent.document.version; if (oldVersion === undefined || newVersion > oldVersion) { exports.openFileVersions.set(textDocumentChangeEvent.document.uri.toString(), newVersion); } } } } onDidOpenTextDocument(document) { if (document.uri.scheme === "file") { exports.openFileVersions.set(document.uri.toString(), document.version); } } onDidCloseTextDocument(document) { if (this.semanticTokensProvider) { this.semanticTokensProvider.invalidateFile(document.uri.toString()); } exports.openFileVersions.delete(document.uri.toString()); } onRegisterCustomConfigurationProvider(provider) { const onRegistered = () => { if (provider.version >= vscode_cpptools_1.Version.v2) { this.pauseParsing(); } }; return this.notifyWhenLanguageClientReady(() => { if (this.registeredProviders.includes(provider)) { return; } this.registeredProviders.push(provider); const rootFolder = this.RootFolder; if (!rootFolder) { return; } this.configuration.handleConfigurationChange(); const selectedProvider = this.configuration.CurrentConfigurationProvider; if (!selectedProvider) { const ask = new persistentState_1.PersistentFolderState("Client.registerProvider", true, rootFolder); if (!fs.existsSync(`${this.RootPath}/.vscode/c_cpp_properties.json`) && !fs.existsSync(`${this.RootPath}/.vscode/settings.json`)) { ask.Value = true; } if (ask.Value) { ui.showConfigureCustomProviderMessage(() => __awaiter(this, void 0, void 0, function* () { const message = (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) ? localize(6, null, provider.name, this.Name) : localize(7, null, provider.name); const allow = localize(8, null); const dontAllow = localize(9, null); const askLater = localize(10, null); return vscode.window.showInformationMessage(message, allow, dontAllow, askLater).then((result) => __awaiter(this, void 0, void 0, function* () { switch (result) { case allow: { yield this.configuration.updateCustomConfigurationProvider(provider.extensionId); onRegistered(); ask.Value = false; telemetry.logLanguageServerEvent("customConfigurationProvider", { "providerId": provider.extensionId }); return true; } case dontAllow: { ask.Value = false; break; } default: { break; } } return false; })); }), () => ask.Value = false); } } else if (customProviders_1.isSameProviderExtensionId(selectedProvider, provider.extensionId)) { onRegistered(); telemetry.logLanguageServerEvent("customConfigurationProvider", { "providerId": provider.extensionId }); } else if (selectedProvider === provider.name) { onRegistered(); this.configuration.updateCustomConfigurationProvider(provider.extensionId); } }); } updateCustomConfigurations(requestingProvider) { return this.notifyWhenLanguageClientReady(() => { if (!this.configurationProvider) { this.clearCustomConfigurations(); return; } const currentProvider = customProviders_1.getCustomConfigProviders().get(this.configurationProvider); if (!currentProvider) { this.clearCustomConfigurations(); return; } if (requestingProvider && requestingProvider.extensionId !== currentProvider.extensionId) { return; } this.clearCustomConfigurations(); this.trackedDocuments.forEach(document => { this.provideCustomConfiguration(document.uri, undefined); }); }); } updateCustomBrowseConfiguration(requestingProvider) { return this.notifyWhenLanguageClientReady(() => { if (!this.configurationProvider) { return; } console.log("updateCustomBrowseConfiguration"); const currentProvider = customProviders_1.getCustomConfigProviders().get(this.configurationProvider); if (!currentProvider || (requestingProvider && requestingProvider.extensionId !== currentProvider.extensionId)) { return; } const tokenSource = new vscode.CancellationTokenSource(); const task = () => __awaiter(this, void 0, void 0, function* () { if (this.RootUri && (yield currentProvider.canProvideBrowseConfigurationsPerFolder(tokenSource.token))) { return (currentProvider.provideFolderBrowseConfiguration(this.RootUri, tokenSource.token)); } if (yield currentProvider.canProvideBrowseConfiguration(tokenSource.token)) { return currentProvider.provideBrowseConfiguration(tokenSource.token); } if (currentProvider.version >= vscode_cpptools_1.Version.v2) { console.warn("failed to provide browse configuration"); } return null; }); let hasCompleted = false; task().then((config) => __awaiter(this, void 0, void 0, function* () { if (!config) { return; } if (currentProvider.version < vscode_cpptools_1.Version.v3) { for (const c of config.browsePath) { if (vscode.workspace.getWorkspaceFolder(vscode.Uri.file(c)) === this.RootFolder) { this.sendCustomBrowseConfiguration(config, currentProvider.extensionId); break; } } } else { this.sendCustomBrowseConfiguration(config, currentProvider.extensionId); } if (!hasCompleted) { hasCompleted = true; if (currentProvider.version >= vscode_cpptools_1.Version.v2) { this.resumeParsing(); } } }), () => { if (!hasCompleted) { hasCompleted = true; if (currentProvider.version >= vscode_cpptools_1.Version.v2) { this.resumeParsing(); } } }); global.setTimeout(() => __awaiter(this, void 0, void 0, function* () { if (!hasCompleted) { hasCompleted = true; this.sendCustomBrowseConfiguration(null, undefined, true); if (currentProvider.version >= vscode_cpptools_1.Version.v2) { console.warn("Configuration Provider timed out in {0}ms.", configProviderTimeout); this.resumeParsing(); } } }), configProviderTimeout); }); } toggleReferenceResultsView() { exports.workspaceReferences.toggleGroupView(); } logDiagnostics() { return __awaiter(this, void 0, void 0, function* () { const response = yield this.requestWhenReady(() => this.languageClient.sendRequest(GetDiagnosticsRequest, null)); if (!diagnosticsChannel) { diagnosticsChannel = vscode.window.createOutputChannel(localize(11, null)); workspaceDisposables.push(diagnosticsChannel); } else { diagnosticsChannel.clear(); } const header = `-------- Diagnostics - ${new Date().toLocaleString()}\n`; const version = `Version: ${util.packageJson.version}\n`; let configJson = ""; if (this.configuration.CurrentConfiguration) { configJson = `Current Configuration:\n${JSON.stringify(this.configuration.CurrentConfiguration, null, 4)}\n`; } let configurationLoggingStr = ""; const tuSearchStart = response.diagnostics.indexOf("Translation Unit Mappings:"); if (tuSearchStart >= 0) { const tuSearchEnd = response.diagnostics.indexOf("Translation Unit Configurations:"); if (tuSearchEnd >= 0 && tuSearchEnd > tuSearchStart) { let tuSearchString = response.diagnostics.substr(tuSearchStart, tuSearchEnd - tuSearchStart); let tuSearchIndex = tuSearchString.indexOf("["); while (tuSearchIndex >= 0) { const tuMatch = tuSearchString.match(/\[\s(.*)\s\]/); if (tuMatch && tuMatch.length > 1) { const tuPath = vscode.Uri.file(tuMatch[1]).toString(); if (this.configurationLogging.has(tuPath)) { if (configurationLoggingStr.length === 0) { configurationLoggingStr += "Custom configurations:\n"; } configurationLoggingStr += `[ ${tuMatch[1]} ]\n${this.configurationLogging.get(tuPath)}\n`; } } tuSearchString = tuSearchString.substr(tuSearchIndex + 1); tuSearchIndex = tuSearchString.indexOf("["); } } } diagnosticsChannel.appendLine(`${header}${version}${configJson}${this.browseConfigurationLogging}${configurationLoggingStr}${response.diagnostics}`); diagnosticsChannel.show(false); }); } rescanFolder() { return __awaiter(this, void 0, void 0, function* () { yield this.notifyWhenLanguageClientReady(() => this.languageClient.sendNotification(RescanFolderNotification)); }); } provideCustomConfiguration(docUri, requestFile) { return __awaiter(this, void 0, void 0, function* () { const onFinished = () => { if (requestFile) { this.languageClient.sendNotification(FinishedRequestCustomConfig, requestFile); } }; const providerId = this.configurationProvider; if (!providerId) { onFinished(); return; } const provider = customProviders_1.getCustomConfigProviders().get(providerId); if (!provider) { onFinished(); return; } if (!provider.isReady) { onFinished(); throw new Error(`${this.configurationProvider} is not ready`); } return this.queueBlockingTask(() => __awaiter(this, void 0, void 0, function* () { var _a; const tokenSource = new vscode.CancellationTokenSource(); console.log("provideCustomConfiguration"); const providerName = provider.name; const params = { uri: docUri.toString(), workspaceFolderUri: this.RootPath }; const response = yield this.languageClient.sendRequest(QueryTranslationUnitSourceRequest, params); if (!response.candidates || response.candidates.length === 0) { onFinished(); return; } const provideConfigurationAsync = () => __awaiter(this, void 0, void 0, function* () { if (provider) { for (let i = 0; i < response.candidates.length; ++i) { try { const candidate = response.candidates[i]; const tuUri = vscode.Uri.parse(candidate); if (yield provider.canProvideConfiguration(tuUri, tokenSource.token)) { const configs = yield provider.provideConfigurations([tuUri], tokenSource.token); if (configs && configs.length > 0 && configs[0]) { return configs; } } if (tokenSource.token.isCancellationRequested) { return null; } } catch (err) { console.warn("Caught exception request configuration"); } } } }); const configs = yield this.callTaskWithTimeout(provideConfigurationAsync, configProviderTimeout, tokenSource); try { if (configs && configs.length > 0) { this.sendCustomConfigurations(configs, provider.version); } onFinished(); } catch (err) { if (requestFile) { onFinished(); return; } const settings = new settings_1.CppSettings(this.RootUri); if (settings.configurationWarnings === "Enabled" && !this.isExternalHeader(docUri) && !vscode.debug.activeDebugSession) { const dismiss = localize(12, null); const disable = localize(13, null); const configName = (_a = this.configuration.CurrentConfiguration) === null || _a === void 0 ? void 0 : _a.name; if (!configName) { return; } let message = localize(14, null, providerName, docUri.fsPath, configName); if (err) { message += ` (${err})`; } vscode.window.showInformationMessage(message, dismiss, disable).then(response => { switch (response) { case disable: { settings.toggleSetting("configurationWarnings", "Enabled", "Disabled"); break; } } }); } } })); }); } handleRequestCustomConfig(requestFile) { return __awaiter(this, void 0, void 0, function* () { yield this.provideCustomConfiguration(vscode.Uri.file(requestFile), requestFile); }); } isExternalHeader(uri) { const rootUri = this.RootUri; return !rootUri || (util.isHeader(uri) && !uri.toString().startsWith(rootUri.toString())); } getCurrentConfigName() { return this.queueTask(() => { var _a; return Promise.resolve((_a = this.configuration.CurrentConfiguration) === null || _a === void 0 ? void 0 : _a.name); }); } getCurrentConfigCustomVariable(variableName) { return this.queueTask(() => { var _a, _b; return Promise.resolve(((_b = (_a = this.configuration.CurrentConfiguration) === null || _a === void 0 ? void 0 : _a.customConfigurationVariables) === null || _b === void 0 ? void 0 : _b[variableName]) || ''); }); } setCurrentConfigName(configurationName) { return this.queueTask(() => new Promise((resolve, reject) => { const configurations = this.configuration.Configurations || []; const configurationIndex = configurations.findIndex((config) => config.name === configurationName); if (configurationIndex !== -1) { this.configuration.select(configurationIndex); resolve(); } else { reject(new Error(localize(15, null, configurationName))); } })); } getCurrentCompilerPathAndArgs() { return this.queueTask(() => { var _a, _b; return Promise.resolve(util.extractCompilerPathAndArgs((_a = this.configuration.CurrentConfiguration) === null || _a === void 0 ? void 0 : _a.compilerPath, (_b = this.configuration.CurrentConfiguration) === null || _b === void 0 ? void 0 : _b.compilerArgs)); }); } getVcpkgInstalled() { return this.queueTask(() => Promise.resolve(this.configuration.VcpkgInstalled)); } getVcpkgEnabled() { const cppSettings = new settings_1.CppSettings(this.RootUri); return Promise.resolve(cppSettings.vcpkgEnabled === true); } getKnownCompilers() { return this.queueTask(() => Promise.resolve(this.configuration.KnownCompiler)); } takeOwnership(document) { const params = { textDocument: { uri: document.uri.toString(), languageId: document.languageId, version: document.version, text: document.getText() } }; this.notifyWhenLanguageClientReady(() => this.languageClient.sendNotification(DidOpenNotification, params)); this.trackedDocuments.add(document); } queueTask(task) { return __awaiter(this, void 0, void 0, function* () { if (this.isSupported) { const nextTask = () => __awaiter(this, void 0, void 0, function* () { try { return yield task(); } catch (err) { console.error(err); throw err; } }); if (pendingTask && !pendingTask.Done) { try { yield pendingTask.getPromise(); } catch (e) { } } else { pendingTask = undefined; } return nextTask(); } else { throw new Error(localize(16, null)); } }); } queueBlockingTask(task) { return __awaiter(this, void 0, void 0, function* () { if (this.isSupported) { pendingTask = new util.BlockingTask(task, pendingTask); return pendingTask.getPromise(); } else { throw new Error(localize(17, null)); } }); } callTaskWithTimeout(task, ms, cancelToken) { let timer; const timeout = () => new Promise((resolve, reject) => { timer = global.setTimeout(() => { clearTimeout(timer); if (cancelToken) { cancelToken.cancel(); } reject(localize(18, null, ms)); }, ms); }); return Promise.race([task(), timeout()]).then((result) => { clearTimeout(timer); return result; }, (error) => { clearTimeout(timer); throw error; }); } requestWhenReady(request) { return this.queueTask(request); } notifyWhenLanguageClientReady(notify) { const task = () => new Promise(resolve => { resolve(notify()); }); return this.queueTask(task); } awaitUntilLanguageClientReady() { const task = () => new Promise(resolve => { resolve(); }); return this.queueTask(task); } registerNotifications() { console.assert(this.languageClient !== undefined, "This method must not be called until this.languageClient is set in \"onReady\""); this.languageClient.onNotification(ReloadWindowNotification, () => util.promptForReloadWindowDueToSettingsChange()); this.languageClient.onNotification(LogTelemetryNotification, logTelemetry); this.languageClient.onNotification(ReportStatusNotification, (e) => this.updateStatus(e)); this.languageClient.onNotification(ReportTagParseStatusNotification, (e) => this.updateTagParseStatus(e)); this.languageClient.onNotification(InactiveRegionNotification, (e) => this.updateInactiveRegions(e)); this.languageClient.onNotification(CompileCommandsPathsNotification, (e) => this.promptCompileCommands(e)); this.languageClient.onNotification(ReferencesNotification, (e) => this.processReferencesResult(e.referencesResult)); this.languageClient.onNotification(ReportReferencesProgressNotification, (e) => this.handleReferencesProgress(e)); this.languageClient.onNotification(RequestCustomConfig, (requestFile) => { const client = clientCollection.getClientFor(vscode.Uri.file(requestFile)); client.handleRequestCustomConfig(requestFile); }); this.languageClient.onNotification(PublishDiagnosticsNotification, publishDiagnostics); this.languageClient.onNotification(ShowMessageWindowNotification, showMessageWindow); this.languageClient.onNotification(ShowWarningNotification, showWarning); this.languageClient.onNotification(ReportTextDocumentLanguage, (e) => this.setTextDocumentLanguage(e)); this.languageClient.onNotification(SemanticTokensChanged, (e) => { var _a; return (_a = this.semanticTokensProvider) === null || _a === void 0 ? void 0 : _a.invalidateFile(e); }); this.languageClient.onNotification(IntelliSenseSetupNotification, (e) => this.logIntellisenseSetupTime(e)); this.languageClient.onNotification(SetTemporaryTextDocumentLanguageNotification, (e) => this.setTemporaryTextDocumentLanguage(e)); setupOutputHandlers(); } setTextDocumentLanguage(languageStr) { const cppSettings = new settings_1.CppSettings(); if (cppSettings.autoAddFileAssociations) { const is_c = languageStr.startsWith("c;"); const is_cuda = languageStr.startsWith("cu;"); languageStr = languageStr.substr(is_c ? 2 : (is_cuda ? 3 : 1)); this.addFileAssociations(languageStr, is_c ? "c" : (is_cuda ? "cuda-cpp" : "cpp")); } } setTemporaryTextDocumentLanguage(params) { return __awaiter(this, void 0, void 0, function* () { const languageId = params.isC ? "c" : (params.isCuda ? "cuda-cpp" : "cpp"); const document = yield vscode.workspace.openTextDocument(params.path); if (!!document && document.languageId !== languageId) { vscode.languages.setTextDocumentLanguage(document, languageId); } }); } registerFileWatcher() { console.assert(this.languageClient !== undefined, "This method must not be called until this.languageClient is set in \"onReady\""); if (this.rootFolder) { this.rootPathFileWatcher = vscode.workspace.createFileSystemWatcher("**/*", false, false, false); this.rootPathFileWatcher.onDidCreate((uri) => { if (path.basename(uri.fsPath).toLowerCase() === ".editorconfig") { exports.cachedEditorConfigSettings.clear(); } this.languageClient.sendNotification(FileCreatedNotification, { uri: uri.toString() }); }); this.associations_for_did_change = new Set(["cu", "cuh", "c", "i", "cpp", "cc", "cxx", "c++", "cp", "hpp", "hh", "hxx", "h++", "hp", "h", "ii", "ino", "inl", "ipp", "tcc", "idl"]); const assocs = new settings_1.OtherSettings().filesAssociations; for (const assoc in assocs) { const dotIndex = assoc.lastIndexOf('.'); if (dotIndex !== -1) { const ext = assoc.substr(dotIndex + 1); this.associations_for_did_change.add(ext); } } this.rootPathFileWatcher.onDidChange((uri) => { var _a; const dotIndex = uri.fsPath.lastIndexOf('.'); if (path.basename(uri.fsPath).toLowerCase() === ".editorconfig") { exports.cachedEditorConfigSettings.clear(); } if (dotIndex !== -1) { const ext = uri.fsPath.substr(dotIndex + 1); if ((_a = this.associations_for_did_change) === null || _a === void 0 ? void 0 : _a.has(ext)) { const mtime = fs.statSync(uri.fsPath).mtime; const duration = Date.now() - mtime.getTime(); if (duration < 10000) { this.languageClient.sendNotification(FileChangedNotification, { uri: uri.toString() }); } } } }); this.rootPathFileWatcher.onDidDelete((uri) => { if (path.basename(uri.fsPath).toLowerCase() === ".editorconfig") { exports.cachedEditorConfigSettings.clear(); } this.languageClient.sendNotification(FileDeletedNotification, { uri: uri.toString() }); }); this.disposables.push(this.rootPathFileWatcher); } else { this.rootPathFileWatcher = undefined; } } addFileAssociations(fileAssociations, languageId) { const settings = new settings_1.OtherSettings(); const assocs = settings.filesAssociations; const filesAndPaths = fileAssociations.split(";"); let foundNewAssociation = false; for (let i = 0; i < filesAndPaths.length; ++i) { const fileAndPath = filesAndPaths[i].split("@"); if (fileAndPath.length === 2) { const file = fileAndPath[0]; const filePath = fileAndPath[1]; if ((file in assocs) || (("**/" + file) in assocs)) { continue; } const j = file.lastIndexOf('.'); if (j !== -1) { const ext = file.substr(j); if ((("*" + ext) in assocs) || (("**/*" + ext) in assocs)) { continue; } } let foundGlobMatch = false; for (const assoc in assocs) { if (minimatch(filePath, assoc)) { foundGlobMatch = true; break; } } if (foundGlobMatch) { continue; } assocs[file] = languageId; foundNewAssociation = true; } } if (foundNewAssociation) { settings.filesAssociations = assocs; } } updateStatus(notificationBody) { var _a; const message = notificationBody.status; util.setProgress(util.getProgressExecutableSuccess()); const testHook = testHook_1.getTestHook(); if (message.endsWith("Indexing...")) { this.model.isTagParsing.Value = true; const status = { status: testApi_1.Status.TagParsingBegun }; testHook.updateStatus(status); } else if (message.endsWith("Updating IntelliSense...")) { timeStamp = Date.now(); this.model.isUpdatingIntelliSense.Value = true; const status = { status: testApi_1.Status.IntelliSenseCompiling }; testHook.updateStatus(status); } else if (message.endsWith("IntelliSense Ready")) { const settings = new settings_1.CppSettings(); if (settings.loggingLevel === "Debug") { const out = logger.getOutputChannelLogger(); const duration = Date.now() - timeStamp; out.appendLine(localize(19, null, duration / 1000)); } this.model.isUpdatingIntelliSense.Value = false; const status = { status: testApi_1.Status.IntelliSenseReady }; testHook.updateStatus(status); } else if (message.endsWith("Ready")) { this.model.isTagParsing.Value = false; const status = { status: testApi_1.Status.TagParsingDone }; testHook.updateStatus(status); util.setProgress(util.getProgressParseRootSuccess()); } else if (message.includes("Squiggles Finished - File name:")) { const index = message.lastIndexOf(":"); const name = message.substring(index + 2); const status = { status: testApi_1.Status.IntelliSenseReady, filename: name }; testHook.updateStatus(status); } else if (message.endsWith("No Squiggles")) { util.setIntelliSenseProgress(util.getProgressIntelliSenseNoSquiggles()); } else if (message.endsWith("Unresolved Headers")) { if (notificationBody.workspaceFolderUri) { const client = clientCollection.getClientFor(vscode.Uri.file(notificationBody.workspaceFolderUri)); if (!((_a = client.configuration.CurrentConfiguration) === null || _a === void 0 ? void 0 : _a.configurationProvider)) { const showIntelliSenseFallbackMessage = new persistentState_1.PersistentState("CPP.showIntelliSenseFallbackMessage", true); if (showIntelliSenseFallbackMessage.Value) { ui.showConfigureIncludePathMessage(() => __awaiter(this, void 0, void 0, function* () { const configJSON = localize(20, null); const configUI = localize(21, null); const dontShowAgain = localize(22, null); const fallbackMsg = client.configuration.VcpkgInstalled ? localize(23, null) : localize(24, null); return vscode.window.showInformationMessage(fallbackMsg, configJSON, configUI, dontShowAgain).then((value) => __awaiter(this, void 0, void 0, function* () { let commands; switch (value) { case configJSON: commands = yield vscode.commands.getCommands(true); if (commands.indexOf("workbench.action.problems.focus") >= 0) { vscode.commands.executeCommand("workbench.action.problems.focus"); } client.handleConfigurationEditJSONCommand(); telemetry.logLanguageServerEvent("SettingsCommand", { "toast": "json" }, undefined); break; case configUI: commands = yield vscode.commands.getCommands(true); if (commands.indexOf("workbench.action.problems.focus") >= 0) { vscode.commands.executeCommand("workbench.action.problems.focus"); } client.handleConfigurationEditUICommand(); telemetry.logLanguageServerEvent("SettingsCommand", { "toast": "ui" }, undefined); break; case dontShowAgain: showIntelliSenseFallbackMessage.Value = false; break; } return true; })); }), () => showIntelliSenseFallbackMessage.Value = false); } } } } } updateTagParseStatus(notificationBody) { this.model.tagParserStatus.Value = util.getLocalizedString(notificationBody); } updateInactiveRegions(params) { const settings = new settings_1.CppSettings(this.RootUri); const opacity = settings.inactiveRegionOpacity; if (opacity !== null && opacity !== undefined) { let backgroundColor = settings.inactiveRegionBackgroundColor; if (backgroundColor === "") { backgroundColor = undefined; } let color = settings.inactiveRegionForegroundColor; if (color === "") { color = undefined; } const decoration = vscode.window.createTextEditorDecorationType({ opacity: opacity.toString(), backgroundColor: backgroundColor, color: color, rangeBehavior: vscode.DecorationRangeBehavior.OpenOpen }); const ranges = []; params.regions.forEach(element => { const newRange = new vscode.Range(element.startLine, 0, element.endLine, 0); ranges.push(newRange); }); const valuePair = this.inactiveRegionsDecorations.get(params.uri); if (valuePair) { valuePair.decoration.dispose(); valuePair.decoration = decoration; valuePair.ranges = ranges; } else { const toInsert = { decoration: decoration, ranges: ranges }; this.inactiveRegionsDecorations.set(params.uri, toInsert); } if (settings.dimInactiveRegions && params.fileVersion === exports.openFileVersions.get(params.uri)) { const editors = vscode.window.visibleTextEditors.filter(e => e.document.uri.toString() === params.uri); for (const e of editors) { e.setDecorations(decoration, ranges); } } } if (this.codeFoldingProvider) { this.codeFoldingProvider.refresh(); } } logIntellisenseSetupTime(notification) { clientCollection.timeTelemetryCollector.setSetupTime(vscode.Uri.parse(notification.uri)); } promptCompileCommands(params) { var _a, _b; if (!params.workspaceFolderUri) { return; } const client = clientCollection.getClientFor(vscode.Uri.file(params.workspaceFolderUri)); if (((_a = client.configuration.CurrentConfiguration) === null || _a === void 0 ? void 0 : _a.compileCommands) || ((_b = client.configuration.CurrentConfiguration) === null || _b === void 0 ? void 0 : _b.configurationProvider)) { return; } const rootFolder = client.RootFolder; if (!rootFolder) { return; } const ask = new persistentState_1.PersistentFolderState("CPP.showCompileCommandsSelection", true, rootFolder); if (!ask.Value) { return; } const aCompileCommandsFile = localize(25, null); const compileCommandStr = params.paths.length > 1 ? aCompileCommandsFile : params.paths[0]; const message = (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) ? localize(26, null, compileCommandStr, client.Name) : localize(27, null, compileCommandStr); ui.showConfigureCompileCommandsMessage(() => __awaiter(this, void 0, void 0, function* () { const yes = localize(28, null); const no = localize(29, null); const askLater = localize(30, null); return vscode.window.showInformationMessage(message, yes, no, askLater).then((value) => __awaiter(this, void 0, void 0, function* () { switch (value) { case yes: if (params.paths.length > 1) { const index = yield ui.showCompileCommands(params.paths); if (index < 0) { return false; } this.configuration.setCompileCommands(params.paths[index]); } else { this.configuration.setCompileCommands(params.paths[0]); } return true; case askLater: break; case no: ask.Value = false; break; } return false; })); }), () => ask.Value = false); } requestSwitchHeaderSource(rootPath, fileName) { const params = { switchHeaderSourceFileName: fileName, workspaceFolderUri: rootPath }; return this.requestWhenReady(() => this.languageClient.sendRequest(SwitchHeaderSourceRequest, params)); } activeDocumentChanged(document) { this.notifyWhenLanguageClientReady(() => { this.languageClient.sendNotification(ActiveDocumentChangeNotification, this.languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document)); }); } activate() { this.model.activate(); this.resumeParsing(); } selectionChanged(selection) { this.notifyWhenLanguageClientReady(() => { this.languageClient.sendNotification(TextEditorSelectionChangeNotification, selection); }); } resetDatabase() { this.notifyWhenLanguageClientReady(() => this.languageClient.sendNotification(ResetDatabaseNotification)); } deactivate() { this.model.deactivate(); } pauseParsing() { this.notifyWhenLanguageClientReady(() => this.languageClient.sendNotification(PauseParsingNotification)); } resumeParsing() { this.notifyWhenLanguageClientReady(() => this.languageClient.sendNotification(ResumeParsingNotification)); } onConfigurationsChanged(cppProperties) { var _a; if (!cppProperties.Configurations) { return; } const configurations = cppProperties.Configurations; const params = { configurations: configurations, currentConfiguration: this.configuration.CurrentConfigurationIndex, workspaceFolderUri: this.RootPath, isReady: true }; params.configurations.forEach((c) => { const compilerPathAndArgs = util.extractCompilerPathAndArgs(c.compilerPath, c.compilerArgs); c.compilerPath = compilerPathAndArgs.compilerPath; c.compilerArgs = compilerPathAndArgs.additionalArgs; }); this.languageClient.sendNotification(ChangeCppPropertiesNotification, params); const lastCustomBrowseConfigurationProviderId = cppProperties.LastCustomBrowseConfigurationProviderId; const lastCustomBrowseConfiguration = cppProperties.LastCustomBrowseConfiguration; if (!!lastCustomBrowseConfigurationProviderId && !!lastCustomBrowseConfiguration) { if (!this.doneInitialCustomBrowseConfigurationCheck) { if (lastCustomBrowseConfiguration.Value) { this.sendCustomBrowseConfiguration(lastCustomBrowseConfiguration.Value, lastCustomBrowseConfigurationProviderId.Value); params.isReady = false; } this.doneInitialCustomBrowseConfigurationCheck = true; } } const configName = (_a = configurations[params.currentConfiguration].name, (_a !== null && _a !== void 0 ? _a : "")); this.model.activeConfigName.setValueIfActive(configName); const newProvider = this.configuration.CurrentConfigurationProvider; if (!customProviders_1.isSameProviderExtensionId(newProvider, this.configurationProvider)) { if (this.configurationProvider) { this.clearCustomBrowseConfiguration(); } this.configurationProvider = newProvider; this.updateCustomBrowseConfiguration(); this.updateCustomConfigurations(); } } onSelectedConfigurationChanged(index) { const params = { currentConfiguration: index, workspaceFolderUri: this.RootPath }; this.notifyWhenLanguageClientReady(() => { this.languageClient.sendNotification(ChangeSelectedSettingNotification, params); let configName = ""; if (this.configuration.ConfigurationNames) { configName = this.configuration.ConfigurationNames[index]; } this.model.activeConfigName.Value = configName; this.configuration.onDidChangeSettings(); }); } onCompileCommandsChanged(path) { const params = { uri: vscode.Uri.file(path).toString(), workspaceFolderUri: this.RootPath }; this.notifyWhenLanguageClientReady(() => this.languageClient.sendNotification(ChangeCompileCommandsNotification, params)); } isSourceFileConfigurationItem(input, providerVersion) { let areOptionalsValid = false; if (providerVersion < vscode_cpptools_1.Version.v5) { areOptionalsValid = util.isString(input.configuration.intelliSenseMode) && util.isString(input.configuration.standard); } else { areOptionalsValid = util.isOptionalString(input.configuration.intelliSenseMode) && util.isOptionalString(input.configuration.standard); } return (input && (util.isString(input.uri) || util.isUri(input.uri)) && input.configuration && areOptionalsValid && util.isArrayOfString(input.configuration.includePath) && util.isArrayOfString(input.configuration.defines) && util.isOptionalArrayOfString(input.configuration.compilerArgs) && util.isOptionalArrayOfString(input.configuration.forcedInclude)); } sendCustomConfigurations(configs, providerVersion) { if (!configs || !(configs instanceof Array)) { console.warn("discarding invalid SourceFileConfigurationItems[]: " + configs); return; } const settings = new settings_1.CppSettings(); const out = logger.getOutputChannelLogger(); if (settings.loggingLevel === "Debug") { out.appendLine(localize(31, null)); } const sanitized = []; configs.forEach(item => { if (this.isSourceFileConfigurationItem(item, providerVersion)) { this.configurationLogging.set(item.uri.toString(), JSON.stringify(item.configuration, null, 4)); if (settings.loggingLevel === "Debug") { out.appendLine(` uri: ${item.uri.toString()}`); out.appendLine(` config: ${JSON.stringify(item.configuration, null, 2)}`); } if (item.configuration.includePath.some(path => path.endsWith('**'))) { console.warn("custom include paths should not use recursive includes ('**')"); } const itemConfig = Object.assign({}, item.configuration); if (util.isString(itemConfig.compilerPath)) { const compilerPathAndArgs = util.extractCompilerPathAndArgs(itemConfig.compilerPath, util.isArrayOfString(itemConfig.compilerArgs) ? itemConfig.compilerArgs : undefined); itemConfig.compilerPath = compilerPathAndArgs.compilerPath; itemConfig.compilerArgs = compilerPathAndArgs.additionalArgs; } sanitized.push({ uri: item.uri.toString(), configuration: itemConfig }); } else { console.warn("discarding invalid SourceFileConfigurationItem: " + JSON.stringify(item)); } }); if (sanitized.length === 0) { return; } const params = { configurationItems: sanitized, workspaceFolderUri: this.RootPath }; this.languageClient.sendNotification(CustomConfigurationNotification, params); } isWorkspaceBrowseConfiguration(input) { return util.isArrayOfString(input.browsePath) && util.isOptionalString(input.compilerPath) && util.isOptionalString(input.standard) && util.isOptionalArrayOfString(input.compilerArgs) && util.isOptionalString(input.windowsSdkVersion); } sendCustomBrowseConfiguration(config, providerId, timeoutOccured) { const rootFolder = this.RootFolder; if (!rootFolder) { return; } const lastCustomBrowseConfiguration = new persistentState_1.PersistentFolderState("CPP.lastCustomBrowseConfiguration", undefined, rootFolder); const lastCustomBrowseConfigurationProviderId = new persistentState_1.PersistentFolderState("CPP.lastCustomBrowseConfigurationProviderId", undefined, rootFolder); let sanitized; this.browseConfigurationLogging = ""; while (true) { if (timeoutOccured || !config || config instanceof Array) { if (!timeoutOccured) { console.log("Received an invalid browse configuration from configuration provider."); } const configValue = lastCustomBrowseConfiguration.Value; if (configValue) { sanitized = configValue; console.log("Falling back to last received browse configuration: ", JSON.stringify(sanitized, null, 2)); break; } console.log("No browse configuration is available."); return; } sanitized = Object.assign({}, config); if (!this.isWorkspaceBrowseConfiguration(sanitized)) { console.log("Received an invalid browse configuration from configuration provider: " + JSON.stringify(sanitized)); const configValue = lastCustomBrowseConfiguration.Value; if (configValue) { sanitized = configValue; console.log("Falling back to last received browse configuration: ", JSON.stringify(sanitized, null, 2)); break; } return; } const settings = new settings_1.CppSettings(); if (settings.loggingLevel === "Debug") { const out = logger.getOutputChannelLogger(); out.appendLine(localize(32, null, JSON.stringify(sanitized, null, 2))); } if (util.isString(sanitized.compilerPath)) { const compilerPathAndArgs = util.extractCompilerPathAndArgs(sanitized.compilerPath, util.isArrayOfString(sanitized.compilerArgs) ? sanitized.compilerArgs : undefined); sanitized.compilerPath = compilerPathAndArgs.compilerPath; sanitized.compilerArgs = compilerPathAndArgs.additionalArgs; } lastCustomBrowseConfiguration.Value = sanitized; if (!providerId) { lastCustomBrowseConfigurationProviderId.setDefault(); } else { lastCustomBrowseConfigurationProviderId.Value = providerId; } break; } this.browseConfigurationLogging = `Custom browse configuration: \n${JSON.stringify(sanitized, null, 4)}\n`; const params = { browseConfiguration: sanitized, workspaceFolderUri: this.RootPath }; this.languageClient.sendNotification(CustomBrowseConfigurationNotification, params); } clearCustomConfigurations() { this.configurationLogging.clear(); const params = { workspaceFolderUri: this.RootPath }; this.notifyWhenLanguageClientReady(() => this.languageClient.sendNotification(ClearCustomConfigurationsNotification, params)); } clearCustomBrowseConfiguration() { this.browseConfigurationLogging = ""; const params = { workspaceFolderUri: this.RootPath }; this.notifyWhenLanguageClientReady(() => this.languageClient.sendNotification(ClearCustomBrowseConfigurationNotification, params)); } handleConfigurationSelectCommand() { return __awaiter(this, void 0, void 0, function* () { yield this.awaitUntilLanguageClientReady(); const configNames = this.configuration.ConfigurationNames; if (configNames) { const index = yield ui.showConfigurations(configNames); if (index < 0) { return; } this.configuration.select(index); } }); } handleConfigurationProviderSelectCommand() { return __awaiter(this, void 0, void 0, function* () { yield this.awaitUntilLanguageClientReady(); const extensionId = yield ui.showConfigurationProviders(this.configuration.CurrentConfigurationProvider); if (extensionId === undefined) { return; } yield this.configuration.updateCustomConfigurationProvider(extensionId); if (extensionId) { const provider = customProviders_1.getCustomConfigProviders().get(extensionId); this.updateCustomBrowseConfiguration(provider); this.updateCustomConfigurations(provider); telemetry.logLanguageServerEvent("customConfigurationProvider", { "providerId": extensionId }); } else { this.clearCustomConfigurations(); this.clearCustomBrowseConfiguration(); } }); } handleShowParsingCommands() { return __awaiter(this, void 0, void 0, function* () { yield this.awaitUntilLanguageClientReady(); const index = yield ui.showParsingCommands(); if (index === 0) { this.pauseParsing(); } else if (index === 1) { this.resumeParsing(); } }); } handleConfigurationEditCommand(viewColumn = vscode.ViewColumn.Active) { this.notifyWhenLanguageClientReady(() => this.configuration.handleConfigurationEditCommand(undefined, vscode.window.showTextDocument, viewColumn)); } handleConfigurationEditJSONCommand(viewColumn = vscode.ViewColumn.Active) { this.notifyWhenLanguageClientReady(() => this.configuration.handleConfigurationEditJSONCommand(undefined, vscode.window.showTextDocument, viewColumn)); } handleConfigurationEditUICommand(viewColumn = vscode.ViewColumn.Active) { this.notifyWhenLanguageClientReady(() => this.configuration.handleConfigurationEditUICommand(undefined, vscode.window.showTextDocument, viewColumn)); } handleAddToIncludePathCommand(path) { this.notifyWhenLanguageClientReady(() => this.configuration.addToIncludePathCommand(path)); } handleGoToDirectiveInGroup(next) { return __awaiter(this, void 0, void 0, function* () { const editor = vscode.window.activeTextEditor; if (editor) { const params = { uri: editor.document.uri.toString(), position: editor.selection.active, next: next }; const response = yield this.languageClient.sendRequest(GoToDirectiveInGroupRequest, params); if (response) { const p = new vscode.Position(response.line, response.character); const r = new vscode.Range(p, p); const currentEditor = vscode.window.activeTextEditor; if (currentEditor && editor.document.uri === currentEditor.document.uri) { currentEditor.selection = new vscode.Selection(r.start, r.end); currentEditor.revealRange(r); } } } }); } handleCheckForCompiler() { return __awaiter(this, void 0, void 0, function* () { yield this.awaitUntilLanguageClientReady(); const compilers = yield this.getKnownCompilers(); if (!compilers || compilers.length === 0) { const compilerName = process.platform === "win32" ? "MSVC" : (process.platform === "darwin" ? "Clang" : "GCC"); vscode.window.showInformationMessage(localize(33, null, compilerName), { modal: true }); } else { const header = localize(34, null); let message = header + "\n"; const settings = new settings_1.CppSettings(this.RootUri); const pathSeparator = settings.preferredPathSeparator; compilers.forEach(compiler => { if (pathSeparator !== "Forward Slash") { message += "\n" + compiler.path.replace(/\//g, '\\'); } else { message += "\n" + compiler.path.replace(/\\/g, '/'); } }); if (compilers.length > 1) { message += "\n\n" + localize(35, null); } vscode.window.showInformationMessage(message, { modal: true }); } }); } onInterval() { if (this.innerLanguageClient !== undefined && this.configuration !== undefined) { this.languageClient.sendNotification(IntervalTimerNotification); this.configuration.checkCppProperties(); this.configuration.checkCompileCommands(); } } dispose() { this.disposables.forEach((d) => d.dispose()); this.disposables = []; if (this.documentFormattingProviderDisposable) { this.documentFormattingProviderDisposable.dispose(); this.documentFormattingProviderDisposable = undefined; } if (this.formattingRangeProviderDisposable) { this.formattingRangeProviderDisposable.dispose(); this.formattingRangeProviderDisposable = undefined; } if (this.onTypeFormattingProviderDisposable) { this.onTypeFormattingProviderDisposable.dispose(); this.onTypeFormattingProviderDisposable = undefined; } if (this.codeFoldingProviderDisposable) { this.codeFoldingProviderDisposable.dispose(); this.codeFoldingProviderDisposable = undefined; } if (this.semanticTokensProviderDisposable) { this.semanticTokensProviderDisposable.dispose(); this.semanticTokensProviderDisposable = undefined; } this.model.dispose(); } static stopLanguageClient() { return languageClient ? languageClient.stop() : Promise.resolve(); } handleReferencesIcon() { this.notifyWhenLanguageClientReady(() => { const cancelling = DefaultClient.referencesPendingCancellations.length > 0; if (!cancelling) { exports.workspaceReferences.UpdateProgressUICounter(this.model.referencesCommandMode.Value); if (this.ReferencesCommandMode === refs.ReferencesCommandMode.Find) { if (!exports.workspaceReferences.referencesRequestPending) { if (exports.workspaceReferences.referencesRequestHasOccurred) { if (!exports.workspaceReferences.referencesRefreshPending) { exports.workspaceReferences.referencesRefreshPending = true; vscode.commands.executeCommand("references-view.refresh"); } } else { exports.workspaceReferences.referencesRequestHasOccurred = true; exports.workspaceReferences.referencesRequestPending = true; this.languageClient.sendNotification(exports.RequestReferencesNotification, false); } } } } }); } cancelReferences() { DefaultClient.referencesParams = undefined; DefaultClient.renamePending = false; if (DefaultClient.referencesRequestPending || exports.workspaceReferences.symbolSearchInProgress) { const cancelling = DefaultClient.referencesPendingCancellations.length > 0; DefaultClient.referencesPendingCancellations.push({ reject: () => { }, callback: () => { } }); if (!cancelling) { exports.workspaceReferences.referencesCanceled = true; languageClient.sendNotification(exports.CancelReferencesNotification); } } } handleReferencesProgress(notificationBody) { exports.workspaceReferences.handleProgress(notificationBody); } processReferencesResult(referencesResult) { exports.workspaceReferences.processResults(referencesResult); } setReferencesCommandMode(mode) { this.model.referencesCommandMode.Value = mode; } abortRequest(id) { const params = { id: id }; languageClient.sendNotification(AbortRequestNotification, params); } } exports.DefaultClient = DefaultClient; DefaultClient.abortRequestId = 0; DefaultClient.referencesRequestPending = false; DefaultClient.referencesPendingCancellations = []; DefaultClient.renameRequestsPending = 0; DefaultClient.renamePending = false; function getLanguageServerFileName() { let extensionProcessName = 'cpptools'; const plat = process.platform; if (plat === 'win32') { extensionProcessName += '.exe'; } else if (plat !== 'linux' && plat !== 'darwin') { throw "Invalid Platform"; } return path.resolve(util.getExtensionFilePath("bin"), extensionProcessName); } class NullClient { constructor() { this.booleanEvent = new vscode.EventEmitter(); this.stringEvent = new vscode.EventEmitter(); this.referencesCommandModeEvent = new vscode.EventEmitter(); this.RootPath = "/"; this.RootRealPath = "/"; this.RootUri = vscode.Uri.file("/"); this.Name = "(empty)"; this.TrackedDocuments = new Set(); } get TagParsingChanged() { return this.booleanEvent.event; } get IntelliSenseParsingChanged() { return this.booleanEvent.event; } get ReferencesCommandModeChanged() { return this.referencesCommandModeEvent.event; } get TagParserStatusChanged() { return this.stringEvent.event; } get ActiveConfigChanged() { return this.stringEvent.event; } onDidChangeSettings(event, isFirstClient) { return {}; } onDidOpenTextDocument(document) { } onDidCloseTextDocument(document) { } onDidChangeVisibleTextEditors(editors) { } onDidChangeTextDocument(textDocumentChangeEvent) { } onRegisterCustomConfigurationProvider(provider) { return Promise.resolve(); } updateCustomConfigurations(requestingProvider) { return Promise.resolve(); } updateCustomBrowseConfiguration(requestingProvider) { return Promise.resolve(); } provideCustomConfiguration(docUri, requestFile) { return Promise.resolve(); } logDiagnostics() { return Promise.resolve(); } rescanFolder() { return Promise.resolve(); } toggleReferenceResultsView() { } setCurrentConfigName(configurationName) { return Promise.resolve(); } getCurrentConfigName() { return Promise.resolve(""); } getCurrentConfigCustomVariable(variableName) { return Promise.resolve(""); } getVcpkgInstalled() { return Promise.resolve(false); } getVcpkgEnabled() { return Promise.resolve(false); } getCurrentCompilerPathAndArgs() { return Promise.resolve(undefined); } getKnownCompilers() { return Promise.resolve([]); } takeOwnership(document) { } queueTask(task) { return Promise.resolve(task()); } requestWhenReady(request) { return request(); } notifyWhenLanguageClientReady(notify) { } awaitUntilLanguageClientReady() { } requestSwitchHeaderSource(rootPath, fileName) { return Promise.resolve(""); } activeDocumentChanged(document) { } activate() { } selectionChanged(selection) { } resetDatabase() { } deactivate() { } pauseParsing() { } resumeParsing() { } handleConfigurationSelectCommand() { return Promise.resolve(); } handleConfigurationProviderSelectCommand() { return Promise.resolve(); } handleShowParsingCommands() { return Promise.resolve(); } handleReferencesIcon() { } handleConfigurationEditCommand(viewColumn) { } handleConfigurationEditJSONCommand(viewColumn) { } handleConfigurationEditUICommand(viewColumn) { } handleAddToIncludePathCommand(path) { } handleGoToDirectiveInGroup(next) { return Promise.resolve(); } handleCheckForCompiler() { return Promise.resolve(); } onInterval() { } dispose() { this.booleanEvent.dispose(); this.stringEvent.dispose(); } addFileAssociations(fileAssociations, languageId) { } sendDidChangeSettings(settings) { } } /***/ }), /***/ 3765: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const util = __webpack_require__(5331); const cpptools = __webpack_require__(9325); const telemetry = __webpack_require__(1818); const customProviders_1 = __webpack_require__(4977); const timeTelemetryCollector_1 = __webpack_require__(9071); const defaultClientKey = "@@default@@"; class ClientCollection { constructor() { this.disposables = []; this.languageClients = new Map(); this.timeTelemetryCollector = new timeTelemetryCollector_1.TimeTelemetryCollector(); let key = defaultClientKey; if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) { let isFirstWorkspaceFolder = true; vscode.workspace.workspaceFolders.forEach(folder => { const newClient = cpptools.createClient(this, folder); this.languageClients.set(util.asFolder(folder.uri), newClient); if (isFirstWorkspaceFolder) { isFirstWorkspaceFolder = false; } else { newClient.deactivate(); } }); key = util.asFolder(vscode.workspace.workspaceFolders[0].uri); const client = this.languageClients.get(key); if (!client) { throw new Error("Failed to construct default client"); } this.activeClient = client; } else { this.activeClient = cpptools.createClient(this); } this.defaultClient = this.activeClient; this.languageClients.set(key, this.activeClient); this.disposables.push(vscode.workspace.onDidChangeWorkspaceFolders(e => this.onDidChangeWorkspaceFolders(e))); this.disposables.push(vscode.workspace.onDidCloseTextDocument(d => this.onDidCloseTextDocument(d))); } get ActiveClient() { return this.activeClient; } get Names() { const result = []; this.languageClients.forEach((client, key) => { result.push({ name: client.Name, key: key }); }); return result; } get Count() { return this.languageClients.size; } activeDocumentChanged(document) { this.activeDocument = document; const activeClient = this.getClientFor(document.uri); activeClient.activeDocumentChanged(document); if (activeClient !== this.activeClient) { activeClient.activate(); this.activeClient.deactivate(); this.activeClient = activeClient; } } get(key) { const client = this.languageClients.get(key); console.assert(client, "key not found"); return client; } forEach(callback) { const languageClients = []; this.languageClients.forEach(client => languageClients.push(client)); languageClients.forEach(callback); } checkOwnership(client, document) { return (this.getClientFor(document.uri) === client); } replace(client, transferFileOwnership) { let key; for (const pair of this.languageClients) { if (pair[1] === client) { key = pair[0]; break; } } if (key) { this.languageClients.delete(key); if (transferFileOwnership) { client.TrackedDocuments.forEach(document => this.transferOwnership(document, client)); client.TrackedDocuments.clear(); } else { this.languageClients.set(key, cpptools.createNullClient()); } if (this.activeClient === client && this.activeDocument) { this.activeClient = this.getClientFor(this.activeDocument.uri); this.activeClient.activeDocumentChanged(this.activeDocument); } client.dispose(); return this.languageClients.get(key); } else { console.assert(key, "unable to locate language client"); return undefined; } } onDidChangeWorkspaceFolders(e) { const folderCount = vscode.workspace.workspaceFolders ? vscode.workspace.workspaceFolders.length : 0; if (folderCount > 1) { telemetry.logLanguageServerEvent("workspaceFoldersChange", { "count": folderCount.toString() }); } if (e !== undefined) { e.removed.forEach(folder => { const path = util.asFolder(folder.uri); const client = this.languageClients.get(path); if (client) { this.languageClients.delete(path); client.TrackedDocuments.forEach(document => this.transferOwnership(document, client)); client.TrackedDocuments.clear(); if (this.activeClient === client && this.activeDocument) { this.activeClient = this.getClientFor(this.activeDocument.uri); this.activeClient.activeDocumentChanged(this.activeDocument); } client.dispose(); } }); e.added.forEach(folder => { const path = util.asFolder(folder.uri); const client = this.languageClients.get(path); if (!client) { const newClient = cpptools.createClient(this, folder); this.languageClients.set(path, newClient); newClient.deactivate(); const defaultClient = newClient; defaultClient.sendAllSettings(); } }); } } transferOwnership(document, oldOwner) { const newOwner = this.getClientFor(document.uri); if (newOwner !== oldOwner) { newOwner.takeOwnership(document); } } getClientFor(uri) { const folder = uri ? vscode.workspace.getWorkspaceFolder(uri) : undefined; if (!folder) { return this.defaultClient; } else { const key = util.asFolder(folder.uri); const client = this.languageClients.get(key); if (client) { return client; } const newClient = cpptools.createClient(this, folder); this.languageClients.set(key, newClient); customProviders_1.getCustomConfigProviders().forEach(provider => newClient.onRegisterCustomConfigurationProvider(provider)); const defaultClient = newClient; defaultClient.sendAllSettings(); return newClient; } } onDidCloseTextDocument(document) { } dispose() { this.disposables.forEach((d) => d.dispose()); this.languageClients.forEach(client => client.dispose()); this.languageClients.clear(); cpptools.disposeWorkspaceData(); return cpptools.DefaultClient.stopLanguageClient(); } } exports.ClientCollection = ClientCollection; /***/ }), /***/ 6932: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __webpack_require__(5622); const fs = __webpack_require__(5747); const vscode = __webpack_require__(7549); const util = __webpack_require__(5331); const telemetry = __webpack_require__(1818); const persistentState_1 = __webpack_require__(1102); const settings_1 = __webpack_require__(296); const customProviders_1 = __webpack_require__(4977); const settingsPanel_1 = __webpack_require__(7597); const os = __webpack_require__(2087); const escapeStringRegExp = __webpack_require__(4419); const jsonc = __webpack_require__(634); const nls = __webpack_require__(3612); const timers_1 = __webpack_require__(8213); const which = __webpack_require__(8750); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\configurations.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\configurations.ts')); const configVersion = 4; function getDefaultConfig() { if (process.platform === 'darwin') { return { name: "Mac" }; } else if (process.platform === 'win32') { return { name: "Win32" }; } else { return { name: "Linux" }; } } function getDefaultCppProperties() { return { configurations: [getDefaultConfig()], version: configVersion }; } class CppProperties { constructor(rootUri, workspaceFolder) { this.propertiesFile = undefined; this.configFileWatcher = null; this.configFileWatcherFallbackTime = new Date(); this.compileCommandsFile = undefined; this.compileCommandsFileWatchers = []; this.compileCommandsFileWatcherFallbackTime = new Date(); this.defaultCompilerPath = null; this.defaultCStandard = null; this.defaultCppStandard = null; this.defaultIncludes = null; this.defaultWindowsSdkVersion = null; this.vcpkgIncludes = []; this.vcpkgPathReady = false; this.nodeAddonIncludes = []; this.configurationGlobPattern = "c_cpp_properties.json"; this.disposables = []; this.configurationsChanged = new vscode.EventEmitter(); this.selectionChanged = new vscode.EventEmitter(); this.compileCommandsChanged = new vscode.EventEmitter(); this.prevSquiggleMetrics = new Map(); this.rootfs = null; this.configurationIncomplete = true; this.compileCommandsFileWatcherFiles = new Set(); this.rootUri = rootUri; const rootPath = rootUri ? rootUri.fsPath : ""; if (workspaceFolder) { this.currentConfigurationIndex = new persistentState_1.PersistentFolderState("CppProperties.currentConfigurationIndex", -1, workspaceFolder); this.lastCustomBrowseConfiguration = new persistentState_1.PersistentFolderState("CPP.lastCustomBrowseConfiguration", undefined, workspaceFolder); this.lastCustomBrowseConfigurationProviderId = new persistentState_1.PersistentFolderState("CPP.lastCustomBrowseConfigurationProviderId", undefined, workspaceFolder); } this.configFolder = path.join(rootPath, ".vscode"); this.diagnosticCollection = vscode.languages.createDiagnosticCollection(rootPath); this.buildVcpkgIncludePath(); const userSettings = new settings_1.CppSettings(); if (userSettings.addNodeAddonIncludePaths) { this.readNodeAddonIncludeLocations(rootPath); } this.disposables.push(vscode.Disposable.from(this.configurationsChanged, this.selectionChanged, this.compileCommandsChanged)); } get ConfigurationsChanged() { return this.configurationsChanged.event; } get SelectionChanged() { return this.selectionChanged.event; } get CompileCommandsChanged() { return this.compileCommandsChanged.event; } get Configurations() { return this.configurationJson ? this.configurationJson.configurations : undefined; } get CurrentConfigurationIndex() { return this.currentConfigurationIndex === undefined ? 0 : this.currentConfigurationIndex.Value; } get CurrentConfiguration() { return this.Configurations ? this.Configurations[this.CurrentConfigurationIndex] : undefined; } get KnownCompiler() { return this.knownCompilers; } get LastCustomBrowseConfiguration() { return this.lastCustomBrowseConfiguration; } get LastCustomBrowseConfigurationProviderId() { return this.lastCustomBrowseConfigurationProviderId; } get CurrentConfigurationProvider() { var _a; if ((_a = this.CurrentConfiguration) === null || _a === void 0 ? void 0 : _a.configurationProvider) { return this.CurrentConfiguration.configurationProvider; } return new settings_1.CppSettings(this.rootUri).defaultConfigurationProvider; } get ConfigurationNames() { const result = []; if (this.configurationJson) { this.configurationJson.configurations.forEach((config) => { result.push(config.name); }); } return result; } set CompilerDefaults(compilerDefaults) { this.defaultCompilerPath = compilerDefaults.compilerPath; this.knownCompilers = compilerDefaults.knownCompilers; this.defaultCStandard = compilerDefaults.cStandard; this.defaultCppStandard = compilerDefaults.cppStandard; this.defaultIncludes = compilerDefaults.includes; this.defaultFrameworks = compilerDefaults.frameworks; this.defaultWindowsSdkVersion = compilerDefaults.windowsSdkVersion; this.defaultIntelliSenseMode = compilerDefaults.intelliSenseMode; this.rootfs = compilerDefaults.rootfs; const configFilePath = path.join(this.configFolder, "c_cpp_properties.json"); if (this.rootUri !== null && fs.existsSync(configFilePath)) { this.propertiesFile = vscode.Uri.file(configFilePath); } else { this.propertiesFile = null; } const settingsPath = path.join(this.configFolder, this.configurationGlobPattern); this.configFileWatcher = vscode.workspace.createFileSystemWatcher(settingsPath); this.disposables.push(this.configFileWatcher); this.configFileWatcher.onDidCreate((uri) => { this.propertiesFile = uri; this.handleConfigurationChange(); }); this.configFileWatcher.onDidDelete(() => { this.propertiesFile = null; this.resetToDefaultSettings(true); this.handleConfigurationChange(); }); this.configFileWatcher.onDidChange(() => { let alreadyTracking = false; for (let i = 0; i < vscode.workspace.textDocuments.length; i++) { if (vscode.workspace.textDocuments[i].uri.fsPath === settingsPath) { alreadyTracking = true; break; } } if (!alreadyTracking) { this.handleConfigurationChange(); } }); vscode.workspace.onDidChangeTextDocument((e) => { if (e.document.uri.fsPath === settingsPath) { this.handleConfigurationChange(); } }); vscode.workspace.onDidSaveTextDocument((doc) => { const savedDocWorkspaceFolder = vscode.workspace.getWorkspaceFolder(doc.uri); const notifyingWorkspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(settingsPath)); if ((!savedDocWorkspaceFolder && vscode.workspace.workspaceFolders && notifyingWorkspaceFolder === vscode.workspace.workspaceFolders[0]) || savedDocWorkspaceFolder === notifyingWorkspaceFolder) { let fileType; const documentPath = doc.uri.fsPath.toLowerCase(); if (documentPath.endsWith("cmakelists.txt")) { fileType = "CMakeLists"; } else if (documentPath.endsWith("cmakecache.txt")) { fileType = "CMakeCache"; } else if (documentPath.endsWith(".cmake")) { fileType = ".cmake"; } if (fileType) { telemetry.logLanguageServerEvent("cmakeFileWrite", { filetype: fileType, outside: (savedDocWorkspaceFolder === undefined).toString() }); } } }); this.handleConfigurationChange(); } get VcpkgInstalled() { return this.vcpkgIncludes.length > 0; } onConfigurationsChanged() { if (this.Configurations) { this.configurationsChanged.fire(this); } } onSelectionChanged() { this.selectionChanged.fire(this.CurrentConfigurationIndex); this.handleSquiggles(); } onCompileCommandsChanged(path) { this.compileCommandsChanged.fire(path); } onDidChangeSettings() { if (!this.propertiesFile) { this.resetToDefaultSettings(true); this.handleConfigurationChange(); } else if (!this.configurationIncomplete) { this.handleConfigurationChange(); } } resetToDefaultSettings(resetIndex) { this.configurationJson = getDefaultCppProperties(); if (resetIndex || this.CurrentConfigurationIndex < 0 || this.CurrentConfigurationIndex >= this.configurationJson.configurations.length) { const index = this.getConfigIndexForPlatform(this.configurationJson); if (this.currentConfigurationIndex !== undefined) { if (index === undefined) { this.currentConfigurationIndex.setDefault(); } else { this.currentConfigurationIndex.Value = index; } } } this.configurationIncomplete = true; } applyDefaultIncludePathsAndFrameworks() { if (this.configurationIncomplete && this.defaultIncludes && this.defaultFrameworks && this.vcpkgPathReady) { const configuration = this.CurrentConfiguration; if (configuration) { this.applyDefaultConfigurationValues(configuration); this.configurationIncomplete = false; } } } applyDefaultConfigurationValues(configuration) { const settings = new settings_1.CppSettings(this.rootUri); const isUnset = (input) => input === null || input === undefined; const rootFolder = "${workspaceFolder}/**"; const defaultFolder = "${default}"; if (isUnset(settings.defaultIncludePath)) { configuration.includePath = [rootFolder].concat(this.vcpkgIncludes); } else { configuration.includePath = [defaultFolder]; } if (isUnset(settings.defaultDefines)) { configuration.defines = (process.platform === 'win32') ? ["_DEBUG", "UNICODE", "_UNICODE"] : []; } if (isUnset(settings.defaultMacFrameworkPath) && process.platform === 'darwin') { configuration.macFrameworkPath = this.defaultFrameworks; } if ((isUnset(settings.defaultWindowsSdkVersion) || settings.defaultWindowsSdkVersion === "") && this.defaultWindowsSdkVersion && process.platform === 'win32') { configuration.windowsSdkVersion = this.defaultWindowsSdkVersion; } if (isUnset(settings.defaultCompilerPath) && this.defaultCompilerPath && (isUnset(settings.defaultCompileCommands) || settings.defaultCompileCommands === "") && !configuration.compileCommands) { configuration.compilerPath = this.defaultCompilerPath; } if ((isUnset(settings.defaultCStandard) || settings.defaultCStandard === "") && this.defaultCStandard) { configuration.cStandard = this.defaultCStandard; } if ((isUnset(settings.defaultCppStandard) || settings.defaultCppStandard === "") && this.defaultCppStandard) { configuration.cppStandard = this.defaultCppStandard; } if (isUnset(settings.defaultIntelliSenseMode) || settings.defaultIntelliSenseMode === "") { configuration.intelliSenseMode = this.defaultIntelliSenseMode; } if (isUnset(settings.defaultCustomConfigurationVariables) || settings.defaultCustomConfigurationVariables === {}) { configuration.customConfigurationVariables = this.defaultCustomConfigurationVariables; } } get ExtendedEnvironment() { var _a; const result = {}; if ((_a = this.configurationJson) === null || _a === void 0 ? void 0 : _a.env) { Object.assign(result, this.configurationJson.env); } result["workspaceFolderBasename"] = this.rootUri ? path.basename(this.rootUri.fsPath) : ""; return result; } buildVcpkgIncludePath() { return __awaiter(this, void 0, void 0, function* () { try { const vcpkgRoot = util.getVcpkgRoot(); if (vcpkgRoot) { const list = yield util.readDir(vcpkgRoot); if (list !== undefined) { list.forEach((entry) => { if (entry !== "vcpkg") { const pathToCheck = path.join(vcpkgRoot, entry); if (fs.existsSync(pathToCheck)) { let p = path.join(pathToCheck, "include"); if (fs.existsSync(p)) { p = p.replace(/\\/g, "/"); p = p.replace(vcpkgRoot, "${vcpkgRoot}"); this.vcpkgIncludes.push(p); } } } }); } } } catch (error) { } finally { this.vcpkgPathReady = true; this.handleConfigurationChange(); } }); } nodeAddonIncludesFound() { return this.nodeAddonIncludes.length; } readNodeAddonIncludeLocations(rootPath) { return __awaiter(this, void 0, void 0, function* () { let error; let pdjFound = false; let packageJson; try { packageJson = JSON.parse(yield fs.promises.readFile(path.join(rootPath, "package.json"), "utf8")); pdjFound = true; } catch (err) { error = err; } if (!error) { try { const pathToNode = which.sync("node"); const nodeAddonMap = [ ["node-addon-api", `"${pathToNode}" --no-warnings -p "require('node-addon-api').include"`], ["nan", `"${pathToNode}" --no-warnings -e "require('nan')"`] ]; const pathToYarn = which.sync("yarn", { nothrow: true }); if (pathToYarn && (yield util.checkDirectoryExists(path.join(rootPath, ".yarn/cache")))) { nodeAddonMap.push(["node-addon-api", `"${pathToYarn}" node --no-warnings -p "require('node-addon-api').include"`], ["nan", `"${pathToYarn}" node --no-warnings -e "require('nan')"`]); } for (const [dep, execCmd] of nodeAddonMap) { if (dep in packageJson.dependencies) { try { let stdout = yield util.execChildProcess(execCmd, rootPath); if (!stdout) { continue; } if (stdout[stdout.length - 1] === "\n") { stdout = stdout.slice(0, -1); } if (stdout[0] === "\"" && stdout[stdout.length - 1] === "\"") { stdout = stdout.slice(1, -1); } if (!(yield util.checkDirectoryExists(stdout))) { stdout = path.join(rootPath, stdout); if (!(yield util.checkDirectoryExists(stdout))) { error = new Error(`${dep} directory ${stdout} doesn't exist`); stdout = ''; } } if (stdout) { this.nodeAddonIncludes.push(stdout); } } catch (err) { console.log('readNodeAddonIncludeLocations', err.message); } } } } catch (e) { error = e; } } if (error) { if (pdjFound) { console.log('readNodeAddonIncludeLocations', error.message); } } else { this.handleConfigurationChange(); } }); } getConfigIndexForPlatform(config) { if (!this.configurationJson) { return undefined; } let plat; if (process.platform === 'darwin') { plat = "Mac"; } else if (process.platform === 'win32') { plat = "Win32"; } else { plat = "Linux"; } for (let i = 0; i < this.configurationJson.configurations.length; i++) { if (config.configurations[i].name === plat) { return i; } } return this.configurationJson.configurations.length - 1; } getIntelliSenseModeForPlatform(name) { if (name === "Linux") { return "linux-gcc-x64"; } else if (name === "Mac") { return "macos-clang-x64"; } else if (name === "Win32") { return "windows-msvc-x64"; } else if (process.platform === 'win32') { return "windows-msvc-x64"; } else if (process.platform === 'darwin') { return "macos-clang-x64"; } else { return "linux-gcc-x64"; } } validateIntelliSenseMode(configuration) { if (configuration.compilerPath === undefined || configuration.compilerPath === "" || configuration.compilerPath === "${default}" || configuration.intelliSenseMode === undefined || configuration.intelliSenseMode === "" || configuration.intelliSenseMode === "${default}") { return ""; } const resolvedCompilerPath = this.resolvePath(configuration.compilerPath, true); const compilerPathAndArgs = util.extractCompilerPathAndArgs(resolvedCompilerPath); const isValid = ((compilerPathAndArgs.compilerName.toLowerCase() === "cl.exe" || compilerPathAndArgs.compilerName.toLowerCase() === "cl") === configuration.intelliSenseMode.includes("msvc") || (compilerPathAndArgs.compilerName.toLowerCase() === "nvcc.exe") || (compilerPathAndArgs.compilerName.toLowerCase() === "nvcc")); if (isValid) { return ""; } else { return localize(0, null, configuration.intelliSenseMode); } } addToIncludePathCommand(path) { this.handleConfigurationEditCommand(() => { this.parsePropertiesFile(); const config = this.CurrentConfiguration; if (config) { telemetry.logLanguageServerEvent("addToIncludePath"); if (config.includePath === undefined) { config.includePath = ["${default}"]; } config.includePath.splice(config.includePath.length, 0, path); this.writeToJson(); this.handleConfigurationChange(); } }, () => { }); } updateCustomConfigurationProvider(providerId) { return new Promise((resolve) => { if (this.propertiesFile) { this.handleConfigurationEditJSONCommand(() => { this.parsePropertiesFile(); const config = this.CurrentConfiguration; if (config) { if (providerId) { config.configurationProvider = providerId; } else { delete config.configurationProvider; } this.writeToJson(); this.handleConfigurationChange(); } resolve(); }, () => { }); } else { const settings = new settings_1.CppSettings(this.rootUri); if (providerId) { settings.update("default.configurationProvider", providerId); } else { settings.update("default.configurationProvider", undefined); } const config = this.CurrentConfiguration; if (config) { config.configurationProvider = providerId; } resolve(); } }); } setCompileCommands(path) { this.handleConfigurationEditJSONCommand(() => { this.parsePropertiesFile(); const config = this.CurrentConfiguration; if (config) { config.compileCommands = path; this.writeToJson(); this.handleConfigurationChange(); } }, () => { }); } select(index) { if (this.configurationJson) { if (index === this.configurationJson.configurations.length) { this.handleConfigurationEditUICommand(() => { }, vscode.window.showTextDocument); return; } if (index === this.configurationJson.configurations.length + 1) { this.handleConfigurationEditJSONCommand(() => { }, vscode.window.showTextDocument); return; } } if (this.currentConfigurationIndex !== undefined) { this.currentConfigurationIndex.Value = index; } this.onSelectionChanged(); } resolveDefaults(entries, defaultValue) { let result = []; entries.forEach(entry => { if (entry === "${default}") { if (defaultValue) { result = result.concat(defaultValue); } } else { result.push(entry); } }); return result; } resolveDefaultsDictionary(entries, defaultValue, env) { const result = {}; for (const property in entries) { if (property === "${default}") { if (defaultValue) { for (const defaultProperty in defaultValue) { if (!(defaultProperty in entries)) { result[defaultProperty] = util.resolveVariables(defaultValue[defaultProperty], env); } } } } else { result[property] = util.resolveVariables(entries[property], env); } } return result; } resolveAndSplit(paths, defaultValue, env) { let result = []; if (paths) { paths = this.resolveDefaults(paths, defaultValue); paths.forEach(entry => { const entries = util.resolveVariables(entry, env).split(util.envDelimiter).filter(e => e); result = result.concat(entries); }); } return result; } updateConfigurationString(property, defaultValue, env, acceptBlank) { if (property === null || property === undefined || property === "${default}") { property = defaultValue; } if (property === null || property === undefined || (acceptBlank !== true && property === "")) { return undefined; } return util.resolveVariables(property, env); } updateConfigurationStringArray(property, defaultValue, env) { if (property) { return this.resolveAndSplit(property, defaultValue, env); } if (!property && defaultValue) { return this.resolveAndSplit(defaultValue, [], env); } return property; } updateConfigurationStringOrBoolean(property, defaultValue, env) { if (!property || property === "${default}") { property = defaultValue; } if (!property || property === "") { return undefined; } if (typeof property === "boolean") { return property; } return util.resolveVariables(property, env); } updateConfigurationStringDictionary(property, defaultValue, env) { if (!property || property === {}) { property = defaultValue; } if (!property || property === {}) { return undefined; } return this.resolveDefaultsDictionary(property, defaultValue, env); } updateServerOnFolderSettingsChange() { if (!this.configurationJson) { return; } const settings = new settings_1.CppSettings(this.rootUri); const userSettings = new settings_1.CppSettings(); const env = this.ExtendedEnvironment; for (let i = 0; i < this.configurationJson.configurations.length; i++) { const configuration = this.configurationJson.configurations[i]; configuration.includePath = this.updateConfigurationStringArray(configuration.includePath, settings.defaultIncludePath, env); const origIncludePath = configuration.includePath; if (userSettings.addNodeAddonIncludePaths) { const includePath = origIncludePath || []; configuration.includePath = includePath.concat(this.nodeAddonIncludes.filter(i => includePath.indexOf(i) < 0)); } configuration.defines = this.updateConfigurationStringArray(configuration.defines, settings.defaultDefines, env); configuration.macFrameworkPath = this.updateConfigurationStringArray(configuration.macFrameworkPath, settings.defaultMacFrameworkPath, env); configuration.windowsSdkVersion = this.updateConfigurationString(configuration.windowsSdkVersion, settings.defaultWindowsSdkVersion, env); configuration.forcedInclude = this.updateConfigurationStringArray(configuration.forcedInclude, settings.defaultForcedInclude, env); configuration.compileCommands = this.updateConfigurationString(configuration.compileCommands, settings.defaultCompileCommands, env); configuration.compilerArgs = this.updateConfigurationStringArray(configuration.compilerArgs, settings.defaultCompilerArgs, env); configuration.cStandard = this.updateConfigurationString(configuration.cStandard, settings.defaultCStandard, env); configuration.cppStandard = this.updateConfigurationString(configuration.cppStandard, settings.defaultCppStandard, env); configuration.intelliSenseMode = this.updateConfigurationString(configuration.intelliSenseMode, settings.defaultIntelliSenseMode, env); configuration.intelliSenseModeIsExplicit = configuration.intelliSenseModeIsExplicit || settings.defaultIntelliSenseMode !== ""; configuration.cStandardIsExplicit = configuration.cStandardIsExplicit || settings.defaultCStandard !== ""; configuration.cppStandardIsExplicit = configuration.cppStandardIsExplicit || settings.defaultCppStandard !== ""; configuration.compilerPathIsExplicit = false; if (!configuration.compileCommands) { configuration.compilerPath = this.updateConfigurationString(configuration.compilerPath, settings.defaultCompilerPath, env, true); configuration.compilerPathIsExplicit = configuration.compilerPath !== undefined; if (configuration.compilerPath === undefined) { if (!!this.defaultCompilerPath) { configuration.compilerPath = this.defaultCompilerPath; if (!configuration.cStandard && !!this.defaultCStandard) { configuration.cStandard = this.defaultCStandard; configuration.cStandardIsExplicit = false; } if (!configuration.cppStandard && !!this.defaultCppStandard) { configuration.cppStandard = this.defaultCppStandard; configuration.cppStandardIsExplicit = false; } if (!configuration.intelliSenseMode && !!this.defaultIntelliSenseMode) { configuration.intelliSenseMode = this.defaultIntelliSenseMode; configuration.intelliSenseModeIsExplicit = false; } if (!configuration.windowsSdkVersion && !!this.defaultWindowsSdkVersion) { configuration.windowsSdkVersion = this.defaultWindowsSdkVersion; } if (!origIncludePath && !!this.defaultIncludes) { const includePath = configuration.includePath || []; configuration.includePath = includePath.concat(this.defaultIncludes); } if (!configuration.macFrameworkPath && !!this.defaultFrameworks) { configuration.macFrameworkPath = this.defaultFrameworks; } } } } else { if (configuration.compilerPath === "${default}") { configuration.compilerPath = settings.defaultCompilerPath; } if (configuration.compilerPath === null) { configuration.compilerPath = undefined; configuration.compilerPathIsExplicit = true; } else if (configuration.compilerPath !== undefined) { configuration.compilerPath = util.resolveVariables(configuration.compilerPath, env); configuration.compilerPathIsExplicit = true; } } configuration.customConfigurationVariables = this.updateConfigurationStringDictionary(configuration.customConfigurationVariables, settings.defaultCustomConfigurationVariables, env); configuration.configurationProvider = this.updateConfigurationString(configuration.configurationProvider, settings.defaultConfigurationProvider, env); if (!configuration.browse) { configuration.browse = {}; } if (!configuration.browse.path) { if (settings.defaultBrowsePath) { configuration.browse.path = settings.defaultBrowsePath; } else if (configuration.includePath) { configuration.browse.path = configuration.includePath.slice(0); if (configuration.includePath.findIndex((value, index) => !!value.match(/^\$\{(workspaceRoot|workspaceFolder)\}(\\\*{0,2}|\/\*{0,2})?$/g)) === -1) { configuration.browse.path.push("${workspaceFolder}"); } } } else { configuration.browse.path = this.updateConfigurationStringArray(configuration.browse.path, settings.defaultBrowsePath, env); } configuration.browse.limitSymbolsToIncludedHeaders = this.updateConfigurationStringOrBoolean(configuration.browse.limitSymbolsToIncludedHeaders, settings.defaultLimitSymbolsToIncludedHeaders, env); configuration.browse.databaseFilename = this.updateConfigurationString(configuration.browse.databaseFilename, settings.defaultDatabaseFilename, env); if (i === this.CurrentConfigurationIndex) { const providers = customProviders_1.getCustomConfigProviders(); const hasEmptyConfiguration = !this.propertiesFile && !settings.defaultCompilerPath && settings.defaultCompilerPath !== "" && !settings.defaultIncludePath && !settings.defaultDefines && !settings.defaultMacFrameworkPath && settings.defaultWindowsSdkVersion === "" && !settings.defaultForcedInclude && settings.defaultCompileCommands === "" && !settings.defaultCompilerArgs && settings.defaultCStandard === "" && settings.defaultCppStandard === "" && settings.defaultIntelliSenseMode === "" && settings.defaultConfigurationProvider === ""; let keepCachedBrowseConfig = true; if (hasEmptyConfiguration) { if (providers.size === 1) { providers.forEach(provider => { configuration.configurationProvider = provider.extensionId; }); if (this.lastCustomBrowseConfigurationProviderId !== undefined) { keepCachedBrowseConfig = configuration.configurationProvider === this.lastCustomBrowseConfigurationProviderId.Value; } } else if (this.lastCustomBrowseConfigurationProviderId !== undefined && !!this.lastCustomBrowseConfigurationProviderId.Value) { configuration.configurationProvider = this.lastCustomBrowseConfigurationProviderId.Value; } } else if (this.lastCustomBrowseConfigurationProviderId !== undefined) { keepCachedBrowseConfig = configuration.configurationProvider === this.lastCustomBrowseConfigurationProviderId.Value; } if (!keepCachedBrowseConfig && this.lastCustomBrowseConfiguration !== undefined) { this.lastCustomBrowseConfiguration.Value = undefined; } } } this.updateCompileCommandsFileWatchers(); if (!this.configurationIncomplete) { this.onConfigurationsChanged(); } } updateCompileCommandsFileWatchers() { if (this.configurationJson) { this.compileCommandsFileWatchers.forEach((watcher) => watcher.close()); this.compileCommandsFileWatchers = []; const filePaths = new Set(); this.configurationJson.configurations.forEach(c => { if (c.compileCommands) { const fileSystemCompileCommandsPath = this.resolvePath(c.compileCommands, os.platform() === "win32"); if (fs.existsSync(fileSystemCompileCommandsPath)) { filePaths.add(fileSystemCompileCommandsPath); } } }); try { filePaths.forEach((path) => { this.compileCommandsFileWatchers.push(fs.watch(path, (event, filename) => { if (this.compileCommandsFileWatcherTimer) { clearInterval(this.compileCommandsFileWatcherTimer); } this.compileCommandsFileWatcherFiles.add(path); this.compileCommandsFileWatcherTimer = timers_1.setTimeout(() => { this.compileCommandsFileWatcherFiles.forEach((path) => { this.onCompileCommandsChanged(path); }); if (this.compileCommandsFileWatcherTimer) { clearInterval(this.compileCommandsFileWatcherTimer); } this.compileCommandsFileWatcherFiles.clear(); this.compileCommandsFileWatcherTimer = undefined; }, 1000); })); }); } catch (e) { } } } handleConfigurationEditCommand(onBeforeOpen, showDocument, viewColumn) { const otherSettings = new settings_1.OtherSettings(this.rootUri); if (otherSettings.settingsEditor === "ui") { this.handleConfigurationEditUICommand(onBeforeOpen, showDocument, viewColumn); } else { this.handleConfigurationEditJSONCommand(onBeforeOpen, showDocument, viewColumn); } } handleConfigurationEditJSONCommand(onBeforeOpen, showDocument, viewColumn) { return __awaiter(this, void 0, void 0, function* () { yield this.ensurePropertiesFile(); console.assert(this.propertiesFile); if (onBeforeOpen) { onBeforeOpen(); } if (this.propertiesFile) { const document = yield vscode.workspace.openTextDocument(this.propertiesFile); if (showDocument) { showDocument(document, viewColumn); } } }); } ensureSettingsPanelInitlialized() { if (this.settingsPanel === undefined) { const settings = new settings_1.CppSettings(this.rootUri); this.settingsPanel = new settingsPanel_1.SettingsPanel(); this.settingsPanel.setKnownCompilers(this.knownCompilers, settings.preferredPathSeparator); this.settingsPanel.SettingsPanelActivated(() => { var _a; if ((_a = this.settingsPanel) === null || _a === void 0 ? void 0 : _a.initialized) { this.onSettingsPanelActivated(); } }); this.settingsPanel.ConfigValuesChanged(() => this.saveConfigurationUI()); this.settingsPanel.ConfigSelectionChanged(() => this.onConfigSelectionChanged()); this.settingsPanel.AddConfigRequested((e) => this.onAddConfigRequested(e)); this.disposables.push(this.settingsPanel); } } handleConfigurationEditUICommand(onBeforeOpen, showDocument, viewColumn) { return __awaiter(this, void 0, void 0, function* () { yield this.ensurePropertiesFile(); if (this.propertiesFile) { if (onBeforeOpen) { onBeforeOpen(); } if (this.parsePropertiesFile()) { this.ensureSettingsPanelInitlialized(); if (this.settingsPanel) { const configNames = this.ConfigurationNames; if (configNames && this.configurationJson) { this.settingsPanel.selectedConfigIndex = this.CurrentConfigurationIndex; this.settingsPanel.createOrShow(configNames, this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex], this.getErrorsForConfigUI(this.settingsPanel.selectedConfigIndex), viewColumn); } } } else { const document = yield vscode.workspace.openTextDocument(this.propertiesFile); if (showDocument) { showDocument(document, viewColumn); } } } }); } onSettingsPanelActivated() { return __awaiter(this, void 0, void 0, function* () { if (this.configurationJson) { yield this.ensurePropertiesFile(); if (this.propertiesFile) { if (this.parsePropertiesFile()) { const configNames = this.ConfigurationNames; if (configNames && this.settingsPanel && this.configurationJson) { if (this.settingsPanel.selectedConfigIndex >= this.configurationJson.configurations.length) { this.settingsPanel.selectedConfigIndex = this.CurrentConfigurationIndex; } this.settingsPanel.updateConfigUI(configNames, this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex], this.getErrorsForConfigUI(this.settingsPanel.selectedConfigIndex)); } else { vscode.workspace.openTextDocument(this.propertiesFile); } } } } }); } saveConfigurationUI() { this.parsePropertiesFile(); if (this.settingsPanel && this.configurationJson) { const config = this.settingsPanel.getLastValuesFromConfigUI(); this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex] = config; this.settingsPanel.updateErrors(this.getErrorsForConfigUI(this.settingsPanel.selectedConfigIndex)); this.writeToJson(); } } onConfigSelectionChanged() { const configNames = this.ConfigurationNames; if (configNames && this.settingsPanel && this.configurationJson) { this.settingsPanel.updateConfigUI(configNames, this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex], this.getErrorsForConfigUI(this.settingsPanel.selectedConfigIndex)); } } onAddConfigRequested(configName) { this.parsePropertiesFile(); const newConfig = { name: configName }; this.applyDefaultConfigurationValues(newConfig); const configNames = this.ConfigurationNames; if (configNames && this.settingsPanel && this.configurationJson) { this.configurationJson.configurations.push(newConfig); this.settingsPanel.selectedConfigIndex = this.configurationJson.configurations.length - 1; this.settingsPanel.updateConfigUI(configNames, this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex], null); this.writeToJson(); } } handleConfigurationChange() { if (this.propertiesFile === undefined) { return; } this.configFileWatcherFallbackTime = new Date(); if (this.propertiesFile) { this.parsePropertiesFile(); if (this.configurationJson) { if (this.CurrentConfigurationIndex < 0 || this.CurrentConfigurationIndex >= this.configurationJson.configurations.length) { const index = this.getConfigIndexForPlatform(this.configurationJson); if (this.currentConfigurationIndex !== undefined) { if (!index) { this.currentConfigurationIndex.setDefault(); } else { this.currentConfigurationIndex.Value = index; } } } } } if (!this.configurationJson) { this.resetToDefaultSettings(true); } this.applyDefaultIncludePathsAndFrameworks(); this.updateServerOnFolderSettingsChange(); } ensurePropertiesFile() { return __awaiter(this, void 0, void 0, function* () { if (this.propertiesFile && (yield util.checkFileExists(this.propertiesFile.fsPath))) { return; } else { try { if (!(yield util.checkDirectoryExists(this.configFolder))) { fs.mkdirSync(this.configFolder); } const fullPathToFile = path.join(this.configFolder, "c_cpp_properties.json"); const settings = new settings_1.CppSettings(this.rootUri); let providerId = settings.defaultConfigurationProvider; if (this.configurationJson) { if (!providerId) { providerId = this.configurationJson.configurations[0].configurationProvider; } this.resetToDefaultSettings(true); } this.applyDefaultIncludePathsAndFrameworks(); if (providerId) { if (this.configurationJson) { this.configurationJson.configurations[0].configurationProvider = providerId; } } yield util.writeFileText(fullPathToFile, jsonc.stringify(this.configurationJson, null, 4)); this.propertiesFile = vscode.Uri.file(path.join(this.configFolder, "c_cpp_properties.json")); } catch (err) { const failedToCreate = localize(1, null, this.configFolder); vscode.window.showErrorMessage(`${failedToCreate}: ${err.message}`); } } return; }); } parsePropertiesFile() { if (!this.propertiesFile) { return false; } let success = true; try { const readResults = fs.readFileSync(this.propertiesFile.fsPath, 'utf8'); if (readResults === "") { return false; } const newJson = jsonc.parse(readResults); if (!newJson || !newJson.configurations || newJson.configurations.length === 0) { throw { message: localize(2, null) }; } if (!this.configurationIncomplete && this.configurationJson && this.configurationJson.configurations && this.CurrentConfigurationIndex >= 0 && this.CurrentConfigurationIndex < this.configurationJson.configurations.length) { for (let i = 0; i < newJson.configurations.length; i++) { if (newJson.configurations[i].name === this.configurationJson.configurations[this.CurrentConfigurationIndex].name) { if (this.currentConfigurationIndex !== undefined) { this.currentConfigurationIndex.Value = i; } break; } } } this.configurationJson = newJson; if (this.CurrentConfigurationIndex < 0 || this.CurrentConfigurationIndex >= newJson.configurations.length) { const index = this.getConfigIndexForPlatform(newJson); if (this.currentConfigurationIndex !== undefined) { if (index === undefined) { this.currentConfigurationIndex.setDefault(); } else { this.currentConfigurationIndex.Value = index; } } } let dirty = false; for (let i = 0; i < this.configurationJson.configurations.length; i++) { const newId = customProviders_1.getCustomConfigProviders().checkId(this.configurationJson.configurations[i].configurationProvider); if (newId !== this.configurationJson.configurations[i].configurationProvider) { dirty = true; this.configurationJson.configurations[i].configurationProvider = newId; } } if (this.configurationJson.env) { delete this.configurationJson.env['workspaceRoot']; delete this.configurationJson.env['workspaceFolder']; delete this.configurationJson.env['workspaceFolderBasename']; delete this.configurationJson.env['default']; } this.configurationIncomplete = false; if (this.configurationJson.version !== configVersion) { dirty = true; if (this.configurationJson.version === undefined) { this.updateToVersion2(); } if (this.configurationJson.version === 2) { this.updateToVersion3(); } if (this.configurationJson.version === 3) { this.updateToVersion4(); } else { this.configurationJson.version = configVersion; vscode.window.showErrorMessage(localize(3, null)); } } this.configurationJson.configurations.forEach(e => { if (e.knownCompilers !== undefined) { delete e.knownCompilers; dirty = true; } }); for (let i = 0; i < this.configurationJson.configurations.length; i++) { if ((this.configurationJson.configurations[i].compilerPathIsExplicit !== undefined) || (this.configurationJson.configurations[i].cStandardIsExplicit !== undefined) || (this.configurationJson.configurations[i].cppStandardIsExplicit !== undefined) || (this.configurationJson.configurations[i].intelliSenseModeIsExplicit !== undefined)) { dirty = true; break; } } if (dirty) { try { this.writeToJson(); } catch (err) { vscode.window.showWarningMessage(localize(4, null, this.propertiesFile.fsPath)); success = false; } } this.configurationJson.configurations.forEach(e => { e.compilerPathIsExplicit = e.compilerPath !== undefined; e.cStandardIsExplicit = e.cStandard !== undefined; e.cppStandardIsExplicit = e.cppStandard !== undefined; e.intelliSenseModeIsExplicit = e.intelliSenseMode !== undefined; }); } catch (err) { const failedToParse = localize(5, null, this.propertiesFile.fsPath); vscode.window.showErrorMessage(`${failedToParse}: ${err.message}`); success = false; } if (success) { this.handleSquiggles(); } return success; } resolvePath(path, isWindows) { if (!path || path === "${default}") { return ""; } let result = ""; result = util.resolveVariables(path, this.ExtendedEnvironment); if (this.rootUri) { if (result.includes("${workspaceFolder}")) { result = result.replace("${workspaceFolder}", this.rootUri.fsPath); } if (result.includes("${workspaceRoot}")) { result = result.replace("${workspaceRoot}", this.rootUri.fsPath); } } if (result.includes("${vcpkgRoot}") && util.getVcpkgRoot()) { result = result.replace("${vcpkgRoot}", util.getVcpkgRoot()); } if (result.includes("*")) { result = result.replace(/\*/g, ""); } if (isWindows && result.startsWith("/")) { const mntStr = "/mnt/"; if (result.length > "/mnt/c/".length && result.substr(0, mntStr.length) === mntStr) { result = result.substr(mntStr.length); result = result.substr(0, 1) + ":" + result.substr(1); } else if (this.rootfs && this.rootfs.length > 0) { result = this.rootfs + result.substr(1); } } return result; } getErrorsForConfigUI(configIndex) { const errors = {}; if (!this.configurationJson) { return errors; } const isWindows = os.platform() === 'win32'; const config = this.configurationJson.configurations[configIndex]; errors.name = this.isConfigNameUnique(config.name); let resolvedCompilerPath = this.resolvePath(config.compilerPath, isWindows); const compilerPathAndArgs = util.extractCompilerPathAndArgs(resolvedCompilerPath); if (resolvedCompilerPath && compilerPathAndArgs.compilerName.toLowerCase() !== "cl.exe" && compilerPathAndArgs.compilerName.toLowerCase() !== "cl") { resolvedCompilerPath = resolvedCompilerPath.trim(); const compilerPathNeedsQuotes = (compilerPathAndArgs.additionalArgs && compilerPathAndArgs.additionalArgs.length > 0) && !resolvedCompilerPath.startsWith('"') && compilerPathAndArgs.compilerPath !== undefined && compilerPathAndArgs.compilerPath.includes(" "); const compilerPathErrors = []; if (compilerPathNeedsQuotes) { compilerPathErrors.push(localize(6, null)); } resolvedCompilerPath = compilerPathAndArgs.compilerPath; if (resolvedCompilerPath) { let pathExists = true; const existsWithExeAdded = (path) => isWindows && !path.startsWith("/") && fs.existsSync(path + ".exe"); if (!fs.existsSync(resolvedCompilerPath)) { if (existsWithExeAdded(resolvedCompilerPath)) { resolvedCompilerPath += ".exe"; } else if (!this.rootUri) { pathExists = false; } else { const relativePath = this.rootUri.fsPath + path.sep + resolvedCompilerPath; if (!fs.existsSync(relativePath)) { if (existsWithExeAdded(resolvedCompilerPath)) { resolvedCompilerPath += ".exe"; } else { pathExists = false; } } else { resolvedCompilerPath = relativePath; } } } if (!pathExists) { const message = localize(7, null, resolvedCompilerPath); compilerPathErrors.push(message); } else if (compilerPathAndArgs.compilerPath === "") { const message = localize(8, null); compilerPathErrors.push(message); } else if (!util.checkFileExistsSync(resolvedCompilerPath)) { const message = localize(9, null, resolvedCompilerPath); compilerPathErrors.push(message); } if (compilerPathErrors.length > 0) { errors.compilerPath = compilerPathErrors.join('\n'); } } } errors.includePath = this.validatePath(config.includePath); errors.macFrameworkPath = this.validatePath(config.macFrameworkPath); errors.browsePath = this.validatePath(config.browse ? config.browse.path : undefined); errors.forcedInclude = this.validatePath(config.forcedInclude, false); errors.compileCommands = this.validatePath(config.compileCommands, false); errors.databaseFilename = this.validatePath((config.browse ? config.browse.databaseFilename : undefined), false); if (isWindows) { const intelliSenesModeError = this.validateIntelliSenseMode(config); if (intelliSenesModeError.length > 0) { errors.intelliSenseMode = intelliSenesModeError; } } return errors; } validatePath(input, isDirectory = true) { if (!input) { return undefined; } const isWindows = os.platform() === 'win32'; let errorMsg; const errors = []; let paths = []; if (util.isString(input)) { paths.push(input); } else { paths = input; } paths = this.resolveAndSplit(paths, undefined, this.ExtendedEnvironment); for (const p of paths) { let pathExists = true; let resolvedPath = this.resolvePath(p, isWindows); if (!resolvedPath) { continue; } if (!fs.existsSync(resolvedPath)) { if (!this.rootUri) { pathExists = false; } else { const relativePath = this.rootUri.fsPath + path.sep + resolvedPath; if (!fs.existsSync(relativePath)) { pathExists = false; } else { resolvedPath = relativePath; } } } if (!pathExists) { const message = localize(10, null, resolvedPath); errors.push(message); continue; } if (isDirectory && !util.checkDirectoryExistsSync(resolvedPath)) { const message = localize(11, null, resolvedPath); errors.push(message); } else if (!isDirectory && !util.checkFileExistsSync(resolvedPath)) { const message = localize(12, null, resolvedPath); errors.push(message); } } if (errors.length > 0) { errorMsg = errors.join('\n'); } return errorMsg; } isConfigNameUnique(configName) { var _a; let errorMsg; const occurrences = (_a = this.ConfigurationNames) === null || _a === void 0 ? void 0 : _a.filter(function (name) { return name === configName; }).length; if (occurrences && occurrences > 1) { errorMsg = localize(13, null, configName); } return errorMsg; } handleSquiggles() { if (!this.propertiesFile) { return; } const settings = new settings_1.CppSettings(this.rootUri); if (!this.configurationJson) { return; } if ((this.configurationJson.enableConfigurationSquiggles !== undefined && !this.configurationJson.enableConfigurationSquiggles) || (this.configurationJson.enableConfigurationSquiggles === undefined && !settings.defaultEnableConfigurationSquiggles)) { this.diagnosticCollection.clear(); return; } vscode.workspace.openTextDocument(this.propertiesFile).then((document) => { var _a, _b, _c, _d, _e; const diagnostics = new Array(); let curText = document.getText(); const configurationsText = util.escapeForSquiggles(curText); const configurations = jsonc.parse(configurationsText); const currentConfiguration = configurations.configurations[this.CurrentConfigurationIndex]; let curTextStartOffset = 0; if (!currentConfiguration.name) { return; } let envText = ""; const envStart = curText.search(/\"env\"\s*:\s*\{/); const envEnd = envStart === -1 ? -1 : curText.indexOf("},", envStart); envText = curText.substr(envStart, envEnd); const envTextStartOffSet = envStart + 1; let allConfigText = curText; let allConfigTextOffset = envTextStartOffSet; const nameRegex = new RegExp(`{\\s*"name"\\s*:\\s*".*"`); let configStart = allConfigText.search(new RegExp(nameRegex)); let configNameStart; let configNameEnd; let configName; const configNames = new Map(); let dupErrorMsg; while (configStart !== -1) { allConfigText = allConfigText.substr(configStart); allConfigTextOffset += configStart; configNameStart = allConfigText.indexOf('"', allConfigText.indexOf(':') + 1) + 1; configNameEnd = allConfigText.indexOf('"', configNameStart); configName = allConfigText.substr(configNameStart, configNameEnd - configNameStart); const newRange = new vscode.Range(0, allConfigTextOffset + configNameStart, 0, allConfigTextOffset + configNameEnd); const allRanges = configNames.get(configName); if (allRanges) { allRanges.push(newRange); configNames.set(configName, allRanges); } else { configNames.set(configName, [newRange]); } allConfigText = allConfigText.substr(configNameEnd + 1); allConfigTextOffset += configNameEnd + 1; configStart = allConfigText.search(new RegExp(nameRegex)); } for (const [configName, allRanges] of configNames) { if (allRanges && allRanges.length > 1) { dupErrorMsg = localize(14, null, configName); allRanges.forEach(nameRange => { const diagnostic = new vscode.Diagnostic(new vscode.Range(document.positionAt(nameRange.start.character), document.positionAt(nameRange.end.character)), dupErrorMsg, vscode.DiagnosticSeverity.Warning); diagnostics.push(diagnostic); }); } } configStart = curText.search(new RegExp(`{\\s*"name"\\s*:\\s*"${escapeStringRegExp(currentConfiguration.name)}"`)); if (configStart === -1) { telemetry.logLanguageServerEvent("ConfigSquiggles", { "error": "config name not first" }); return; } curTextStartOffset = configStart + 1; curText = curText.substr(curTextStartOffset); const nameEnd = curText.indexOf(":"); curTextStartOffset += nameEnd + 1; curText = curText.substr(nameEnd + 1); const nextNameStart = curText.search(new RegExp('"name"\\s*:\\s*"')); if (nextNameStart !== -1) { curText = curText.substr(0, nextNameStart + 6); const nextNameStart2 = curText.search(new RegExp('\\s*}\\s*,\\s*{\\s*"name"')); if (nextNameStart2 === -1) { telemetry.logLanguageServerEvent("ConfigSquiggles", { "error": "next config name not first" }); return; } curText = curText.substr(0, nextNameStart2); } if (this.prevSquiggleMetrics.get(currentConfiguration.name) === undefined) { this.prevSquiggleMetrics.set(currentConfiguration.name, { PathNonExistent: 0, PathNotAFile: 0, PathNotADirectory: 0, CompilerPathMissingQuotes: 0, CompilerModeMismatch: 0 }); } const newSquiggleMetrics = { PathNonExistent: 0, PathNotAFile: 0, PathNotADirectory: 0, CompilerPathMissingQuotes: 0, CompilerModeMismatch: 0 }; const isWindows = os.platform() === 'win32'; if (isWindows) { const intelliSenseModeStart = curText.search(/\s*\"intelliSenseMode\"\s*:\s*\"/); if (intelliSenseModeStart !== -1) { const intelliSenseModeValueStart = curText.indexOf('"', curText.indexOf(":", intelliSenseModeStart)); const intelliSenseModeValueEnd = intelliSenseModeStart === -1 ? -1 : curText.indexOf('"', intelliSenseModeValueStart + 1) + 1; const intelliSenseModeError = this.validateIntelliSenseMode(currentConfiguration); if (intelliSenseModeError.length > 0) { const message = intelliSenseModeError; const diagnostic = new vscode.Diagnostic(new vscode.Range(document.positionAt(curTextStartOffset + intelliSenseModeValueStart), document.positionAt(curTextStartOffset + intelliSenseModeValueEnd)), message, vscode.DiagnosticSeverity.Warning); diagnostics.push(diagnostic); newSquiggleMetrics.CompilerModeMismatch++; } } } let paths = []; let compilerPath; for (const pathArray of [(currentConfiguration.browse ? currentConfiguration.browse.path : undefined), currentConfiguration.includePath, currentConfiguration.macFrameworkPath, currentConfiguration.forcedInclude]) { if (pathArray) { for (const curPath of pathArray) { paths.push(`${curPath}`); } } } if (currentConfiguration.compileCommands) { paths.push(`${currentConfiguration.compileCommands}`); } if (currentConfiguration.compilerPath) { compilerPath = currentConfiguration.compilerPath; } paths = this.resolveAndSplit(paths, undefined, this.ExtendedEnvironment); compilerPath = util.resolveVariables(compilerPath, this.ExtendedEnvironment).trim(); compilerPath = this.resolvePath(compilerPath, isWindows); const forcedIncludeStart = curText.search(/\s*\"forcedInclude\"\s*:\s*\[/); const forcedeIncludeEnd = forcedIncludeStart === -1 ? -1 : curText.indexOf("]", forcedIncludeStart); const compileCommandsStart = curText.search(/\s*\"compileCommands\"\s*:\s*\"/); const compileCommandsEnd = compileCommandsStart === -1 ? -1 : curText.indexOf('"', curText.indexOf('"', curText.indexOf(":", compileCommandsStart)) + 1); const compilerPathStart = curText.search(/\s*\"compilerPath\"\s*:\s*\"/); const compilerPathValueStart = curText.indexOf('"', curText.indexOf(":", compilerPathStart)); const compilerPathEnd = compilerPathStart === -1 ? -1 : curText.indexOf('"', compilerPathValueStart + 1) + 1; const processedPaths = new Set(); let compilerPathNeedsQuotes = false; let compilerMessage; const compilerPathAndArgs = util.extractCompilerPathAndArgs(compilerPath); const compilerLowerCase = compilerPathAndArgs.compilerName.toLowerCase(); const isClCompiler = compilerLowerCase === "cl" || compilerLowerCase === "cl.exe"; if (compilerPathAndArgs.compilerPath && !isClCompiler) { compilerPathNeedsQuotes = (compilerPathAndArgs.additionalArgs && compilerPathAndArgs.additionalArgs.length > 0) && !compilerPath.startsWith('"') && compilerPathAndArgs.compilerPath.includes(" "); compilerPath = compilerPathAndArgs.compilerPath; if (compilerPathNeedsQuotes || (compilerPath && !which.sync(compilerPath, { nothrow: true }))) { if (compilerPathNeedsQuotes) { compilerMessage = localize(15, null); newSquiggleMetrics.CompilerPathMissingQuotes++; } else if (!util.checkFileExistsSync(compilerPath)) { compilerMessage = localize(16, null, compilerPath); newSquiggleMetrics.PathNotAFile++; } } } const isWSL = isWindows && compilerPath.startsWith("/"); let compilerPathExists = true; if (this.rootUri && !isClCompiler) { const checkPathExists = util.checkPathExistsSync(compilerPath, this.rootUri.fsPath + path.sep, isWindows, isWSL, true); compilerPathExists = checkPathExists.pathExists; compilerPath = checkPathExists.path; } if (!compilerPathExists) { compilerMessage = localize(17, null, compilerPath); newSquiggleMetrics.PathNonExistent++; } if (compilerMessage) { const diagnostic = new vscode.Diagnostic(new vscode.Range(document.positionAt(curTextStartOffset + compilerPathValueStart), document.positionAt(curTextStartOffset + compilerPathEnd)), compilerMessage, vscode.DiagnosticSeverity.Warning); diagnostics.push(diagnostic); } for (const curPath of paths) { if (processedPaths.has(curPath)) { continue; } processedPaths.add(curPath); if (curPath === "${default}") { continue; } let resolvedPath = this.resolvePath(curPath, isWindows); if (!resolvedPath) { continue; } let pathExists = true; if (this.rootUri) { const checkPathExists = util.checkPathExistsSync(resolvedPath, this.rootUri.fsPath + path.sep, isWindows, isWSL, false); pathExists = checkPathExists.pathExists; resolvedPath = checkPathExists.path; } if (path.sep === "/") { resolvedPath = resolvedPath.replace(/\\/g, path.sep); } else { resolvedPath = resolvedPath.replace(/\//g, path.sep); } let escapedPath = curPath.replace(/\"/g, '\\\"'); escapedPath = escapedPath.replace(/[-\"\/\\^$*+?.()|[\]{}]/g, '\\$&'); const pattern = new RegExp(`"[^"]*?(?<="|;)${escapedPath}(?="|;).*?"`, "g"); const configMatches = curText.match(pattern); if (configMatches) { let curOffset = 0; let endOffset = 0; for (const curMatch of configMatches) { curOffset = curText.substr(endOffset).search(pattern) + endOffset; endOffset = curOffset + curMatch.length; if (curOffset >= compilerPathStart && curOffset <= compilerPathEnd) { continue; } let message; if (!pathExists) { if (curOffset >= forcedIncludeStart && curOffset <= forcedeIncludeEnd && !path.isAbsolute(resolvedPath)) { continue; } message = localize(18, null, resolvedPath); newSquiggleMetrics.PathNonExistent++; } else { if ((curOffset >= forcedIncludeStart && curOffset <= forcedeIncludeEnd) || (curOffset >= compileCommandsStart && curOffset <= compileCommandsEnd)) { if (util.checkFileExistsSync(resolvedPath)) { continue; } message = localize(19, null, resolvedPath); newSquiggleMetrics.PathNotAFile++; } else { if (util.checkDirectoryExistsSync(resolvedPath)) { continue; } message = localize(20, null, resolvedPath); newSquiggleMetrics.PathNotADirectory++; } } const diagnostic = new vscode.Diagnostic(new vscode.Range(document.positionAt(curTextStartOffset + curOffset), document.positionAt(curTextStartOffset + endOffset)), message, vscode.DiagnosticSeverity.Warning); diagnostics.push(diagnostic); } } else if (envText) { const envMatches = envText.match(pattern); if (envMatches) { let curOffset = 0; let endOffset = 0; for (const curMatch of envMatches) { curOffset = envText.substr(endOffset).search(pattern) + endOffset; endOffset = curOffset + curMatch.length; let message; if (!pathExists) { message = localize(21, null, resolvedPath); newSquiggleMetrics.PathNonExistent++; const diagnostic = new vscode.Diagnostic(new vscode.Range(document.positionAt(envTextStartOffSet + curOffset), document.positionAt(envTextStartOffSet + endOffset)), message, vscode.DiagnosticSeverity.Warning); diagnostics.push(diagnostic); } } } } } if (diagnostics.length !== 0) { this.diagnosticCollection.set(document.uri, diagnostics); } else { this.diagnosticCollection.clear(); } const changedSquiggleMetrics = {}; if (newSquiggleMetrics.PathNonExistent !== ((_a = this.prevSquiggleMetrics.get(currentConfiguration.name)) === null || _a === void 0 ? void 0 : _a.PathNonExistent)) { changedSquiggleMetrics.PathNonExistent = newSquiggleMetrics.PathNonExistent; } if (newSquiggleMetrics.PathNotAFile !== ((_b = this.prevSquiggleMetrics.get(currentConfiguration.name)) === null || _b === void 0 ? void 0 : _b.PathNotAFile)) { changedSquiggleMetrics.PathNotAFile = newSquiggleMetrics.PathNotAFile; } if (newSquiggleMetrics.PathNotADirectory !== ((_c = this.prevSquiggleMetrics.get(currentConfiguration.name)) === null || _c === void 0 ? void 0 : _c.PathNotADirectory)) { changedSquiggleMetrics.PathNotADirectory = newSquiggleMetrics.PathNotADirectory; } if (newSquiggleMetrics.CompilerPathMissingQuotes !== ((_d = this.prevSquiggleMetrics.get(currentConfiguration.name)) === null || _d === void 0 ? void 0 : _d.CompilerPathMissingQuotes)) { changedSquiggleMetrics.CompilerPathMissingQuotes = newSquiggleMetrics.CompilerPathMissingQuotes; } if (newSquiggleMetrics.CompilerModeMismatch !== ((_e = this.prevSquiggleMetrics.get(currentConfiguration.name)) === null || _e === void 0 ? void 0 : _e.CompilerModeMismatch)) { changedSquiggleMetrics.CompilerModeMismatch = newSquiggleMetrics.CompilerModeMismatch; } if (Object.keys(changedSquiggleMetrics).length > 0) { telemetry.logLanguageServerEvent("ConfigSquiggles", undefined, changedSquiggleMetrics); } this.prevSquiggleMetrics.set(currentConfiguration.name, newSquiggleMetrics); }); } updateToVersion2() { if (this.configurationJson) { this.configurationJson.version = 2; } } updateToVersion3() { if (this.configurationJson) { this.configurationJson.version = 3; for (let i = 0; i < this.configurationJson.configurations.length; i++) { const config = this.configurationJson.configurations[i]; if (config.name === "Mac" || (process.platform === 'darwin' && config.name !== "Win32" && config.name !== "Linux")) { if (config.macFrameworkPath === undefined) { config.macFrameworkPath = [ "/System/Library/Frameworks", "/Library/Frameworks" ]; } } } } } updateToVersion4() { if (this.configurationJson) { this.configurationJson.version = 4; const settings = new settings_1.CppSettings(this.rootUri); for (let i = 0; i < this.configurationJson.configurations.length; i++) { const config = this.configurationJson.configurations[i]; if (config.intelliSenseMode === undefined && !settings.defaultIntelliSenseMode) { config.intelliSenseMode = this.getIntelliSenseModeForPlatform(config.name); } if (config.compilerPath === undefined && this.defaultCompilerPath && !config.compileCommands && !settings.defaultCompilerPath) { config.compilerPath = this.defaultCompilerPath; } if (!config.cStandard && this.defaultCStandard && !settings.defaultCStandard) { config.cStandard = this.defaultCStandard; } if (!config.cppStandard && this.defaultCppStandard && !settings.defaultCppStandard) { config.cppStandard = this.defaultCppStandard; } } } } writeToJson() { const savedCompilerPathIsExplicit = []; const savedCStandardIsExplicit = []; const savedCppStandardIsExplicit = []; const savedIntelliSenseModeIsExplicit = []; if (this.configurationJson) { this.configurationJson.configurations.forEach(e => { savedCompilerPathIsExplicit.push(!!e.compilerPathIsExplicit); if (e.compilerPathIsExplicit !== undefined) { delete e.compilerPathIsExplicit; } savedCStandardIsExplicit.push(!!e.cStandardIsExplicit); if (e.cStandardIsExplicit !== undefined) { delete e.cStandardIsExplicit; } savedCppStandardIsExplicit.push(!!e.cppStandardIsExplicit); if (e.cppStandardIsExplicit !== undefined) { delete e.cppStandardIsExplicit; } savedIntelliSenseModeIsExplicit.push(!!e.intelliSenseModeIsExplicit); if (e.intelliSenseModeIsExplicit !== undefined) { delete e.intelliSenseModeIsExplicit; } }); } console.assert(this.propertiesFile); if (this.propertiesFile) { fs.writeFileSync(this.propertiesFile.fsPath, jsonc.stringify(this.configurationJson, null, 4)); } if (this.configurationJson) { for (let i = 0; i < this.configurationJson.configurations.length; i++) { this.configurationJson.configurations[i].compilerPathIsExplicit = savedCompilerPathIsExplicit[i]; this.configurationJson.configurations[i].cStandardIsExplicit = savedCStandardIsExplicit[i]; this.configurationJson.configurations[i].cppStandardIsExplicit = savedCppStandardIsExplicit[i]; this.configurationJson.configurations[i].intelliSenseModeIsExplicit = savedIntelliSenseModeIsExplicit[i]; } } } checkCppProperties() { const propertiesFile = path.join(this.configFolder, "c_cpp_properties.json"); fs.stat(propertiesFile, (err, stats) => { if (err) { if (err.code === "ENOENT" && this.propertiesFile) { this.propertiesFile = null; this.resetToDefaultSettings(true); this.handleConfigurationChange(); } } else if (stats.mtime > this.configFileWatcherFallbackTime) { if (!this.propertiesFile) { this.propertiesFile = vscode.Uri.file(propertiesFile); } this.handleConfigurationChange(); } }); } checkCompileCommands() { var _a; const compileCommands = (_a = this.CurrentConfiguration) === null || _a === void 0 ? void 0 : _a.compileCommands; if (!compileCommands) { return; } const compileCommandsFile = this.resolvePath(compileCommands, os.platform() === "win32"); fs.stat(compileCommandsFile, (err, stats) => { if (err) { if (err.code === "ENOENT" && this.compileCommandsFile) { this.compileCommandsFileWatchers = []; this.onCompileCommandsChanged(compileCommandsFile); this.compileCommandsFile = null; } } else if (stats.mtime > this.compileCommandsFileWatcherFallbackTime) { this.compileCommandsFileWatcherFallbackTime = new Date(); this.onCompileCommandsChanged(compileCommandsFile); this.compileCommandsFile = vscode.Uri.file(compileCommandsFile); } }); } dispose() { this.disposables.forEach((d) => d.dispose()); this.disposables = []; this.compileCommandsFileWatchers.forEach((watcher) => watcher.close()); this.compileCommandsFileWatchers = []; this.diagnosticCollection.dispose(); } } exports.CppProperties = CppProperties; /***/ }), /***/ 7523: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __webpack_require__(5622); const vscode_1 = __webpack_require__(7549); const os = __webpack_require__(2087); const util = __webpack_require__(5331); const telemetry = __webpack_require__(1818); const ext = __webpack_require__(2973); const cp = __webpack_require__(3129); const settings_1 = __webpack_require__(296); const nls = __webpack_require__(3612); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\cppBuildTaskProvider.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\cppBuildTaskProvider.ts')); class CppBuildTask extends vscode_1.Task { } exports.CppBuildTask = CppBuildTask; class CppBuildTaskProvider { constructor() { this.getTask = (compilerPath, appendSourceToName, compilerArgs, definition, detail) => { var _a; const compilerPathBase = path.basename(compilerPath); const isCl = compilerPathBase.toLowerCase() === "cl.exe"; let resolvedcompilerPath = isCl ? compilerPathBase : compilerPath; if (resolvedcompilerPath && !resolvedcompilerPath.startsWith("\"") && resolvedcompilerPath.includes(" ")) { resolvedcompilerPath = "\"" + resolvedcompilerPath + "\""; } if (!definition) { const taskLabel = ((appendSourceToName && !compilerPathBase.startsWith(CppBuildTaskProvider.CppBuildSourceStr)) ? CppBuildTaskProvider.CppBuildSourceStr + ": " : "") + compilerPathBase + " " + localize(0, null); const filePath = path.join('${fileDirname}', '${fileBasenameNoExtension}'); const isWindows = os.platform() === 'win32'; let args = isCl ? ['/Zi', '/EHsc', '/nologo', '/Fe:', filePath + '.exe', '${file}'] : ['-g', '${file}', '-o', filePath + (isWindows ? '.exe' : '')]; if (compilerArgs && compilerArgs.length > 0) { args = args.concat(compilerArgs); } const cwd = isWindows && !isCl && !((_a = process.env.PATH) === null || _a === void 0 ? void 0 : _a.includes(path.dirname(compilerPath))) ? path.dirname(compilerPath) : "${fileDirname}"; const options = { cwd: cwd }; definition = { type: CppBuildTaskProvider.CppBuildScriptType, label: taskLabel, command: isCl ? compilerPathBase : compilerPath, args: args, options: options }; } const editor = vscode_1.window.activeTextEditor; const folder = editor ? vscode_1.workspace.getWorkspaceFolder(editor.document.uri) : undefined; if (folder) { const activeClient = ext.getActiveClient(); const uri = activeClient.RootUri; if (!uri) { throw new Error("No client URI found in getBuildTasks()"); } if (!vscode_1.workspace.getWorkspaceFolder(uri)) { throw new Error("No target WorkspaceFolder found in getBuildTasks()"); } } const scope = folder ? folder : vscode_1.TaskScope.Workspace; const task = new vscode_1.Task(definition, scope, definition.label, CppBuildTaskProvider.CppBuildSourceStr, new vscode_1.CustomExecution((resolvedDefinition) => __awaiter(this, void 0, void 0, function* () { return new CustomBuildTaskTerminal(resolvedcompilerPath, resolvedDefinition.args, resolvedDefinition.options); })), isCl ? '$msCompile' : '$gcc'); task.group = vscode_1.TaskGroup.Build; task.detail = detail ? detail : localize(1, null) + " " + resolvedcompilerPath; return task; }; } provideTasks() { return __awaiter(this, void 0, void 0, function* () { return this.getTasks(false); }); } resolveTask(_task) { const execution = _task.execution; if (!execution) { const definition = _task.definition; _task = this.getTask(definition.command, false, definition.args ? definition.args : [], definition, _task.detail); return _task; } return undefined; } getTasks(appendSourceToName) { var _a; return __awaiter(this, void 0, void 0, function* () { const editor = vscode_1.window.activeTextEditor; const emptyTasks = []; if (!editor) { return emptyTasks; } const fileExt = path.extname(editor.document.fileName); if (!fileExt) { return emptyTasks; } const fileExtLower = fileExt.toLowerCase(); const isHeader = !fileExt || [".cuh", ".hpp", ".hh", ".hxx", ".h++", ".hp", ".h", ".ii", ".inl", ".idl", ""].some(ext => fileExtLower === ext); if (isHeader) { return emptyTasks; } let fileIsCpp; let fileIsC; if (fileExt === ".C") { fileIsCpp = true; fileIsC = true; } else { fileIsCpp = [".cu", ".cpp", ".cc", ".cxx", ".c++", ".cp", ".ino", ".ipp", ".tcc"].some(ext => fileExtLower === ext); fileIsC = fileExtLower === ".c"; } if (!(fileIsCpp || fileIsC)) { return emptyTasks; } const isWindows = os.platform() === 'win32'; let activeClient; try { activeClient = ext.getActiveClient(); } catch (e) { if (!e || e.message !== ext.intelliSenseDisabledError) { console.error("Unknown error calling getActiveClient()."); } return emptyTasks; } const userCompilerPathAndArgs = yield activeClient.getCurrentCompilerPathAndArgs(); let userCompilerPath; if (userCompilerPathAndArgs) { userCompilerPath = userCompilerPathAndArgs.compilerPath; if (userCompilerPath && userCompilerPathAndArgs.compilerName) { userCompilerPath = userCompilerPath.trim(); if (isWindows && userCompilerPath.startsWith("/")) { userCompilerPath = undefined; } else { userCompilerPath = userCompilerPath.replace(/\\\\/g, "\\"); } } } const isCompilerValid = userCompilerPath ? yield util.checkFileExists(userCompilerPath) : false; const knownCompilerPathsSet = new Set(); let knownCompilers = yield activeClient.getKnownCompilers(); if (knownCompilers) { knownCompilers = knownCompilers.filter(info => ((fileIsCpp && !info.isC) || (fileIsC && info.isC)) && (!isCompilerValid || (userCompilerPathAndArgs && (path.basename(info.path) !== userCompilerPathAndArgs.compilerName))) && (!isWindows || !info.path.startsWith("/"))); knownCompilers.map(info => { knownCompilerPathsSet.add(info.path); }); } const knownCompilerPaths = knownCompilerPathsSet.size ? Array.from(knownCompilerPathsSet) : undefined; if (!knownCompilerPaths && !userCompilerPath) { telemetry.logLanguageServerEvent('noCompilerFound'); return emptyTasks; } let result = []; if (knownCompilerPaths) { result = knownCompilerPaths.map(compilerPath => this.getTask(compilerPath, appendSourceToName, undefined)); } if (isCompilerValid && userCompilerPath) { result.push(this.getTask(userCompilerPath, appendSourceToName, (_a = userCompilerPathAndArgs) === null || _a === void 0 ? void 0 : _a.additionalArgs)); } return result; }); } getJsonTasks() { return __awaiter(this, void 0, void 0, function* () { const rawJson = yield this.getRawTasksJson(); const rawTasksJson = (!rawJson.tasks) ? new Array() : rawJson.tasks; const buildTasksJson = rawTasksJson.map((task) => { if (!task.label) { return null; } const definition = { type: task.type, label: task.label, command: task.command, args: task.args, options: task.options }; const cppBuildTask = new vscode_1.Task(definition, vscode_1.TaskScope.Workspace, task.label, "C/C++"); cppBuildTask.detail = task.detail; return cppBuildTask; }); return buildTasksJson.filter((task) => task !== null); }); } ensureBuildTaskExists(taskLabel) { return __awaiter(this, void 0, void 0, function* () { const rawTasksJson = yield this.getRawTasksJson(); if (!rawTasksJson.tasks) { rawTasksJson.tasks = new Array(); } let selectedTask = rawTasksJson.tasks.find((task) => task.label && task.label === taskLabel); if (selectedTask) { return; } const buildTasks = yield this.getTasks(true); const normalizedLabel = (taskLabel.indexOf("ver(") !== -1) ? taskLabel.slice(0, taskLabel.indexOf("ver(")).trim() : taskLabel; selectedTask = buildTasks.find(task => task.name === normalizedLabel); console.assert(selectedTask); if (!selectedTask) { throw new Error("Failed to get selectedTask in ensureBuildTaskExists()"); } else { selectedTask.definition.label = taskLabel; selectedTask.name = taskLabel; } rawTasksJson.version = "2.0.0"; rawTasksJson.tasks.forEach((task) => { var _a; if (task.label === ((_a = selectedTask) === null || _a === void 0 ? void 0 : _a.definition.label)) { task.group = { kind: "build", "isDefault": true }; } else if (task.group.kind && task.group.kind === "build" && task.group.isDefault && task.group.isDefault === true) { task.group = "build"; } }); if (!rawTasksJson.tasks.find((task) => { var _a; return task.label === ((_a = selectedTask) === null || _a === void 0 ? void 0 : _a.definition.label); })) { const newTask = Object.assign(Object.assign({}, selectedTask.definition), { problemMatcher: selectedTask.problemMatchers, group: { kind: "build", "isDefault": true }, detail: localize(2, null) }); rawTasksJson.tasks.push(newTask); } const settings = new settings_1.OtherSettings(); const tasksJsonPath = this.getTasksJsonPath(); if (!tasksJsonPath) { throw new Error("Failed to get tasksJsonPath in ensureBuildTaskExists()"); } yield util.writeFileText(tasksJsonPath, JSON.stringify(rawTasksJson, null, settings.editorTabSize)); }); } ensureDebugConfigExists(configName) { return __awaiter(this, void 0, void 0, function* () { const launchJsonPath = this.getLaunchJsonPath(); if (!launchJsonPath) { throw new Error("Failed to get launchJsonPath in ensureDebugConfigExists()"); } const rawLaunchJson = yield this.getRawLaunchJson(); if (!rawLaunchJson || !rawLaunchJson.configurations) { throw new Error(`Configuration '${configName}' is missing in 'launch.json'.`); } const selectedConfig = rawLaunchJson.configurations.find((config) => config.name && config.name === configName); if (!selectedConfig) { throw new Error(`Configuration '${configName}' is missing in 'launch.json'.`); } return; }); } provideUniqueTaskLabel(label, buildTasksJson) { const taskNameDictionary = {}; buildTasksJson.forEach(task => { taskNameDictionary[task.definition.label] = {}; }); let newLabel = label; let version = 0; do { version = version + 1; newLabel = label + ` ver(${version})`; } while (taskNameDictionary[newLabel]); return newLabel; } getLaunchJsonPath() { return util.getJsonPath("launch.json"); } getTasksJsonPath() { return util.getJsonPath("tasks.json"); } getRawLaunchJson() { const path = this.getLaunchJsonPath(); return util.getRawJson(path); } getRawTasksJson() { const path = this.getTasksJsonPath(); return util.getRawJson(path); } } exports.CppBuildTaskProvider = CppBuildTaskProvider; CppBuildTaskProvider.CppBuildScriptType = 'cppbuild'; CppBuildTaskProvider.CppBuildSourceStr = "C/C++"; class CustomBuildTaskTerminal { constructor(command, args, options) { this.command = command; this.args = args; this.options = options; this.writeEmitter = new vscode_1.EventEmitter(); this.closeEmitter = new vscode_1.EventEmitter(); this.endOfLine = "\r\n"; } get onDidWrite() { return this.writeEmitter.event; } get onDidClose() { return this.closeEmitter.event; } open(_initialDimensions) { return __awaiter(this, void 0, void 0, function* () { telemetry.logLanguageServerEvent("cppBuildTaskStarted"); this.writeEmitter.fire(localize(3, null) + this.endOfLine); yield this.doBuild(); }); } close() { } doBuild() { var _a; return __awaiter(this, void 0, void 0, function* () { let activeCommand = util.resolveVariables(this.command); this.args.forEach(value => { let temp = util.resolveVariables(value); if (temp && temp.includes(" ")) { temp = "\"" + temp + "\""; } activeCommand = activeCommand + " " + temp; }); if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.cwd) { this.options.cwd = util.resolveVariables(this.options.cwd); } const splitWriteEmitter = (lines) => { for (const line of lines.toString().split(/\r?\n/g)) { this.writeEmitter.fire(line + this.endOfLine); } }; this.writeEmitter.fire(activeCommand + this.endOfLine); try { const result = yield new Promise((resolve, reject) => { cp.exec(activeCommand, this.options, (_error, stdout, _stderr) => { const dot = "."; const is_cl = (_stderr || _stderr === '') && stdout ? true : false; if (is_cl) { if (_stderr) { splitWriteEmitter(_stderr); } splitWriteEmitter(stdout); } if (_error) { if (stdout) { } else if (_stderr) { splitWriteEmitter(_stderr); } else { splitWriteEmitter(_error.message); } telemetry.logLanguageServerEvent("cppBuildTaskError"); this.writeEmitter.fire(localize(4, null) + dot + this.endOfLine); resolve(-1); } else if (_stderr && !stdout) { splitWriteEmitter(_stderr); telemetry.logLanguageServerEvent("cppBuildTaskWarnings"); this.writeEmitter.fire(localize(5, null) + dot + this.endOfLine); resolve(0); } else if (stdout && stdout.includes("warning C")) { telemetry.logLanguageServerEvent("cppBuildTaskWarnings"); this.writeEmitter.fire(localize(6, null) + dot + this.endOfLine); resolve(0); } else { this.writeEmitter.fire(localize(7, null) + this.endOfLine); resolve(0); } }); }); this.closeEmitter.fire(result); } catch (_b) { this.closeEmitter.fire(-1); } }); } } /***/ }), /***/ 4977: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode_cpptools_1 = __webpack_require__(3286); const settings_1 = __webpack_require__(296); const oldCmakeToolsExtensionId = "vector-of-bool.cmake-tools"; const newCmakeToolsExtensionId = "ms-vscode.cmake-tools"; class CustomProviderWrapper { constructor(provider, version) { this._isReady = version < vscode_cpptools_1.Version.v2; this.provider = provider; if (provider.extensionId && version === vscode_cpptools_1.Version.v0) { version = vscode_cpptools_1.Version.v1; } this._version = version; } get isReady() { return this._isReady; } set isReady(ready) { this._isReady = ready; } get isValid() { let valid = !!(this.provider.name && this.provider.canProvideConfiguration && this.provider.provideConfigurations); if (valid && this._version > vscode_cpptools_1.Version.v0) { valid = !!(this.provider.extensionId && this.provider.dispose); } if (valid && this._version > vscode_cpptools_1.Version.v1) { valid = !!(this.provider.canProvideBrowseConfiguration && this.provider.provideBrowseConfiguration); } if (valid && this._version > vscode_cpptools_1.Version.v2) { valid = !!(this.provider.canProvideBrowseConfigurationsPerFolder && this.provider.provideFolderBrowseConfiguration); } return valid; } get version() { return this._version; } get name() { return this.provider.name; } get extensionId() { return this._version === vscode_cpptools_1.Version.v0 ? this.provider.name : this.provider.extensionId; } canProvideConfiguration(uri, token) { return this.provider.canProvideConfiguration(uri, token); } provideConfigurations(uris, token) { return this.provider.provideConfigurations(uris, token); } canProvideBrowseConfiguration(token) { return this._version < vscode_cpptools_1.Version.v2 ? Promise.resolve(false) : this.provider.canProvideBrowseConfiguration(token); } provideBrowseConfiguration(token) { console.assert(this._version >= vscode_cpptools_1.Version.v2); return this._version < vscode_cpptools_1.Version.v2 ? Promise.resolve({ browsePath: [] }) : this.provider.provideBrowseConfiguration(token); } canProvideBrowseConfigurationsPerFolder(token) { return this._version < vscode_cpptools_1.Version.v3 ? Promise.resolve(false) : this.provider.canProvideBrowseConfigurationsPerFolder(token); } provideFolderBrowseConfiguration(uri, token) { console.assert(this._version >= vscode_cpptools_1.Version.v3); return this._version < vscode_cpptools_1.Version.v3 ? Promise.resolve({ browsePath: [] }) : this.provider.provideFolderBrowseConfiguration(uri, token); } dispose() { if (this._version !== vscode_cpptools_1.Version.v0) { this.provider.dispose(); } } } class CustomConfigurationProviderCollection { constructor() { this.providers = new Map(); } logProblems(provider, version) { const missing = []; if (!provider.name) { missing.push("'name'"); } if (version !== vscode_cpptools_1.Version.v0 && !provider.extensionId) { missing.push("'extensionId'"); } if (!provider.canProvideConfiguration) { missing.push("'canProvideConfiguration'"); } if (!provider.provideConfigurations) { missing.push("'canProvideConfiguration'"); } if (version !== vscode_cpptools_1.Version.v0 && !provider.dispose) { missing.push("'dispose'"); } if (version >= vscode_cpptools_1.Version.v2 && !provider.canProvideBrowseConfiguration) { missing.push("'canProvideBrowseConfiguration'"); } if (version >= vscode_cpptools_1.Version.v2 && !provider.provideBrowseConfiguration) { missing.push("'provideBrowseConfiguration'"); } if (version >= vscode_cpptools_1.Version.v3 && !provider.canProvideBrowseConfigurationsPerFolder) { missing.push("'canProvideBrowseConfigurationsPerFolder'"); } if (version >= vscode_cpptools_1.Version.v3 && !provider.provideFolderBrowseConfiguration) { missing.push("'provideFolderBrowseConfiguration'"); } console.error(`CustomConfigurationProvider was not registered. The following properties are missing from the implementation: ${missing.join(", ")}.`); } getId(provider) { if (typeof provider === "string") { return provider; } else if (provider.extensionId) { return provider.extensionId; } else if (provider.name) { return provider.name; } else { console.error(`invalid provider: ${provider}`); return ""; } } get size() { return this.providers.size; } add(provider, version) { if (new settings_1.CppSettings().intelliSenseEngine === "Disabled") { console.warn("Language service is disabled. Provider will not be registered."); return false; } const wrapper = new CustomProviderWrapper(provider, version); if (!wrapper.isValid) { this.logProblems(provider, version); return false; } let exists = false; const existing = this.providers.get(wrapper.extensionId); if (existing) { exists = (existing.version === vscode_cpptools_1.Version.v0 && wrapper.version === vscode_cpptools_1.Version.v0); } if (!exists) { this.providers.set(wrapper.extensionId, wrapper); } else { console.error(`CustomConfigurationProvider '${wrapper.extensionId}' has already been registered.`); } return !exists; } get(provider) { let id = this.getId(provider); if (this.providers.has(id)) { return this.providers.get(id); } if (typeof provider === "string") { if (provider === newCmakeToolsExtensionId) { id = oldCmakeToolsExtensionId; } else if (provider === oldCmakeToolsExtensionId) { id = newCmakeToolsExtensionId; } if (this.providers.has(id)) { return this.providers.get(id); } } return undefined; } forEach(func) { this.providers.forEach(func); } remove(provider) { const id = this.getId(provider); if (this.providers.has(id)) { this.providers.delete(id); } else { console.warn(`${id} is not registered`); } } checkId(providerId) { if (!providerId) { return undefined; } const found = []; let noUpdate = false; this.forEach(provider => { if (provider.extensionId === providerId) { noUpdate = true; } else if (provider.name === providerId && provider.version !== vscode_cpptools_1.Version.v0) { found.push(provider); } }); if (noUpdate) { return providerId; } if (found.length === 1) { return found[0].extensionId; } else if (found.length > 1) { console.warn("duplicate provider name found. Not upgrading."); } return providerId; } } exports.CustomConfigurationProviderCollection = CustomConfigurationProviderCollection; const providerCollection = new CustomConfigurationProviderCollection(); function getCustomConfigProviders() { return providerCollection; } exports.getCustomConfigProviders = getCustomConfigProviders; function isSameProviderExtensionId(settingExtensionId, providerExtensionId) { if (!settingExtensionId && !providerExtensionId) { return true; } if (settingExtensionId === providerExtensionId) { return true; } if ((settingExtensionId === newCmakeToolsExtensionId && providerExtensionId === oldCmakeToolsExtensionId) || (settingExtensionId === oldCmakeToolsExtensionId && providerExtensionId === newCmakeToolsExtensionId)) { return true; } return false; } exports.isSameProviderExtensionId = isSameProviderExtensionId; /***/ }), /***/ 1748: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); class DataBinding { constructor(value) { this.valueChanged = new vscode.EventEmitter(); this.isActive = true; this.value = value; this.isActive = true; } get Value() { return this.value; } set Value(value) { if (value !== this.value) { this.value = value; this.valueChanged.fire(this.value); } } setValueIfActive(value) { if (value !== this.value) { this.value = value; if (this.isActive) { this.valueChanged.fire(this.value); } } } get ValueChanged() { return this.valueChanged.event; } activate() { this.isActive = true; this.valueChanged.fire(this.value); } deactivate() { this.isActive = false; } dispose() { this.deactivate(); this.valueChanged.dispose(); } } exports.DataBinding = DataBinding; /***/ }), /***/ 2973: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __webpack_require__(5622); const vscode = __webpack_require__(7549); const os = __webpack_require__(2087); const fs = __webpack_require__(5747); const util = __webpack_require__(5331); const telemetry = __webpack_require__(1818); const referencesModel_1 = __webpack_require__(9997); const ui_1 = __webpack_require__(6713); const clientCollection_1 = __webpack_require__(3765); const settings_1 = __webpack_require__(296); const persistentState_1 = __webpack_require__(1102); const languageConfig_1 = __webpack_require__(1626); const customProviders_1 = __webpack_require__(4977); const platform_1 = __webpack_require__(3383); const vscode_languageclient_1 = __webpack_require__(3094); const child_process_1 = __webpack_require__(3129); const githubAPI_1 = __webpack_require__(3158); const packageVersion_1 = __webpack_require__(302); const commands_1 = __webpack_require__(4960); const rd = __webpack_require__(1058); const yauzl = __webpack_require__(8798); const nls = __webpack_require__(3612); const cppBuildTaskProvider_1 = __webpack_require__(7523); const which = __webpack_require__(8750); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\extension.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\extension.ts')); exports.cppBuildTaskProvider = new cppBuildTaskProvider_1.CppBuildTaskProvider(); let prevCrashFile; let clients; let activeDocument; let ui; const disposables = []; let languageConfigurations = []; let intervalTimer; let insiderUpdateEnabled = false; let insiderUpdateTimer; const insiderUpdateTimerInterval = 1000 * 60 * 60; let realActivationOccurred = false; let tempCommands = []; let activatedPreviously; let buildInfoCache; const cppInstallVsixStr = 'C/C++: Install vsix -- '; let taskProvider; let codeActionProvider; exports.intelliSenseDisabledError = "Do not activate the extension when IntelliSense is disabled."; let vcpkgDbPromise; function initVcpkgDatabase() { return new Promise((resolve, reject) => { yauzl.open(util.getExtensionFilePath('VCPkgHeadersDatabase.zip'), { lazyEntries: true }, (err, zipfile) => { const database = {}; if (err || !zipfile) { resolve(database); return; } zipfile.on('close', () => { resolve(database); }); zipfile.on('entry', entry => { if (entry.fileName !== 'VCPkgHeadersDatabase.txt') { zipfile.readEntry(); return; } zipfile.openReadStream(entry, (err, stream) => { if (err || !stream) { zipfile.close(); return; } const reader = rd.createInterface(stream); reader.on('line', (lineText) => { const portFilePair = lineText.split(':'); if (portFilePair.length !== 2) { return; } const portName = portFilePair[0]; const relativeHeader = portFilePair[1]; if (!database[relativeHeader]) { database[relativeHeader] = []; } database[relativeHeader].push(portName); }); reader.on('close', () => { zipfile.close(); }); }); }); zipfile.readEntry(); }); }); } function getVcpkgHelpAction() { const dummy = [{}]; return { command: { title: 'vcpkgOnlineHelpSuggested', command: 'C_Cpp.VcpkgOnlineHelpSuggested', arguments: dummy }, title: localize(0, null), kind: vscode.CodeActionKind.QuickFix }; } function getVcpkgClipboardInstallAction(port) { return { command: { title: 'vcpkgClipboardInstallSuggested', command: 'C_Cpp.VcpkgClipboardInstallSuggested', arguments: [[port]] }, title: localize(1, null, port), kind: vscode.CodeActionKind.QuickFix }; } function lookupIncludeInVcpkg(document, line) { return __awaiter(this, void 0, void 0, function* () { const matches = document.lineAt(line).text.match(/#include\s*[<"](?[^>"]*)[>"]/); if (!matches || !matches.length || !matches.groups) { return []; } const missingHeader = matches.groups['includeFile'].replace(/\//g, '\\'); let portsWithHeader; const vcpkgDb = yield vcpkgDbPromise; if (vcpkgDb) { portsWithHeader = vcpkgDb[missingHeader]; } return portsWithHeader ? portsWithHeader : []; }); } function isMissingIncludeDiagnostic(diagnostic) { const missingIncludeCode = 1696; if (diagnostic.code === null || diagnostic.code === undefined || !diagnostic.source) { return false; } return diagnostic.code === missingIncludeCode && diagnostic.source === 'C/C++'; } function activate(activationEventOccurred) { return __awaiter(this, void 0, void 0, function* () { if (realActivationOccurred) { return; } activatedPreviously = new persistentState_1.PersistentWorkspaceState("activatedPreviously", false); if (activatedPreviously.Value) { activatedPreviously.Value = false; realActivation(); } if (tempCommands.length === 0) { tempCommands.push(vscode.workspace.onDidOpenTextDocument(onDidOpenTextDocument)); } let cppPropertiesExists = false; if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) { for (let i = 0; i < vscode.workspace.workspaceFolders.length; ++i) { const config = path.join(vscode.workspace.workspaceFolders[i].uri.fsPath, ".vscode/c_cpp_properties.json"); if (yield util.checkFileExists(config)) { cppPropertiesExists = true; const doc = yield vscode.workspace.openTextDocument(config); vscode.languages.setTextDocumentLanguage(doc, "jsonc"); } } } if (activationEventOccurred) { onActivationEvent(); return; } taskProvider = vscode.tasks.registerTaskProvider(cppBuildTaskProvider_1.CppBuildTaskProvider.CppBuildScriptType, exports.cppBuildTaskProvider); vscode.tasks.onDidStartTask(event => { if (event.execution.task.source === cppBuildTaskProvider_1.CppBuildTaskProvider.CppBuildSourceStr) { telemetry.logLanguageServerEvent('buildTaskStarted'); } }); const selector = [ { scheme: 'file', language: 'c' }, { scheme: 'file', language: 'cpp' }, { scheme: 'file', language: 'cuda-cpp' } ]; codeActionProvider = vscode.languages.registerCodeActionsProvider(selector, { provideCodeActions: (document, range, context, token) => __awaiter(this, void 0, void 0, function* () { if (!(yield clients.ActiveClient.getVcpkgEnabled())) { return []; } if (!context.diagnostics.some(isMissingIncludeDiagnostic)) { return []; } telemetry.logLanguageServerEvent('codeActionsProvided', { "source": "vcpkg" }); if (!(yield clients.ActiveClient.getVcpkgInstalled())) { return [getVcpkgHelpAction()]; } const ports = yield lookupIncludeInVcpkg(document, range.start.line); const actions = ports.map(getVcpkgClipboardInstallAction); return actions; }) }); if (cppPropertiesExists) { onActivationEvent(); return; } if (vscode.workspace.textDocuments !== undefined && vscode.workspace.textDocuments.length > 0) { for (let i = 0; i < vscode.workspace.textDocuments.length; ++i) { const document = vscode.workspace.textDocuments[i]; if (document.uri.scheme === "file") { if (document.languageId === "c" || document.languageId === "cpp" || document.languageId === "cuda-cpp") { onActivationEvent(); return; } } } } }); } exports.activate = activate; function onDidOpenTextDocument(document) { if (document.languageId === "c" || document.languageId === "cpp" || document.languageId === "cuda-cpp") { onActivationEvent(); } } function onActivationEvent() { if (tempCommands.length === 0) { return; } tempCommands.forEach((command) => { command.dispose(); }); tempCommands = []; if (!realActivationOccurred) { realActivation(); } activatedPreviously.Value = true; } function sendActivationTelemetry() { const activateEvent = {}; if (vscode.env.machineId !== "someValue.machineId") { const machineIdPersistentState = new persistentState_1.PersistentState("CPP.machineId", undefined); if (!machineIdPersistentState.Value) { activateEvent["newMachineId"] = vscode.env.machineId; } else if (machineIdPersistentState.Value !== vscode.env.machineId) { activateEvent["newMachineId"] = vscode.env.machineId; activateEvent["oldMachineId"] = machineIdPersistentState.Value; } machineIdPersistentState.Value = vscode.env.machineId; } if (vscode.env.uiKind === vscode.UIKind.Web) { activateEvent["WebUI"] = "1"; } telemetry.logLanguageServerEvent("Activate", activateEvent); } function realActivation() { if (new settings_1.CppSettings().intelliSenseEngine === "Disabled") { throw new Error(exports.intelliSenseDisabledError); } else { console.log("activating extension"); sendActivationTelemetry(); const checkForConflictingExtensions = new persistentState_1.PersistentState("CPP." + util.packageJson.version + ".checkForConflictingExtensions", true); if (checkForConflictingExtensions.Value) { checkForConflictingExtensions.Value = false; const clangCommandAdapterActive = vscode.extensions.all.some((extension, index, array) => extension.isActive && extension.id === "mitaki28.vscode-clang"); if (clangCommandAdapterActive) { telemetry.logLanguageServerEvent("conflictingExtension"); } } } realActivationOccurred = true; console.log("starting language server"); clients = new clientCollection_1.ClientCollection(); ui = ui_1.getUI(); const activeEditor = vscode.window.activeTextEditor; if (activeEditor) { clients.timeTelemetryCollector.setFirstFile(activeEditor.document.uri); } clients.forEach(client => { customProviders_1.getCustomConfigProviders().forEach(provider => client.onRegisterCustomConfigurationProvider(provider)); }); disposables.push(vscode.workspace.onDidChangeConfiguration(onDidChangeSettings)); disposables.push(vscode.window.onDidChangeActiveTextEditor(onDidChangeActiveTextEditor)); ui.activeDocumentChanged(); disposables.push(vscode.window.onDidChangeTextEditorSelection(onDidChangeTextEditorSelection)); disposables.push(vscode.window.onDidChangeVisibleTextEditors(onDidChangeVisibleTextEditors)); updateLanguageConfigurations(); reportMacCrashes(); const settings = new settings_1.CppSettings(); vcpkgDbPromise = initVcpkgDatabase(); platform_1.PlatformInformation.GetPlatformInformation().then((info) => __awaiter(this, void 0, void 0, function* () { if (info.platform !== "linux" || info.architecture === "x64" || info.architecture === "arm" || info.architecture === "arm64") { const experimentationService = yield telemetry.getExperimentationService(); if (experimentationService !== undefined) { const allowInsiders = yield experimentationService.getTreatmentVariableAsync("vscode", "allowInsiders"); if (allowInsiders) { insiderUpdateEnabled = true; if (settings.updateChannel === 'Default') { const userVersion = new packageVersion_1.PackageVersion(util.packageJson.version); if (userVersion.suffix === "insiders") { checkAndApplyUpdate(settings.updateChannel, false); } else { suggestInsidersChannel(); } } else if (settings.updateChannel === 'Insiders') { insiderUpdateTimer = global.setInterval(checkAndApplyUpdateOnTimer, insiderUpdateTimerInterval); checkAndApplyUpdate(settings.updateChannel, false); } } } } })); clients.ActiveClient.notifyWhenLanguageClientReady(() => { intervalTimer = global.setInterval(onInterval, 2500); }); } function updateLanguageConfigurations() { languageConfigurations.forEach(d => d.dispose()); languageConfigurations = []; languageConfigurations.push(vscode.languages.setLanguageConfiguration('c', languageConfig_1.getLanguageConfig('c'))); languageConfigurations.push(vscode.languages.setLanguageConfiguration('cpp', languageConfig_1.getLanguageConfig('cpp'))); languageConfigurations.push(vscode.languages.setLanguageConfiguration('cuda-cpp', languageConfig_1.getLanguageConfig('cuda-cpp'))); } exports.updateLanguageConfigurations = updateLanguageConfigurations; function onDidChangeSettings(event) { const activeClient = clients.ActiveClient; const changedActiveClientSettings = activeClient.onDidChangeSettings(event, true); clients.forEach(client => { if (client !== activeClient) { client.onDidChangeSettings(event, false); } }); if (insiderUpdateEnabled) { const newUpdateChannel = changedActiveClientSettings['updateChannel']; if (newUpdateChannel) { if (newUpdateChannel === 'Default') { clearInterval(insiderUpdateTimer); } else if (newUpdateChannel === 'Insiders') { insiderUpdateTimer = global.setInterval(checkAndApplyUpdateOnTimer, insiderUpdateTimerInterval); } checkAndApplyUpdate(newUpdateChannel, true); } } } function onDidChangeActiveTextEditor(editor) { console.assert(clients !== undefined, "client should be available before active editor is changed"); if (clients === undefined) { return; } const activeEditor = vscode.window.activeTextEditor; if (!editor || !activeEditor || activeEditor.document.uri.scheme !== "file" || (activeEditor.document.languageId !== "c" && activeEditor.document.languageId !== "cpp" && activeEditor.document.languageId !== "cuda-cpp")) { activeDocument = ""; } else { activeDocument = editor.document.uri.toString(); clients.activeDocumentChanged(editor.document); clients.ActiveClient.selectionChanged(vscode_languageclient_1.Range.create(editor.selection.start, editor.selection.end)); } ui.activeDocumentChanged(); } exports.onDidChangeActiveTextEditor = onDidChangeActiveTextEditor; function onDidChangeTextEditorSelection(event) { if (!event.textEditor || !vscode.window.activeTextEditor || event.textEditor.document.uri !== vscode.window.activeTextEditor.document.uri || event.textEditor.document.uri.scheme !== "file" || (event.textEditor.document.languageId !== "cpp" && event.textEditor.document.languageId !== "c")) { return; } if (activeDocument !== event.textEditor.document.uri.toString()) { activeDocument = event.textEditor.document.uri.toString(); clients.activeDocumentChanged(event.textEditor.document); ui.activeDocumentChanged(); } clients.ActiveClient.selectionChanged(vscode_languageclient_1.Range.create(event.selections[0].start, event.selections[0].end)); } function processDelayedDidOpen(document) { const client = clients.getClientFor(document.uri); if (client) { if (clients.checkOwnership(client, document)) { if (!client.TrackedDocuments.has(document)) { clients.timeTelemetryCollector.setDidOpenTime(document.uri); client.TrackedDocuments.add(document); const finishDidOpen = (doc) => { client.provideCustomConfiguration(doc.uri, undefined); client.notifyWhenLanguageClientReady(() => { client.takeOwnership(doc); client.onDidOpenTextDocument(doc); }); }; let languageChanged = false; if ((document.uri.path.endsWith(".C") || document.uri.path.endsWith(".H")) && document.languageId === "c") { const cppSettings = new settings_1.CppSettings(); if (cppSettings.autoAddFileAssociations) { const fileName = path.basename(document.uri.fsPath); const mappingString = fileName + "@" + document.uri.fsPath; client.addFileAssociations(mappingString, "cpp"); client.sendDidChangeSettings({ files: { associations: new settings_1.OtherSettings().filesAssociations } }); vscode.languages.setTextDocumentLanguage(document, "cpp").then((newDoc) => { finishDidOpen(newDoc); }); languageChanged = true; } } if (!languageChanged) { finishDidOpen(document); } } } } } exports.processDelayedDidOpen = processDelayedDidOpen; function onDidChangeVisibleTextEditors(editors) { editors.forEach(editor => { if ((editor.document.uri.scheme === "file") && (editor.document.languageId === "c" || editor.document.languageId === "cpp" || editor.document.languageId === "cuda-cpp")) { processDelayedDidOpen(editor.document); } }); } function onInterval() { clients.ActiveClient.onInterval(); } function installVsix(vsixLocation) { return __awaiter(this, void 0, void 0, function* () { const userVersion = new packageVersion_1.PackageVersion(vscode.version); const lastVersionWithoutInstallExtensionCommand = new packageVersion_1.PackageVersion('1.32.3'); if (userVersion.isVsCodeVersionGreaterThan(lastVersionWithoutInstallExtensionCommand)) { return vscode.commands.executeCommand('workbench.extensions.installExtension', vscode.Uri.file(vsixLocation)); } return platform_1.PlatformInformation.GetPlatformInformation().then((platformInfo) => { const getVsCodeScriptPath = (platformInfo) => { if (platformInfo.platform === 'win32') { const vsCodeBinName = path.basename(process.execPath); let cmdFile; if (vsCodeBinName === 'Code - Insiders.exe') { cmdFile = 'code-insiders.cmd'; } else if (vsCodeBinName === 'Code - Exploration.exe') { cmdFile = 'code-exploration.cmd'; } else { cmdFile = 'code.cmd'; } const vsCodeExeDir = path.dirname(process.execPath); return path.join(vsCodeExeDir, 'bin', cmdFile); } else if (platformInfo.platform === 'darwin') { return path.join(process.execPath, '..', '..', '..', '..', '..', 'Resources', 'app', 'bin', 'code'); } else { const vsCodeBinName = path.basename(process.execPath); return which.sync(vsCodeBinName); } }; let vsCodeScriptPath; try { vsCodeScriptPath = getVsCodeScriptPath(platformInfo); } catch (err) { return Promise.reject(new Error('Failed to find VS Code script')); } const oldVersion = new packageVersion_1.PackageVersion('1.27.2'); if (userVersion.isVsCodeVersionGreaterThan(oldVersion)) { return new Promise((resolve, reject) => { let process; try { process = child_process_1.spawn(vsCodeScriptPath, ['--install-extension', vsixLocation, '--force']); const timer = global.setTimeout(() => { process.kill(); reject(new Error('Failed to receive response from VS Code script process for installation within 30s.')); }, 30000); process.on('exit', (code) => { clearInterval(timer); if (code !== 0) { reject(new Error(`VS Code script exited with error code ${code}`)); } else { resolve(); } }); if (process.pid === undefined) { throw new Error(); } } catch (error) { reject(new Error('Failed to launch VS Code script process for installation')); return; } }); } return new Promise((resolve, reject) => { let process; try { process = child_process_1.spawn(vsCodeScriptPath, ['--install-extension', vsixLocation]); if (process.pid === undefined) { throw new Error(); } } catch (error) { reject(new Error('Failed to launch VS Code script process for installation')); return; } const timer = global.setTimeout(() => { process.kill(); reject(new Error('Failed to receive response from VS Code script process for installation within 30s.')); }, 30000); let sentOverride = false; const stdout = process.stdout; if (!stdout) { reject(new Error("Failed to communicate with VS Code script process for installation")); return; } stdout.on('data', () => { if (sentOverride) { return; } const stdin = process.stdin; if (!stdin) { reject(new Error("Failed to communicate with VS Code script process for installation")); return; } stdin.write('0\n'); sentOverride = true; clearInterval(timer); resolve(); }); }); }); }); } function suggestInsidersChannel() { return __awaiter(this, void 0, void 0, function* () { if (util.isCodespaces()) { return; } const suggestInsiders = new persistentState_1.PersistentState("CPP.suggestInsiders", true); if (!suggestInsiders.Value) { return; } const suggestInsidersCount = new persistentState_1.PersistentState("CPP.suggestInsidersCount", 0); if (suggestInsidersCount.Value < 10) { suggestInsidersCount.Value = suggestInsidersCount.Value + 1; return; } let buildInfo; try { buildInfo = yield githubAPI_1.getTargetBuildInfo("Insiders", false); } catch (error) { console.log(`${cppInstallVsixStr}${error.message}`); if (error.message.indexOf('/') !== -1 || error.message.indexOf('\\') !== -1) { error.message = "Potential PII hidden"; } telemetry.logLanguageServerEvent('suggestInsiders', { 'error': error.message, 'success': 'false' }); } if (!buildInfo) { return; } const message = localize(2, null, buildInfo.name); const yes = localize(3, null); const askLater = localize(4, null); const dontShowAgain = localize(5, null); vscode.window.showInformationMessage(message, yes, askLater, dontShowAgain).then((selection) => { switch (selection) { case yes: buildInfoCache = buildInfo; vscode.workspace.getConfiguration("C_Cpp").update("updateChannel", "Insiders", vscode.ConfigurationTarget.Global); break; case dontShowAgain: suggestInsiders.Value = false; break; case askLater: break; default: break; } }); }); } function applyUpdate(buildInfo) { var _a, _b, _c; return __awaiter(this, void 0, void 0, function* () { let tempVSIX; try { tempVSIX = yield util.createTempFileWithPostfix('.vsix'); const config = vscode.workspace.getConfiguration(); const originalProxySupport = (_a = config.inspect('http.proxySupport')) === null || _a === void 0 ? void 0 : _a.globalValue; while (true) { try { yield util.downloadFileToDestination(buildInfo.downloadUrl, tempVSIX.name); } catch (_d) { if (originalProxySupport !== ((_b = config.inspect('http.proxySupport')) === null || _b === void 0 ? void 0 : _b.globalValue)) { config.update('http.proxySupport', originalProxySupport, true); throw new Error('Failed to download VSIX package with proxySupport off'); } if (config.get('http.proxySupport') !== "off" && originalProxySupport !== "off") { config.update('http.proxySupport', "off", true); continue; } throw new Error('Failed to download VSIX package'); } if (originalProxySupport !== ((_c = config.inspect('http.proxySupport')) === null || _c === void 0 ? void 0 : _c.globalValue)) { config.update('http.proxySupport', originalProxySupport, true); telemetry.logLanguageServerEvent('installVsix', { 'error': "Success with proxySupport off", 'success': 'true' }); } break; } try { yield installVsix(tempVSIX.name); } catch (error) { throw new Error('Failed to install VSIX package'); } clearInterval(insiderUpdateTimer); const message = localize(6, null, buildInfo.name); util.promptReloadWindow(message); telemetry.logLanguageServerEvent('installVsix', { 'success': 'true' }); } catch (error) { console.error(`${cppInstallVsixStr}${error.message}`); if (error.message.indexOf('/') !== -1 || error.message.indexOf('\\') !== -1) { error.message = "Potential PII hidden"; } telemetry.logLanguageServerEvent('installVsix', { 'error': error.message, 'success': 'false' }); } if (tempVSIX) { tempVSIX.removeCallback(); } }); } function checkAndApplyUpdateOnTimer() { return __awaiter(this, void 0, void 0, function* () { return checkAndApplyUpdate('Insiders', false); }); } function checkAndApplyUpdate(updateChannel, isFromSettingsChange) { return __awaiter(this, void 0, void 0, function* () { let buildInfo = buildInfoCache; buildInfoCache = undefined; if (!buildInfo) { try { buildInfo = yield githubAPI_1.getTargetBuildInfo(updateChannel, isFromSettingsChange); } catch (error) { telemetry.logLanguageServerEvent('installVsix', { 'error': error.message, 'success': 'false' }); } } if (!buildInfo) { return; } yield applyUpdate(buildInfo); }); } let commandsRegistered = false; function registerCommands() { if (commandsRegistered) { return; } commandsRegistered = true; commands_1.getTemporaryCommandRegistrarInstance().clearTempCommands(); disposables.push(vscode.commands.registerCommand('C_Cpp.SwitchHeaderSource', onSwitchHeaderSource)); disposables.push(vscode.commands.registerCommand('C_Cpp.ResetDatabase', onResetDatabase)); disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationSelect', onSelectConfiguration)); disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationProviderSelect', onSelectConfigurationProvider)); disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationEditJSON', onEditConfigurationJSON)); disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationEditUI', onEditConfigurationUI)); disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationEdit', onEditConfiguration)); disposables.push(vscode.commands.registerCommand('C_Cpp.AddToIncludePath', onAddToIncludePath)); disposables.push(vscode.commands.registerCommand('C_Cpp.EnableErrorSquiggles', onEnableSquiggles)); disposables.push(vscode.commands.registerCommand('C_Cpp.DisableErrorSquiggles', onDisableSquiggles)); disposables.push(vscode.commands.registerCommand('C_Cpp.ToggleIncludeFallback', onToggleIncludeFallback)); disposables.push(vscode.commands.registerCommand('C_Cpp.ToggleDimInactiveRegions', onToggleDimInactiveRegions)); disposables.push(vscode.commands.registerCommand('C_Cpp.PauseParsing', onPauseParsing)); disposables.push(vscode.commands.registerCommand('C_Cpp.ResumeParsing', onResumeParsing)); disposables.push(vscode.commands.registerCommand('C_Cpp.ShowParsingCommands', onShowParsingCommands)); disposables.push(vscode.commands.registerCommand('C_Cpp.ShowReferencesProgress', onShowReferencesProgress)); disposables.push(vscode.commands.registerCommand('C_Cpp.TakeSurvey', onTakeSurvey)); disposables.push(vscode.commands.registerCommand('C_Cpp.LogDiagnostics', onLogDiagnostics)); disposables.push(vscode.commands.registerCommand('C_Cpp.RescanWorkspace', onRescanWorkspace)); disposables.push(vscode.commands.registerCommand('C_Cpp.ShowReferenceItem', onShowRefCommand)); disposables.push(vscode.commands.registerCommand('C_Cpp.referencesViewGroupByType', onToggleRefGroupView)); disposables.push(vscode.commands.registerCommand('C_Cpp.referencesViewUngroupByType', onToggleRefGroupView)); disposables.push(vscode.commands.registerCommand('C_Cpp.VcpkgClipboardInstallSuggested', onVcpkgClipboardInstallSuggested)); disposables.push(vscode.commands.registerCommand('C_Cpp.VcpkgOnlineHelpSuggested', onVcpkgOnlineHelpSuggested)); disposables.push(vscode.commands.registerCommand('C_Cpp.GenerateEditorConfig', onGenerateEditorConfig)); disposables.push(vscode.commands.registerCommand('C_Cpp.GoToNextDirectiveInGroup', onGoToNextDirectiveInGroup)); disposables.push(vscode.commands.registerCommand('C_Cpp.GoToPrevDirectiveInGroup', onGoToPrevDirectiveInGroup)); disposables.push(vscode.commands.registerCommand('C_Cpp.CheckForCompiler', onCheckForCompiler)); disposables.push(vscode.commands.registerCommand('cpptools.activeConfigName', onGetActiveConfigName)); disposables.push(vscode.commands.registerCommand('cpptools.activeConfigCustomVariable', onGetActiveConfigCustomVariable)); disposables.push(vscode.commands.registerCommand('cpptools.setActiveConfigName', onSetActiveConfigName)); commands_1.getTemporaryCommandRegistrarInstance().executeDelayedCommands(); } exports.registerCommands = registerCommands; function onSwitchHeaderSource() { return __awaiter(this, void 0, void 0, function* () { onActivationEvent(); const activeEditor = vscode.window.activeTextEditor; if (!activeEditor || !activeEditor.document) { return; } if (activeEditor.document.languageId !== "c" && activeEditor.document.languageId !== "cpp" && activeEditor.document.languageId !== "cuda-cpp") { return; } let rootPath = clients.ActiveClient.RootPath; const fileName = activeEditor.document.fileName; if (!rootPath) { rootPath = path.dirname(fileName); } let targetFileName = yield clients.ActiveClient.requestSwitchHeaderSource(rootPath, fileName); let targetFileNameReplaced = false; clients.forEach(client => { if (!targetFileNameReplaced && client.RootRealPath && client.RootPath !== client.RootRealPath && targetFileName.indexOf(client.RootRealPath) === 0) { targetFileName = client.RootPath + targetFileName.substr(client.RootRealPath.length); targetFileNameReplaced = true; } }); const document = yield vscode.workspace.openTextDocument(targetFileName); let foundEditor = false; vscode.window.visibleTextEditors.forEach((editor, index, array) => { if (editor.document === document && !foundEditor) { foundEditor = true; vscode.window.showTextDocument(document, editor.viewColumn); } }); if (!foundEditor) { vscode.window.showTextDocument(document); } }); } function selectClient() { return __awaiter(this, void 0, void 0, function* () { if (clients.Count === 1) { return clients.ActiveClient; } else { const key = yield ui.showWorkspaces(clients.Names); if (key !== "") { const client = clients.get(key); if (client) { return client; } else { console.assert("client not found"); } } throw new Error(localize(7, null)); } }); } function onResetDatabase() { onActivationEvent(); clients.ActiveClient.resetDatabase(); } function onSelectConfiguration() { onActivationEvent(); if (!isFolderOpen()) { vscode.window.showInformationMessage(localize(8, null)); } else { clients.ActiveClient.handleConfigurationSelectCommand(); } } function onSelectConfigurationProvider() { onActivationEvent(); if (!isFolderOpen()) { vscode.window.showInformationMessage(localize(9, null)); } else { selectClient().then(client => client.handleConfigurationProviderSelectCommand(), rejected => { }); } } function onEditConfigurationJSON(viewColumn = vscode.ViewColumn.Active) { onActivationEvent(); telemetry.logLanguageServerEvent("SettingsCommand", { "palette": "json" }, undefined); if (!isFolderOpen()) { vscode.window.showInformationMessage(localize(10, null)); } else { selectClient().then(client => client.handleConfigurationEditJSONCommand(viewColumn), rejected => { }); } } function onEditConfigurationUI(viewColumn = vscode.ViewColumn.Active) { onActivationEvent(); telemetry.logLanguageServerEvent("SettingsCommand", { "palette": "ui" }, undefined); if (!isFolderOpen()) { vscode.window.showInformationMessage(localize(11, null)); } else { selectClient().then(client => client.handleConfigurationEditUICommand(viewColumn), rejected => { }); } } function onEditConfiguration(viewColumn = vscode.ViewColumn.Active) { onActivationEvent(); if (!isFolderOpen()) { vscode.window.showInformationMessage(localize(12, null)); } else { selectClient().then(client => client.handleConfigurationEditCommand(viewColumn), rejected => { }); } } function onGenerateEditorConfig() { onActivationEvent(); if (!isFolderOpen()) { settings_1.generateEditorConfig(); } else { selectClient().then(client => settings_1.generateEditorConfig(client.RootUri)); } } function onGoToNextDirectiveInGroup() { onActivationEvent(); const client = getActiveClient(); client.handleGoToDirectiveInGroup(true); } function onGoToPrevDirectiveInGroup() { onActivationEvent(); const client = getActiveClient(); client.handleGoToDirectiveInGroup(false); } function onCheckForCompiler() { onActivationEvent(); const client = getActiveClient(); client.handleCheckForCompiler(); } function onAddToIncludePath(path) { if (!isFolderOpen()) { vscode.window.showInformationMessage(localize(13, null, "includePath")); } else { clients.ActiveClient.handleAddToIncludePathCommand(path); } } function onEnableSquiggles() { onActivationEvent(); const settings = new settings_1.CppSettings(clients.ActiveClient.RootUri); settings.update("errorSquiggles", "Enabled"); } function onDisableSquiggles() { onActivationEvent(); const settings = new settings_1.CppSettings(clients.ActiveClient.RootUri); settings.update("errorSquiggles", "Disabled"); } function onToggleIncludeFallback() { onActivationEvent(); const settings = new settings_1.CppSettings(clients.ActiveClient.RootUri); settings.toggleSetting("intelliSenseEngineFallback", "Enabled", "Disabled"); } function onToggleDimInactiveRegions() { onActivationEvent(); const settings = new settings_1.CppSettings(clients.ActiveClient.RootUri); settings.update("dimInactiveRegions", !settings.dimInactiveRegions); } function onPauseParsing() { onActivationEvent(); clients.ActiveClient.pauseParsing(); } function onResumeParsing() { onActivationEvent(); clients.ActiveClient.resumeParsing(); } function onShowParsingCommands() { onActivationEvent(); clients.ActiveClient.handleShowParsingCommands(); } function onShowReferencesProgress() { onActivationEvent(); clients.ActiveClient.handleReferencesIcon(); } function onToggleRefGroupView() { const client = getActiveClient(); client.toggleReferenceResultsView(); } function onTakeSurvey() { onActivationEvent(); telemetry.logLanguageServerEvent("onTakeSurvey"); const uri = vscode.Uri.parse(`https://www.research.net/r/VBVV6C6?o=${os.platform()}&m=${vscode.env.machineId}`); vscode.commands.executeCommand('vscode.open', uri); } function onVcpkgOnlineHelpSuggested(dummy) { telemetry.logLanguageServerEvent('vcpkgAction', { 'source': dummy ? 'CodeAction' : 'CommandPalette', 'action': 'vcpkgOnlineHelpSuggested' }); const uri = vscode.Uri.parse(`https://aka.ms/vcpkg`); vscode.commands.executeCommand('vscode.open', uri); } function onVcpkgClipboardInstallSuggested(ports) { return __awaiter(this, void 0, void 0, function* () { onActivationEvent(); let source; if (ports && ports.length) { source = 'CodeAction'; } else { source = 'CommandPalette'; const missingIncludeLocations = []; vscode.languages.getDiagnostics().forEach(uriAndDiagnostics => { const textDocument = vscode.workspace.textDocuments.find(doc => doc.uri.fsPath === uriAndDiagnostics[0].fsPath); if (!textDocument) { return; } let lines = uriAndDiagnostics[1].filter(isMissingIncludeDiagnostic).map(d => d.range.start.line); if (!lines.length) { return; } lines = lines.filter((line, index) => { const foundIndex = lines.indexOf(line); return foundIndex === index; }); missingIncludeLocations.push([textDocument, lines]); }); if (!missingIncludeLocations.length) { return; } const portsPromises = []; missingIncludeLocations.forEach(docAndLineNumbers => { docAndLineNumbers[1].forEach((line) => __awaiter(this, void 0, void 0, function* () { portsPromises.push(lookupIncludeInVcpkg(docAndLineNumbers[0], line)); })); }); ports = [].concat(...(yield Promise.all(portsPromises))); if (!ports.length) { return; } const ports2 = ports; ports = ports2.filter((port, index) => ports2.indexOf(port) === index); } let installCommand = 'vcpkg install'; ports.forEach(port => installCommand += ` ${port}`); telemetry.logLanguageServerEvent('vcpkgAction', { 'source': source, 'action': 'vcpkgClipboardInstallSuggested', 'ports': ports.toString() }); yield vscode.env.clipboard.writeText(installCommand); }); } function onSetActiveConfigName(configurationName) { return clients.ActiveClient.setCurrentConfigName(configurationName); } function onGetActiveConfigName() { return clients.ActiveClient.getCurrentConfigName(); } function onGetActiveConfigCustomVariable(variableName) { return clients.ActiveClient.getCurrentConfigCustomVariable(variableName); } function onLogDiagnostics() { onActivationEvent(); clients.ActiveClient.logDiagnostics(); } function onRescanWorkspace() { onActivationEvent(); clients.ActiveClient.rescanFolder(); } function onShowRefCommand(arg) { if (!arg) { return; } const { node } = arg; if (node === referencesModel_1.NodeType.reference) { const { referenceLocation } = arg; if (referenceLocation) { vscode.window.showTextDocument(referenceLocation.uri, { selection: referenceLocation.range.with({ start: referenceLocation.range.start, end: referenceLocation.range.end }) }); } } else if (node === referencesModel_1.NodeType.fileWithPendingRef) { const { fileUri } = arg; if (fileUri) { vscode.window.showTextDocument(fileUri); } } } function reportMacCrashes() { if (process.platform === "darwin") { prevCrashFile = ""; const home = os.homedir(); const crashFolder = path.resolve(home, "Library/Logs/DiagnosticReports"); fs.stat(crashFolder, (err, stats) => { var _a; const crashObject = {}; if ((_a = err) === null || _a === void 0 ? void 0 : _a.code) { crashObject["fs.stat: err.code"] = err.code; telemetry.logLanguageServerEvent("MacCrash", crashObject, undefined); return; } try { fs.watch(crashFolder, (event, filename) => { if (event !== "rename") { return; } if (filename === prevCrashFile) { return; } prevCrashFile = filename; if (!filename.startsWith("cpptools")) { return; } setTimeout(() => { fs.readFile(path.resolve(crashFolder, filename), 'utf8', (err, data) => { if (err) { fs.readFile(path.resolve(crashFolder, filename), 'utf8', handleMacCrashFileRead); return; } handleMacCrashFileRead(err, data); }); }, 5000); }); } catch (e) { } }); } } let previousMacCrashData; let previousMacCrashCount = 0; function logMacCrashTelemetry(data) { const crashObject = {}; const crashCountObject = {}; crashObject["CrashingThreadCallStack"] = data; previousMacCrashCount = data === previousMacCrashData ? previousMacCrashCount + 1 : 0; previousMacCrashData = data; crashCountObject["CrashCount"] = previousMacCrashCount; telemetry.logLanguageServerEvent("MacCrash", crashObject, crashCountObject); } function handleMacCrashFileRead(err, data) { if (err) { return logMacCrashTelemetry("readFile: " + err.code); } let binaryVersion = ""; const startVersion = data.indexOf("Version:"); if (startVersion >= 0) { data = data.substr(startVersion); const binaryVersionMatches = data.match(/^Version:\s*(\d*\.\d*\.\d*\.\d*|\d)/); binaryVersion = binaryVersionMatches && binaryVersionMatches.length > 1 ? binaryVersionMatches[1] : ""; } const crashStart = " Crashed:"; let startCrash = data.indexOf(crashStart); if (startCrash < 0) { return logMacCrashTelemetry("No crash start"); } startCrash += crashStart.length + 1; let endCrash = data.indexOf("Thread ", startCrash); if (endCrash < 0) { endCrash = data.length - 1; } if (endCrash <= startCrash) { return logMacCrashTelemetry("No crash end"); } data = data.substr(startCrash, endCrash - startCrash); data = data.replace(/0x................ /g, ""); data = data.replace(/0x1........ \+ 0/g, ""); const process1 = "cpptools-srv"; const process2 = "cpptools"; if (data.includes(process1)) { data = data.replace(new RegExp(process1 + "\\s+", "g"), ""); data = `${process1}\t${binaryVersion}\n${data}`; } else if (data.includes(process2)) { data = data.replace(new RegExp(process2 + "\\s+", "g"), ""); data = `${process2}\t${binaryVersion}\n${data}`; } else { data = `cpptools?\t${binaryVersion}\n${data}`; } const lines = data.split("\n"); data = ""; lines.forEach((line) => { if (!line.includes(".dylib") && !line.includes("???")) { line = line.replace(/^\d+\s+/, ""); line = line.replace(/std::__1::/g, "std::"); data += (line + "\n"); } }); data = data.trimRight(); if (data.length > 8192) { data = data.substr(0, 8189) + "..."; } logMacCrashTelemetry(data); } function deactivate() { clients.timeTelemetryCollector.clear(); console.log("deactivating extension"); telemetry.logLanguageServerEvent("LanguageServerShutdown"); clearInterval(intervalTimer); clearInterval(insiderUpdateTimer); disposables.forEach(d => d.dispose()); languageConfigurations.forEach(d => d.dispose()); ui.dispose(); if (taskProvider) { taskProvider.dispose(); } if (codeActionProvider) { codeActionProvider.dispose(); } return clients.dispose(); } exports.deactivate = deactivate; function isFolderOpen() { return vscode.workspace.workspaceFolders !== undefined && vscode.workspace.workspaceFolders.length > 0; } exports.isFolderOpen = isFolderOpen; function getClients() { if (!realActivationOccurred) { realActivation(); } return clients; } exports.getClients = getClients; function getActiveClient() { if (!realActivationOccurred) { realActivation(); } return clients.ActiveClient; } exports.getActiveClient = getActiveClient; /***/ }), /***/ 1626: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const settings_1 = __webpack_require__(296); const logger_1 = __webpack_require__(5610); const nls = __webpack_require__(3612); const common_1 = __webpack_require__(5331); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\languageConfig.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\languageConfig.ts')); const escapeChars = /[\\\^\$\*\+\?\{\}\(\)\.\!\=\|\[\]\ \/]/; function escape(chars) { let result = ""; for (const char of chars) { if (char.match(escapeChars)) { result += `\\${char}`; } else { result += char; } } return result; } function getMLBeginPattern(insert) { if (insert.startsWith("/*")) { const match = escape(insert.substr(2)); return `^\\s*\\/\\*${match}(?!\\/)([^\\*]|\\*(?!\\/))*$`; } return undefined; } function getMLSplitAfterPattern() { return "^\\s*\\*\\/$"; } function getMLPreviousLinePattern(insert) { if (insert.startsWith("/*")) { return `(?=^(\\s*(\\/\\*\\*|\\*)).*)(?=(?!(\\s*\\*\\/)))`; } return undefined; } function getMLContinuePattern(insert) { if (insert) { const match = escape(insert.trimRight()); if (match) { const right = escape(insert.substr(insert.trimRight().length)); return `^(\\t|[ ])*${match}(${right}([^\\*]|\\*(?!\\/))*)?$`; } } return undefined; } function getMLEmptyEndPattern(insert) { insert = insert.trimRight(); if (insert !== "") { if (insert.endsWith('*')) { insert = insert.substr(0, insert.length - 1); } const match = escape(insert.trimRight()); return `^(\\t|[ ])*${match}\\*\\/\\s*$`; } return undefined; } function getMLEndPattern(insert) { const match = escape(insert.trimRight().trimLeft()); if (match) { return `^(\\t|[ ])*${match}[^/]*\\*\\/\\s*$`; } return undefined; } function getSLBeginPattern(insert) { const match = escape(insert.trimRight()); return `^\\s*${match}.*$`; } function getSLContinuePattern(insert) { const match = escape(insert.trimRight()); return `^\\s*${match}.+$`; } function getSLEndPattern(insert) { let match = escape(insert); const trimmed = escape(insert.trimRight()); if (match !== trimmed) { match = `(${match}|${trimmed})`; } return `^\\s*${match}$`; } function getMLSplitRule(comment) { const beforePattern = getMLBeginPattern(comment.begin); if (beforePattern) { return { beforeText: new RegExp(beforePattern), afterText: new RegExp(getMLSplitAfterPattern()), action: { indentAction: vscode.IndentAction.IndentOutdent, appendText: comment.continue ? comment.continue : '' } }; } return undefined; } function getMLFirstLineRule(comment) { const beforePattern = getMLBeginPattern(comment.begin); if (beforePattern) { return { beforeText: new RegExp(beforePattern), action: { indentAction: vscode.IndentAction.None, appendText: comment.continue ? comment.continue : '' } }; } return undefined; } function getMLContinuationRule(comment) { const previousLinePattern = getMLPreviousLinePattern(comment.begin); if (previousLinePattern) { const beforePattern = getMLContinuePattern(comment.continue); if (beforePattern) { return { beforeText: new RegExp(beforePattern), previousLineText: new RegExp(previousLinePattern), action: { indentAction: vscode.IndentAction.None, appendText: comment.continue.trimLeft() } }; } } return undefined; } function getMLEndRule(comment) { const beforePattern = getMLEndPattern(comment.continue); if (beforePattern) { return { beforeText: new RegExp(beforePattern), action: { indentAction: vscode.IndentAction.None, removeText: comment.continue.length - comment.continue.trimLeft().length } }; } return undefined; } function getMLEmptyEndRule(comment) { const beforePattern = getMLEmptyEndPattern(comment.continue); if (beforePattern) { return { beforeText: new RegExp(beforePattern), action: { indentAction: vscode.IndentAction.None, removeText: comment.continue.length - comment.continue.trimLeft().length } }; } return undefined; } function getSLFirstLineRule(comment) { const beforePattern = getSLBeginPattern(comment.begin); return { beforeText: new RegExp(beforePattern), action: { indentAction: vscode.IndentAction.None, appendText: comment.continue.trimLeft() } }; } function getSLContinuationRule(comment) { const beforePattern = getSLContinuePattern(comment.continue); return { beforeText: new RegExp(beforePattern), action: { indentAction: vscode.IndentAction.None, appendText: comment.continue.trimLeft() } }; } function getSLEndRule(comment) { const beforePattern = getSLEndPattern(comment.continue); return { beforeText: new RegExp(beforePattern), action: { indentAction: vscode.IndentAction.None, removeText: comment.continue.length - comment.continue.trimLeft().length } }; } function getLanguageConfig(languageId) { const settings = new settings_1.CppSettings(); const patterns = settings.commentContinuationPatterns; return getLanguageConfigFromPatterns(languageId, patterns); } exports.getLanguageConfig = getLanguageConfig; function getLanguageConfigFromPatterns(languageId, patterns) { const beginPatterns = []; const continuePatterns = []; let duplicates = false; let beginRules = []; let continueRules = []; let endRules = []; if (!patterns) { patterns = ["/**"]; } patterns.forEach(pattern => { const c = common_1.isString(pattern) ? { begin: pattern, continue: pattern.startsWith('/*') ? " * " : pattern } : pattern; const r = constructCommentRules(c, languageId); if (beginPatterns.indexOf(c.begin) < 0) { if (r.begin && r.begin.length > 0) { beginRules = beginRules.concat(r.begin); } beginPatterns.push(c.begin); } else { duplicates = true; } if (continuePatterns.indexOf(c.continue) < 0) { if (r.continue && r.continue.length > 0) { continueRules = continueRules.concat(r.continue); } if (r.end && r.end.length > 0) { endRules = endRules.concat(r.end); } continuePatterns.push(c.continue); } }); if (duplicates) { logger_1.getOutputChannel().appendLine(localize(0, null)); } return { onEnterRules: beginRules.concat(continueRules).concat(endRules).filter(e => (e)) }; } exports.getLanguageConfigFromPatterns = getLanguageConfigFromPatterns; function constructCommentRules(comment, languageId) { var _a, _b, _c, _d; if (((_b = (_a = comment) === null || _a === void 0 ? void 0 : _a.begin) === null || _b === void 0 ? void 0 : _b.startsWith('/*')) && (languageId === 'c' || languageId === 'cpp' || languageId === 'cuda-cpp')) { const mlBegin1 = getMLSplitRule(comment); if (!mlBegin1) { throw new Error("Failure in constructCommentRules() - mlBegin1"); } const mlBegin2 = getMLFirstLineRule(comment); if (!mlBegin2) { throw new Error("Failure in constructCommentRules() - mlBegin2"); } const mlContinue = getMLContinuationRule(comment); if (!mlContinue) { throw new Error("Failure in constructCommentRules() - mlContinue"); } const mlEnd1 = getMLEmptyEndRule(comment); if (!mlEnd1) { throw new Error("Failure in constructCommentRules() - mlEnd1"); } const mlEnd2 = getMLEndRule(comment); if (!mlEnd2) { throw new Error("Failure in constructCommentRules() = mlEnd2"); } return { begin: [mlBegin1, mlBegin2], continue: [mlContinue], end: [mlEnd1, mlEnd2] }; } else if (((_d = (_c = comment) === null || _c === void 0 ? void 0 : _c.begin) === null || _d === void 0 ? void 0 : _d.startsWith('//')) && (languageId === 'cpp' || languageId === 'cuda-cpp')) { const slContinue = getSLContinuationRule(comment); const slEnd = getSLEndRule(comment); if (comment.begin !== comment.continue) { const slBegin = getSLFirstLineRule(comment); return { begin: (comment.begin === comment.continue) ? [] : [slBegin], continue: [slContinue], end: [slEnd] }; } else { return { begin: [], continue: [slContinue], end: [slEnd] }; } } return { begin: [], continue: [], end: [] }; } /***/ }), /***/ 1102: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const util = __webpack_require__(5331); const path = __webpack_require__(5622); class PersistentStateBase { constructor(key, defaultValue, state) { this.key = key; this.defaultvalue = defaultValue; this.state = state; this.curvalue = defaultValue; } get Value() { return this.state ? this.state.get(this.key, this.defaultvalue) : this.curvalue; } set Value(newValue) { if (this.state) { this.state.update(this.key, newValue); } this.curvalue = newValue; } get DefaultValue() { return this.defaultvalue; } setDefault() { if (this.state) { this.state.update(this.key, this.defaultvalue); } this.curvalue = this.defaultvalue; } } class PersistentState extends PersistentStateBase { constructor(key, defaultValue) { super(key, defaultValue, util.extensionContext ? util.extensionContext.globalState : undefined); } } exports.PersistentState = PersistentState; class PersistentWorkspaceState extends PersistentStateBase { constructor(key, defaultValue) { super(key, defaultValue, util.extensionContext ? util.extensionContext.workspaceState : undefined); } } exports.PersistentWorkspaceState = PersistentWorkspaceState; class PersistentFolderState extends PersistentWorkspaceState { constructor(key, defaultValue, folder) { const old_key = key + (folder ? `-${path.basename(folder.uri.fsPath)}` : "-untitled"); let old_val; if (util.extensionContext) { old_val = util.extensionContext.workspaceState.get(old_key); if (old_val !== undefined) { util.extensionContext.workspaceState.update(old_key, undefined); } } const newKey = key + (folder ? `-${folder.uri.fsPath}` : "-untitled"); super(newKey, defaultValue); if (old_val !== undefined) { this.Value = old_val; } } } exports.PersistentFolderState = PersistentFolderState; /***/ }), /***/ 9696: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __webpack_require__(5622); const vscode = __webpack_require__(7549); const settings_1 = __webpack_require__(296); const extension_1 = __webpack_require__(2973); function createProtocolFilter(clients) { const defaultHandler = (data, callback) => { clients.ActiveClient.notifyWhenLanguageClientReady(() => callback(data)); }; const invoke2 = (a, b, callback) => clients.ActiveClient.requestWhenReady(() => callback(a, b)); const invoke3 = (a, b, c, callback) => clients.ActiveClient.requestWhenReady(() => callback(a, b, c)); const invoke4 = (a, b, c, d, callback) => clients.ActiveClient.requestWhenReady(() => callback(a, b, c, d)); const invoke5 = (a, b, c, d, e, callback) => clients.ActiveClient.requestWhenReady(() => callback(a, b, c, d, e)); return { didOpen: (document, sendMessage) => { const editor = vscode.window.visibleTextEditors.find(e => e.document === document); if (editor) { const me = clients.getClientFor(document.uri); if (!me.TrackedDocuments.has(document)) { clients.timeTelemetryCollector.setDidOpenTime(document.uri); if (clients.checkOwnership(me, document)) { me.TrackedDocuments.add(document); const finishDidOpen = (doc) => { me.provideCustomConfiguration(doc.uri, undefined); me.notifyWhenLanguageClientReady(() => { sendMessage(doc); me.onDidOpenTextDocument(doc); if (editor && editor === vscode.window.activeTextEditor) { extension_1.onDidChangeActiveTextEditor(editor); } }); }; let languageChanged = false; if ((document.uri.path.endsWith(".C") || document.uri.path.endsWith(".H")) && document.languageId === "c") { const cppSettings = new settings_1.CppSettings(); if (cppSettings.autoAddFileAssociations) { const fileName = path.basename(document.uri.fsPath); const mappingString = fileName + "@" + document.uri.fsPath; me.addFileAssociations(mappingString, "cpp"); me.sendDidChangeSettings({ files: { associations: new settings_1.OtherSettings().filesAssociations } }); vscode.languages.setTextDocumentLanguage(document, "cpp").then((newDoc) => { finishDidOpen(newDoc); }); languageChanged = true; } } if (!languageChanged) { finishDidOpen(document); } } } } else { } }, didChange: (textDocumentChangeEvent, sendMessage) => { const me = clients.getClientFor(textDocumentChangeEvent.document.uri); if (!me.TrackedDocuments.has(textDocumentChangeEvent.document)) { extension_1.processDelayedDidOpen(textDocumentChangeEvent.document); } me.onDidChangeTextDocument(textDocumentChangeEvent); me.notifyWhenLanguageClientReady(() => sendMessage(textDocumentChangeEvent)); }, willSave: defaultHandler, willSaveWaitUntil: (event, sendMessage) => { const me = clients.getClientFor(event.document.uri); if (me.TrackedDocuments.has(event.document)) { return me.requestWhenReady(() => sendMessage(event)); } return Promise.resolve([]); }, didSave: defaultHandler, didClose: (document, sendMessage) => { const me = clients.getClientFor(document.uri); if (me.TrackedDocuments.has(document)) { me.onDidCloseTextDocument(document); me.TrackedDocuments.delete(document); me.notifyWhenLanguageClientReady(() => sendMessage(document)); } }, provideCompletionItem: invoke4, resolveCompletionItem: invoke2, provideHover: (document, position, token, next) => { const me = clients.getClientFor(document.uri); if (clients.checkOwnership(me, document)) { return clients.ActiveClient.requestWhenReady(() => next(document, position, token)); } return null; }, provideSignatureHelp: invoke3, provideDefinition: invoke3, provideReferences: invoke4, provideDocumentHighlights: invoke3, provideDocumentSymbols: invoke2, provideWorkspaceSymbols: invoke2, provideCodeActions: invoke4, provideCodeLenses: invoke2, resolveCodeLens: invoke2, provideDocumentFormattingEdits: invoke3, provideDocumentRangeFormattingEdits: invoke4, provideOnTypeFormattingEdits: invoke5, provideRenameEdits: invoke4, provideDocumentLinks: invoke2, resolveDocumentLink: invoke2, provideDeclaration: invoke3 }; } exports.createProtocolFilter = createProtocolFilter; /***/ }), /***/ 2664: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const referencesView_1 = __webpack_require__(3053); const telemetry = __webpack_require__(1818); const nls = __webpack_require__(3612); const logger = __webpack_require__(5610); const persistentState_1 = __webpack_require__(1102); const util = __webpack_require__(5331); const timers_1 = __webpack_require__(8213); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\references.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\references.ts')); var ReferenceType; (function (ReferenceType) { ReferenceType[ReferenceType["Confirmed"] = 0] = "Confirmed"; ReferenceType[ReferenceType["ConfirmationInProgress"] = 1] = "ConfirmationInProgress"; ReferenceType[ReferenceType["Comment"] = 2] = "Comment"; ReferenceType[ReferenceType["String"] = 3] = "String"; ReferenceType[ReferenceType["Inactive"] = 4] = "Inactive"; ReferenceType[ReferenceType["CannotConfirm"] = 5] = "CannotConfirm"; ReferenceType[ReferenceType["NotAReference"] = 6] = "NotAReference"; })(ReferenceType = exports.ReferenceType || (exports.ReferenceType = {})); var ReferencesProgress; (function (ReferencesProgress) { ReferencesProgress[ReferencesProgress["Started"] = 0] = "Started"; ReferencesProgress[ReferencesProgress["StartedRename"] = 1] = "StartedRename"; ReferencesProgress[ReferencesProgress["ProcessingSource"] = 2] = "ProcessingSource"; ReferencesProgress[ReferencesProgress["ProcessingTargets"] = 3] = "ProcessingTargets"; })(ReferencesProgress || (ReferencesProgress = {})); var TargetReferencesProgress; (function (TargetReferencesProgress) { TargetReferencesProgress[TargetReferencesProgress["WaitingToLex"] = 0] = "WaitingToLex"; TargetReferencesProgress[TargetReferencesProgress["Lexing"] = 1] = "Lexing"; TargetReferencesProgress[TargetReferencesProgress["WaitingToParse"] = 2] = "WaitingToParse"; TargetReferencesProgress[TargetReferencesProgress["Parsing"] = 3] = "Parsing"; TargetReferencesProgress[TargetReferencesProgress["ConfirmingReferences"] = 4] = "ConfirmingReferences"; TargetReferencesProgress[TargetReferencesProgress["FinishedWithoutConfirming"] = 5] = "FinishedWithoutConfirming"; TargetReferencesProgress[TargetReferencesProgress["FinishedConfirming"] = 6] = "FinishedConfirming"; })(TargetReferencesProgress || (TargetReferencesProgress = {})); var ReferencesCommandMode; (function (ReferencesCommandMode) { ReferencesCommandMode[ReferencesCommandMode["None"] = 0] = "None"; ReferencesCommandMode[ReferencesCommandMode["Find"] = 1] = "Find"; ReferencesCommandMode[ReferencesCommandMode["Peek"] = 2] = "Peek"; ReferencesCommandMode[ReferencesCommandMode["Rename"] = 3] = "Rename"; })(ReferencesCommandMode = exports.ReferencesCommandMode || (exports.ReferencesCommandMode = {})); function referencesCommandModeToString(referencesCommandMode) { switch (referencesCommandMode) { case ReferencesCommandMode.Find: return localize(0, null); case ReferencesCommandMode.Peek: return localize(1, null); case ReferencesCommandMode.Rename: return localize(2, null); default: return ""; } } exports.referencesCommandModeToString = referencesCommandModeToString; function convertReferenceTypeToString(referenceType, upperCase) { if (upperCase) { switch (referenceType) { case ReferenceType.Confirmed: return localize(3, null); case ReferenceType.ConfirmationInProgress: return localize(4, null); case ReferenceType.Comment: return localize(5, null); case ReferenceType.String: return localize(6, null); case ReferenceType.Inactive: return localize(7, null); case ReferenceType.CannotConfirm: return localize(8, null); case ReferenceType.NotAReference: return localize(9, null); } } else { switch (referenceType) { case ReferenceType.Confirmed: return localize(10, null); case ReferenceType.ConfirmationInProgress: return localize(11, null); case ReferenceType.Comment: return localize(12, null); case ReferenceType.String: return localize(13, null); case ReferenceType.Inactive: return localize(14, null); case ReferenceType.CannotConfirm: return localize(15, null); case ReferenceType.NotAReference: return localize(16, null); } } return ""; } exports.convertReferenceTypeToString = convertReferenceTypeToString; function getReferenceCanceledString(upperCase) { return upperCase ? localize(17, null) : localize(18, null); } function getReferenceTagString(referenceType, referenceCanceled, upperCase) { return referenceCanceled && referenceType === ReferenceType.ConfirmationInProgress ? getReferenceCanceledString(upperCase) : convertReferenceTypeToString(referenceType, upperCase); } exports.getReferenceTagString = getReferenceTagString; function getReferenceTypeIconPath(referenceType) { const assetsFolder = "assets/"; const postFixLight = "-light.svg"; const postFixDark = "-dark.svg"; let basePath = "ref-cannot-confirm"; switch (referenceType) { case ReferenceType.Confirmed: basePath = "ref-confirmed"; break; case ReferenceType.Comment: basePath = "ref-comment"; break; case ReferenceType.String: basePath = "ref-string"; break; case ReferenceType.Inactive: basePath = "ref-inactive"; break; case ReferenceType.CannotConfirm: basePath = "ref-cannot-confirm"; break; case ReferenceType.NotAReference: basePath = "ref-not-a-reference"; break; case ReferenceType.ConfirmationInProgress: basePath = "ref-confirmation-in-progress"; break; } const lightPath = util.getExtensionFilePath(assetsFolder + basePath + postFixLight); const lightPathUri = vscode.Uri.file(lightPath); const darkPath = util.getExtensionFilePath(assetsFolder + basePath + postFixDark); const darkPathUri = vscode.Uri.file(darkPath); return { light: lightPathUri, dark: darkPathUri }; } exports.getReferenceTypeIconPath = getReferenceTypeIconPath; function getReferenceCanceledIconPath() { const lightPath = util.getExtensionFilePath("assets/ref-canceled-light.svg"); const lightPathUri = vscode.Uri.file(lightPath); const darkPath = util.getExtensionFilePath("assets/ref-canceled-dark.svg"); const darkPathUri = vscode.Uri.file(darkPath); return { light: lightPathUri, dark: darkPathUri }; } function getReferenceItemIconPath(type, isCanceled) { return (isCanceled && type === ReferenceType.ConfirmationInProgress) ? getReferenceCanceledIconPath() : getReferenceTypeIconPath(type); } exports.getReferenceItemIconPath = getReferenceItemIconPath; class ReferencesManager { constructor(client) { this.disposables = []; this.viewsInitialized = false; this.symbolSearchInProgress = false; this.referencesPrevProgressIncrement = 0; this.referencesPrevProgressMessage = ""; this.referencesRequestHasOccurred = false; this.referencesFinished = false; this.referencesRequestPending = false; this.referencesRefreshPending = false; this.referencesCanceled = false; this.referencesCurrentProgressUICounter = 0; this.referencesProgressUpdateInterval = 1000; this.referencesProgressDelayInterval = 2000; this.prevVisibleRangesLength = 0; this.visibleRangesDecreased = false; this.visibleRangesDecreasedTicks = 0; this.ticksForDetectingPeek = 1000; this.groupByFile = new persistentState_1.PersistentState("CPP.referencesGroupByFile", false); this.lastResults = null; this.client = client; } initializeViews() { if (!this.viewsInitialized) { this.findAllRefsView = new referencesView_1.FindAllRefsView(); this.viewsInitialized = true; } } dispose() { this.disposables.forEach((d) => d.dispose()); this.disposables = []; } toggleGroupView() { this.groupByFile.Value = !this.groupByFile.Value; if (this.findAllRefsView) { this.findAllRefsView.setGroupBy(this.groupByFile.Value); } } UpdateProgressUICounter(mode) { if (mode !== ReferencesCommandMode.None) { ++this.referencesCurrentProgressUICounter; } } updateVisibleRange(visibleRangesLength) { this.visibleRangesDecreased = visibleRangesLength < this.prevVisibleRangesLength; if (this.visibleRangesDecreased) { this.visibleRangesDecreasedTicks = Date.now(); } this.prevVisibleRangesLength = visibleRangesLength; } reportProgress(progress, forceUpdate, mode) { const helpMessage = (mode !== ReferencesCommandMode.Find) ? "" : ` ${localize(19, null)}`; if (this.referencesCurrentProgress) { switch (this.referencesCurrentProgress.referencesProgress) { case ReferencesProgress.Started: case ReferencesProgress.StartedRename: progress.report({ message: localize(20, null), increment: 0 }); break; case ReferencesProgress.ProcessingSource: progress.report({ message: localize(21, null), increment: 0 }); break; case ReferencesProgress.ProcessingTargets: let numWaitingToLex = 0; let numLexing = 0; let numParsing = 0; let numConfirmingReferences = 0; let numFinishedWithoutConfirming = 0; let numFinishedConfirming = 0; for (const targetLocationProgress of this.referencesCurrentProgress.targetReferencesProgress) { switch (targetLocationProgress) { case TargetReferencesProgress.WaitingToLex: ++numWaitingToLex; break; case TargetReferencesProgress.Lexing: ++numLexing; break; case TargetReferencesProgress.WaitingToParse: break; case TargetReferencesProgress.Parsing: ++numParsing; break; case TargetReferencesProgress.ConfirmingReferences: ++numConfirmingReferences; break; case TargetReferencesProgress.FinishedWithoutConfirming: ++numFinishedWithoutConfirming; break; case TargetReferencesProgress.FinishedConfirming: ++numFinishedConfirming; break; default: break; } } let currentMessage; const numTotalToLex = this.referencesCurrentProgress.targetReferencesProgress.length; const numFinishedLexing = numTotalToLex - numWaitingToLex - numLexing; const numTotalToParse = this.referencesCurrentProgress.targetReferencesProgress.length - numFinishedWithoutConfirming; if (numLexing >= (numParsing + numConfirmingReferences) && numFinishedConfirming === 0) { if (numTotalToLex === 0) { currentMessage = localize(22, null); } else { currentMessage = localize(23, null, numFinishedLexing, numTotalToLex, helpMessage); } } else { currentMessage = localize(24, null, numFinishedConfirming, numTotalToParse, helpMessage); } const currentLexProgress = numFinishedLexing / numTotalToLex; const confirmingWeight = 0.5; const currentParseProgress = (numConfirmingReferences * confirmingWeight + numFinishedConfirming) / numTotalToParse; const averageLexingPercent = 25; const currentIncrement = currentLexProgress * averageLexingPercent + currentParseProgress * (100 - averageLexingPercent); if (forceUpdate || currentIncrement > this.referencesPrevProgressIncrement || currentMessage !== this.referencesPrevProgressMessage) { progress.report({ message: currentMessage, increment: currentIncrement - this.referencesPrevProgressIncrement }); this.referencesPrevProgressIncrement = currentIncrement; this.referencesPrevProgressMessage = currentMessage; } break; } } } handleProgressStarted(referencesProgress) { this.referencesStartedWhileTagParsing = this.client.IsTagParsing; const mode = (referencesProgress === ReferencesProgress.StartedRename) ? ReferencesCommandMode.Rename : (this.visibleRangesDecreased && (Date.now() - this.visibleRangesDecreasedTicks < this.ticksForDetectingPeek) ? ReferencesCommandMode.Peek : ReferencesCommandMode.Find); this.client.setReferencesCommandMode(mode); this.referencesPrevProgressIncrement = 0; this.referencesPrevProgressMessage = ""; this.referencesCurrentProgressUICounter = 0; this.currentUpdateProgressTimer = undefined; this.currentUpdateProgressResolve = undefined; let referencePreviousProgressUICounter = 0; this.clearViews(); this.referencesDelayProgress = timers_1.setInterval(() => { this.referencesProgressOptions = { location: vscode.ProgressLocation.Notification, title: referencesCommandModeToString(this.client.ReferencesCommandMode), cancellable: true }; this.referencesProgressMethod = (progress, token) => new Promise((resolve) => { this.currentUpdateProgressResolve = resolve; this.reportProgress(progress, true, mode); this.currentUpdateProgressTimer = timers_1.setInterval(() => { if (token.isCancellationRequested && !this.referencesCanceled) { this.client.cancelReferences(); this.referencesCanceled = true; } if (this.referencesCurrentProgressUICounter !== referencePreviousProgressUICounter) { if (this.currentUpdateProgressTimer) { clearInterval(this.currentUpdateProgressTimer); } this.currentUpdateProgressTimer = undefined; if (this.referencesCurrentProgressUICounter !== referencePreviousProgressUICounter) { referencePreviousProgressUICounter = this.referencesCurrentProgressUICounter; this.referencesPrevProgressIncrement = 0; if (this.referencesProgressOptions && this.referencesProgressMethod) { vscode.window.withProgress(this.referencesProgressOptions, this.referencesProgressMethod); } } resolve(); } else { this.reportProgress(progress, false, mode); } }, this.referencesProgressUpdateInterval); }); vscode.window.withProgress(this.referencesProgressOptions, this.referencesProgressMethod); if (this.referencesDelayProgress) { clearInterval(this.referencesDelayProgress); } }, this.referencesProgressDelayInterval); } handleProgress(notificationBody) { this.initializeViews(); switch (notificationBody.referencesProgress) { case ReferencesProgress.StartedRename: case ReferencesProgress.Started: if (this.client.ReferencesCommandMode === ReferencesCommandMode.Peek) { telemetry.logLanguageServerEvent("peekReferences"); } this.handleProgressStarted(notificationBody.referencesProgress); break; default: this.referencesCurrentProgress = notificationBody; break; } } startRename(params) { this.lastResults = null; this.referencesFinished = false; this.referencesRequestHasOccurred = false; this.referencesRequestPending = false; this.referencesCanceledWhilePreviewing = false; if (this.referencesCanceled) { this.referencesCanceled = false; if (this.resultsCallback) { this.resultsCallback(null, true); } } else { this.client.sendRenameNofication(params); } } startFindAllReferences(params) { this.lastResults = null; this.referencesFinished = false; this.referencesRequestHasOccurred = false; this.referencesRequestPending = false; this.referencesCanceledWhilePreviewing = false; if (this.referencesCanceled) { this.referencesCanceled = false; if (this.resultsCallback) { this.resultsCallback(null, true); } } else { this.client.sendFindAllReferencesNotification(params); } } processResults(referencesResult) { if (this.referencesFinished) { return; } this.initializeViews(); this.clearViews(); if (this.client.ReferencesCommandMode === ReferencesCommandMode.Peek && !this.referencesChannel) { this.referencesChannel = vscode.window.createOutputChannel(localize(25, null)); this.disposables.push(this.referencesChannel); } if (this.referencesStartedWhileTagParsing) { const msg = localize(26, null, referencesCommandModeToString(this.client.ReferencesCommandMode)); if (this.client.ReferencesCommandMode === ReferencesCommandMode.Peek) { if (this.referencesChannel) { this.referencesChannel.appendLine(msg); this.referencesChannel.appendLine(""); this.referencesChannel.show(true); } } else if (this.client.ReferencesCommandMode === ReferencesCommandMode.Find) { const logChannel = logger.getOutputChannel(); logChannel.appendLine(msg); logChannel.appendLine(""); logChannel.show(true); } } const referencesRequestPending = this.referencesRequestPending; const referencesCanceled = this.referencesCanceled; this.referencesRequestPending = false; this.referencesCanceled = false; const currentReferenceCommandMode = this.client.ReferencesCommandMode; if (referencesResult.isFinished) { this.symbolSearchInProgress = false; if (this.referencesDelayProgress) { clearInterval(this.referencesDelayProgress); } if (this.currentUpdateProgressTimer) { if (this.currentUpdateProgressTimer) { clearInterval(this.currentUpdateProgressTimer); } if (this.currentUpdateProgressResolve) { this.currentUpdateProgressResolve(); } this.currentUpdateProgressResolve = undefined; this.currentUpdateProgressTimer = undefined; } this.client.setReferencesCommandMode(ReferencesCommandMode.None); } if (currentReferenceCommandMode === ReferencesCommandMode.Rename) { if (!referencesCanceled) { if (this.resultsCallback) { this.resultsCallback(referencesResult, true); } } else { if (this.resultsCallback) { this.resultsCallback(null, true); } } } else { if (this.findAllRefsView) { this.findAllRefsView.setData(referencesResult, referencesCanceled, this.groupByFile.Value); } if (currentReferenceCommandMode === ReferencesCommandMode.Peek) { const showConfirmedReferences = referencesCanceled; if (this.findAllRefsView) { const peekReferencesResults = this.findAllRefsView.getResultsAsText(showConfirmedReferences); if (peekReferencesResults) { if (this.referencesChannel) { this.referencesChannel.appendLine(peekReferencesResults); this.referencesChannel.show(true); } } } } else if (currentReferenceCommandMode === ReferencesCommandMode.Find) { if (this.findAllRefsView) { this.findAllRefsView.show(true); } } if (referencesResult.isFinished) { this.lastResults = referencesResult; this.referencesFinished = true; } if (!this.referencesRefreshPending) { if (referencesResult.isFinished && this.referencesRequestHasOccurred && !referencesRequestPending && !this.referencesCanceledWhilePreviewing) { this.referencesRefreshPending = true; vscode.commands.executeCommand("references-view.refresh"); } else { if (this.resultsCallback) { this.resultsCallback(referencesResult, !this.referencesCanceledWhilePreviewing); } } } } } setResultsCallback(callback) { this.symbolSearchInProgress = true; this.resultsCallback = callback; } clearViews() { if (this.client.ReferencesCommandMode !== ReferencesCommandMode.Rename) { if (this.referencesChannel) { this.referencesChannel.clear(); } if (this.findAllRefsView) { this.findAllRefsView.show(false); } } } } exports.ReferencesManager = ReferencesManager; /***/ }), /***/ 9997: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const references_1 = __webpack_require__(2664); class ReferencesModel { constructor(resultsInput, isCanceled, groupByFile, refreshCallback) { this.isCanceled = isCanceled; this.refreshCallback = refreshCallback; this.nodes = []; this.originalSymbol = ""; this.originalSymbol = resultsInput.text; this.groupByFile = groupByFile; const results = resultsInput.referenceInfos.filter(r => r.type !== references_1.ReferenceType.Confirmed); for (const r of results) { const noReferenceLocation = (r.position.line === 0 && r.position.character === 0); if (noReferenceLocation) { const node = new TreeNode(this, NodeType.fileWithPendingRef); node.fileUri = vscode.Uri.file(r.file); node.filename = r.file; node.referenceType = r.type; this.nodes.push(node); } else { const range = new vscode.Range(r.position.line, r.position.character, r.position.line, r.position.character + this.originalSymbol.length); const uri = vscode.Uri.file(r.file); const location = new vscode.Location(uri, range); const node = new TreeNode(this, NodeType.reference); node.fileUri = uri; node.filename = r.file; node.referencePosition = r.position; node.referenceLocation = location; node.referenceText = r.text; node.referenceType = r.type; this.nodes.push(node); } } } hasResults() { return this.nodes.length > 0; } getReferenceTypeNodes() { const result = []; for (const n of this.nodes) { const i = result.findIndex(e => e.referenceType === n.referenceType); if (i < 0) { const node = new TreeNode(this, NodeType.referenceType); node.referenceType = n.referenceType; result.push(node); } } return result; } getFileNodes(refType) { const result = []; let filteredFiles = []; if (refType !== undefined) { filteredFiles = this.nodes.filter(i => i.referenceType === refType); } else { filteredFiles = this.nodes; } for (const n of filteredFiles) { const i = result.findIndex(item => item.filename === n.filename); if (i < 0) { const nodeType = (n.node === NodeType.fileWithPendingRef ? NodeType.fileWithPendingRef : NodeType.file); const node = new TreeNode(this, nodeType); node.filename = n.filename; node.fileUri = n.fileUri; node.referenceType = refType; result.push(node); } } result.sort((a, b) => { if (a.filename === undefined) { if (b.filename === undefined) { return 0; } else { return -1; } } else if (b.filename === undefined) { return 1; } else { return a.filename.localeCompare(b.filename); } }); return result; } getReferenceNodes(filename, refType) { if (refType === undefined || refType === null) { if (filename === undefined || filename === null) { return this.nodes; } return this.nodes.filter(i => i.filename === filename); } if (filename === undefined || filename === null) { return this.nodes.filter(i => i.referenceType === refType); } return this.nodes.filter(i => i.filename === filename && i.referenceType === refType); } getAllReferenceNodes() { return this.nodes.filter(i => i.node === NodeType.reference); } getAllFilesWithPendingReferenceNodes() { const result = this.nodes.filter(i => i.node === NodeType.fileWithPendingRef); result.sort((a, b) => { if (a.filename === undefined) { if (b.filename === undefined) { return 0; } else { return -1; } } else if (b.filename === undefined) { return 1; } else { return a.filename.localeCompare(b.filename); } }); return result; } } exports.ReferencesModel = ReferencesModel; var NodeType; (function (NodeType) { NodeType[NodeType["undefined"] = 0] = "undefined"; NodeType[NodeType["referenceType"] = 1] = "referenceType"; NodeType[NodeType["file"] = 2] = "file"; NodeType[NodeType["fileWithPendingRef"] = 3] = "fileWithPendingRef"; NodeType[NodeType["reference"] = 4] = "reference"; })(NodeType = exports.NodeType || (exports.NodeType = {})); class TreeNode { constructor(model, node) { this.model = model; this.node = node; } } exports.TreeNode = TreeNode; /***/ }), /***/ 6673: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const referencesModel_1 = __webpack_require__(9997); const references_1 = __webpack_require__(2664); const nls = __webpack_require__(3612); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\referencesTreeDataProvider.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\referencesTreeDataProvider.ts')); class ReferencesTreeDataProvider { constructor() { this._onDidChangeTreeData = new vscode.EventEmitter(); this.onDidChangeTreeData = this._onDidChangeTreeData.event; } refresh() { if (this.referencesModel) { vscode.commands.executeCommand('setContext', 'refView.isGroupedByFile', this.referencesModel.groupByFile); this._onDidChangeTreeData.fire(); } } setModel(model) { this.referencesModel = model; vscode.commands.executeCommand('setContext', 'refView.isGroupedByFile', this.referencesModel.groupByFile); this._onDidChangeTreeData.fire(); } clear() { this.referencesModel = undefined; this._onDidChangeTreeData.fire(); } getTreeItem(element) { if (this.referencesModel === undefined) { throw new Error("Undefined RefrencesModel in getTreeItem()"); } switch (element.node) { case referencesModel_1.NodeType.referenceType: if (element.referenceType === undefined) { throw new Error("Undefined referenceType in getTreeItem()"); } const label = references_1.getReferenceTagString(element.referenceType, this.referencesModel.isCanceled, true); const resultRefType = new vscode.TreeItem(label, vscode.TreeItemCollapsibleState.Expanded); return resultRefType; case referencesModel_1.NodeType.file: case referencesModel_1.NodeType.fileWithPendingRef: if (element.fileUri === undefined) { throw new Error("Undefined fileUri in getTreeItem()"); } const resultFile = new vscode.TreeItem(element.fileUri); resultFile.collapsibleState = vscode.TreeItemCollapsibleState.Expanded; resultFile.iconPath = vscode.ThemeIcon.File; resultFile.description = true; if (element.node === referencesModel_1.NodeType.fileWithPendingRef) { resultFile.command = { title: localize(0, null), command: 'C_Cpp.ShowReferenceItem', arguments: [element] }; const tag = references_1.getReferenceTagString(references_1.ReferenceType.ConfirmationInProgress, this.referencesModel.isCanceled); resultFile.tooltip = `[${tag}]\n${element.filename}`; resultFile.collapsibleState = vscode.TreeItemCollapsibleState.None; } return resultFile; case referencesModel_1.NodeType.reference: if (element.referenceText === undefined) { throw new Error("Undefined referenceText in getTreeItem()"); } if (element.referenceType === undefined) { throw new Error("Undefined referenceType in getTreeItem()"); } const resultRef = new vscode.TreeItem(element.referenceText, vscode.TreeItemCollapsibleState.None); resultRef.iconPath = references_1.getReferenceItemIconPath(element.referenceType, this.referencesModel.isCanceled); const tag = references_1.getReferenceTagString(element.referenceType, this.referencesModel.isCanceled); resultRef.tooltip = `[${tag}]\n${element.referenceText}`; resultRef.command = { title: localize(1, null), command: 'C_Cpp.ShowReferenceItem', arguments: [element] }; return resultRef; } throw new Error("Invalid NoteType in getTreeItem()"); } getChildren(element) { if (!this.referencesModel) { return undefined; } if (element instanceof referencesModel_1.TreeNode) { if (element.node === referencesModel_1.NodeType.file) { let type; if (!this.referencesModel.groupByFile) { type = element.referenceType; } return this.referencesModel.getReferenceNodes(element.filename, type); } if (element.node === referencesModel_1.NodeType.referenceType) { return this.referencesModel.getFileNodes(element.referenceType); } } if (this.referencesModel.groupByFile) { return this.referencesModel.getFileNodes(); } else { return this.referencesModel.getReferenceTypeNodes(); } } } exports.ReferencesTreeDataProvider = ReferencesTreeDataProvider; /***/ }), /***/ 3053: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const references_1 = __webpack_require__(2664); const referencesTreeDataProvider_1 = __webpack_require__(6673); const referencesModel_1 = __webpack_require__(9997); class FindAllRefsView { constructor() { this.referenceViewProvider = new referencesTreeDataProvider_1.ReferencesTreeDataProvider(); vscode.window.createTreeView('CppReferencesView', { treeDataProvider: this.referenceViewProvider, showCollapseAll: true }); } show(showView) { if (!showView) { this.clearData(); } let hasResults = false; if (this.referencesModel) { hasResults = this.referencesModel.hasResults(); } vscode.commands.executeCommand('setContext', 'cppReferenceTypes:hasResults', hasResults); } setData(results, isCanceled, groupByFile) { this.referencesModel = new referencesModel_1.ReferencesModel(results, isCanceled, groupByFile, () => { this.referenceViewProvider.refresh(); }); this.referenceViewProvider.setModel(this.referencesModel); } clearData() { this.referenceViewProvider.clear(); } setGroupBy(groupByFile) { if (this.referencesModel) { this.referencesModel.groupByFile = groupByFile; this.referenceViewProvider.refresh(); } } getResultsAsText(includeConfirmedReferences) { let results = []; const confirmedRefs = []; const otherRefs = []; const fileRefs = []; if (!this.referencesModel) { throw new Error("Missiung ReferencesModel in getResultsAsText()"); } for (const ref of this.referencesModel.getAllReferenceNodes()) { let line = ""; if (ref.referenceType !== null && ref.referenceType !== undefined) { line = "[" + references_1.getReferenceTagString(ref.referenceType, this.referencesModel.isCanceled) + "] "; } line += ref.filename; if (ref.referencePosition !== null && ref.referencePosition !== undefined) { line += ":" + (ref.referencePosition.line + 1) + ":" + (ref.referencePosition.character + 1) + " " + ref.referenceText; } if (includeConfirmedReferences && ref.referenceType === references_1.ReferenceType.Confirmed) { confirmedRefs.push(line); } else { otherRefs.push(line); } } const fileReferences = this.referencesModel.getAllFilesWithPendingReferenceNodes(); for (const fileRef of fileReferences) { const line = ("[" + references_1.getReferenceTagString(references_1.ReferenceType.ConfirmationInProgress, this.referencesModel.isCanceled) + "] " + fileRef.filename); fileRefs.push(line); } results = results.concat(confirmedRefs, otherRefs, fileRefs); return results.join('\n'); } } exports.FindAllRefsView = FindAllRefsView; /***/ }), /***/ 296: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const common_1 = __webpack_require__(5331); const os = __webpack_require__(2087); const which = __webpack_require__(8750); const child_process_1 = __webpack_require__(3129); const semver = __webpack_require__(2751); function getTarget() { return (vscode.workspace.workspaceFolders) ? vscode.ConfigurationTarget.WorkspaceFolder : vscode.ConfigurationTarget.Global; } class Settings { constructor(section, resource) { this.settings = vscode.workspace.getConfiguration(section, resource ? resource : undefined); } get Section() { return this.settings; } getWithFallback(section, deprecatedSection) { const info = this.settings.inspect(section); if (info.workspaceFolderValue !== undefined) { return info.workspaceFolderValue; } else if (info.workspaceValue !== undefined) { return info.workspaceValue; } else if (info.globalValue !== undefined) { return info.globalValue; } const value = this.settings.get(deprecatedSection); if (value !== undefined) { return value; } return info.defaultValue; } getWithNullAsUndefined(section) { const result = this.settings.get(section); if (result === null) { return undefined; } return result; } } class CppSettings extends Settings { constructor(resource) { super("C_Cpp", resource); } get clangFormatName() { switch (os.platform()) { case "win32": return "clang-format.exe"; case "darwin": return "clang-format.darwin"; case "linux": default: return "clang-format"; } } get clangFormatPath() { let path = super.Section.get("clang_format_path"); if (!path) { const cachedClangFormatPath = common_1.getCachedClangFormatPath(); if (cachedClangFormatPath !== undefined) { if (cachedClangFormatPath === null) { return undefined; } return cachedClangFormatPath; } path = which.sync('clang-format', { nothrow: true }); common_1.setCachedClangFormatPath(path); if (!path) { return undefined; } else { let clangFormatVersion; try { const exePath = common_1.getExtensionFilePath(`./LLVM/bin/${this.clangFormatName}`); const output = child_process_1.execSync(`${exePath} --version`).toString().split(" "); if (output.length < 3 || output[0] !== "clang-format" || output[1] !== "version" || !semver.valid(output[2])) { return path; } clangFormatVersion = output[2]; } catch (e) { return path; } try { const output = child_process_1.execSync(`"${path}" --version`).toString().split(" "); if (output.length < 3 || output[0] !== "clang-format" || output[1] !== "version" || semver.ltr(output[2], clangFormatVersion)) { path = ""; } } catch (e) { path = ""; } } } return path; } get clangFormatStyle() { return super.Section.get("clang_format_style"); } get clangFormatFallbackStyle() { return super.Section.get("clang_format_fallbackStyle"); } get clangFormatSortIncludes() { return super.Section.get("clang_format_sortIncludes"); } get experimentalFeatures() { return super.Section.get("experimentalFeatures"); } get suggestSnippets() { return super.Section.get("suggestSnippets"); } get intelliSenseEngine() { return super.Section.get("intelliSenseEngine"); } get intelliSenseEngineFallback() { return super.Section.get("intelliSenseEngineFallback"); } get intelliSenseCachePath() { return super.Section.get("intelliSenseCachePath"); } get intelliSenseCacheSize() { return super.Section.get("intelliSenseCacheSize"); } get intelliSenseMemoryLimit() { return super.Section.get("intelliSenseMemoryLimit"); } get intelliSenseUpdateDelay() { return super.Section.get("intelliSenseUpdateDelay"); } get errorSquiggles() { return super.Section.get("errorSquiggles"); } get inactiveRegionOpacity() { return super.Section.get("inactiveRegionOpacity"); } get inactiveRegionForegroundColor() { return super.Section.get("inactiveRegionForegroundColor"); } get inactiveRegionBackgroundColor() { return super.Section.get("inactiveRegionBackgroundColor"); } get autocomplete() { return super.Section.get("autocomplete"); } get autocompleteAddParentheses() { return super.Section.get("autocompleteAddParentheses"); } get loggingLevel() { return super.Section.get("loggingLevel"); } get autoAddFileAssociations() { return super.Section.get("autoAddFileAssociations"); } get workspaceParsingPriority() { return super.Section.get("workspaceParsingPriority"); } get workspaceSymbols() { return super.Section.get("workspaceSymbols"); } get exclusionPolicy() { return super.Section.get("exclusionPolicy"); } get simplifyStructuredComments() { return super.Section.get("simplifyStructuredComments"); } get commentContinuationPatterns() { return super.Section.get("commentContinuationPatterns"); } get configurationWarnings() { return super.Section.get("configurationWarnings"); } get preferredPathSeparator() { return super.Section.get("preferredPathSeparator"); } get updateChannel() { return super.Section.get("updateChannel"); } get vcpkgEnabled() { return super.Section.get("vcpkg.enabled"); } get addNodeAddonIncludePaths() { return super.Section.get("addNodeAddonIncludePaths"); } get renameRequiresIdentifier() { return super.Section.get("renameRequiresIdentifier"); } get filesExclude() { return super.Section.get("files.exclude"); } get defaultIncludePath() { return super.Section.get("default.includePath"); } get defaultDefines() { return super.Section.get("default.defines"); } get defaultMacFrameworkPath() { return super.Section.get("default.macFrameworkPath"); } get defaultWindowsSdkVersion() { return super.Section.get("default.windowsSdkVersion"); } get defaultCompileCommands() { return super.Section.get("default.compileCommands"); } get defaultForcedInclude() { return super.Section.get("default.forcedInclude"); } get defaultIntelliSenseMode() { return super.Section.get("default.intelliSenseMode"); } get defaultCompilerPath() { const result = super.Section.get("default.compilerPath"); if (result === null) { return undefined; } return result; } get defaultCompilerArgs() { return super.Section.get("default.compilerArgs"); } get defaultCStandard() { return super.Section.get("default.cStandard"); } get defaultCppStandard() { return super.Section.get("default.cppStandard"); } get defaultConfigurationProvider() { return super.Section.get("default.configurationProvider"); } get defaultBrowsePath() { return super.Section.get("default.browse.path"); } get defaultDatabaseFilename() { return super.Section.get("default.browse.databaseFilename"); } get defaultLimitSymbolsToIncludedHeaders() { return super.Section.get("default.browse.limitSymbolsToIncludedHeaders"); } get defaultSystemIncludePath() { return super.Section.get("default.systemIncludePath"); } get defaultEnableConfigurationSquiggles() { return super.Section.get("default.enableConfigurationSquiggles"); } get defaultCustomConfigurationVariables() { return super.Section.get("default.customConfigurationVariables"); } get useBacktickCommandSubstitution() { return super.Section.get("debugger.useBacktickCommandSubstitution"); } get codeFolding() { return super.Section.get("codeFolding") === "Enabled"; } get enhancedColorization() { return super.Section.get("enhancedColorization") === "Enabled" && super.Section.get("intelliSenseEngine") === "Default" && vscode.workspace.getConfiguration("workbench").get("colorTheme") !== "Default High Contrast"; } get formattingEngine() { return super.Section.get("formatting"); } get vcFormatIndentBraces() { return super.Section.get("vcFormat.indent.braces") === true; } get vcFormatIndentMultiLineRelativeTo() { return super.Section.get("vcFormat.indent.multiLineRelativeTo"); } get vcFormatIndentWithinParentheses() { return super.Section.get("vcFormat.indent.withinParentheses"); } get vcFormatIndentPreserveWithinParentheses() { return super.Section.get("vcFormat.indent.preserveWithinParentheses") === true; } get vcFormatIndentCaseLabels() { return super.Section.get("vcFormat.indent.caseLabels") === true; } get vcFormatIndentCaseContents() { return super.Section.get("vcFormat.indent.caseContents") === true; } get vcFormatIndentCaseContentsWhenBlock() { return super.Section.get("vcFormat.indent.caseContentsWhenBlock") === true; } get vcFormatIndentLambdaBracesWhenParameter() { return super.Section.get("vcFormat.indent.lambdaBracesWhenParameter") === true; } get vcFormatIndentGotoLables() { return super.Section.get("vcFormat.indent.gotoLabels"); } get vcFormatIndentPreprocessor() { return super.Section.get("vcFormat.indent.preprocessor"); } get vcFormatIndentAccessSpecifiers() { return super.Section.get("vcFormat.indent.accessSpecifiers") === true; } get vcFormatIndentNamespaceContents() { return super.Section.get("vcFormat.indent.namespaceContents") === true; } get vcFormatIndentPreserveComments() { return super.Section.get("vcFormat.indent.preserveComments") === true; } get vcFormatNewlineBeforeOpenBraceNamespace() { return super.Section.get("vcFormat.newLine.beforeOpenBrace.namespace"); } get vcFormatNewlineBeforeOpenBraceType() { return super.Section.get("vcFormat.newLine.beforeOpenBrace.type"); } get vcFormatNewlineBeforeOpenBraceFunction() { return super.Section.get("vcFormat.newLine.beforeOpenBrace.function"); } get vcFormatNewlineBeforeOpenBraceBlock() { return super.Section.get("vcFormat.newLine.beforeOpenBrace.block"); } get vcFormatNewlineBeforeOpenBraceLambda() { return super.Section.get("vcFormat.newLine.beforeOpenBrace.lambda"); } get vcFormatNewlineScopeBracesOnSeparateLines() { return super.Section.get("vcFormat.newLine.scopeBracesOnSeparateLines") === true; } get vcFormatNewlineCloseBraceSameLineEmptyType() { return super.Section.get("vcFormat.newLine.closeBraceSameLine.emptyType") === true; } get vcFormatNewlineCloseBraceSameLineEmptyFunction() { return super.Section.get("vcFormat.newLine.closeBraceSameLine.emptyFunction") === true; } get vcFormatNewlineBeforeCatch() { return super.Section.get("vcFormat.newLine.beforeCatch") === true; } get vcFormatNewlineBeforeElse() { return super.Section.get("vcFormat.newLine.beforeElse") === true; } get vcFormatNewlineBeforeWhileInDoWhile() { return super.Section.get("vcFormat.newLine.beforeWhileInDoWhile") === true; } get vcFormatSpaceBeforeFunctionOpenParenthesis() { return super.Section.get("vcFormat.space.beforeFunctionOpenParenthesis"); } get vcFormatSpaceWithinParameterListParentheses() { return super.Section.get("vcFormat.space.withinParameterListParentheses") === true; } get vcFormatSpaceBetweenEmptyParameterListParentheses() { return super.Section.get("vcFormat.space.betweenEmptyParameterListParentheses") === true; } get vcFormatSpaceAfterKeywordsInControlFlowStatements() { return super.Section.get("vcFormat.space.afterKeywordsInControlFlowStatements") === true; } get vcFormatSpaceWithinControlFlowStatementParentheses() { return super.Section.get("vcFormat.space.withinControlFlowStatementParentheses") === true; } get vcFormatSpaceBeforeLambdaOpenParenthesis() { return super.Section.get("vcFormat.space.beforeLambdaOpenParenthesis") === true; } get vcFormatSpaceWithinCastParentheses() { return super.Section.get("vcFormat.space.withinCastParentheses") === true; } get vcFormatSpaceAfterCastCloseParenthesis() { return super.Section.get("vcFormat.space.afterCastCloseParenthesis") === true; } get vcFormatSpaceWithinExpressionParentheses() { return super.Section.get("vcFormat.space.withinExpressionParentheses") === true; } get vcFormatSpaceBeforeBlockOpenBrace() { return super.Section.get("vcFormat.space.beforeBlockOpenBrace") === true; } get vcFormatSpaceBetweenEmptyBraces() { return super.Section.get("vcFormat.space.betweenEmptyBraces") === true; } get vcFormatSpaceBeforeInitializerListOpenBrace() { return super.Section.get("vcFormat.space.beforeInitializerListOpenBrace") === true; } get vcFormatSpaceWithinInitializerListBraces() { return super.Section.get("vcFormat.space.withinInitializerListBraces") === true; } get vcFormatSpacePreserveInInitializerList() { return super.Section.get("vcFormat.space.preserveInInitializerList") === true; } get vcFormatSpaceBeforeOpenSquareBracket() { return super.Section.get("vcFormat.space.beforeOpenSquareBracket") === true; } get vcFormatSpaceWithinSquareBrackets() { return super.Section.get("vcFormat.space.withinSquareBrackets") === true; } get vcFormatSpaceBeforeEmptySquareBrackets() { return super.Section.get("vcFormat.space.beforeEmptySquareBrackets") === true; } get vcFormatSpaceBetweenEmptySquareBrackets() { return super.Section.get("vcFormat.space.betweenEmptySquareBrackets") === true; } get vcFormatSpaceGroupSquareBrackets() { return super.Section.get("vcFormat.space.groupSquareBrackets") === true; } get vcFormatSpaceWithinLambdaBrackets() { return super.Section.get("vcFormat.space.withinLambdaBrackets") === true; } get vcFormatSpaceBetweenEmptyLambdaBrackets() { return super.Section.get("vcFormat.space.betweenEmptyLambdaBrackets") === true; } get vcFormatSpaceBeforeComma() { return super.Section.get("vcFormat.space.beforeComma") === true; } get vcFormatSpaceAfterComma() { return super.Section.get("vcFormat.space.afterComma") === true; } get vcFormatSpaceRemoveAroundMemberOperators() { return super.Section.get("vcFormat.space.removeAroundMemberOperators") === true; } get vcFormatSpaceBeforeInheritanceColon() { return super.Section.get("vcFormat.space.beforeInheritanceColon") === true; } get vcFormatSpaceBeforeConstructorColon() { return super.Section.get("vcFormat.space.beforeConstructorColon") === true; } get vcFormatSpaceRemoveBeforeSemicolon() { return super.Section.get("vcFormat.space.removeBeforeSemicolon") === true; } get vcFormatSpaceInsertAfterSemicolon() { return super.Section.get("vcFormat.space.insertAfterSemicolon") === true; } get vcFormatSpaceRemoveAroundUnaryOperator() { return super.Section.get("vcFormat.space.removeAroundUnaryOperator") === true; } get vcFormatSpaceAroundBinaryOperator() { return super.Section.get("vcFormat.space.aroundBinaryOperator"); } get vcFormatSpaceAroundAssignmentOperator() { return super.Section.get("vcFormat.space.aroundAssignmentOperator"); } get vcFormatSpacePointerReferenceAlignment() { return super.Section.get("vcFormat.space.pointerReferenceAlignment"); } get vcFormatSpaceAroundTernaryOperator() { return super.Section.get("vcFormat.space.aroundTernaryOperator"); } get vcFormatWrapPreserveBlocks() { return super.Section.get("vcFormat.wrap.preserveBlocks"); } get dimInactiveRegions() { return super.Section.get("dimInactiveRegions") === true && super.Section.get("intelliSenseEngine") === "Default" && vscode.workspace.getConfiguration("workbench").get("colorTheme") !== "Default High Contrast"; } toggleSetting(name, value1, value2) { const value = super.Section.get(name); super.Section.update(name, value === value1 ? value2 : value1, getTarget()); } update(name, value) { super.Section.update(name, value); } } exports.CppSettings = CppSettings; class OtherSettings { constructor(resource) { if (!resource) { resource = undefined; } this.resource = resource; } get editorTabSize() { return vscode.workspace.getConfiguration("editor", this.resource).get("tabSize"); } get editorAutoClosingBrackets() { return vscode.workspace.getConfiguration("editor", this.resource).get("autoClosingBrackets"); } get filesEncoding() { return vscode.workspace.getConfiguration("files", { uri: this.resource, languageId: "cpp" }).get("encoding"); } get filesAssociations() { return vscode.workspace.getConfiguration("files").get("associations"); } set filesAssociations(value) { vscode.workspace.getConfiguration("files").update("associations", value, vscode.ConfigurationTarget.Workspace); } get filesExclude() { return vscode.workspace.getConfiguration("files", this.resource).get("exclude"); } get searchExclude() { return vscode.workspace.getConfiguration("search", this.resource).get("exclude"); } get settingsEditor() { return vscode.workspace.getConfiguration("workbench.settings").get("editor"); } get colorTheme() { return vscode.workspace.getConfiguration("workbench").get("colorTheme"); } getCustomColorToken(colorTokenName) { return vscode.workspace.getConfiguration("editor.tokenColorCustomizations").get(colorTokenName); } getCustomThemeSpecificColorToken(themeName, colorTokenName) { return vscode.workspace.getConfiguration(`editor.tokenColorCustomizations.[${themeName}]`, this.resource).get(colorTokenName); } get customTextMateRules() { return vscode.workspace.getConfiguration("editor.tokenColorCustomizations").get("textMateRules"); } getCustomThemeSpecificTextMateRules(themeName) { return vscode.workspace.getConfiguration(`editor.tokenColorCustomizations.[${themeName}]`, this.resource).get("textMateRules"); } } exports.OtherSettings = OtherSettings; function mapIndentationReferenceToEditorConfig(value) { if (value !== undefined) { if (value === "statementBegin") { return "statement_begin"; } if (value === "outermostParenthesis") { return "outermost_parenthesis"; } } return "innermost_parenthesis"; } function mapIndentToEditorConfig(value) { if (value !== undefined) { if (value === "leftmostColumn") { return "leftmost_column"; } if (value === "oneLeft") { return "one_left"; } } return "none"; } function mapNewOrSameLineToEditorConfig(value) { if (value !== undefined) { if (value === "newLine") { return "new_line"; } if (value === "sameLine") { return "same_line"; } } return "ignore"; } function mapWrapToEditorConfig(value) { if (value !== undefined) { if (value === "allOneLineScopes") { return "all_one_line_scopes"; } if (value === "oneLiners") { return "one_liners"; } } return "never"; } function populateEditorConfig(rootUri, document) { const settings = new CppSettings(rootUri); const settingMap = new Map(); settingMap.set("cpp_indent_braces", settings.vcFormatIndentBraces.toString()); settingMap.set("cpp_indent_multi_line_relative_to", mapIndentationReferenceToEditorConfig(settings.vcFormatIndentMultiLineRelativeTo)); settingMap.set("cpp_indent_within_parentheses", settings.vcFormatIndentWithinParentheses.toString()); settingMap.set("cpp_indent_preserve_within_parentheses", settings.vcFormatIndentPreserveWithinParentheses.toString()); settingMap.set("cpp_indent_case_labels", settings.vcFormatIndentCaseLabels.toString()); settingMap.set("cpp_indent_case_contents", settings.vcFormatIndentCaseContents.toString()); settingMap.set("cpp_indent_case_contents_when_block", settings.vcFormatIndentCaseContentsWhenBlock.toString()); settingMap.set("cpp_indent_lambda_braces_when_parameter", settings.vcFormatIndentLambdaBracesWhenParameter.toString()); settingMap.set("cpp_indent_goto_labels", mapIndentToEditorConfig(settings.vcFormatIndentGotoLables)); settingMap.set("cpp_indent_preprocessor", mapIndentToEditorConfig(settings.vcFormatIndentPreprocessor)); settingMap.set("cpp_indent_access_specifiers", settings.vcFormatIndentAccessSpecifiers.toString()); settingMap.set("cpp_indent_namespace_contents", settings.vcFormatIndentNamespaceContents.toString()); settingMap.set("cpp_indent_preserve_comments", settings.vcFormatIndentPreserveComments.toString()); settingMap.set("cpp_new_line_before_open_brace_namespace", mapNewOrSameLineToEditorConfig(settings.vcFormatNewlineBeforeOpenBraceNamespace)); settingMap.set("cpp_new_line_before_open_brace_type", mapNewOrSameLineToEditorConfig(settings.vcFormatNewlineBeforeOpenBraceType)); settingMap.set("cpp_new_line_before_open_brace_function", mapNewOrSameLineToEditorConfig(settings.vcFormatNewlineBeforeOpenBraceFunction)); settingMap.set("cpp_new_line_before_open_brace_block", mapNewOrSameLineToEditorConfig(settings.vcFormatNewlineBeforeOpenBraceBlock)); settingMap.set("cpp_new_line_before_open_brace_lambda", mapNewOrSameLineToEditorConfig(settings.vcFormatNewlineBeforeOpenBraceLambda)); settingMap.set("cpp_new_line_scope_braces_on_separate_lines", settings.vcFormatNewlineScopeBracesOnSeparateLines.toString()); settingMap.set("cpp_new_line_close_brace_same_line_empty_type", settings.vcFormatNewlineCloseBraceSameLineEmptyType.toString()); settingMap.set("cpp_new_line_close_brace_same_line_empty_function", settings.vcFormatNewlineCloseBraceSameLineEmptyFunction.toString()); settingMap.set("cpp_new_line_before_catch", settings.vcFormatNewlineBeforeCatch.toString().toString()); settingMap.set("cpp_new_line_before_else", settings.vcFormatNewlineBeforeElse.toString().toString()); settingMap.set("cpp_new_line_before_while_in_do_while", settings.vcFormatNewlineBeforeWhileInDoWhile.toString()); settingMap.set("cpp_space_before_function_open_parenthesis", settings.vcFormatSpaceBeforeFunctionOpenParenthesis.toString()); settingMap.set("cpp_space_within_parameter_list_parentheses", settings.vcFormatSpaceWithinParameterListParentheses.toString()); settingMap.set("cpp_space_between_empty_parameter_list_parentheses", settings.vcFormatSpaceBetweenEmptyParameterListParentheses.toString()); settingMap.set("cpp_space_after_keywords_in_control_flow_statements", settings.vcFormatSpaceAfterKeywordsInControlFlowStatements.toString()); settingMap.set("cpp_space_within_control_flow_statement_parentheses", settings.vcFormatSpaceWithinControlFlowStatementParentheses.toString()); settingMap.set("cpp_space_before_lambda_open_parenthesis", settings.vcFormatSpaceBeforeLambdaOpenParenthesis.toString()); settingMap.set("cpp_space_within_cast_parentheses", settings.vcFormatSpaceWithinCastParentheses.toString()); settingMap.set("cpp_space_after_cast_close_parenthesis", settings.vcFormatSpaceAfterCastCloseParenthesis.toString()); settingMap.set("cpp_space_within_expression_parentheses", settings.vcFormatSpaceWithinExpressionParentheses.toString()); settingMap.set("cpp_space_before_block_open_brace", settings.vcFormatSpaceBeforeBlockOpenBrace.toString()); settingMap.set("cpp_space_between_empty_braces", settings.vcFormatSpaceBetweenEmptyBraces.toString()); settingMap.set("cpp_space_before_initializer_list_open_brace", settings.vcFormatSpaceBeforeInitializerListOpenBrace.toString()); settingMap.set("cpp_space_within_initializer_list_braces", settings.vcFormatSpaceWithinInitializerListBraces.toString()); settingMap.set("cpp_space_preserve_in_initializer_list", settings.vcFormatSpacePreserveInInitializerList.toString()); settingMap.set("cpp_space_before_open_square_bracket", settings.vcFormatSpaceBeforeOpenSquareBracket.toString()); settingMap.set("cpp_space_within_square_brackets", settings.vcFormatSpaceWithinSquareBrackets.toString()); settingMap.set("cpp_space_before_empty_square_brackets", settings.vcFormatSpaceBeforeEmptySquareBrackets.toString()); settingMap.set("cpp_space_between_empty_square_brackets", settings.vcFormatSpaceBetweenEmptySquareBrackets.toString()); settingMap.set("cpp_space_group_square_brackets", settings.vcFormatSpaceGroupSquareBrackets.toString()); settingMap.set("cpp_space_within_lambda_brackets", settings.vcFormatSpaceWithinLambdaBrackets.toString()); settingMap.set("cpp_space_between_empty_lambda_brackets", settings.vcFormatSpaceBetweenEmptyLambdaBrackets.toString()); settingMap.set("cpp_space_before_comma", settings.vcFormatSpaceBeforeComma.toString()); settingMap.set("cpp_space_after_comma", settings.vcFormatSpaceAfterComma.toString()); settingMap.set("cpp_space_remove_around_member_operators", settings.vcFormatSpaceRemoveAroundMemberOperators.toString()); settingMap.set("cpp_space_before_inheritance_colon", settings.vcFormatSpaceBeforeInheritanceColon.toString()); settingMap.set("cpp_space_before_constructor_colon", settings.vcFormatSpaceBeforeConstructorColon.toString()); settingMap.set("cpp_space_remove_before_semicolon", settings.vcFormatSpaceRemoveBeforeSemicolon.toString()); settingMap.set("cpp_space_after_semicolon", settings.vcFormatSpaceInsertAfterSemicolon.toString()); settingMap.set("cpp_space_remove_around_unary_operator", settings.vcFormatSpaceRemoveAroundUnaryOperator.toString()); settingMap.set("cpp_space_around_binary_operator", settings.vcFormatSpaceAroundBinaryOperator.toString()); settingMap.set("cpp_space_around_assignment_operator", settings.vcFormatSpaceAroundAssignmentOperator.toString()); settingMap.set("cpp_space_pointer_reference_alignment", settings.vcFormatSpacePointerReferenceAlignment.toString()); settingMap.set("cpp_space_around_ternary_operator", settings.vcFormatSpaceAroundTernaryOperator.toString()); settingMap.set("cpp_wrap_preserve_blocks", mapWrapToEditorConfig(settings.vcFormatWrapPreserveBlocks)); const edits = new vscode.WorkspaceEdit(); let isInWildcardSection = false; let trailingBlankLines = 0; for (let i = 0; i < document.lineCount; ++i) { let textLine = document.lineAt(i); if (textLine.range.end.character === 0) { trailingBlankLines++; continue; } trailingBlankLines = 0; let text = textLine.text.trim(); if (text.startsWith("[")) { isInWildcardSection = text.startsWith("[*]"); continue; } for (const setting of settingMap) { if (text.startsWith(setting[0])) { if (text.length > setting[0].length) { const c = text[setting[0].length]; if (c !== '=' && c.trim() !== "") { continue; } } edits.replace(document.uri, textLine.range, setting[0] + "=" + setting[1]); for (let j = i + 1; j < document.lineCount; ++j) { textLine = document.lineAt(j); text = textLine.text.trim(); if (text.startsWith(setting[0])) { if (text.length > setting[0].length) { const c = text[setting[0].length]; if (c !== '=' && c.trim() !== "") { continue; } } edits.replace(document.uri, textLine.range, setting[0] + "=" + setting[1]); } } settingMap.delete(setting[0]); break; } } if (settingMap.size === 0) { break; } } if (settingMap.size > 0) { let remainingSettingsText = ""; if (document.lineCount > 0) { while (++trailingBlankLines < 2) { remainingSettingsText += "\n"; } } if (!isInWildcardSection) { remainingSettingsText += "[*]\n"; } for (const setting of settingMap) { remainingSettingsText += setting[0] + "=" + setting[1] + "\n"; } const lastPosition = document.lineAt(document.lineCount - 1).range.end; edits.insert(document.uri, lastPosition, remainingSettingsText); } vscode.workspace.applyEdit(edits).then(() => vscode.window.showTextDocument(document)); } function generateEditorConfig(rootUri) { return __awaiter(this, void 0, void 0, function* () { let document; if (rootUri) { const uri = vscode.Uri.joinPath(rootUri, ".editorconfig"); const edits = new vscode.WorkspaceEdit(); edits.createFile(uri, { ignoreIfExists: true, overwrite: false }); try { yield vscode.workspace.applyEdit(edits); document = yield vscode.workspace.openTextDocument(uri); } catch (e) { document = yield vscode.workspace.openTextDocument(); } } else { document = yield vscode.workspace.openTextDocument(); } populateEditorConfig(rootUri, document); }); } exports.generateEditorConfig = generateEditorConfig; /***/ }), /***/ 7597: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __webpack_require__(5622); const fs = __webpack_require__(5747); const vscode = __webpack_require__(7549); const util = __webpack_require__(5331); const telemetry = __webpack_require__(1818); const elementId = { configName: "configName", configNameInvalid: "configNameInvalid", configSelection: "configSelection", addConfigBtn: "addConfigBtn", addConfigOk: "addConfigOk", addConfigCancel: "addConfigCancel", addConfigName: "addConfigName", compilerPath: "compilerPath", compilerPathInvalid: "compilerPathInvalid", knownCompilers: "knownCompilers", compilerArgs: "compilerArgs", intelliSenseMode: "intelliSenseMode", intelliSenseModeInvalid: "intelliSenseModeInvalid", includePath: "includePath", includePathInvalid: "includePathInvalid", defines: "defines", cStandard: "cStandard", cppStandard: "cppStandard", windowsSdkVersion: "windowsSdkVersion", macFrameworkPath: "macFrameworkPath", compileCommands: "compileCommands", configurationProvider: "configurationProvider", forcedInclude: "forcedInclude", browsePath: "browsePath", limitSymbolsToIncludedHeaders: "limitSymbolsToIncludedHeaders", databaseFilename: "databaseFilename", showAdvancedBtn: "showAdvancedBtn" }; class SettingsPanel { constructor() { this.telemetry = {}; this.settingsPanelActivated = new vscode.EventEmitter(); this.configValuesChanged = new vscode.EventEmitter(); this.configSelectionChanged = new vscode.EventEmitter(); this.addConfigRequested = new vscode.EventEmitter(); this.configValues = { name: "" }; this.isIntelliSenseModeDefined = false; this.configIndexSelected = 0; this.compilerPaths = []; this.initialized = false; this.disposable = vscode.Disposable.from(this.settingsPanelActivated, this.configValuesChanged, this.configSelectionChanged, this.addConfigRequested); } createOrShow(configSelection, activeConfiguration, errors, viewColumn) { var _a; const column = (viewColumn !== null && viewColumn !== void 0 ? viewColumn : (_a = vscode.window.activeTextEditor) === null || _a === void 0 ? void 0 : _a.viewColumn); if (this.panel) { this.panel.reveal(column, false); return; } this.initialized = false; this.panel = vscode.window.createWebviewPanel(SettingsPanel.viewType, SettingsPanel.title, column || vscode.ViewColumn.One, { enableCommandUris: true, enableScripts: true, localResourceRoots: [ vscode.Uri.file(util.extensionPath), vscode.Uri.file(path.join(util.extensionPath, 'ui')), vscode.Uri.file(path.join(util.extensionPath, 'out', 'ui')) ] }); this.panel.iconPath = vscode.Uri.file(util.getExtensionFilePath("LanguageCCPP_color_128x.png")); this.disposablesPanel = vscode.Disposable.from(this.panel, this.panel.onDidDispose(this.onPanelDisposed, this), this.panel.onDidChangeViewState(this.onViewStateChanged, this), this.panel.webview.onDidReceiveMessage(this.onMessageReceived, this), vscode.window.onDidChangeWindowState(this.onWindowStateChanged, this)); this.panel.webview.html = this.getHtml(); this.updateWebview(configSelection, activeConfiguration, errors); } get SettingsPanelActivated() { return this.settingsPanelActivated.event; } get ConfigValuesChanged() { return this.configValuesChanged.event; } get ConfigSelectionChanged() { return this.configSelectionChanged.event; } get AddConfigRequested() { return this.addConfigRequested.event; } get selectedConfigIndex() { return this.configIndexSelected; } set selectedConfigIndex(index) { this.configIndexSelected = index; } getLastValuesFromConfigUI() { return this.configValues; } updateConfigUI(configSelection, configuration, errors) { if (this.panel) { this.updateWebview(configSelection, configuration, errors); } } setKnownCompilers(knownCompilers, pathSeparator) { if (knownCompilers && knownCompilers.length) { for (const compiler of knownCompilers) { let path = compiler.path; if (pathSeparator === "Forward Slash") { path = path.replace(/\\/g, '/'); } else { path = path.replace(/\//g, '\\'); } if (this.compilerPaths.indexOf(path) === -1) { this.compilerPaths.push(path); } } } } updateErrors(errors) { if (this.panel) { this.panel.webview.postMessage({ command: 'updateErrors', errors: errors }); } } dispose() { if (Object.keys(this.telemetry).length) { telemetry.logLanguageServerEvent("ConfigUI", undefined, this.telemetry); } if (this.panel) { this.panel.dispose(); } if (this.disposable) { this.disposable.dispose(); } if (this.disposablesPanel) { this.disposablesPanel.dispose(); } } onPanelDisposed() { if (this.disposablesPanel) { this.disposablesPanel.dispose(); this.panel = undefined; } } updateWebview(configSelection, configuration, errors) { this.configValues = Object.assign({}, configuration); this.isIntelliSenseModeDefined = (this.configValues.intelliSenseMode !== undefined); if (this.panel && this.initialized) { this.panel.webview.postMessage({ command: 'setKnownCompilers', compilers: this.compilerPaths }); this.panel.webview.postMessage({ command: 'updateConfigSelection', selections: configSelection, selectedIndex: this.configIndexSelected }); this.panel.webview.postMessage({ command: 'updateConfig', config: this.configValues }); if (errors !== null) { this.panel.webview.postMessage({ command: 'updateErrors', errors: errors }); } } } onViewStateChanged(e) { if (e.webviewPanel.active) { this.settingsPanelActivated.fire(); } } onWindowStateChanged(e) { if (e.focused) { this.settingsPanelActivated.fire(); } } onMessageReceived(message) { if (message === null || message === undefined) { return; } switch (message.command) { case 'change': this.updateConfig(message); break; case 'configSelect': this.configSelect(message.index); break; case 'addConfig': this.addConfig(message.name); break; case 'knownCompilerSelect': this.knownCompilerSelect(); break; case "initialized": this.initialized = true; this.settingsPanelActivated.fire(); break; } } addConfig(name) { this.addConfigRequested.fire(name); this.logTelemetryForElement(elementId.addConfigName); } configSelect(index) { this.configIndexSelected = index; this.configSelectionChanged.fire(); this.logTelemetryForElement(elementId.configSelection); } knownCompilerSelect() { this.logTelemetryForElement(elementId.knownCompilers); if (this.telemetry[elementId.compilerPath]) { this.telemetry[elementId.compilerPath]--; } } updateConfig(message) { const splitEntries = (input) => input.split("\n").filter((e) => e); switch (message.key) { case elementId.configName: this.configValues.name = message.value; break; case elementId.compilerPath: this.configValues.compilerPath = message.value; break; case elementId.compilerArgs: this.configValues.compilerArgs = splitEntries(message.value); break; case elementId.includePath: this.configValues.includePath = splitEntries(message.value); break; case elementId.defines: this.configValues.defines = splitEntries(message.value); break; case elementId.intelliSenseMode: if (message.value !== "${default}" || this.isIntelliSenseModeDefined) { this.configValues.intelliSenseMode = message.value; } else { this.configValues.intelliSenseMode = undefined; } break; case elementId.cStandard: this.configValues.cStandard = message.value; break; case elementId.cppStandard: this.configValues.cppStandard = message.value; break; case elementId.windowsSdkVersion: this.configValues.windowsSdkVersion = message.value; break; case elementId.macFrameworkPath: this.configValues.macFrameworkPath = splitEntries(message.value); break; case elementId.compileCommands: this.configValues.compileCommands = message.value; break; case elementId.configurationProvider: this.configValues.configurationProvider = message.value; break; case elementId.forcedInclude: this.configValues.forcedInclude = splitEntries(message.value); break; case elementId.browsePath: if (!this.configValues.browse) { this.configValues.browse = {}; } this.configValues.browse.path = splitEntries(message.value); break; case elementId.limitSymbolsToIncludedHeaders: if (!this.configValues.browse) { this.configValues.browse = {}; } this.configValues.browse.limitSymbolsToIncludedHeaders = message.value; break; case elementId.databaseFilename: if (!this.configValues.browse) { this.configValues.browse = {}; } this.configValues.browse.databaseFilename = message.value; break; } this.configValuesChanged.fire(); this.logTelemetryForElement(message.key); } logTelemetryForElement(elementId) { if (this.telemetry[elementId] === undefined) { this.telemetry[elementId] = 0; } this.telemetry[elementId]++; } getHtml() { let content; content = fs.readFileSync(util.getLocalizedHtmlPath("ui/settings.html")).toString(); if (this.panel && this.panel.webview) { const cppImageUri = this.panel.webview.asWebviewUri(vscode.Uri.file(path.join(util.extensionPath, 'LanguageCCPP_color_128x.png'))); content = content.replace(/{{cpp_image_uri}}/g, cppImageUri.toString()); const settingsJsUri = this.panel.webview.asWebviewUri(vscode.Uri.file(path.join(util.extensionPath, 'out/ui/settings.js'))); content = content.replace(/{{settings_js_uri}}/g, settingsJsUri.toString()); } content = content.replace(/{{nonce}}/g, this.getNonce()); return content; } getNonce() { let nonce = ""; const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < 32; i++) { nonce += possible.charAt(Math.floor(Math.random() * possible.length)); } return nonce; } } exports.SettingsPanel = SettingsPanel; SettingsPanel.viewType = 'settingsPanel'; SettingsPanel.title = 'C/C++ Configurations'; /***/ }), /***/ 5313: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const util = __webpack_require__(5331); const maxSettingLengthForTelemetry = 50; let cache; class SettingsTracker { constructor(resource) { this.previousCppSettings = {}; this.resource = resource; this.collectSettings(() => true); } getUserModifiedSettings() { const filter = (key, val, settings) => { var _a; return !this.areEqual(val, (_a = settings.inspect(key)) === null || _a === void 0 ? void 0 : _a.defaultValue); }; return this.collectSettings(filter); } getChangedSettings() { const filter = (key, val) => !(key in this.previousCppSettings) || !this.areEqual(val, this.previousCppSettings[key]); return this.collectSettings(filter); } collectSettings(filter) { const settingsResourceScope = vscode.workspace.getConfiguration("C_Cpp", this.resource); const settingsNonScoped = vscode.workspace.getConfiguration("C_Cpp"); const selectCorrectlyScopedSettings = (rawSetting) => (!rawSetting || rawSetting.scope === "resource" || rawSetting.scope === "machine-overridable") ? settingsResourceScope : settingsNonScoped; const result = {}; for (const key in settingsResourceScope) { const rawSetting = util.packageJson.contributes.configuration.properties["C_Cpp." + key]; const correctlyScopedSettings = selectCorrectlyScopedSettings(rawSetting); const val = this.getSetting(correctlyScopedSettings, key); if (val === undefined) { continue; } const collectSettingsRecursive = (key, val, depth) => { if (depth > 4) { return; } for (const subKey in val) { const newKey = key + "." + subKey; const newRawSetting = util.packageJson.contributes.configuration.properties["C_Cpp." + newKey]; const correctlyScopedSubSettings = selectCorrectlyScopedSettings(newRawSetting); const subVal = this.getSetting(correctlyScopedSubSettings, newKey); if (subVal === undefined) { continue; } if (subVal instanceof Object && !(subVal instanceof Array)) { collectSettingsRecursive(newKey, subVal, depth + 1); } else { const entry = this.filterAndSanitize(newKey, subVal, correctlyScopedSubSettings, filter); if (entry && entry.key && entry.value) { result[entry.key] = entry.value; } } } }; if (val instanceof Object && !(val instanceof Array)) { collectSettingsRecursive(key, val, 1); continue; } const entry = this.filterAndSanitize(key, val, correctlyScopedSettings, filter); if (entry && entry.key && entry.value) { result[entry.key] = entry.value; } } return result; } getSetting(settings, key) { var _a; if (((_a = settings.inspect(key)) === null || _a === void 0 ? void 0 : _a.defaultValue) !== undefined) { const val = settings.get(key); if (val instanceof Object) { return val; } const curSetting = util.packageJson.contributes.configuration.properties["C_Cpp." + key]; if (curSetting) { const type = this.typeMatch(val, curSetting["type"]); if (type) { if (type !== "string") { return val; } const curEnum = curSetting["enum"]; if (curEnum && curEnum.indexOf(val) === -1) { return ""; } return val; } } } return undefined; } typeMatch(value, type) { if (type) { if (type instanceof Array) { for (let i = 0; i < type.length; i++) { const t = type[i]; if (t) { if (typeof value === t) { return t; } if (t === "array" && value instanceof Array) { return t; } if (t === "null" && value === null) { return t; } } } } else if (typeof type === "string" && typeof value === type) { return type; } } return undefined; } filterAndSanitize(key, val, settings, filter) { var _a, _b; if (filter(key, val, settings)) { let value; this.previousCppSettings[key] = val; switch (key) { case "clang_format_style": case "clang_format_fallbackStyle": { const newKey = key + "2"; if (val) { switch (String(val).toLowerCase()) { case "emulated visual studio": case "visual studio": case "llvm": case "google": case "chromium": case "mozilla": case "webkit": case "file": case "none": { value = String(this.previousCppSettings[key]); break; } default: { value = "..."; break; } } } else { value = "null"; } key = newKey; break; } case "commentContinuationPatterns": { key = "commentContinuationPatterns2"; value = this.areEqual(val, (_a = settings.inspect(key)) === null || _a === void 0 ? void 0 : _a.defaultValue) ? "" : "..."; break; } default: { if (key === "clang_format_path" || key === "intelliSenseCachePath" || key.startsWith("default.")) { value = this.areEqual(val, (_b = settings.inspect(key)) === null || _b === void 0 ? void 0 : _b.defaultValue) ? "" : "..."; } else { value = String(this.previousCppSettings[key]); } } } if (value && value.length > maxSettingLengthForTelemetry) { value = value.substr(0, maxSettingLengthForTelemetry) + "..."; } return { key: key, value: value }; } return undefined; } areEqual(value1, value2) { if (value1 instanceof Object && value2 instanceof Object) { return JSON.stringify(value1) === JSON.stringify(value2); } return value1 === value2; } } exports.SettingsTracker = SettingsTracker; function getTracker(resource) { if (!cache) { cache = new SettingsTracker(resource); } return cache; } exports.getTracker = getTracker; /***/ }), /***/ 9071: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const telemetry = __webpack_require__(1818); const util = __webpack_require__(5331); class TimeTelemetryCollector { constructor() { this.cachedTimeStamps = new Map(); } setFirstFile(uri) { if (util.fileIsCOrCppSource(uri.path)) { const curTimeStamps = this.getTimeStamp(uri.path); curTimeStamps.firstFile = new Date().getTime(); this.cachedTimeStamps.set(uri.path, curTimeStamps); } } setDidOpenTime(uri) { const curTimeStamps = this.getTimeStamp(uri.path); curTimeStamps.didOpen = new Date().getTime(); this.cachedTimeStamps.set(uri.path, curTimeStamps); } setSetupTime(uri) { const curTimeStamps = this.getTimeStamp(uri.path); curTimeStamps.setup = new Date().getTime(); this.cachedTimeStamps.set(uri.path, curTimeStamps); if (curTimeStamps.didOpen && curTimeStamps.updateRange) { this.logTelemetry(uri.path, curTimeStamps); } } setUpdateRangeTime(uri) { const curTimeStamps = this.getTimeStamp(uri.path); if (!curTimeStamps.updateRange) { curTimeStamps.updateRange = new Date().getTime(); this.cachedTimeStamps.set(uri.path, curTimeStamps); } if (curTimeStamps.didOpen && curTimeStamps.setup) { this.logTelemetry(uri.path, curTimeStamps); } } clear() { console.log("clearing timestamp log"); this.cachedTimeStamps.clear(); } getTimeStamp(uri) { return this.cachedTimeStamps.get(uri) ? this.cachedTimeStamps.get(uri) : { firstFile: 0, didOpen: 0, setup: 0, updateRange: 0 }; } removeTimeStamp(uri) { this.cachedTimeStamps.delete(uri); } logTelemetry(uri, timeStamps) { const startTime = timeStamps.firstFile ? timeStamps.firstFile : timeStamps.didOpen; let properties = {}; let metrics = { "setupTime": (timeStamps.setup - timeStamps.didOpen), "updateRangeTime": (timeStamps.updateRange - timeStamps.setup), "totalTime": (timeStamps.updateRange - startTime) }; if (timeStamps.firstFile) { properties = { "coldstart": "true" }; metrics = Object.assign({ "activationTime": (timeStamps.didOpen - startTime) }, metrics); } telemetry.logLanguageServerEvent("timeStamps", properties, metrics); this.removeTimeStamp(uri); } } exports.TimeTelemetryCollector = TimeTelemetryCollector; /***/ }), /***/ 6713: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const references_1 = __webpack_require__(2664); const customProviders_1 = __webpack_require__(4977); const nls = __webpack_require__(3612); const timers_1 = __webpack_require__(8213); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\ui.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\LanguageServer\\ui.ts')); let ui; var ConfigurationPriority; (function (ConfigurationPriority) { ConfigurationPriority[ConfigurationPriority["IncludePath"] = 1] = "IncludePath"; ConfigurationPriority[ConfigurationPriority["CompileCommands"] = 2] = "CompileCommands"; ConfigurationPriority[ConfigurationPriority["CustomProvider"] = 3] = "CustomProvider"; })(ConfigurationPriority || (ConfigurationPriority = {})); class UI { constructor() { this.referencesPreviewTooltip = ` (${localize(0, null)})`; this.iconDelayTime = 1000; this.configStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 0); this.configStatusBarItem.command = "C_Cpp.ConfigurationSelect"; this.configStatusBarItem.tooltip = localize(1, null); this.ShowConfiguration = true; this.referencesStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 901); this.referencesStatusBarItem.text = ""; this.referencesStatusBarItem.tooltip = ""; this.referencesStatusBarItem.color = new vscode.ThemeColor("statusBar.foreground"); this.referencesStatusBarItem.command = "C_Cpp.ShowReferencesProgress"; this.ShowReferencesIcon = true; this.intelliSenseStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 903); this.intelliSenseStatusBarItem.text = ""; this.intelliSenseStatusBarItem.tooltip = localize(2, null); this.intelliSenseStatusBarItem.color = new vscode.ThemeColor("statusBar.foreground"); this.ShowFlameIcon = true; this.browseEngineStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 902); this.browseEngineStatusBarItem.text = ""; this.browseEngineStatusBarItem.tooltip = localize(3, null); this.browseEngineStatusBarItem.color = new vscode.ThemeColor("statusBar.foreground"); this.browseEngineStatusBarItem.command = "C_Cpp.ShowParsingCommands"; this.ShowDBIcon = true; } set ActiveConfig(label) { this.configStatusBarItem.text = label; } set TagParseStatus(label) { this.browseEngineStatusBarItem.tooltip = label; } get IsTagParsing() { return this.browseEngineStatusBarItem.text !== ""; } set IsTagParsing(val) { this.browseEngineStatusBarItem.text = val ? "$(database)" : ""; this.ShowDBIcon = val; } get IsUpdatingIntelliSense() { return this.intelliSenseStatusBarItem.text !== ""; } set IsUpdatingIntelliSense(val) { this.intelliSenseStatusBarItem.text = val ? "$(flame)" : ""; this.ShowFlameIcon = val; } get ReferencesCommand() { return this.referencesStatusBarItem.tooltip === "" ? references_1.ReferencesCommandMode.None : (this.referencesStatusBarItem.tooltip === references_1.referencesCommandModeToString(references_1.ReferencesCommandMode.Find) ? references_1.ReferencesCommandMode.Find : (this.referencesStatusBarItem.tooltip === references_1.referencesCommandModeToString(references_1.ReferencesCommandMode.Rename) ? references_1.ReferencesCommandMode.Rename : references_1.ReferencesCommandMode.Peek)); } set ReferencesCommand(val) { if (val === references_1.ReferencesCommandMode.None) { this.referencesStatusBarItem.text = ""; this.ShowReferencesIcon = false; } else { this.referencesStatusBarItem.text = "$(search)"; this.referencesStatusBarItem.tooltip = references_1.referencesCommandModeToString(val) + (val !== references_1.ReferencesCommandMode.Find ? "" : this.referencesPreviewTooltip); this.ShowReferencesIcon = true; } } set ShowDBIcon(show) { if (this.dbTimeout) { clearTimeout(this.dbTimeout); } if (show && this.IsTagParsing) { this.dbTimeout = timers_1.setTimeout(() => { this.browseEngineStatusBarItem.show(); }, this.iconDelayTime); } else { this.dbTimeout = timers_1.setTimeout(() => { this.browseEngineStatusBarItem.hide(); }, this.iconDelayTime); } } set ShowFlameIcon(show) { if (this.flameTimeout) { clearTimeout(this.flameTimeout); } if (show && this.IsUpdatingIntelliSense) { this.flameTimeout = timers_1.setTimeout(() => { this.intelliSenseStatusBarItem.show(); }, this.iconDelayTime); } else { this.flameTimeout = timers_1.setTimeout(() => { this.intelliSenseStatusBarItem.hide(); }, this.iconDelayTime); } } set ShowReferencesIcon(show) { if (show && this.ReferencesCommand !== references_1.ReferencesCommandMode.None) { this.referencesStatusBarItem.show(); } else { this.referencesStatusBarItem.hide(); } } set ShowConfiguration(show) { if (show) { this.configStatusBarItem.show(); } else { this.configStatusBarItem.hide(); } } activeDocumentChanged() { const activeEditor = vscode.window.activeTextEditor; if (!activeEditor) { this.ShowConfiguration = false; } else { const isCpp = (activeEditor.document.uri.scheme === "file" && (activeEditor.document.languageId === "c" || activeEditor.document.languageId === "cpp" || activeEditor.document.languageId === "cuda-cpp")); let isCppPropertiesJson = false; if (activeEditor.document.languageId === "json" || activeEditor.document.languageId === "jsonc") { isCppPropertiesJson = activeEditor.document.fileName.endsWith("c_cpp_properties.json"); if (isCppPropertiesJson) { vscode.languages.setTextDocumentLanguage(activeEditor.document, "jsonc"); } } this.ShowConfiguration = isCpp || isCppPropertiesJson || activeEditor.document.uri.scheme === "output" || activeEditor.document.fileName.endsWith("settings.json") || activeEditor.document.fileName.endsWith("tasks.json") || activeEditor.document.fileName.endsWith("launch.json") || activeEditor.document.fileName.endsWith(".code-workspace"); } } bind(client) { client.TagParsingChanged(value => { this.IsTagParsing = value; }); client.IntelliSenseParsingChanged(value => { this.IsUpdatingIntelliSense = value; }); client.ReferencesCommandModeChanged(value => { this.ReferencesCommand = value; }); client.TagParserStatusChanged(value => { this.TagParseStatus = value; }); client.ActiveConfigChanged(value => { this.ActiveConfig = value; }); } showConfigurations(configurationNames) { return __awaiter(this, void 0, void 0, function* () { const options = {}; options.placeHolder = localize(4, null); const items = []; for (let i = 0; i < configurationNames.length; i++) { items.push({ label: configurationNames[i], description: "", index: i }); } items.push({ label: localize(5, null), description: "", index: configurationNames.length }); items.push({ label: localize(6, null), description: "", index: configurationNames.length + 1 }); const selection = yield vscode.window.showQuickPick(items, options); return (selection) ? selection.index : -1; }); } showConfigurationProviders(currentProvider) { return __awaiter(this, void 0, void 0, function* () { const options = {}; options.placeHolder = localize(7, null); const providers = customProviders_1.getCustomConfigProviders(); const items = []; providers.forEach(provider => { let label = provider.name; if (customProviders_1.isSameProviderExtensionId(currentProvider, provider.extensionId)) { label += ` (${localize(8, null)})`; } items.push({ label: label, description: "", key: provider.extensionId }); }); items.push({ label: `(${localize(9, null)})`, description: localize(10, null), key: "" }); const selection = yield vscode.window.showQuickPick(items, options); return (selection) ? selection.key : undefined; }); } showCompileCommands(paths) { return __awaiter(this, void 0, void 0, function* () { const options = {}; options.placeHolder = localize(11, null); const items = []; for (let i = 0; i < paths.length; i++) { items.push({ label: paths[i], description: "", index: i }); } const selection = yield vscode.window.showQuickPick(items, options); return (selection) ? selection.index : -1; }); } showWorkspaces(workspaceNames) { return __awaiter(this, void 0, void 0, function* () { const options = {}; options.placeHolder = localize(12, null); const items = []; workspaceNames.forEach(name => items.push({ label: name.name, description: "", key: name.key })); const selection = yield vscode.window.showQuickPick(items, options); return (selection) ? selection.key : ""; }); } showParsingCommands() { return __awaiter(this, void 0, void 0, function* () { const options = {}; options.placeHolder = localize(13, null); const items = []; if (this.browseEngineStatusBarItem.tooltip === "Parsing paused") { items.push({ label: localize(14, null), description: "", index: 1 }); } else { items.push({ label: localize(15, null), description: "", index: 0 }); } const selection = yield vscode.window.showQuickPick(items, options); return (selection) ? selection.index : -1; }); } showConfigureIncludePathMessage(prompt, onSkip) { timers_1.setTimeout(() => { this.showConfigurationPrompt(ConfigurationPriority.IncludePath, prompt, onSkip); }, 10000); } showConfigureCompileCommandsMessage(prompt, onSkip) { timers_1.setTimeout(() => { this.showConfigurationPrompt(ConfigurationPriority.CompileCommands, prompt, onSkip); }, 5000); } showConfigureCustomProviderMessage(prompt, onSkip) { this.showConfigurationPrompt(ConfigurationPriority.CustomProvider, prompt, onSkip); } showConfigurationPrompt(priority, prompt, onSkip) { const showPrompt = () => __awaiter(this, void 0, void 0, function* () { const configured = yield prompt(); return Promise.resolve({ priority: priority, configured: configured }); }); if (this.curConfigurationStatus) { this.curConfigurationStatus = this.curConfigurationStatus.then(result => { if (priority > result.priority) { return showPrompt(); } else if (!result.configured) { return showPrompt(); } onSkip(); return Promise.resolve({ priority: result.priority, configured: true }); }); } else { this.curConfigurationStatus = showPrompt(); } } dispose() { this.configStatusBarItem.dispose(); this.browseEngineStatusBarItem.dispose(); this.intelliSenseStatusBarItem.dispose(); this.referencesStatusBarItem.dispose(); } } exports.UI = UI; function getUI() { if (!ui) { ui = new UI(); } return ui; } exports.getUI = getUI; /***/ }), /***/ 4960: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const LanguageServer = __webpack_require__(2973); const util = __webpack_require__(5331); const nls = __webpack_require__(3612); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\commands.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\commands.ts')); class TemporaryCommandRegistrar { constructor() { this.isLanguageServerDisabled = false; this.isActivationReady = false; this.commandsToRegister = [ "C_Cpp.ConfigurationEditJSON", "C_Cpp.ConfigurationEditUI", "C_Cpp.ConfigurationSelect", "C_Cpp.ConfigurationProviderSelect", "C_Cpp.SwitchHeaderSource", "C_Cpp.EnableErrorSquiggles", "C_Cpp.DisableErrorSquiggles", "C_Cpp.ToggleIncludeFallback", "C_Cpp.ToggleDimInactiveRegions", "C_Cpp.ResetDatabase", "C_Cpp.TakeSurvey", "C_Cpp.LogDiagnostics", "C_Cpp.RescanWorkspace", "C_Cpp.GenerateEditorConfig", "C_Cpp.VcpkgClipboardInstallSuggested", "C_Cpp.VcpkgOnlineHelpSuggested", "C_Cpp.CheckForCompiler" ]; this.tempCommands = []; this.delayedCommandsToExecute = new Set(); if (util.extensionContext) { this.commandsToRegister.forEach(command => { this.registerTempCommand(command); }); } } registerTempCommand(command) { this.tempCommands.push(vscode.commands.registerCommand(command, () => { if (this.isLanguageServerDisabled) { vscode.window.showInformationMessage(localize(0, null, "C_Cpp.intelliSenseEngine", "Disabled")); return; } this.delayedCommandsToExecute.add(command); if (this.isActivationReady) { LanguageServer.activate(true); } })); } disableLanguageServer() { this.isLanguageServerDisabled = true; } activateLanguageServer() { LanguageServer.activate(this.delayedCommandsToExecute.size > 0); this.isActivationReady = true; } clearTempCommands() { this.tempCommands.forEach((command) => { command.dispose(); }); this.tempCommands = []; } executeDelayedCommands() { this.delayedCommandsToExecute.forEach((command) => { vscode.commands.executeCommand(command); }); this.delayedCommandsToExecute.clear(); } } let tempCommandRegistrar; function initializeTemporaryCommandRegistrar() { tempCommandRegistrar = new TemporaryCommandRegistrar(); } exports.initializeTemporaryCommandRegistrar = initializeTemporaryCommandRegistrar; function getTemporaryCommandRegistrarInstance() { return tempCommandRegistrar; } exports.getTemporaryCommandRegistrarInstance = getTemporaryCommandRegistrarInstance; /***/ }), /***/ 5331: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __webpack_require__(5622); const fs = __webpack_require__(5747); const os = __webpack_require__(2087); const child_process = __webpack_require__(3129); const vscode = __webpack_require__(7549); const Telemetry = __webpack_require__(1818); const HttpsProxyAgent = __webpack_require__(6638); const url = __webpack_require__(8835); const platform_1 = __webpack_require__(3383); const logger_1 = __webpack_require__(5610); const assert = __webpack_require__(2357); const https = __webpack_require__(7211); const tmp = __webpack_require__(7010); const nativeStrings_1 = __webpack_require__(5391); const nls = __webpack_require__(3612); const packageManager_1 = __webpack_require__(4426); const jsonc = __webpack_require__(634); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\common.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\common.ts')); exports.failedToParseJson = localize(0, null); exports.supportCuda = false; exports.envDelimiter = (process.platform === 'win32') ? ";" : ":"; function setExtensionContext(context) { exports.extensionContext = context; exports.extensionPath = exports.extensionContext.extensionPath; } exports.setExtensionContext = setExtensionContext; function setExtensionPath(path) { exports.extensionPath = path; } exports.setExtensionPath = setExtensionPath; let cachedClangFormatPath; function getCachedClangFormatPath() { return cachedClangFormatPath; } exports.getCachedClangFormatPath = getCachedClangFormatPath; function setCachedClangFormatPath(path) { cachedClangFormatPath = path; } exports.setCachedClangFormatPath = setCachedClangFormatPath; exports.packageJson = (_a = vscode.extensions.getExtension("ms-vscode.cpptools")) === null || _a === void 0 ? void 0 : _a.packageJSON; let rawPackageJson = null; function getRawPackageJson() { if (rawPackageJson === null || rawPackageJson === undefined) { const fileContents = fs.readFileSync(getPackageJsonPath()); rawPackageJson = JSON.parse(fileContents.toString()); } return rawPackageJson; } exports.getRawPackageJson = getRawPackageJson; function getRawJson(path) { return __awaiter(this, void 0, void 0, function* () { if (!path) { return {}; } const fileExists = yield checkFileExists(path); if (!fileExists) { return {}; } const fileContents = yield readFileText(path); let rawElement = {}; try { rawElement = jsonc.parse(fileContents); } catch (error) { throw new Error(exports.failedToParseJson); } return rawElement; }); } exports.getRawJson = getRawJson; function fileIsCOrCppSource(file) { const fileExtLower = path.extname(file).toLowerCase(); return [".cu", ".c", ".cpp", ".cc", ".cxx", ".c++", ".cp", ".tcc", ".mm", ".ino", ".ipp", ".inl"].some(ext => fileExtLower === ext); } exports.fileIsCOrCppSource = fileIsCOrCppSource; function isEditorFileCpp(file) { const editor = vscode.window.visibleTextEditors.find(e => e.document.uri.toString() === file); if (!editor) { return false; } return editor.document.languageId === "cpp"; } exports.isEditorFileCpp = isEditorFileCpp; function stringifyPackageJson(packageJson) { return JSON.stringify(packageJson, null, 2); } exports.stringifyPackageJson = stringifyPackageJson; function getExtensionFilePath(extensionfile) { return path.resolve(exports.extensionPath, extensionfile); } exports.getExtensionFilePath = getExtensionFilePath; function getPackageJsonPath() { return getExtensionFilePath("package.json"); } exports.getPackageJsonPath = getPackageJsonPath; function getJsonPath(jsonFilaName) { const editor = vscode.window.activeTextEditor; if (!editor) { return undefined; } const folder = vscode.workspace.getWorkspaceFolder(editor.document.uri); if (!folder) { return undefined; } return path.join(folder.uri.fsPath, ".vscode", jsonFilaName); } exports.getJsonPath = getJsonPath; function getVcpkgPathDescriptorFile() { if (process.platform === 'win32') { const pathPrefix = process.env.LOCALAPPDATA; if (!pathPrefix) { throw new Error("Unable to read process.env.LOCALAPPDATA"); } return path.join(pathPrefix, "vcpkg/vcpkg.path.txt"); } else { const pathPrefix = os.homedir(); return path.join(pathPrefix, ".vcpkg/vcpkg.path.txt"); } } exports.getVcpkgPathDescriptorFile = getVcpkgPathDescriptorFile; let vcpkgRoot; function getVcpkgRoot() { if (!vcpkgRoot && vcpkgRoot !== "") { vcpkgRoot = ""; if (fs.existsSync(getVcpkgPathDescriptorFile())) { let vcpkgRootTemp = fs.readFileSync(getVcpkgPathDescriptorFile()).toString(); vcpkgRootTemp = vcpkgRootTemp.trim(); if (fs.existsSync(vcpkgRootTemp)) { vcpkgRoot = path.join(vcpkgRootTemp, "/installed").replace(/\\/g, "/"); } } } return vcpkgRoot; } exports.getVcpkgRoot = getVcpkgRoot; function isHeader(uri) { const ext = path.extname(uri.fsPath); return !ext || ext.startsWith(".h") || ext.startsWith(".H"); } exports.isHeader = isHeader; function isExtensionReady() { return __awaiter(this, void 0, void 0, function* () { const doesInstallLockFileExist = yield checkInstallLockFile(); return doesInstallLockFileExist; }); } exports.isExtensionReady = isExtensionReady; let isExtensionNotReadyPromptDisplayed = false; exports.extensionNotReadyString = localize(1, null); function displayExtensionNotReadyPrompt() { if (!isExtensionNotReadyPromptDisplayed) { isExtensionNotReadyPromptDisplayed = true; logger_1.showOutputChannel(); logger_1.getOutputChannelLogger().showInformationMessage(exports.extensionNotReadyString).then(() => { isExtensionNotReadyPromptDisplayed = false; }, () => { isExtensionNotReadyPromptDisplayed = false; }); } } exports.displayExtensionNotReadyPrompt = displayExtensionNotReadyPrompt; const progressInstallSuccess = 100; const progressExecutableStarted = 150; const progressExecutableSuccess = 200; const progressParseRootSuccess = 300; const progressIntelliSenseNoSquiggles = 1000; const installProgressStr = "CPP." + exports.packageJson.version + ".Progress"; const intelliSenseProgressStr = "CPP." + exports.packageJson.version + ".IntelliSenseProgress"; function getProgress() { return exports.extensionContext ? exports.extensionContext.globalState.get(installProgressStr, -1) : -1; } exports.getProgress = getProgress; function getIntelliSenseProgress() { return exports.extensionContext ? exports.extensionContext.globalState.get(intelliSenseProgressStr, -1) : -1; } exports.getIntelliSenseProgress = getIntelliSenseProgress; function setProgress(progress) { if (exports.extensionContext && getProgress() < progress) { exports.extensionContext.globalState.update(installProgressStr, progress); const telemetryProperties = {}; let progressName; switch (progress) { case 0: progressName = "install started"; break; case progressInstallSuccess: progressName = "install succeeded"; break; case progressExecutableStarted: progressName = "executable started"; break; case progressExecutableSuccess: progressName = "executable succeeded"; break; case progressParseRootSuccess: progressName = "parse root succeeded"; break; } if (progressName) { telemetryProperties['progress'] = progressName; } Telemetry.logDebuggerEvent("progress", telemetryProperties); } } exports.setProgress = setProgress; function setIntelliSenseProgress(progress) { if (exports.extensionContext && getIntelliSenseProgress() < progress) { exports.extensionContext.globalState.update(intelliSenseProgressStr, progress); const telemetryProperties = {}; let progressName; switch (progress) { case progressIntelliSenseNoSquiggles: progressName = "IntelliSense no squiggles"; break; } if (progressName) { telemetryProperties['progress'] = progressName; } Telemetry.logDebuggerEvent("progress", telemetryProperties); } } exports.setIntelliSenseProgress = setIntelliSenseProgress; function getProgressInstallSuccess() { return progressInstallSuccess; } exports.getProgressInstallSuccess = getProgressInstallSuccess; function getProgressExecutableStarted() { return progressExecutableStarted; } exports.getProgressExecutableStarted = getProgressExecutableStarted; function getProgressExecutableSuccess() { return progressExecutableSuccess; } exports.getProgressExecutableSuccess = getProgressExecutableSuccess; function getProgressParseRootSuccess() { return progressParseRootSuccess; } exports.getProgressParseRootSuccess = getProgressParseRootSuccess; function getProgressIntelliSenseNoSquiggles() { return progressIntelliSenseNoSquiggles; } exports.getProgressIntelliSenseNoSquiggles = getProgressIntelliSenseNoSquiggles; function isUri(input) { return input && input instanceof vscode.Uri; } exports.isUri = isUri; function isString(input) { return typeof (input) === "string"; } exports.isString = isString; function isNumber(input) { return typeof (input) === "number"; } exports.isNumber = isNumber; function isBoolean(input) { return typeof (input) === "boolean"; } exports.isBoolean = isBoolean; function isObject(input) { return typeof (input) === "object"; } exports.isObject = isObject; function isArray(input) { return input instanceof Array; } exports.isArray = isArray; function isOptionalString(input) { return input === undefined || isString(input); } exports.isOptionalString = isOptionalString; function isArrayOfString(input) { return isArray(input) && input.every(isString); } exports.isArrayOfString = isArrayOfString; function isOptionalArrayOfString(input) { return input === undefined || isArrayOfString(input); } exports.isOptionalArrayOfString = isOptionalArrayOfString; function resolveCachePath(input, additionalEnvironment) { let resolvedPath = ""; if (!input) { return resolvedPath; } resolvedPath = resolveVariables(input, additionalEnvironment); return resolvedPath; } exports.resolveCachePath = resolveCachePath; function resolveVariables(input, additionalEnvironment) { if (!input) { return ""; } let regexp = () => /\$\{((env|config|workspaceFolder|file|fileDirname|fileBasenameNoExtension)(\.|:))?(.*?)\}/g; let ret = input; const cycleCache = new Set(); while (!cycleCache.has(ret)) { cycleCache.add(ret); ret = ret.replace(regexp(), (match, ignored1, varType, ignored2, name) => { if (!varType) { varType = "env"; } let newValue; switch (varType) { case "env": { if (additionalEnvironment) { const v = additionalEnvironment[name]; if (isString(v)) { newValue = v; } else if (input === match && isArrayOfString(v)) { newValue = v.join(exports.envDelimiter); } } if (newValue === undefined) { newValue = process.env[name]; } break; } case "config": { const config = vscode.workspace.getConfiguration(); if (config) { newValue = config.get(name); } break; } case "workspaceFolder": { if (name && vscode.workspace && vscode.workspace.workspaceFolders) { const folder = vscode.workspace.workspaceFolders.find(folder => folder.name.toLocaleLowerCase() === name.toLocaleLowerCase()); if (folder) { newValue = folder.uri.fsPath; } } break; } default: { assert.fail("unknown varType matched"); } } return newValue !== undefined ? newValue : match; }); } regexp = () => /^\~/g; ret = ret.replace(regexp(), (match, name) => os.homedir()); return ret; } exports.resolveVariables = resolveVariables; function asFolder(uri) { let result = uri.toString(); if (result.charAt(result.length - 1) !== '/') { result += '/'; } return result; } exports.asFolder = asFolder; function getOpenCommand() { if (os.platform() === 'win32') { return 'explorer'; } else if (os.platform() === 'darwin') { return '/usr/bin/open'; } else { return '/usr/bin/xdg-open'; } } exports.getOpenCommand = getOpenCommand; function getDebugAdaptersPath(file) { return path.resolve(getExtensionFilePath("debugAdapters"), file); } exports.getDebugAdaptersPath = getDebugAdaptersPath; function getHttpsProxyAgent() { let proxy = vscode.workspace.getConfiguration().get('http.proxy'); if (!proxy) { proxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy; if (!proxy) { return undefined; } } const proxyUrl = url.parse(proxy); if (proxyUrl.protocol !== "https:" && proxyUrl.protocol !== "http:") { return undefined; } const strictProxy = vscode.workspace.getConfiguration().get("http.proxyStrictSSL", true); const proxyOptions = { host: proxyUrl.hostname, port: parseInt(proxyUrl.port, 10), auth: proxyUrl.auth, rejectUnauthorized: strictProxy }; return new HttpsProxyAgent(proxyOptions); } exports.getHttpsProxyAgent = getHttpsProxyAgent; ; function touchInstallLockFile(info) { const installLockObject = { platform: info.platform, architecture: info.architecture }; const content = JSON.stringify(installLockObject); return writeFileText(getInstallLockPath(), content); } exports.touchInstallLockFile = touchInstallLockFile; function touchExtensionFolder() { return new Promise((resolve, reject) => { fs.utimes(path.resolve(exports.extensionPath, ".."), new Date(Date.now()), new Date(Date.now()), (err) => { if (err) { reject(err); } resolve(); }); }); } exports.touchExtensionFolder = touchExtensionFolder; function checkFileExists(filePath) { return new Promise((resolve, reject) => { fs.stat(filePath, (err, stats) => { if (stats && stats.isFile()) { resolve(true); } else { resolve(false); } }); }); } exports.checkFileExists = checkFileExists; function checkDirectoryExists(dirPath) { return new Promise((resolve, reject) => { fs.stat(dirPath, (err, stats) => { if (stats && stats.isDirectory()) { resolve(true); } else { resolve(false); } }); }); } exports.checkDirectoryExists = checkDirectoryExists; function checkFileExistsSync(filePath) { try { return fs.statSync(filePath).isFile(); } catch (e) { } return false; } exports.checkFileExistsSync = checkFileExistsSync; function checkDirectoryExistsSync(dirPath) { try { return fs.statSync(dirPath).isDirectory(); } catch (e) { } return false; } exports.checkDirectoryExistsSync = checkDirectoryExistsSync; function checkPathExistsSync(path, relativePath, isWindows, isWSL, isCompilerPath) { let pathExists = true; const existsWithExeAdded = (path) => isCompilerPath && isWindows && !isWSL && fs.existsSync(path + ".exe"); if (!fs.existsSync(path)) { if (existsWithExeAdded(path)) { path += ".exe"; } else if (!relativePath) { pathExists = false; } else { relativePath = relativePath + path; if (!fs.existsSync(relativePath)) { if (existsWithExeAdded(path)) { path += ".exe"; } else { pathExists = false; } } else { path = relativePath; } } } return { pathExists, path }; } exports.checkPathExistsSync = checkPathExistsSync; function readDir(dirPath) { return new Promise((resolve) => { fs.readdir(dirPath, (err, list) => { resolve(list); }); }); } exports.readDir = readDir; function checkInstallLockFile() { return checkFileExists(getInstallLockPath()); } exports.checkInstallLockFile = checkInstallLockFile; function checkInstallBinariesExist() { return __awaiter(this, void 0, void 0, function* () { if (!checkInstallLockFile()) { return false; } let installBinariesExist = true; const info = yield platform_1.PlatformInformation.GetPlatformInformation(); const packageManager = new packageManager_1.PackageManager(info); const packages = packageManager.GetPackages(); for (const pkg of yield packages) { if (pkg.binaries) { yield Promise.all(pkg.binaries.map((file) => __awaiter(this, void 0, void 0, function* () { if (!(yield checkFileExists(file))) { installBinariesExist = false; const fileBase = path.basename(file); console.log(`Extension file ${fileBase} is missing.`); Telemetry.logLanguageServerEvent("missingBinary", { "source": `${fileBase}` }); } }))); } } return installBinariesExist; }); } exports.checkInstallBinariesExist = checkInstallBinariesExist; function checkInstallJsonsExist() { return __awaiter(this, void 0, void 0, function* () { let installJsonsExist = true; const jsonFiles = [ "bin/common.json", "bin/linux.clang.arm.json", "bin/linux.clang.arm64.json", "bin/linux.clang.x64.json", "bin/linux.clang.x86.json", "bin/linux.gcc.arm.json", "bin/linux.gcc.arm64.json", "bin/linux.gcc.x64.json", "bin/linux.gcc.x86.json", "bin/macos.clang.arm.json", "bin/macos.clang.arm64.json", "bin/macos.clang.x64.json", "bin/macos.clang.x86.json", "bin/macos.gcc.arm.json", "bin/macos.gcc.arm64.json", "bin/macos.gcc.x64.json", "bin/macos.gcc.x86.json", "bin/windows.clang.arm.json", "bin/windows.clang.arm64.json", "bin/windows.clang.x64.json", "bin/windows.clang.x86.json", "bin/windows.gcc.arm.json", "bin/windows.gcc.arm64.json", "bin/windows.gcc.x64.json", "bin/windows.gcc.x86.json", "bin/windows.msvc.arm.json", "bin/windows.msvc.arm64.json", "bin/windows.msvc.x64.json", "bin/windows.msvc.x86.json", "debugAdapters/bin/cppdbg.ad7Engine.json" ]; yield Promise.all(jsonFiles.map((file) => __awaiter(this, void 0, void 0, function* () { if (!(yield checkFileExists(path.join(exports.extensionPath, file)))) { installJsonsExist = false; console.log(`Extension file ${file} is missing.`); Telemetry.logLanguageServerEvent("missingJson", { "source": `${file}` }); } }))); return installJsonsExist; }); } exports.checkInstallJsonsExist = checkInstallJsonsExist; function removeInstallLockFile() { return __awaiter(this, void 0, void 0, function* () { yield unlinkAsync(path.join(exports.extensionPath, "install.lock")); }); } exports.removeInstallLockFile = removeInstallLockFile; function readFileText(filePath, encoding = "utf8") { return new Promise((resolve, reject) => { fs.readFile(filePath, encoding, (err, data) => { if (err) { reject(err); } else { resolve(data); } }); }); } exports.readFileText = readFileText; function writeFileText(filePath, content, encoding = "utf8") { const folders = filePath.split(path.sep).slice(0, -1); if (folders.length) { folders.reduce((previous, folder) => { const folderPath = previous + path.sep + folder; if (!fs.existsSync(folderPath)) { fs.mkdirSync(folderPath); } return folderPath; }); } return new Promise((resolve, reject) => { fs.writeFile(filePath, content, { encoding }, (err) => { if (err) { reject(err); } else { resolve(); } }); }); } exports.writeFileText = writeFileText; function deleteFile(filePath) { return new Promise((resolve, reject) => { if (fs.existsSync(filePath)) { fs.unlink(filePath, (err) => { if (err) { reject(err); } else { resolve(); } }); } else { resolve(); } }); } exports.deleteFile = deleteFile; function getInstallLockPath() { return getExtensionFilePath("install.lock"); } exports.getInstallLockPath = getInstallLockPath; function getReadmeMessage() { const readmePath = getExtensionFilePath("README.md"); const readmeMessage = localize(2, null, readmePath, "https://github.com/Microsoft/vscode-cpptools/issues"); return readmeMessage; } exports.getReadmeMessage = getReadmeMessage; function logToFile(message) { const logFolder = getExtensionFilePath("extension.log"); fs.writeFileSync(logFolder, `${message}${os.EOL}`, { flag: 'a' }); } exports.logToFile = logToFile; function execChildProcess(process, workingDirectory, channel) { return new Promise((resolve, reject) => { child_process.exec(process, { cwd: workingDirectory, maxBuffer: 500 * 1024 }, (error, stdout, stderr) => { if (channel) { let message = ""; let err = false; if (stdout && stdout.length > 0) { message += stdout; } if (stderr && stderr.length > 0) { message += stderr; err = true; } if (error) { message += error.message; err = true; } if (err) { channel.append(message); channel.show(); } } if (error) { reject(error); return; } if (stderr && stderr.length > 0) { reject(new Error(stderr)); return; } resolve(stdout); }); }); } exports.execChildProcess = execChildProcess; function spawnChildProcess(process, args, workingDirectory, dataCallback, errorCallback) { return new Promise(function (resolve, reject) { const child = child_process.spawn(process, args, { cwd: workingDirectory }); const stdout = child.stdout; if (stdout) { stdout.on('data', (data) => { dataCallback(`${data}`); }); } const stderr = child.stderr; if (stderr) { stderr.on('data', (data) => { errorCallback(`${data}`); }); } child.on('exit', (code) => { if (code !== 0) { reject(new Error(localize(3, null, process, code))); } else { resolve(); } }); }); } exports.spawnChildProcess = spawnChildProcess; function isExecutable(file) { return new Promise((resolve) => { fs.access(file, fs.constants.X_OK, (err) => { if (err) { resolve(false); } else { resolve(true); } }); }); } exports.isExecutable = isExecutable; function allowExecution(file) { return __awaiter(this, void 0, void 0, function* () { if (process.platform !== 'win32') { const exists = yield checkFileExists(file); if (exists) { const isExec = yield isExecutable(file); if (!isExec) { yield chmodAsync(file, '755'); } } else { logger_1.getOutputChannelLogger().appendLine(""); logger_1.getOutputChannelLogger().appendLine(localize(4, null, file)); } } }); } exports.allowExecution = allowExecution; function chmodAsync(path, mode) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { fs.chmod(path, mode, (err) => { if (err) { return reject(err); } return resolve(); }); }); }); } exports.chmodAsync = chmodAsync; function removePotentialPII(str) { const words = str.split(" "); let result = ""; for (const word of words) { if (word.indexOf(".") === -1 && word.indexOf("/") === -1 && word.indexOf("\\") === -1 && word.indexOf(":") === -1) { result += word + " "; } else { result += "? "; } } return result; } exports.removePotentialPII = removePotentialPII; function checkDistro(platformInfo) { if (platformInfo.platform !== 'win32' && platformInfo.platform !== 'linux' && platformInfo.platform !== 'darwin') { logger_1.getOutputChannelLogger().appendLine(localize(5, null) + " " + getReadmeMessage()); } } exports.checkDistro = checkDistro; function unlinkAsync(fileName) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { fs.unlink(fileName, err => { if (err) { return reject(err); } return resolve(); }); }); }); } exports.unlinkAsync = unlinkAsync; function renameAsync(oldName, newName) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { fs.rename(oldName, newName, err => { if (err) { return reject(err); } return resolve(); }); }); }); } exports.renameAsync = renameAsync; function promptForReloadWindowDueToSettingsChange() { promptReloadWindow(localize(6, null)); } exports.promptForReloadWindowDueToSettingsChange = promptForReloadWindowDueToSettingsChange; function promptReloadWindow(message) { const reload = localize(7, null); vscode.window.showInformationMessage(message, reload).then((value) => { if (value === reload) { vscode.commands.executeCommand("workbench.action.reloadWindow"); } }); } exports.promptReloadWindow = promptReloadWindow; function createTempFileWithPostfix(postfix) { return new Promise((resolve, reject) => { tmp.file({ postfix: postfix }, (err, path, fd, cleanupCallback) => { if (err) { return reject(err); } return resolve({ name: path, fd: fd, removeCallback: cleanupCallback }); }); }); } exports.createTempFileWithPostfix = createTempFileWithPostfix; function downloadFileToDestination(urlStr, destinationPath, headers) { return new Promise((resolve, reject) => { const parsedUrl = url.parse(urlStr); const request = https.request({ host: parsedUrl.host, path: parsedUrl.path, agent: getHttpsProxyAgent(), rejectUnauthorized: vscode.workspace.getConfiguration().get('http.proxyStrictSSL', true), headers: headers }, (response) => { if (response.statusCode === 301 || response.statusCode === 302) { let redirectUrl; if (typeof response.headers.location === 'string') { redirectUrl = response.headers.location; } else { if (!response.headers.location) { return reject(new Error(localize(8, null))); } redirectUrl = response.headers.location[0]; } return resolve(downloadFileToDestination(redirectUrl, destinationPath, headers)); } if (response.statusCode !== 200) { return reject(); } const createdFile = fs.createWriteStream(destinationPath); createdFile.on('finish', () => { resolve(); }); response.on('error', (error) => { reject(error); }); response.pipe(createdFile); }); request.on('error', (error) => { reject(error); }); request.end(); }); } exports.downloadFileToDestination = downloadFileToDestination; function downloadFileToStr(urlStr, headers) { return new Promise((resolve, reject) => { const parsedUrl = url.parse(urlStr); const request = https.request({ host: parsedUrl.host, path: parsedUrl.path, agent: getHttpsProxyAgent(), rejectUnauthorized: vscode.workspace.getConfiguration().get('http.proxyStrictSSL', true), headers: headers }, (response) => { if (response.statusCode === 301 || response.statusCode === 302) { let redirectUrl; if (typeof response.headers.location === 'string') { redirectUrl = response.headers.location; } else { if (!response.headers.location) { return reject(new Error(localize(9, null))); } redirectUrl = response.headers.location[0]; } return resolve(downloadFileToStr(redirectUrl, headers)); } if (response.statusCode !== 200) { return reject(); } let downloadedData = ''; response.on('data', (data) => { downloadedData += data; }); response.on('error', (error) => { reject(error); }); response.on('end', () => { resolve(downloadedData); }); }); request.on('error', (error) => { reject(error); }); request.end(); }); } exports.downloadFileToStr = downloadFileToStr; function extractArgs(argsString) { const isWindows = os.platform() === 'win32'; const result = []; let currentArg = ""; let isWithinDoubleQuote = false; let isWithinSingleQuote = false; for (let i = 0; i < argsString.length; i++) { const c = argsString[i]; if (c === '\\') { currentArg += c; if (++i === argsString.length) { if (currentArg !== "") { result.push(currentArg); } return result; } currentArg += argsString[i]; continue; } if (c === '"') { if (!isWithinSingleQuote) { isWithinDoubleQuote = !isWithinDoubleQuote; } } else if (c === '\'') { if (!isWindows) { if (!isWithinDoubleQuote) { isWithinSingleQuote = !isWithinSingleQuote; } } } else if (c === ' ') { if (!isWithinDoubleQuote && !isWithinSingleQuote) { if (currentArg !== "") { result.push(currentArg); currentArg = ""; } continue; } } currentArg += c; } if (currentArg !== "") { result.push(currentArg); } return result; } function extractCompilerPathAndArgs(inputCompilerPath, inputCompilerArgs) { var _a, _b, _c, _d, _e; let compilerPath = inputCompilerPath; const compilerPathLowercase = (_a = inputCompilerPath) === null || _a === void 0 ? void 0 : _a.toLowerCase(); let compilerName = ""; let additionalArgs = []; if (compilerPath) { if (((_b = compilerPathLowercase) === null || _b === void 0 ? void 0 : _b.endsWith("\\cl.exe")) || ((_c = compilerPathLowercase) === null || _c === void 0 ? void 0 : _c.endsWith("/cl.exe")) || (compilerPathLowercase === "cl.exe") || ((_d = compilerPathLowercase) === null || _d === void 0 ? void 0 : _d.endsWith("\\cl")) || ((_e = compilerPathLowercase) === null || _e === void 0 ? void 0 : _e.endsWith("/cl")) || (compilerPathLowercase === "cl")) { compilerName = path.basename(compilerPath); } else if (compilerPath.startsWith("\"")) { const endQuote = compilerPath.substr(1).search("\"") + 1; if (endQuote !== -1) { additionalArgs = extractArgs(compilerPath.substr(endQuote + 1)); compilerPath = compilerPath.substr(1, endQuote - 1); compilerName = path.basename(compilerPath); } } else { let spaceStart = compilerPath.lastIndexOf(" "); if (checkFileExistsSync(compilerPath)) { compilerName = path.basename(compilerPath); } else if (spaceStart !== -1 && !checkFileExistsSync(compilerPath)) { let potentialCompilerPath = compilerPath.substr(0, spaceStart); while (!checkFileExistsSync(potentialCompilerPath)) { spaceStart = potentialCompilerPath.lastIndexOf(" "); if (spaceStart === -1) { potentialCompilerPath = compilerPath; break; } potentialCompilerPath = potentialCompilerPath.substr(0, spaceStart); } if (compilerPath !== potentialCompilerPath) { additionalArgs = extractArgs(compilerPath.substr(spaceStart + 1)); compilerPath = potentialCompilerPath; compilerName = path.basename(potentialCompilerPath); } } } } if (inputCompilerArgs && inputCompilerArgs.length) { additionalArgs = inputCompilerArgs.concat(additionalArgs.filter(function (item) { return inputCompilerArgs.indexOf(item) < 0; })); } return { compilerPath, compilerName, additionalArgs }; } exports.extractCompilerPathAndArgs = extractCompilerPathAndArgs; function escapeForSquiggles(s) { let newResults = ""; let lastWasBackslash = false; let lastBackslashWasEscaped = false; for (let i = 0; i < s.length; i++) { if (s[i] === '\\') { if (lastWasBackslash) { newResults += "\\"; lastBackslashWasEscaped = !lastBackslashWasEscaped; } else { lastBackslashWasEscaped = false; } newResults += "\\"; lastWasBackslash = true; } else { if (lastWasBackslash && (lastBackslashWasEscaped || (s[i] !== '"'))) { newResults += "\\"; } lastWasBackslash = false; lastBackslashWasEscaped = false; newResults += s[i]; } } if (lastWasBackslash) { newResults += "\\"; } return newResults; } exports.escapeForSquiggles = escapeForSquiggles; class BlockingTask { constructor(task, dependency) { this.done = false; if (!dependency) { this.promise = task(); } else { this.promise = new Promise((resolve, reject) => { const f1 = () => { task().then(resolve, reject); }; const f2 = (err) => { console.log(err); task().then(resolve, reject); }; dependency.promise.then(f1, f2); }); } this.promise.then(() => this.done = true, () => this.done = true); } get Done() { return this.done; } getPromise() { return this.promise; } } exports.BlockingTask = BlockingTask; function getLocaleId() { if (isString(process.env.VSCODE_NLS_CONFIG)) { const vscodeOptions = JSON.parse(process.env.VSCODE_NLS_CONFIG); if (vscodeOptions.availableLanguages) { const value = vscodeOptions.availableLanguages['*']; if (isString(value)) { return value; } } if (isString(vscodeOptions.locale)) { return vscodeOptions.locale.toLowerCase(); } } return "en"; } exports.getLocaleId = getLocaleId; function getLocalizedHtmlPath(originalPath) { const locale = getLocaleId(); const localizedFilePath = getExtensionFilePath(path.join("dist/html/", locale, originalPath)); if (!fs.existsSync(localizedFilePath)) { return getExtensionFilePath(originalPath); } return localizedFilePath; } exports.getLocalizedHtmlPath = getLocalizedHtmlPath; function getLocalizedString(params) { let indent = ""; if (params.indentSpaces) { indent = " ".repeat(params.indentSpaces); } let text = params.text; if (params.stringId !== 0) { text = nativeStrings_1.lookupString(params.stringId, params.stringArgs); } return indent + text; } exports.getLocalizedString = getLocalizedString; function getLocalizedSymbolScope(scope, detail) { return localize(10, null, scope, detail); } exports.getLocalizedSymbolScope = getLocalizedSymbolScope; function decodeUCS16(input) { const output = []; let counter = 0; const length = input.length; let value; let extra; while (counter < length) { value = input.charCodeAt(counter++); if ((value & 0xF800) === 0xD800 && counter < length) { extra = input.charCodeAt(counter++); if ((extra & 0xFC00) === 0xDC00) { output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { output.push(value, extra); } } else { output.push(value); } } return output; } const allowedIdentifierUnicodeRanges = [ [0x0030, 0x0039], [0x0041, 0x005A], [0x005F, 0x005F], [0x0061, 0x007A], [0x00A8, 0x00A8], [0x00AA, 0x00AA], [0x00AD, 0x00AD], [0x00AF, 0x00AF], [0x00B2, 0x00B5], [0x00B7, 0x00BA], [0x00BC, 0x00BE], [0x00C0, 0x00D6], [0x00D8, 0x00F6], [0x00F8, 0x167F], [0x1681, 0x180D], [0x180F, 0x1FFF], [0x200B, 0x200D], [0x202A, 0x202E], [0x203F, 0x2040], [0x2054, 0x2054], [0x2060, 0x218F], [0x2460, 0x24FF], [0x2776, 0x2793], [0x2C00, 0x2DFF], [0x2E80, 0x2FFF], [0x3004, 0x3007], [0x3021, 0x302F], [0x3031, 0xD7FF], [0xF900, 0xFD3D], [0xFD40, 0xFDCF], [0xFDF0, 0xFE44], [0xFE47, 0xFFFD], [0x10000, 0x1FFFD], [0x20000, 0x2FFFD], [0x30000, 0x3FFFD], [0x40000, 0x4FFFD], [0x50000, 0x5FFFD], [0x60000, 0x6FFFD], [0x70000, 0x7FFFD], [0x80000, 0x8FFFD], [0x90000, 0x9FFFD], [0xA0000, 0xAFFFD], [0xB0000, 0xBFFFD], [0xC0000, 0xCFFFD], [0xD0000, 0xDFFFD], [0xE0000, 0xEFFFD] ]; const disallowedFirstCharacterIdentifierUnicodeRanges = [ [0x0030, 0x0039], [0x0300, 0x036F], [0x1DC0, 0x1DFF], [0x20D0, 0x20FF], [0xFE20, 0xFE2F] ]; function isValidIdentifier(candidate) { if (!candidate) { return false; } const decoded = decodeUCS16(candidate); if (!decoded || !decoded.length) { return false; } for (let i = 0; i < disallowedFirstCharacterIdentifierUnicodeRanges.length; i++) { const disallowedCharacters = disallowedFirstCharacterIdentifierUnicodeRanges[i]; if (decoded[0] >= disallowedCharacters[0] && decoded[0] <= disallowedCharacters[1]) { return false; } } for (let position = 0; position < decoded.length; position++) { let found = false; for (let i = 0; i < allowedIdentifierUnicodeRanges.length; i++) { const allowedCharacters = allowedIdentifierUnicodeRanges[i]; if (decoded[position] >= allowedCharacters[0] && decoded[position] <= allowedCharacters[1]) { found = true; break; } } if (!found) { return false; } } return true; } exports.isValidIdentifier = isValidIdentifier; function getUniqueWorkspaceNameHelper(workspaceFolder, addSubfolder) { const workspaceFolderName = workspaceFolder ? workspaceFolder.name : "untitled"; if (!workspaceFolder || workspaceFolder.index < 1) { return workspaceFolderName; } for (let i = 0; i < workspaceFolder.index; ++i) { if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders[i].name === workspaceFolderName) { return addSubfolder ? path.join(workspaceFolderName, String(workspaceFolder.index)) : workspaceFolderName + String(workspaceFolder.index); } } return workspaceFolderName; } function getUniqueWorkspaceName(workspaceFolder) { return getUniqueWorkspaceNameHelper(workspaceFolder, false); } exports.getUniqueWorkspaceName = getUniqueWorkspaceName; function getUniqueWorkspaceStorageName(workspaceFolder) { return getUniqueWorkspaceNameHelper(workspaceFolder, true); } exports.getUniqueWorkspaceStorageName = getUniqueWorkspaceStorageName; function isCodespaces() { return !!process.env["CODESPACES"]; } exports.isCodespaces = isCodespaces; function checkCuda() { return __awaiter(this, void 0, void 0, function* () { const langs = yield vscode.languages.getLanguages(); exports.supportCuda = langs.findIndex((s) => s === "cuda-cpp") !== -1; }); } exports.checkCuda = checkCuda; function sequentialResolve(items, promiseBuilder) { return items.reduce((previousPromise, nextItem) => __awaiter(this, void 0, void 0, function* () { yield previousPromise; return promiseBuilder(nextItem); }), Promise.resolve()); } exports.sequentialResolve = sequentialResolve; /***/ }), /***/ 2451: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode_cpptools_1 = __webpack_require__(3286); const customProviders_1 = __webpack_require__(4977); const logger_1 = __webpack_require__(5610); const LanguageServer = __webpack_require__(2973); const test = __webpack_require__(5648); const nls = __webpack_require__(3612); const settings_1 = __webpack_require__(296); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\cppTools.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\cppTools.ts')); class CppTools { constructor(version) { this.providers = []; this.failedRegistrations = []; this.timers = new Map(); if (version > vscode_cpptools_1.Version.latest) { console.warn(`version ${version} is not supported by this version of cpptools`); console.warn(` using ${vscode_cpptools_1.Version.latest} instead`); version = vscode_cpptools_1.Version.latest; } this.version = version; } addNotifyReadyTimer(provider) { if (this.version >= vscode_cpptools_1.Version.v2) { const timeout = 30; const timer = global.setTimeout(() => { console.warn(`registered provider ${provider.extensionId} did not call 'notifyReady' within ${timeout} seconds`); }, timeout * 1000); this.timers.set(provider.extensionId, timer); } } removeNotifyReadyTimer(provider) { if (this.version >= vscode_cpptools_1.Version.v2) { const timer = this.timers.get(provider.extensionId); if (timer) { this.timers.delete(provider.extensionId); clearTimeout(timer); } } } getVersion() { return this.version; } registerCustomConfigurationProvider(provider) { const providers = customProviders_1.getCustomConfigProviders(); if (providers.add(provider, this.version)) { const added = providers.get(provider); if (added) { const settings = new settings_1.CppSettings(); if (settings.loggingLevel === "Information" || settings.loggingLevel === "Debug") { logger_1.getOutputChannel().appendLine(localize(0, null, added.name)); } this.providers.push(added); LanguageServer.getClients().forEach(client => client.onRegisterCustomConfigurationProvider(added)); this.addNotifyReadyTimer(added); } } else { this.failedRegistrations.push(provider); } } notifyReady(provider) { const providers = customProviders_1.getCustomConfigProviders(); const p = providers.get(provider); if (p) { this.removeNotifyReadyTimer(p); p.isReady = true; LanguageServer.getClients().forEach(client => { client.updateCustomBrowseConfiguration(p); client.updateCustomConfigurations(p); }); } else if (this.failedRegistrations.find(p => p === provider)) { console.warn("provider not successfully registered; 'notifyReady' ignored"); } else { console.warn("provider should be registered before signaling it's ready to provide configurations"); } } didChangeCustomConfiguration(provider) { const providers = customProviders_1.getCustomConfigProviders(); const p = providers.get(provider); if (p) { if (!p.isReady) { console.warn("didChangeCustomConfiguration was invoked before notifyReady"); } LanguageServer.getClients().forEach(client => client.updateCustomConfigurations(p)); } else if (this.failedRegistrations.find(p => p === provider)) { console.warn("provider not successfully registered, 'didChangeCustomConfiguration' ignored"); } else { console.warn("provider should be registered before sending config change messages"); } } didChangeCustomBrowseConfiguration(provider) { const providers = customProviders_1.getCustomConfigProviders(); const p = providers.get(provider); if (p) { LanguageServer.getClients().forEach(client => client.updateCustomBrowseConfiguration(p)); } else if (this.failedRegistrations.find(p => p === provider)) { console.warn("provider not successfully registered, 'didChangeCustomBrowseConfiguration' ignored"); } else { console.warn("provider should be registered before sending config change messages"); } } dispose() { this.providers.forEach(provider => { customProviders_1.getCustomConfigProviders().remove(provider); provider.dispose(); }); this.providers = []; } getTestHook() { return test.getTestHook(); } } exports.CppTools = CppTools; /***/ }), /***/ 8674: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode_cpptools_1 = __webpack_require__(3286); const cppTools_1 = __webpack_require__(2451); class CppTools1 { get BackupApi() { if (!this.backupApi) { this.backupApi = new cppTools_1.CppTools(vscode_cpptools_1.Version.v0); } return this.backupApi; } getApi(version) { switch (version) { case vscode_cpptools_1.Version.v0: return this.BackupApi; default: return new cppTools_1.CppTools(version); } } getTestApi(version) { return this.getApi(version); } getVersion() { return this.BackupApi.getVersion(); } registerCustomConfigurationProvider(provider) { this.BackupApi.registerCustomConfigurationProvider(provider); } notifyReady(provider) { this.BackupApi.notifyReady(provider); } didChangeCustomConfiguration(provider) { this.BackupApi.didChangeCustomConfiguration(provider); } didChangeCustomBrowseConfiguration(provider) { this.BackupApi.didChangeCustomBrowseConfiguration(provider); } dispose() { } getTestHook() { return this.BackupApi.getTestHook(); } } exports.CppTools1 = CppTools1; class NullCppTools { constructor() { this.version = vscode_cpptools_1.Version.v0; } getApi(version) { this.version = version; return this; } getVersion() { return this.version; } registerCustomConfigurationProvider(provider) { } notifyReady(provider) { } didChangeCustomConfiguration(provider) { } didChangeCustomBrowseConfiguration(provider) { } dispose() { } } exports.NullCppTools = NullCppTools; /***/ }), /***/ 3158: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const packageVersion_1 = __webpack_require__(302); const util = __webpack_require__(5331); const platform_1 = __webpack_require__(3383); const vscode = __webpack_require__(7549); const telemetry = __webpack_require__(1818); const testingInsidersVsixInstall = false; exports.releaseDownloadUrl = "https://github.com/microsoft/vscode-cpptools/releases"; function getVsixDownloadUrl(build, vsixName) { const asset = build.assets.find(asset => asset.name === vsixName); const downloadUrl = (asset) ? asset.browser_download_url : null; if (!downloadUrl) { throw new Error(`Failed to find VSIX: ${vsixName} in build: ${build.name}`); } return downloadUrl; } function isAsset(input) { return input && input.name && typeof (input.name) === "string" && input.browser_download_url && typeof (input.browser_download_url) === "string"; } function isBuild(input) { return input && input.name && typeof (input.name) === "string" && isArrayOfAssets(input.assets); } function isValidBuild(input) { return isBuild(input) && input.assets.length >= 3; } function isArrayOfAssets(input) { return input instanceof Array && input.every(isAsset); } function getArrayOfBuilds(input) { const builds = []; if (!input || !(input instanceof Array) || input.length === 0) { return builds; } for (let i = 0; i < input.length; i++) { if (isBuild(input[i])) { builds.push(input[i]); if (input[i].name.indexOf('-') === -1 && isValidBuild(input[i])) { break; } } } return builds; } function vsixNameForPlatform(info) { const vsixName = function (platformInfo) { switch (platformInfo.platform) { case 'win32': switch (platformInfo.architecture) { case 'x64': return 'cpptools-win32.vsix'; case 'x86': return 'cpptools-win32.vsix'; case 'arm64': return 'cpptools-win-arm64.vsix'; default: throw new Error(`Unexpected Windows architecture: ${platformInfo.architecture}`); } case 'darwin': switch (platformInfo.architecture) { case 'x64': return 'cpptools-osx.vsix'; case 'arm64': return 'cpptools-osx-arm64.vsix'; default: throw new Error(`Unexpected macOS architecture: ${platformInfo.architecture}`); } default: { switch (platformInfo.architecture) { case 'x64': return 'cpptools-linux.vsix'; case 'arm': return 'cpptools-linux-armhf.vsix'; case 'arm64': return 'cpptools-linux-aarch64.vsix'; default: throw new Error(`Unexpected Linux architecture: ${platformInfo.architecture}`); } } } }(info); if (!vsixName) { throw new Error(`Failed to match VSIX name for: ${info.platform}: ${info.architecture}`); } return vsixName; } exports.vsixNameForPlatform = vsixNameForPlatform; function getTargetBuildInfo(updateChannel, isFromSettingsChange) { return __awaiter(this, void 0, void 0, function* () { const builds = yield getReleaseJson(); if (!builds || builds.length === 0) { return undefined; } const userVersion = new packageVersion_1.PackageVersion(util.packageJson.version); const targetBuild = getTargetBuild(builds, userVersion, updateChannel, isFromSettingsChange); if (targetBuild === undefined) { telemetry.logLanguageServerEvent("UpgradeCheck", { "action": "none" }); } else if (userVersion.isExtensionVersionGreaterThan(new packageVersion_1.PackageVersion(targetBuild.name))) { telemetry.logLanguageServerEvent("UpgradeCheck", { "action": "downgrade", "newVersion": targetBuild.name }); } else { telemetry.logLanguageServerEvent("UpgradeCheck", { "action": "upgrade", "newVersion": targetBuild.name }); } if (!targetBuild) { return undefined; } const platformInfo = yield platform_1.PlatformInformation.GetPlatformInformation(); const vsixName = vsixNameForPlatform(platformInfo); const downloadUrl = getVsixDownloadUrl(targetBuild, vsixName); if (!downloadUrl) { return undefined; } return { downloadUrl: downloadUrl, name: targetBuild.name }; }); } exports.getTargetBuildInfo = getTargetBuildInfo; function getTargetBuild(builds, userVersion, updateChannel, isFromSettingsChange) { if (!isFromSettingsChange && !vscode.workspace.getConfiguration("extensions", null).get("autoUpdate")) { return undefined; } const latestVersionOnline = new packageVersion_1.PackageVersion(builds[0].name); if ((!testingInsidersVsixInstall && userVersion.suffix && userVersion.suffix !== 'insiders') || userVersion.isExtensionVersionGreaterThan(latestVersionOnline)) { return undefined; } let needsUpdate; let useBuild; if (updateChannel === 'Insiders') { needsUpdate = (installed, target) => testingInsidersVsixInstall || (!target.isEqual(installed)); useBuild = isValidBuild; } else if (updateChannel === 'Default') { needsUpdate = function (installed, target) { return installed.isExtensionVersionGreaterThan(target); }; useBuild = (build) => build.name.indexOf('-') === -1 && isValidBuild(build); } else { throw new Error('Incorrect updateChannel setting provided'); } const targetBuild = builds.find(useBuild); if (!targetBuild) { throw new Error('Failed to determine installation candidate'); } const targetVersion = new packageVersion_1.PackageVersion(targetBuild.name); if (needsUpdate(userVersion, targetVersion)) { return targetBuild; } else { return undefined; } } exports.getTargetBuild = getTargetBuild; function isRate(input) { return input && util.isNumber(input.remaining); } function isRateLimit(input) { return input && isRate(input.rate); } function getRateLimit() { return __awaiter(this, void 0, void 0, function* () { const header = { 'User-Agent': 'vscode-cpptools' }; try { const data = yield util.downloadFileToStr('https://api.github.com/rate_limit', header); if (!data) { return undefined; } let rateLimit; try { rateLimit = JSON.parse(data); } catch (error) { throw new Error('Failed to parse rate limit JSON'); } if (isRateLimit(rateLimit)) { return rateLimit; } else { throw new Error('Rate limit JSON is not of type RateLimit'); } } catch (err) { if (err && err.code && err.code !== "ENOENT") { throw new Error('Failed to download rate limit JSON'); } } }); } function rateLimitExceeded() { return __awaiter(this, void 0, void 0, function* () { const rateLimit = yield getRateLimit(); return rateLimit !== undefined && rateLimit.rate.remaining <= 0; }); } function getReleaseJson() { return __awaiter(this, void 0, void 0, function* () { if (yield rateLimitExceeded()) { throw new Error('Failed to stay within GitHub API rate limit'); } const releaseUrl = 'https://api.github.com/repos/Microsoft/vscode-cpptools/releases'; const header = { 'User-Agent': 'vscode-cpptools' }; try { const data = yield util.downloadFileToStr(releaseUrl, header); if (!data) { return undefined; } let releaseJson; try { releaseJson = JSON.parse(data); } catch (error) { throw new Error('Failed to parse release JSON'); } const builds = getArrayOfBuilds(releaseJson); if (!builds || builds.length === 0) { throw new Error('Release JSON is not of type Build[]'); } else { return builds; } } catch (err) { if (err && err.code && err.code !== "ENOENT") { throw new Error('Failed to download release JSON'); } } }); } /***/ }), /***/ 7065: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var InstallationType; (function (InstallationType) { InstallationType[InstallationType["Online"] = 0] = "Online"; InstallationType[InstallationType["Offline"] = 1] = "Offline"; })(InstallationType = exports.InstallationType || (exports.InstallationType = {})); class InstallationInformation { constructor() { this.hasError = false; this.telemetryProperties = {}; } } exports.InstallationInformation = InstallationInformation; let installBlob; function getInstallationInformation() { if (!installBlob) { installBlob = new InstallationInformation(); } return installBlob; } exports.getInstallationInformation = getInstallationInformation; function setInstallationStage(stage) { getInstallationInformation().stage = stage; } exports.setInstallationStage = setInstallationStage; function setInstallationType(type) { getInstallationInformation().type = type; } exports.setInstallationType = setInstallationType; /***/ }), /***/ 6547: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fs = __webpack_require__(5747); const os = __webpack_require__(2087); class LinuxDistribution { constructor(name, version) { this.name = name; this.version = version; } static GetDistroInformation() { const linuxDistro = LinuxDistribution.getDistroInformationFromFile('/etc/os-release') .catch(() => LinuxDistribution.getDistroInformationFromFile('/usr/lib/os-release')) .catch(() => Promise.resolve(new LinuxDistribution('unknown', 'unknown'))); return linuxDistro; } static getDistroInformationFromFile(path) { return new Promise((resolve, reject) => { fs.readFile(path, 'utf8', (error, data) => { if (error) { reject(error); return; } resolve(LinuxDistribution.getDistroInformation(data)); }); }); } static getDistroInformation(data) { const idKey = 'ID'; const versionKey = 'VERSION_ID'; let distroName = 'unknown'; let distroVersion = 'unknown'; const keyValues = data.split(os.EOL); for (let i = 0; i < keyValues.length; i++) { const keyValue = keyValues[i].split('='); if (keyValue.length === 2) { if (keyValue[0] === idKey) { distroName = keyValue[1]; } else if (keyValue[0] === versionKey) { distroVersion = keyValue[1]; } } } return new LinuxDistribution(distroName, distroVersion); } } exports.LinuxDistribution = LinuxDistribution; /***/ }), /***/ 5610: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); const os = __webpack_require__(2087); let Subscriber; function subscribeToAllLoggers(subscriber) { Subscriber = subscriber; } exports.subscribeToAllLoggers = subscribeToAllLoggers; class Logger { constructor(writer) { this.writer = writer; } append(message) { this.writer(message); if (Subscriber) { Subscriber(message); } } appendLine(message) { this.writer(message + os.EOL); if (Subscriber) { Subscriber(message + os.EOL); } } showInformationMessage(message, items) { this.appendLine(message); if (!items) { return vscode.window.showInformationMessage(message); } return vscode.window.showInformationMessage(message, ...items); } showWarningMessage(message, items) { this.appendLine(message); if (!items) { return vscode.window.showWarningMessage(message); } return vscode.window.showWarningMessage(message, ...items); } showErrorMessage(message, items) { this.appendLine(message); if (!items) { return vscode.window.showErrorMessage(message); } return vscode.window.showErrorMessage(message, ...items); } } exports.Logger = Logger; let outputChannel; function getOutputChannel() { if (!outputChannel) { outputChannel = vscode.window.createOutputChannel("C/C++"); } return outputChannel; } exports.getOutputChannel = getOutputChannel; function showOutputChannel() { getOutputChannel().show(); } exports.showOutputChannel = showOutputChannel; let outputChannelLogger; function getOutputChannelLogger() { if (!outputChannelLogger) { outputChannelLogger = new Logger(message => getOutputChannel().append(message)); } return outputChannelLogger; } exports.getOutputChannelLogger = getOutputChannelLogger; /***/ }), /***/ 7114: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const DebuggerExtension = __webpack_require__(2763); const fs = __webpack_require__(5747); const LanguageServer = __webpack_require__(2973); const os = __webpack_require__(2087); const path = __webpack_require__(5622); const Telemetry = __webpack_require__(1818); const util = __webpack_require__(5331); const vscode = __webpack_require__(7549); const nls = __webpack_require__(3612); const persistentState_1 = __webpack_require__(1102); const commands_1 = __webpack_require__(4960); const platform_1 = __webpack_require__(3383); const packageManager_1 = __webpack_require__(4426); const installationInformation_1 = __webpack_require__(7065); const logger_1 = __webpack_require__(5610); const cppTools1_1 = __webpack_require__(8674); const settings_1 = __webpack_require__(296); const githubAPI_1 = __webpack_require__(3158); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\main.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\main.ts')); const cppTools = new cppTools1_1.CppTools1(); let languageServiceDisabled = false; let reloadMessageShown = false; const disposables = []; function activate(context) { return __awaiter(this, void 0, void 0, function* () { yield util.checkCuda(); let errMsg = ""; const arch = platform_1.PlatformInformation.GetArchitecture(); if (arch !== 'x64' && (process.platform !== 'win32' || (arch !== 'x86' && arch !== 'arm64')) && (process.platform !== 'linux' || (arch !== 'x64' && arch !== 'arm' && arch !== 'arm64')) && (process.platform !== 'darwin' || arch !== 'arm64')) { errMsg = localize(0, null, String(arch)); } else if (process.platform === 'linux' && (yield util.checkDirectoryExists('/etc/alpine-release'))) { errMsg = localize(1, null); } if (errMsg) { vscode.window.showErrorMessage(errMsg); return new cppTools1_1.NullCppTools(); } util.setExtensionContext(context); commands_1.initializeTemporaryCommandRegistrar(); Telemetry.activate(); util.setProgress(0); class SchemaProvider { provideTextDocumentContent(uri) { return __awaiter(this, void 0, void 0, function* () { console.assert(uri.path[0] === '/', "A preceeding slash is expected on schema uri path"); const fileName = uri.path.substr(1); const locale = util.getLocaleId(); let localizedFilePath = util.getExtensionFilePath(path.join("dist/schema/", locale, fileName)); const fileExists = yield util.checkFileExists(localizedFilePath); if (!fileExists) { localizedFilePath = util.getExtensionFilePath(fileName); } return util.readFileText(localizedFilePath); }); } } vscode.workspace.registerTextDocumentContentProvider('cpptools-schema', new SchemaProvider()); DebuggerExtension.initialize(context); yield processRuntimeDependencies(); const fileContents = yield util.readFileText(util.getInstallLockPath()); let installedPlatformAndArchitecture = { platform: process.platform, architecture: arch }; if (fileContents.length !== 0) { try { installedPlatformAndArchitecture = JSON.parse(fileContents); } catch (error) { } } if (process.platform !== installedPlatformAndArchitecture.platform || (arch !== installedPlatformAndArchitecture.architecture && !(process.platform === "win32" && ((arch === "x64" && installedPlatformAndArchitecture.architecture === "x86") || (arch === "arm64" && ((installedPlatformAndArchitecture.architecture === "x86") || (installedPlatformAndArchitecture.architecture === "x64"))))) && !(process.platform === "darwin" && arch === "arm64" && installedPlatformAndArchitecture.architecture === "x64"))) { const platformInfo = yield platform_1.PlatformInformation.GetPlatformInformation(); const vsixName = githubAPI_1.vsixNameForPlatform(platformInfo); const downloadLink = localize(2, null); errMsg = localize(3, null, platform_1.GetOSName(installedPlatformAndArchitecture.platform), installedPlatformAndArchitecture.architecture, vsixName); vscode.window.showErrorMessage(errMsg, downloadLink).then((selection) => __awaiter(this, void 0, void 0, function* () { if (selection === downloadLink) { vscode.env.openExternal(vscode.Uri.parse(githubAPI_1.releaseDownloadUrl)); } })); } else if (!(yield util.checkInstallBinariesExist())) { errMsg = localize(4, null); const reload = localize(5, null); vscode.window.showErrorMessage(errMsg, reload).then((value) => __awaiter(this, void 0, void 0, function* () { if (value === reload) { yield util.removeInstallLockFile(); vscode.commands.executeCommand("workbench.action.reloadWindow"); } })); } else if (!(yield util.checkInstallJsonsExist())) { errMsg = localize(6, null); const downloadLink = localize(7, null); vscode.window.showErrorMessage(errMsg, downloadLink).then((selection) => __awaiter(this, void 0, void 0, function* () { if (selection === downloadLink) { vscode.env.openExternal(vscode.Uri.parse(githubAPI_1.releaseDownloadUrl)); } })); } return cppTools; }); } exports.activate = activate; function deactivate() { DebuggerExtension.dispose(); Telemetry.deactivate(); disposables.forEach(d => d.dispose()); if (languageServiceDisabled) { return Promise.resolve(); } return LanguageServer.deactivate(); } exports.deactivate = deactivate; function processRuntimeDependencies() { return __awaiter(this, void 0, void 0, function* () { const installLockExists = yield util.checkInstallLockFile(); installationInformation_1.setInstallationStage('getPlatformInfo'); const info = yield platform_1.PlatformInformation.GetPlatformInformation(); let forceOnlineInstall = false; if (info.platform === "darwin" && info.version) { const darwinVersion = new persistentState_1.PersistentState("Cpp.darwinVersion", info.version); if (darwinVersion.Value !== info.version) { const highSierraOrLowerRegex = new RegExp('10\\.(1[0-3]|[0-9])(\\..*)*$'); const lldbMiFolderPath = util.getExtensionFilePath('./debugAdapters/lldb-mi'); if (!highSierraOrLowerRegex.test(info.version) && !(yield util.checkDirectoryExists(lldbMiFolderPath))) { forceOnlineInstall = true; installationInformation_1.setInstallationStage('cleanUpUnusedBinaries'); yield cleanUpUnusedBinaries(info); } } } const doOfflineInstall = installLockExists && !forceOnlineInstall; if (doOfflineInstall) { if (util.packageJson.activationEvents && util.packageJson.activationEvents.length === 1) { try { yield offlineInstallation(info); } catch (error) { logger_1.getOutputChannelLogger().showErrorMessage(localize(8, null)); logger_1.showOutputChannel(); sendTelemetry(info); } } else { yield finalizeExtensionActivation(); } } else { try { yield onlineInstallation(info); } catch (error) { handleError(error); sendTelemetry(info); } } }); } function offlineInstallation(info) { return __awaiter(this, void 0, void 0, function* () { installationInformation_1.setInstallationType(installationInformation_1.InstallationType.Offline); installationInformation_1.setInstallationStage('cleanUpUnusedBinaries'); yield cleanUpUnusedBinaries(info); installationInformation_1.setInstallationStage('makeBinariesExecutable'); yield makeBinariesExecutable(); installationInformation_1.setInstallationStage('makeOfflineBinariesExecutable'); yield makeOfflineBinariesExecutable(info); installationInformation_1.setInstallationStage('removeUnnecessaryFile'); yield removeUnnecessaryFile(); installationInformation_1.setInstallationStage('rewriteManifest'); yield rewriteManifest(); installationInformation_1.setInstallationStage('postInstall'); yield postInstall(info); }); } function onlineInstallation(info) { return __awaiter(this, void 0, void 0, function* () { installationInformation_1.setInstallationType(installationInformation_1.InstallationType.Online); yield downloadAndInstallPackages(info); installationInformation_1.setInstallationStage('makeBinariesExecutable'); yield makeBinariesExecutable(); installationInformation_1.setInstallationStage('removeUnnecessaryFile'); yield removeUnnecessaryFile(); installationInformation_1.setInstallationStage('rewriteManifest'); yield rewriteManifest(); installationInformation_1.setInstallationStage('touchInstallLockFile'); yield touchInstallLockFile(info); installationInformation_1.setInstallationStage('postInstall'); yield postInstall(info); }); } function downloadAndInstallPackages(info) { return __awaiter(this, void 0, void 0, function* () { const outputChannelLogger = logger_1.getOutputChannelLogger(); outputChannelLogger.appendLine(localize(9, null)); const packageManager = new packageManager_1.PackageManager(info, outputChannelLogger); return vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, cancellable: false }, (progress, token) => __awaiter(this, void 0, void 0, function* () { progress.report({ message: "C/C++ Extension", increment: 0 }); outputChannelLogger.appendLine(''); installationInformation_1.setInstallationStage('downloadPackages'); yield packageManager.DownloadPackages(progress); outputChannelLogger.appendLine(''); installationInformation_1.setInstallationStage('installPackages'); yield packageManager.InstallPackages(progress); })); }); } function makeBinariesExecutable() { return util.allowExecution(util.getDebugAdaptersPath("OpenDebugAD7")); } function packageMatchesPlatform(pkg, info) { return packageManager_1.PlatformsMatch(pkg, info) && (pkg.architectures === undefined || packageManager_1.ArchitecturesMatch(pkg, info)) && packageManager_1.VersionsMatch(pkg, info); } function invalidPackageVersion(pkg, info) { return packageManager_1.PlatformsMatch(pkg, info) && (pkg.architectures === undefined || packageManager_1.ArchitecturesMatch(pkg, info)) && !packageManager_1.VersionsMatch(pkg, info); } function makeOfflineBinariesExecutable(info) { return __awaiter(this, void 0, void 0, function* () { const promises = []; const packages = util.packageJson["runtimeDependencies"]; packages.forEach(p => { if (p.binaries && p.binaries.length > 0 && packageMatchesPlatform(p, info)) { p.binaries.forEach(binary => promises.push(util.allowExecution(util.getExtensionFilePath(binary)))); } }); yield Promise.all(promises); }); } function cleanUpUnusedBinaries(info) { return __awaiter(this, void 0, void 0, function* () { const promises = []; const packages = util.packageJson["runtimeDependencies"]; const logger = logger_1.getOutputChannelLogger(); packages.forEach(p => { if (p.binaries && p.binaries.length > 0 && invalidPackageVersion(p, info)) { p.binaries.forEach(binary => { const path = util.getExtensionFilePath(binary); if (fs.existsSync(path)) { logger.appendLine(`deleting: ${path}`); promises.push(util.deleteFile(path)); } }); } }); yield Promise.all(promises); }); } function removeUnnecessaryFile() { if (os.platform() !== 'win32') { const sourcePath = util.getDebugAdaptersPath("bin/OpenDebugAD7.exe.config"); if (fs.existsSync(sourcePath)) { fs.rename(sourcePath, util.getDebugAdaptersPath("bin/OpenDebugAD7.exe.config.unused"), (err) => { if (err) { logger_1.getOutputChannelLogger().appendLine(localize(10, null, err.message, sourcePath)); } }); } } return Promise.resolve(); } function touchInstallLockFile(info) { return util.touchInstallLockFile(info); } function handleError(error) { var _a; const installationInformation = installationInformation_1.getInstallationInformation(); installationInformation.hasError = true; installationInformation.telemetryProperties['stage'] = (_a = installationInformation.stage, (_a !== null && _a !== void 0 ? _a : "")); let errorMessage; if (error instanceof packageManager_1.PackageManagerError) { const packageError = error; installationInformation.telemetryProperties['error.methodName'] = packageError.methodName; installationInformation.telemetryProperties['error.message'] = packageError.message; if (packageError.innerError) { errorMessage = packageError.innerError.toString(); installationInformation.telemetryProperties['error.innerError'] = util.removePotentialPII(errorMessage); } else { errorMessage = packageError.localizedMessageText; } if (packageError.pkg) { installationInformation.telemetryProperties['error.packageName'] = packageError.pkg.description; installationInformation.telemetryProperties['error.packageUrl'] = packageError.pkg.url; } if (packageError.errorCode) { installationInformation.telemetryProperties['error.errorCode'] = util.removePotentialPII(packageError.errorCode); } } else { errorMessage = error.toString(); installationInformation.telemetryProperties['error.toString'] = util.removePotentialPII(errorMessage); } const outputChannelLogger = logger_1.getOutputChannelLogger(); if (installationInformation.stage === 'downloadPackages') { outputChannelLogger.appendLine(""); } outputChannelLogger.appendLine(localize(11, null, installationInformation.stage)); outputChannelLogger.appendLine(errorMessage); outputChannelLogger.appendLine(""); outputChannelLogger.appendLine(localize(12, null, githubAPI_1.releaseDownloadUrl)); logger_1.showOutputChannel(); } function sendTelemetry(info) { const installBlob = installationInformation_1.getInstallationInformation(); const success = !installBlob.hasError; installBlob.telemetryProperties['success'] = success.toString(); installBlob.telemetryProperties['type'] = installBlob.type === installationInformation_1.InstallationType.Online ? "online" : "offline"; if (info.distribution) { installBlob.telemetryProperties['linuxDistroName'] = info.distribution.name; installBlob.telemetryProperties['linuxDistroVersion'] = info.distribution.version; } if (success) { util.setProgress(util.getProgressInstallSuccess()); } installBlob.telemetryProperties['osArchitecture'] = os.arch(); installBlob.telemetryProperties['infoArchitecture'] = info.architecture; Telemetry.logDebuggerEvent("acquisition", installBlob.telemetryProperties); return success; } function postInstall(info) { return __awaiter(this, void 0, void 0, function* () { const outputChannelLogger = logger_1.getOutputChannelLogger(); outputChannelLogger.appendLine(""); outputChannelLogger.appendLine(localize(13, null)); outputChannelLogger.appendLine(""); const installSuccess = sendTelemetry(info); if (!installSuccess) { throw new Error(localize(14, null)); } else { util.checkDistro(info); return finalizeExtensionActivation(); } }); } function finalizeExtensionActivation() { return __awaiter(this, void 0, void 0, function* () { const settings = new settings_1.CppSettings(); if (settings.intelliSenseEngine === "Disabled") { languageServiceDisabled = true; commands_1.getTemporaryCommandRegistrarInstance().disableLanguageServer(); disposables.push(vscode.workspace.onDidChangeConfiguration(() => { if (!reloadMessageShown && settings.intelliSenseEngine !== "Disabled") { reloadMessageShown = true; util.promptForReloadWindowDueToSettingsChange(); } })); return; } disposables.push(vscode.workspace.onDidChangeConfiguration(() => { if (!reloadMessageShown && settings.intelliSenseEngine === "Disabled") { reloadMessageShown = true; util.promptForReloadWindowDueToSettingsChange(); } })); commands_1.getTemporaryCommandRegistrarInstance().activateLanguageServer(); const packageJson = util.getRawPackageJson(); let writePackageJson = false; const packageJsonPath = util.getExtensionFilePath("package.json"); if (packageJsonPath.includes(".vscode-insiders") || packageJsonPath.includes(".vscode-exploration")) { if (packageJson.contributes.configuration.properties['C_Cpp.updateChannel'].default === 'Default') { packageJson.contributes.configuration.properties['C_Cpp.updateChannel'].default = 'Insiders'; writePackageJson = true; } } if (writePackageJson) { return util.writeFileText(util.getPackageJsonPath(), util.stringifyPackageJson(packageJson)); } }); } function rewriteManifest() { const packageJson = util.getRawPackageJson(); packageJson.activationEvents = [ "onLanguage:c", "onLanguage:cpp", "onLanguage:cuda-cpp", "onCommand:extension.pickNativeProcess", "onCommand:extension.pickRemoteNativeProcess", "onCommand:C_Cpp.BuildAndDebugActiveFile", "onCommand:C_Cpp.ConfigurationEditJSON", "onCommand:C_Cpp.ConfigurationEditUI", "onCommand:C_Cpp.ConfigurationSelect", "onCommand:C_Cpp.ConfigurationProviderSelect", "onCommand:C_Cpp.SwitchHeaderSource", "onCommand:C_Cpp.EnableErrorSquiggles", "onCommand:C_Cpp.DisableErrorSquiggles", "onCommand:C_Cpp.ToggleIncludeFallback", "onCommand:C_Cpp.ToggleDimInactiveRegions", "onCommand:C_Cpp.ResetDatabase", "onCommand:C_Cpp.TakeSurvey", "onCommand:C_Cpp.LogDiagnostics", "onCommand:C_Cpp.RescanWorkspace", "onCommand:C_Cpp.VcpkgClipboardInstallSuggested", "onCommand:C_Cpp.VcpkgOnlineHelpSuggested", "onCommand:C_Cpp.GenerateEditorConfig", "onCommand:C_Cpp.GoToNextDirectiveInGroup", "onCommand:C_Cpp.GoToPrevDirectiveInGroup", "onCommand:C_Cpp.CheckForCompiler", "onDebugInitialConfigurations", "onDebugResolve:cppdbg", "onDebugResolve:cppvsdbg", "workspaceContains:/.vscode/c_cpp_properties.json", "onFileSystem:cpptools-schema" ]; return util.writeFileText(util.getPackageJsonPath(), util.stringifyPackageJson(packageJson)); } /***/ }), /***/ 5391: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const nls = __webpack_require__(3612); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\nativeStrings.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\nativeStrings.ts')); exports.localizedStringCount = 211; function lookupString(stringId, stringArgs) { let message = ""; switch (stringId) { case 0: break; case 1: message = localize(0, null); break; case 2: message = localize(1, null); break; case 3: message = localize(2, null); break; case 4: if (stringArgs) { message = localize(3, null, stringArgs[0]); break; } message = localize(4, null); break; case 5: message = localize(5, null); break; case 6: message = localize(6, null); break; case 7: message = localize(7, null); break; case 8: if (stringArgs) { message = localize(8, null, stringArgs[0]); break; } message = localize(9, null); break; case 9: if (stringArgs) { message = localize(10, null, stringArgs[0]); break; } message = localize(11, null); break; case 10: if (stringArgs) { message = localize(12, null, stringArgs[0]); break; } message = localize(13, null); break; case 11: if (stringArgs) { message = localize(14, null, stringArgs[0], stringArgs[1]); break; } message = localize(15, null); break; case 12: if (stringArgs) { message = localize(16, null, stringArgs[0], stringArgs[1]); break; } message = localize(17, null); break; case 13: if (stringArgs) { message = localize(18, null, stringArgs[0], stringArgs[1], stringArgs[2]); break; } message = localize(19, null); break; case 14: message = localize(20, null); break; case 15: if (stringArgs) { message = localize(21, null, stringArgs[0]); break; } message = localize(22, null); break; case 16: if (stringArgs) { message = localize(23, null, stringArgs[0]); break; } message = localize(24, null); break; case 17: if (stringArgs) { message = localize(25, null, stringArgs[0]); break; } message = localize(26, null); break; case 18: if (stringArgs) { message = localize(27, null, stringArgs[0]); break; } message = localize(28, null); break; case 19: if (stringArgs) { message = localize(29, null, stringArgs[0], stringArgs[1]); break; } message = localize(30, null); break; case 20: if (stringArgs) { message = localize(31, null, stringArgs[0]); break; } message = localize(32, null); break; case 21: if (stringArgs) { message = localize(33, null, stringArgs[0]); break; } message = localize(34, null); break; case 22: if (stringArgs) { message = localize(35, null, stringArgs[0]); break; } message = localize(36, null); break; case 23: if (stringArgs) { message = localize(37, null, stringArgs[0]); break; } message = localize(38, null); break; case 24: if (stringArgs) { message = localize(39, null, stringArgs[0]); break; } message = localize(40, null); break; case 25: message = localize(41, null); break; case 26: if (stringArgs) { message = localize(42, null, stringArgs[0]); break; } message = localize(43, null); break; case 27: if (stringArgs) { message = localize(44, null, stringArgs[0]); break; } message = localize(45, null); break; case 28: if (stringArgs) { message = localize(46, null, stringArgs[0]); break; } message = localize(47, null); break; case 29: message = localize(48, null); break; case 30: if (stringArgs) { message = localize(49, null, stringArgs[0], stringArgs[1]); break; } message = localize(50, null); break; case 31: if (stringArgs) { message = localize(51, null, stringArgs[0], stringArgs[1]); break; } message = localize(52, null); break; case 32: if (stringArgs) { message = localize(53, null, stringArgs[0], stringArgs[1]); break; } message = localize(54, null); break; case 33: if (stringArgs) { message = localize(55, null, stringArgs[0], stringArgs[1]); break; } message = localize(56, null); break; case 34: if (stringArgs) { message = localize(57, null, stringArgs[0], stringArgs[1]); break; } message = localize(58, null); break; case 35: if (stringArgs) { message = localize(59, null, stringArgs[0], stringArgs[1]); break; } message = localize(60, null); break; case 36: if (stringArgs) { message = localize(61, null, stringArgs[0]); break; } message = localize(62, null); break; case 37: message = localize(63, null); break; case 38: if (stringArgs) { message = localize(64, null, stringArgs[0]); break; } message = localize(65, null); break; case 39: message = localize(66, null); break; case 40: if (stringArgs) { message = localize(67, null, stringArgs[0]); break; } message = localize(68, null); break; case 41: if (stringArgs) { message = localize(69, null, stringArgs[0], stringArgs[1]); break; } message = localize(70, null); break; case 42: message = localize(71, null); break; case 43: if (stringArgs) { message = localize(72, null, stringArgs[0]); break; } message = localize(73, null); break; case 44: message = localize(74, null); break; case 45: if (stringArgs) { message = localize(75, null, stringArgs[0]); break; } message = localize(76, null); break; case 46: if (stringArgs) { message = localize(77, null, stringArgs[0]); break; } message = localize(78, null); break; case 47: if (stringArgs) { message = localize(79, null, stringArgs[0]); break; } message = localize(80, null); break; case 48: if (stringArgs) { message = localize(81, null, stringArgs[0]); break; } message = localize(82, null); break; case 49: if (stringArgs) { message = localize(83, null, stringArgs[0]); break; } message = localize(84, null); break; case 50: if (stringArgs) { message = localize(85, null, stringArgs[0]); break; } message = localize(86, null); break; case 51: if (stringArgs) { message = localize(87, null, stringArgs[0]); break; } message = localize(88, null); break; case 52: if (stringArgs) { message = localize(89, null, stringArgs[0]); break; } message = localize(90, null); break; case 53: if (stringArgs) { message = localize(91, null, stringArgs[0]); break; } message = localize(92, null); break; case 54: if (stringArgs) { message = localize(93, null, stringArgs[0]); break; } message = localize(94, null); break; case 55: if (stringArgs) { message = localize(95, null, stringArgs[0]); break; } message = localize(96, null); break; case 56: message = localize(97, null); break; case 57: if (stringArgs) { message = localize(98, null, stringArgs[0]); break; } message = localize(99, null); break; case 58: message = localize(100, null); break; case 59: message = localize(101, null); break; case 60: message = localize(102, null); break; case 61: message = localize(103, null); break; case 62: message = localize(104, null); break; case 63: message = localize(105, null); break; case 64: message = localize(106, null); break; case 65: if (stringArgs) { message = localize(107, null, stringArgs[0]); break; } message = localize(108, null); break; case 66: if (stringArgs) { message = localize(109, null, stringArgs[0]); break; } message = localize(110, null); break; case 67: if (stringArgs) { message = localize(111, null, stringArgs[0]); break; } message = localize(112, null); break; case 68: if (stringArgs) { message = localize(113, null, stringArgs[0]); break; } message = localize(114, null); break; case 69: message = localize(115, null); break; case 70: message = localize(116, null); break; case 71: message = localize(117, null); break; case 72: message = localize(118, null); break; case 73: message = localize(119, null); break; case 74: message = localize(120, null); break; case 75: message = localize(121, null); break; case 76: message = localize(122, null); break; case 77: if (stringArgs) { message = localize(123, null, stringArgs[0]); break; } message = localize(124, null); break; case 78: if (stringArgs) { message = localize(125, null, stringArgs[0]); break; } message = localize(126, null); break; case 79: if (stringArgs) { message = localize(127, null, stringArgs[0]); break; } message = localize(128, null); break; case 80: if (stringArgs) { message = localize(129, null, stringArgs[0]); break; } message = localize(130, null); break; case 81: if (stringArgs) { message = localize(131, null, stringArgs[0], stringArgs[1], stringArgs[2]); break; } message = localize(132, null); break; case 82: if (stringArgs) { message = localize(133, null, stringArgs[0]); break; } message = localize(134, null); break; case 83: message = localize(135, null); break; case 84: message = localize(136, null); break; case 85: if (stringArgs) { message = localize(137, null, stringArgs[0]); break; } message = localize(138, null); break; case 86: if (stringArgs) { message = localize(139, null, stringArgs[0], stringArgs[1]); break; } message = localize(140, null); break; case 87: message = localize(141, null); break; case 88: if (stringArgs) { message = localize(142, null, stringArgs[0]); break; } message = localize(143, null); break; case 89: if (stringArgs) { message = localize(144, null, stringArgs[0]); break; } message = localize(145, null); break; case 90: if (stringArgs) { message = localize(146, null, stringArgs[0]); break; } message = localize(147, null); break; case 91: message = localize(148, null); break; case 92: message = localize(149, null); break; case 93: message = localize(150, null); break; case 94: if (stringArgs) { message = localize(151, null, stringArgs[0]); break; } message = localize(152, null); break; case 95: if (stringArgs) { message = localize(153, null, stringArgs[0]); break; } message = localize(154, null); break; case 96: if (stringArgs) { message = localize(155, null, stringArgs[0]); break; } message = localize(156, null); break; case 97: if (stringArgs) { message = localize(157, null, stringArgs[0]); break; } message = localize(158, null); break; case 98: if (stringArgs) { message = localize(159, null, stringArgs[0]); break; } message = localize(160, null); break; case 99: if (stringArgs) { message = localize(161, null, stringArgs[0]); break; } message = localize(162, null); break; case 100: if (stringArgs) { message = localize(163, null, stringArgs[0]); break; } message = localize(164, null); break; case 101: if (stringArgs) { message = localize(165, null, stringArgs[0]); break; } message = localize(166, null); break; case 102: message = localize(167, null); break; case 103: message = localize(168, null); break; case 104: if (stringArgs) { message = localize(169, null, stringArgs[0]); break; } message = localize(170, null); break; case 105: message = localize(171, null); break; case 106: message = localize(172, null); break; case 107: if (stringArgs) { message = localize(173, null, stringArgs[0]); break; } message = localize(174, null); break; case 108: if (stringArgs) { message = localize(175, null, stringArgs[0]); break; } message = localize(176, null); break; case 109: if (stringArgs) { message = localize(177, null, stringArgs[0]); break; } message = localize(178, null); break; case 110: message = localize(179, null); break; case 111: message = localize(180, null); break; case 112: message = localize(181, null); break; case 113: message = localize(182, null); break; case 114: message = localize(183, null); break; case 115: message = localize(184, null); break; case 116: if (stringArgs) { message = localize(185, null, stringArgs[0]); break; } message = localize(186, null); break; case 117: if (stringArgs) { message = localize(187, null, stringArgs[0]); break; } message = localize(188, null); break; case 118: if (stringArgs) { message = localize(189, null, stringArgs[0]); break; } message = localize(190, null); break; case 119: message = localize(191, null); break; case 120: message = localize(192, null); break; case 121: if (stringArgs) { message = localize(193, null, stringArgs[0]); break; } message = localize(194, null); break; case 122: message = localize(195, null); break; case 123: message = localize(196, null); break; case 124: message = localize(197, null); break; case 125: if (stringArgs) { message = localize(198, null, stringArgs[0]); break; } message = localize(199, null); break; case 126: if (stringArgs) { message = localize(200, null, stringArgs[0], stringArgs[1], stringArgs[2]); break; } message = localize(201, null); break; case 127: if (stringArgs) { message = localize(202, null, stringArgs[0], stringArgs[1], stringArgs[2]); break; } message = localize(203, null); break; case 128: message = localize(204, null); break; case 129: if (stringArgs) { message = localize(205, null, stringArgs[0]); break; } message = localize(206, null); break; case 130: message = localize(207, null); break; case 131: if (stringArgs) { message = localize(208, null, stringArgs[0]); break; } message = localize(209, null); break; case 132: if (stringArgs) { message = localize(210, null, stringArgs[0]); break; } message = localize(211, null); break; case 133: if (stringArgs) { message = localize(212, null, stringArgs[0]); break; } message = localize(213, null); break; case 134: if (stringArgs) { message = localize(214, null, stringArgs[0]); break; } message = localize(215, null); break; case 135: if (stringArgs) { message = localize(216, null, stringArgs[0]); break; } message = localize(217, null); break; case 136: if (stringArgs) { message = localize(218, null, stringArgs[0]); break; } message = localize(219, null); break; case 137: message = localize(220, null); break; case 138: message = localize(221, null); break; case 139: message = localize(222, null); break; case 140: message = localize(223, null); break; case 141: if (stringArgs) { message = localize(224, null, stringArgs[0]); break; } message = localize(225, null); break; case 142: if (stringArgs) { message = localize(226, null, stringArgs[0]); break; } message = localize(227, null); break; case 143: if (stringArgs) { message = localize(228, null, stringArgs[0]); break; } message = localize(229, null); break; case 144: message = localize(230, null); break; case 145: if (stringArgs) { message = localize(231, null, stringArgs[0]); break; } message = localize(232, null); break; case 146: if (stringArgs) { message = localize(233, null, stringArgs[0]); break; } message = localize(234, null); break; case 147: message = localize(235, null); break; case 148: message = localize(236, null); break; case 149: message = localize(237, null); break; case 150: message = localize(238, null); break; case 151: message = localize(239, null); break; case 152: message = localize(240, null); break; case 153: message = localize(241, null); break; case 154: if (stringArgs) { message = localize(242, null, stringArgs[0]); break; } message = localize(243, null); break; case 155: if (stringArgs) { message = localize(244, null, stringArgs[0]); break; } message = localize(245, null); break; case 156: if (stringArgs) { message = localize(246, null, stringArgs[0]); break; } message = localize(247, null); break; case 157: message = localize(248, null); break; case 158: message = localize(249, null); break; case 159: message = localize(250, null); break; case 160: message = localize(251, null); break; case 161: message = localize(252, null); break; case 162: message = localize(253, null); break; case 163: message = localize(254, null); break; case 164: message = localize(255, null); break; case 165: message = localize(256, null); break; case 166: message = localize(257, null); break; case 167: message = localize(258, null); break; case 168: message = localize(259, null); break; case 169: message = localize(260, null); break; case 170: message = localize(261, null); break; case 171: if (stringArgs) { message = localize(262, null, stringArgs[0]); break; } message = localize(263, null); break; case 172: if (stringArgs) { message = localize(264, null, stringArgs[0]); break; } message = localize(265, null); break; case 173: if (stringArgs) { message = localize(266, null, stringArgs[0]); break; } message = localize(267, null); break; case 174: if (stringArgs) { message = localize(268, null, stringArgs[0]); break; } message = localize(269, null); break; case 175: if (stringArgs) { message = localize(270, null, stringArgs[0]); break; } message = localize(271, null); break; case 176: if (stringArgs) { message = localize(272, null, stringArgs[0], stringArgs[1]); break; } message = localize(273, null); break; case 177: if (stringArgs) { message = localize(274, null, stringArgs[0], stringArgs[1]); break; } message = localize(275, null); break; case 178: if (stringArgs) { message = localize(276, null, stringArgs[0], stringArgs[1]); break; } message = localize(277, null); break; case 179: if (stringArgs) { message = localize(278, null, stringArgs[0], stringArgs[1]); break; } message = localize(279, null); break; case 180: if (stringArgs) { message = localize(280, null, stringArgs[0], stringArgs[1], stringArgs[2], stringArgs[3]); break; } message = localize(281, null); break; case 181: if (stringArgs) { message = localize(282, null, stringArgs[0], stringArgs[1], stringArgs[2], stringArgs[3]); break; } message = localize(283, null); break; case 182: if (stringArgs) { message = localize(284, null, stringArgs[0], stringArgs[1], stringArgs[2]); break; } message = localize(285, null); break; case 183: if (stringArgs) { message = localize(286, null, stringArgs[0], stringArgs[1], stringArgs[2]); break; } message = localize(287, null); break; case 184: if (stringArgs) { message = localize(288, null, stringArgs[0], stringArgs[1], stringArgs[2]); break; } message = localize(289, null); break; case 185: if (stringArgs) { message = localize(290, null, stringArgs[0], stringArgs[1], stringArgs[2]); break; } message = localize(291, null); break; case 186: if (stringArgs) { message = localize(292, null, stringArgs[0], stringArgs[1], stringArgs[2], stringArgs[3], stringArgs[4]); break; } message = localize(293, null); break; case 187: if (stringArgs) { message = localize(294, null, stringArgs[0], stringArgs[1], stringArgs[2], stringArgs[3], stringArgs[4]); break; } message = localize(295, null); break; case 188: if (stringArgs) { message = localize(296, null, stringArgs[0], stringArgs[1]); break; } message = localize(297, null); break; case 189: if (stringArgs) { message = localize(298, null, stringArgs[0]); break; } message = localize(299, null); break; case 190: message = localize(300, null); break; case 191: message = localize(301, null); break; case 192: message = localize(302, null); break; case 193: if (stringArgs) { message = localize(303, null, stringArgs[0], stringArgs[1]); break; } message = localize(304, null); break; case 194: if (stringArgs) { message = localize(305, null, stringArgs[0]); break; } message = localize(306, null); break; case 195: if (stringArgs) { message = localize(307, null, stringArgs[0]); break; } message = localize(308, null); break; case 196: if (stringArgs) { message = localize(309, null, stringArgs[0]); break; } message = localize(310, null); break; case 197: if (stringArgs) { message = localize(311, null, stringArgs[0]); break; } message = localize(312, null); break; case 198: if (stringArgs) { message = localize(313, null, stringArgs[0]); break; } message = localize(314, null); break; case 199: if (stringArgs) { message = localize(315, null, stringArgs[0]); break; } message = localize(316, null); break; case 200: if (stringArgs) { message = localize(317, null, stringArgs[0], stringArgs[1], stringArgs[2]); break; } message = localize(318, null); break; case 201: if (stringArgs) { message = localize(319, null, stringArgs[0]); break; } message = localize(320, null); break; case 202: message = localize(321, null); break; case 203: message = localize(322, null); break; case 204: message = localize(323, null); break; case 205: if (stringArgs) { message = localize(324, null, stringArgs[0]); break; } message = localize(325, null); break; case 206: if (stringArgs) { message = localize(326, null, stringArgs[0]); break; } message = localize(327, null); break; case 207: if (stringArgs) { message = localize(328, null, stringArgs[0]); break; } message = localize(329, null); break; case 208: message = localize(330, null); break; case 209: if (stringArgs) { message = localize(331, null, stringArgs[0]); break; } message = localize(332, null); break; case 210: message = localize(333, null); break; default: console.assert("Unrecognized string ID"); break; } return message; } exports.lookupString = lookupString; /***/ }), /***/ 4426: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const fs = __webpack_require__(5747); const https = __webpack_require__(7211); const path = __webpack_require__(5622); const vscode = __webpack_require__(7549); const url = __webpack_require__(8835); const tmp = __webpack_require__(7010); const yauzl = __webpack_require__(8798); const mkdirp = __webpack_require__(596); const util = __webpack_require__(5331); const Telemetry = __webpack_require__(1818); const nls = __webpack_require__(3612); const crypto = __webpack_require__(6417); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\packageManager.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\packageManager.ts')); function isValidPackage(buffer, integrity) { if (integrity && integrity.length > 0) { const hash = crypto.createHash('sha256'); hash.update(buffer); const value = hash.digest('hex').toUpperCase(); return (value === integrity.toUpperCase()); } return false; } exports.isValidPackage = isValidPackage; class PackageManagerError extends Error { constructor(message, localizedMessage, methodName, pkg = null, innerError = null, errorCode = '') { super(message); this.message = message; this.localizedMessage = localizedMessage; this.methodName = methodName; this.pkg = pkg; this.innerError = innerError; this.errorCode = errorCode; this.localizedMessageText = localizedMessage; } } exports.PackageManagerError = PackageManagerError; class PackageManagerWebResponseError extends PackageManagerError { constructor(socket, message, localizedMessage, methodName, pkg = null, innerError = null, errorCode = '') { super(message, localizedMessage, methodName, pkg, innerError, errorCode); this.socket = socket; this.message = message; this.localizedMessage = localizedMessage; this.methodName = methodName; this.pkg = pkg; this.innerError = innerError; this.errorCode = errorCode; } } exports.PackageManagerWebResponseError = PackageManagerWebResponseError; class PackageManager { constructor(platformInfo, outputChannel) { this.platformInfo = platformInfo; this.outputChannel = outputChannel; tmp.setGracefulCleanup(); } DownloadPackages(progress) { return __awaiter(this, void 0, void 0, function* () { const packages = yield this.GetPackages(); let count = 1; return util.sequentialResolve(packages, (pkg) => __awaiter(this, void 0, void 0, function* () { progress.report({ message: localize(0, null, pkg.description), increment: this.GetIncrement(count, packages.length) }); count += 1; yield this.DownloadPackage(pkg); })); }); } InstallPackages(progress) { return __awaiter(this, void 0, void 0, function* () { const packages = yield this.GetPackages(); let count = 1; return util.sequentialResolve(packages, (pkg) => __awaiter(this, void 0, void 0, function* () { progress.report({ message: localize(1, null, pkg.description), increment: this.GetIncrement(count, packages.length) }); count += 1; yield this.InstallPackage(pkg); })); }); } GetIncrement(curStep, totalSteps) { const maxIncrement = 100 / 2; const increment = Math.floor(maxIncrement / totalSteps); return (curStep !== totalSteps) ? increment : maxIncrement - (totalSteps - 1) * increment; } GetPackages() { return __awaiter(this, void 0, void 0, function* () { const list = yield this.GetPackageList(); return list.filter((value, index, array) => ArchitecturesMatch(value, this.platformInfo) && PlatformsMatch(value, this.platformInfo) && VersionsMatch(value, this.platformInfo)); }); } GetPackageList() { return new Promise((resolve, reject) => { if (!this.allPackages) { if (util.packageJson.runtimeDependencies) { this.allPackages = util.packageJson.runtimeDependencies; for (const pkg of this.allPackages) { if (pkg.binaries) { pkg.binaries = pkg.binaries.map((value) => util.getExtensionFilePath(value)); } } resolve(this.allPackages); } else { reject(new PackageManagerError("Package manifest does not exist", localize(2, null), 'GetPackageList')); } } else { resolve(this.allPackages); } }); } DownloadPackage(pkg) { return __awaiter(this, void 0, void 0, function* () { this.AppendChannel(localize(3, null, pkg.description)); const tmpResult = yield this.CreateTempFile(pkg); yield this.DownloadPackageWithRetries(pkg, tmpResult); }); } CreateTempFile(pkg) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { tmp.file({ prefix: "package-" }, (err, path, fd, cleanupCallback) => { if (err) { return reject(new PackageManagerError("Error from temp.file", localize(4, null, "temp.file"), 'DownloadPackage', pkg, err)); } return resolve({ name: path, fd: fd, removeCallback: cleanupCallback }); }); }); }); } DownloadPackageWithRetries(pkg, tmpResult) { return __awaiter(this, void 0, void 0, function* () { pkg.tmpFile = tmpResult; let success = false; let lastError = null; let retryCount = 0; const MAX_RETRIES = 5; do { try { yield this.DownloadFile(pkg.url, pkg, retryCount); success = true; } catch (error) { retryCount += 1; lastError = error; if (retryCount >= MAX_RETRIES) { this.AppendChannel(" " + localize(5, null, pkg.url)); throw error; } else { this.AppendChannel(" " + localize(6, null)); continue; } } } while (!success && retryCount < MAX_RETRIES); this.AppendLineChannel(" " + localize(7, null)); if (retryCount !== 0) { const telemetryProperties = {}; telemetryProperties["success"] = success ? `OnRetry${retryCount}` : 'false'; if (lastError instanceof PackageManagerError) { const packageError = lastError; telemetryProperties['error.methodName'] = packageError.methodName; telemetryProperties['error.message'] = packageError.message; if (packageError.pkg) { telemetryProperties['error.packageName'] = packageError.pkg.description; telemetryProperties['error.packageUrl'] = packageError.pkg.url; } if (packageError.errorCode) { telemetryProperties['error.errorCode'] = packageError.errorCode; } } Telemetry.logDebuggerEvent("acquisition", telemetryProperties); } }); } DownloadFile(urlString, pkg, delay) { const parsedUrl = url.parse(urlString); const proxyStrictSSL = vscode.workspace.getConfiguration().get("http.proxyStrictSSL", true); const options = { host: parsedUrl.host, path: parsedUrl.path, agent: util.getHttpsProxyAgent(), rejectUnauthorized: proxyStrictSSL }; const buffers = []; return new Promise((resolve, reject) => { let secondsDelay = Math.pow(2, delay); if (secondsDelay === 1) { secondsDelay = 0; } if (secondsDelay > 4) { this.AppendChannel(localize(8, null, secondsDelay)); } setTimeout(() => { if (!pkg.tmpFile || pkg.tmpFile.fd === 0) { return reject(new PackageManagerError('Temporary Package file unavailable', localize(9, null), 'DownloadFile', pkg)); } const handleHttpResponse = (response) => { if (response.statusCode === 301 || response.statusCode === 302) { let redirectUrl; if (typeof response.headers.location === "string") { redirectUrl = response.headers.location; } else { if (!response.headers.location) { return reject(new PackageManagerError('Invalid download location received', localize(10, null), 'DownloadFile', pkg)); } redirectUrl = response.headers.location[0]; } return resolve(this.DownloadFile(redirectUrl, pkg, 0)); } else if (response.statusCode !== 200) { if (response.statusCode === undefined || response.statusCode === null) { return reject(new PackageManagerError('Invalid response code received', localize(11, null), 'DownloadFile', pkg)); } const errorMessage = localize(12, null, response.statusCode); return reject(new PackageManagerWebResponseError(response.socket, 'HTTP/HTTPS Response Error', localize(13, null), 'DownloadFile', pkg, errorMessage, response.statusCode.toString())); } else { let contentLength = response.headers['content-length']; if (typeof response.headers['content-length'] === "string") { contentLength = response.headers['content-length']; } else { if (response.headers['content-length'] === undefined || response.headers['content-length'] === null) { return reject(new PackageManagerError('Invalid content length location received', localize(14, null), 'DownloadFile', pkg)); } contentLength = response.headers['content-length'][0]; } const packageSize = parseInt(contentLength, 10); const downloadPercentage = 0; let dots = 0; const tmpFile = fs.createWriteStream("", { fd: pkg.tmpFile.fd }); this.AppendChannel(`(${Math.ceil(packageSize / 1024)} KB) `); response.on('data', (data) => { buffers.push(data); const newDots = Math.ceil(downloadPercentage / 5); if (newDots > dots) { this.AppendChannel(".".repeat(newDots - dots)); dots = newDots; } }); response.on('end', () => { const packageBuffer = Buffer.concat(buffers); if (isValidPackage(packageBuffer, pkg.integrity)) { resolve(); } else { reject(new PackageManagerError('Invalid content received. Hash is incorrect.', localize(15, null), 'DownloadFile', pkg)); } }); response.on('error', (error) => reject(new PackageManagerWebResponseError(response.socket, 'HTTP/HTTPS Response Error', localize(16, null), 'DownloadFile', pkg, error.stack, error.name))); response.pipe(tmpFile, { end: false }); } }; const request = https.request(options, handleHttpResponse); request.on('error', (error) => reject(new PackageManagerError('HTTP/HTTPS Request error' + (urlString.includes("fwlink") ? ": fwlink" : ""), localize(17, null) + (urlString.includes("fwlink") ? ": fwlink" : ""), 'DownloadFile', pkg, error.stack, error.message))); request.end(); }, secondsDelay * 1000); }); } InstallPackage(pkg) { this.AppendLineChannel(localize(18, null, pkg.description)); return new Promise((resolve, reject) => { if (!pkg.tmpFile || pkg.tmpFile.fd === 0) { return reject(new PackageManagerError('Downloaded file unavailable', localize(19, null), 'InstallPackage', pkg)); } yauzl.fromFd(pkg.tmpFile.fd, { lazyEntries: true, autoClose: true }, (err, zipfile) => { if (err || !zipfile) { return reject(new PackageManagerError('Zip file error', localize(20, null), 'InstallPackage', pkg, err)); } let pendingError; zipfile.on('close', () => { if (!pendingError) { resolve(); } else { reject(pendingError); } }); zipfile.on('error', err => { if (!pendingError) { pendingError = new PackageManagerError('Zip file error', localize(21, null), 'InstallPackage', pkg, err, err.code); zipfile.close(); } }); zipfile.on('entry', (entry) => { const absoluteEntryPath = util.getExtensionFilePath(entry.fileName); if (entry.fileName.endsWith("/")) { mkdirp(absoluteEntryPath, { mode: 0o775 }, (err) => { if (err) { pendingError = new PackageManagerError('Error creating directory', localize(22, null), 'InstallPackage', pkg, err, err.code); zipfile.close(); return; } zipfile.readEntry(); }); } else { util.checkFileExists(absoluteEntryPath).then((exists) => { if (!exists) { zipfile.openReadStream(entry, (err, readStream) => { if (err || !readStream) { pendingError = new PackageManagerError('Error reading zip stream', localize(23, null), 'InstallPackage', pkg, err); zipfile.close(); return; } mkdirp(path.dirname(absoluteEntryPath), { mode: 0o775 }, (err) => __awaiter(this, void 0, void 0, function* () { if (err) { pendingError = new PackageManagerError('Error creating directory', localize(24, null), 'InstallPackage', pkg, err, err.code); zipfile.close(); return; } const absoluteEntryTempFile = absoluteEntryPath + ".tmp"; if (yield util.checkFileExists(absoluteEntryTempFile)) { try { yield util.unlinkAsync(absoluteEntryTempFile); } catch (err) { pendingError = new PackageManagerError(`Error unlinking file ${absoluteEntryTempFile}`, localize(25, null, absoluteEntryTempFile), 'InstallPackage', pkg, err); zipfile.close(); return; } } const fileMode = (this.platformInfo.platform !== "win32" && pkg.binaries && pkg.binaries.indexOf(absoluteEntryPath) !== -1) ? 0o755 : 0o664; const writeStream = fs.createWriteStream(absoluteEntryTempFile, { mode: fileMode }); writeStream.on('close', () => __awaiter(this, void 0, void 0, function* () { if (!pendingError) { try { yield util.renameAsync(absoluteEntryTempFile, absoluteEntryPath); } catch (err) { pendingError = new PackageManagerError(`Error renaming file ${absoluteEntryTempFile}`, localize(26, null, absoluteEntryTempFile), 'InstallPackage', pkg, err); zipfile.close(); return; } zipfile.readEntry(); } else { try { yield util.unlinkAsync(absoluteEntryTempFile); } catch (err) { } } })); readStream.on('error', (err) => { if (!pendingError) { pendingError = new PackageManagerError('Error in readStream', localize(27, null), 'InstallPackage', pkg, err); zipfile.close(); } }); writeStream.on('error', (err) => { if (!pendingError) { pendingError = new PackageManagerError('Error in writeStream', localize(28, null), 'InstallPackage', pkg, err); zipfile.close(); } }); readStream.pipe(writeStream); })); }); } else { if (path.extname(absoluteEntryPath) !== ".txt") { this.AppendLineChannel(localize(29, null, absoluteEntryPath)); } zipfile.readEntry(); } }); } }); zipfile.readEntry(); }); }).then(() => { pkg.tmpFile.removeCallback(); }); } AppendChannel(text) { if (this.outputChannel) { this.outputChannel.append(text); } } AppendLineChannel(text) { if (this.outputChannel) { this.outputChannel.appendLine(text); } } } exports.PackageManager = PackageManager; function VersionsMatch(pkg, info) { if (pkg.versionRegex) { if (!info.version) { return !pkg.matchVersion; } const regex = new RegExp(pkg.versionRegex); return (pkg.matchVersion ? regex.test(info.version) : !regex.test(info.version)); } return true; } exports.VersionsMatch = VersionsMatch; function ArchitecturesMatch(value, info) { return !value.architectures || (value.architectures.indexOf(info.architecture) !== -1); } exports.ArchitecturesMatch = ArchitecturesMatch; function PlatformsMatch(value, info) { return !value.platforms || value.platforms.indexOf(info.platform) !== -1; } exports.PlatformsMatch = PlatformsMatch; /***/ }), /***/ 302: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class PackageVersion { constructor(version) { const tokens = version.split(new RegExp('[-\\.]', 'g')); if (tokens.length < 3) { throw new Error(`Failed to parse version string: ${version}`); } this.major = parseInt(tokens[0]); this.minor = parseInt(tokens[1]); this.patch = parseInt(tokens[2]); if (tokens.length > 3) { const firstDigitOffset = tokens[3].search(new RegExp(/(\d)/)); if (firstDigitOffset !== -1) { this.suffix = tokens[3].substring(0, firstDigitOffset); this.suffixVersion = parseInt(tokens[3].substring(firstDigitOffset)); } else { this.suffix = tokens[3]; this.suffixVersion = 1; } } else { this.suffix = undefined; this.suffixVersion = 0; } if (this.major === undefined || this.major === null || this.minor === undefined || this.minor === null || this.patch === undefined || this.patch === null) { throw new Error(`Failed to parse version string: ${version}`); } } isEqual(other) { return this.major === other.major && this.minor === other.minor && this.patch === other.patch && this.suffix === other.suffix && this.suffixVersion === other.suffixVersion; } isVsCodeVersionGreaterThan(other) { return this.isGreaterThan(other, 'insider') || this.isGreaterThan(other, 'exploration'); } isExtensionVersionGreaterThan(other) { return this.isGreaterThan(other, 'insiders'); } isMajorMinorPatchGreaterThan(other) { return this.isGreaterThan(other, ""); } isGreaterThan(other, suffixStr) { if (suffixStr && ((this.suffix && !this.suffix.startsWith(suffixStr)) || (other.suffix && !other.suffix.startsWith(suffixStr)))) { return false; } let diff = this.major - other.major; if (diff) { return diff > 0; } else { diff = this.minor - other.minor; if (diff) { return diff > 0; } else { diff = this.patch - other.patch; if (diff) { return diff > 0; } else { if (!suffixStr) { return false; } if (this.suffix) { if (!other.suffix) { return false; } return (this.suffixVersion > other.suffixVersion); } else { return other.suffix ? true : false; } } } } } } exports.PackageVersion = PackageVersion; /***/ }), /***/ 3383: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const os = __webpack_require__(2087); const linuxDistribution_1 = __webpack_require__(6547); const plist = __webpack_require__(6540); const fs = __webpack_require__(5747); const logger = __webpack_require__(5610); const nls = __webpack_require__(3612); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(__webpack_require__(5622).join(__dirname, 'src\\platform.ts')); const localize = nls.loadMessageBundle(__webpack_require__(5622).join(__dirname, 'src\\platform.ts')); function GetOSName(processPlatform) { switch (processPlatform) { case "win32": return "Windows"; case "darwin": return "macOS"; case "linux": return "Linux"; default: return undefined; } } exports.GetOSName = GetOSName; class PlatformInformation { constructor(platform, architecture, distribution, version) { this.platform = platform; this.architecture = architecture; this.distribution = distribution; this.version = version; } static GetPlatformInformation() { return __awaiter(this, void 0, void 0, function* () { const platform = os.platform(); const architecture = PlatformInformation.GetArchitecture(); let distribution; let version; switch (platform) { case "win32": break; case "linux": distribution = yield linuxDistribution_1.LinuxDistribution.GetDistroInformation(); break; case "darwin": version = yield PlatformInformation.GetDarwinVersion(); break; default: throw new Error(localize(0, null)); } return new PlatformInformation(platform, architecture, distribution, version); }); } static GetArchitecture() { const arch = os.arch(); switch (arch) { case "x64": case "arm64": case "arm": return arch; case "x32": case "ia32": return "x86"; default: if (os.platform() === "win32") { return "x86"; } else { return "x64"; } } } static GetDarwinVersion() { const DARWIN_SYSTEM_VERSION_PLIST = "/System/Library/CoreServices/SystemVersion.plist"; let productDarwinVersion = ""; let errorMessage = ""; if (fs.existsSync(DARWIN_SYSTEM_VERSION_PLIST)) { const systemVersionPListBuffer = fs.readFileSync(DARWIN_SYSTEM_VERSION_PLIST); const systemVersionData = plist.parse(systemVersionPListBuffer.toString()); if (systemVersionData) { productDarwinVersion = systemVersionData.ProductVersion; } else { errorMessage = localize(1, null); } } else { errorMessage = localize(2, null, DARWIN_SYSTEM_VERSION_PLIST); } if (errorMessage) { logger.getOutputChannel().appendLine(errorMessage); logger.showOutputChannel(); } return Promise.resolve(productDarwinVersion); } } exports.PlatformInformation = PlatformInformation; /***/ }), /***/ 1818: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode_extension_telemetry_1 = __webpack_require__(4182); const vscode_tas_client_1 = __webpack_require__(2579); const util = __webpack_require__(5331); const packageVersion_1 = __webpack_require__(302); class ExperimentationTelemetry { constructor(baseReporter) { this.baseReporter = baseReporter; this.sharedProperties = {}; } sendTelemetryEvent(eventName, properties, measurements) { this.baseReporter.sendTelemetryEvent(eventName, Object.assign(Object.assign({}, this.sharedProperties), properties), measurements); } sendTelemetryErrorEvent(eventName, properties, _measurements) { this.baseReporter.sendTelemetryErrorEvent(eventName, Object.assign(Object.assign({}, this.sharedProperties), properties)); } setSharedProperty(name, value) { this.sharedProperties[name] = value; } postEvent(eventName, props) { const event = {}; for (const [key, value] of props) { event[key] = value; } this.sendTelemetryEvent(eventName, event); } dispose() { return this.baseReporter.dispose(); } } exports.ExperimentationTelemetry = ExperimentationTelemetry; let initializationPromise; let experimentationTelemetry; const appInsightsKey = "AIF-d9b70cd4-b9f9-4d70-929b-a071c400b217"; function activate() { try { if (util.extensionContext) { const packageInfo = getPackageInfo(); if (packageInfo) { let targetPopulation; const userVersion = new packageVersion_1.PackageVersion(packageInfo.version); if (userVersion.suffix === "") { targetPopulation = vscode_tas_client_1.TargetPopulation.Public; } else if (userVersion.suffix === "insiders") { targetPopulation = vscode_tas_client_1.TargetPopulation.Insiders; } else { targetPopulation = vscode_tas_client_1.TargetPopulation.Internal; } experimentationTelemetry = new ExperimentationTelemetry(new vscode_extension_telemetry_1.default(packageInfo.name, packageInfo.version, appInsightsKey)); initializationPromise = vscode_tas_client_1.getExperimentationServiceAsync(packageInfo.name, packageInfo.version, targetPopulation, experimentationTelemetry, util.extensionContext.globalState); } } } catch (e) { } } exports.activate = activate; function getExperimentationService() { return __awaiter(this, void 0, void 0, function* () { return initializationPromise; }); } exports.getExperimentationService = getExperimentationService; function deactivate() { return __awaiter(this, void 0, void 0, function* () { if (initializationPromise) { try { yield initializationPromise; } catch (e) { } if (experimentationTelemetry) { experimentationTelemetry.dispose(); } } }); } exports.deactivate = deactivate; function logDebuggerEvent(eventName, properties) { return __awaiter(this, void 0, void 0, function* () { try { yield initializationPromise; } catch (e) { } if (experimentationTelemetry) { const eventNamePrefix = "cppdbg/VS/Diagnostics/Debugger/"; experimentationTelemetry.sendTelemetryEvent(eventNamePrefix + eventName, properties); } }); } exports.logDebuggerEvent = logDebuggerEvent; function logLanguageServerEvent(eventName, properties, metrics) { return __awaiter(this, void 0, void 0, function* () { try { yield initializationPromise; } catch (e) { } if (experimentationTelemetry) { const eventNamePrefix = "C_Cpp/LanguageServer/"; experimentationTelemetry.sendTelemetryEvent(eventNamePrefix + eventName, properties, metrics); } }); } exports.logLanguageServerEvent = logLanguageServerEvent; function getPackageInfo() { return { name: util.packageJson.publisher + "." + util.packageJson.name, version: util.packageJson.version }; } /***/ }), /***/ 5648: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); class TestHook { constructor() { this.intelliSenseStatusChangedEvent = new vscode.EventEmitter(); this.statusChangedEvent = new vscode.EventEmitter(); } get StatusChanged() { return this.statusChangedEvent.event; } get IntelliSenseStatusChanged() { return this.intelliSenseStatusChangedEvent.event; } get valid() { return !!this.intelliSenseStatusChangedEvent && !!this.statusChangedEvent; } updateStatus(status) { this.intelliSenseStatusChangedEvent.fire(status); this.statusChangedEvent.fire(status.status); } dispose() { this.intelliSenseStatusChangedEvent.dispose(); this.statusChangedEvent.dispose(); } } exports.TestHook = TestHook; let testHook; function getTestHook() { if (!testHook || !testHook.valid) { testHook = new TestHook(); } return testHook; } exports.getTestHook = getTestHook; /***/ }), /***/ 3286: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. * ------------------------------------------------------------------------------------------ */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCppToolsApi = exports.Version = void 0; const vscode = __webpack_require__(7549); /** * API version information. */ var Version; (function (Version) { Version[Version["v0"] = 0] = "v0"; Version[Version["v1"] = 1] = "v1"; Version[Version["v2"] = 2] = "v2"; Version[Version["v3"] = 3] = "v3"; Version[Version["v4"] = 4] = "v4"; Version[Version["v5"] = 5] = "v5"; Version[Version["latest"] = 5] = "latest"; })(Version = exports.Version || (exports.Version = {})); /** * Check if an object satisfies the contract of the CppToolsExtension interface. */ function isCppToolsExtension(extension) { return extension && extension.getApi; } /** * Check if an object satisfies the contract of the first version of the CppToolsApi. * (The first release of the API only had two functions) */ function isLegacyCppToolsApi(api) { return api && api.registerCustomConfigurationProvider && api.didChangeCustomConfiguration; } /** * Helper function to get the CppToolsApi from the cpptools extension. * @param version The desired API version * @example ``` import {CppToolsApi, Version, CustomConfigurationProvider, getCppToolsApi} from 'vscode-cpptools'; let api: CppToolsApi|undefined = await getCppToolsApi(Version.v1); if (api) { // Inform cpptools that a custom config provider // will be able to service the current workspace. api.registerCustomConfigurationProvider(provider); // Do any required setup that the provider needs. // Notify cpptools that the provider is ready to // provide IntelliSense configurations. api.notifyReady(provider); } // Dispose of the 'api' in your extension's // deactivate() method, or whenever you want to // unregister the provider. ``` */ function getCppToolsApi(version) { return __awaiter(this, void 0, void 0, function* () { let cpptools = vscode.extensions.getExtension("ms-vscode.cpptools"); let extension = undefined; let api = undefined; if (cpptools) { if (!cpptools.isActive) { extension = yield cpptools.activate(); } else { extension = cpptools.exports; } if (isCppToolsExtension(extension)) { // ms-vscode.cpptools > 0.17.5 try { api = extension.getApi(version); } catch (err) { // Unfortunately, ms-vscode.cpptools [0.17.6, 0.18.1] throws a RangeError if you specify a version greater than v1. // These versions of the extension will not be able to act on the newer interface and v2 is a superset of v1, so we can safely fall back to v1. let e = err; if (e && e.message && e.message.startsWith("Invalid version")) { api = extension.getApi(Version.v1); } } if (version !== Version.v1) { if (!api.getVersion) { console.warn(`[vscode-cpptools-api] version ${version} requested, but is not available in the current version of the cpptools extension. Using version 1 instead.`); } else if (version !== api.getVersion()) { console.warn(`[vscode-cpptools-api] version ${version} requested, but is not available in the current version of the cpptools extension. Using version ${api.getVersion()} instead.`); } } } else if (isLegacyCppToolsApi(extension)) { // ms-vscode.cpptools version 0.17.5 api = extension; if (version !== Version.v0) { console.warn(`[vscode-cpptools-api] version ${version} requested, but is not available in version 0.17.5 of the cpptools extension. Using version 0 instead.`); } } else { console.warn('[vscode-cpptools-api] No cpptools API was found.'); } } else { console.warn('[vscode-cpptools-api] C/C++ extension is not installed'); } return api; }); } exports.getCppToolsApi = getCppToolsApi; /***/ }), /***/ 7373: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. * ------------------------------------------------------------------------------------------ */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCppToolsTestApi = exports.Status = void 0; const api_1 = __webpack_require__(3286); const vscode = __webpack_require__(7549); /** * Tag Parser or IntelliSense status codes. */ var Status; (function (Status) { Status[Status["TagParsingBegun"] = 1] = "TagParsingBegun"; Status[Status["TagParsingDone"] = 2] = "TagParsingDone"; Status[Status["IntelliSenseCompiling"] = 3] = "IntelliSenseCompiling"; Status[Status["IntelliSenseReady"] = 4] = "IntelliSenseReady"; })(Status = exports.Status || (exports.Status = {})); function isCppToolsTestExtension(extension) { return extension.getTestApi !== undefined; } function getCppToolsTestApi(version) { return __awaiter(this, void 0, void 0, function* () { let cpptools = vscode.extensions.getExtension("ms-vscode.cpptools"); let extension; let api; if (cpptools) { if (!cpptools.isActive) { extension = yield cpptools.activate(); } else { extension = cpptools.exports; } if (isCppToolsTestExtension(extension)) { // ms-vscode.cpptools > 0.17.5 try { api = extension.getTestApi(version); } catch (err) { // Unfortunately, ms-vscode.cpptools [0.17.6, 0.18.1] throws a RangeError if you specify a version greater than v1. // These versions of the extension will not be able to act on the newer interface and v2 is a superset of v1, so we can safely fall back to v1. let e = err; if (e.message && e.message.startsWith("Invalid version")) { api = extension.getTestApi(api_1.Version.v1); } } if (version !== api_1.Version.v1) { if (!api.getVersion) { console.warn(`vscode-cpptools-api version ${version} requested, but is not available in the current version of the cpptools extension. Using version 1 instead.`); } else if (version !== api.getVersion()) { console.warn(`vscode-cpptools-api version ${version} requested, but is not available in the current version of the cpptools extension. Using version ${api.getVersion()} instead.`); } } } else { // ms-vscode.cpptools version 0.17.5 api = extension; if (version !== api_1.Version.v0) { console.warn(`vscode-cpptools-api version ${version} requested, but is not available in version 0.17.5 of the cpptools extension. Using version 0 instead.`); } } } else { console.warn("C/C++ extension is not installed"); } return api; }); } exports.getCppToolsTestApi = getCppToolsTestApi; /***/ }), /***/ 4182: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", ({ value: true })); process.env['APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL'] = true; var fs = __webpack_require__(5747); var os = __webpack_require__(2087); var path = __webpack_require__(5622); var vscode = __webpack_require__(7549); var appInsights = __webpack_require__(4310); var TelemetryReporter = /** @class */ (function () { // tslint:disable-next-line function TelemetryReporter(extensionId, extensionVersion, key, firstParty) { var _this = this; this.extensionId = extensionId; this.extensionVersion = extensionVersion; this.firstParty = false; this.userOptIn = false; this.firstParty = !!firstParty; var logFilePath = process.env['VSCODE_LOGS'] || ''; if (logFilePath && extensionId && process.env['VSCODE_LOG_LEVEL'] === 'trace') { logFilePath = path.join(logFilePath, extensionId + ".txt"); this.logStream = fs.createWriteStream(logFilePath, { flags: 'a', encoding: 'utf8', autoClose: true }); } this.updateUserOptIn(key); if (vscode.env.onDidChangeTelemetryEnabled !== undefined) { this.optOutListener = vscode.env.onDidChangeTelemetryEnabled(function () { return _this.updateUserOptIn(key); }); } else { this.optOutListener = vscode.workspace.onDidChangeConfiguration(function () { return _this.updateUserOptIn(key); }); } } TelemetryReporter.prototype.updateUserOptIn = function (key) { // Newer versions of vscode api have telemetry enablement exposed, but fallback to setting for older versions var config = vscode.workspace.getConfiguration(TelemetryReporter.TELEMETRY_CONFIG_ID); var newOptInValue = vscode.env.isTelemetryEnabled === undefined ? config.get(TelemetryReporter.TELEMETRY_CONFIG_ENABLED_ID, true) : vscode.env.isTelemetryEnabled; if (this.userOptIn !== newOptInValue) { this.userOptIn = newOptInValue; if (this.userOptIn) { this.createAppInsightsClient(key); } else { this.dispose(); } } }; TelemetryReporter.prototype.createAppInsightsClient = function (key) { //check if another instance is already initialized if (appInsights.defaultClient) { this.appInsightsClient = new appInsights.TelemetryClient(key); // no other way to enable offline mode this.appInsightsClient.channel.setUseDiskRetryCaching(true); } else { appInsights.setup(key) .setAutoCollectRequests(false) .setAutoCollectPerformance(false) .setAutoCollectExceptions(false) .setAutoCollectDependencies(false) .setAutoDependencyCorrelation(false) .setAutoCollectConsole(false) .setUseDiskRetryCaching(true) .start(); this.appInsightsClient = appInsights.defaultClient; } this.appInsightsClient.commonProperties = this.getCommonProperties(); if (vscode && vscode.env) { this.appInsightsClient.context.tags[this.appInsightsClient.context.keys.userId] = vscode.env.machineId; this.appInsightsClient.context.tags[this.appInsightsClient.context.keys.sessionId] = vscode.env.sessionId; } //check if it's an Asimov key to change the endpoint if (key && key.indexOf('AIF-') === 0) { this.appInsightsClient.config.endpointUrl = "https://vortex.data.microsoft.com/collect/v1"; this.firstParty = true; } }; // __GDPR__COMMON__ "common.os" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } // __GDPR__COMMON__ "common.platformversion" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } // __GDPR__COMMON__ "common.extname" : { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } // __GDPR__COMMON__ "common.extversion" : { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } // __GDPR__COMMON__ "common.vscodemachineid" : { "endPoint": "MacAddressHash", "classification": "EndUserPseudonymizedInformation", "purpose": "FeatureInsight" } // __GDPR__COMMON__ "common.vscodesessionid" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } // __GDPR__COMMON__ "common.vscodeversion" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } // __GDPR__COMMON__ "common.uikind" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } // __GDPR__COMMON__ "common.remotename" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } // __GDPR__COMMON__ "common.isnewappinstall" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } TelemetryReporter.prototype.getCommonProperties = function () { var commonProperties = Object.create(null); commonProperties['common.os'] = os.platform(); commonProperties['common.platformversion'] = (os.release() || '').replace(/^(\d+)(\.\d+)?(\.\d+)?(.*)/, '$1$2$3'); commonProperties['common.extname'] = this.extensionId; commonProperties['common.extversion'] = this.extensionVersion; if (vscode && vscode.env) { commonProperties['common.vscodemachineid'] = vscode.env.machineId; commonProperties['common.vscodesessionid'] = vscode.env.sessionId; commonProperties['common.vscodeversion'] = vscode.version; commonProperties['common.isnewappinstall'] = vscode.env.isNewAppInstall; switch (vscode.env.uiKind) { case vscode.UIKind.Web: commonProperties['common.uikind'] = 'web'; break; case vscode.UIKind.Desktop: commonProperties['common.uikind'] = 'desktop'; break; default: commonProperties['common.uikind'] = 'unknown'; } commonProperties['common.remotename'] = this.cleanRemoteName(vscode.env.remoteName); } return commonProperties; }; TelemetryReporter.prototype.cleanRemoteName = function (remoteName) { if (!remoteName) { return 'none'; } var ret = 'other'; // Allowed remote authorities ['ssh-remote', 'dev-container', 'attached-container', 'wsl'].forEach(function (res) { if (remoteName.indexOf(res + "+") === 0) { ret = res; } }); return ret; }; TelemetryReporter.prototype.shouldSendErrorTelemetry = function () { if (this.firstParty) { if (this.cleanRemoteName(vscode.env.remoteName) !== 'other') { return true; } if (this.extension === undefined || this.extension.extensionKind === vscode.ExtensionKind.Workspace) { return false; } if (vscode.env.uiKind === vscode.UIKind.Web) { return false; } return true; } return true; }; Object.defineProperty(TelemetryReporter.prototype, "extension", { get: function () { if (this._extension === undefined) { this._extension = vscode.extensions.getExtension(this.extensionId); } return this._extension; }, enumerable: false, configurable: true }); TelemetryReporter.prototype.cloneAndChange = function (obj, change) { if (obj === null || typeof obj !== 'object') return obj; if (typeof change !== 'function') return obj; var ret = {}; for (var key in obj) { ret[key] = change(key, obj[key]); } return ret; }; TelemetryReporter.prototype.anonymizeFilePaths = function (stack, anonymizeFilePaths) { if (stack === undefined || stack === null) { return ''; } var cleanupPatterns = [new RegExp(vscode.env.appRoot.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi')]; if (this.extension) { cleanupPatterns.push(new RegExp(this.extension.extensionPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi')); } var updatedStack = stack; if (anonymizeFilePaths) { var cleanUpIndexes = []; for (var _i = 0, cleanupPatterns_1 = cleanupPatterns; _i < cleanupPatterns_1.length; _i++) { var regexp = cleanupPatterns_1[_i]; while (true) { var result = regexp.exec(stack); if (!result) { break; } cleanUpIndexes.push([result.index, regexp.lastIndex]); } } var nodeModulesRegex = /^[\\\/]?(node_modules|node_modules\.asar)[\\\/]/; var fileRegex = /(file:\/\/)?([a-zA-Z]:(\\\\|\\|\/)|(\\\\|\\|\/))?([\w-\._]+(\\\\|\\|\/))+[\w-\._]*/g; var lastIndex = 0; updatedStack = ''; var _loop_1 = function () { var result = fileRegex.exec(stack); if (!result) { return "break"; } // Anoynimize user file paths that do not need to be retained or cleaned up. if (!nodeModulesRegex.test(result[0]) && cleanUpIndexes.every(function (_a) { var x = _a[0], y = _a[1]; return result.index < x || result.index >= y; })) { updatedStack += stack.substring(lastIndex, result.index) + ''; lastIndex = fileRegex.lastIndex; } }; while (true) { var state_1 = _loop_1(); if (state_1 === "break") break; } if (lastIndex < stack.length) { updatedStack += stack.substr(lastIndex); } } // sanitize with configured cleanup patterns for (var _a = 0, cleanupPatterns_2 = cleanupPatterns; _a < cleanupPatterns_2.length; _a++) { var regexp = cleanupPatterns_2[_a]; updatedStack = updatedStack.replace(regexp, ''); } return updatedStack; }; TelemetryReporter.prototype.sendTelemetryEvent = function (eventName, properties, measurements) { var _this = this; if (this.userOptIn && eventName && this.appInsightsClient) { var cleanProperties = this.cloneAndChange(properties, function (_key, prop) { return _this.anonymizeFilePaths(prop, _this.firstParty); }); this.appInsightsClient.trackEvent({ name: this.extensionId + "/" + eventName, properties: cleanProperties, measurements: measurements }); if (this.logStream) { this.logStream.write("telemetry/" + eventName + " " + JSON.stringify({ properties: properties, measurements: measurements }) + "\n"); } } }; TelemetryReporter.prototype.sendTelemetryErrorEvent = function (eventName, properties, measurements, errorProps) { var _this = this; if (this.userOptIn && eventName && this.appInsightsClient) { // always clean the properties if first party // do not send any error properties if we shouldn't send error telemetry // if we have no errorProps, assume all are error props var cleanProperties = this.cloneAndChange(properties, function (key, prop) { if (_this.shouldSendErrorTelemetry()) { return _this.anonymizeFilePaths(prop, _this.firstParty); } if (errorProps === undefined || errorProps.indexOf(key) !== -1) { return 'REDACTED'; } return _this.anonymizeFilePaths(prop, _this.firstParty); }); this.appInsightsClient.trackEvent({ name: this.extensionId + "/" + eventName, properties: cleanProperties, measurements: measurements }); if (this.logStream) { this.logStream.write("telemetry/" + eventName + " " + JSON.stringify({ properties: properties, measurements: measurements }) + "\n"); } } }; TelemetryReporter.prototype.sendTelemetryException = function (error, properties, measurements) { var _this = this; if (this.shouldSendErrorTelemetry() && this.userOptIn && error && this.appInsightsClient) { var cleanProperties = this.cloneAndChange(properties, function (_key, prop) { return _this.anonymizeFilePaths(prop, _this.firstParty); }); this.appInsightsClient.trackException({ exception: error, properties: cleanProperties, measurements: measurements }); if (this.logStream) { this.logStream.write("telemetry/" + error.name + " " + error.message + " " + JSON.stringify({ properties: properties, measurements: measurements }) + "\n"); } } }; TelemetryReporter.prototype.dispose = function () { var _this = this; this.optOutListener.dispose(); var flushEventsToLogger = new Promise(function (resolve) { if (!_this.logStream) { return resolve(void 0); } _this.logStream.on('finish', resolve); _this.logStream.end(); }); var flushEventsToAI = new Promise(function (resolve) { if (_this.appInsightsClient) { _this.appInsightsClient.flush({ callback: function () { // all data flushed _this.appInsightsClient = undefined; resolve(void 0); } }); } else { resolve(void 0); } }); return Promise.all([flushEventsToAI, flushEventsToLogger]); }; TelemetryReporter.TELEMETRY_CONFIG_ID = 'telemetry'; TelemetryReporter.TELEMETRY_CONFIG_ENABLED_ID = 'enableTelemetry'; return TelemetryReporter; }()); exports.default = TelemetryReporter; //# sourceMappingURL=telemetryReporter.js.map /***/ }), /***/ 8528: /***/ ((__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 events_1 = __webpack_require__(2403); const Is = __webpack_require__(1081); 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) { let 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) { let handle = setTimeout(callback.bind(context), 0); return { dispose() { clearTimeout(handle); } }; }); class MutableToken { constructor() { this._isCancelled = false; } cancel() { if (!this._isCancelled) { this._isCancelled = true; if (this._emitter) { this._emitter.fire(undefined); this._emitter = undefined; } } } 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; } } 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() { this.cancel(); } } exports.CancellationTokenSource = CancellationTokenSource; /***/ }), /***/ 2403: /***/ ((__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 })); var Disposable; (function (Disposable) { function create(func) { return { dispose: func }; } Disposable.create = create; })(Disposable = exports.Disposable || (exports.Disposable = {})); 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; } var foundCallbackWithDifferentContext = false; for (var 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 []; } var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0); for (var i = 0, len = callbacks.length; i < len; i++) { try { ret.push(callbacks[i].apply(contexts[i], args)); } catch (e) { 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); let result; result = { dispose: () => { 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; } } } Emitter._noop = function () { }; exports.Emitter = Emitter; /***/ }), /***/ 1081: /***/ ((__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 })); 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; /***/ }), /***/ 4461: /***/ ((__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 })); var Touch; (function (Touch) { Touch.None = 0; Touch.First = 1; Touch.Last = 2; })(Touch = exports.Touch || (exports.Touch = {})); class LinkedMap { constructor() { this._map = new Map(); this._head = undefined; this._tail = undefined; this._size = 0; } clear() { this._map.clear(); this._head = undefined; this._tail = undefined; this._size = 0; } isEmpty() { return !this._head && !this._tail; } get size() { return this._size; } has(key) { return this._map.has(key); } get(key) { const item = this._map.get(key); if (!item) { return undefined; } 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++; } } delete(key) { const item = this._map.get(key); if (!item) { return false; } this._map.delete(key); this.removeItem(item); this._size--; return true; } 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) { let current = this._head; while (current) { if (thisArg) { callbackfn.bind(thisArg)(current.value, current.key, this); } else { callbackfn(current.value, current.key, this); } current = current.next; } } forEachReverse(callbackfn, thisArg) { let current = this._tail; while (current) { if (thisArg) { callbackfn.bind(thisArg)(current.value, current.key, this); } else { callbackfn(current.value, current.key, this); } current = current.previous; } } values() { let result = []; let current = this._head; while (current) { result.push(current.value); current = current.next; } return result; } keys() { let result = []; let current = this._head; while (current) { result.push(current.key); current = current.next; } return result; } /* JSON RPC run on es5 which has no Symbol.iterator public keys(): IterableIterator { let current = this._head; let iterator: IterableIterator = { [Symbol.iterator]() { return iterator; }, next():IteratorResult { if (current) { let result = { value: current.key, done: false }; current = current.next; return result; } else { return { value: undefined, done: true }; } } }; return iterator; } public values(): IterableIterator { let current = this._head; let iterator: IterableIterator = { [Symbol.iterator]() { return iterator; }, next():IteratorResult { if (current) { let result = { value: current.value, done: false }; current = current.next; return result; } else { return { value: undefined, done: true }; } } }; return iterator; } */ 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; } 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; } removeItem(item) { if (item === this._head && item === this._tail) { this._head = undefined; this._tail = undefined; } else if (item === this._head) { this._head = item.next; } else if (item === this._tail) { 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; } } 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; } 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; } } } exports.LinkedMap = LinkedMap; /***/ }), /***/ 617: /***/ ((__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. * ------------------------------------------------------------------------------------------ */ /// function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", ({ value: true })); const Is = __webpack_require__(1081); const messages_1 = __webpack_require__(3722); exports.RequestType = messages_1.RequestType; exports.RequestType0 = messages_1.RequestType0; exports.RequestType1 = messages_1.RequestType1; exports.RequestType2 = messages_1.RequestType2; exports.RequestType3 = messages_1.RequestType3; exports.RequestType4 = messages_1.RequestType4; exports.RequestType5 = messages_1.RequestType5; exports.RequestType6 = messages_1.RequestType6; exports.RequestType7 = messages_1.RequestType7; exports.RequestType8 = messages_1.RequestType8; exports.RequestType9 = messages_1.RequestType9; exports.ResponseError = messages_1.ResponseError; exports.ErrorCodes = messages_1.ErrorCodes; exports.NotificationType = messages_1.NotificationType; exports.NotificationType0 = messages_1.NotificationType0; exports.NotificationType1 = messages_1.NotificationType1; exports.NotificationType2 = messages_1.NotificationType2; exports.NotificationType3 = messages_1.NotificationType3; exports.NotificationType4 = messages_1.NotificationType4; exports.NotificationType5 = messages_1.NotificationType5; exports.NotificationType6 = messages_1.NotificationType6; exports.NotificationType7 = messages_1.NotificationType7; exports.NotificationType8 = messages_1.NotificationType8; exports.NotificationType9 = messages_1.NotificationType9; const messageReader_1 = __webpack_require__(1160); exports.MessageReader = messageReader_1.MessageReader; exports.StreamMessageReader = messageReader_1.StreamMessageReader; exports.IPCMessageReader = messageReader_1.IPCMessageReader; exports.SocketMessageReader = messageReader_1.SocketMessageReader; const messageWriter_1 = __webpack_require__(7636); exports.MessageWriter = messageWriter_1.MessageWriter; exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter; exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter; exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter; const events_1 = __webpack_require__(2403); exports.Disposable = events_1.Disposable; exports.Event = events_1.Event; exports.Emitter = events_1.Emitter; const cancellation_1 = __webpack_require__(8528); exports.CancellationTokenSource = cancellation_1.CancellationTokenSource; exports.CancellationToken = cancellation_1.CancellationToken; const linkedMap_1 = __webpack_require__(4461); __export(__webpack_require__(5362)); __export(__webpack_require__(4502)); var CancelNotification; (function (CancelNotification) { CancelNotification.type = new messages_1.NotificationType('$/cancelRequest'); })(CancelNotification || (CancelNotification = {})); 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) { 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('$/setTraceNotification'); })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {})); var LogTraceNotification; (function (LogTraceNotification) { LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification'); })(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) { let candidate = value; return candidate && Is.func(candidate.cancelUndispatched); } ConnectionStrategy.is = is; })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {})); 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, strategy) { let sequenceNumber = 0; let notificationSquenceNumber = 0; let unknownResponseSquenceNumber = 0; const version = '2.0'; let starRequestHandler = undefined; let requestHandlers = Object.create(null); let starNotificationHandler = undefined; let notificationHandlers = Object.create(null); 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; let errorEmitter = new events_1.Emitter(); let closeEmitter = new events_1.Emitter(); let unhandledNotificationEmitter = new events_1.Emitter(); let disposeEmitter = new events_1.Emitter(); function createRequestQueueKey(id) { 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 = setImmediate(() => { timer = undefined; processMessageQueue(); }); } function processMessageQueue() { if (messageQueue.size === 0) { return; } let 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(); } } let 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) { let key = createRequestQueueKey(message.params.id); let toCancel = messageQueue.get(key); if (messages_1.isRequestMessage(toCancel)) { let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel); if (response && (response.error !== void 0 || response.result !== void 0)) { 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) { let message = { jsonrpc: version, id: requestMessage.id }; if (resultOrError instanceof messages_1.ResponseError) { message.error = resultOrError.toJson(); } else { message.result = resultOrError === void 0 ? null : resultOrError; } traceSendingResponse(message, method, startTime); messageWriter.write(message); } function replyError(error, method, startTime) { let 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 === void 0) { result = null; } let message = { jsonrpc: version, id: requestMessage.id, result: result }; traceSendingResponse(message, method, startTime); messageWriter.write(message); } traceReceivedRequest(requestMessage); let element = requestHandlers[requestMessage.method]; let type; let requestHandler; if (element) { type = element.type; requestHandler = element.handler; } let startTime = Date.now(); if (requestHandler || starRequestHandler) { let cancellationSource = new cancellation_1.CancellationTokenSource(); let tokenKey = String(requestMessage.id); requestTokens[tokenKey] = cancellationSource; try { let handlerResult; if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) { handlerResult = requestHandler ? requestHandler(cancellationSource.token) : starRequestHandler(requestMessage.method, cancellationSource.token); } else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) { handlerResult = requestHandler ? requestHandler(...requestMessage.params, cancellationSource.token) : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token); } else { handlerResult = requestHandler ? requestHandler(requestMessage.params, cancellationSource.token) : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token); } let 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 { let key = String(responseMessage.id); let responsePromise = responsePromises[key]; traceReceivedResponse(responseMessage, responsePromise); if (responsePromise) { delete responsePromises[key]; try { if (responseMessage.error) { let error = responseMessage.error; responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data)); } else if (responseMessage.result !== void 0) { 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) => { let id = params.id; let source = requestTokens[String(id)]; if (source) { source.cancel(); } }; } else { let element = notificationHandlers[message.method]; if (element) { notificationHandler = element.handler; type = element.type; } } if (notificationHandler || starNotificationHandler) { try { traceReceivedNotification(message); if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) { notificationHandler ? notificationHandler() : starNotificationHandler(message.method); } else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) { notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params); } else { notificationHandler ? notificationHandler(message.params) : 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 let responseMessage = message; if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) { let key = String(responseMessage.id); let 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 === void 0) { 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 === void 0) { data = 'No result returned.\n\n'; } } } if (responsePromise) { let 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 === void 0) { return null; } else { return param; } } function computeMessageParams(type, params) { let result; let numberOfParams = type.numberOfParams; switch (numberOfParams) { case 0: result = null; break; case 1: result = undefinedToNull(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; } let connection = { sendNotification: (type, ...params) => { throwIfClosedOrDisposed(); let method; let messageParams; if (Is.string(type)) { method = type; switch (params.length) { case 0: messageParams = null; break; case 1: messageParams = params[0]; break; default: messageParams = params; break; } } else { method = type.method; messageParams = computeMessageParams(type, params); } let notificationMessage = { jsonrpc: version, method: method, params: messageParams }; traceSendingNotification(notificationMessage); messageWriter.write(notificationMessage); }, onNotification: (type, handler) => { throwIfClosedOrDisposed(); if (Is.func(type)) { starNotificationHandler = type; } else if (handler) { if (Is.string(type)) { notificationHandlers[type] = { type: undefined, handler }; } else { notificationHandlers[type.method] = { type, handler }; } } }, sendRequest: (type, ...params) => { throwIfClosedOrDisposed(); throwIfNotListening(); let method; let messageParams; let token = undefined; if (Is.string(type)) { method = type; switch (params.length) { case 0: messageParams = null; break; case 1: // The cancellation token is optional so it can also be undefined. if (cancellation_1.CancellationToken.is(params[0])) { messageParams = null; token = params[0]; } else { messageParams = undefinedToNull(params[0]); } break; default: const last = params.length - 1; if (cancellation_1.CancellationToken.is(params[last])) { token = params[last]; if (params.length === 2) { messageParams = undefinedToNull(params[0]); } else { messageParams = params.slice(0, last).map(value => undefinedToNull(value)); } } else { messageParams = params.map(value => undefinedToNull(value)); } break; } } else { method = type.method; messageParams = computeMessageParams(type, params); let numberOfParams = type.numberOfParams; token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined; } let id = sequenceNumber++; let result = new Promise((resolve, reject) => { let requestMessage = { jsonrpc: version, id: id, method: method, params: messageParams }; let responsePromise = { method: method, timerStart: Date.now(), resolve, reject }; 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; } }); if (token) { token.onCancellationRequested(() => { connection.sendNotification(CancelNotification.type, { id }); }); } return result; }, onRequest: (type, handler) => { throwIfClosedOrDisposed(); if (Is.func(type)) { starRequestHandler = type; } else if (handler) { if (Is.string(type)) { requestHandlers[type] = { type: undefined, handler }; } else { requestHandlers[type.method] = { type, handler }; } } }, trace: (_value, _tracer, sendNotificationOrTraceOptions) => { let _sendNotification = false; let _traceFormat = TraceFormat.Text; if (sendNotificationOrTraceOptions !== void 0) { 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, dispose: () => { if (isDisposed()) { return; } state = ConnectionState.Disposed; disposeEmitter.fire(undefined); let 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: () => { console.log("inspect"); } }; connection.onNotification(LogTraceNotification.type, (params) => { if (trace === Trace.Off || !tracer) { return; } tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined); }); return connection; } function isMessageReader(value) { return value.listen !== void 0 && value.read === void 0; } function isMessageWriter(value) { return value.write !== void 0 && value.end === void 0; } function createMessageConnection(input, output, logger, strategy) { if (!logger) { logger = exports.NullLogger; } let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input); let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output); return _createMessageConnection(reader, writer, logger, strategy); } exports.createMessageConnection = createMessageConnection; /***/ }), /***/ 1160: /***/ ((__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 events_1 = __webpack_require__(2403); const Is = __webpack_require__(1081); let DefaultSize = 8192; let CR = Buffer.from('\r', 'ascii')[0]; let LF = Buffer.from('\n', 'ascii')[0]; let CRLF = '\r\n'; class MessageBuffer { constructor(encoding = 'utf8') { this.encoding = encoding; this.index = 0; this.buffer = Buffer.allocUnsafe(DefaultSize); } append(chunk) { var toAppend = chunk; if (typeof (chunk) === 'string') { var str = chunk; var bufferLen = Buffer.byteLength(str, this.encoding); toAppend = Buffer.allocUnsafe(bufferLen); toAppend.write(str, 0, bufferLen, this.encoding); } if (this.buffer.length - this.index >= toAppend.length) { toAppend.copy(this.buffer, this.index, 0, toAppend.length); } else { var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize; if (this.index === 0) { this.buffer = Buffer.allocUnsafe(newSize); toAppend.copy(this.buffer, 0, 0, toAppend.length); } else { this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize); } } this.index += toAppend.length; } tryReadHeaders() { let result = undefined; let current = 0; while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) { current++; } // No header / body separator found (e.g CRLFCRLF) if (current + 3 >= this.index) { return result; } result = Object.create(null); let headers = this.buffer.toString('ascii', 0, current).split(CRLF); headers.forEach((header) => { let index = header.indexOf(':'); if (index === -1) { throw new Error('Message header must separate key and value using :'); } let key = header.substr(0, index); let value = header.substr(index + 1).trim(); result[key] = value; }); let nextStart = current + 4; this.buffer = this.buffer.slice(nextStart); this.index = this.index - nextStart; return result; } tryReadContent(length) { if (this.index < length) { return null; } let result = this.buffer.toString(this.encoding, 0, length); let nextStart = length; this.buffer.copy(this.buffer, 0, nextStart); this.index = this.index - nextStart; return result; } get numberOfBytes() { return this.index; } } 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 recevied error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`); } } } exports.AbstractMessageReader = AbstractMessageReader; class StreamMessageReader extends AbstractMessageReader { constructor(readable, encoding = 'utf8') { super(); this.readable = readable; this.buffer = new MessageBuffer(encoding); this._partialMessageTimeout = 10000; } 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; this.readable.on('data', (data) => { this.onData(data); }); this.readable.on('error', (error) => this.fireError(error)); this.readable.on('close', () => this.fireClose()); } onData(data) { this.buffer.append(data); while (true) { if (this.nextMessageLength === -1) { let headers = this.buffer.tryReadHeaders(); if (!headers) { return; } let contentLength = headers['Content-Length']; if (!contentLength) { throw new Error('Header must provide a Content-Length property.'); } let length = parseInt(contentLength); if (isNaN(length)) { throw new Error('Content-Length value must be a number.'); } this.nextMessageLength = length; // Take the encoding form the header. For compatibility // treat both utf-8 and utf8 as node utf8 } var msg = this.buffer.tryReadContent(this.nextMessageLength); if (msg === null) { /** We haven't recevied the full message yet. */ this.setPartialMessageTimer(); return; } this.clearPartialMessageTimer(); this.nextMessageLength = -1; this.messageToken++; var json = JSON.parse(msg); this.callback(json); } } clearPartialMessageTimer() { if (this.partialMessageTimer) { clearTimeout(this.partialMessageTimer); this.partialMessageTimer = undefined; } } setPartialMessageTimer() { this.clearPartialMessageTimer(); if (this._partialMessageTimeout <= 0) { return; } this.partialMessageTimer = 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.StreamMessageReader = StreamMessageReader; class IPCMessageReader extends 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); } } exports.IPCMessageReader = IPCMessageReader; class SocketMessageReader extends StreamMessageReader { constructor(socket, encoding = 'utf-8') { super(socket, encoding); } } exports.SocketMessageReader = SocketMessageReader; /***/ }), /***/ 7636: /***/ ((__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 events_1 = __webpack_require__(2403); const Is = __webpack_require__(1081); let ContentLength = 'Content-Length: '; let 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 recevied error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`); } } } exports.AbstractMessageWriter = AbstractMessageWriter; class StreamMessageWriter extends AbstractMessageWriter { constructor(writable, encoding = 'utf8') { super(); this.writable = writable; this.encoding = encoding; this.errorCount = 0; this.writable.on('error', (error) => this.fireError(error)); this.writable.on('close', () => this.fireClose()); } write(msg) { let json = JSON.stringify(msg); let contentLength = Buffer.byteLength(json, this.encoding); let headers = [ ContentLength, contentLength.toString(), CRLF, CRLF ]; try { // Header must be written in ASCII encoding this.writable.write(headers.join(''), 'ascii'); // Now write the content. This can be written in any encoding this.writable.write(json, this.encoding); this.errorCount = 0; } catch (error) { this.errorCount++; this.fireError(error, msg, this.errorCount); } } } exports.StreamMessageWriter = StreamMessageWriter; class IPCMessageWriter extends AbstractMessageWriter { constructor(process) { super(); this.process = process; this.errorCount = 0; this.queue = []; this.sending = false; let eventEmitter = this.process; eventEmitter.on('error', (error) => this.fireError(error)); eventEmitter.on('close', () => this.fireClose); } write(msg) { if (!this.sending && this.queue.length === 0) { // See https://github.com/nodejs/node/issues/7657 this.doWriteMessage(msg); } else { this.queue.push(msg); } } doWriteMessage(msg) { try { if (this.process.send) { this.sending = true; this.process.send(msg, undefined, undefined, (error) => { this.sending = false; if (error) { this.errorCount++; this.fireError(error, msg, this.errorCount); } else { this.errorCount = 0; } if (this.queue.length > 0) { this.doWriteMessage(this.queue.shift()); } }); } } catch (error) { this.errorCount++; this.fireError(error, msg, this.errorCount); } } } exports.IPCMessageWriter = IPCMessageWriter; class SocketMessageWriter extends AbstractMessageWriter { constructor(socket, encoding = 'utf8') { super(); this.socket = socket; this.queue = []; this.sending = false; this.encoding = encoding; this.errorCount = 0; this.socket.on('error', (error) => this.fireError(error)); this.socket.on('close', () => this.fireClose()); } write(msg) { if (!this.sending && this.queue.length === 0) { // See https://github.com/nodejs/node/issues/7657 this.doWriteMessage(msg); } else { this.queue.push(msg); } } doWriteMessage(msg) { let json = JSON.stringify(msg); let contentLength = Buffer.byteLength(json, this.encoding); let headers = [ ContentLength, contentLength.toString(), CRLF, CRLF ]; try { // Header must be written in ASCII encoding this.sending = true; this.socket.write(headers.join(''), 'ascii', (error) => { if (error) { this.handleError(error, msg); } try { // Now write the content. This can be written in any encoding this.socket.write(json, this.encoding, (error) => { this.sending = false; if (error) { this.handleError(error, msg); } else { this.errorCount = 0; } if (this.queue.length > 0) { this.doWriteMessage(this.queue.shift()); } }); } catch (error) { this.handleError(error, msg); } }); } catch (error) { this.handleError(error, msg); } } handleError(error, msg) { this.errorCount++; this.fireError(error, msg, this.errorCount); } } exports.SocketMessageWriter = SocketMessageWriter; /***/ }), /***/ 3722: /***/ ((__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 is = __webpack_require__(1081); /** * 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; ErrorCodes.serverErrorStart = -32099; ErrorCodes.serverErrorEnd = -32000; ErrorCodes.ServerNotInitialized = -32002; ErrorCodes.UnknownErrorCode = -32001; // Defined by the protocol. ErrorCodes.RequestCancelled = -32800; // Defined by VSCode library. ErrorCodes.MessageWriteError = 1; ErrorCodes.MessageReadError = 2; })(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; /** * An abstract implementation of a MessageType. */ class AbstractMessageType { constructor(_method, _numberOfParams) { this._method = _method; this._numberOfParams = _numberOfParams; } get method() { return this._method; } get numberOfParams() { return this._numberOfParams; } } exports.AbstractMessageType = AbstractMessageType; /** * Classes to type request response pairs */ class RequestType0 extends AbstractMessageType { constructor(method) { super(method, 0); this._ = undefined; } } exports.RequestType0 = RequestType0; class RequestType extends AbstractMessageType { constructor(method) { super(method, 1); this._ = undefined; } } exports.RequestType = RequestType; class RequestType1 extends AbstractMessageType { constructor(method) { super(method, 1); this._ = undefined; } } exports.RequestType1 = RequestType1; class RequestType2 extends AbstractMessageType { constructor(method) { super(method, 2); this._ = undefined; } } exports.RequestType2 = RequestType2; class RequestType3 extends AbstractMessageType { constructor(method) { super(method, 3); this._ = undefined; } } exports.RequestType3 = RequestType3; class RequestType4 extends AbstractMessageType { constructor(method) { super(method, 4); this._ = undefined; } } exports.RequestType4 = RequestType4; class RequestType5 extends AbstractMessageType { constructor(method) { super(method, 5); this._ = undefined; } } exports.RequestType5 = RequestType5; class RequestType6 extends AbstractMessageType { constructor(method) { super(method, 6); this._ = undefined; } } exports.RequestType6 = RequestType6; class RequestType7 extends AbstractMessageType { constructor(method) { super(method, 7); this._ = undefined; } } exports.RequestType7 = RequestType7; class RequestType8 extends AbstractMessageType { constructor(method) { super(method, 8); this._ = undefined; } } exports.RequestType8 = RequestType8; class RequestType9 extends AbstractMessageType { constructor(method) { super(method, 9); this._ = undefined; } } exports.RequestType9 = RequestType9; class NotificationType extends AbstractMessageType { constructor(method) { super(method, 1); this._ = undefined; } } exports.NotificationType = NotificationType; class NotificationType0 extends AbstractMessageType { constructor(method) { super(method, 0); this._ = undefined; } } exports.NotificationType0 = NotificationType0; class NotificationType1 extends AbstractMessageType { constructor(method) { super(method, 1); this._ = undefined; } } exports.NotificationType1 = NotificationType1; class NotificationType2 extends AbstractMessageType { constructor(method) { super(method, 2); this._ = undefined; } } exports.NotificationType2 = NotificationType2; class NotificationType3 extends AbstractMessageType { constructor(method) { super(method, 3); this._ = undefined; } } exports.NotificationType3 = NotificationType3; class NotificationType4 extends AbstractMessageType { constructor(method) { super(method, 4); this._ = undefined; } } exports.NotificationType4 = NotificationType4; class NotificationType5 extends AbstractMessageType { constructor(method) { super(method, 5); this._ = undefined; } } exports.NotificationType5 = NotificationType5; class NotificationType6 extends AbstractMessageType { constructor(method) { super(method, 6); this._ = undefined; } } exports.NotificationType6 = NotificationType6; class NotificationType7 extends AbstractMessageType { constructor(method) { super(method, 7); this._ = undefined; } } exports.NotificationType7 = NotificationType7; class NotificationType8 extends AbstractMessageType { constructor(method) { super(method, 8); this._ = undefined; } } exports.NotificationType8 = NotificationType8; class NotificationType9 extends AbstractMessageType { constructor(method) { super(method, 9); this._ = undefined; } } exports.NotificationType9 = NotificationType9; /** * Tests if the given message is a request message */ function isRequestMessage(message) { let 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) { let 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) { let candidate = message; return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null); } exports.isResponseMessage = isResponseMessage; /***/ }), /***/ 5362: /***/ ((__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 path_1 = __webpack_require__(5622); const os_1 = __webpack_require__(2087); const crypto_1 = __webpack_require__(6417); const net_1 = __webpack_require__(1631); const messageReader_1 = __webpack_require__(1160); const messageWriter_1 = __webpack_require__(7636); function generateRandomPipeName() { const randomSuffix = crypto_1.randomBytes(21).toString('hex'); if (process.platform === 'win32') { return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`; } else { // Mac/Unix: use socket file return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`); } } exports.generateRandomPipeName = generateRandomPipeName; function createClientPipeTransport(pipeName, encoding = 'utf-8') { let connectResolve; let connected = new Promise((resolve, _reject) => { connectResolve = resolve; }); return new Promise((resolve, reject) => { let server = net_1.createServer((socket) => { server.close(); connectResolve([ new messageReader_1.SocketMessageReader(socket, encoding), new messageWriter_1.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 messageReader_1.SocketMessageReader(socket, encoding), new messageWriter_1.SocketMessageWriter(socket, encoding) ]; } exports.createServerPipeTransport = createServerPipeTransport; /***/ }), /***/ 4502: /***/ ((__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 net_1 = __webpack_require__(1631); const messageReader_1 = __webpack_require__(1160); const messageWriter_1 = __webpack_require__(7636); function createClientSocketTransport(port, encoding = 'utf-8') { let connectResolve; let connected = new Promise((resolve, _reject) => { connectResolve = resolve; }); return new Promise((resolve, reject) => { let server = net_1.createServer((socket) => { server.close(); connectResolve([ new messageReader_1.SocketMessageReader(socket, encoding), new messageWriter_1.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 messageReader_1.SocketMessageReader(socket, encoding), new messageWriter_1.SocketMessageWriter(socket, encoding) ]; } exports.createServerSocketTransport = createServerSocketTransport; /***/ }), /***/ 7014: /***/ ((__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. * ------------------------------------------------------------------------------------------ */ function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode_1 = __webpack_require__(7549); const vscode_languageserver_protocol_1 = __webpack_require__(5310); const c2p = __webpack_require__(2639); const p2c = __webpack_require__(8899); const Is = __webpack_require__(4797); const async_1 = __webpack_require__(4834); const UUID = __webpack_require__(8861); __export(__webpack_require__(5310)); class ConsoleLogger { error(message) { console.error(message); } warn(message) { console.warn(message); } info(message) { console.info(message); } log(message) { console.log(message); } } function createConnection(input, output, errorHandler, closeHandler) { let logger = new ConsoleLogger(); let connection = vscode_languageserver_protocol_1.createProtocolConnection(input, output, logger); 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), trace: (value, tracer, sendNotificationOrTraceOptions) => { const defaultTraceOptions = { sendNotification: false, traceFormat: vscode_languageserver_protocol_1.TraceFormat.Text }; if (sendNotificationOrTraceOptions === void 0) { 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), 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) { this.name = name; 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 < 5) { 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 5 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 ]; function ensure(target, key) { if (target[key] === void 0) { target[key] = {}; } return target[key]; } 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.messages !== void 0; } DynamicFeature.is = is; })(DynamicFeature || (DynamicFeature = {})); class DocumentNotifiactions { 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(_message, 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; } } } class DidOpenTextDocumentFeature extends DocumentNotifiactions { constructor(client, _syncedDocuments) { super(client, vscode_1.workspace.onDidOpenTextDocument, vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, client.clientOptions.middleware.didOpen, (textDocument) => client.code2ProtocolConverter.asOpenTextDocumentParams(textDocument), DocumentNotifiactions.textDocumentFilter); this._syncedDocuments = _syncedDocuments; } get messages() { return vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } register(message, data) { super.register(message, 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 DocumentNotifiactions { constructor(client, _syncedDocuments) { super(client, vscode_1.workspace.onDidCloseTextDocument, vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, client.clientOptions.middleware.didClose, (textDocument) => client.code2ProtocolConverter.asCloseTextDocumentParams(textDocument), DocumentNotifiactions.textDocumentFilter); this._syncedDocuments = _syncedDocuments; } get messages() { 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(this.messages, { 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 messages() { 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 !== void 0 && textDocumentSyncOptions.change !== vscode_languageserver_protocol_1.TextDocumentSyncKind.None) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, { syncKind: textDocumentSyncOptions.change }) }); } } register(_message, 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 / undirty 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; } } } class WillSaveFeature extends DocumentNotifiactions { 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) => DocumentNotifiactions.textDocumentFilter(selectors, willSaveEvent.document)); } get messages() { 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(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } } class WillSaveWaitUntilFeature { constructor(_client) { this._client = _client; this._selectors = new Map(); } get messages() { 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(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } register(_message, 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 (DocumentNotifiactions.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 === void 0 ? [] : 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 DocumentNotifiactions { 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), DocumentNotifiactions.textDocumentFilter); } get messages() { return vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').didSave = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.save) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, { includeText: !!textDocumentSyncOptions.save.includeText }) }); } } register(method, data) { this._includeText = !!data.registerOptions.includeText; super.register(method, data); } } class FileSystemWatcherFeature { constructor(_client, _notifyFileEvent) { this._client = _client; this._notifyFileEvent = _notifyFileEvent; this._watchers = new Map(); } get messages() { return vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'workspace'), 'didChangeWatchedFiles').dynamicRegistration = true; } initialize(_capabilities, _documentSelector) { } register(_method, data) { if (!Array.isArray(data.registerOptions.watchers)) { return; } let disposeables = []; for (let watcher of data.registerOptions.watchers) { if (!Is.string(watcher.globPattern)) { continue; } let watchCreate = true, watchChange = true, watchDelete = true; if (watcher.kind !== void 0 && 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); disposeables.push(fileSystemWatcher); } this._watchers.set(data.id, disposeables); } registerRaw(id, fileSystemWatchers) { let disposeables = []; for (let fileSystemWatcher of fileSystemWatchers) { this.hookListeners(fileSystemWatcher, true, true, true, disposeables); } this._watchers.set(id, disposeables); } 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 disposeables = this._watchers.get(id); if (disposeables) { for (let disposable of disposeables) { disposable.dispose(); } } } dispose() { this._watchers.forEach((disposeables) => { for (let disposable of disposeables) { disposable.dispose(); } }); this._watchers.clear(); } } class TextDocumentFeature { constructor(_client, _message) { this._client = _client; this._message = _message; this._providers = new Map(); } get messages() { return this._message; } register(message, data) { if (message.method !== this.messages.method) { throw new Error(`Register called on wrong feature. Requested ${message.method} but reached feature ${this.messages.method}`); } if (!data.registerOptions.documentSelector) { return; } let provider = this.registerLanguageProvider(data.registerOptions); if (provider) { this._providers.set(data.id, provider); } } unregister(id) { let provider = this._providers.get(id); if (provider) { provider.dispose(); } } dispose() { this._providers.forEach((value) => { value.dispose(); }); this._providers.clear(); } } exports.TextDocumentFeature = TextDocumentFeature; class WorkspaceFeature { constructor(_client, _message) { this._client = _client; this._message = _message; this._providers = new Map(); } get messages() { return this._message; } register(message, data) { if (message.method !== this.messages.method) { throw new Error(`Register called on wron feature. Requested ${message.method} but reached feature ${this.messages.method}`); } let provider = this.registerLanguageProvider(data.registerOptions); if (provider) { this._providers.set(data.id, provider); } } unregister(id) { let provider = this._providers.get(id); if (provider) { provider.dispose(); } } dispose() { this._providers.forEach((value) => { value.dispose(); }); this._providers.clear(); } } class CompletionItemFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.CompletionRequest.type); } fillClientCapabilities(capabilites) { let completion = ensure(ensure(capabilites, '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 }; completion.completionItemKind = { valueSet: SupportedCompletionItemKinds }; } initialize(capabilities, documentSelector) { if (!capabilities.completionProvider || !documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, capabilities.completionProvider) }); } registerLanguageProvider(options) { let triggerCharacters = options.triggerCharacters || []; let client = this._client; let 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) => { client.logFailedRequest(vscode_languageserver_protocol_1.CompletionRequest.type, error); return Promise.resolve([]); }); }; let resolveCompletionItem = (item, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, client.code2ProtocolConverter.asCompletionItem(item), token).then(client.protocol2CodeConverter.asCompletionItem, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, error); return Promise.resolve(item); }); }; let middleware = this._client.clientOptions.middleware; return vscode_1.languages.registerCompletionItemProvider(options.documentSelector, { provideCompletionItems: (document, position, token, context) => { return middleware.provideCompletionItem ? middleware.provideCompletionItem(document, position, context, token, provideCompletionItems) : provideCompletionItems(document, position, context, token); }, resolveCompletionItem: options.resolveProvider ? (item, token) => { return middleware.resolveCompletionItem ? middleware.resolveCompletionItem(item, token, resolveCompletionItem) : resolveCompletionItem(item, token); } : undefined }, ...triggerCharacters); } } class HoverFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.HoverRequest.type); } fillClientCapabilities(capabilites) { const hoverCapability = (ensure(ensure(capabilites, 'textDocument'), 'hover')); hoverCapability.dynamicRegistration = true; hoverCapability.contentFormat = [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText]; } initialize(capabilities, documentSelector) { if (!capabilities.hoverProvider || !documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }) }); } registerLanguageProvider(options) { let client = this._client; let provideHover = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.HoverRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asHover, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.HoverRequest.type, error); return Promise.resolve(null); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerHoverProvider(options.documentSelector, { provideHover: (document, position, token) => { return middleware.provideHover ? middleware.provideHover(document, position, token, provideHover) : provideHover(document, position, token); } }); } } class SignatureHelpFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.SignatureHelpRequest.type); } fillClientCapabilities(capabilites) { let config = ensure(ensure(capabilites, '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 }; } initialize(capabilities, documentSelector) { if (!capabilities.signatureHelpProvider || !documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, capabilities.signatureHelpProvider) }); } registerLanguageProvider(options) { let client = this._client; let providerSignatureHelp = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asSignatureHelp, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, error); return Promise.resolve(null); }); }; let middleware = client.clientOptions.middleware; let triggerCharacters = options.triggerCharacters || []; return vscode_1.languages.registerSignatureHelpProvider(options.documentSelector, { provideSignatureHelp: (document, position, token) => { return middleware.provideSignatureHelp ? middleware.provideSignatureHelp(document, position, token, providerSignatureHelp) : providerSignatureHelp(document, position, token); } }, ...triggerCharacters); } } class DefinitionFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DefinitionRequest.type); } fillClientCapabilities(capabilites) { let definitionSupport = ensure(ensure(capabilites, 'textDocument'), 'definition'); definitionSupport.dynamicRegistration = true; definitionSupport.linkSupport = true; } initialize(capabilities, documentSelector) { if (!capabilities.definitionProvider || !documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }) }); } registerLanguageProvider(options) { let client = this._client; let provideDefinition = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDefinitionResult, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, error); return Promise.resolve(null); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerDefinitionProvider(options.documentSelector, { provideDefinition: (document, position, token) => { return middleware.provideDefinition ? middleware.provideDefinition(document, position, token, provideDefinition) : provideDefinition(document, position, token); } }); } } class ReferencesFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.ReferencesRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'references').dynamicRegistration = true; } initialize(capabilities, documentSelector) { if (!capabilities.referencesProvider || !documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }) }); } registerLanguageProvider(options) { let client = this._client; let 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) => { client.logFailedRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, error); return Promise.resolve([]); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerReferenceProvider(options.documentSelector, { provideReferences: (document, position, options, token) => { return middleware.provideReferences ? middleware.provideReferences(document, position, options, token, providerReferences) : providerReferences(document, position, options, token); } }); } } class DocumentHighlightFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentHighlightRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'documentHighlight').dynamicRegistration = true; } initialize(capabilities, documentSelector) { if (!capabilities.documentHighlightProvider || !documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }) }); } registerLanguageProvider(options) { let client = this._client; let provideDocumentHighlights = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDocumentHighlights, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, error); return Promise.resolve([]); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerDocumentHighlightProvider(options.documentSelector, { provideDocumentHighlights: (document, position, token) => { return middleware.provideDocumentHighlights ? middleware.provideDocumentHighlights(document, position, token, provideDocumentHighlights) : provideDocumentHighlights(document, position, token); } }); } } class DocumentSymbolFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentSymbolRequest.type); } fillClientCapabilities(capabilites) { let symbolCapabilities = ensure(ensure(capabilites, 'textDocument'), 'documentSymbol'); symbolCapabilities.dynamicRegistration = true; symbolCapabilities.symbolKind = { valueSet: SupportedSymbolKinds }; symbolCapabilities.hierarchicalDocumentSymbolSupport = true; } initialize(capabilities, documentSelector) { if (!capabilities.documentSymbolProvider || !documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }) }); } registerLanguageProvider(options) { let client = this._client; let 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) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, error); return Promise.resolve([]); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerDocumentSymbolProvider(options.documentSelector, { provideDocumentSymbols: (document, token) => { return middleware.provideDocumentSymbols ? middleware.provideDocumentSymbols(document, token, provideDocumentSymbols) : provideDocumentSymbols(document, token); } }); } } class WorkspaceSymbolFeature extends WorkspaceFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type); } fillClientCapabilities(capabilites) { let symbolCapabilities = ensure(ensure(capabilites, 'workspace'), 'symbol'); symbolCapabilities.dynamicRegistration = true; symbolCapabilities.symbolKind = { valueSet: SupportedSymbolKinds }; } initialize(capabilities) { if (!capabilities.workspaceSymbolProvider) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: undefined }); } registerLanguageProvider(_options) { let client = this._client; let provideWorkspaceSymbols = (query, token) => { return client.sendRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, { query }, token).then(client.protocol2CodeConverter.asSymbolInformations, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, error); return Promise.resolve([]); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerWorkspaceSymbolProvider({ provideWorkspaceSymbols: (query, token) => { return middleware.provideWorkspaceSymbols ? middleware.provideWorkspaceSymbols(query, token, provideWorkspaceSymbols) : provideWorkspaceSymbols(query, token); } }); } } class CodeActionFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.CodeActionRequest.type); } fillClientCapabilities(capabilites) { const cap = ensure(ensure(capabilites, 'textDocument'), 'codeAction'); cap.dynamicRegistration = true; cap.codeActionLiteralSupport = { codeActionKind: { valueSet: [ '', 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 ] } }; } initialize(capabilities, documentSelector) { if (!capabilities.codeActionProvider || !documentSelector) { return; } let codeActionKinds = undefined; if (!Is.boolean(capabilities.codeActionProvider)) { codeActionKinds = capabilities.codeActionProvider.codeActionKinds; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector, codeActionKinds } }); } registerLanguageProvider(options) { let client = this._client; let provideCodeActions = (document, range, context, token) => { let 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; } let 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) => { client.logFailedRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, error); return Promise.resolve([]); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerCodeActionsProvider(options.documentSelector, { provideCodeActions: (document, range, context, token) => { return middleware.provideCodeActions ? middleware.provideCodeActions(document, range, context, token, provideCodeActions) : provideCodeActions(document, range, context, token); } }, options.codeActionKinds ? { providedCodeActionKinds: client.protocol2CodeConverter.asCodeActionKinds(options.codeActionKinds) } : undefined); } } class CodeLensFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.CodeLensRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'codeLens').dynamicRegistration = true; } initialize(capabilities, documentSelector) { if (!capabilities.codeLensProvider || !documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, capabilities.codeLensProvider) }); } registerLanguageProvider(options) { let client = this._client; let provideCodeLenses = (document, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, client.code2ProtocolConverter.asCodeLensParams(document), token).then(client.protocol2CodeConverter.asCodeLenses, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, error); return Promise.resolve([]); }); }; let resolveCodeLens = (codeLens, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, client.code2ProtocolConverter.asCodeLens(codeLens), token).then(client.protocol2CodeConverter.asCodeLens, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, error); return codeLens; }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerCodeLensProvider(options.documentSelector, { provideCodeLenses: (document, token) => { return middleware.provideCodeLenses ? middleware.provideCodeLenses(document, token, provideCodeLenses) : provideCodeLenses(document, token); }, resolveCodeLens: (options.resolveProvider) ? (codeLens, token) => { return middleware.resolveCodeLens ? middleware.resolveCodeLens(codeLens, token, resolveCodeLens) : resolveCodeLens(codeLens, token); } : undefined }); } } class DocumentFormattingFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentFormattingRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'formatting').dynamicRegistration = true; } initialize(capabilities, documentSelector) { if (!capabilities.documentFormattingProvider || !documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }) }); } registerLanguageProvider(options) { let client = this._client; let provideDocumentFormattingEdits = (document, options, token) => { let params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), options: client.code2ProtocolConverter.asFormattingOptions(options) }; return client.sendRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, error); return Promise.resolve([]); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerDocumentFormattingEditProvider(options.documentSelector, { provideDocumentFormattingEdits: (document, options, token) => { return middleware.provideDocumentFormattingEdits ? middleware.provideDocumentFormattingEdits(document, options, token, provideDocumentFormattingEdits) : provideDocumentFormattingEdits(document, options, token); } }); } } class DocumentRangeFormattingFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'rangeFormatting').dynamicRegistration = true; } initialize(capabilities, documentSelector) { if (!capabilities.documentRangeFormattingProvider || !documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }) }); } registerLanguageProvider(options) { let client = this._client; let provideDocumentRangeFormattingEdits = (document, range, options, token) => { let params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), range: client.code2ProtocolConverter.asRange(range), options: client.code2ProtocolConverter.asFormattingOptions(options) }; return client.sendRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, error); return Promise.resolve([]); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerDocumentRangeFormattingEditProvider(options.documentSelector, { provideDocumentRangeFormattingEdits: (document, range, options, token) => { return middleware.provideDocumentRangeFormattingEdits ? middleware.provideDocumentRangeFormattingEdits(document, range, options, token, provideDocumentRangeFormattingEdits) : provideDocumentRangeFormattingEdits(document, range, options, token); } }); } } class DocumentOnTypeFormattingFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'onTypeFormatting').dynamicRegistration = true; } initialize(capabilities, documentSelector) { if (!capabilities.documentOnTypeFormattingProvider || !documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, capabilities.documentOnTypeFormattingProvider) }); } registerLanguageProvider(options) { let client = this._client; let moreTriggerCharacter = options.moreTriggerCharacter || []; let 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) }; return client.sendRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, error); return Promise.resolve([]); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerOnTypeFormattingEditProvider(options.documentSelector, { provideOnTypeFormattingEdits: (document, position, ch, options, token) => { return middleware.provideOnTypeFormattingEdits ? middleware.provideOnTypeFormattingEdits(document, position, ch, options, token, provideOnTypeFormattingEdits) : provideOnTypeFormattingEdits(document, position, ch, options, token); } }, options.firstTriggerCharacter, ...moreTriggerCharacter); } } class RenameFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.RenameRequest.type); } fillClientCapabilities(capabilites) { let rename = ensure(ensure(capabilites, 'textDocument'), 'rename'); rename.dynamicRegistration = true; rename.prepareSupport = true; } initialize(capabilities, documentSelector) { if (!capabilities.renameProvider || !documentSelector) { return; } let options = Object.assign({}, { documentSelector: documentSelector }); if (Is.boolean(capabilities.renameProvider)) { options.prepareProvider = false; } else { options.prepareProvider = capabilities.renameProvider.prepareProvider; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { let client = this._client; let 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) => { client.logFailedRequest(vscode_languageserver_protocol_1.RenameRequest.type, error); return Promise.reject(new Error(error.message)); }); }; let 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 (result && result.range) { return { range: client.protocol2CodeConverter.asRange(result.range), placeholder: result.placeholder }; } return null; }, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, error); return Promise.reject(new Error(error.message)); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerRenameProvider(options.documentSelector, { provideRenameEdits: (document, position, newName, token) => { return middleware.provideRenameEdits ? middleware.provideRenameEdits(document, position, newName, token, provideRenameEdits) : provideRenameEdits(document, position, newName, token); }, prepareRename: options.prepareProvider ? (document, position, token) => { return middleware.prepareRename ? middleware.prepareRename(document, position, token, prepareRename) : prepareRename(document, position, token); } : undefined }); } } class DocumentLinkFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentLinkRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'documentLink').dynamicRegistration = true; } initialize(capabilities, documentSelector) { if (!capabilities.documentLinkProvider || !documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, capabilities.documentLinkProvider) }); } registerLanguageProvider(options) { let client = this._client; let provideDocumentLinks = (document, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, client.code2ProtocolConverter.asDocumentLinkParams(document), token).then(client.protocol2CodeConverter.asDocumentLinks, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, error); Promise.resolve(new Error(error.message)); }); }; let resolveDocumentLink = (link, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, client.code2ProtocolConverter.asDocumentLink(link), token).then(client.protocol2CodeConverter.asDocumentLink, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, error); Promise.resolve(new Error(error.message)); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerDocumentLinkProvider(options.documentSelector, { provideDocumentLinks: (document, token) => { return middleware.provideDocumentLinks ? middleware.provideDocumentLinks(document, token, provideDocumentLinks) : provideDocumentLinks(document, token); }, resolveDocumentLink: options.resolveProvider ? (link, token) => { return middleware.resolveDocumentLink ? middleware.resolveDocumentLink(link, token, resolveDocumentLink) : resolveDocumentLink(link, token); } : undefined }); } } class ConfigurationFeature { constructor(_client) { this._client = _client; this._listeners = new Map(); } get messages() { 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 !== void 0) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { section: section } }); } } register(_message, data) { let disposable = vscode_1.workspace.onDidChangeConfiguration((event) => { this.onDidChangeConfiguration(data.registerOptions.section, event); }); this._listeners.set(data.id, disposable); if (data.registerOptions.section !== void 0) { 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 !== void 0 && event !== void 0) { let affected = sections.some((section) => event.affectsConfiguration(section)); if (!affected) { return; } } let didChangeConfiguration = (sections) => { if (sections === void 0) { 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(key, resource); } if (config) { let path = keys[i].split('.'); ensurePath(result, path)[path[path.length - 1]] = 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 messages() { return vscode_languageserver_protocol_1.ExecuteCommandRequest.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'workspace'), 'executeCommand').dynamicRegistration = true; } initialize(capabilities) { if (!capabilities.executeCommandProvider) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, capabilities.executeCommandProvider) }); } register(_message, data) { let client = this._client; if (data.registerOptions.commands) { let disposeables = []; for (const command of data.registerOptions.commands) { disposeables.push(vscode_1.commands.registerCommand(command, (...args) => { let params = { command, arguments: args }; return client.sendRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, params).then(undefined, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, error); }); })); } this._commands.set(data.id, disposeables); } } unregister(id) { let disposeables = this._commands.get(id); if (disposeables) { disposeables.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) { this._traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text; this._features = []; this._method2Message = new Map(); this._dynamicFeatures = new Map(); this._id = id; this._name = name; clientOptions = clientOptions || {}; 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, errorHandler: clientOptions.errorHandler || new DefaultErrorHandler(this._name), middleware: clientOptions.middleware || {}, uriConverters: clientOptions.uriConverters, workspaceFolder: clientOptions.workspaceFolder }; 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._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._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._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 { 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 { this._resolvedConnection.onNotification(type, handler); } catch (error) { this.error(`Registering notification handler ${Is.string(type) ? type : type.method} 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 diagnostics() { return this._diagnostics; } createDefaultErrorHandler() { return new DefaultErrorHandler(this._name); } 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) { this.outputChannel.appendLine(`[Info - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.outputChannel.appendLine(this.data2String(data)); } if (this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Info) { this.outputChannel.show(true); } } warn(message, data) { this.outputChannel.appendLine(`[Warn - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.outputChannel.appendLine(this.data2String(data)); } if (this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Warn) { this.outputChannel.show(true); } } error(message, data) { this.outputChannel.appendLine(`[Error - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.outputChannel.appendLine(this.data2String(data)); } if (this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Error) { this.outputChannel.show(true); } } logTrace(message, data) { this.outputChannel.appendLine(`[Trace - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.outputChannel.appendLine(this.data2String(data)); } } logObjectTrace(data) { if (data.isLSPMessage && data.type) { this.outputChannel.append(`[LSP - ${(new Date().toLocaleTimeString())}] `); } else { this.outputChannel.append(`[Trace - ${(new Date().toLocaleTimeString())}] `); } if (data) { this.outputChannel.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); break; case vscode_languageserver_protocol_1.MessageType.Warning: this.warn(message.message); break; case vscode_languageserver_protocol_1.MessageType.Info: this.info(message.message); 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.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: process.pid, 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); 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 !== void 0 && 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); } }); } _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(); // unhook listeners return this._onStop = this.resolveConnection().then(connection => { return connection.shutdown().then(() => { connection.exit(); connection.dispose(); this.state = ClientState.Stopped; 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 (let handler of this._dynamicFeatures.values()) { handler.dispose(); } if (channel && this._outputChannel && this._disposeOutputChannel) { this._outputChannel.dispose(); this._outputChannel = undefined; } if (diagnostics && this._diagnostics) { this._diagnostics.dispose(); this._diagnostics = undefined; } } notifyFileEvent(event) { this._fileEvents.push(event); this._fileEventDelayer.trigger(() => { this.onReady().then(() => { this.resolveConnection().then(connection => { if (this.isConnectionActive()) { connection.didChangeWatchedFiles({ changes: this._fileEvents }); } this._fileEvents = []; }); }, (error) => { this.error(`Notify file events failed.`, error); }); }); } forceDocumentSync() { this._dynamicFeatures.get(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type.method).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.handleDiagnostics; if (middleware) { middleware(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); }); } 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.'); 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)) { let messages = feature.messages; if (Array.isArray(messages)) { for (let message of messages) { this._method2Message.set(message.method, message); this._dynamicFeatures.set(message.method, feature); } } else { this._method2Message.set(messages.method, messages); this._dynamicFeatures.set(messages.method, feature); } } } 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() { let result = {}; ensure(result, 'workspace').applyEdit = true; let 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; ensure(ensure(result, 'textDocument'), 'publishDiagnostics').relatedInformation = true; 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 (let registration of params.registrations) { const feature = this._dynamicFeatures.get(registration.method); if (!feature) { 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 }; feature.register(this._method2Message.get(registration.method), data); } 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 vscode_1.workspace.applyEdit(this._p2c.asWorkspaceEdit(params.edit)).then((value) => { return { applied: value }; }); } ; logFailedRequest(type, error) { // If we get a request cancel don't log anything. if (error instanceof vscode_languageserver_protocol_1.ResponseError && error.code === vscode_languageserver_protocol_1.ErrorCodes.RequestCancelled) { return; } this.error(`Request ${type.method} failed.`, error); } } exports.BaseLanguageClient = BaseLanguageClient; /***/ }), /***/ 2639: /***/ ((__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__(7549); const proto = __webpack_require__(5310); const Is = __webpack_require__(4797); const protocolCompletionItem_1 = __webpack_require__(3810); const protocolCodeLens_1 = __webpack_require__(3780); const protocolDocumentLink_1 = __webpack_require__(6380); 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: asVersionedTextDocumentIdentifier(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 asTextDocumentPositionParams(textDocument, position) { return { textDocument: asTextDocumentIdentifier(textDocument), position: asWorkerPosition(position) }; } function asTriggerKind(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: asTriggerKind(context.triggerKind), triggerCharacter: context.triggerCharacter } }; } function asWorkerPosition(position) { return { line: position.line, character: position.character }; } function asPosition(value) { if (value === void 0) { return undefined; } else if (value === null) { return null; } return { line: value.line, character: value.character }; } function asRange(value) { if (value === void 0 || value === null) { return value; } return { start: asPosition(value.start), end: asPosition(value.end) }; } 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 asDiagnostic(item) { let result = proto.Diagnostic.create(asRange(item.range), item.message); if (Is.number(item.severity)) { result.severity = asDiagnosticSeverity(item.severity); } if (Is.number(item.code) || Is.string(item.code)) { result.code = item.code; } if (item.source) { result.source = item.source; } return result; } function asDiagnostics(items) { if (items === void 0 || 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 asCompletionItemKind(value, original) { if (original !== void 0) { 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; } if (protocolItem) { if (protocolItem.data !== void 0) { result.data = protocolItem.data; } if (protocolItem.deprecated === true || protocolItem.deprecated === false) { result.deprecated = protocolItem.deprecated; } } return result; } function fillPrimaryInsertText(target, source) { let format = proto.InsertTextFormat.PlainText; let text; let range = undefined; if (source.textEdit) { text = source.textEdit.newText; range = asRange(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 = asRange(source.range); } target.insertTextFormat = format; if (source.fromEdit && text && range) { target.textEdit = { newText: text, range: range }; } else { target.insertText = text; } } function asTextEdit(edit) { return { range: asRange(edit.range), newText: edit.newText }; } function asTextEdits(edits) { if (edits === void 0 || edits === null) { return edits; } return edits.map(asTextEdit); } function asReferenceParams(textDocument, position, options) { return { textDocument: asTextDocumentIdentifier(textDocument), position: asWorkerPosition(position), context: { includeDeclaration: options.includeDeclaration } }; } function asCodeActionContext(context) { if (context === void 0 || context === null) { return context; } return proto.CodeActionContext.create(asDiagnostics(context.diagnostics), Is.string(context.only) ? [context.only] : undefined); } 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(item) { return { tabSize: item.tabSize, insertSpaces: item.insertSpaces }; } 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); } 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) }; } return { asUri, asTextDocumentIdentifier, asVersionedTextDocumentIdentifier, asOpenTextDocumentParams, asChangeTextDocumentParams, asCloseTextDocumentParams, asSaveTextDocumentParams, asWillSaveTextDocumentParams, asTextDocumentPositionParams, asCompletionParams, asWorkerPosition, asRange, asPosition, asDiagnosticSeverity, asDiagnostic, asDiagnostics, asCompletionItem, asTextEdit, asReferenceParams, asCodeActionContext, asCommand, asCodeLens, asFormattingOptions, asDocumentSymbolParams, asCodeLensParams, asDocumentLink, asDocumentLinkParams }; } exports.createConverter = createConverter; /***/ }), /***/ 2014: /***/ ((__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 UUID = __webpack_require__(8861); const Is = __webpack_require__(4797); const vscode_1 = __webpack_require__(7549); const vscode_languageserver_protocol_1 = __webpack_require__(5310); const client_1 = __webpack_require__(7014); 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(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'colorProvider').dynamicRegistration = true; } initialize(capabilities, documentSelector) { if (!capabilities.colorProvider) { return; } const implCapabilities = capabilities.colorProvider; const id = Is.string(implCapabilities.id) && implCapabilities.id.length > 0 ? implCapabilities.id : UUID.generateUuid(); const selector = implCapabilities.documentSelector || documentSelector; if (selector) { this.register(this.messages, { id, registerOptions: Object.assign({}, { documentSelector: selector }) }); } } registerLanguageProvider(options) { let client = this._client; let 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) => { client.logFailedRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, error); return Promise.resolve(null); }); }; let 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) => { client.logFailedRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, error); return Promise.resolve(null); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerColorProvider(options.documentSelector, { provideColorPresentations: (color, context, token) => { return middleware.provideColorPresentations ? middleware.provideColorPresentations(color, context, token, provideColorPresentations) : provideColorPresentations(color, context, token); }, provideDocumentColors: (document, token) => { return middleware.provideDocumentColors ? middleware.provideDocumentColors(document, token, provideDocumentColors) : provideDocumentColors(document, token); } }); } 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; /***/ }), /***/ 1877: /***/ ((__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_1 = __webpack_require__(7549); const vscode_languageserver_protocol_1 = __webpack_require__(5310); 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 = vscode_1.workspace.getConfiguration(undefined, resource).get(section); } else { let config = vscode_1.workspace.getConfiguration(section.substr(0, index)); if (config) { result = 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] = config.get(key); } } } if (!result) { return null; } return result; } } exports.ConfigurationFeature = ConfigurationFeature; /***/ }), /***/ 5874: /***/ ((__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 UUID = __webpack_require__(8861); const Is = __webpack_require__(4797); const vscode_1 = __webpack_require__(7549); const vscode_languageserver_protocol_1 = __webpack_require__(5310); const client_1 = __webpack_require__(7014); 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(capabilites) { let declarationSupport = ensure(ensure(capabilites, 'textDocument'), 'declaration'); declarationSupport.dynamicRegistration = true; declarationSupport.linkSupport = true; } initialize(capabilities, documentSelector) { if (!capabilities.declarationProvider) { return; } if (capabilities.declarationProvider === true) { if (!documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }) }); } else { const declCapabilities = capabilities.declarationProvider; const id = Is.string(declCapabilities.id) && declCapabilities.id.length > 0 ? declCapabilities.id : UUID.generateUuid(); const selector = declCapabilities.documentSelector || documentSelector; if (selector) { this.register(this.messages, { id, registerOptions: Object.assign({}, { documentSelector: selector }) }); } } } registerLanguageProvider(options) { let client = this._client; let provideDeclaration = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDeclarationResult, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, error); return Promise.resolve(null); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerDeclarationProvider(options.documentSelector, { provideDeclaration: (document, position, token) => { return middleware.provideDeclaration ? middleware.provideDeclaration(document, position, token, provideDeclaration) : provideDeclaration(document, position, token); } }); } } exports.DeclarationFeature = DeclarationFeature; /***/ }), /***/ 9882: /***/ ((__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 UUID = __webpack_require__(8861); const Is = __webpack_require__(4797); const vscode_1 = __webpack_require__(7549); const vscode_languageserver_protocol_1 = __webpack_require__(5310); const client_1 = __webpack_require__(7014); 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(capabilites) { let capability = ensure(ensure(capabilites, 'textDocument'), 'foldingRange'); capability.dynamicRegistration = true; capability.rangeLimit = 5000; capability.lineFoldingOnly = true; } initialize(capabilities, documentSelector) { if (!capabilities.foldingRangeProvider) { return; } const implCapabilities = capabilities.foldingRangeProvider; const id = Is.string(implCapabilities.id) && implCapabilities.id.length > 0 ? implCapabilities.id : UUID.generateUuid(); const selector = implCapabilities.documentSelector || documentSelector; if (selector) { this.register(this.messages, { id, registerOptions: Object.assign({}, { documentSelector: selector }) }); } } registerLanguageProvider(options) { let client = this._client; let provideFoldingRanges = (document, _, token) => { const requestParams = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document) }; return client.sendRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, requestParams, token).then(this.asFoldingRanges.bind(this), (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, error); return Promise.resolve(null); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerFoldingRangeProvider(options.documentSelector, { provideFoldingRanges(document, context, token) { return middleware.provideFoldingRanges ? middleware.provideFoldingRanges(document, context, token, provideFoldingRanges) : provideFoldingRanges(document, context, token); } }); } 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; } asFoldingRanges(foldingRanges) { if (Array.isArray(foldingRanges)) { return foldingRanges.map(r => { return new vscode_1.FoldingRange(r.startLine, r.endLine, this.asFoldingRangeKind(r.kind)); }); } return []; } } exports.FoldingRangeFeature = FoldingRangeFeature; /***/ }), /***/ 1133: /***/ ((__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 UUID = __webpack_require__(8861); const Is = __webpack_require__(4797); const vscode_1 = __webpack_require__(7549); const vscode_languageserver_protocol_1 = __webpack_require__(5310); const client_1 = __webpack_require__(7014); 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(capabilites) { let implementationSupport = ensure(ensure(capabilites, 'textDocument'), 'implementation'); implementationSupport.dynamicRegistration = true; implementationSupport.linkSupport = true; } initialize(capabilities, documentSelector) { if (!capabilities.implementationProvider) { return; } if (capabilities.implementationProvider === true) { if (!documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }) }); } else { const implCapabilities = capabilities.implementationProvider; const id = Is.string(implCapabilities.id) && implCapabilities.id.length > 0 ? implCapabilities.id : UUID.generateUuid(); const selector = implCapabilities.documentSelector || documentSelector; if (selector) { this.register(this.messages, { id, registerOptions: Object.assign({}, { documentSelector: selector }) }); } } } registerLanguageProvider(options) { let client = this._client; let provideImplementation = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDefinitionResult, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, error); return Promise.resolve(null); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerImplementationProvider(options.documentSelector, { provideImplementation: (document, position, token) => { return middleware.provideImplementation ? middleware.provideImplementation(document, position, token, provideImplementation) : provideImplementation(document, position, token); } }); } } exports.ImplementationFeature = ImplementationFeature; /***/ }), /***/ 3094: /***/ ((__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. * ------------------------------------------------------------------------------------------ */ function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", ({ value: true })); const cp = __webpack_require__(3129); const fs = __webpack_require__(5747); const SemVer = __webpack_require__(2751); const client_1 = __webpack_require__(7014); const vscode_1 = __webpack_require__(7549); const vscode_languageserver_protocol_1 = __webpack_require__(5310); const colorProvider_1 = __webpack_require__(2014); const configuration_1 = __webpack_require__(1877); const implementation_1 = __webpack_require__(1133); const typeDefinition_1 = __webpack_require__(1505); const workspaceFolders_1 = __webpack_require__(4484); const foldingRange_1 = __webpack_require__(9882); const declaration_1 = __webpack_require__(5874); const Is = __webpack_require__(4797); const processes_1 = __webpack_require__(4108); __export(__webpack_require__(7014)); const REQUIRED_VSCODE_VERSION = '^1.30'; // 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 client_1.BaseLanguageClient { 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(); } createMessageTransports(encoding) { function getEnvironment(env) { if (!env) { return process.env; } let result = Object.create(null); Object.keys(process.env).forEach(key => result[key] = process.env[key]); Object.keys(env).forEach(key => result[key] = env[key]); return result; } function startedInDebugMode() { let args = process.execArgv; if (args) { return args.some((arg) => /^--debug=?/.test(arg) || /^--debug-brk=?/.test(arg) || /^--inspect=?/.test(arg) || /^--inspect-brk=?/.test(arg)); } ; return false; } 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 vscode_languageserver_protocol_1.StreamMessageReader(result.reader), writer: new vscode_languageserver_protocol_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 vscode_languageserver_protocol_1.StreamMessageReader(cp.stdout), writer: new vscode_languageserver_protocol_1.StreamMessageWriter(cp.stdin) }; } }); } let json; let runDebug = server; if (runDebug.run || runDebug.debug) { // We are under debugging. So use debug as well. if (typeof v8debug === 'object' || 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)); } let execOptions = Object.create(null); execOptions.cwd = serverWorkingDir; execOptions.env = getEnvironment(options.env); 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 = vscode_languageserver_protocol_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(node.runtime, args, execOptions); if (!serverProcess || !serverProcess.pid) { return Promise.reject(`Launching server using runtime ${node.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 vscode_languageserver_protocol_1.IPCMessageReader(serverProcess), writer: new vscode_languageserver_protocol_1.IPCMessageWriter(serverProcess) }); } else { return Promise.resolve({ reader: new vscode_languageserver_protocol_1.StreamMessageReader(serverProcess.stdout), writer: new vscode_languageserver_protocol_1.StreamMessageWriter(serverProcess.stdin) }); } } else if (transport == TransportKind.pipe) { return vscode_languageserver_protocol_1.createClientPipeTransport(pipeName).then((transport) => { let process = cp.spawn(node.runtime, args, execOptions); if (!process || !process.pid) { return Promise.reject(`Launching server using runtime ${node.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 vscode_languageserver_protocol_1.createClientSocketTransport(transport.port).then((transport) => { let process = cp.spawn(node.runtime, args, execOptions); if (!process || !process.pid) { return Promise.reject(`Launching server using runtime ${node.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 = vscode_languageserver_protocol_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.execArgv = options.execArgv || []; options.cwd = serverWorkingDir; options.silent = true; if (transport === TransportKind.ipc || transport === TransportKind.stdio) { let sp = cp.fork(node.module, args || [], options); 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 vscode_languageserver_protocol_1.IPCMessageReader(this._serverProcess), writer: new vscode_languageserver_protocol_1.IPCMessageWriter(this._serverProcess) }); } else { resolve({ reader: new vscode_languageserver_protocol_1.StreamMessageReader(sp.stdout), writer: new vscode_languageserver_protocol_1.StreamMessageWriter(sp.stdin) }); } } else if (transport === TransportKind.pipe) { vscode_languageserver_protocol_1.createClientPipeTransport(pipeName).then((transport) => { let sp = cp.fork(node.module, args || [], options); 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)) { vscode_languageserver_protocol_1.createClientSocketTransport(transport.port).then((transport) => { let sp = cp.fork(node.module, args || [], options); 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 vscode_languageserver_protocol_1.StreamMessageReader(serverProcess.stdout), writer: new vscode_languageserver_protocol_1.StreamMessageWriter(serverProcess.stdin) }); } return Promise.reject(new Error(`Unsupported server configuration ` + JSON.stringify(server, null, 4))); }); } 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)); } _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); } } 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; // Exporting proposed protocol. var ProposedFeatures; (function (ProposedFeatures) { function createAll(_client) { let result = []; return result; } ProposedFeatures.createAll = createAll; })(ProposedFeatures = exports.ProposedFeatures || (exports.ProposedFeatures = {})); /***/ }), /***/ 3780: /***/ ((__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__(7549); class ProtocolCodeLens extends code.CodeLens { constructor(range) { super(range); } } exports.default = ProtocolCodeLens; /***/ }), /***/ 3810: /***/ ((__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__(7549); class ProtocolCompletionItem extends code.CompletionItem { constructor(label) { super(label); } } exports.default = ProtocolCompletionItem; /***/ }), /***/ 8899: /***/ ((__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__(7549); const ls = __webpack_require__(5310); const Is = __webpack_require__(4797); const protocolCompletionItem_1 = __webpack_require__(3810); const protocolCodeLens_1 = __webpack_require__(3780); const protocolDocumentLink_1 = __webpack_require__(6380); 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) { 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 code.Diagnostic(asRange(diagnostic.range), diagnostic.message, asDiagnosticSeverity(diagnostic.severity)); if (Is.number(diagnostic.code) || Is.string(diagnostic.code)) { result.code = diagnostic.code; } if (diagnostic.source) { result.source = diagnostic.source; } if (diagnostic.relatedInformation) { result.relatedInformation = asRelatedInformation(diagnostic.relatedInformation); } return result; } function asRelatedInformation(relatedInformation) { return relatedInformation.map(asDiagnosticRelatedInformation); } function asDiagnosticRelatedInformation(information) { return new code.DiagnosticRelatedInformation(asLocation(information.location), information.message); } 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 asDiagnosticSeverity(value) { if (value === void 0 || 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 new code.MarkdownString(value); } else if (CodeBlock.is(value)) { let result = new code.MarkdownString(); return result.appendCodeblock(value.value, value.language); } else if (Array.isArray(value)) { let result = []; for (let element of value) { let item = new code.MarkdownString(); 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 new code.MarkdownString(value.value); case ls.MarkupKind.PlainText: result = new code.MarkdownString(); result.appendText(value.value); return result; default: result = new code.MarkdownString(); 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 new code.MarkdownString(value.value); case ls.MarkupKind.PlainText: return value.value; default: return `Unsupported Markup content received. Kind is: ${value.kind}`; } } } 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 asCompletionItem(item) { 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.preselect === true || item.preselect === false) { result.preselect = item.preselect; } if (item.data !== void 0) { result.data = item.data; } return result; } function asCompletionInsertText(item) { if (item.textEdit) { if (item.insertTextFormat === ls.InsertTextFormat.Snippet) { return { text: new code.SnippetString(item.textEdit.newText), range: asRange(item.textEdit.range), fromEdit: true }; } else { return { text: item.textEdit.newText, range: asRange(item.textEdit.range), 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 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) { result.documentation = asDocumentation(item.documentation); } if (item.parameters) { result.parameters = asParameterInformations(item.parameters); } 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; } return { targetUri: _uriConverter(item.targetUri), targetRange: asRange(item.targetSelectionRange), originSelectionRange: asRange(item.originSelectionRange), targetSelectionRange: asRange(item.targetSelectionRange) }; } 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 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); if (item.containerName) { result.containerName = item.containerName; } return result; } function asDocumentSymbols(values) { if (values === void 0 || 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)); if (value.children !== void 0 && value.children.length > 0) { let children = []; for (let child of value.children) { children.push(asDocumentSymbol(child)); } result.children = children; } return result; } 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('', 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 === void 0 || 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 === void 0 || items === null) { return undefined; } return items.map(kind => asCodeActionKind(kind)); } function asCodeAction(item) { if (item === void 0 || item === null) { return undefined; } let result = new code.CodeAction(item.title); if (item.kind !== void 0) { result.kind = asCodeActionKind(item.kind); } if (item.diagnostics) { result.diagnostics = asDiagnostics(item.diagnostics); } if (item.edit) { result.edit = asWorkspaceEdit(item.edit); } if (item.command) { result.command = asCommand(item.command); } 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 !== void 0 && 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; } let result = new code.WorkspaceEdit(); if (item.documentChanges) { item.documentChanges.forEach(change => { if (ls.CreateFile.is(change)) { result.createFile(_uriConverter(change.uri), change.options); } else if (ls.RenameFile.is(change)) { result.renameFile(_uriConverter(change.oldUri), _uriConverter(change.newUri), change.options); } else if (ls.DeleteFile.is(change)) { result.deleteFile(_uriConverter(change.uri), change.options); } else if (ls.TextDocumentEdit.is(change)) { result.set(_uriConverter(change.textDocument.uri), asTextEdits(change.edits)); } else { console.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 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.data !== void 0 && 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 void 0; } 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 void 0; } return { asUri, asDiagnostics, asDiagnostic, asRange, asPosition, asDiagnosticSeverity, asHover, asCompletionResult, asCompletionItem, asTextEdit, asTextEdits, asSignatureHelp, asSignatureInformations, asSignatureInformation, asParameterInformations, asParameterInformation, asDeclarationResult, asDefinitionResult, asLocation, asReferences, asDocumentHighlights, asDocumentHighlight, asDocumentHighlightKind, asSymbolInformations, asSymbolInformation, asDocumentSymbols, asDocumentSymbol, asCommand, asCommands, asCodeAction, asCodeActionKind, asCodeActionKinds, asCodeLens, asCodeLenses, asWorkspaceEdit, asDocumentLink, asDocumentLinks, asFoldingRangeKind, asFoldingRange, asFoldingRanges, asColor, asColorInformation, asColorInformations, asColorPresentation, asColorPresentations }; } exports.createConverter = createConverter; /***/ }), /***/ 6380: /***/ ((__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__(7549); class ProtocolDocumentLink extends code.DocumentLink { constructor(range, target) { super(range, target); } } exports.default = ProtocolDocumentLink; /***/ }), /***/ 1505: /***/ ((__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 UUID = __webpack_require__(8861); const Is = __webpack_require__(4797); const vscode_1 = __webpack_require__(7549); const vscode_languageserver_protocol_1 = __webpack_require__(5310); const client_1 = __webpack_require__(7014); 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(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'typeDefinition').dynamicRegistration = true; let typeDefinitionSupport = ensure(ensure(capabilites, 'textDocument'), 'typeDefinition'); typeDefinitionSupport.dynamicRegistration = true; typeDefinitionSupport.linkSupport = true; } initialize(capabilities, documentSelector) { if (!capabilities.typeDefinitionProvider) { return; } if (capabilities.typeDefinitionProvider === true) { if (!documentSelector) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }) }); } else { const implCapabilities = capabilities.typeDefinitionProvider; const id = Is.string(implCapabilities.id) && implCapabilities.id.length > 0 ? implCapabilities.id : UUID.generateUuid(); const selector = implCapabilities.documentSelector || documentSelector; if (selector) { this.register(this.messages, { id, registerOptions: Object.assign({}, { documentSelector: selector }) }); } } } registerLanguageProvider(options) { let client = this._client; let provideTypeDefinition = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDefinitionResult, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, error); return Promise.resolve(null); }); }; let middleware = client.clientOptions.middleware; return vscode_1.languages.registerTypeDefinitionProvider(options.documentSelector, { provideTypeDefinition: (document, position, token) => { return middleware.provideTypeDefinition ? middleware.provideTypeDefinition(document, position, token, provideTypeDefinition) : provideTypeDefinition(document, position, token); } }); } } exports.TypeDefinitionFeature = TypeDefinitionFeature; /***/ }), /***/ 4834: /***/ ((__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 })); 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 = 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) { clearTimeout(this.timeout); this.timeout = undefined; } } } exports.Delayer = Delayer; /***/ }), /***/ 4797: /***/ ((__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 })); 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; /***/ }), /***/ 4108: /***/ ((__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 cp = __webpack_require__(3129); const path_1 = __webpack_require__(5622); 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; /***/ }), /***/ 8861: /***/ ((__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 })); 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; /***/ }), /***/ 4484: /***/ ((__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 UUID = __webpack_require__(8861); const vscode_1 = __webpack_require__(7549); const vscode_languageserver_protocol_1 = __webpack_require__(5310); function access(target, key) { if (target === void 0) { return undefined; } return target[key]; } class WorkspaceFoldersFeature { constructor(_client) { this._client = _client; this._listeners = new Map(); } get messages() { return vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type; } fillInitializeParams(params) { let folders = vscode_1.workspace.workspaceFolders; if (folders === void 0) { params.workspaceFolders = null; } else { params.workspaceFolders = folders.map(folder => this.asProtocol(folder)); } } fillClientCapabilities(capabilities) { capabilities.workspace = capabilities.workspace || {}; capabilities.workspace.workspaceFolders = true; } initialize(capabilities) { let client = this._client; client.onRequest(vscode_languageserver_protocol_1.WorkspaceFoldersRequest.type, (token) => { let workspaceFolders = () => { let folders = vscode_1.workspace.workspaceFolders; if (folders === void 0) { return null; } let result = folders.map((folder) => { return this.asProtocol(folder); }); return result; }; let middleware = client.clientOptions.middleware.workspace; return middleware && middleware.workspaceFolders ? middleware.workspaceFolders(token, workspaceFolders) : workspaceFolders(token); }); let 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(this.messages, { id: id, registerOptions: undefined }); } } register(_message, data) { let id = data.id; let client = this._client; let disposable = vscode_1.workspace.onDidChangeWorkspaceFolders((event) => { let didChangeWorkspaceFolders = (event) => { let params = { event: { added: event.added.map(folder => this.asProtocol(folder)), removed: event.removed.map(folder => this.asProtocol(folder)) } }; this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type, params); }; let middleware = client.clientOptions.middleware.workspace; middleware && middleware.didChangeWorkspaceFolders ? middleware.didChangeWorkspaceFolders(event, didChangeWorkspaceFolders) : didChangeWorkspaceFolders(event); }); this._listeners.set(id, disposable); } 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; /***/ }), /***/ 5310: /***/ ((__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. * ------------------------------------------------------------------------------------------ */ function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode_jsonrpc_1 = __webpack_require__(617); exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes; exports.ResponseError = vscode_jsonrpc_1.ResponseError; exports.CancellationToken = vscode_jsonrpc_1.CancellationToken; exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource; exports.Disposable = vscode_jsonrpc_1.Disposable; exports.Event = vscode_jsonrpc_1.Event; exports.Emitter = vscode_jsonrpc_1.Emitter; exports.Trace = vscode_jsonrpc_1.Trace; exports.TraceFormat = vscode_jsonrpc_1.TraceFormat; exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification; exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification; exports.RequestType = vscode_jsonrpc_1.RequestType; exports.RequestType0 = vscode_jsonrpc_1.RequestType0; exports.NotificationType = vscode_jsonrpc_1.NotificationType; exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0; exports.MessageReader = vscode_jsonrpc_1.MessageReader; exports.MessageWriter = vscode_jsonrpc_1.MessageWriter; exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy; exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader; exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter; exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader; exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter; exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport; exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport; exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName; exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport; exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport; __export(__webpack_require__(4970)); __export(__webpack_require__(6161)); function createProtocolConnection(reader, writer, logger, strategy) { return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy); } exports.createProtocolConnection = createProtocolConnection; /***/ }), /***/ 6807: /***/ ((__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_jsonrpc_1 = __webpack_require__(617); /** * 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.type = new vscode_jsonrpc_1.RequestType('textDocument/documentColor'); })(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 vscode_jsonrpc_1.RequestType('textDocument/colorPresentation'); })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {})); /***/ }), /***/ 7772: /***/ ((__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_jsonrpc_1 = __webpack_require__(617); /** * 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 vscode_jsonrpc_1.RequestType('workspace/configuration'); })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {})); /***/ }), /***/ 4653: /***/ ((__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_jsonrpc_1 = __webpack_require__(617); // @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.type = new vscode_jsonrpc_1.RequestType('textDocument/declaration'); })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {})); /***/ }), /***/ 7959: /***/ ((__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_jsonrpc_1 = __webpack_require__(617); /** * 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.type = new vscode_jsonrpc_1.RequestType('textDocument/foldingRange'); })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {})); /***/ }), /***/ 2685: /***/ ((__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_jsonrpc_1 = __webpack_require__(617); // @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.type = new vscode_jsonrpc_1.RequestType('textDocument/implementation'); })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {})); /***/ }), /***/ 6161: /***/ ((__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 Is = __webpack_require__(3379); const vscode_jsonrpc_1 = __webpack_require__(617); const protocol_implementation_1 = __webpack_require__(2685); exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest; const protocol_typeDefinition_1 = __webpack_require__(936); exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest; const protocol_workspaceFolders_1 = __webpack_require__(2899); exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest; exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification; const protocol_configuration_1 = __webpack_require__(7772); exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest; const protocol_colorProvider_1 = __webpack_require__(6807); exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest; exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest; const protocol_foldingRange_1 = __webpack_require__(7959); exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest; const protocol_declaration_1 = __webpack_require__(4653); exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest; // @ts-ignore: to avoid inlining LocatioLink as dynamic import let __noDynamicImport; var DocumentFilter; (function (DocumentFilter) { function is(value) { let candidate = value; return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern); } DocumentFilter.is = is; })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {})); /** * 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 vscode_jsonrpc_1.RequestType('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 vscode_jsonrpc_1.RequestType('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 startegy is abort. */ FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional'; /** * The client tries to undo the operations already executed. But there is no * guaruntee that this is succeeding. */ FailureHandlingKind.Undo = 'undo'; })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {})); /** * 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 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 vscode_jsonrpc_1.RequestType('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 intialized 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 vscode_jsonrpc_1.NotificationType('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 vscode_jsonrpc_1.RequestType0('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 vscode_jsonrpc_1.NotificationType0('exit'); })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {})); //---- Configuration notification ---- /** * 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 vscode_jsonrpc_1.NotificationType('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 vscode_jsonrpc_1.NotificationType('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 vscode_jsonrpc_1.RequestType('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 vscode_jsonrpc_1.NotificationType('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 vscode_jsonrpc_1.NotificationType('telemetry/event'); })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {})); /** * 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.type = new vscode_jsonrpc_1.NotificationType('textDocument/didOpen'); })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {})); /** * The document change notification is sent from the client to the server to signal * changes to a text document. */ var DidChangeTextDocumentNotification; (function (DidChangeTextDocumentNotification) { DidChangeTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/didChange'); })(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.type = new vscode_jsonrpc_1.NotificationType('textDocument/didClose'); })(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.type = new vscode_jsonrpc_1.NotificationType('textDocument/didSave'); })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {})); /** * A document will save notification is sent from the client to the server before * the document is actually saved. */ var WillSaveTextDocumentNotification; (function (WillSaveTextDocumentNotification) { WillSaveTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/willSave'); })(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.type = new vscode_jsonrpc_1.RequestType('textDocument/willSaveWaitUntil'); })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {})); //---- File eventing ---- /** * 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 vscode_jsonrpc_1.NotificationType('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 = {})); //---- Diagnostic notification ---- /** * Diagnostics notification are sent from the server to the client to signal * results of validation runs. */ var PublishDiagnosticsNotification; (function (PublishDiagnosticsNotification) { PublishDiagnosticsNotification.type = new vscode_jsonrpc_1.NotificationType('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.type = new vscode_jsonrpc_1.RequestType('textDocument/completion'); })(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.type = new vscode_jsonrpc_1.RequestType('completionItem/resolve'); })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {})); //---- Hover Support ------------------------------- /** * 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.type = new vscode_jsonrpc_1.RequestType('textDocument/hover'); })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {})); var SignatureHelpRequest; (function (SignatureHelpRequest) { SignatureHelpRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/signatureHelp'); })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {})); //---- Goto Definition ------------------------------------- /** * 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.type = new vscode_jsonrpc_1.RequestType('textDocument/definition'); })(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.type = new vscode_jsonrpc_1.RequestType('textDocument/references'); })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {})); //---- Document Highlight ---------------------------------- /** * 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.type = new vscode_jsonrpc_1.RequestType('textDocument/documentHighlight'); })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {})); //---- Document Symbol Provider --------------------------- /** * 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.type = new vscode_jsonrpc_1.RequestType('textDocument/documentSymbol'); })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {})); //---- Workspace Symbol Provider --------------------------- /** * 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.type = new vscode_jsonrpc_1.RequestType('workspace/symbol'); })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {})); /** * A request to provide commands for the given text document and range. */ var CodeActionRequest; (function (CodeActionRequest) { CodeActionRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/codeAction'); })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {})); /** * A request to provide code lens for the given text document. */ var CodeLensRequest; (function (CodeLensRequest) { CodeLensRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/codeLens'); })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {})); /** * A request to resolve a command for a given code lens. */ var CodeLensResolveRequest; (function (CodeLensResolveRequest) { CodeLensResolveRequest.type = new vscode_jsonrpc_1.RequestType('codeLens/resolve'); })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {})); /** * A request to to format a whole document. */ var DocumentFormattingRequest; (function (DocumentFormattingRequest) { DocumentFormattingRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/formatting'); })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {})); /** * A request to to format a range in a document. */ var DocumentRangeFormattingRequest; (function (DocumentRangeFormattingRequest) { DocumentRangeFormattingRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/rangeFormatting'); })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {})); /** * A request to format a document on type. */ var DocumentOnTypeFormattingRequest; (function (DocumentOnTypeFormattingRequest) { DocumentOnTypeFormattingRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/onTypeFormatting'); })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {})); /** * A request to rename a symbol. */ var RenameRequest; (function (RenameRequest) { RenameRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/rename'); })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {})); /** * A request to test and perform the setup necessary for a rename. */ var PrepareRenameRequest; (function (PrepareRenameRequest) { PrepareRenameRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/prepareRename'); })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {})); /** * A request to provide document links */ var DocumentLinkRequest; (function (DocumentLinkRequest) { DocumentLinkRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/documentLink'); })(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.type = new vscode_jsonrpc_1.RequestType('documentLink/resolve'); })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {})); /** * 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 vscode_jsonrpc_1.RequestType('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 vscode_jsonrpc_1.RequestType('workspace/applyEdit'); })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {})); /***/ }), /***/ 936: /***/ ((__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_jsonrpc_1 = __webpack_require__(617); // @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.type = new vscode_jsonrpc_1.RequestType('textDocument/typeDefinition'); })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {})); /***/ }), /***/ 2899: /***/ ((__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_jsonrpc_1 = __webpack_require__(617); /** * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders. */ var WorkspaceFoldersRequest; (function (WorkspaceFoldersRequest) { WorkspaceFoldersRequest.type = new vscode_jsonrpc_1.RequestType0('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 vscode_jsonrpc_1.NotificationType('workspace/didChangeWorkspaceFolders'); })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {})); /***/ }), /***/ 3379: /***/ ((__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 })); 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; /***/ }), /***/ 4970: /***/ ((module, exports, __webpack_require__) => { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (factory) { if ( true && typeof module.exports === "object") { var v = factory(__webpack_require__(7492), exports); if (v !== undefined) module.exports = v; } else if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__, exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } })(function (require, exports) { /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * 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) { return { line: line, character: character }; } Position.create = create; /** * Checks whether the given liternal conforms to the [Position](#Position) interface. */ function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character); } Position.is = is; })(Position = exports.Position || (exports.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.number(one) && Is.number(two) && Is.number(three) && Is.number(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 = exports.Range || (exports.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 = exports.Location || (exports.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 = exports.LocationLink || (exports.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.number(candidate.red) && Is.number(candidate.green) && Is.number(candidate.blue) && Is.number(candidate.alpha); } Color.is = is; })(Color = exports.Color || (exports.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 = exports.ColorInformation || (exports.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 = exports.ColorPresentation || (exports.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 = exports.FoldingRangeKind || (exports.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.number(candidate.startLine) && Is.number(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind)); } FoldingRange.is = is; })(FoldingRange = exports.FoldingRange || (exports.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 = exports.DiagnosticRelatedInformation || (exports.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 = exports.DiagnosticSeverity || (exports.DiagnosticSeverity = {})); /** * 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 candidate = value; return Is.defined(candidate) && Range.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is)); } Diagnostic.is = is; })(Diagnostic = exports.Diagnostic || (exports.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 = exports.Command || (exports.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 = exports.TextEdit || (exports.TextEdit = {})); /** * 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) && VersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits); } TextDocumentEdit.is = is; })(TextDocumentEdit = exports.TextDocumentEdit || (exports.TextDocumentEdit = {})); var CreateFile; (function (CreateFile) { function create(uri, options) { var result = { kind: 'create', uri: uri }; if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) { result.options = options; } return result; } CreateFile.create = create; function is(value) { var candidate = value; return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && (candidate.options === void 0 || ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists)))); } CreateFile.is = is; })(CreateFile = exports.CreateFile || (exports.CreateFile = {})); var RenameFile; (function (RenameFile) { function create(oldUri, newUri, options) { var result = { kind: 'rename', oldUri: oldUri, newUri: newUri }; if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) { result.options = options; } 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 === void 0 || ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists)))); } RenameFile.is = is; })(RenameFile = exports.RenameFile || (exports.RenameFile = {})); var DeleteFile; (function (DeleteFile) { function create(uri, options) { var result = { kind: 'delete', uri: uri }; if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) { result.options = options; } return result; } DeleteFile.create = create; function is(value) { var candidate = value; return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && (candidate.options === void 0 || ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists)))); } DeleteFile.is = is; })(DeleteFile = exports.DeleteFile || (exports.DeleteFile = {})); var WorkspaceEdit; (function (WorkspaceEdit) { function is(value) { var candidate = value; return candidate && (candidate.changes !== void 0 || candidate.documentChanges !== void 0) && (candidate.documentChanges === void 0 || 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 = exports.WorkspaceEdit || (exports.WorkspaceEdit = {})); var TextEditChangeImpl = /** @class */ (function () { function TextEditChangeImpl(edits) { this.edits = edits; } TextEditChangeImpl.prototype.insert = function (position, newText) { this.edits.push(TextEdit.insert(position, newText)); }; TextEditChangeImpl.prototype.replace = function (range, newText) { this.edits.push(TextEdit.replace(range, newText)); }; TextEditChangeImpl.prototype.delete = function (range) { this.edits.push(TextEdit.del(range)); }; 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); }; return TextEditChangeImpl; }()); /** * 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) { this._workspaceEdit = workspaceEdit; if (workspaceEdit.documentChanges) { workspaceEdit.documentChanges.forEach(function (change) { if (TextDocumentEdit.is(change)) { var textEditChange = new TextEditChangeImpl(change.edits); _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; }); } } } Object.defineProperty(WorkspaceChange.prototype, "edit", { /** * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal * use to be returned from a workspace edit operation like rename. */ get: function () { return this._workspaceEdit; }, enumerable: true, configurable: true }); WorkspaceChange.prototype.getTextEditChange = function (key) { if (VersionedTextDocumentIdentifier.is(key)) { if (!this._workspaceEdit) { this._workspaceEdit = { documentChanges: [] }; } if (!this._workspaceEdit.documentChanges) { throw new Error('Workspace edit is not configured for document changes.'); } var textDocument = key; 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._textEditChanges[textDocument.uri] = result; } return result; } else { if (!this._workspaceEdit) { this._workspaceEdit = { changes: Object.create(null) }; } if (!this._workspaceEdit.changes) { 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.createFile = function (uri, options) { this.checkDocumentChanges(); this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options)); }; WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) { this.checkDocumentChanges(); this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options)); }; WorkspaceChange.prototype.deleteFile = function (uri, options) { this.checkDocumentChanges(); this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options)); }; WorkspaceChange.prototype.checkDocumentChanges = function () { if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) { throw new Error('Workspace edit is not configured for document changes.'); } }; return WorkspaceChange; }()); exports.WorkspaceChange = 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 = exports.TextDocumentIdentifier || (exports.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) && (candidate.version === null || Is.number(candidate.version)); } VersionedTextDocumentIdentifier.is = is; })(VersionedTextDocumentIdentifier = exports.VersionedTextDocumentIdentifier || (exports.VersionedTextDocumentIdentifier = {})); /** * 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.number(candidate.version) && Is.string(candidate.text); } TextDocumentItem.is = is; })(TextDocumentItem = exports.TextDocumentItem || (exports.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 = exports.MarkupKind || (exports.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 = exports.MarkupKind || (exports.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 = exports.MarkupContent || (exports.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 = exports.CompletionItemKind || (exports.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://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md */ InsertTextFormat.Snippet = 2; })(InsertTextFormat = exports.InsertTextFormat || (exports.InsertTextFormat = {})); /** * 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 = exports.CompletionItem || (exports.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 = exports.CompletionList || (exports.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 = exports.MarkedString || (exports.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 === void 0 || Range.is(value.range)); } Hover.is = is; })(Hover = exports.Hover || (exports.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 = exports.ParameterInformation || (exports.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 = exports.SignatureInformation || (exports.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 = exports.DocumentHighlightKind || (exports.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 = exports.DocumentHighlight || (exports.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 = exports.SymbolKind || (exports.SymbolKind = {})); 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 = exports.SymbolInformation || (exports.SymbolInformation = {})); /** * Represents programming constructs like variables, classes, interfaces etc. * that appear in a document. Document symbols can be hierarchical and they * have two ranges: one that encloses its definition and one that points to * its most interesting range, e.g. the range of an identifier. */ var DocumentSymbol = /** @class */ (function () { function DocumentSymbol() { } return DocumentSymbol; }()); exports.DocumentSymbol = 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 !== void 0) { 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 === void 0 || Is.string(candidate.detail)) && (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) && (candidate.children === void 0 || Array.isArray(candidate.children)); } DocumentSymbol.is = is; })(DocumentSymbol = exports.DocumentSymbol || (exports.DocumentSymbol = {})); exports.DocumentSymbol = DocumentSymbol; /** * A set of predefined code action kinds */ var CodeActionKind; (function (CodeActionKind) { /** * 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'; })(CodeActionKind = exports.CodeActionKind || (exports.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 !== void 0 && 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 === void 0 || Is.typedArray(candidate.only, Is.string)); } CodeActionContext.is = is; })(CodeActionContext = exports.CodeActionContext || (exports.CodeActionContext = {})); var CodeAction; (function (CodeAction) { function create(title, commandOrEdit, kind) { var result = { title: title }; if (Command.is(commandOrEdit)) { result.command = commandOrEdit; } else { result.edit = commandOrEdit; } if (kind !== void null) { result.kind = kind; } return result; } CodeAction.create = create; function is(value) { var candidate = value; return candidate && Is.string(candidate.title) && (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === void 0 || Is.string(candidate.kind)) && (candidate.edit !== void 0 || candidate.command !== void 0) && (candidate.command === void 0 || Command.is(candidate.command)) && (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit)); } CodeAction.is = is; })(CodeAction = exports.CodeAction || (exports.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 = exports.CodeLens || (exports.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.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces); } FormattingOptions.is = is; })(FormattingOptions = exports.FormattingOptions || (exports.FormattingOptions = {})); /** * A document link is a range in a text document that links to an internal or external resource, like another * text document or a web site. */ var DocumentLink = /** @class */ (function () { function DocumentLink() { } return DocumentLink; }()); exports.DocumentLink = DocumentLink; /** * The DocumentLink namespace provides helper functions to work with * [DocumentLink](#DocumentLink) literals. */ (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 = exports.DocumentLink || (exports.DocumentLink = {})); exports.DocumentLink = DocumentLink; exports.EOL = ['\n', '\r\n', '\r']; 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.number(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 = exports.TextDocument || (exports.TextDocument = {})); /** * 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 = {})); var FullTextDocument = /** @class */ (function () { function FullTextDocument(uri, languageId, version, content) { this._uri = uri; this._languageId = languageId; this._version = version; this._content = content; this._lineOffsets = null; } Object.defineProperty(FullTextDocument.prototype, "uri", { get: function () { return this._uri; }, enumerable: true, configurable: true }); Object.defineProperty(FullTextDocument.prototype, "languageId", { get: function () { return this._languageId; }, enumerable: true, configurable: true }); Object.defineProperty(FullTextDocument.prototype, "version", { get: function () { return this._version; }, enumerable: true, 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 = null; }; FullTextDocument.prototype.getLineOffsets = function () { if (this._lineOffsets === null) { 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: true, 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 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 = {})); }); /***/ }), /***/ 3612: /***/ ((__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 })); var path = __webpack_require__(5622); var fs = __webpack_require__(5747); var toString = Object.prototype.toString; function isDefined(value) { return typeof value !== 'undefined'; } function isNumber(value) { return toString.call(value) === '[object Number]'; } function isString(value) { return toString.call(value) === '[object String]'; } function isBoolean(value) { return value === true || value === false; } function readJsonFileSync(filename) { return JSON.parse(fs.readFileSync(filename, 'utf8')); } var MessageFormat; (function (MessageFormat) { MessageFormat["file"] = "file"; MessageFormat["bundle"] = "bundle"; MessageFormat["both"] = "both"; })(MessageFormat = exports.MessageFormat || (exports.MessageFormat = {})); var BundleFormat; (function (BundleFormat) { // the nls.bundle format BundleFormat["standalone"] = "standalone"; BundleFormat["languagePack"] = "languagePack"; })(BundleFormat = exports.BundleFormat || (exports.BundleFormat = {})); var LocalizeInfo; (function (LocalizeInfo) { function is(value) { var candidate = value; return candidate && isDefined(candidate.key) && isDefined(candidate.comment); } LocalizeInfo.is = is; })(LocalizeInfo || (LocalizeInfo = {})); var resolvedLanguage; var resolvedBundles; var options; var isPseudo; function initializeSettings() { options = { locale: undefined, language: undefined, languagePackSupport: false, cacheLanguageResolution: true, messageFormat: MessageFormat.bundle }; if (isString(process.env.VSCODE_NLS_CONFIG)) { try { var vscodeOptions = JSON.parse(process.env.VSCODE_NLS_CONFIG); var language = void 0; var locale = void 0; if (vscodeOptions.availableLanguages) { var value = vscodeOptions.availableLanguages['*']; if (isString(value)) { language = value; } } if (isString(vscodeOptions.locale)) { options.locale = vscodeOptions.locale.toLowerCase(); } if (language === undefined) { options.language = options.locale; } else if (language !== 'en') { options.language = language; } if (isBoolean(vscodeOptions._languagePackSupport)) { options.languagePackSupport = vscodeOptions._languagePackSupport; } if (isString(vscodeOptions._cacheRoot)) { options.cacheRoot = vscodeOptions._cacheRoot; } if (isString(vscodeOptions._languagePackId)) { options.languagePackId = vscodeOptions._languagePackId; } if (isString(vscodeOptions._translationsConfigFile)) { options.translationsConfigFile = vscodeOptions._translationsConfigFile; try { options.translationsConfig = readJsonFileSync(options.translationsConfigFile); } catch (error) { // We can't read the translation config file. Mark the cache as corrupted. if (vscodeOptions._corruptedFile) { fs.writeFile(vscodeOptions._corruptedFile, 'corrupted', 'utf8', function (err) { console.error(err); }); } } } } catch (_a) { // Do nothing. } } isPseudo = options.locale === 'pseudo'; resolvedLanguage = undefined; resolvedBundles = Object.create(null); } initializeSettings(); function supportsLanguagePack() { return options.languagePackSupport === true && options.cacheRoot !== undefined && options.languagePackId !== undefined && options.translationsConfigFile !== undefined && options.translationsConfig !== undefined; } function format(message, args) { var result; if (isPseudo) { // FF3B and FF3D is the Unicode zenkaku representation for [ and ] message = '\uFF3B' + message.replace(/[aouei]/g, '$&$&') + '\uFF3D'; } if (args.length === 0) { result = message; } else { result = message.replace(/\{(\d+)\}/g, function (match, rest) { var index = rest[0]; var arg = args[index]; var replacement = match; if (typeof arg === 'string') { replacement = arg; } else if (typeof arg === 'number' || typeof arg === 'boolean' || arg === void 0 || arg === null) { replacement = String(arg); } return replacement; }); } return result; } function createScopedLocalizeFunction(messages) { return function (key, message) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } if (isNumber(key)) { if (key >= messages.length) { console.error("Broken localize call found. Index out of bounds. Stacktrace is\n: " + new Error('').stack); return; } return format(messages[key], args); } else { if (isString(message)) { console.warn("Message " + message + " didn't get externalized correctly."); return format(message, args); } else { console.error("Broken localize call found. Stacktrace is\n: " + new Error('').stack); } } }; } function localize(key, message) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } return format(message, args); } function resolveLanguage(file) { var resolvedLanguage; if (options.cacheLanguageResolution && resolvedLanguage) { resolvedLanguage = resolvedLanguage; } else { if (isPseudo || !options.language) { resolvedLanguage = '.nls.json'; } else { var locale = options.language; while (locale) { var candidate = '.nls.' + locale + '.json'; if (fs.existsSync(file + candidate)) { resolvedLanguage = candidate; break; } else { var index = locale.lastIndexOf('-'); if (index > 0) { locale = locale.substring(0, index); } else { resolvedLanguage = '.nls.json'; locale = null; } } } } if (options.cacheLanguageResolution) { resolvedLanguage = resolvedLanguage; } } return file + resolvedLanguage; } function findInTheBoxBundle(root) { var language = options.language; while (language) { var candidate = path.join(root, "nls.bundle." + language + ".json"); if (fs.existsSync(candidate)) { return candidate; } else { var index = language.lastIndexOf('-'); if (index > 0) { language = language.substring(0, index); } else { language = undefined; } } } // Test if we can reslove the default bundle. if (language === undefined) { var candidate = path.join(root, 'nls.bundle.json'); if (fs.existsSync(candidate)) { return candidate; } } return undefined; } function mkdir(directory) { try { fs.mkdirSync(directory); } catch (err) { if (err.code === 'EEXIST') { return; } else if (err.code === 'ENOENT') { var parent = path.dirname(directory); if (parent !== directory) { mkdir(parent); fs.mkdirSync(directory); } } else { throw err; } } } function createDefaultNlsBundle(folder) { var metaData = readJsonFileSync(path.join(folder, 'nls.metadata.json')); var result = Object.create(null); for (var module_1 in metaData) { var entry = metaData[module_1]; result[module_1] = entry.messages; } return result; } function createNLSBundle(header, metaDataPath) { var languagePackLocation = options.translationsConfig[header.id]; if (!languagePackLocation) { return undefined; } var languagePack = readJsonFileSync(languagePackLocation).contents; var metaData = readJsonFileSync(path.join(metaDataPath, 'nls.metadata.json')); var result = Object.create(null); for (var module_2 in metaData) { var entry = metaData[module_2]; var translations = languagePack[header.outDir + "/" + module_2]; if (translations) { var resultMessages = []; for (var i = 0; i < entry.keys.length; i++) { var messageKey = entry.keys[i]; var key = isString(messageKey) ? messageKey : messageKey.key; var translatedMessage = translations[key]; if (translatedMessage === undefined) { translatedMessage = entry.messages[i]; } resultMessages.push(translatedMessage); } result[module_2] = resultMessages; } else { result[module_2] = entry.messages; } } return result; } function touch(file) { var d = new Date(); fs.utimes(file, d, d, function () { // Do nothing. Ignore }); } function cacheBundle(key, bundle) { resolvedBundles[key] = bundle; return bundle; } function loadNlsBundleOrCreateFromI18n(header, bundlePath) { var result; var bundle = path.join(options.cacheRoot, header.id + "-" + header.hash + ".json"); var useMemoryOnly = false; var writeBundle = false; try { result = JSON.parse(fs.readFileSync(bundle, { encoding: 'utf8', flag: 'r' })); touch(bundle); return result; } catch (err) { if (err.code === 'ENOENT') { writeBundle = true; } else if (err instanceof SyntaxError) { // We have a syntax error. So no valid JSON. Use console.log("Syntax error parsing message bundle: " + err.message + "."); fs.unlink(bundle, function (err) { if (err) { console.error("Deleting corrupted bundle " + bundle + " failed."); } }); useMemoryOnly = true; } else { throw err; } } result = createNLSBundle(header, bundlePath); if (!result || useMemoryOnly) { return result; } if (writeBundle) { try { fs.writeFileSync(bundle, JSON.stringify(result), { encoding: 'utf8', flag: 'wx' }); } catch (err) { if (err.code === 'EEXIST') { return result; } throw err; } } return result; } function loadDefaultNlsBundle(bundlePath) { try { return createDefaultNlsBundle(bundlePath); } catch (err) { console.log("Generating default bundle from meta data failed.", err); return undefined; } } function loadNlsBundle(header, bundlePath) { var result; // Core decided to use a language pack. Do the same in the extension if (supportsLanguagePack()) { try { result = loadNlsBundleOrCreateFromI18n(header, bundlePath); } catch (err) { console.log("Load or create bundle failed ", err); } } if (!result) { // No language pack found, but core is running in language pack mode // Don't try to use old in the box bundles since the might be stale // Fall right back to the default bundle. if (options.languagePackSupport) { return loadDefaultNlsBundle(bundlePath); } var candidate = findInTheBoxBundle(bundlePath); if (candidate) { try { return readJsonFileSync(candidate); } catch (err) { console.log("Loading in the box message bundle failed.", err); } } result = loadDefaultNlsBundle(bundlePath); } return result; } function tryFindMetaDataHeaderFile(file) { var result; var dirname = path.dirname(file); while (true) { result = path.join(dirname, 'nls.metadata.header.json'); if (fs.existsSync(result)) { break; } var parent = path.dirname(dirname); if (parent === dirname) { result = undefined; break; } else { dirname = parent; } } return result; } function loadMessageBundle(file) { if (!file) { // No file. We are in dev mode. Return the default // localize function. return localize; } // Remove extension since we load json files. var ext = path.extname(file); if (ext) { file = file.substr(0, file.length - ext.length); } if (options.messageFormat === MessageFormat.both || options.messageFormat === MessageFormat.bundle) { var headerFile = tryFindMetaDataHeaderFile(file); if (headerFile) { var bundlePath = path.dirname(headerFile); var bundle = resolvedBundles[bundlePath]; if (bundle === undefined) { try { var header = JSON.parse(fs.readFileSync(headerFile, 'utf8')); try { var nlsBundle = loadNlsBundle(header, bundlePath); bundle = cacheBundle(bundlePath, nlsBundle ? { header: header, nlsBundle: nlsBundle } : null); } catch (err) { console.error('Failed to load nls bundle', err); bundle = cacheBundle(bundlePath, null); } } catch (err) { console.error('Failed to read header file', err); bundle = cacheBundle(bundlePath, null); } } if (bundle) { var module_3 = file.substr(bundlePath.length + 1).replace(/\\/g, '/'); var messages = bundle.nlsBundle[module_3]; if (messages === undefined) { console.error("Messages for file " + file + " not found. See console for details."); return function () { return 'Messages not found.'; }; } return createScopedLocalizeFunction(messages); } } } if (options.messageFormat === MessageFormat.both || options.messageFormat === MessageFormat.file) { // Try to load a single file bundle try { var json = readJsonFileSync(resolveLanguage(file)); if (Array.isArray(json)) { return createScopedLocalizeFunction(json); } else { if (isDefined(json.messages) && isDefined(json.keys)) { return createScopedLocalizeFunction(json.messages); } else { console.error("String bundle '" + file + "' uses an unsupported format."); return function () { return 'File bundle has unsupported format. See console for details'; }; } } } catch (err) { if (err.code !== 'ENOENT') { console.error('Failed to load single file bundle', err); } } } console.error("Failed to load message bundle for file " + file); return function () { return 'Failed to load message bundle. See console for details.'; }; } exports.loadMessageBundle = loadMessageBundle; function config(opts) { if (opts) { if (isString(opts.locale)) { options.locale = opts.locale.toLowerCase(); options.language = options.locale; resolvedLanguage = undefined; resolvedBundles = Object.create(null); } if (opts.messageFormat !== undefined) { options.messageFormat = opts.messageFormat; } if (opts.bundleFormat === BundleFormat.standalone && options.languagePackSupport === true) { options.languagePackSupport = false; } } isPseudo = options.locale === 'pseudo'; return loadMessageBundle; } exports.config = config; //# sourceMappingURL=main.js.map /***/ }), /***/ 2579: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // // Copyright (c) Microsoft Corporation. All rights reserved. // Object.defineProperty(exports, "__esModule", ({ value: true })); var VSCodeTasClient_1 = __webpack_require__(2050); exports.getExperimentationService = VSCodeTasClient_1.getExperimentationService; exports.getExperimentationServiceAsync = VSCodeTasClient_1.getExperimentationServiceAsync; var VSCodeFilterProvider_1 = __webpack_require__(4978); exports.TargetPopulation = VSCodeFilterProvider_1.TargetPopulation; //# sourceMappingURL=index.js.map /***/ }), /***/ 4091: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class MementoKeyValueStorage { constructor(mementoGlobalStorage) { this.mementoGlobalStorage = mementoGlobalStorage; } async getValue(key, defaultValue) { const value = await this.mementoGlobalStorage.get(key); return value || defaultValue; } setValue(key, value) { this.mementoGlobalStorage.update(key, value); } } exports.MementoKeyValueStorage = MementoKeyValueStorage; //# sourceMappingURL=MementoKeyValueStorage.js.map /***/ }), /***/ 2545: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class TelemetryDisabledExperimentationService { constructor() { this.initializePromise = Promise.resolve(); this.initialFetch = Promise.resolve(); } isFlightEnabled(flight) { return false; } isCachedFlightEnabled(flight) { return Promise.resolve(false); } isFlightEnabledAsync(flight) { return Promise.resolve(false); } getTreatmentVariable(configId, name) { return undefined; } getTreatmentVariableAsync(configId, name) { return Promise.resolve(undefined); } } exports.default = TelemetryDisabledExperimentationService; //# sourceMappingURL=TelemetryDisabledExperimentationService.js.map /***/ }), /***/ 4978: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(7549); /** * Here is where we are going to define the filters we will set. */ class VSCodeFilterProvider { constructor(extensionName, extensionVersion, targetPopulation) { this.extensionName = extensionName; this.extensionVersion = extensionVersion; this.targetPopulation = targetPopulation; } /** * Returns a version string that can be parsed into a .NET Build object * by removing the tag suffix (for example -dev). * * @param version Version string to be trimmed. */ static trimVersionSuffix(version) { const regex = /\-[a-zA-Z0-9]+$/; const result = version.split(regex); return result[0]; } getFilterValue(filter) { switch (filter) { case Filters.ApplicationVersion: return VSCodeFilterProvider.trimVersionSuffix(vscode.version); case Filters.Build: return vscode.env.appName; case Filters.ClientId: return vscode.env.machineId; case Filters.ExtensionName: return this.extensionName; case Filters.ExtensionVersion: return VSCodeFilterProvider.trimVersionSuffix(this.extensionVersion); case Filters.Language: return vscode.env.language; case Filters.TargetPopulation: return this.targetPopulation; default: return ''; } } getFilters() { let filters = new Map(); let filterValues = Object.values(Filters); for (let value of filterValues) { filters.set(value, this.getFilterValue(value)); } return filters; } } exports.VSCodeFilterProvider = VSCodeFilterProvider; /* Based upon the official VSCode currently existing filters in the ExP backend for the VSCode cluster. https://experimentation.visualstudio.com/Analysis%20and%20Experimentation/_git/AnE.ExP.TAS.TachyonHost.Configuration?path=%2FConfigurations%2Fvscode%2Fvscode.json&version=GBmaster "X-MSEdge-Market": "detection.market", "X-FD-Corpnet": "detection.corpnet", "X-VSCode–AppVersion": "appversion", "X-VSCode-Build": "build", "X-MSEdge-ClientId": "clientid", "X-VSCode-ExtensionName": "extensionname", "X-VSCode-ExtensionVersion": "extensionversion", "X-VSCode-TargetPopulation": "targetpopulation", "X-VSCode-Language": "language" */ /** * All available filters, can be updated. */ var Filters; (function (Filters) { /** * The market in which the extension is distributed. */ Filters["Market"] = "X-MSEdge-Market"; /** * The corporation network. */ Filters["CorpNet"] = "X-FD-Corpnet"; /** * Version of the application which uses experimentation service. */ Filters["ApplicationVersion"] = "X-VSCode-AppVersion"; /** * Insiders vs Stable. */ Filters["Build"] = "X-VSCode-Build"; /** * Client Id which is used as primary unit for the experimentation. */ Filters["ClientId"] = "X-MSEdge-ClientId"; /** * Extension header. */ Filters["ExtensionName"] = "X-VSCode-ExtensionName"; /** * The version of the extension. */ Filters["ExtensionVersion"] = "X-VSCode-ExtensionVersion"; /** * The language in use by VS Code */ Filters["Language"] = "X-VSCode-Language"; /** * The target population. * This is used to separate internal, early preview, GA, etc. */ Filters["TargetPopulation"] = "X-VSCode-TargetPopulation"; })(Filters = exports.Filters || (exports.Filters = {})); /** * Specifies the target population for the experimentation filter. */ var TargetPopulation; (function (TargetPopulation) { TargetPopulation["Team"] = "team"; TargetPopulation["Internal"] = "internal"; TargetPopulation["Insiders"] = "insider"; TargetPopulation["Public"] = "public"; })(TargetPopulation = exports.TargetPopulation || (exports.TargetPopulation = {})); //# sourceMappingURL=VSCodeFilterProvider.js.map /***/ }), /***/ 2050: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const VSCodeFilterProvider_1 = __webpack_require__(4978); const tas_client_1 = __webpack_require__(4248); const vscode = __webpack_require__(7549); const MementoKeyValueStorage_1 = __webpack_require__(4091); const TelemetryDisabledExperimentationService_1 = __webpack_require__(2545); const endpoint = 'https://default.exp-tas.com/vscode/ab'; const telemetryEventName = 'query-expfeature'; const featuresTelemetryPropertyName = 'VSCode.ABExp.Features'; const assignmentContextTelemetryPropertyName = 'abexp.assignmentcontext'; const storageKey = 'VSCode.ABExp.FeatureData'; const refetchInterval = 1000 * 60 * 30; // By default it's set up to 30 minutes. /** * * @param extensionName The name of the extension. * @param extensionVersion The version of the extension. * @param telemetry Telemetry implementation. * @param targetPopulation An enum containing the target population ('team', 'internal', 'insiders', 'public'). * @param memento The memento state to be used for cache. * @param filterProviders The filter providers. */ function getExperimentationService(extensionName, extensionVersion, targetPopulation, telemetry, memento, ...filterProviders) { if (!memento) { throw new Error('Memento storage was not provided.'); } const config = vscode.workspace.getConfiguration('telemetry'); const telemetryEnabled = vscode.env.isTelemetryEnabled === undefined ? config.get('enableTelemetry', true) : vscode.env.isTelemetryEnabled; if (!telemetryEnabled) { return new TelemetryDisabledExperimentationService_1.default(); } const extensionFilterProvider = new VSCodeFilterProvider_1.VSCodeFilterProvider(extensionName, extensionVersion, targetPopulation); const providerList = [extensionFilterProvider, ...filterProviders]; const keyValueStorage = new MementoKeyValueStorage_1.MementoKeyValueStorage(memento); return new tas_client_1.ExperimentationService({ filterProviders: providerList, telemetry: telemetry, storageKey: storageKey, keyValueStorage: keyValueStorage, featuresTelemetryPropertyName: featuresTelemetryPropertyName, assignmentContextTelemetryPropertyName: assignmentContextTelemetryPropertyName, telemetryEventName: telemetryEventName, endpoint: endpoint, refetchInterval: refetchInterval, }); } exports.getExperimentationService = getExperimentationService; /** * Returns the experimentation service after waiting on initialize. * * @param extensionName The name of the extension. * @param extensionVersion The version of the extension. * @param telemetry Telemetry implementation. * @param targetPopulation An enum containing the target population ('team', 'internal', 'insiders', 'public'). * @param memento The memento state to be used for cache. * @param filterProviders The filter providers. */ async function getExperimentationServiceAsync(extensionName, extensionVersion, targetPopulation, telemetry, memento, ...filterProviders) { const experimentationService = getExperimentationService(extensionName, extensionVersion, targetPopulation, telemetry, memento, ...filterProviders); await experimentationService.initializePromise; return experimentationService; } exports.getExperimentationServiceAsync = getExperimentationServiceAsync; //# sourceMappingURL=VSCodeTasClient.js.map /***/ }), /***/ 8750: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const isWindows = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys' const path = __webpack_require__(5622) const COLON = isWindows ? ';' : ':' const isexe = __webpack_require__(4219) const getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) const getPathInfo = (cmd, opt) => { const colon = opt.colon || COLON // If it has a slash, then we don't bother searching the pathenv. // just check the file itself, and that's it. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] : ( [ // windows always checks the cwd first ...(isWindows ? [process.cwd()] : []), ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ '').split(colon), ] ) const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' : '' const pathExt = isWindows ? pathExtExe.split(colon) : [''] if (isWindows) { if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift('') } return { pathEnv, pathExt, pathExtExe, } } const which = (cmd, opt, cb) => { if (typeof opt === 'function') { cb = opt opt = {} } if (!opt) opt = {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] const step = i => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)) const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd resolve(subStep(p, i, 0)) }) const subStep = (p, i, ii) => new Promise((resolve, reject) => { if (ii === pathExt.length) return resolve(step(i + 1)) const ext = pathExt[ii] isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { if (!er && is) { if (opt.all) found.push(p + ext) else return resolve(p + ext) } return resolve(subStep(p, i, ii + 1)) }) }) return cb ? step(0).then(res => cb(null, res), cb) : step(0) } const whichSync = (cmd, opt) => { opt = opt || {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] for (let i = 0; i < pathEnv.length; i ++) { const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd for (let j = 0; j < pathExt.length; j ++) { const cur = p + pathExt[j] try { const is = isexe.sync(cur, { pathExt: pathExtExe }) if (is) { if (opt.all) found.push(cur) else return cur } } catch (ex) {} } } if (opt.all && found.length) return found if (opt.nothrow) return null throw getNotFoundError(cmd) } module.exports = which which.sync = whichSync /***/ }), /***/ 7534: /***/ ((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 } } /***/ }), /***/ 4753: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var __webpack_unused_export__; function DOMParser(options){ this.options = options ||{locator:{}}; } DOMParser.prototype.parseFromString = function(source,mimeType){ var options = this.options; var sax = new XMLReader(); var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler var errorHandler = options.errorHandler; var locator = options.locator; var defaultNSMap = options.xmlns||{}; var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1; var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"}; if(locator){ domBuilder.setDocumentLocator(locator) } sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator); sax.domBuilder = options.domBuilder || domBuilder; if(isHTML){ defaultNSMap['']= 'http://www.w3.org/1999/xhtml'; } defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace'; if(source && typeof source === 'string'){ sax.parse(source,defaultNSMap,entityMap); }else{ sax.errorHandler.error("invalid doc source"); } return domBuilder.doc; } function buildErrorHandler(errorImpl,domBuilder,locator){ if(!errorImpl){ if(domBuilder instanceof DOMHandler){ return domBuilder; } errorImpl = domBuilder ; } var errorHandler = {} var isCallback = errorImpl instanceof Function; locator = locator||{} function build(key){ var fn = errorImpl[key]; if(!fn && isCallback){ fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl; } errorHandler[key] = fn && function(msg){ fn('[xmldom '+key+']\t'+msg+_locator(locator)); }||function(){}; } build('warning'); build('error'); build('fatalError'); return errorHandler; } //console.log('#\n\n\n\n\n\n\n####') /** * +ContentHandler+ErrorHandler * +LexicalHandler+EntityResolver2 * -DeclHandler-DTDHandler * * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2 * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html */ function DOMHandler() { this.cdata = false; } function position(locator,node){ node.lineNumber = locator.lineNumber; node.columnNumber = locator.columnNumber; } /** * @see org.xml.sax.ContentHandler#startDocument * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html */ DOMHandler.prototype = { startDocument : function() { this.doc = new DOMImplementation().createDocument(null, null, null); if (this.locator) { this.doc.documentURI = this.locator.systemId; } }, startElement:function(namespaceURI, localName, qName, attrs) { var doc = this.doc; var el = doc.createElementNS(namespaceURI, qName||localName); var len = attrs.length; appendElement(this, el); this.currentElement = el; this.locator && position(this.locator,el) for (var i = 0 ; i < len; i++) { var namespaceURI = attrs.getURI(i); var value = attrs.getValue(i); var qName = attrs.getQName(i); var attr = doc.createAttributeNS(namespaceURI, qName); this.locator &&position(attrs.getLocator(i),attr); attr.value = attr.nodeValue = value; el.setAttributeNode(attr) } }, endElement:function(namespaceURI, localName, qName) { var current = this.currentElement var tagName = current.tagName; this.currentElement = current.parentNode; }, startPrefixMapping:function(prefix, uri) { }, endPrefixMapping:function(prefix) { }, processingInstruction:function(target, data) { var ins = this.doc.createProcessingInstruction(target, data); this.locator && position(this.locator,ins) appendElement(this, ins); }, ignorableWhitespace:function(ch, start, length) { }, characters:function(chars, start, length) { chars = _toString.apply(this,arguments) //console.log(chars) if(chars){ if (this.cdata) { var charNode = this.doc.createCDATASection(chars); } else { var charNode = this.doc.createTextNode(chars); } if(this.currentElement){ this.currentElement.appendChild(charNode); }else if(/^\s*$/.test(chars)){ this.doc.appendChild(charNode); //process xml } this.locator && position(this.locator,charNode) } }, skippedEntity:function(name) { }, endDocument:function() { this.doc.normalize(); }, setDocumentLocator:function (locator) { if(this.locator = locator){// && !('lineNumber' in locator)){ locator.lineNumber = 0; } }, //LexicalHandler comment:function(chars, start, length) { chars = _toString.apply(this,arguments) var comm = this.doc.createComment(chars); this.locator && position(this.locator,comm) appendElement(this, comm); }, startCDATA:function() { //used in characters() methods this.cdata = true; }, endCDATA:function() { this.cdata = false; }, startDTD:function(name, publicId, systemId) { var impl = this.doc.implementation; if (impl && impl.createDocumentType) { var dt = impl.createDocumentType(name, publicId, systemId); this.locator && position(this.locator,dt) appendElement(this, dt); } }, /** * @see org.xml.sax.ErrorHandler * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html */ warning:function(error) { console.warn('[xmldom warning]\t'+error,_locator(this.locator)); }, error:function(error) { console.error('[xmldom error]\t'+error,_locator(this.locator)); }, fatalError:function(error) { throw new ParseError(error, this.locator); } } function _locator(l){ if(l){ return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']' } } function _toString(chars,start,length){ if(typeof chars == 'string'){ return chars.substr(start,length) }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)") if(chars.length >= start+length || start){ return new java.lang.String(chars,start,length)+''; } return chars; } } /* * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html * used method of org.xml.sax.ext.LexicalHandler: * #comment(chars, start, length) * #startCDATA() * #endCDATA() * #startDTD(name, publicId, systemId) * * * IGNORED method of org.xml.sax.ext.LexicalHandler: * #endDTD() * #startEntity(name) * #endEntity(name) * * * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html * IGNORED method of org.xml.sax.ext.DeclHandler * #attributeDecl(eName, aName, type, mode, value) * #elementDecl(name, model) * #externalEntityDecl(name, publicId, systemId) * #internalEntityDecl(name, value) * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html * IGNORED method of org.xml.sax.EntityResolver2 * #resolveEntity(String name,String publicId,String baseURI,String systemId) * #resolveEntity(publicId, systemId) * #getExternalSubset(name, baseURI) * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html * IGNORED method of org.xml.sax.DTDHandler * #notationDecl(name, publicId, systemId) {}; * #unparsedEntityDecl(name, publicId, systemId, notationName) {}; */ "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){ DOMHandler.prototype[key] = function(){return null} }) /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */ function appendElement (hander,node) { if (!hander.currentElement) { hander.doc.appendChild(node); } else { hander.currentElement.appendChild(node); } }//appendChild and setAttributeNS are preformance key //if(typeof require == 'function'){ var htmlEntity = __webpack_require__(9742); var sax = __webpack_require__(3303); var XMLReader = sax.XMLReader; var ParseError = sax.ParseError; var DOMImplementation = /* unused reexport */ __webpack_require__(2095).DOMImplementation; /* unused reexport */ __webpack_require__(2095) ; exports.a = DOMParser; __webpack_unused_export__ = DOMHandler; //} /***/ }), /***/ 2095: /***/ ((__unused_webpack_module, exports) => { var __webpack_unused_export__; function copy(src,dest){ for(var p in src){ dest[p] = src[p]; } } /** ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));? ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));? */ function _extends(Class,Super){ var pt = Class.prototype; if(!(pt instanceof Super)){ function t(){}; t.prototype = Super.prototype; t = new t(); copy(pt,t); Class.prototype = pt = t; } if(pt.constructor != Class){ if(typeof Class != 'function'){ console.error("unknow Class:"+Class) } pt.constructor = Class } } var htmlns = 'http://www.w3.org/1999/xhtml' ; // Node Types var NodeType = {} var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1; var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2; var TEXT_NODE = NodeType.TEXT_NODE = 3; var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4; var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5; var ENTITY_NODE = NodeType.ENTITY_NODE = 6; var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7; var COMMENT_NODE = NodeType.COMMENT_NODE = 8; var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9; var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10; var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11; var NOTATION_NODE = NodeType.NOTATION_NODE = 12; // ExceptionCode var ExceptionCode = {} var ExceptionMessage = {}; var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1); var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2); var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3); var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4); var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5); var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6); var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7); var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8); var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9); var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10); //level2 var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11); var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12); var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13); var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14); var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15); /** * DOM Level 2 * Object DOMException * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html */ function DOMException(code, message) { if(message instanceof Error){ var error = message; }else{ error = this; Error.call(this, ExceptionMessage[code]); this.message = ExceptionMessage[code]; if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException); } error.code = code; if(message) this.message = this.message + ": " + message; return error; }; DOMException.prototype = Error.prototype; copy(ExceptionCode,DOMException) /** * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177 * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live. * The items in the NodeList are accessible via an integral index, starting from 0. */ function NodeList() { }; NodeList.prototype = { /** * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive. * @standard level1 */ length:0, /** * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null. * @standard level1 * @param index unsigned long * Index into the collection. * @return Node * The node at the indexth position in the NodeList, or null if that is not a valid index. */ item: function(index) { return this[index] || null; }, toString:function(isHTML,nodeFilter){ for(var buf = [], i = 0;i=0){ var lastIndex = list.length-1 while(i0 || key == 'xmlns'){ // return null; // } //console.log() var i = this.length; while(i--){ var attr = this[i]; //console.log(attr.nodeName,key) if(attr.nodeName == key){ return attr; } } }, setNamedItem: function(attr) { var el = attr.ownerElement; if(el && el!=this._ownerElement){ throw new DOMException(INUSE_ATTRIBUTE_ERR); } var oldAttr = this.getNamedItem(attr.nodeName); _addNamedNode(this._ownerElement,this,attr,oldAttr); return oldAttr; }, /* returns Node */ setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR var el = attr.ownerElement, oldAttr; if(el && el!=this._ownerElement){ throw new DOMException(INUSE_ATTRIBUTE_ERR); } oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName); _addNamedNode(this._ownerElement,this,attr,oldAttr); return oldAttr; }, /* returns Node */ removeNamedItem: function(key) { var attr = this.getNamedItem(key); _removeNamedNode(this._ownerElement,this,attr); return attr; },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR //for level2 removeNamedItemNS:function(namespaceURI,localName){ var attr = this.getNamedItemNS(namespaceURI,localName); _removeNamedNode(this._ownerElement,this,attr); return attr; }, getNamedItemNS: function(namespaceURI, localName) { var i = this.length; while(i--){ var node = this[i]; if(node.localName == localName && node.namespaceURI == namespaceURI){ return node; } } return null; } }; /** * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 */ function DOMImplementation(/* Object */ features) { this._features = {}; if (features) { for (var feature in features) { this._features = features[feature]; } } }; DOMImplementation.prototype = { hasFeature: function(/* string */ feature, /* string */ version) { var versions = this._features[feature.toLowerCase()]; if (versions && (!version || version in versions)) { return true; } else { return false; } }, // Introduced in DOM Level 2: createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR var doc = new Document(); doc.implementation = this; doc.childNodes = new NodeList(); doc.doctype = doctype; if(doctype){ doc.appendChild(doctype); } if(qualifiedName){ var root = doc.createElementNS(namespaceURI,qualifiedName); doc.appendChild(root); } return doc; }, // Introduced in DOM Level 2: createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR var node = new DocumentType(); node.name = qualifiedName; node.nodeName = qualifiedName; node.publicId = publicId; node.systemId = systemId; // Introduced in DOM Level 2: //readonly attribute DOMString internalSubset; //TODO:.. // readonly attribute NamedNodeMap entities; // readonly attribute NamedNodeMap notations; return node; } }; /** * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 */ function Node() { }; Node.prototype = { firstChild : null, lastChild : null, previousSibling : null, nextSibling : null, attributes : null, parentNode : null, childNodes : null, ownerDocument : null, nodeValue : null, namespaceURI : null, prefix : null, localName : null, // Modified in DOM Level 2: insertBefore:function(newChild, refChild){//raises return _insertBefore(this,newChild,refChild); }, replaceChild:function(newChild, oldChild){//raises this.insertBefore(newChild,oldChild); if(oldChild){ this.removeChild(oldChild); } }, removeChild:function(oldChild){ return _removeChild(this,oldChild); }, appendChild:function(newChild){ return this.insertBefore(newChild,null); }, hasChildNodes:function(){ return this.firstChild != null; }, cloneNode:function(deep){ return cloneNode(this.ownerDocument||this,this,deep); }, // Modified in DOM Level 2: normalize:function(){ var child = this.firstChild; while(child){ var next = child.nextSibling; if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){ this.removeChild(next); child.appendData(next.data); }else{ child.normalize(); child = next; } } }, // Introduced in DOM Level 2: isSupported:function(feature, version){ return this.ownerDocument.implementation.hasFeature(feature,version); }, // Introduced in DOM Level 2: hasAttributes:function(){ return this.attributes.length>0; }, lookupPrefix:function(namespaceURI){ var el = this; while(el){ var map = el._nsMap; //console.dir(map) if(map){ for(var n in map){ if(map[n] == namespaceURI){ return n; } } } el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; } return null; }, // Introduced in DOM Level 3: lookupNamespaceURI:function(prefix){ var el = this; while(el){ var map = el._nsMap; //console.dir(map) if(map){ if(prefix in map){ return map[prefix] ; } } el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; } return null; }, // Introduced in DOM Level 3: isDefaultNamespace:function(namespaceURI){ var prefix = this.lookupPrefix(namespaceURI); return prefix == null; } }; function _xmlEncoder(c){ return c == '<' && '<' || c == '>' && '>' || c == '&' && '&' || c == '"' && '"' || '&#'+c.charCodeAt()+';' } copy(NodeType,Node); copy(NodeType,Node.prototype); /** * @param callback return true for continue,false for break * @return boolean true: break visit; */ function _visitNode(node,callback){ if(callback(node)){ return true; } if(node = node.firstChild){ do{ if(_visitNode(node,callback)){return true} }while(node=node.nextSibling) } } function Document(){ } function _onAddAttribute(doc,el,newAttr){ doc && doc._inc++; var ns = newAttr.namespaceURI ; if(ns == 'http://www.w3.org/2000/xmlns/'){ //update namespace el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value } } function _onRemoveAttribute(doc,el,newAttr,remove){ doc && doc._inc++; var ns = newAttr.namespaceURI ; if(ns == 'http://www.w3.org/2000/xmlns/'){ //update namespace delete el._nsMap[newAttr.prefix?newAttr.localName:''] } } function _onUpdateChild(doc,el,newChild){ if(doc && doc._inc){ doc._inc++; //update childNodes var cs = el.childNodes; if(newChild){ cs[cs.length++] = newChild; }else{ //console.log(1) var child = el.firstChild; var i = 0; while(child){ cs[i++] = child; child =child.nextSibling; } cs.length = i; } } } /** * attributes; * children; * * writeable properties: * nodeValue,Attr:value,CharacterData:data * prefix */ function _removeChild(parentNode,child){ var previous = child.previousSibling; var next = child.nextSibling; if(previous){ previous.nextSibling = next; }else{ parentNode.firstChild = next } if(next){ next.previousSibling = previous; }else{ parentNode.lastChild = previous; } _onUpdateChild(parentNode.ownerDocument,parentNode); return child; } /** * preformance key(refChild == null) */ function _insertBefore(parentNode,newChild,nextChild){ var cp = newChild.parentNode; if(cp){ cp.removeChild(newChild);//remove and update } if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ var newFirst = newChild.firstChild; if (newFirst == null) { return newChild; } var newLast = newChild.lastChild; }else{ newFirst = newLast = newChild; } var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild; newFirst.previousSibling = pre; newLast.nextSibling = nextChild; if(pre){ pre.nextSibling = newFirst; }else{ parentNode.firstChild = newFirst; } if(nextChild == null){ parentNode.lastChild = newLast; }else{ nextChild.previousSibling = newLast; } do{ newFirst.parentNode = parentNode; }while(newFirst !== newLast && (newFirst= newFirst.nextSibling)) _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode); //console.log(parentNode.lastChild.nextSibling == null) if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) { newChild.firstChild = newChild.lastChild = null; } return newChild; } function _appendSingleChild(parentNode,newChild){ var cp = newChild.parentNode; if(cp){ var pre = parentNode.lastChild; cp.removeChild(newChild);//remove and update var pre = parentNode.lastChild; } var pre = parentNode.lastChild; newChild.parentNode = parentNode; newChild.previousSibling = pre; newChild.nextSibling = null; if(pre){ pre.nextSibling = newChild; }else{ parentNode.firstChild = newChild; } parentNode.lastChild = newChild; _onUpdateChild(parentNode.ownerDocument,parentNode,newChild); return newChild; //console.log("__aa",parentNode.lastChild.nextSibling == null) } Document.prototype = { //implementation : null, nodeName : '#document', nodeType : DOCUMENT_NODE, doctype : null, documentElement : null, _inc : 1, insertBefore : function(newChild, refChild){//raises if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){ var child = newChild.firstChild; while(child){ var next = child.nextSibling; this.insertBefore(child,refChild); child = next; } return newChild; } if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){ this.documentElement = newChild; } return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild; }, removeChild : function(oldChild){ if(this.documentElement == oldChild){ this.documentElement = null; } return _removeChild(this,oldChild); }, // Introduced in DOM Level 2: importNode : function(importedNode,deep){ return importNode(this,importedNode,deep); }, // Introduced in DOM Level 2: getElementById : function(id){ var rtv = null; _visitNode(this.documentElement,function(node){ if(node.nodeType == ELEMENT_NODE){ if(node.getAttribute('id') == id){ rtv = node; return true; } } }) return rtv; }, getElementsByClassName: function(className) { var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)"); return new LiveNodeList(this, function(base) { var ls = []; _visitNode(base.documentElement, function(node) { if(node !== base && node.nodeType == ELEMENT_NODE) { if(pattern.test(node.getAttribute('class'))) { ls.push(node); } } }); return ls; }); }, //document factory method: createElement : function(tagName){ var node = new Element(); node.ownerDocument = this; node.nodeName = tagName; node.tagName = tagName; node.childNodes = new NodeList(); var attrs = node.attributes = new NamedNodeMap(); attrs._ownerElement = node; return node; }, createDocumentFragment : function(){ var node = new DocumentFragment(); node.ownerDocument = this; node.childNodes = new NodeList(); return node; }, createTextNode : function(data){ var node = new Text(); node.ownerDocument = this; node.appendData(data) return node; }, createComment : function(data){ var node = new Comment(); node.ownerDocument = this; node.appendData(data) return node; }, createCDATASection : function(data){ var node = new CDATASection(); node.ownerDocument = this; node.appendData(data) return node; }, createProcessingInstruction : function(target,data){ var node = new ProcessingInstruction(); node.ownerDocument = this; node.tagName = node.target = target; node.nodeValue= node.data = data; return node; }, createAttribute : function(name){ var node = new Attr(); node.ownerDocument = this; node.name = name; node.nodeName = name; node.localName = name; node.specified = true; return node; }, createEntityReference : function(name){ var node = new EntityReference(); node.ownerDocument = this; node.nodeName = name; return node; }, // Introduced in DOM Level 2: createElementNS : function(namespaceURI,qualifiedName){ var node = new Element(); var pl = qualifiedName.split(':'); var attrs = node.attributes = new NamedNodeMap(); node.childNodes = new NodeList(); node.ownerDocument = this; node.nodeName = qualifiedName; node.tagName = qualifiedName; node.namespaceURI = namespaceURI; if(pl.length == 2){ node.prefix = pl[0]; node.localName = pl[1]; }else{ //el.prefix = null; node.localName = qualifiedName; } attrs._ownerElement = node; return node; }, // Introduced in DOM Level 2: createAttributeNS : function(namespaceURI,qualifiedName){ var node = new Attr(); var pl = qualifiedName.split(':'); node.ownerDocument = this; node.nodeName = qualifiedName; node.name = qualifiedName; node.namespaceURI = namespaceURI; node.specified = true; if(pl.length == 2){ node.prefix = pl[0]; node.localName = pl[1]; }else{ //el.prefix = null; node.localName = qualifiedName; } return node; } }; _extends(Document,Node); function Element() { this._nsMap = {}; }; Element.prototype = { nodeType : ELEMENT_NODE, hasAttribute : function(name){ return this.getAttributeNode(name)!=null; }, getAttribute : function(name){ var attr = this.getAttributeNode(name); return attr && attr.value || ''; }, getAttributeNode : function(name){ return this.attributes.getNamedItem(name); }, setAttribute : function(name, value){ var attr = this.ownerDocument.createAttribute(name); attr.value = attr.nodeValue = "" + value; this.setAttributeNode(attr) }, removeAttribute : function(name){ var attr = this.getAttributeNode(name) attr && this.removeAttributeNode(attr); }, //four real opeartion method appendChild:function(newChild){ if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ return this.insertBefore(newChild,null); }else{ return _appendSingleChild(this,newChild); } }, setAttributeNode : function(newAttr){ return this.attributes.setNamedItem(newAttr); }, setAttributeNodeNS : function(newAttr){ return this.attributes.setNamedItemNS(newAttr); }, removeAttributeNode : function(oldAttr){ //console.log(this == oldAttr.ownerElement) return this.attributes.removeNamedItem(oldAttr.nodeName); }, //get real attribute name,and remove it by removeAttributeNode removeAttributeNS : function(namespaceURI, localName){ var old = this.getAttributeNodeNS(namespaceURI, localName); old && this.removeAttributeNode(old); }, hasAttributeNS : function(namespaceURI, localName){ return this.getAttributeNodeNS(namespaceURI, localName)!=null; }, getAttributeNS : function(namespaceURI, localName){ var attr = this.getAttributeNodeNS(namespaceURI, localName); return attr && attr.value || ''; }, setAttributeNS : function(namespaceURI, qualifiedName, value){ var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName); attr.value = attr.nodeValue = "" + value; this.setAttributeNode(attr) }, getAttributeNodeNS : function(namespaceURI, localName){ return this.attributes.getNamedItemNS(namespaceURI, localName); }, getElementsByTagName : function(tagName){ return new LiveNodeList(this,function(base){ var ls = []; _visitNode(base,function(node){ if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){ ls.push(node); } }); return ls; }); }, getElementsByTagNameNS : function(namespaceURI, localName){ return new LiveNodeList(this,function(base){ var ls = []; _visitNode(base,function(node){ if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){ ls.push(node); } }); return ls; }); } }; Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName; Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS; _extends(Element,Node); function Attr() { }; Attr.prototype.nodeType = ATTRIBUTE_NODE; _extends(Attr,Node); function CharacterData() { }; CharacterData.prototype = { data : '', substringData : function(offset, count) { return this.data.substring(offset, offset+count); }, appendData: function(text) { text = this.data+text; this.nodeValue = this.data = text; this.length = text.length; }, insertData: function(offset,text) { this.replaceData(offset,0,text); }, appendChild:function(newChild){ throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]) }, deleteData: function(offset, count) { this.replaceData(offset,count,""); }, replaceData: function(offset, count, text) { var start = this.data.substring(0,offset); var end = this.data.substring(offset+count); text = start + text + end; this.nodeValue = this.data = text; this.length = text.length; } } _extends(CharacterData,Node); function Text() { }; Text.prototype = { nodeName : "#text", nodeType : TEXT_NODE, splitText : function(offset) { var text = this.data; var newText = text.substring(offset); text = text.substring(0, offset); this.data = this.nodeValue = text; this.length = text.length; var newNode = this.ownerDocument.createTextNode(newText); if(this.parentNode){ this.parentNode.insertBefore(newNode, this.nextSibling); } return newNode; } } _extends(Text,CharacterData); function Comment() { }; Comment.prototype = { nodeName : "#comment", nodeType : COMMENT_NODE } _extends(Comment,CharacterData); function CDATASection() { }; CDATASection.prototype = { nodeName : "#cdata-section", nodeType : CDATA_SECTION_NODE } _extends(CDATASection,CharacterData); function DocumentType() { }; DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE; _extends(DocumentType,Node); function Notation() { }; Notation.prototype.nodeType = NOTATION_NODE; _extends(Notation,Node); function Entity() { }; Entity.prototype.nodeType = ENTITY_NODE; _extends(Entity,Node); function EntityReference() { }; EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE; _extends(EntityReference,Node); function DocumentFragment() { }; DocumentFragment.prototype.nodeName = "#document-fragment"; DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE; _extends(DocumentFragment,Node); function ProcessingInstruction() { } ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE; _extends(ProcessingInstruction,Node); function XMLSerializer(){} XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){ return nodeSerializeToString.call(node,isHtml,nodeFilter); } Node.prototype.toString = nodeSerializeToString; function nodeSerializeToString(isHtml,nodeFilter){ var buf = []; var refNode = this.nodeType == 9 && this.documentElement || this; var prefix = refNode.prefix; var uri = refNode.namespaceURI; if(uri && prefix == null){ //console.log(prefix) var prefix = refNode.lookupPrefix(uri); if(prefix == null){ //isHTML = true; var visibleNamespaces=[ {namespace:uri,prefix:null} //{namespace:uri,prefix:''} ] } } serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces); //console.log('###',this.nodeType,uri,prefix,buf.join('')) return buf.join(''); } function needNamespaceDefine(node,isHTML, visibleNamespaces) { var prefix = node.prefix||''; var uri = node.namespaceURI; if (!prefix && !uri){ return false; } if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace" || uri == 'http://www.w3.org/2000/xmlns/'){ return false; } var i = visibleNamespaces.length //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces) while (i--) { var ns = visibleNamespaces[i]; // get namespace prefix //console.log(node.nodeType,node.tagName,ns.prefix,prefix) if (ns.prefix == prefix){ return ns.namespace != uri; } } //console.log(isHTML,uri,prefix=='') //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){ // return false; //} //node.flag = '11111' //console.error(3,true,node.flag,node.prefix,node.namespaceURI) return true; } function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){ if(nodeFilter){ node = nodeFilter(node); if(node){ if(typeof node == 'string'){ buf.push(node); return; } }else{ return; } //buf.sort.apply(attrs, attributeSorter); } switch(node.nodeType){ case ELEMENT_NODE: if (!visibleNamespaces) visibleNamespaces = []; var startVisibleNamespaces = visibleNamespaces.length; var attrs = node.attributes; var len = attrs.length; var child = node.firstChild; var nodeName = node.tagName; isHTML = (htmlns === node.namespaceURI) ||isHTML buf.push('<',nodeName); for(var i=0;i'); //if is cdata child node if(isHTML && /^script$/i.test(nodeName)){ while(child){ if(child.data){ buf.push(child.data); }else{ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); } child = child.nextSibling; } }else { while(child){ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); child = child.nextSibling; } } buf.push(''); }else{ buf.push('/>'); } // remove added visible namespaces //visibleNamespaces.length = startVisibleNamespaces; return; case DOCUMENT_NODE: case DOCUMENT_FRAGMENT_NODE: var child = node.firstChild; while(child){ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); child = child.nextSibling; } return; case ATTRIBUTE_NODE: return buf.push(' ',node.name,'="',node.value.replace(/[&"]/g,_xmlEncoder),'"'); case TEXT_NODE: /** * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. * If they are needed elsewhere, they must be escaped using either numeric character references or the strings * `&` and `<` respectively. * The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, * be escaped using either `>` or a character reference when it appears in the string `]]>` in content, * when that string is not marking the end of a CDATA section. * * In the content of elements, character data is any string of characters * which does not contain the start-delimiter of any markup * and does not include the CDATA-section-close delimiter, `]]>`. * * @see https://www.w3.org/TR/xml/#NT-CharData */ return buf.push(node.data .replace(/[<&]/g,_xmlEncoder) .replace(/]]>/g, ']]>') ); case CDATA_SECTION_NODE: return buf.push( ''); case COMMENT_NODE: return buf.push( ""); case DOCUMENT_TYPE_NODE: var pubid = node.publicId; var sysid = node.systemId; buf.push(''); }else if(sysid && sysid!='.'){ buf.push(' SYSTEM ', sysid, '>'); }else{ var sub = node.internalSubset; if(sub){ buf.push(" [",sub,"]"); } buf.push(">"); } return; case PROCESSING_INSTRUCTION_NODE: return buf.push( ""); case ENTITY_REFERENCE_NODE: return buf.push( '&',node.nodeName,';'); //case ENTITY_NODE: //case NOTATION_NODE: default: buf.push('??',node.nodeName); } } function importNode(doc,node,deep){ var node2; switch (node.nodeType) { case ELEMENT_NODE: node2 = node.cloneNode(false); node2.ownerDocument = doc; //var attrs = node2.attributes; //var len = attrs.length; //for(var i=0;i { exports.entityMap = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'", Agrave: "À", Aacute: "Á", Acirc: "Â", Atilde: "Ã", Auml: "Ä", Aring: "Å", AElig: "Æ", Ccedil: "Ç", Egrave: "È", Eacute: "É", Ecirc: "Ê", Euml: "Ë", Igrave: "Ì", Iacute: "Í", Icirc: "Î", Iuml: "Ï", ETH: "Ð", Ntilde: "Ñ", Ograve: "Ò", Oacute: "Ó", Ocirc: "Ô", Otilde: "Õ", Ouml: "Ö", Oslash: "Ø", Ugrave: "Ù", Uacute: "Ú", Ucirc: "Û", Uuml: "Ü", Yacute: "Ý", THORN: "Þ", szlig: "ß", agrave: "à", aacute: "á", acirc: "â", atilde: "ã", auml: "ä", aring: "å", aelig: "æ", ccedil: "ç", egrave: "è", eacute: "é", ecirc: "ê", euml: "ë", igrave: "ì", iacute: "í", icirc: "î", iuml: "ï", eth: "ð", ntilde: "ñ", ograve: "ò", oacute: "ó", ocirc: "ô", otilde: "õ", ouml: "ö", oslash: "ø", ugrave: "ù", uacute: "ú", ucirc: "û", uuml: "ü", yacute: "ý", thorn: "þ", yuml: "ÿ", nbsp: "\u00a0", iexcl: "¡", cent: "¢", pound: "£", curren: "¤", yen: "¥", brvbar: "¦", sect: "§", uml: "¨", copy: "©", ordf: "ª", laquo: "«", not: "¬", shy: "­­", reg: "®", macr: "¯", deg: "°", plusmn: "±", sup2: "²", sup3: "³", acute: "´", micro: "µ", para: "¶", middot: "·", cedil: "¸", sup1: "¹", ordm: "º", raquo: "»", frac14: "¼", frac12: "½", frac34: "¾", iquest: "¿", times: "×", divide: "÷", forall: "∀", part: "∂", exist: "∃", empty: "∅", nabla: "∇", isin: "∈", notin: "∉", ni: "∋", prod: "∏", sum: "∑", minus: "−", lowast: "∗", radic: "√", prop: "∝", infin: "∞", ang: "∠", and: "∧", or: "∨", cap: "∩", cup: "∪", 'int': "∫", there4: "∴", sim: "∼", cong: "≅", asymp: "≈", ne: "≠", equiv: "≡", le: "≤", ge: "≥", sub: "⊂", sup: "⊃", nsub: "⊄", sube: "⊆", supe: "⊇", oplus: "⊕", otimes: "⊗", perp: "⊥", sdot: "⋅", Alpha: "Α", Beta: "Β", Gamma: "Γ", Delta: "Δ", Epsilon: "Ε", Zeta: "Ζ", Eta: "Η", Theta: "Θ", Iota: "Ι", Kappa: "Κ", Lambda: "Λ", Mu: "Μ", Nu: "Ν", Xi: "Ξ", Omicron: "Ο", Pi: "Π", Rho: "Ρ", Sigma: "Σ", Tau: "Τ", Upsilon: "Υ", Phi: "Φ", Chi: "Χ", Psi: "Ψ", Omega: "Ω", alpha: "α", beta: "β", gamma: "γ", delta: "δ", epsilon: "ε", zeta: "ζ", eta: "η", theta: "θ", iota: "ι", kappa: "κ", lambda: "λ", mu: "μ", nu: "ν", xi: "ξ", omicron: "ο", pi: "π", rho: "ρ", sigmaf: "ς", sigma: "σ", tau: "τ", upsilon: "υ", phi: "φ", chi: "χ", psi: "ψ", omega: "ω", thetasym: "ϑ", upsih: "ϒ", piv: "ϖ", OElig: "Œ", oelig: "œ", Scaron: "Š", scaron: "š", Yuml: "Ÿ", fnof: "ƒ", circ: "ˆ", tilde: "˜", ensp: " ", emsp: " ", thinsp: " ", zwnj: "‌", zwj: "‍", lrm: "‎", rlm: "‏", ndash: "–", mdash: "—", lsquo: "‘", rsquo: "’", sbquo: "‚", ldquo: "“", rdquo: "”", bdquo: "„", dagger: "†", Dagger: "‡", bull: "•", hellip: "…", permil: "‰", prime: "′", Prime: "″", lsaquo: "‹", rsaquo: "›", oline: "‾", euro: "€", trade: "™", larr: "←", uarr: "↑", rarr: "→", darr: "↓", harr: "↔", crarr: "↵", lceil: "⌈", rceil: "⌉", lfloor: "⌊", rfloor: "⌋", loz: "◊", spades: "♠", clubs: "♣", hearts: "♥", diams: "♦" }; /***/ }), /***/ 3303: /***/ ((__unused_webpack_module, exports) => { //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] //[5] Name ::= NameStartChar (NameChar)* var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"); var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$'); //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/ //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',') //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE var S_TAG = 0;//tag name offerring var S_ATTR = 1;//attr name offerring var S_ATTR_SPACE=2;//attr name end and space offer var S_EQ = 3;//=space? var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only) var S_ATTR_END = 5;//attr value end and no space(quot end) var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer) var S_TAG_CLOSE = 7;//closed el /** * Creates an error that will not be caught by XMLReader aka the SAX parser. * * @param {string} message * @param {any?} locator Optional, can provide details about the location in the source * @constructor */ function ParseError(message, locator) { this.message = message this.locator = locator if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError); } ParseError.prototype = new Error(); ParseError.prototype.name = ParseError.name function XMLReader(){ } XMLReader.prototype = { parse:function(source,defaultNSMap,entityMap){ var domBuilder = this.domBuilder; domBuilder.startDocument(); _copy(defaultNSMap ,defaultNSMap = {}) parse(source,defaultNSMap,entityMap, domBuilder,this.errorHandler); domBuilder.endDocument(); } } function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){ function fixedFromCharCode(code) { // String.prototype.fromCharCode does not supports // > 2 bytes unicode chars directly if (code > 0xffff) { code -= 0x10000; var surrogate1 = 0xd800 + (code >> 10) , surrogate2 = 0xdc00 + (code & 0x3ff); return String.fromCharCode(surrogate1, surrogate2); } else { return String.fromCharCode(code); } } function entityReplacer(a){ var k = a.slice(1,-1); if(k in entityMap){ return entityMap[k]; }else if(k.charAt(0) === '#'){ return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x'))) }else{ errorHandler.error('entity not found:'+a); return a; } } function appendText(end){//has some bugs if(end>start){ var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer); locator&&position(start); domBuilder.characters(xt,0,end-start); start = end } } function position(p,m){ while(p>=lineEnd && (m = linePattern.exec(source))){ lineStart = m.index; lineEnd = lineStart + m[0].length; locator.lineNumber++; //console.log('line++:',locator,startPos,endPos) } locator.columnNumber = p-lineStart+1; } var lineStart = 0; var lineEnd = 0; var linePattern = /.*(?:\r\n?|\n)|.*$/g var locator = domBuilder.locator; var parseStack = [{currentNSMap:defaultNSMapCopy}] var closeMap = {}; var start = 0; while(true){ try{ var tagStart = source.indexOf('<',start); if(tagStart<0){ if(!source.substr(start).match(/^\s*$/)){ var doc = domBuilder.doc; var text = doc.createTextNode(source.substr(start)); doc.appendChild(text); domBuilder.currentElement = text; } return; } if(tagStart>start){ appendText(tagStart); } switch(source.charAt(tagStart+1)){ case '/': var end = source.indexOf('>',tagStart+3); var tagName = source.substring(tagStart+2,end); var config = parseStack.pop(); if(end<0){ tagName = source.substring(tagStart+2).replace(/[\s<].*/,''); //console.error('#@@@@@@'+tagName) errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName); end = tagStart+1+tagName.length; }else if(tagName.match(/\s locator&&position(tagStart); end = parseInstruction(source,tagStart,domBuilder); break; case '!':// start){ start = end; }else{ //TODO: 这里有可能sax回退,有位置错误风险 appendText(Math.max(tagStart,start)+1); } } } function copyLocator(f,t){ t.lineNumber = f.lineNumber; t.columnNumber = f.columnNumber; return t; } /** * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack); * @return end of the elementStartPart(end of elementEndPart for selfClosed el) */ function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){ /** * @param {string} qname * @param {string} value * @param {number} startIndex */ function addAttribute(qname, value, startIndex) { if (qname in el.attributeNames) errorHandler.fatalError('Attribute ' + qname + ' redefined') el.addValue(qname, value, startIndex) } var attrName; var value; var p = ++start; var s = S_TAG;//status while(true){ var c = source.charAt(p); switch(c){ case '=': if(s === S_ATTR){//attrName attrName = source.slice(start,p); s = S_EQ; }else if(s === S_ATTR_SPACE){ s = S_EQ; }else{ //fatalError: equal must after attrName or space after attrName throw new Error('attribute equal must after attrName'); // No known test case } break; case '\'': case '"': if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE ){//equal if(s === S_ATTR){ errorHandler.warning('attribute value must after "="') attrName = source.slice(start,p) } start = p+1; p = source.indexOf(c,start) if(p>0){ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); addAttribute(attrName, value, start-1); s = S_ATTR_END; }else{ //fatalError: no end quot match throw new Error('attribute value no end \''+c+'\' match'); } }else if(s == S_ATTR_NOQUOT_VALUE){ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); //console.log(attrName,value,start,p) addAttribute(attrName, value, start); //console.dir(el) errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!'); start = p+1; s = S_ATTR_END }else{ //fatalError: no equal before throw new Error('attribute value must after "="'); // No known test case } break; case '/': switch(s){ case S_TAG: el.setTagName(source.slice(start,p)); case S_ATTR_END: case S_TAG_SPACE: case S_TAG_CLOSE: s =S_TAG_CLOSE; el.closed = true; case S_ATTR_NOQUOT_VALUE: case S_ATTR: case S_ATTR_SPACE: break; //case S_EQ: default: throw new Error("attribute invalid close char('/')") // No known test case } break; case ''://end document errorHandler.error('unexpected end of input'); if(s == S_TAG){ el.setTagName(source.slice(start,p)); } return p; case '>': switch(s){ case S_TAG: el.setTagName(source.slice(start,p)); case S_ATTR_END: case S_TAG_SPACE: case S_TAG_CLOSE: break;//normal case S_ATTR_NOQUOT_VALUE://Compatible state case S_ATTR: value = source.slice(start,p); if(value.slice(-1) === '/'){ el.closed = true; value = value.slice(0,-1) } case S_ATTR_SPACE: if(s === S_ATTR_SPACE){ value = attrName; } if(s == S_ATTR_NOQUOT_VALUE){ errorHandler.warning('attribute "'+value+'" missed quot(")!'); addAttribute(attrName, value.replace(/&#?\w+;/g,entityReplacer), start) }else{ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){ errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!') } addAttribute(value, value, start) } break; case S_EQ: throw new Error('attribute value missed!!'); } // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName)) return p; /*xml space '\x20' | #x9 | #xD | #xA; */ case '\u0080': c = ' '; default: if(c<= ' '){//space switch(s){ case S_TAG: el.setTagName(source.slice(start,p));//tagName s = S_TAG_SPACE; break; case S_ATTR: attrName = source.slice(start,p) s = S_ATTR_SPACE; break; case S_ATTR_NOQUOT_VALUE: var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); errorHandler.warning('attribute "'+value+'" missed quot(")!!'); addAttribute(attrName, value, start) case S_ATTR_END: s = S_TAG_SPACE; break; //case S_TAG_SPACE: //case S_EQ: //case S_ATTR_SPACE: // void();break; //case S_TAG_CLOSE: //ignore warning } }else{//not space //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE switch(s){ //case S_TAG:void();break; //case S_ATTR:void();break; //case S_ATTR_NOQUOT_VALUE:void();break; case S_ATTR_SPACE: var tagName = el.tagName; if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){ errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!') } addAttribute(attrName, attrName, start); start = p; s = S_ATTR; break; case S_ATTR_END: errorHandler.warning('attribute space is required"'+attrName+'"!!') case S_TAG_SPACE: s = S_ATTR; start = p; break; case S_EQ: s = S_ATTR_NOQUOT_VALUE; start = p; break; case S_TAG_CLOSE: throw new Error("elements closed character '/' and '>' must be connected to"); } } }//end outer switch //console.log('p++',p) p++; } } /** * @return true if has new namespace define */ function appendElement(el,domBuilder,currentNSMap){ var tagName = el.tagName; var localNSMap = null; //var currentNSMap = parseStack[parseStack.length-1].currentNSMap; var i = el.length; while(i--){ var a = el[i]; var qName = a.qName; var value = a.value; var nsp = qName.indexOf(':'); if(nsp>0){ var prefix = a.prefix = qName.slice(0,nsp); var localName = qName.slice(nsp+1); var nsPrefix = prefix === 'xmlns' && localName }else{ localName = qName; prefix = null nsPrefix = qName === 'xmlns' && '' } //can not set prefix,because prefix !== '' a.localName = localName ; //prefix == null for no ns prefix attribute if(nsPrefix !== false){//hack!! if(localNSMap == null){ localNSMap = {} //console.log(currentNSMap,0) _copy(currentNSMap,currentNSMap={}) //console.log(currentNSMap,1) } currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; a.uri = 'http://www.w3.org/2000/xmlns/' domBuilder.startPrefixMapping(nsPrefix, value) } } var i = el.length; while(i--){ a = el[i]; var prefix = a.prefix; if(prefix){//no prefix attribute has no namespace if(prefix === 'xml'){ a.uri = 'http://www.w3.org/XML/1998/namespace'; }if(prefix !== 'xmlns'){ a.uri = currentNSMap[prefix || ''] //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)} } } } var nsp = tagName.indexOf(':'); if(nsp>0){ prefix = el.prefix = tagName.slice(0,nsp); localName = el.localName = tagName.slice(nsp+1); }else{ prefix = null;//important!! localName = el.localName = tagName; } //no prefix element has default namespace var ns = el.uri = currentNSMap[prefix || '']; domBuilder.startElement(ns,localName,tagName,el); //endPrefixMapping and startPrefixMapping have not any help for dom builder //localNSMap = null if(el.closed){ domBuilder.endElement(ns,localName,tagName); if(localNSMap){ for(prefix in localNSMap){ domBuilder.endPrefixMapping(prefix) } } }else{ el.currentNSMap = currentNSMap; el.localNSMap = localNSMap; //parseStack.push(el); return true; } } function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){ if(/^(?:script|textarea)$/i.test(tagName)){ var elEndStart = source.indexOf('',elStartEnd); var text = source.substring(elStartEnd+1,elEndStart); if(/[&<]/.test(text)){ if(/^script$/i.test(tagName)){ //if(!/\]\]>/.test(text)){ //lexHandler.startCDATA(); domBuilder.characters(text,0,text.length); //lexHandler.endCDATA(); return elEndStart; //} }//}else{//text area text = text.replace(/&#?\w+;/g,entityReplacer); domBuilder.characters(text,0,text.length); return elEndStart; //} } } return elStartEnd+1; } function fixSelfClosed(source,elStartEnd,tagName,closeMap){ //if(tagName in closeMap){ var pos = closeMap[tagName]; if(pos == null){ //console.log(tagName) pos = source.lastIndexOf('') if(pos',start+4); //append comment source.substring(4,end)//