+ workspaceFolders.forEach(wf => {
+ const allHtmlConfig = coc_nvim_1.workspace.getConfiguration(undefined, wf.uri);
+ const wfHtmlConfig = allHtmlConfig.inspect('html');
+ if (wfHtmlConfig &&
+ wfHtmlConfig.workspaceFolderValue &&
+ wfHtmlConfig.workspaceFolderValue.experimental &&
+ wfHtmlConfig.workspaceFolderValue.experimental.customData) {
+ const customData = wfHtmlConfig.workspaceFolderValue.experimental.customData;
+ if (Array.isArray(customData)) {
+ customData.forEach(t => {
+ if (typeof t === 'string') {
+ dataPaths.push(path.resolve(coc_nvim_1.Uri.parse(wf.uri).fsPath, t));
+ }
+ });
+ }
+ }
+ });
+ return dataPaths;
+}
+exports.getCustomDataPathsInAllWorkspaces = getCustomDataPathsInAllWorkspaces;
+function getCustomDataPathsFromAllExtensions() {
+ const dataPaths = [];
+ for (const extension of coc_nvim_1.extensions.all) {
+ const contributes = extension.packageJSON && extension.packageJSON.contributes;
+ if (contributes &&
+ contributes.html &&
+ contributes.html.experimental.customData &&
+ Array.isArray(contributes.html.experimental.customData)) {
+ const relativePaths = contributes.html.experimental.customData;
+ relativePaths.forEach(rp => {
+ dataPaths.push(path.resolve(extension.extensionPath, rp));
+ });
+ }
+ }
+ return dataPaths;
+}
+exports.getCustomDataPathsFromAllExtensions = getCustomDataPathsFromAllExtensions;
+
+
+/***/ }),
+/* 3 */
+/***/ ((module) => {
+
+module.exports = require("path");;
+
+/***/ }),
+/* 4 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+
+/* --------------------------------------------------------------------------------------------
+ * 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 node_1 = __webpack_require__(5);
+__export(__webpack_require__(5));
+__export(__webpack_require__(24));
+function createProtocolConnection(input, output, logger, options) {
+ return node_1.createMessageConnection(input, output, logger, options);
+}
+exports.createProtocolConnection = createProtocolConnection;
+//# sourceMappingURL=main.js.map
+
+/***/ }),
+/* 5 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+/* --------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT License. See License.txt in the project root for license information.
+ * ----------------------------------------------------------------------------------------- */
+
+
+module.exports = __webpack_require__(6);
+
+/***/ }),
+/* 6 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+
+function __export(m) {
+ for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
+}
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+/* --------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT License. See License.txt in the project root for license information.
+ * ----------------------------------------------------------------------------------------- */
+const ril_1 = __webpack_require__(7);
+// Install the node runtime abstract.
+ril_1.default.install();
+const api_1 = __webpack_require__(11);
+const path = __webpack_require__(3);
+const os = __webpack_require__(21);
+const crypto_1 = __webpack_require__(22);
+const net_1 = __webpack_require__(23);
+__export(__webpack_require__(11));
+class IPCMessageReader extends api_1.AbstractMessageReader {
+ constructor(process) {
+ super();
+ this.process = process;
+ let eventEmitter = this.process;
+ eventEmitter.on('error', (error) => this.fireError(error));
+ eventEmitter.on('close', () => this.fireClose());
+ }
+ listen(callback) {
+ this.process.on('message', callback);
+ return api_1.Disposable.create(() => this.process.off('message', callback));
+ }
+}
+exports.IPCMessageReader = IPCMessageReader;
+class IPCMessageWriter extends api_1.AbstractMessageWriter {
+ constructor(process) {
+ super();
+ this.process = process;
+ this.errorCount = 0;
+ let eventEmitter = this.process;
+ eventEmitter.on('error', (error) => this.fireError(error));
+ eventEmitter.on('close', () => this.fireClose);
+ }
+ write(msg) {
+ try {
+ if (typeof this.process.send === 'function') {
+ this.process.send(msg, undefined, undefined, (error) => {
+ if (error) {
+ this.errorCount++;
+ this.handleError(error, msg);
+ }
+ else {
+ this.errorCount = 0;
+ }
+ });
+ }
+ return Promise.resolve();
+ }
+ catch (error) {
+ this.handleError(error, msg);
+ return Promise.reject(error);
+ }
+ }
+ handleError(error, msg) {
+ this.errorCount++;
+ this.fireError(error, msg, this.errorCount);
+ }
+}
+exports.IPCMessageWriter = IPCMessageWriter;
+class SocketMessageReader extends api_1.ReadableStreamMessageReader {
+ constructor(socket, encoding = 'utf-8') {
+ super(ril_1.default().stream.asReadableStream(socket), encoding);
+ }
+}
+exports.SocketMessageReader = SocketMessageReader;
+class SocketMessageWriter extends api_1.WriteableStreamMessageWriter {
+ constructor(socket, options) {
+ super(ril_1.default().stream.asWritableStream(socket), options);
+ this.socket = socket;
+ }
+ dispose() {
+ super.dispose();
+ this.socket.destroy();
+ }
+}
+exports.SocketMessageWriter = SocketMessageWriter;
+class StreamMessageReader extends api_1.ReadableStreamMessageReader {
+ constructor(readble, encoding) {
+ super(ril_1.default().stream.asReadableStream(readble), encoding);
+ }
+}
+exports.StreamMessageReader = StreamMessageReader;
+class StreamMessageWriter extends api_1.WriteableStreamMessageWriter {
+ constructor(writable, options) {
+ super(ril_1.default().stream.asWritableStream(writable), options);
+ }
+}
+exports.StreamMessageWriter = StreamMessageWriter;
+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.join(os.tmpdir(), `vscode-${randomSuffix}.sock`);
+ }
+}
+exports.generateRandomPipeName = generateRandomPipeName;
+function createClientPipeTransport(pipeName, encoding = 'utf-8') {
+ let connectResolve;
+ const connected = new Promise((resolve, _reject) => {
+ connectResolve = resolve;
+ });
+ return new Promise((resolve, reject) => {
+ let server = net_1.createServer((socket) => {
+ server.close();
+ connectResolve([
+ new SocketMessageReader(socket, encoding),
+ new SocketMessageWriter(socket, encoding)
+ ]);
+ });
+ server.on('error', reject);
+ server.listen(pipeName, () => {
+ server.removeListener('error', reject);
+ resolve({
+ onConnected: () => { return connected; }
+ });
+ });
+ });
+}
+exports.createClientPipeTransport = createClientPipeTransport;
+function createServerPipeTransport(pipeName, encoding = 'utf-8') {
+ const socket = net_1.createConnection(pipeName);
+ return [
+ new SocketMessageReader(socket, encoding),
+ new SocketMessageWriter(socket, encoding)
+ ];
+}
+exports.createServerPipeTransport = createServerPipeTransport;
+function createClientSocketTransport(port, encoding = 'utf-8') {
+ let connectResolve;
+ const connected = new Promise((resolve, _reject) => {
+ connectResolve = resolve;
+ });
+ return new Promise((resolve, reject) => {
+ const server = net_1.createServer((socket) => {
+ server.close();
+ connectResolve([
+ new SocketMessageReader(socket, encoding),
+ new SocketMessageWriter(socket, encoding)
+ ]);
+ });
+ server.on('error', reject);
+ server.listen(port, '127.0.0.1', () => {
+ server.removeListener('error', reject);
+ resolve({
+ onConnected: () => { return connected; }
+ });
+ });
+ });
+}
+exports.createClientSocketTransport = createClientSocketTransport;
+function createServerSocketTransport(port, encoding = 'utf-8') {
+ const socket = net_1.createConnection(port, '127.0.0.1');
+ return [
+ new SocketMessageReader(socket, encoding),
+ new SocketMessageWriter(socket, encoding)
+ ];
+}
+exports.createServerSocketTransport = createServerSocketTransport;
+function isMessageReader(value) {
+ return value.listen !== undefined && value.read === undefined;
+}
+function isMessageWriter(value) {
+ return value.write !== undefined && value.end === undefined;
+}
+function createMessageConnection(input, output, logger, options) {
+ if (!logger) {
+ logger = api_1.NullLogger;
+ }
+ const reader = isMessageReader(input) ? input : new StreamMessageReader(input);
+ const writer = isMessageWriter(output) ? output : new StreamMessageWriter(output);
+ if (api_1.ConnectionStrategy.is(options)) {
+ options = { connectionStrategy: options };
+ }
+ return api_1.createMessageConnection(reader, writer, logger, options);
+}
+exports.createMessageConnection = createMessageConnection;
+//# sourceMappingURL=main.js.map
+
+/***/ }),
+/* 7 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+
+/* --------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT License. See License.txt in the project root for license information.
+ * ------------------------------------------------------------------------------------------ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const ral_1 = __webpack_require__(8);
+const disposable_1 = __webpack_require__(9);
+const util_1 = __webpack_require__(10);
+const DefaultSize = 8192;
+const CR = Buffer.from('\r', 'ascii')[0];
+const LF = Buffer.from('\n', 'ascii')[0];
+const CRLF = '\r\n';
+class MessageBuffer {
+ constructor(encoding = 'utf-8') {
+ this._encoding = encoding;
+ this.index = 0;
+ this.buffer = Buffer.allocUnsafe(DefaultSize);
+ }
+ get encoding() {
+ return this._encoding;
+ }
+ append(chunk) {
+ let toAppend;
+ if (typeof chunk === 'string') {
+ toAppend = Buffer.from(chunk, this._encoding);
+ }
+ else {
+ toAppend = chunk;
+ }
+ if (this.buffer.length - this.index >= toAppend.length) {
+ this.buffer.set(toAppend, this.index);
+ }
+ else {
+ var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
+ if (this.index === 0) {
+ this.buffer = Buffer.allocUnsafe(newSize);
+ this.buffer.set(toAppend);
+ }
+ else {
+ this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
+ }
+ }
+ this.index += toAppend.length;
+ }
+ tryReadHeaders() {
+ 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 undefined;
+ }
+ const result = new Map();
+ const 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.set(key, value);
+ });
+ let nextStart = current + 4;
+ this.buffer = this.buffer.slice(nextStart);
+ this.index = this.index - nextStart;
+ return result;
+ }
+ tryReadBody(length) {
+ if (this.index < length) {
+ return undefined;
+ }
+ const result = Buffer.alloc(length);
+ this.buffer.copy(result, 0, 0, length);
+ const nextStart = length;
+ this.buffer.copy(this.buffer, 0, nextStart);
+ this.index = this.index - nextStart;
+ return result;
+ }
+ get numberOfBytes() {
+ return this.index;
+ }
+}
+class ReadableStreamWrapper {
+ constructor(stream) {
+ this.stream = stream;
+ }
+ onClose(listener) {
+ this.stream.on('close', listener);
+ return disposable_1.Disposable.create(() => this.stream.off('close', listener));
+ }
+ onError(listener) {
+ this.stream.on('error', listener);
+ return disposable_1.Disposable.create(() => this.stream.off('error', listener));
+ }
+ onEnd(listener) {
+ this.stream.on('end', listener);
+ return disposable_1.Disposable.create(() => this.stream.off('end', listener));
+ }
+ onData(listener) {
+ this.stream.on('data', listener);
+ return disposable_1.Disposable.create(() => this.stream.off('data', listener));
+ }
+}
+class WritableStreamWrapper {
+ constructor(stream) {
+ this.stream = stream;
+ }
+ onClose(listener) {
+ this.stream.on('close', listener);
+ return disposable_1.Disposable.create(() => this.stream.off('close', listener));
+ }
+ onError(listener) {
+ this.stream.on('error', listener);
+ return disposable_1.Disposable.create(() => this.stream.off('error', listener));
+ }
+ onEnd(listener) {
+ this.stream.on('end', listener);
+ return disposable_1.Disposable.create(() => this.stream.off('end', listener));
+ }
+ write(data, encoding) {
+ return new Promise((resolve, reject) => {
+ const callback = (error) => {
+ if (error === undefined || error === null) {
+ resolve();
+ }
+ else {
+ reject(error);
+ }
+ };
+ if (typeof data === 'string') {
+ this.stream.write(data, encoding, callback);
+ }
+ else {
+ this.stream.write(data, callback);
+ }
+ });
+ }
+ end() {
+ this.stream.end();
+ }
+}
+const _ril = Object.freeze({
+ messageBuffer: Object.freeze({
+ create: (encoding) => new MessageBuffer(encoding)
+ }),
+ applicationJson: Object.freeze({
+ encoder: Object.freeze({
+ name: 'application/json',
+ encode: (msg, options) => {
+ return Promise.resolve(Buffer.from(JSON.stringify(msg, undefined, 0), options.charset));
+ }
+ }),
+ decoder: Object.freeze({
+ name: 'application/json',
+ decode: (buffer, options) => {
+ if (buffer instanceof Buffer) {
+ return Promise.resolve(JSON.parse(buffer.toString(options.charset)));
+ }
+ else {
+ return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer)));
+ }
+ }
+ })
+ }),
+ stream: Object.freeze({
+ asReadableStream: (socket) => new ReadableStreamWrapper(socket),
+ asWritableStream: (socket) => new WritableStreamWrapper(socket)
+ }),
+ console: console,
+ timer: Object.freeze({
+ setTimeout(callback, ms, ...args) {
+ return setTimeout(callback, ms, ...args);
+ },
+ clearTimeout(handle) {
+ clearTimeout(handle);
+ },
+ setImmediate(callback, ...args) {
+ return setImmediate(callback, ...args);
+ },
+ clearImmediate(handle) {
+ clearImmediate(handle);
+ }
+ })
+});
+function RIL() {
+ return _ril;
+}
+(function (RIL) {
+ function install() {
+ ral_1.default.install(_ril);
+ }
+ RIL.install = install;
+})(RIL || (RIL = {}));
+exports.default = RIL;
+//# sourceMappingURL=ril.js.map
+
+/***/ }),
+/* 8 */
+/***/ ((__unused_webpack_module, exports) => {
+
+
+/* --------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT License. See License.txt in the project root for license information.
+ * ------------------------------------------------------------------------------------------ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+let _ral;
+function RAL() {
+ if (_ral === undefined) {
+ throw new Error(`No runtime abstraction layer installed`);
+ }
+ return _ral;
+}
+(function (RAL) {
+ function install(ral) {
+ if (ral === undefined) {
+ throw new Error(`No runtime abstraction layer provided`);
+ }
+ _ral = ral;
+ }
+ RAL.install = install;
+})(RAL || (RAL = {}));
+exports.default = RAL;
+//# sourceMappingURL=ral.js.map
+
+/***/ }),
+/* 9 */
+/***/ ((__unused_webpack_module, exports) => {
+
+
+/*---------------------------------------------------------------------------------------------
+ * 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 = {}));
+//# sourceMappingURL=disposable.js.map
+
+/***/ }),
+/* 10 */
+/***/ ((module) => {
+
+module.exports = require("util");;
+
+/***/ }),
+/* 11 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+
+/* --------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT License. See License.txt in the project root for license information.
+ * ------------------------------------------------------------------------------------------ */
+/// <reference path="../../typings/thenable.d.ts" />
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const messages_1 = __webpack_require__(12);
+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 disposable_1 = __webpack_require__(9);
+exports.Disposable = disposable_1.Disposable;
+const events_1 = __webpack_require__(14);
+exports.Event = events_1.Event;
+exports.Emitter = events_1.Emitter;
+const cancellation_1 = __webpack_require__(15);
+exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
+exports.CancellationToken = cancellation_1.CancellationToken;
+const messageReader_1 = __webpack_require__(16);
+exports.MessageReader = messageReader_1.MessageReader;
+exports.AbstractMessageReader = messageReader_1.AbstractMessageReader;
+exports.ReadableStreamMessageReader = messageReader_1.ReadableStreamMessageReader;
+const messageWriter_1 = __webpack_require__(17);
+exports.MessageWriter = messageWriter_1.MessageWriter;
+exports.AbstractMessageWriter = messageWriter_1.AbstractMessageWriter;
+exports.WriteableStreamMessageWriter = messageWriter_1.WriteableStreamMessageWriter;
+const connection_1 = __webpack_require__(19);
+exports.ConnectionStrategy = connection_1.ConnectionStrategy;
+exports.ConnectionOptions = connection_1.ConnectionOptions;
+exports.NullLogger = connection_1.NullLogger;
+exports.createMessageConnection = connection_1.createMessageConnection;
+exports.ProgressType = connection_1.ProgressType;
+exports.Trace = connection_1.Trace;
+exports.TraceFormat = connection_1.TraceFormat;
+exports.SetTraceNotification = connection_1.SetTraceNotification;
+exports.LogTraceNotification = connection_1.LogTraceNotification;
+exports.ConnectionErrors = connection_1.ConnectionErrors;
+exports.ConnectionError = connection_1.ConnectionError;
+exports.CancellationReceiverStrategy = connection_1.CancellationReceiverStrategy;
+exports.CancellationSenderStrategy = connection_1.CancellationSenderStrategy;
+exports.CancellationStrategy = connection_1.CancellationStrategy;
+const ral_1 = __webpack_require__(8);
+exports.RAL = ral_1.default;
+//# sourceMappingURL=api.js.map
+
+/***/ }),
+/* 12 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+
+/* --------------------------------------------------------------------------------------------
+ * 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__(13);
+/**
+ * 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;
+ ErrorCodes.ContentModified = -32801;
+ // 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 AbstractMessageSignature {
+ constructor(_method, _numberOfParams) {
+ this._method = _method;
+ this._numberOfParams = _numberOfParams;
+ }
+ get method() {
+ return this._method;
+ }
+ get numberOfParams() {
+ return this._numberOfParams;
+ }
+}
+exports.AbstractMessageSignature = AbstractMessageSignature;
+/**
+ * Classes to type request response pairs
+ *
+ * The type parameter RO will be removed in the next major version
+ * of the JSON RPC library since it is a LSP concept and doesn't
+ * belong here. For now it is tagged as default never.
+ */
+class RequestType0 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 0);
+ }
+}
+exports.RequestType0 = RequestType0;
+class RequestType extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 1);
+ }
+}
+exports.RequestType = RequestType;
+class RequestType1 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 1);
+ }
+}
+exports.RequestType1 = RequestType1;
+class RequestType2 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 2);
+ }
+}
+exports.RequestType2 = RequestType2;
+class RequestType3 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 3);
+ }
+}
+exports.RequestType3 = RequestType3;
+class RequestType4 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 4);
+ }
+}
+exports.RequestType4 = RequestType4;
+class RequestType5 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 5);
+ }
+}
+exports.RequestType5 = RequestType5;
+class RequestType6 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 6);
+ }
+}
+exports.RequestType6 = RequestType6;
+class RequestType7 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 7);
+ }
+}
+exports.RequestType7 = RequestType7;
+class RequestType8 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 8);
+ }
+}
+exports.RequestType8 = RequestType8;
+class RequestType9 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 9);
+ }
+}
+exports.RequestType9 = RequestType9;
+/**
+ * The type parameter RO will be removed in the next major version
+ * of the JSON RPC library since it is a LSP concept and doesn't
+ * belong here. For now it is tagged as default never.
+ */
+class NotificationType extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 1);
+ this._ = undefined;
+ }
+}
+exports.NotificationType = NotificationType;
+class NotificationType0 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 0);
+ }
+}
+exports.NotificationType0 = NotificationType0;
+class NotificationType1 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 1);
+ }
+}
+exports.NotificationType1 = NotificationType1;
+class NotificationType2 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 2);
+ }
+}
+exports.NotificationType2 = NotificationType2;
+class NotificationType3 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 3);
+ }
+}
+exports.NotificationType3 = NotificationType3;
+class NotificationType4 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 4);
+ }
+}
+exports.NotificationType4 = NotificationType4;
+class NotificationType5 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 5);
+ }
+}
+exports.NotificationType5 = NotificationType5;
+class NotificationType6 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 6);
+ }
+}
+exports.NotificationType6 = NotificationType6;
+class NotificationType7 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 7);
+ }
+}
+exports.NotificationType7 = NotificationType7;
+class NotificationType8 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 8);
+ }
+}
+exports.NotificationType8 = NotificationType8;
+class NotificationType9 extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 9);
+ }
+}
+exports.NotificationType9 = NotificationType9;
+/**
+ * Tests if the given message is a request message
+ */
+function isRequestMessage(message) {
+ const candidate = message;
+ return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
+}
+exports.isRequestMessage = isRequestMessage;
+/**
+ * Tests if the given message is a notification message
+ */
+function isNotificationMessage(message) {
+ const candidate = message;
+ return candidate && is.string(candidate.method) && message.id === void 0;
+}
+exports.isNotificationMessage = isNotificationMessage;
+/**
+ * Tests if the given message is a response message
+ */
+function isResponseMessage(message) {
+ const candidate = message;
+ return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
+}
+exports.isResponseMessage = isResponseMessage;
+//# sourceMappingURL=messages.js.map
+
+/***/ }),
+/* 13 */
+/***/ ((__unused_webpack_module, exports) => {
+
+
+/* --------------------------------------------------------------------------------------------
+ * 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;
+//# sourceMappingURL=is.js.map
+
+/***/ }),
+/* 14 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+
+/* --------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT License. See License.txt in the project root for license information.
+ * ------------------------------------------------------------------------------------------ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const ral_1 = __webpack_require__(8);
+var Event;
+(function (Event) {
+ const _disposable = { dispose() { } };
+ Event.None = function () { return _disposable; };
+})(Event = exports.Event || (exports.Event = {}));
+class CallbackList {
+ add(callback, context = null, bucket) {
+ if (!this._callbacks) {
+ this._callbacks = [];
+ this._contexts = [];
+ }
+ this._callbacks.push(callback);
+ this._contexts.push(context);
+ if (Array.isArray(bucket)) {
+ bucket.push({ dispose: () => this.remove(callback, context) });
+ }
+ }
+ remove(callback, context = null) {
+ if (!this._callbacks) {
+ return;
+ }
+ let foundCallbackWithDifferentContext = false;
+ for (let i = 0, len = this._callbacks.length; i < len; i++) {
+ if (this._callbacks[i] === callback) {
+ if (this._contexts[i] === context) {
+ // callback & context match => remove it
+ this._callbacks.splice(i, 1);
+ this._contexts.splice(i, 1);
+ return;
+ }
+ else {
+ foundCallbackWithDifferentContext = true;
+ }
+ }
+ }
+ if (foundCallbackWithDifferentContext) {
+ throw new Error('When adding a listener with a context, you should remove it with the same context');
+ }
+ }
+ invoke(...args) {
+ if (!this._callbacks) {
+ return [];
+ }
+ const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
+ for (let i = 0, len = callbacks.length; i < len; i++) {
+ try {
+ ret.push(callbacks[i].apply(contexts[i], args));
+ }
+ catch (e) {
+ // eslint-disable-next-line no-console
+ ral_1.default().console.error(e);
+ }
+ }
+ return ret;
+ }
+ isEmpty() {
+ return !this._callbacks || this._callbacks.length === 0;
+ }
+ dispose() {
+ this._callbacks = undefined;
+ this._contexts = undefined;
+ }
+}
+class Emitter {
+ constructor(_options) {
+ this._options = _options;
+ }
+ /**
+ * For the public to allow to subscribe
+ * to events from this Emitter
+ */
+ get event() {
+ if (!this._event) {
+ this._event = (listener, thisArgs, disposables) => {
+ if (!this._callbacks) {
+ this._callbacks = new CallbackList();
+ }
+ if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
+ this._options.onFirstListenerAdd(this);
+ }
+ this._callbacks.add(listener, thisArgs);
+ const result = {
+ dispose: () => {
+ if (!this._callbacks) {
+ // disposable is disposed after emitter is disposed.
+ return;
+ }
+ this._callbacks.remove(listener, thisArgs);
+ result.dispose = Emitter._noop;
+ if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
+ this._options.onLastListenerRemove(this);
+ }
+ }
+ };
+ if (Array.isArray(disposables)) {
+ disposables.push(result);
+ }
+ return result;
+ };
+ }
+ return this._event;
+ }
+ /**
+ * To be kept private to fire an event to
+ * subscribers
+ */
+ fire(event) {
+ if (this._callbacks) {
+ this._callbacks.invoke.call(this._callbacks, event);
+ }
+ }
+ dispose() {
+ if (this._callbacks) {
+ this._callbacks.dispose();
+ this._callbacks = undefined;
+ }
+ }
+}
+exports.Emitter = Emitter;
+Emitter._noop = function () { };
+//# sourceMappingURL=events.js.map
+
+/***/ }),
+/* 15 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+
+/*---------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT License. See License.txt in the project root for license information.
+ *--------------------------------------------------------------------------------------------*/
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const ral_1 = __webpack_require__(8);
+const Is = __webpack_require__(13);
+const events_1 = __webpack_require__(14);
+var CancellationToken;
+(function (CancellationToken) {
+ CancellationToken.None = Object.freeze({
+ isCancellationRequested: false,
+ onCancellationRequested: events_1.Event.None
+ });
+ CancellationToken.Cancelled = Object.freeze({
+ isCancellationRequested: true,
+ onCancellationRequested: events_1.Event.None
+ });
+ function is(value) {
+ const candidate = value;
+ return candidate && (candidate === CancellationToken.None
+ || candidate === CancellationToken.Cancelled
+ || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
+ }
+ CancellationToken.is = is;
+})(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
+const shortcutEvent = Object.freeze(function (callback, context) {
+ const handle = ral_1.default().timer.setTimeout(callback.bind(context), 0);
+ return { dispose() { ral_1.default().timer.clearTimeout(handle); } };
+});
+class MutableToken {
+ constructor() {
+ this._isCancelled = false;
+ }
+ cancel() {
+ if (!this._isCancelled) {
+ this._isCancelled = true;
+ if (this._emitter) {
+ this._emitter.fire(undefined);
+ this.dispose();
+ }
+ }
+ }
+ get isCancellationRequested() {
+ return this._isCancelled;
+ }
+ get onCancellationRequested() {
+ if (this._isCancelled) {
+ return shortcutEvent;
+ }
+ if (!this._emitter) {
+ this._emitter = new events_1.Emitter();
+ }
+ return this._emitter.event;
+ }
+ dispose() {
+ if (this._emitter) {
+ this._emitter.dispose();
+ this._emitter = undefined;
+ }
+ }
+}
+class CancellationTokenSource {
+ get token() {
+ if (!this._token) {
+ // be lazy and create the token only when
+ // actually needed
+ this._token = new MutableToken();
+ }
+ return this._token;
+ }
+ cancel() {
+ if (!this._token) {
+ // save an object by returning the default
+ // cancelled token when cancellation happens
+ // before someone asks for the token
+ this._token = CancellationToken.Cancelled;
+ }
+ else {
+ this._token.cancel();
+ }
+ }
+ dispose() {
+ if (!this._token) {
+ // ensure to initialize with an empty token if we had none
+ this._token = CancellationToken.None;
+ }
+ else if (this._token instanceof MutableToken) {
+ // actually dispose
+ this._token.dispose();
+ }
+ }
+}
+exports.CancellationTokenSource = CancellationTokenSource;
+//# sourceMappingURL=cancellation.js.map
+
+/***/ }),
+/* 16 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+
+/* --------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT License. See License.txt in the project root for license information.
+ * ------------------------------------------------------------------------------------------ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const ral_1 = __webpack_require__(8);
+const Is = __webpack_require__(13);
+const events_1 = __webpack_require__(14);
+var MessageReader;
+(function (MessageReader) {
+ function is(value) {
+ let candidate = value;
+ return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
+ Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
+ }
+ MessageReader.is = is;
+})(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
+class AbstractMessageReader {
+ constructor() {
+ this.errorEmitter = new events_1.Emitter();
+ this.closeEmitter = new events_1.Emitter();
+ this.partialMessageEmitter = new events_1.Emitter();
+ }
+ dispose() {
+ this.errorEmitter.dispose();
+ this.closeEmitter.dispose();
+ }
+ get onError() {
+ return this.errorEmitter.event;
+ }
+ fireError(error) {
+ this.errorEmitter.fire(this.asError(error));
+ }
+ get onClose() {
+ return this.closeEmitter.event;
+ }
+ fireClose() {
+ this.closeEmitter.fire(undefined);
+ }
+ get onPartialMessage() {
+ return this.partialMessageEmitter.event;
+ }
+ firePartialMessage(info) {
+ this.partialMessageEmitter.fire(info);
+ }
+ asError(error) {
+ if (error instanceof Error) {
+ return error;
+ }
+ else {
+ return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
+ }
+ }
+}
+exports.AbstractMessageReader = AbstractMessageReader;
+var ResolvedMessageReaderOptions;
+(function (ResolvedMessageReaderOptions) {
+ function fromOptions(options) {
+ var _a;
+ let charset;
+ let result;
+ let contentDecoder;
+ const contentDecoders = new Map();
+ let contentTypeDecoder;
+ const contentTypeDecoders = new Map();
+ if (options === undefined || typeof options === 'string') {
+ charset = options !== null && options !== void 0 ? options : 'utf-8';
+ }
+ else {
+ charset = (_a = options.charset) !== null && _a !== void 0 ? _a : 'utf-8';
+ if (options.contentDecoder !== undefined) {
+ contentDecoder = options.contentDecoder;
+ contentDecoders.set(contentDecoder.name, contentDecoder);
+ }
+ if (options.contentDecoders !== undefined) {
+ for (const decoder of options.contentDecoders) {
+ contentDecoders.set(decoder.name, decoder);
+ }
+ }
+ if (options.contentTypeDecoder !== undefined) {
+ contentTypeDecoder = options.contentTypeDecoder;
+ contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
+ }
+ if (options.contentTypeDecoders !== undefined) {
+ for (const decoder of options.contentTypeDecoders) {
+ contentTypeDecoders.set(decoder.name, decoder);
+ }
+ }
+ }
+ if (contentTypeDecoder === undefined) {
+ contentTypeDecoder = ral_1.default().applicationJson.decoder;
+ contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
+ }
+ return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders };
+ }
+ ResolvedMessageReaderOptions.fromOptions = fromOptions;
+})(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));
+class ReadableStreamMessageReader extends AbstractMessageReader {
+ constructor(readable, options) {
+ super();
+ this.readable = readable;
+ this.options = ResolvedMessageReaderOptions.fromOptions(options);
+ this.buffer = ral_1.default().messageBuffer.create(this.options.charset);
+ this._partialMessageTimeout = 10000;
+ this.nextMessageLength = -1;
+ this.messageToken = 0;
+ }
+ set partialMessageTimeout(timeout) {
+ this._partialMessageTimeout = timeout;
+ }
+ get partialMessageTimeout() {
+ return this._partialMessageTimeout;
+ }
+ listen(callback) {
+ this.nextMessageLength = -1;
+ this.messageToken = 0;
+ this.partialMessageTimer = undefined;
+ this.callback = callback;
+ const result = this.readable.onData((data) => {
+ this.onData(data);
+ });
+ this.readable.onError((error) => this.fireError(error));
+ this.readable.onClose(() => this.fireClose());
+ return result;
+ }
+ onData(data) {
+ this.buffer.append(data);
+ while (true) {
+ if (this.nextMessageLength === -1) {
+ const headers = this.buffer.tryReadHeaders();
+ if (!headers) {
+ return;
+ }
+ const contentLength = headers.get('Content-Length');
+ if (!contentLength) {
+ throw new Error('Header must provide a Content-Length property.');
+ }
+ const length = parseInt(contentLength);
+ if (isNaN(length)) {
+ throw new Error('Content-Length value must be a number.');
+ }
+ this.nextMessageLength = length;
+ }
+ const body = this.buffer.tryReadBody(this.nextMessageLength);
+ if (body === undefined) {
+ /** We haven't received the full message yet. */
+ this.setPartialMessageTimer();
+ return;
+ }
+ this.clearPartialMessageTimer();
+ this.nextMessageLength = -1;
+ let p;
+ if (this.options.contentDecoder !== undefined) {
+ p = this.options.contentDecoder.decode(body);
+ }
+ else {
+ p = Promise.resolve(body);
+ }
+ p.then((value) => {
+ this.options.contentTypeDecoder.decode(value, this.options).then((msg) => {
+ this.callback(msg);
+ }, (error) => {
+ this.fireError(error);
+ });
+ }, (error) => {
+ this.fireError(error);
+ });
+ }
+ }
+ clearPartialMessageTimer() {
+ if (this.partialMessageTimer) {
+ ral_1.default().timer.clearTimeout(this.partialMessageTimer);
+ this.partialMessageTimer = undefined;
+ }
+ }
+ setPartialMessageTimer() {
+ this.clearPartialMessageTimer();
+ if (this._partialMessageTimeout <= 0) {
+ return;
+ }
+ this.partialMessageTimer = ral_1.default().timer.setTimeout((token, timeout) => {
+ this.partialMessageTimer = undefined;
+ if (token === this.messageToken) {
+ this.firePartialMessage({ messageToken: token, waitingTime: timeout });
+ this.setPartialMessageTimer();
+ }
+ }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
+ }
+}
+exports.ReadableStreamMessageReader = ReadableStreamMessageReader;
+//# sourceMappingURL=messageReader.js.map
+
+/***/ }),
+/* 17 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+
+/* --------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT License. See License.txt in the project root for license information.
+ * ------------------------------------------------------------------------------------------ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const ral_1 = __webpack_require__(8);
+const Is = __webpack_require__(13);
+const semaphore_1 = __webpack_require__(18);
+const events_1 = __webpack_require__(14);
+const ContentLength = 'Content-Length: ';
+const CRLF = '\r\n';
+var MessageWriter;
+(function (MessageWriter) {
+ function is(value) {
+ let candidate = value;
+ return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
+ Is.func(candidate.onError) && Is.func(candidate.write);
+ }
+ MessageWriter.is = is;
+})(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
+class AbstractMessageWriter {
+ constructor() {
+ this.errorEmitter = new events_1.Emitter();
+ this.closeEmitter = new events_1.Emitter();
+ }
+ dispose() {
+ this.errorEmitter.dispose();
+ this.closeEmitter.dispose();
+ }
+ get onError() {
+ return this.errorEmitter.event;
+ }
+ fireError(error, message, count) {
+ this.errorEmitter.fire([this.asError(error), message, count]);
+ }
+ get onClose() {
+ return this.closeEmitter.event;
+ }
+ fireClose() {
+ this.closeEmitter.fire(undefined);
+ }
+ asError(error) {
+ if (error instanceof Error) {
+ return error;
+ }
+ else {
+ return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
+ }
+ }
+}
+exports.AbstractMessageWriter = AbstractMessageWriter;
+var ResolvedMessageWriterOptions;
+(function (ResolvedMessageWriterOptions) {
+ function fromOptions(options) {
+ var _a, _b;
+ if (options === undefined || typeof options === 'string') {
+ return { charset: options !== null && options !== void 0 ? options : 'utf-8', contentTypeEncoder: ral_1.default().applicationJson.encoder };
+ }
+ else {
+ return { charset: (_a = options.charset) !== null && _a !== void 0 ? _a : 'utf-8', contentEncoder: options.contentEncoder, contentTypeEncoder: (_b = options.contentTypeEncoder) !== null && _b !== void 0 ? _b : ral_1.default().applicationJson.encoder };
+ }
+ }
+ ResolvedMessageWriterOptions.fromOptions = fromOptions;
+})(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));
+class WriteableStreamMessageWriter extends AbstractMessageWriter {
+ constructor(writable, options) {
+ super();
+ this.writable = writable;
+ this.options = ResolvedMessageWriterOptions.fromOptions(options);
+ this.errorCount = 0;
+ this.writeSemaphore = new semaphore_1.Semaphore(1);
+ this.writable.onError((error) => this.fireError(error));
+ this.writable.onClose(() => this.fireClose());
+ }
+ async write(msg) {
+ const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {
+ if (this.options.contentEncoder !== undefined) {
+ return this.options.contentEncoder.encode(buffer);
+ }
+ else {
+ return buffer;
+ }
+ });
+ return payload.then((buffer) => {
+ const headers = [];
+ headers.push(ContentLength, buffer.byteLength.toString(), CRLF);
+ headers.push(CRLF);
+ return this.doWrite(msg, headers, buffer);
+ }, (error) => {
+ this.fireError(error);
+ throw error;
+ });
+ }
+ doWrite(msg, headers, data) {
+ return this.writeSemaphore.lock(async () => {
+ try {
+ await this.writable.write(headers.join(''), 'ascii');
+ return this.writable.write(data);
+ }
+ catch (error) {
+ this.handleError(error, msg);
+ }
+ });
+ }
+ handleError(error, msg) {
+ this.errorCount++;
+ this.fireError(error, msg, this.errorCount);
+ }
+}
+exports.WriteableStreamMessageWriter = WriteableStreamMessageWriter;
+//# sourceMappingURL=messageWriter.js.map
+
+/***/ }),
+/* 18 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+
+/* --------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT License. See License.txt in the project root for license information.
+ * ------------------------------------------------------------------------------------------ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const ral_1 = __webpack_require__(8);
+class Semaphore {
+ constructor(capacity = 1) {
+ if (capacity <= 0) {
+ throw new Error('Capacity must be greater than 0');
+ }
+ this._capacity = capacity;
+ this._active = 0;
+ this._waiting = [];
+ }
+ lock(thunk) {
+ return new Promise((resolve, reject) => {
+ this._waiting.push({ thunk, resolve, reject });
+ this.runNext();
+ });
+ }
+ get active() {
+ return this._active;
+ }
+ runNext() {
+ if (this._waiting.length === 0 || this._active === this._capacity) {
+ return;
+ }
+ ral_1.default().timer.setImmediate(() => this.doRunNext());
+ }
+ doRunNext() {
+ if (this._waiting.length === 0 || this._active === this._capacity) {
+ return;
+ }
+ const next = this._waiting.shift();
+ this._active++;
+ if (this._active > this._capacity) {
+ throw new Error(`To many thunks active`);
+ }
+ try {
+ const result = next.thunk();
+ if (result instanceof Promise) {
+ result.then((value) => {
+ this._active--;
+ next.resolve(value);
+ this.runNext();
+ }, (err) => {
+ this._active--;
+ next.reject(err);
+ this.runNext();
+ });
+ }
+ else {
+ this._active--;
+ next.resolve(result);
+ this.runNext();
+ }
+ }
+ catch (err) {
+ this._active--;
+ next.reject(err);
+ this.runNext();
+ }
+ }
+}
+exports.Semaphore = Semaphore;
+//# sourceMappingURL=semaphore.js.map
+
+/***/ }),
+/* 19 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+
+/* --------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT License. See License.txt in the project root for license information.
+ * ------------------------------------------------------------------------------------------ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const ral_1 = __webpack_require__(8);
+const Is = __webpack_require__(13);
+const messages_1 = __webpack_require__(12);
+const linkedMap_1 = __webpack_require__(20);
+const events_1 = __webpack_require__(14);
+const cancellation_1 = __webpack_require__(15);
+var CancelNotification;
+(function (CancelNotification) {
+ CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
+})(CancelNotification || (CancelNotification = {}));
+var ProgressNotification;
+(function (ProgressNotification) {
+ ProgressNotification.type = new messages_1.NotificationType('$/progress');
+})(ProgressNotification || (ProgressNotification = {}));
+class ProgressType {
+ constructor() {
+ }
+}
+exports.ProgressType = ProgressType;
+exports.NullLogger = Object.freeze({
+ error: () => { },
+ warn: () => { },
+ info: () => { },
+ log: () => { }
+});
+var Trace;
+(function (Trace) {
+ Trace[Trace["Off"] = 0] = "Off";
+ Trace[Trace["Messages"] = 1] = "Messages";
+ Trace[Trace["Verbose"] = 2] = "Verbose";
+})(Trace = exports.Trace || (exports.Trace = {}));
+(function (Trace) {
+ function fromString(value) {
+ if (!Is.string(value)) {
+ return Trace.Off;
+ }
+ value = value.toLowerCase();
+ switch (value) {
+ case 'off':
+ return Trace.Off;
+ case 'messages':
+ return Trace.Messages;
+ case 'verbose':
+ return Trace.Verbose;
+ default:
+ return Trace.Off;
+ }
+ }
+ Trace.fromString = fromString;
+ function toString(value) {
+ switch (value) {
+ case Trace.Off:
+ return 'off';
+ case Trace.Messages:
+ return 'messages';
+ case Trace.Verbose:
+ return 'verbose';
+ default:
+ return 'off';
+ }
+ }
+ Trace.toString = toString;
+})(Trace = exports.Trace || (exports.Trace = {}));
+var TraceFormat;
+(function (TraceFormat) {
+ TraceFormat["Text"] = "text";
+ TraceFormat["JSON"] = "json";
+})(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
+(function (TraceFormat) {
+ function fromString(value) {
+ value = value.toLowerCase();
+ if (value === 'json') {
+ return TraceFormat.JSON;
+ }
+ else {
+ return TraceFormat.Text;
+ }
+ }
+ TraceFormat.fromString = fromString;
+})(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
+var SetTraceNotification;
+(function (SetTraceNotification) {
+ SetTraceNotification.type = new messages_1.NotificationType('$/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) {
+ const candidate = value;
+ return candidate && Is.func(candidate.cancelUndispatched);
+ }
+ ConnectionStrategy.is = is;
+})(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
+var CancellationReceiverStrategy;
+(function (CancellationReceiverStrategy) {
+ CancellationReceiverStrategy.Message = Object.freeze({
+ createCancellationTokenSource(_) {
+ return new cancellation_1.CancellationTokenSource();
+ }
+ });
+ function is(value) {
+ const candidate = value;
+ return candidate && Is.func(candidate.createCancellationTokenSource);
+ }
+ CancellationReceiverStrategy.is = is;
+})(CancellationReceiverStrategy = exports.CancellationReceiverStrategy || (exports.CancellationReceiverStrategy = {}));
+var CancellationSenderStrategy;
+(function (CancellationSenderStrategy) {
+ CancellationSenderStrategy.Message = Object.freeze({
+ sendCancellation(conn, id) {
+ conn.sendNotification(CancelNotification.type, { id });
+ },
+ cleanup(_) { }
+ });
+ function is(value) {
+ const candidate = value;
+ return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup);
+ }
+ CancellationSenderStrategy.is = is;
+})(CancellationSenderStrategy = exports.CancellationSenderStrategy || (exports.CancellationSenderStrategy = {}));
+var CancellationStrategy;
+(function (CancellationStrategy) {
+ CancellationStrategy.Message = Object.freeze({
+ receiver: CancellationReceiverStrategy.Message,
+ sender: CancellationSenderStrategy.Message
+ });
+ function is(value) {
+ const candidate = value;
+ return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);
+ }
+ CancellationStrategy.is = is;
+})(CancellationStrategy = exports.CancellationStrategy || (exports.CancellationStrategy = {}));
+var ConnectionOptions;
+(function (ConnectionOptions) {
+ function is(value) {
+ const candidate = value;
+ return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy));
+ }
+ ConnectionOptions.is = is;
+})(ConnectionOptions = exports.ConnectionOptions || (exports.ConnectionOptions = {}));
+var ConnectionState;
+(function (ConnectionState) {
+ ConnectionState[ConnectionState["New"] = 1] = "New";
+ ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
+ ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
+ ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
+})(ConnectionState || (ConnectionState = {}));
+function createMessageConnection(messageReader, messageWriter, _logger, options) {
+ const logger = _logger !== undefined ? _logger : exports.NullLogger;
+ let sequenceNumber = 0;
+ let notificationSquenceNumber = 0;
+ let unknownResponseSquenceNumber = 0;
+ const version = '2.0';
+ let starRequestHandler = undefined;
+ const requestHandlers = Object.create(null);
+ let starNotificationHandler = undefined;
+ const notificationHandlers = Object.create(null);
+ const progressHandlers = new Map();
+ let timer;
+ let messageQueue = new linkedMap_1.LinkedMap();
+ let responsePromises = Object.create(null);
+ let requestTokens = Object.create(null);
+ let trace = Trace.Off;
+ let traceFormat = TraceFormat.Text;
+ let tracer;
+ let state = ConnectionState.New;
+ const errorEmitter = new events_1.Emitter();
+ const closeEmitter = new events_1.Emitter();
+ const unhandledNotificationEmitter = new events_1.Emitter();
+ const unhandledProgressEmitter = new events_1.Emitter();
+ const disposeEmitter = new events_1.Emitter();
+ const cancellationStrategy = (options && options.cancellationStrategy) ? options.cancellationStrategy : CancellationStrategy.Message;
+ function createRequestQueueKey(id) {
+ return 'req-' + id.toString();
+ }
+ function createResponseQueueKey(id) {
+ if (id === null) {
+ return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
+ }
+ else {
+ return 'res-' + id.toString();
+ }
+ }
+ function createNotificationQueueKey() {
+ return 'not-' + (++notificationSquenceNumber).toString();
+ }
+ function addMessageToQueue(queue, message) {
+ if (messages_1.isRequestMessage(message)) {
+ queue.set(createRequestQueueKey(message.id), message);
+ }
+ else if (messages_1.isResponseMessage(message)) {
+ queue.set(createResponseQueueKey(message.id), message);
+ }
+ else {
+ queue.set(createNotificationQueueKey(), message);
+ }
+ }
+ function cancelUndispatched(_message) {
+ return undefined;
+ }
+ function isListening() {
+ return state === ConnectionState.Listening;
+ }
+ function isClosed() {
+ return state === ConnectionState.Closed;
+ }
+ function isDisposed() {
+ return state === ConnectionState.Disposed;
+ }
+ function closeHandler() {
+ if (state === ConnectionState.New || state === ConnectionState.Listening) {
+ state = ConnectionState.Closed;
+ closeEmitter.fire(undefined);
+ }
+ // If the connection is disposed don't sent close events.
+ }
+ function readErrorHandler(error) {
+ errorEmitter.fire([error, undefined, undefined]);
+ }
+ function writeErrorHandler(data) {
+ errorEmitter.fire(data);
+ }
+ messageReader.onClose(closeHandler);
+ messageReader.onError(readErrorHandler);
+ messageWriter.onClose(closeHandler);
+ messageWriter.onError(writeErrorHandler);
+ function triggerMessageQueue() {
+ if (timer || messageQueue.size === 0) {
+ return;
+ }
+ timer = ral_1.default().timer.setImmediate(() => {
+ timer = undefined;
+ processMessageQueue();
+ });
+ }
+ function processMessageQueue() {
+ if (messageQueue.size === 0) {
+ return;
+ }
+ const message = messageQueue.shift();
+ try {
+ if (messages_1.isRequestMessage(message)) {
+ handleRequest(message);
+ }
+ else if (messages_1.isNotificationMessage(message)) {
+ handleNotification(message);
+ }
+ else if (messages_1.isResponseMessage(message)) {
+ handleResponse(message);
+ }
+ else {
+ handleInvalidMessage(message);
+ }
+ }
+ finally {
+ triggerMessageQueue();
+ }
+ }
+ const callback = (message) => {
+ try {
+ // We have received a cancellation message. Check if the message is still in the queue
+ // and cancel it if allowed to do so.
+ if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
+ const key = createRequestQueueKey(message.params.id);
+ const toCancel = messageQueue.get(key);
+ if (messages_1.isRequestMessage(toCancel)) {
+ const strategy = options === null || options === void 0 ? void 0 : options.connectionStrategy;
+ const response = (strategy && strategy.cancelUndispatched) ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
+ if (response && (response.error !== undefined || response.result !== undefined)) {
+ messageQueue.delete(key);
+ response.id = toCancel.id;
+ traceSendingResponse(response, message.method, Date.now());
+ messageWriter.write(response);
+ return;
+ }
+ }
+ }
+ addMessageToQueue(messageQueue, message);
+ }
+ finally {
+ triggerMessageQueue();
+ }
+ };
+ function handleRequest(requestMessage) {
+ if (isDisposed()) {
+ // we return here silently since we fired an event when the
+ // connection got disposed.
+ return;
+ }
+ function reply(resultOrError, method, startTime) {
+ const message = {
+ jsonrpc: version,
+ id: requestMessage.id
+ };
+ if (resultOrError instanceof messages_1.ResponseError) {
+ message.error = resultOrError.toJson();
+ }
+ else {
+ message.result = resultOrError === undefined ? null : resultOrError;
+ }
+ traceSendingResponse(message, method, startTime);
+ messageWriter.write(message);
+ }
+ function replyError(error, method, startTime) {
+ const message = {
+ jsonrpc: version,
+ id: requestMessage.id,
+ error: error.toJson()
+ };
+ traceSendingResponse(message, method, startTime);
+ messageWriter.write(message);
+ }
+ function replySuccess(result, method, startTime) {
+ // The JSON RPC defines that a response must either have a result or an error
+ // So we can't treat undefined as a valid response result.
+ if (result === undefined) {
+ result = null;
+ }
+ const message = {
+ jsonrpc: version,
+ id: requestMessage.id,
+ result: result
+ };
+ traceSendingResponse(message, method, startTime);
+ messageWriter.write(message);
+ }
+ traceReceivedRequest(requestMessage);
+ const element = requestHandlers[requestMessage.method];
+ let type;
+ let requestHandler;
+ if (element) {
+ type = element.type;
+ requestHandler = element.handler;
+ }
+ const startTime = Date.now();
+ if (requestHandler || starRequestHandler) {
+ const tokenKey = String(requestMessage.id);
+ const cancellationSource = cancellationStrategy.receiver.createCancellationTokenSource(tokenKey);
+ requestTokens[tokenKey] = cancellationSource;
+ try {
+ let handlerResult;
+ if (requestMessage.params === undefined || (type !== undefined && type.numberOfParams === 0)) {
+ handlerResult = requestHandler
+ ? requestHandler(cancellationSource.token)
+ : starRequestHandler(requestMessage.method, cancellationSource.token);
+ }
+ else if (Is.array(requestMessage.params) && (type === undefined || 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);
+ }
+ const promise = handlerResult;
+ if (!handlerResult) {
+ delete requestTokens[tokenKey];
+ replySuccess(handlerResult, requestMessage.method, startTime);
+ }
+ else if (promise.then) {
+ promise.then((resultOrError) => {
+ delete requestTokens[tokenKey];
+ reply(resultOrError, requestMessage.method, startTime);
+ }, error => {
+ delete requestTokens[tokenKey];
+ if (error instanceof messages_1.ResponseError) {
+ replyError(error, requestMessage.method, startTime);
+ }
+ else if (error && Is.string(error.message)) {
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
+ }
+ else {
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
+ }
+ });
+ }
+ else {
+ delete requestTokens[tokenKey];
+ reply(handlerResult, requestMessage.method, startTime);
+ }
+ }
+ catch (error) {
+ delete requestTokens[tokenKey];
+ if (error instanceof messages_1.ResponseError) {
+ reply(error, requestMessage.method, startTime);
+ }
+ else if (error && Is.string(error.message)) {
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
+ }
+ else {
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
+ }
+ }
+ }
+ else {
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
+ }
+ }
+ function handleResponse(responseMessage) {
+ if (isDisposed()) {
+ // See handle request.
+ return;
+ }
+ if (responseMessage.id === null) {
+ if (responseMessage.error) {
+ logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
+ }
+ else {
+ logger.error(`Received response message without id. No further error information provided.`);
+ }
+ }
+ else {
+ const key = String(responseMessage.id);
+ const responsePromise = responsePromises[key];
+ traceReceivedResponse(responseMessage, responsePromise);
+ if (responsePromise) {
+ delete responsePromises[key];
+ try {
+ if (responseMessage.error) {
+ const error = responseMessage.error;
+ responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
+ }
+ else if (responseMessage.result !== undefined) {
+ responsePromise.resolve(responseMessage.result);
+ }
+ else {
+ throw new Error('Should never happen.');
+ }
+ }
+ catch (error) {
+ if (error.message) {
+ logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
+ }
+ else {
+ logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
+ }
+ }
+ }
+ }
+ }
+ function handleNotification(message) {
+ if (isDisposed()) {
+ // See handle request.
+ return;
+ }
+ let type = undefined;
+ let notificationHandler;
+ if (message.method === CancelNotification.type.method) {
+ notificationHandler = (params) => {
+ const id = params.id;
+ const source = requestTokens[String(id)];
+ if (source) {
+ source.cancel();
+ }
+ };
+ }
+ else {
+ const element = notificationHandlers[message.method];
+ if (element) {
+ notificationHandler = element.handler;
+ type = element.type;
+ }
+ }
+ if (notificationHandler || starNotificationHandler) {
+ try {
+ traceReceivedNotification(message);
+ if (message.params === undefined || (type !== undefined && type.numberOfParams === 0)) {
+ notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
+ }
+ else if (Is.array(message.params) && (type === undefined || 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
+ const responseMessage = message;
+ if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
+ const key = String(responseMessage.id);
+ const responseHandler = responsePromises[key];
+ if (responseHandler) {
+ responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
+ }
+ }
+ }
+ function traceSendingRequest(message) {
+ if (trace === Trace.Off || !tracer) {
+ return;
+ }
+ if (traceFormat === TraceFormat.Text) {
+ let data = undefined;
+ if (trace === Trace.Verbose && message.params) {
+ data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
+ }
+ tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
+ }
+ else {
+ logLSPMessage('send-request', message);
+ }
+ }
+ function traceSendingNotification(message) {
+ if (trace === Trace.Off || !tracer) {
+ return;
+ }
+ if (traceFormat === TraceFormat.Text) {
+ let data = undefined;
+ if (trace === Trace.Verbose) {
+ if (message.params) {
+ data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
+ }
+ else {
+ data = 'No parameters provided.\n\n';
+ }
+ }
+ tracer.log(`Sending notification '${message.method}'.`, data);
+ }
+ else {
+ logLSPMessage('send-notification', message);
+ }
+ }
+ function traceSendingResponse(message, method, startTime) {
+ if (trace === Trace.Off || !tracer) {
+ return;
+ }
+ if (traceFormat === TraceFormat.Text) {
+ let data = undefined;
+ if (trace === Trace.Verbose) {
+ if (message.error && message.error.data) {
+ data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
+ }
+ else {
+ if (message.result) {
+ data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
+ }
+ else if (message.error === undefined) {
+ data = 'No result returned.\n\n';
+ }
+ }
+ }
+ tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
+ }
+ else {
+ logLSPMessage('send-response', message);
+ }
+ }
+ function traceReceivedRequest(message) {
+ if (trace === Trace.Off || !tracer) {
+ return;
+ }
+ if (traceFormat === TraceFormat.Text) {
+ let data = undefined;
+ if (trace === Trace.Verbose && message.params) {
+ data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
+ }
+ tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
+ }
+ else {
+ logLSPMessage('receive-request', message);
+ }
+ }
+ function traceReceivedNotification(message) {
+ if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
+ return;
+ }
+ if (traceFormat === TraceFormat.Text) {
+ let data = undefined;
+ if (trace === Trace.Verbose) {
+ if (message.params) {
+ data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
+ }
+ else {
+ data = 'No parameters provided.\n\n';
+ }
+ }
+ tracer.log(`Received notification '${message.method}'.`, data);
+ }
+ else {
+ logLSPMessage('receive-notification', message);
+ }
+ }
+ function traceReceivedResponse(message, responsePromise) {
+ if (trace === Trace.Off || !tracer) {
+ return;
+ }
+ if (traceFormat === TraceFormat.Text) {
+ let data = undefined;
+ if (trace === Trace.Verbose) {
+ if (message.error && message.error.data) {
+ data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
+ }
+ else {
+ if (message.result) {
+ data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
+ }
+ else if (message.error === undefined) {
+ data = 'No result returned.\n\n';
+ }
+ }
+ }
+ if (responsePromise) {
+ const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
+ tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
+ }
+ else {
+ tracer.log(`Received response ${message.id} without active response promise.`, data);
+ }
+ }
+ else {
+ logLSPMessage('receive-response', message);
+ }
+ }
+ function logLSPMessage(type, message) {
+ if (!tracer || trace === Trace.Off) {
+ return;
+ }
+ const lspMessage = {
+ isLSPMessage: true,
+ type,
+ message,
+ timestamp: Date.now()
+ };
+ tracer.log(lspMessage);
+ }
+ function throwIfClosedOrDisposed() {
+ if (isClosed()) {
+ throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
+ }
+ if (isDisposed()) {
+ throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
+ }
+ }
+ function throwIfListening() {
+ if (isListening()) {
+ throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
+ }
+ }
+ function throwIfNotListening() {
+ if (!isListening()) {
+ throw new Error('Call listen() first.');
+ }
+ }
+ function undefinedToNull(param) {
+ if (param === undefined) {
+ return null;
+ }
+ else {
+ return param;
+ }
+ }
+ function computeMessageParams(type, params) {
+ let result;
+ const 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;
+ }
+ const 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);
+ }
+ const 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 };
+ }
+ }
+ },
+ onProgress: (_type, token, handler) => {
+ if (progressHandlers.has(token)) {
+ throw new Error(`Progress handler for token ${token} already registered`);
+ }
+ progressHandlers.set(token, handler);
+ return {
+ dispose: () => {
+ progressHandlers.delete(token);
+ }
+ };
+ },
+ sendProgress: (_type, token, value) => {
+ connection.sendNotification(ProgressNotification.type, { token, value });
+ },
+ onUnhandledProgress: unhandledProgressEmitter.event,
+ sendRequest: (type, ...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);
+ const numberOfParams = type.numberOfParams;
+ token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
+ }
+ const id = sequenceNumber++;
+ let disposable;
+ if (token) {
+ disposable = token.onCancellationRequested(() => {
+ cancellationStrategy.sender.sendCancellation(connection, id);
+ });
+ }
+ const result = new Promise((resolve, reject) => {
+ const requestMessage = {
+ jsonrpc: version,
+ id: id,
+ method: method,
+ params: messageParams
+ };
+ const resolveWithCleanup = (r) => {
+ resolve(r);
+ cancellationStrategy.sender.cleanup(id);
+ disposable === null || disposable === void 0 ? void 0 : disposable.dispose();
+ };
+ const rejectWithCleanup = (r) => {
+ reject(r);
+ cancellationStrategy.sender.cleanup(id);
+ disposable === null || disposable === void 0 ? void 0 : disposable.dispose();
+ };
+ let responsePromise = { method: method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup };
+ traceSendingRequest(requestMessage);
+ try {
+ messageWriter.write(requestMessage);
+ }
+ catch (e) {
+ // Writing the message failed. So we need to reject the promise.
+ responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
+ responsePromise = null;
+ }
+ if (responsePromise) {
+ responsePromises[String(id)] = responsePromise;
+ }
+ });
+ return result;
+ },
+ onRequest: (type, handler) => {
+ throwIfClosedOrDisposed();
+ 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 !== undefined) {
+ if (Is.boolean(sendNotificationOrTraceOptions)) {
+ _sendNotification = sendNotificationOrTraceOptions;
+ }
+ else {
+ _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
+ _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
+ }
+ }
+ trace = _value;
+ traceFormat = _traceFormat;
+ if (trace === Trace.Off) {
+ tracer = undefined;
+ }
+ else {
+ tracer = _tracer;
+ }
+ if (_sendNotification && !isClosed() && !isDisposed()) {
+ connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
+ }
+ },
+ onError: errorEmitter.event,
+ onClose: closeEmitter.event,
+ onUnhandledNotification: unhandledNotificationEmitter.event,
+ onDispose: disposeEmitter.event,
+ dispose: () => {
+ if (isDisposed()) {
+ return;
+ }
+ state = ConnectionState.Disposed;
+ disposeEmitter.fire(undefined);
+ const error = new Error('Connection got disposed.');
+ Object.keys(responsePromises).forEach((key) => {
+ responsePromises[key].reject(error);
+ });
+ responsePromises = Object.create(null);
+ requestTokens = Object.create(null);
+ messageQueue = new linkedMap_1.LinkedMap();
+ // Test for backwards compatibility
+ if (Is.func(messageWriter.dispose)) {
+ messageWriter.dispose();
+ }
+ if (Is.func(messageReader.dispose)) {
+ messageReader.dispose();
+ }
+ },
+ listen: () => {
+ throwIfClosedOrDisposed();
+ throwIfListening();
+ state = ConnectionState.Listening;
+ messageReader.listen(callback);
+ },
+ inspect: () => {
+ // eslint-disable-next-line no-console
+ ral_1.default().console.log('inspect');
+ }
+ };
+ connection.onNotification(LogTraceNotification.type, (params) => {
+ if (trace === Trace.Off || !tracer) {
+ return;
+ }
+ tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
+ });
+ connection.onNotification(ProgressNotification.type, (params) => {
+ const handler = progressHandlers.get(params.token);
+ if (handler) {
+ handler(params.value);
+ }
+ else {
+ unhandledProgressEmitter.fire(params);
+ }
+ });
+ return connection;
+}
+exports.createMessageConnection = createMessageConnection;
+//# sourceMappingURL=connection.js.map
+
+/***/ }),
+/* 20 */
+/***/ ((__unused_webpack_module, exports) => {
+
+
+/*---------------------------------------------------------------------------------------------
+ * 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.AsOld = Touch.First;
+ Touch.Last = 2;
+ Touch.AsNew = Touch.Last;
+})(Touch = exports.Touch || (exports.Touch = {}));
+class LinkedMap {
+ constructor() {
+ this[Symbol.toStringTag] = 'LinkedMap';
+ this._map = new Map();
+ this._head = undefined;
+ this._tail = undefined;
+ this._size = 0;
+ this._state = 0;
+ }
+ clear() {
+ this._map.clear();
+ this._head = undefined;
+ this._tail = undefined;
+ this._size = 0;
+ this._state++;
+ }
+ isEmpty() {
+ return !this._head && !this._tail;
+ }
+ get size() {
+ return this._size;
+ }
+ get first() {
+ var _a;
+ return (_a = this._head) === null || _a === void 0 ? void 0 : _a.value;
+ }
+ get last() {
+ var _a;
+ return (_a = this._tail) === null || _a === void 0 ? void 0 : _a.value;
+ }
+ has(key) {
+ return this._map.has(key);
+ }
+ get(key, touch = Touch.None) {
+ const item = this._map.get(key);
+ if (!item) {
+ return undefined;
+ }
+ if (touch !== Touch.None) {
+ this.touch(item, touch);
+ }
+ return item.value;
+ }
+ set(key, value, touch = Touch.None) {
+ let item = this._map.get(key);
+ if (item) {
+ item.value = value;
+ if (touch !== Touch.None) {
+ this.touch(item, touch);
+ }
+ }
+ else {
+ item = { key, value, next: undefined, previous: undefined };
+ switch (touch) {
+ case Touch.None:
+ this.addItemLast(item);
+ break;
+ case Touch.First:
+ this.addItemFirst(item);
+ break;
+ case Touch.Last:
+ this.addItemLast(item);
+ break;
+ default:
+ this.addItemLast(item);
+ break;
+ }
+ this._map.set(key, item);
+ this._size++;
+ }
+ return this;
+ }
+ delete(key) {
+ return !!this.remove(key);
+ }
+ remove(key) {
+ const item = this._map.get(key);
+ if (!item) {
+ return undefined;
+ }
+ this._map.delete(key);
+ this.removeItem(item);
+ this._size--;
+ return item.value;
+ }
+ shift() {
+ if (!this._head && !this._tail) {
+ return undefined;
+ }
+ if (!this._head || !this._tail) {
+ throw new Error('Invalid list');
+ }
+ const item = this._head;
+ this._map.delete(item.key);
+ this.removeItem(item);
+ this._size--;
+ return item.value;
+ }
+ forEach(callbackfn, thisArg) {
+ const state = this._state;
+ let current = this._head;
+ while (current) {
+ if (thisArg) {
+ callbackfn.bind(thisArg)(current.value, current.key, this);
+ }
+ else {
+ callbackfn(current.value, current.key, this);
+ }
+ if (this._state !== state) {
+ throw new Error(`LinkedMap got modified during iteration.`);
+ }
+ current = current.next;
+ }
+ }
+ keys() {
+ const map = this;
+ const state = this._state;
+ let current = this._head;
+ const iterator = {
+ [Symbol.iterator]() {
+ return iterator;
+ },
+ next() {
+ if (map._state !== state) {
+ throw new Error(`LinkedMap got modified during iteration.`);
+ }
+ if (current) {
+ const result = { value: current.key, done: false };
+ current = current.next;
+ return result;
+ }
+ else {
+ return { value: undefined, done: true };
+ }
+ }
+ };
+ return iterator;
+ }
+ values() {
+ const map = this;
+ const state = this._state;
+ let current = this._head;
+ const iterator = {
+ [Symbol.iterator]() {
+ return iterator;
+ },
+ next() {
+ if (map._state !== state) {
+ throw new Error(`LinkedMap got modified during iteration.`);
+ }
+ if (current) {
+ const result = { value: current.value, done: false };
+ current = current.next;
+ return result;
+ }
+ else {
+ return { value: undefined, done: true };
+ }
+ }
+ };
+ return iterator;
+ }
+ entries() {
+ const map = this;
+ const state = this._state;
+ let current = this._head;
+ const iterator = {
+ [Symbol.iterator]() {
+ return iterator;
+ },
+ next() {
+ if (map._state !== state) {
+ throw new Error(`LinkedMap got modified during iteration.`);
+ }
+ if (current) {
+ const result = { value: [current.key, current.value], done: false };
+ current = current.next;
+ return result;
+ }
+ else {
+ return { value: undefined, done: true };
+ }