Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-eslint / lib / server.js
1 (function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
2 /******/        // The module cache
3 /******/        var installedModules = {};
4 /******/
5 /******/        // The require function
6 /******/        function __webpack_require__(moduleId) {
7 /******/
8 /******/                // Check if module is in cache
9 /******/                if(installedModules[moduleId]) {
10 /******/                        return installedModules[moduleId].exports;
11 /******/                }
12 /******/                // Create a new module (and put it into the cache)
13 /******/                var module = installedModules[moduleId] = {
14 /******/                        i: moduleId,
15 /******/                        l: false,
16 /******/                        exports: {}
17 /******/                };
18 /******/
19 /******/                // Execute the module function
20 /******/                modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
21 /******/
22 /******/                // Flag the module as loaded
23 /******/                module.l = true;
24 /******/
25 /******/                // Return the exports of the module
26 /******/                return module.exports;
27 /******/        }
28 /******/
29 /******/
30 /******/        // expose the modules object (__webpack_modules__)
31 /******/        __webpack_require__.m = modules;
32 /******/
33 /******/        // expose the module cache
34 /******/        __webpack_require__.c = installedModules;
35 /******/
36 /******/        // define getter function for harmony exports
37 /******/        __webpack_require__.d = function(exports, name, getter) {
38 /******/                if(!__webpack_require__.o(exports, name)) {
39 /******/                        Object.defineProperty(exports, name, { enumerable: true, get: getter });
40 /******/                }
41 /******/        };
42 /******/
43 /******/        // define __esModule on exports
44 /******/        __webpack_require__.r = function(exports) {
45 /******/                if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
46 /******/                        Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
47 /******/                }
48 /******/                Object.defineProperty(exports, '__esModule', { value: true });
49 /******/        };
50 /******/
51 /******/        // create a fake namespace object
52 /******/        // mode & 1: value is a module id, require it
53 /******/        // mode & 2: merge all properties of value into the ns
54 /******/        // mode & 4: return value when already ns object
55 /******/        // mode & 8|1: behave like require
56 /******/        __webpack_require__.t = function(value, mode) {
57 /******/                if(mode & 1) value = __webpack_require__(value);
58 /******/                if(mode & 8) return value;
59 /******/                if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
60 /******/                var ns = Object.create(null);
61 /******/                __webpack_require__.r(ns);
62 /******/                Object.defineProperty(ns, 'default', { enumerable: true, value: value });
63 /******/                if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
64 /******/                return ns;
65 /******/        };
66 /******/
67 /******/        // getDefaultExport function for compatibility with non-harmony modules
68 /******/        __webpack_require__.n = function(module) {
69 /******/                var getter = module && module.__esModule ?
70 /******/                        function getDefault() { return module['default']; } :
71 /******/                        function getModuleExports() { return module; };
72 /******/                __webpack_require__.d(getter, 'a', getter);
73 /******/                return getter;
74 /******/        };
75 /******/
76 /******/        // Object.prototype.hasOwnProperty.call
77 /******/        __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
78 /******/
79 /******/        // __webpack_public_path__
80 /******/        __webpack_require__.p = "";
81 /******/
82 /******/
83 /******/        // Load entry module and return exports
84 /******/        return __webpack_require__(__webpack_require__.s = 38);
85 /******/ })
86 /************************************************************************/
87 /******/ ([
88 /* 0 */,
89 /* 1 */,
90 /* 2 */
91 /***/ (function(module, exports) {
92
93 module.exports = require("fs");
94
95 /***/ }),
96 /* 3 */
97 /***/ (function(module, exports) {
98
99 module.exports = require("path");
100
101 /***/ }),
102 /* 4 */
103 /***/ (function(module, exports, __webpack_require__) {
104
105 "use strict";
106 /* --------------------------------------------------------------------------------------------\r
107  * Copyright (c) Microsoft Corporation. All rights reserved.\r
108  * Licensed under the MIT License. See License.txt in the project root for license information.\r
109  * ------------------------------------------------------------------------------------------ */\r
110 \r
111 function __export(m) {\r
112     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r
113 }\r
114 Object.defineProperty(exports, "__esModule", { value: true });\r
115 const vscode_jsonrpc_1 = __webpack_require__(5);\r
116 exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;\r
117 exports.ResponseError = vscode_jsonrpc_1.ResponseError;\r
118 exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;\r
119 exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;\r
120 exports.Disposable = vscode_jsonrpc_1.Disposable;\r
121 exports.Event = vscode_jsonrpc_1.Event;\r
122 exports.Emitter = vscode_jsonrpc_1.Emitter;\r
123 exports.Trace = vscode_jsonrpc_1.Trace;\r
124 exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;\r
125 exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;\r
126 exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;\r
127 exports.RequestType = vscode_jsonrpc_1.RequestType;\r
128 exports.RequestType0 = vscode_jsonrpc_1.RequestType0;\r
129 exports.NotificationType = vscode_jsonrpc_1.NotificationType;\r
130 exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;\r
131 exports.MessageReader = vscode_jsonrpc_1.MessageReader;\r
132 exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;\r
133 exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;\r
134 exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;\r
135 exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;\r
136 exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;\r
137 exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;\r
138 exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;\r
139 exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;\r
140 exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;\r
141 exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;\r
142 exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;\r
143 exports.ProgressType = vscode_jsonrpc_1.ProgressType;\r
144 __export(__webpack_require__(18));\r
145 __export(__webpack_require__(19));\r
146 const callHierarchy = __webpack_require__(31);\r
147 const st = __webpack_require__(32);\r
148 var Proposed;\r
149 (function (Proposed) {\r
150     let CallHierarchyPrepareRequest;\r
151     (function (CallHierarchyPrepareRequest) {\r
152         CallHierarchyPrepareRequest.method = callHierarchy.CallHierarchyPrepareRequest.method;\r
153         CallHierarchyPrepareRequest.type = callHierarchy.CallHierarchyPrepareRequest.type;\r
154     })(CallHierarchyPrepareRequest = Proposed.CallHierarchyPrepareRequest || (Proposed.CallHierarchyPrepareRequest = {}));\r
155     let CallHierarchyIncomingCallsRequest;\r
156     (function (CallHierarchyIncomingCallsRequest) {\r
157         CallHierarchyIncomingCallsRequest.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;\r
158         CallHierarchyIncomingCallsRequest.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;\r
159     })(CallHierarchyIncomingCallsRequest = Proposed.CallHierarchyIncomingCallsRequest || (Proposed.CallHierarchyIncomingCallsRequest = {}));\r
160     let CallHierarchyOutgoingCallsRequest;\r
161     (function (CallHierarchyOutgoingCallsRequest) {\r
162         CallHierarchyOutgoingCallsRequest.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;\r
163         CallHierarchyOutgoingCallsRequest.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;\r
164     })(CallHierarchyOutgoingCallsRequest = Proposed.CallHierarchyOutgoingCallsRequest || (Proposed.CallHierarchyOutgoingCallsRequest = {}));\r
165     Proposed.SemanticTokenTypes = st.SemanticTokenTypes;\r
166     Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers;\r
167     Proposed.SemanticTokens = st.SemanticTokens;\r
168     let SemanticTokensRequest;\r
169     (function (SemanticTokensRequest) {\r
170         SemanticTokensRequest.method = st.SemanticTokensRequest.method;\r
171         SemanticTokensRequest.type = st.SemanticTokensRequest.type;\r
172     })(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {}));\r
173     let SemanticTokensEditsRequest;\r
174     (function (SemanticTokensEditsRequest) {\r
175         SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method;\r
176         SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type;\r
177     })(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {}));\r
178     let SemanticTokensRangeRequest;\r
179     (function (SemanticTokensRangeRequest) {\r
180         SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method;\r
181         SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type;\r
182     })(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {}));\r
183 })(Proposed = exports.Proposed || (exports.Proposed = {}));\r
184 function createProtocolConnection(reader, writer, logger, strategy) {\r
185     return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);\r
186 }\r
187 exports.createProtocolConnection = createProtocolConnection;\r
188
189
190 /***/ }),
191 /* 5 */
192 /***/ (function(module, exports, __webpack_require__) {
193
194 "use strict";
195 /* --------------------------------------------------------------------------------------------\r
196  * Copyright (c) Microsoft Corporation. All rights reserved.\r
197  * Licensed under the MIT License. See License.txt in the project root for license information.\r
198  * ------------------------------------------------------------------------------------------ */\r
199 /// <reference path="../typings/thenable.d.ts" />\r
200 \r
201 function __export(m) {\r
202     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r
203 }\r
204 Object.defineProperty(exports, "__esModule", { value: true });\r
205 const Is = __webpack_require__(6);\r
206 const messages_1 = __webpack_require__(7);\r
207 exports.RequestType = messages_1.RequestType;\r
208 exports.RequestType0 = messages_1.RequestType0;\r
209 exports.RequestType1 = messages_1.RequestType1;\r
210 exports.RequestType2 = messages_1.RequestType2;\r
211 exports.RequestType3 = messages_1.RequestType3;\r
212 exports.RequestType4 = messages_1.RequestType4;\r
213 exports.RequestType5 = messages_1.RequestType5;\r
214 exports.RequestType6 = messages_1.RequestType6;\r
215 exports.RequestType7 = messages_1.RequestType7;\r
216 exports.RequestType8 = messages_1.RequestType8;\r
217 exports.RequestType9 = messages_1.RequestType9;\r
218 exports.ResponseError = messages_1.ResponseError;\r
219 exports.ErrorCodes = messages_1.ErrorCodes;\r
220 exports.NotificationType = messages_1.NotificationType;\r
221 exports.NotificationType0 = messages_1.NotificationType0;\r
222 exports.NotificationType1 = messages_1.NotificationType1;\r
223 exports.NotificationType2 = messages_1.NotificationType2;\r
224 exports.NotificationType3 = messages_1.NotificationType3;\r
225 exports.NotificationType4 = messages_1.NotificationType4;\r
226 exports.NotificationType5 = messages_1.NotificationType5;\r
227 exports.NotificationType6 = messages_1.NotificationType6;\r
228 exports.NotificationType7 = messages_1.NotificationType7;\r
229 exports.NotificationType8 = messages_1.NotificationType8;\r
230 exports.NotificationType9 = messages_1.NotificationType9;\r
231 const messageReader_1 = __webpack_require__(8);\r
232 exports.MessageReader = messageReader_1.MessageReader;\r
233 exports.StreamMessageReader = messageReader_1.StreamMessageReader;\r
234 exports.IPCMessageReader = messageReader_1.IPCMessageReader;\r
235 exports.SocketMessageReader = messageReader_1.SocketMessageReader;\r
236 const messageWriter_1 = __webpack_require__(10);\r
237 exports.MessageWriter = messageWriter_1.MessageWriter;\r
238 exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;\r
239 exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;\r
240 exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;\r
241 const events_1 = __webpack_require__(9);\r
242 exports.Disposable = events_1.Disposable;\r
243 exports.Event = events_1.Event;\r
244 exports.Emitter = events_1.Emitter;\r
245 const cancellation_1 = __webpack_require__(11);\r
246 exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;\r
247 exports.CancellationToken = cancellation_1.CancellationToken;\r
248 const linkedMap_1 = __webpack_require__(12);\r
249 __export(__webpack_require__(13));\r
250 __export(__webpack_require__(17));\r
251 var CancelNotification;\r
252 (function (CancelNotification) {\r
253     CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');\r
254 })(CancelNotification || (CancelNotification = {}));\r
255 var ProgressNotification;\r
256 (function (ProgressNotification) {\r
257     ProgressNotification.type = new messages_1.NotificationType('$/progress');\r
258 })(ProgressNotification || (ProgressNotification = {}));\r
259 class ProgressType {\r
260     constructor() {\r
261     }\r
262 }\r
263 exports.ProgressType = ProgressType;\r
264 exports.NullLogger = Object.freeze({\r
265     error: () => { },\r
266     warn: () => { },\r
267     info: () => { },\r
268     log: () => { }\r
269 });\r
270 var Trace;\r
271 (function (Trace) {\r
272     Trace[Trace["Off"] = 0] = "Off";\r
273     Trace[Trace["Messages"] = 1] = "Messages";\r
274     Trace[Trace["Verbose"] = 2] = "Verbose";\r
275 })(Trace = exports.Trace || (exports.Trace = {}));\r
276 (function (Trace) {\r
277     function fromString(value) {\r
278         if (!Is.string(value)) {\r
279             return Trace.Off;\r
280         }\r
281         value = value.toLowerCase();\r
282         switch (value) {\r
283             case 'off':\r
284                 return Trace.Off;\r
285             case 'messages':\r
286                 return Trace.Messages;\r
287             case 'verbose':\r
288                 return Trace.Verbose;\r
289             default:\r
290                 return Trace.Off;\r
291         }\r
292     }\r
293     Trace.fromString = fromString;\r
294     function toString(value) {\r
295         switch (value) {\r
296             case Trace.Off:\r
297                 return 'off';\r
298             case Trace.Messages:\r
299                 return 'messages';\r
300             case Trace.Verbose:\r
301                 return 'verbose';\r
302             default:\r
303                 return 'off';\r
304         }\r
305     }\r
306     Trace.toString = toString;\r
307 })(Trace = exports.Trace || (exports.Trace = {}));\r
308 var TraceFormat;\r
309 (function (TraceFormat) {\r
310     TraceFormat["Text"] = "text";\r
311     TraceFormat["JSON"] = "json";\r
312 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));\r
313 (function (TraceFormat) {\r
314     function fromString(value) {\r
315         value = value.toLowerCase();\r
316         if (value === 'json') {\r
317             return TraceFormat.JSON;\r
318         }\r
319         else {\r
320             return TraceFormat.Text;\r
321         }\r
322     }\r
323     TraceFormat.fromString = fromString;\r
324 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));\r
325 var SetTraceNotification;\r
326 (function (SetTraceNotification) {\r
327     SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');\r
328 })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));\r
329 var LogTraceNotification;\r
330 (function (LogTraceNotification) {\r
331     LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');\r
332 })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));\r
333 var ConnectionErrors;\r
334 (function (ConnectionErrors) {\r
335     /**\r
336      * The connection is closed.\r
337      */\r
338     ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";\r
339     /**\r
340      * The connection got disposed.\r
341      */\r
342     ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";\r
343     /**\r
344      * The connection is already in listening mode.\r
345      */\r
346     ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";\r
347 })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));\r
348 class ConnectionError extends Error {\r
349     constructor(code, message) {\r
350         super(message);\r
351         this.code = code;\r
352         Object.setPrototypeOf(this, ConnectionError.prototype);\r
353     }\r
354 }\r
355 exports.ConnectionError = ConnectionError;\r
356 var ConnectionStrategy;\r
357 (function (ConnectionStrategy) {\r
358     function is(value) {\r
359         let candidate = value;\r
360         return candidate && Is.func(candidate.cancelUndispatched);\r
361     }\r
362     ConnectionStrategy.is = is;\r
363 })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));\r
364 var ConnectionState;\r
365 (function (ConnectionState) {\r
366     ConnectionState[ConnectionState["New"] = 1] = "New";\r
367     ConnectionState[ConnectionState["Listening"] = 2] = "Listening";\r
368     ConnectionState[ConnectionState["Closed"] = 3] = "Closed";\r
369     ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";\r
370 })(ConnectionState || (ConnectionState = {}));\r
371 function _createMessageConnection(messageReader, messageWriter, logger, strategy) {\r
372     let sequenceNumber = 0;\r
373     let notificationSquenceNumber = 0;\r
374     let unknownResponseSquenceNumber = 0;\r
375     const version = '2.0';\r
376     let starRequestHandler = undefined;\r
377     let requestHandlers = Object.create(null);\r
378     let starNotificationHandler = undefined;\r
379     let notificationHandlers = Object.create(null);\r
380     let progressHandlers = new Map();\r
381     let timer;\r
382     let messageQueue = new linkedMap_1.LinkedMap();\r
383     let responsePromises = Object.create(null);\r
384     let requestTokens = Object.create(null);\r
385     let trace = Trace.Off;\r
386     let traceFormat = TraceFormat.Text;\r
387     let tracer;\r
388     let state = ConnectionState.New;\r
389     let errorEmitter = new events_1.Emitter();\r
390     let closeEmitter = new events_1.Emitter();\r
391     let unhandledNotificationEmitter = new events_1.Emitter();\r
392     let unhandledProgressEmitter = new events_1.Emitter();\r
393     let disposeEmitter = new events_1.Emitter();\r
394     function createRequestQueueKey(id) {\r
395         return 'req-' + id.toString();\r
396     }\r
397     function createResponseQueueKey(id) {\r
398         if (id === null) {\r
399             return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();\r
400         }\r
401         else {\r
402             return 'res-' + id.toString();\r
403         }\r
404     }\r
405     function createNotificationQueueKey() {\r
406         return 'not-' + (++notificationSquenceNumber).toString();\r
407     }\r
408     function addMessageToQueue(queue, message) {\r
409         if (messages_1.isRequestMessage(message)) {\r
410             queue.set(createRequestQueueKey(message.id), message);\r
411         }\r
412         else if (messages_1.isResponseMessage(message)) {\r
413             queue.set(createResponseQueueKey(message.id), message);\r
414         }\r
415         else {\r
416             queue.set(createNotificationQueueKey(), message);\r
417         }\r
418     }\r
419     function cancelUndispatched(_message) {\r
420         return undefined;\r
421     }\r
422     function isListening() {\r
423         return state === ConnectionState.Listening;\r
424     }\r
425     function isClosed() {\r
426         return state === ConnectionState.Closed;\r
427     }\r
428     function isDisposed() {\r
429         return state === ConnectionState.Disposed;\r
430     }\r
431     function closeHandler() {\r
432         if (state === ConnectionState.New || state === ConnectionState.Listening) {\r
433             state = ConnectionState.Closed;\r
434             closeEmitter.fire(undefined);\r
435         }\r
436         // If the connection is disposed don't sent close events.\r
437     }\r
438     function readErrorHandler(error) {\r
439         errorEmitter.fire([error, undefined, undefined]);\r
440     }\r
441     function writeErrorHandler(data) {\r
442         errorEmitter.fire(data);\r
443     }\r
444     messageReader.onClose(closeHandler);\r
445     messageReader.onError(readErrorHandler);\r
446     messageWriter.onClose(closeHandler);\r
447     messageWriter.onError(writeErrorHandler);\r
448     function triggerMessageQueue() {\r
449         if (timer || messageQueue.size === 0) {\r
450             return;\r
451         }\r
452         timer = setImmediate(() => {\r
453             timer = undefined;\r
454             processMessageQueue();\r
455         });\r
456     }\r
457     function processMessageQueue() {\r
458         if (messageQueue.size === 0) {\r
459             return;\r
460         }\r
461         let message = messageQueue.shift();\r
462         try {\r
463             if (messages_1.isRequestMessage(message)) {\r
464                 handleRequest(message);\r
465             }\r
466             else if (messages_1.isNotificationMessage(message)) {\r
467                 handleNotification(message);\r
468             }\r
469             else if (messages_1.isResponseMessage(message)) {\r
470                 handleResponse(message);\r
471             }\r
472             else {\r
473                 handleInvalidMessage(message);\r
474             }\r
475         }\r
476         finally {\r
477             triggerMessageQueue();\r
478         }\r
479     }\r
480     let callback = (message) => {\r
481         try {\r
482             // We have received a cancellation message. Check if the message is still in the queue\r
483             // and cancel it if allowed to do so.\r
484             if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {\r
485                 let key = createRequestQueueKey(message.params.id);\r
486                 let toCancel = messageQueue.get(key);\r
487                 if (messages_1.isRequestMessage(toCancel)) {\r
488                     let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);\r
489                     if (response && (response.error !== void 0 || response.result !== void 0)) {\r
490                         messageQueue.delete(key);\r
491                         response.id = toCancel.id;\r
492                         traceSendingResponse(response, message.method, Date.now());\r
493                         messageWriter.write(response);\r
494                         return;\r
495                     }\r
496                 }\r
497             }\r
498             addMessageToQueue(messageQueue, message);\r
499         }\r
500         finally {\r
501             triggerMessageQueue();\r
502         }\r
503     };\r
504     function handleRequest(requestMessage) {\r
505         if (isDisposed()) {\r
506             // we return here silently since we fired an event when the\r
507             // connection got disposed.\r
508             return;\r
509         }\r
510         function reply(resultOrError, method, startTime) {\r
511             let message = {\r
512                 jsonrpc: version,\r
513                 id: requestMessage.id\r
514             };\r
515             if (resultOrError instanceof messages_1.ResponseError) {\r
516                 message.error = resultOrError.toJson();\r
517             }\r
518             else {\r
519                 message.result = resultOrError === void 0 ? null : resultOrError;\r
520             }\r
521             traceSendingResponse(message, method, startTime);\r
522             messageWriter.write(message);\r
523         }\r
524         function replyError(error, method, startTime) {\r
525             let message = {\r
526                 jsonrpc: version,\r
527                 id: requestMessage.id,\r
528                 error: error.toJson()\r
529             };\r
530             traceSendingResponse(message, method, startTime);\r
531             messageWriter.write(message);\r
532         }\r
533         function replySuccess(result, method, startTime) {\r
534             // The JSON RPC defines that a response must either have a result or an error\r
535             // So we can't treat undefined as a valid response result.\r
536             if (result === void 0) {\r
537                 result = null;\r
538             }\r
539             let message = {\r
540                 jsonrpc: version,\r
541                 id: requestMessage.id,\r
542                 result: result\r
543             };\r
544             traceSendingResponse(message, method, startTime);\r
545             messageWriter.write(message);\r
546         }\r
547         traceReceivedRequest(requestMessage);\r
548         let element = requestHandlers[requestMessage.method];\r
549         let type;\r
550         let requestHandler;\r
551         if (element) {\r
552             type = element.type;\r
553             requestHandler = element.handler;\r
554         }\r
555         let startTime = Date.now();\r
556         if (requestHandler || starRequestHandler) {\r
557             let cancellationSource = new cancellation_1.CancellationTokenSource();\r
558             let tokenKey = String(requestMessage.id);\r
559             requestTokens[tokenKey] = cancellationSource;\r
560             try {\r
561                 let handlerResult;\r
562                 if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {\r
563                     handlerResult = requestHandler\r
564                         ? requestHandler(cancellationSource.token)\r
565                         : starRequestHandler(requestMessage.method, cancellationSource.token);\r
566                 }\r
567                 else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {\r
568                     handlerResult = requestHandler\r
569                         ? requestHandler(...requestMessage.params, cancellationSource.token)\r
570                         : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);\r
571                 }\r
572                 else {\r
573                     handlerResult = requestHandler\r
574                         ? requestHandler(requestMessage.params, cancellationSource.token)\r
575                         : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);\r
576                 }\r
577                 let promise = handlerResult;\r
578                 if (!handlerResult) {\r
579                     delete requestTokens[tokenKey];\r
580                     replySuccess(handlerResult, requestMessage.method, startTime);\r
581                 }\r
582                 else if (promise.then) {\r
583                     promise.then((resultOrError) => {\r
584                         delete requestTokens[tokenKey];\r
585                         reply(resultOrError, requestMessage.method, startTime);\r
586                     }, error => {\r
587                         delete requestTokens[tokenKey];\r
588                         if (error instanceof messages_1.ResponseError) {\r
589                             replyError(error, requestMessage.method, startTime);\r
590                         }\r
591                         else if (error && Is.string(error.message)) {\r
592                             replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);\r
593                         }\r
594                         else {\r
595                             replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);\r
596                         }\r
597                     });\r
598                 }\r
599                 else {\r
600                     delete requestTokens[tokenKey];\r
601                     reply(handlerResult, requestMessage.method, startTime);\r
602                 }\r
603             }\r
604             catch (error) {\r
605                 delete requestTokens[tokenKey];\r
606                 if (error instanceof messages_1.ResponseError) {\r
607                     reply(error, requestMessage.method, startTime);\r
608                 }\r
609                 else if (error && Is.string(error.message)) {\r
610                     replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);\r
611                 }\r
612                 else {\r
613                     replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);\r
614                 }\r
615             }\r
616         }\r
617         else {\r
618             replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);\r
619         }\r
620     }\r
621     function handleResponse(responseMessage) {\r
622         if (isDisposed()) {\r
623             // See handle request.\r
624             return;\r
625         }\r
626         if (responseMessage.id === null) {\r
627             if (responseMessage.error) {\r
628                 logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);\r
629             }\r
630             else {\r
631                 logger.error(`Received response message without id. No further error information provided.`);\r
632             }\r
633         }\r
634         else {\r
635             let key = String(responseMessage.id);\r
636             let responsePromise = responsePromises[key];\r
637             traceReceivedResponse(responseMessage, responsePromise);\r
638             if (responsePromise) {\r
639                 delete responsePromises[key];\r
640                 try {\r
641                     if (responseMessage.error) {\r
642                         let error = responseMessage.error;\r
643                         responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));\r
644                     }\r
645                     else if (responseMessage.result !== void 0) {\r
646                         responsePromise.resolve(responseMessage.result);\r
647                     }\r
648                     else {\r
649                         throw new Error('Should never happen.');\r
650                     }\r
651                 }\r
652                 catch (error) {\r
653                     if (error.message) {\r
654                         logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);\r
655                     }\r
656                     else {\r
657                         logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);\r
658                     }\r
659                 }\r
660             }\r
661         }\r
662     }\r
663     function handleNotification(message) {\r
664         if (isDisposed()) {\r
665             // See handle request.\r
666             return;\r
667         }\r
668         let type = undefined;\r
669         let notificationHandler;\r
670         if (message.method === CancelNotification.type.method) {\r
671             notificationHandler = (params) => {\r
672                 let id = params.id;\r
673                 let source = requestTokens[String(id)];\r
674                 if (source) {\r
675                     source.cancel();\r
676                 }\r
677             };\r
678         }\r
679         else {\r
680             let element = notificationHandlers[message.method];\r
681             if (element) {\r
682                 notificationHandler = element.handler;\r
683                 type = element.type;\r
684             }\r
685         }\r
686         if (notificationHandler || starNotificationHandler) {\r
687             try {\r
688                 traceReceivedNotification(message);\r
689                 if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {\r
690                     notificationHandler ? notificationHandler() : starNotificationHandler(message.method);\r
691                 }\r
692                 else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {\r
693                     notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);\r
694                 }\r
695                 else {\r
696                     notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);\r
697                 }\r
698             }\r
699             catch (error) {\r
700                 if (error.message) {\r
701                     logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);\r
702                 }\r
703                 else {\r
704                     logger.error(`Notification handler '${message.method}' failed unexpectedly.`);\r
705                 }\r
706             }\r
707         }\r
708         else {\r
709             unhandledNotificationEmitter.fire(message);\r
710         }\r
711     }\r
712     function handleInvalidMessage(message) {\r
713         if (!message) {\r
714             logger.error('Received empty message.');\r
715             return;\r
716         }\r
717         logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);\r
718         // Test whether we find an id to reject the promise\r
719         let responseMessage = message;\r
720         if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {\r
721             let key = String(responseMessage.id);\r
722             let responseHandler = responsePromises[key];\r
723             if (responseHandler) {\r
724                 responseHandler.reject(new Error('The received response has neither a result nor an error property.'));\r
725             }\r
726         }\r
727     }\r
728     function traceSendingRequest(message) {\r
729         if (trace === Trace.Off || !tracer) {\r
730             return;\r
731         }\r
732         if (traceFormat === TraceFormat.Text) {\r
733             let data = undefined;\r
734             if (trace === Trace.Verbose && message.params) {\r
735                 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;\r
736             }\r
737             tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);\r
738         }\r
739         else {\r
740             logLSPMessage('send-request', message);\r
741         }\r
742     }\r
743     function traceSendingNotification(message) {\r
744         if (trace === Trace.Off || !tracer) {\r
745             return;\r
746         }\r
747         if (traceFormat === TraceFormat.Text) {\r
748             let data = undefined;\r
749             if (trace === Trace.Verbose) {\r
750                 if (message.params) {\r
751                     data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;\r
752                 }\r
753                 else {\r
754                     data = 'No parameters provided.\n\n';\r
755                 }\r
756             }\r
757             tracer.log(`Sending notification '${message.method}'.`, data);\r
758         }\r
759         else {\r
760             logLSPMessage('send-notification', message);\r
761         }\r
762     }\r
763     function traceSendingResponse(message, method, startTime) {\r
764         if (trace === Trace.Off || !tracer) {\r
765             return;\r
766         }\r
767         if (traceFormat === TraceFormat.Text) {\r
768             let data = undefined;\r
769             if (trace === Trace.Verbose) {\r
770                 if (message.error && message.error.data) {\r
771                     data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;\r
772                 }\r
773                 else {\r
774                     if (message.result) {\r
775                         data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;\r
776                     }\r
777                     else if (message.error === void 0) {\r
778                         data = 'No result returned.\n\n';\r
779                     }\r
780                 }\r
781             }\r
782             tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);\r
783         }\r
784         else {\r
785             logLSPMessage('send-response', message);\r
786         }\r
787     }\r
788     function traceReceivedRequest(message) {\r
789         if (trace === Trace.Off || !tracer) {\r
790             return;\r
791         }\r
792         if (traceFormat === TraceFormat.Text) {\r
793             let data = undefined;\r
794             if (trace === Trace.Verbose && message.params) {\r
795                 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;\r
796             }\r
797             tracer.log(`Received request '${message.method} - (${message.id})'.`, data);\r
798         }\r
799         else {\r
800             logLSPMessage('receive-request', message);\r
801         }\r
802     }\r
803     function traceReceivedNotification(message) {\r
804         if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {\r
805             return;\r
806         }\r
807         if (traceFormat === TraceFormat.Text) {\r
808             let data = undefined;\r
809             if (trace === Trace.Verbose) {\r
810                 if (message.params) {\r
811                     data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;\r
812                 }\r
813                 else {\r
814                     data = 'No parameters provided.\n\n';\r
815                 }\r
816             }\r
817             tracer.log(`Received notification '${message.method}'.`, data);\r
818         }\r
819         else {\r
820             logLSPMessage('receive-notification', message);\r
821         }\r
822     }\r
823     function traceReceivedResponse(message, responsePromise) {\r
824         if (trace === Trace.Off || !tracer) {\r
825             return;\r
826         }\r
827         if (traceFormat === TraceFormat.Text) {\r
828             let data = undefined;\r
829             if (trace === Trace.Verbose) {\r
830                 if (message.error && message.error.data) {\r
831                     data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;\r
832                 }\r
833                 else {\r
834                     if (message.result) {\r
835                         data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;\r
836                     }\r
837                     else if (message.error === void 0) {\r
838                         data = 'No result returned.\n\n';\r
839                     }\r
840                 }\r
841             }\r
842             if (responsePromise) {\r
843                 let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';\r
844                 tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);\r
845             }\r
846             else {\r
847                 tracer.log(`Received response ${message.id} without active response promise.`, data);\r
848             }\r
849         }\r
850         else {\r
851             logLSPMessage('receive-response', message);\r
852         }\r
853     }\r
854     function logLSPMessage(type, message) {\r
855         if (!tracer || trace === Trace.Off) {\r
856             return;\r
857         }\r
858         const lspMessage = {\r
859             isLSPMessage: true,\r
860             type,\r
861             message,\r
862             timestamp: Date.now()\r
863         };\r
864         tracer.log(lspMessage);\r
865     }\r
866     function throwIfClosedOrDisposed() {\r
867         if (isClosed()) {\r
868             throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');\r
869         }\r
870         if (isDisposed()) {\r
871             throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');\r
872         }\r
873     }\r
874     function throwIfListening() {\r
875         if (isListening()) {\r
876             throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');\r
877         }\r
878     }\r
879     function throwIfNotListening() {\r
880         if (!isListening()) {\r
881             throw new Error('Call listen() first.');\r
882         }\r
883     }\r
884     function undefinedToNull(param) {\r
885         if (param === void 0) {\r
886             return null;\r
887         }\r
888         else {\r
889             return param;\r
890         }\r
891     }\r
892     function computeMessageParams(type, params) {\r
893         let result;\r
894         let numberOfParams = type.numberOfParams;\r
895         switch (numberOfParams) {\r
896             case 0:\r
897                 result = null;\r
898                 break;\r
899             case 1:\r
900                 result = undefinedToNull(params[0]);\r
901                 break;\r
902             default:\r
903                 result = [];\r
904                 for (let i = 0; i < params.length && i < numberOfParams; i++) {\r
905                     result.push(undefinedToNull(params[i]));\r
906                 }\r
907                 if (params.length < numberOfParams) {\r
908                     for (let i = params.length; i < numberOfParams; i++) {\r
909                         result.push(null);\r
910                     }\r
911                 }\r
912                 break;\r
913         }\r
914         return result;\r
915     }\r
916     let connection = {\r
917         sendNotification: (type, ...params) => {\r
918             throwIfClosedOrDisposed();\r
919             let method;\r
920             let messageParams;\r
921             if (Is.string(type)) {\r
922                 method = type;\r
923                 switch (params.length) {\r
924                     case 0:\r
925                         messageParams = null;\r
926                         break;\r
927                     case 1:\r
928                         messageParams = params[0];\r
929                         break;\r
930                     default:\r
931                         messageParams = params;\r
932                         break;\r
933                 }\r
934             }\r
935             else {\r
936                 method = type.method;\r
937                 messageParams = computeMessageParams(type, params);\r
938             }\r
939             let notificationMessage = {\r
940                 jsonrpc: version,\r
941                 method: method,\r
942                 params: messageParams\r
943             };\r
944             traceSendingNotification(notificationMessage);\r
945             messageWriter.write(notificationMessage);\r
946         },\r
947         onNotification: (type, handler) => {\r
948             throwIfClosedOrDisposed();\r
949             if (Is.func(type)) {\r
950                 starNotificationHandler = type;\r
951             }\r
952             else if (handler) {\r
953                 if (Is.string(type)) {\r
954                     notificationHandlers[type] = { type: undefined, handler };\r
955                 }\r
956                 else {\r
957                     notificationHandlers[type.method] = { type, handler };\r
958                 }\r
959             }\r
960         },\r
961         onProgress: (_type, token, handler) => {\r
962             if (progressHandlers.has(token)) {\r
963                 throw new Error(`Progress handler for token ${token} already registered`);\r
964             }\r
965             progressHandlers.set(token, handler);\r
966             return {\r
967                 dispose: () => {\r
968                     progressHandlers.delete(token);\r
969                 }\r
970             };\r
971         },\r
972         sendProgress: (_type, token, value) => {\r
973             connection.sendNotification(ProgressNotification.type, { token, value });\r
974         },\r
975         onUnhandledProgress: unhandledProgressEmitter.event,\r
976         sendRequest: (type, ...params) => {\r
977             throwIfClosedOrDisposed();\r
978             throwIfNotListening();\r
979             let method;\r
980             let messageParams;\r
981             let token = undefined;\r
982             if (Is.string(type)) {\r
983                 method = type;\r
984                 switch (params.length) {\r
985                     case 0:\r
986                         messageParams = null;\r
987                         break;\r
988                     case 1:\r
989                         // The cancellation token is optional so it can also be undefined.\r
990                         if (cancellation_1.CancellationToken.is(params[0])) {\r
991                             messageParams = null;\r
992                             token = params[0];\r
993                         }\r
994                         else {\r
995                             messageParams = undefinedToNull(params[0]);\r
996                         }\r
997                         break;\r
998                     default:\r
999                         const last = params.length - 1;\r
1000                         if (cancellation_1.CancellationToken.is(params[last])) {\r
1001                             token = params[last];\r
1002                             if (params.length === 2) {\r
1003                                 messageParams = undefinedToNull(params[0]);\r
1004                             }\r
1005                             else {\r
1006                                 messageParams = params.slice(0, last).map(value => undefinedToNull(value));\r
1007                             }\r
1008                         }\r
1009                         else {\r
1010                             messageParams = params.map(value => undefinedToNull(value));\r
1011                         }\r
1012                         break;\r
1013                 }\r
1014             }\r
1015             else {\r
1016                 method = type.method;\r
1017                 messageParams = computeMessageParams(type, params);\r
1018                 let numberOfParams = type.numberOfParams;\r
1019                 token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;\r
1020             }\r
1021             let id = sequenceNumber++;\r
1022             let result = new Promise((resolve, reject) => {\r
1023                 let requestMessage = {\r
1024                     jsonrpc: version,\r
1025                     id: id,\r
1026                     method: method,\r
1027                     params: messageParams\r
1028                 };\r
1029                 let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };\r
1030                 traceSendingRequest(requestMessage);\r
1031                 try {\r
1032                     messageWriter.write(requestMessage);\r
1033                 }\r
1034                 catch (e) {\r
1035                     // Writing the message failed. So we need to reject the promise.\r
1036                     responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));\r
1037                     responsePromise = null;\r
1038                 }\r
1039                 if (responsePromise) {\r
1040                     responsePromises[String(id)] = responsePromise;\r
1041                 }\r
1042             });\r
1043             if (token) {\r
1044                 token.onCancellationRequested(() => {\r
1045                     connection.sendNotification(CancelNotification.type, { id });\r
1046                 });\r
1047             }\r
1048             return result;\r
1049         },\r
1050         onRequest: (type, handler) => {\r
1051             throwIfClosedOrDisposed();\r
1052             if (Is.func(type)) {\r
1053                 starRequestHandler = type;\r
1054             }\r
1055             else if (handler) {\r
1056                 if (Is.string(type)) {\r
1057                     requestHandlers[type] = { type: undefined, handler };\r
1058                 }\r
1059                 else {\r
1060                     requestHandlers[type.method] = { type, handler };\r
1061                 }\r
1062             }\r
1063         },\r
1064         trace: (_value, _tracer, sendNotificationOrTraceOptions) => {\r
1065             let _sendNotification = false;\r
1066             let _traceFormat = TraceFormat.Text;\r
1067             if (sendNotificationOrTraceOptions !== void 0) {\r
1068                 if (Is.boolean(sendNotificationOrTraceOptions)) {\r
1069                     _sendNotification = sendNotificationOrTraceOptions;\r
1070                 }\r
1071                 else {\r
1072                     _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;\r
1073                     _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;\r
1074                 }\r
1075             }\r
1076             trace = _value;\r
1077             traceFormat = _traceFormat;\r
1078             if (trace === Trace.Off) {\r
1079                 tracer = undefined;\r
1080             }\r
1081             else {\r
1082                 tracer = _tracer;\r
1083             }\r
1084             if (_sendNotification && !isClosed() && !isDisposed()) {\r
1085                 connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });\r
1086             }\r
1087         },\r
1088         onError: errorEmitter.event,\r
1089         onClose: closeEmitter.event,\r
1090         onUnhandledNotification: unhandledNotificationEmitter.event,\r
1091         onDispose: disposeEmitter.event,\r
1092         dispose: () => {\r
1093             if (isDisposed()) {\r
1094                 return;\r
1095             }\r
1096             state = ConnectionState.Disposed;\r
1097             disposeEmitter.fire(undefined);\r
1098             let error = new Error('Connection got disposed.');\r
1099             Object.keys(responsePromises).forEach((key) => {\r
1100                 responsePromises[key].reject(error);\r
1101             });\r
1102             responsePromises = Object.create(null);\r
1103             requestTokens = Object.create(null);\r
1104             messageQueue = new linkedMap_1.LinkedMap();\r
1105             // Test for backwards compatibility\r
1106             if (Is.func(messageWriter.dispose)) {\r
1107                 messageWriter.dispose();\r
1108             }\r
1109             if (Is.func(messageReader.dispose)) {\r
1110                 messageReader.dispose();\r
1111             }\r
1112         },\r
1113         listen: () => {\r
1114             throwIfClosedOrDisposed();\r
1115             throwIfListening();\r
1116             state = ConnectionState.Listening;\r
1117             messageReader.listen(callback);\r
1118         },\r
1119         inspect: () => {\r
1120             // eslint-disable-next-line no-console\r
1121             console.log('inspect');\r
1122         }\r
1123     };\r
1124     connection.onNotification(LogTraceNotification.type, (params) => {\r
1125         if (trace === Trace.Off || !tracer) {\r
1126             return;\r
1127         }\r
1128         tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);\r
1129     });\r
1130     connection.onNotification(ProgressNotification.type, (params) => {\r
1131         const handler = progressHandlers.get(params.token);\r
1132         if (handler) {\r
1133             handler(params.value);\r
1134         }\r
1135         else {\r
1136             unhandledProgressEmitter.fire(params);\r
1137         }\r
1138     });\r
1139     return connection;\r
1140 }\r
1141 function isMessageReader(value) {\r
1142     return value.listen !== void 0 && value.read === void 0;\r
1143 }\r
1144 function isMessageWriter(value) {\r
1145     return value.write !== void 0 && value.end === void 0;\r
1146 }\r
1147 function createMessageConnection(input, output, logger, strategy) {\r
1148     if (!logger) {\r
1149         logger = exports.NullLogger;\r
1150     }\r
1151     let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);\r
1152     let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);\r
1153     return _createMessageConnection(reader, writer, logger, strategy);\r
1154 }\r
1155 exports.createMessageConnection = createMessageConnection;\r
1156
1157
1158 /***/ }),
1159 /* 6 */
1160 /***/ (function(module, exports, __webpack_require__) {
1161
1162 "use strict";
1163 /* --------------------------------------------------------------------------------------------\r
1164  * Copyright (c) Microsoft Corporation. All rights reserved.\r
1165  * Licensed under the MIT License. See License.txt in the project root for license information.\r
1166  * ------------------------------------------------------------------------------------------ */\r
1167 \r
1168 Object.defineProperty(exports, "__esModule", { value: true });\r
1169 function boolean(value) {\r
1170     return value === true || value === false;\r
1171 }\r
1172 exports.boolean = boolean;\r
1173 function string(value) {\r
1174     return typeof value === 'string' || value instanceof String;\r
1175 }\r
1176 exports.string = string;\r
1177 function number(value) {\r
1178     return typeof value === 'number' || value instanceof Number;\r
1179 }\r
1180 exports.number = number;\r
1181 function error(value) {\r
1182     return value instanceof Error;\r
1183 }\r
1184 exports.error = error;\r
1185 function func(value) {\r
1186     return typeof value === 'function';\r
1187 }\r
1188 exports.func = func;\r
1189 function array(value) {\r
1190     return Array.isArray(value);\r
1191 }\r
1192 exports.array = array;\r
1193 function stringArray(value) {\r
1194     return array(value) && value.every(elem => string(elem));\r
1195 }\r
1196 exports.stringArray = stringArray;\r
1197
1198
1199 /***/ }),
1200 /* 7 */
1201 /***/ (function(module, exports, __webpack_require__) {
1202
1203 "use strict";
1204 /* --------------------------------------------------------------------------------------------\r
1205  * Copyright (c) Microsoft Corporation. All rights reserved.\r
1206  * Licensed under the MIT License. See License.txt in the project root for license information.\r
1207  * ------------------------------------------------------------------------------------------ */\r
1208 \r
1209 Object.defineProperty(exports, "__esModule", { value: true });\r
1210 const is = __webpack_require__(6);\r
1211 /**\r
1212  * Predefined error codes.\r
1213  */\r
1214 var ErrorCodes;\r
1215 (function (ErrorCodes) {\r
1216     // Defined by JSON RPC\r
1217     ErrorCodes.ParseError = -32700;\r
1218     ErrorCodes.InvalidRequest = -32600;\r
1219     ErrorCodes.MethodNotFound = -32601;\r
1220     ErrorCodes.InvalidParams = -32602;\r
1221     ErrorCodes.InternalError = -32603;\r
1222     ErrorCodes.serverErrorStart = -32099;\r
1223     ErrorCodes.serverErrorEnd = -32000;\r
1224     ErrorCodes.ServerNotInitialized = -32002;\r
1225     ErrorCodes.UnknownErrorCode = -32001;\r
1226     // Defined by the protocol.\r
1227     ErrorCodes.RequestCancelled = -32800;\r
1228     ErrorCodes.ContentModified = -32801;\r
1229     // Defined by VSCode library.\r
1230     ErrorCodes.MessageWriteError = 1;\r
1231     ErrorCodes.MessageReadError = 2;\r
1232 })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));\r
1233 /**\r
1234  * An error object return in a response in case a request\r
1235  * has failed.\r
1236  */\r
1237 class ResponseError extends Error {\r
1238     constructor(code, message, data) {\r
1239         super(message);\r
1240         this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;\r
1241         this.data = data;\r
1242         Object.setPrototypeOf(this, ResponseError.prototype);\r
1243     }\r
1244     toJson() {\r
1245         return {\r
1246             code: this.code,\r
1247             message: this.message,\r
1248             data: this.data,\r
1249         };\r
1250     }\r
1251 }\r
1252 exports.ResponseError = ResponseError;\r
1253 /**\r
1254  * An abstract implementation of a MessageType.\r
1255  */\r
1256 class AbstractMessageType {\r
1257     constructor(_method, _numberOfParams) {\r
1258         this._method = _method;\r
1259         this._numberOfParams = _numberOfParams;\r
1260     }\r
1261     get method() {\r
1262         return this._method;\r
1263     }\r
1264     get numberOfParams() {\r
1265         return this._numberOfParams;\r
1266     }\r
1267 }\r
1268 exports.AbstractMessageType = AbstractMessageType;\r
1269 /**\r
1270  * Classes to type request response pairs\r
1271  *\r
1272  * The type parameter RO will be removed in the next major version\r
1273  * of the JSON RPC library since it is a LSP concept and doesn't\r
1274  * belong here. For now it is tagged as default never.\r
1275  */\r
1276 class RequestType0 extends AbstractMessageType {\r
1277     constructor(method) {\r
1278         super(method, 0);\r
1279     }\r
1280 }\r
1281 exports.RequestType0 = RequestType0;\r
1282 class RequestType extends AbstractMessageType {\r
1283     constructor(method) {\r
1284         super(method, 1);\r
1285     }\r
1286 }\r
1287 exports.RequestType = RequestType;\r
1288 class RequestType1 extends AbstractMessageType {\r
1289     constructor(method) {\r
1290         super(method, 1);\r
1291     }\r
1292 }\r
1293 exports.RequestType1 = RequestType1;\r
1294 class RequestType2 extends AbstractMessageType {\r
1295     constructor(method) {\r
1296         super(method, 2);\r
1297     }\r
1298 }\r
1299 exports.RequestType2 = RequestType2;\r
1300 class RequestType3 extends AbstractMessageType {\r
1301     constructor(method) {\r
1302         super(method, 3);\r
1303     }\r
1304 }\r
1305 exports.RequestType3 = RequestType3;\r
1306 class RequestType4 extends AbstractMessageType {\r
1307     constructor(method) {\r
1308         super(method, 4);\r
1309     }\r
1310 }\r
1311 exports.RequestType4 = RequestType4;\r
1312 class RequestType5 extends AbstractMessageType {\r
1313     constructor(method) {\r
1314         super(method, 5);\r
1315     }\r
1316 }\r
1317 exports.RequestType5 = RequestType5;\r
1318 class RequestType6 extends AbstractMessageType {\r
1319     constructor(method) {\r
1320         super(method, 6);\r
1321     }\r
1322 }\r
1323 exports.RequestType6 = RequestType6;\r
1324 class RequestType7 extends AbstractMessageType {\r
1325     constructor(method) {\r
1326         super(method, 7);\r
1327     }\r
1328 }\r
1329 exports.RequestType7 = RequestType7;\r
1330 class RequestType8 extends AbstractMessageType {\r
1331     constructor(method) {\r
1332         super(method, 8);\r
1333     }\r
1334 }\r
1335 exports.RequestType8 = RequestType8;\r
1336 class RequestType9 extends AbstractMessageType {\r
1337     constructor(method) {\r
1338         super(method, 9);\r
1339     }\r
1340 }\r
1341 exports.RequestType9 = RequestType9;\r
1342 /**\r
1343  * The type parameter RO will be removed in the next major version\r
1344  * of the JSON RPC library since it is a LSP concept and doesn't\r
1345  * belong here. For now it is tagged as default never.\r
1346  */\r
1347 class NotificationType extends AbstractMessageType {\r
1348     constructor(method) {\r
1349         super(method, 1);\r
1350         this._ = undefined;\r
1351     }\r
1352 }\r
1353 exports.NotificationType = NotificationType;\r
1354 class NotificationType0 extends AbstractMessageType {\r
1355     constructor(method) {\r
1356         super(method, 0);\r
1357     }\r
1358 }\r
1359 exports.NotificationType0 = NotificationType0;\r
1360 class NotificationType1 extends AbstractMessageType {\r
1361     constructor(method) {\r
1362         super(method, 1);\r
1363     }\r
1364 }\r
1365 exports.NotificationType1 = NotificationType1;\r
1366 class NotificationType2 extends AbstractMessageType {\r
1367     constructor(method) {\r
1368         super(method, 2);\r
1369     }\r
1370 }\r
1371 exports.NotificationType2 = NotificationType2;\r
1372 class NotificationType3 extends AbstractMessageType {\r
1373     constructor(method) {\r
1374         super(method, 3);\r
1375     }\r
1376 }\r
1377 exports.NotificationType3 = NotificationType3;\r
1378 class NotificationType4 extends AbstractMessageType {\r
1379     constructor(method) {\r
1380         super(method, 4);\r
1381     }\r
1382 }\r
1383 exports.NotificationType4 = NotificationType4;\r
1384 class NotificationType5 extends AbstractMessageType {\r
1385     constructor(method) {\r
1386         super(method, 5);\r
1387     }\r
1388 }\r
1389 exports.NotificationType5 = NotificationType5;\r
1390 class NotificationType6 extends AbstractMessageType {\r
1391     constructor(method) {\r
1392         super(method, 6);\r
1393     }\r
1394 }\r
1395 exports.NotificationType6 = NotificationType6;\r
1396 class NotificationType7 extends AbstractMessageType {\r
1397     constructor(method) {\r
1398         super(method, 7);\r
1399     }\r
1400 }\r
1401 exports.NotificationType7 = NotificationType7;\r
1402 class NotificationType8 extends AbstractMessageType {\r
1403     constructor(method) {\r
1404         super(method, 8);\r
1405     }\r
1406 }\r
1407 exports.NotificationType8 = NotificationType8;\r
1408 class NotificationType9 extends AbstractMessageType {\r
1409     constructor(method) {\r
1410         super(method, 9);\r
1411     }\r
1412 }\r
1413 exports.NotificationType9 = NotificationType9;\r
1414 /**\r
1415  * Tests if the given message is a request message\r
1416  */\r
1417 function isRequestMessage(message) {\r
1418     let candidate = message;\r
1419     return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));\r
1420 }\r
1421 exports.isRequestMessage = isRequestMessage;\r
1422 /**\r
1423  * Tests if the given message is a notification message\r
1424  */\r
1425 function isNotificationMessage(message) {\r
1426     let candidate = message;\r
1427     return candidate && is.string(candidate.method) && message.id === void 0;\r
1428 }\r
1429 exports.isNotificationMessage = isNotificationMessage;\r
1430 /**\r
1431  * Tests if the given message is a response message\r
1432  */\r
1433 function isResponseMessage(message) {\r
1434     let candidate = message;\r
1435     return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);\r
1436 }\r
1437 exports.isResponseMessage = isResponseMessage;\r
1438
1439
1440 /***/ }),
1441 /* 8 */
1442 /***/ (function(module, exports, __webpack_require__) {
1443
1444 "use strict";
1445 /* --------------------------------------------------------------------------------------------\r
1446  * Copyright (c) Microsoft Corporation. All rights reserved.\r
1447  * Licensed under the MIT License. See License.txt in the project root for license information.\r
1448  * ------------------------------------------------------------------------------------------ */\r
1449 \r
1450 Object.defineProperty(exports, "__esModule", { value: true });\r
1451 const events_1 = __webpack_require__(9);\r
1452 const Is = __webpack_require__(6);\r
1453 let DefaultSize = 8192;\r
1454 let CR = Buffer.from('\r', 'ascii')[0];\r
1455 let LF = Buffer.from('\n', 'ascii')[0];\r
1456 let CRLF = '\r\n';\r
1457 class MessageBuffer {\r
1458     constructor(encoding = 'utf8') {\r
1459         this.encoding = encoding;\r
1460         this.index = 0;\r
1461         this.buffer = Buffer.allocUnsafe(DefaultSize);\r
1462     }\r
1463     append(chunk) {\r
1464         var toAppend = chunk;\r
1465         if (typeof (chunk) === 'string') {\r
1466             var str = chunk;\r
1467             var bufferLen = Buffer.byteLength(str, this.encoding);\r
1468             toAppend = Buffer.allocUnsafe(bufferLen);\r
1469             toAppend.write(str, 0, bufferLen, this.encoding);\r
1470         }\r
1471         if (this.buffer.length - this.index >= toAppend.length) {\r
1472             toAppend.copy(this.buffer, this.index, 0, toAppend.length);\r
1473         }\r
1474         else {\r
1475             var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;\r
1476             if (this.index === 0) {\r
1477                 this.buffer = Buffer.allocUnsafe(newSize);\r
1478                 toAppend.copy(this.buffer, 0, 0, toAppend.length);\r
1479             }\r
1480             else {\r
1481                 this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);\r
1482             }\r
1483         }\r
1484         this.index += toAppend.length;\r
1485     }\r
1486     tryReadHeaders() {\r
1487         let result = undefined;\r
1488         let current = 0;\r
1489         while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {\r
1490             current++;\r
1491         }\r
1492         // No header / body separator found (e.g CRLFCRLF)\r
1493         if (current + 3 >= this.index) {\r
1494             return result;\r
1495         }\r
1496         result = Object.create(null);\r
1497         let headers = this.buffer.toString('ascii', 0, current).split(CRLF);\r
1498         headers.forEach((header) => {\r
1499             let index = header.indexOf(':');\r
1500             if (index === -1) {\r
1501                 throw new Error('Message header must separate key and value using :');\r
1502             }\r
1503             let key = header.substr(0, index);\r
1504             let value = header.substr(index + 1).trim();\r
1505             result[key] = value;\r
1506         });\r
1507         let nextStart = current + 4;\r
1508         this.buffer = this.buffer.slice(nextStart);\r
1509         this.index = this.index - nextStart;\r
1510         return result;\r
1511     }\r
1512     tryReadContent(length) {\r
1513         if (this.index < length) {\r
1514             return null;\r
1515         }\r
1516         let result = this.buffer.toString(this.encoding, 0, length);\r
1517         let nextStart = length;\r
1518         this.buffer.copy(this.buffer, 0, nextStart);\r
1519         this.index = this.index - nextStart;\r
1520         return result;\r
1521     }\r
1522     get numberOfBytes() {\r
1523         return this.index;\r
1524     }\r
1525 }\r
1526 var MessageReader;\r
1527 (function (MessageReader) {\r
1528     function is(value) {\r
1529         let candidate = value;\r
1530         return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&\r
1531             Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);\r
1532     }\r
1533     MessageReader.is = is;\r
1534 })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));\r
1535 class AbstractMessageReader {\r
1536     constructor() {\r
1537         this.errorEmitter = new events_1.Emitter();\r
1538         this.closeEmitter = new events_1.Emitter();\r
1539         this.partialMessageEmitter = new events_1.Emitter();\r
1540     }\r
1541     dispose() {\r
1542         this.errorEmitter.dispose();\r
1543         this.closeEmitter.dispose();\r
1544     }\r
1545     get onError() {\r
1546         return this.errorEmitter.event;\r
1547     }\r
1548     fireError(error) {\r
1549         this.errorEmitter.fire(this.asError(error));\r
1550     }\r
1551     get onClose() {\r
1552         return this.closeEmitter.event;\r
1553     }\r
1554     fireClose() {\r
1555         this.closeEmitter.fire(undefined);\r
1556     }\r
1557     get onPartialMessage() {\r
1558         return this.partialMessageEmitter.event;\r
1559     }\r
1560     firePartialMessage(info) {\r
1561         this.partialMessageEmitter.fire(info);\r
1562     }\r
1563     asError(error) {\r
1564         if (error instanceof Error) {\r
1565             return error;\r
1566         }\r
1567         else {\r
1568             return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);\r
1569         }\r
1570     }\r
1571 }\r
1572 exports.AbstractMessageReader = AbstractMessageReader;\r
1573 class StreamMessageReader extends AbstractMessageReader {\r
1574     constructor(readable, encoding = 'utf8') {\r
1575         super();\r
1576         this.readable = readable;\r
1577         this.buffer = new MessageBuffer(encoding);\r
1578         this._partialMessageTimeout = 10000;\r
1579     }\r
1580     set partialMessageTimeout(timeout) {\r
1581         this._partialMessageTimeout = timeout;\r
1582     }\r
1583     get partialMessageTimeout() {\r
1584         return this._partialMessageTimeout;\r
1585     }\r
1586     listen(callback) {\r
1587         this.nextMessageLength = -1;\r
1588         this.messageToken = 0;\r
1589         this.partialMessageTimer = undefined;\r
1590         this.callback = callback;\r
1591         this.readable.on('data', (data) => {\r
1592             this.onData(data);\r
1593         });\r
1594         this.readable.on('error', (error) => this.fireError(error));\r
1595         this.readable.on('close', () => this.fireClose());\r
1596     }\r
1597     onData(data) {\r
1598         this.buffer.append(data);\r
1599         while (true) {\r
1600             if (this.nextMessageLength === -1) {\r
1601                 let headers = this.buffer.tryReadHeaders();\r
1602                 if (!headers) {\r
1603                     return;\r
1604                 }\r
1605                 let contentLength = headers['Content-Length'];\r
1606                 if (!contentLength) {\r
1607                     throw new Error('Header must provide a Content-Length property.');\r
1608                 }\r
1609                 let length = parseInt(contentLength);\r
1610                 if (isNaN(length)) {\r
1611                     throw new Error('Content-Length value must be a number.');\r
1612                 }\r
1613                 this.nextMessageLength = length;\r
1614                 // Take the encoding form the header. For compatibility\r
1615                 // treat both utf-8 and utf8 as node utf8\r
1616             }\r
1617             var msg = this.buffer.tryReadContent(this.nextMessageLength);\r
1618             if (msg === null) {\r
1619                 /** We haven't received the full message yet. */\r
1620                 this.setPartialMessageTimer();\r
1621                 return;\r
1622             }\r
1623             this.clearPartialMessageTimer();\r
1624             this.nextMessageLength = -1;\r
1625             this.messageToken++;\r
1626             var json = JSON.parse(msg);\r
1627             this.callback(json);\r
1628         }\r
1629     }\r
1630     clearPartialMessageTimer() {\r
1631         if (this.partialMessageTimer) {\r
1632             clearTimeout(this.partialMessageTimer);\r
1633             this.partialMessageTimer = undefined;\r
1634         }\r
1635     }\r
1636     setPartialMessageTimer() {\r
1637         this.clearPartialMessageTimer();\r
1638         if (this._partialMessageTimeout <= 0) {\r
1639             return;\r
1640         }\r
1641         this.partialMessageTimer = setTimeout((token, timeout) => {\r
1642             this.partialMessageTimer = undefined;\r
1643             if (token === this.messageToken) {\r
1644                 this.firePartialMessage({ messageToken: token, waitingTime: timeout });\r
1645                 this.setPartialMessageTimer();\r
1646             }\r
1647         }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);\r
1648     }\r
1649 }\r
1650 exports.StreamMessageReader = StreamMessageReader;\r
1651 class IPCMessageReader extends AbstractMessageReader {\r
1652     constructor(process) {\r
1653         super();\r
1654         this.process = process;\r
1655         let eventEmitter = this.process;\r
1656         eventEmitter.on('error', (error) => this.fireError(error));\r
1657         eventEmitter.on('close', () => this.fireClose());\r
1658     }\r
1659     listen(callback) {\r
1660         this.process.on('message', callback);\r
1661     }\r
1662 }\r
1663 exports.IPCMessageReader = IPCMessageReader;\r
1664 class SocketMessageReader extends StreamMessageReader {\r
1665     constructor(socket, encoding = 'utf-8') {\r
1666         super(socket, encoding);\r
1667     }\r
1668 }\r
1669 exports.SocketMessageReader = SocketMessageReader;\r
1670
1671
1672 /***/ }),
1673 /* 9 */
1674 /***/ (function(module, exports, __webpack_require__) {
1675
1676 "use strict";
1677 /* --------------------------------------------------------------------------------------------\r
1678  * Copyright (c) Microsoft Corporation. All rights reserved.\r
1679  * Licensed under the MIT License. See License.txt in the project root for license information.\r
1680  * ------------------------------------------------------------------------------------------ */\r
1681 \r
1682 Object.defineProperty(exports, "__esModule", { value: true });\r
1683 var Disposable;\r
1684 (function (Disposable) {\r
1685     function create(func) {\r
1686         return {\r
1687             dispose: func\r
1688         };\r
1689     }\r
1690     Disposable.create = create;\r
1691 })(Disposable = exports.Disposable || (exports.Disposable = {}));\r
1692 var Event;\r
1693 (function (Event) {\r
1694     const _disposable = { dispose() { } };\r
1695     Event.None = function () { return _disposable; };\r
1696 })(Event = exports.Event || (exports.Event = {}));\r
1697 class CallbackList {\r
1698     add(callback, context = null, bucket) {\r
1699         if (!this._callbacks) {\r
1700             this._callbacks = [];\r
1701             this._contexts = [];\r
1702         }\r
1703         this._callbacks.push(callback);\r
1704         this._contexts.push(context);\r
1705         if (Array.isArray(bucket)) {\r
1706             bucket.push({ dispose: () => this.remove(callback, context) });\r
1707         }\r
1708     }\r
1709     remove(callback, context = null) {\r
1710         if (!this._callbacks) {\r
1711             return;\r
1712         }\r
1713         var foundCallbackWithDifferentContext = false;\r
1714         for (var i = 0, len = this._callbacks.length; i < len; i++) {\r
1715             if (this._callbacks[i] === callback) {\r
1716                 if (this._contexts[i] === context) {\r
1717                     // callback & context match => remove it\r
1718                     this._callbacks.splice(i, 1);\r
1719                     this._contexts.splice(i, 1);\r
1720                     return;\r
1721                 }\r
1722                 else {\r
1723                     foundCallbackWithDifferentContext = true;\r
1724                 }\r
1725             }\r
1726         }\r
1727         if (foundCallbackWithDifferentContext) {\r
1728             throw new Error('When adding a listener with a context, you should remove it with the same context');\r
1729         }\r
1730     }\r
1731     invoke(...args) {\r
1732         if (!this._callbacks) {\r
1733             return [];\r
1734         }\r
1735         var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);\r
1736         for (var i = 0, len = callbacks.length; i < len; i++) {\r
1737             try {\r
1738                 ret.push(callbacks[i].apply(contexts[i], args));\r
1739             }\r
1740             catch (e) {\r
1741                 // eslint-disable-next-line no-console\r
1742                 console.error(e);\r
1743             }\r
1744         }\r
1745         return ret;\r
1746     }\r
1747     isEmpty() {\r
1748         return !this._callbacks || this._callbacks.length === 0;\r
1749     }\r
1750     dispose() {\r
1751         this._callbacks = undefined;\r
1752         this._contexts = undefined;\r
1753     }\r
1754 }\r
1755 class Emitter {\r
1756     constructor(_options) {\r
1757         this._options = _options;\r
1758     }\r
1759     /**\r
1760      * For the public to allow to subscribe\r
1761      * to events from this Emitter\r
1762      */\r
1763     get event() {\r
1764         if (!this._event) {\r
1765             this._event = (listener, thisArgs, disposables) => {\r
1766                 if (!this._callbacks) {\r
1767                     this._callbacks = new CallbackList();\r
1768                 }\r
1769                 if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {\r
1770                     this._options.onFirstListenerAdd(this);\r
1771                 }\r
1772                 this._callbacks.add(listener, thisArgs);\r
1773                 let result;\r
1774                 result = {\r
1775                     dispose: () => {\r
1776                         this._callbacks.remove(listener, thisArgs);\r
1777                         result.dispose = Emitter._noop;\r
1778                         if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {\r
1779                             this._options.onLastListenerRemove(this);\r
1780                         }\r
1781                     }\r
1782                 };\r
1783                 if (Array.isArray(disposables)) {\r
1784                     disposables.push(result);\r
1785                 }\r
1786                 return result;\r
1787             };\r
1788         }\r
1789         return this._event;\r
1790     }\r
1791     /**\r
1792      * To be kept private to fire an event to\r
1793      * subscribers\r
1794      */\r
1795     fire(event) {\r
1796         if (this._callbacks) {\r
1797             this._callbacks.invoke.call(this._callbacks, event);\r
1798         }\r
1799     }\r
1800     dispose() {\r
1801         if (this._callbacks) {\r
1802             this._callbacks.dispose();\r
1803             this._callbacks = undefined;\r
1804         }\r
1805     }\r
1806 }\r
1807 exports.Emitter = Emitter;\r
1808 Emitter._noop = function () { };\r
1809
1810
1811 /***/ }),
1812 /* 10 */
1813 /***/ (function(module, exports, __webpack_require__) {
1814
1815 "use strict";
1816 /* --------------------------------------------------------------------------------------------\r
1817  * Copyright (c) Microsoft Corporation. All rights reserved.\r
1818  * Licensed under the MIT License. See License.txt in the project root for license information.\r
1819  * ------------------------------------------------------------------------------------------ */\r
1820 \r
1821 Object.defineProperty(exports, "__esModule", { value: true });\r
1822 const events_1 = __webpack_require__(9);\r
1823 const Is = __webpack_require__(6);\r
1824 let ContentLength = 'Content-Length: ';\r
1825 let CRLF = '\r\n';\r
1826 var MessageWriter;\r
1827 (function (MessageWriter) {\r
1828     function is(value) {\r
1829         let candidate = value;\r
1830         return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&\r
1831             Is.func(candidate.onError) && Is.func(candidate.write);\r
1832     }\r
1833     MessageWriter.is = is;\r
1834 })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));\r
1835 class AbstractMessageWriter {\r
1836     constructor() {\r
1837         this.errorEmitter = new events_1.Emitter();\r
1838         this.closeEmitter = new events_1.Emitter();\r
1839     }\r
1840     dispose() {\r
1841         this.errorEmitter.dispose();\r
1842         this.closeEmitter.dispose();\r
1843     }\r
1844     get onError() {\r
1845         return this.errorEmitter.event;\r
1846     }\r
1847     fireError(error, message, count) {\r
1848         this.errorEmitter.fire([this.asError(error), message, count]);\r
1849     }\r
1850     get onClose() {\r
1851         return this.closeEmitter.event;\r
1852     }\r
1853     fireClose() {\r
1854         this.closeEmitter.fire(undefined);\r
1855     }\r
1856     asError(error) {\r
1857         if (error instanceof Error) {\r
1858             return error;\r
1859         }\r
1860         else {\r
1861             return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);\r
1862         }\r
1863     }\r
1864 }\r
1865 exports.AbstractMessageWriter = AbstractMessageWriter;\r
1866 class StreamMessageWriter extends AbstractMessageWriter {\r
1867     constructor(writable, encoding = 'utf8') {\r
1868         super();\r
1869         this.writable = writable;\r
1870         this.encoding = encoding;\r
1871         this.errorCount = 0;\r
1872         this.writable.on('error', (error) => this.fireError(error));\r
1873         this.writable.on('close', () => this.fireClose());\r
1874     }\r
1875     write(msg) {\r
1876         let json = JSON.stringify(msg);\r
1877         let contentLength = Buffer.byteLength(json, this.encoding);\r
1878         let headers = [\r
1879             ContentLength, contentLength.toString(), CRLF,\r
1880             CRLF\r
1881         ];\r
1882         try {\r
1883             // Header must be written in ASCII encoding\r
1884             this.writable.write(headers.join(''), 'ascii');\r
1885             // Now write the content. This can be written in any encoding\r
1886             this.writable.write(json, this.encoding);\r
1887             this.errorCount = 0;\r
1888         }\r
1889         catch (error) {\r
1890             this.errorCount++;\r
1891             this.fireError(error, msg, this.errorCount);\r
1892         }\r
1893     }\r
1894 }\r
1895 exports.StreamMessageWriter = StreamMessageWriter;\r
1896 class IPCMessageWriter extends AbstractMessageWriter {\r
1897     constructor(process) {\r
1898         super();\r
1899         this.process = process;\r
1900         this.errorCount = 0;\r
1901         this.queue = [];\r
1902         this.sending = false;\r
1903         let eventEmitter = this.process;\r
1904         eventEmitter.on('error', (error) => this.fireError(error));\r
1905         eventEmitter.on('close', () => this.fireClose);\r
1906     }\r
1907     write(msg) {\r
1908         if (!this.sending && this.queue.length === 0) {\r
1909             // See https://github.com/nodejs/node/issues/7657\r
1910             this.doWriteMessage(msg);\r
1911         }\r
1912         else {\r
1913             this.queue.push(msg);\r
1914         }\r
1915     }\r
1916     doWriteMessage(msg) {\r
1917         try {\r
1918             if (this.process.send) {\r
1919                 this.sending = true;\r
1920                 this.process.send(msg, undefined, undefined, (error) => {\r
1921                     this.sending = false;\r
1922                     if (error) {\r
1923                         this.errorCount++;\r
1924                         this.fireError(error, msg, this.errorCount);\r
1925                     }\r
1926                     else {\r
1927                         this.errorCount = 0;\r
1928                     }\r
1929                     if (this.queue.length > 0) {\r
1930                         this.doWriteMessage(this.queue.shift());\r
1931                     }\r
1932                 });\r
1933             }\r
1934         }\r
1935         catch (error) {\r
1936             this.errorCount++;\r
1937             this.fireError(error, msg, this.errorCount);\r
1938         }\r
1939     }\r
1940 }\r
1941 exports.IPCMessageWriter = IPCMessageWriter;\r
1942 class SocketMessageWriter extends AbstractMessageWriter {\r
1943     constructor(socket, encoding = 'utf8') {\r
1944         super();\r
1945         this.socket = socket;\r
1946         this.queue = [];\r
1947         this.sending = false;\r
1948         this.encoding = encoding;\r
1949         this.errorCount = 0;\r
1950         this.socket.on('error', (error) => this.fireError(error));\r
1951         this.socket.on('close', () => this.fireClose());\r
1952     }\r
1953     dispose() {\r
1954         super.dispose();\r
1955         this.socket.destroy();\r
1956     }\r
1957     write(msg) {\r
1958         if (!this.sending && this.queue.length === 0) {\r
1959             // See https://github.com/nodejs/node/issues/7657\r
1960             this.doWriteMessage(msg);\r
1961         }\r
1962         else {\r
1963             this.queue.push(msg);\r
1964         }\r
1965     }\r
1966     doWriteMessage(msg) {\r
1967         let json = JSON.stringify(msg);\r
1968         let contentLength = Buffer.byteLength(json, this.encoding);\r
1969         let headers = [\r
1970             ContentLength, contentLength.toString(), CRLF,\r
1971             CRLF\r
1972         ];\r
1973         try {\r
1974             // Header must be written in ASCII encoding\r
1975             this.sending = true;\r
1976             this.socket.write(headers.join(''), 'ascii', (error) => {\r
1977                 if (error) {\r
1978                     this.handleError(error, msg);\r
1979                 }\r
1980                 try {\r
1981                     // Now write the content. This can be written in any encoding\r
1982                     this.socket.write(json, this.encoding, (error) => {\r
1983                         this.sending = false;\r
1984                         if (error) {\r
1985                             this.handleError(error, msg);\r
1986                         }\r
1987                         else {\r
1988                             this.errorCount = 0;\r
1989                         }\r
1990                         if (this.queue.length > 0) {\r
1991                             this.doWriteMessage(this.queue.shift());\r
1992                         }\r
1993                     });\r
1994                 }\r
1995                 catch (error) {\r
1996                     this.handleError(error, msg);\r
1997                 }\r
1998             });\r
1999         }\r
2000         catch (error) {\r
2001             this.handleError(error, msg);\r
2002         }\r
2003     }\r
2004     handleError(error, msg) {\r
2005         this.errorCount++;\r
2006         this.fireError(error, msg, this.errorCount);\r
2007     }\r
2008 }\r
2009 exports.SocketMessageWriter = SocketMessageWriter;\r
2010
2011
2012 /***/ }),
2013 /* 11 */
2014 /***/ (function(module, exports, __webpack_require__) {
2015
2016 "use strict";
2017 /*---------------------------------------------------------------------------------------------\r
2018  *  Copyright (c) Microsoft Corporation. All rights reserved.\r
2019  *  Licensed under the MIT License. See License.txt in the project root for license information.\r
2020  *--------------------------------------------------------------------------------------------*/\r
2021 \r
2022 Object.defineProperty(exports, "__esModule", { value: true });\r
2023 const events_1 = __webpack_require__(9);\r
2024 const Is = __webpack_require__(6);\r
2025 var CancellationToken;\r
2026 (function (CancellationToken) {\r
2027     CancellationToken.None = Object.freeze({\r
2028         isCancellationRequested: false,\r
2029         onCancellationRequested: events_1.Event.None\r
2030     });\r
2031     CancellationToken.Cancelled = Object.freeze({\r
2032         isCancellationRequested: true,\r
2033         onCancellationRequested: events_1.Event.None\r
2034     });\r
2035     function is(value) {\r
2036         let candidate = value;\r
2037         return candidate && (candidate === CancellationToken.None\r
2038             || candidate === CancellationToken.Cancelled\r
2039             || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));\r
2040     }\r
2041     CancellationToken.is = is;\r
2042 })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));\r
2043 const shortcutEvent = Object.freeze(function (callback, context) {\r
2044     let handle = setTimeout(callback.bind(context), 0);\r
2045     return { dispose() { clearTimeout(handle); } };\r
2046 });\r
2047 class MutableToken {\r
2048     constructor() {\r
2049         this._isCancelled = false;\r
2050     }\r
2051     cancel() {\r
2052         if (!this._isCancelled) {\r
2053             this._isCancelled = true;\r
2054             if (this._emitter) {\r
2055                 this._emitter.fire(undefined);\r
2056                 this.dispose();\r
2057             }\r
2058         }\r
2059     }\r
2060     get isCancellationRequested() {\r
2061         return this._isCancelled;\r
2062     }\r
2063     get onCancellationRequested() {\r
2064         if (this._isCancelled) {\r
2065             return shortcutEvent;\r
2066         }\r
2067         if (!this._emitter) {\r
2068             this._emitter = new events_1.Emitter();\r
2069         }\r
2070         return this._emitter.event;\r
2071     }\r
2072     dispose() {\r
2073         if (this._emitter) {\r
2074             this._emitter.dispose();\r
2075             this._emitter = undefined;\r
2076         }\r
2077     }\r
2078 }\r
2079 class CancellationTokenSource {\r
2080     get token() {\r
2081         if (!this._token) {\r
2082             // be lazy and create the token only when\r
2083             // actually needed\r
2084             this._token = new MutableToken();\r
2085         }\r
2086         return this._token;\r
2087     }\r
2088     cancel() {\r
2089         if (!this._token) {\r
2090             // save an object by returning the default\r
2091             // cancelled token when cancellation happens\r
2092             // before someone asks for the token\r
2093             this._token = CancellationToken.Cancelled;\r
2094         }\r
2095         else {\r
2096             this._token.cancel();\r
2097         }\r
2098     }\r
2099     dispose() {\r
2100         if (!this._token) {\r
2101             // ensure to initialize with an empty token if we had none\r
2102             this._token = CancellationToken.None;\r
2103         }\r
2104         else if (this._token instanceof MutableToken) {\r
2105             // actually dispose\r
2106             this._token.dispose();\r
2107         }\r
2108     }\r
2109 }\r
2110 exports.CancellationTokenSource = CancellationTokenSource;\r
2111
2112
2113 /***/ }),
2114 /* 12 */
2115 /***/ (function(module, exports, __webpack_require__) {
2116
2117 "use strict";
2118 \r
2119 /*---------------------------------------------------------------------------------------------\r
2120  *  Copyright (c) Microsoft Corporation. All rights reserved.\r
2121  *  Licensed under the MIT License. See License.txt in the project root for license information.\r
2122  *--------------------------------------------------------------------------------------------*/\r
2123 Object.defineProperty(exports, "__esModule", { value: true });\r
2124 var Touch;\r
2125 (function (Touch) {\r
2126     Touch.None = 0;\r
2127     Touch.First = 1;\r
2128     Touch.Last = 2;\r
2129 })(Touch = exports.Touch || (exports.Touch = {}));\r
2130 class LinkedMap {\r
2131     constructor() {\r
2132         this._map = new Map();\r
2133         this._head = undefined;\r
2134         this._tail = undefined;\r
2135         this._size = 0;\r
2136     }\r
2137     clear() {\r
2138         this._map.clear();\r
2139         this._head = undefined;\r
2140         this._tail = undefined;\r
2141         this._size = 0;\r
2142     }\r
2143     isEmpty() {\r
2144         return !this._head && !this._tail;\r
2145     }\r
2146     get size() {\r
2147         return this._size;\r
2148     }\r
2149     has(key) {\r
2150         return this._map.has(key);\r
2151     }\r
2152     get(key) {\r
2153         const item = this._map.get(key);\r
2154         if (!item) {\r
2155             return undefined;\r
2156         }\r
2157         return item.value;\r
2158     }\r
2159     set(key, value, touch = Touch.None) {\r
2160         let item = this._map.get(key);\r
2161         if (item) {\r
2162             item.value = value;\r
2163             if (touch !== Touch.None) {\r
2164                 this.touch(item, touch);\r
2165             }\r
2166         }\r
2167         else {\r
2168             item = { key, value, next: undefined, previous: undefined };\r
2169             switch (touch) {\r
2170                 case Touch.None:\r
2171                     this.addItemLast(item);\r
2172                     break;\r
2173                 case Touch.First:\r
2174                     this.addItemFirst(item);\r
2175                     break;\r
2176                 case Touch.Last:\r
2177                     this.addItemLast(item);\r
2178                     break;\r
2179                 default:\r
2180                     this.addItemLast(item);\r
2181                     break;\r
2182             }\r
2183             this._map.set(key, item);\r
2184             this._size++;\r
2185         }\r
2186     }\r
2187     delete(key) {\r
2188         const item = this._map.get(key);\r
2189         if (!item) {\r
2190             return false;\r
2191         }\r
2192         this._map.delete(key);\r
2193         this.removeItem(item);\r
2194         this._size--;\r
2195         return true;\r
2196     }\r
2197     shift() {\r
2198         if (!this._head && !this._tail) {\r
2199             return undefined;\r
2200         }\r
2201         if (!this._head || !this._tail) {\r
2202             throw new Error('Invalid list');\r
2203         }\r
2204         const item = this._head;\r
2205         this._map.delete(item.key);\r
2206         this.removeItem(item);\r
2207         this._size--;\r
2208         return item.value;\r
2209     }\r
2210     forEach(callbackfn, thisArg) {\r
2211         let current = this._head;\r
2212         while (current) {\r
2213             if (thisArg) {\r
2214                 callbackfn.bind(thisArg)(current.value, current.key, this);\r
2215             }\r
2216             else {\r
2217                 callbackfn(current.value, current.key, this);\r
2218             }\r
2219             current = current.next;\r
2220         }\r
2221     }\r
2222     forEachReverse(callbackfn, thisArg) {\r
2223         let current = this._tail;\r
2224         while (current) {\r
2225             if (thisArg) {\r
2226                 callbackfn.bind(thisArg)(current.value, current.key, this);\r
2227             }\r
2228             else {\r
2229                 callbackfn(current.value, current.key, this);\r
2230             }\r
2231             current = current.previous;\r
2232         }\r
2233     }\r
2234     values() {\r
2235         let result = [];\r
2236         let current = this._head;\r
2237         while (current) {\r
2238             result.push(current.value);\r
2239             current = current.next;\r
2240         }\r
2241         return result;\r
2242     }\r
2243     keys() {\r
2244         let result = [];\r
2245         let current = this._head;\r
2246         while (current) {\r
2247             result.push(current.key);\r
2248             current = current.next;\r
2249         }\r
2250         return result;\r
2251     }\r
2252     /* JSON RPC run on es5 which has no Symbol.iterator\r
2253     public keys(): IterableIterator<K> {\r
2254         let current = this._head;\r
2255         let iterator: IterableIterator<K> = {\r
2256             [Symbol.iterator]() {\r
2257                 return iterator;\r
2258             },\r
2259             next():IteratorResult<K> {\r
2260                 if (current) {\r
2261                     let result = { value: current.key, done: false };\r
2262                     current = current.next;\r
2263                     return result;\r
2264                 } else {\r
2265                     return { value: undefined, done: true };\r
2266                 }\r
2267             }\r
2268         };\r
2269         return iterator;\r
2270     }\r
2271 \r
2272     public values(): IterableIterator<V> {\r
2273         let current = this._head;\r
2274         let iterator: IterableIterator<V> = {\r
2275             [Symbol.iterator]() {\r
2276                 return iterator;\r
2277             },\r
2278             next():IteratorResult<V> {\r
2279                 if (current) {\r
2280                     let result = { value: current.value, done: false };\r
2281                     current = current.next;\r
2282                     return result;\r
2283                 } else {\r
2284                     return { value: undefined, done: true };\r
2285                 }\r
2286             }\r
2287         };\r
2288         return iterator;\r
2289     }\r
2290     */\r
2291     addItemFirst(item) {\r
2292         // First time Insert\r
2293         if (!this._head && !this._tail) {\r
2294             this._tail = item;\r
2295         }\r
2296         else if (!this._head) {\r
2297             throw new Error('Invalid list');\r
2298         }\r
2299         else {\r
2300             item.next = this._head;\r
2301             this._head.previous = item;\r
2302         }\r
2303         this._head = item;\r
2304     }\r
2305     addItemLast(item) {\r
2306         // First time Insert\r
2307         if (!this._head && !this._tail) {\r
2308             this._head = item;\r
2309         }\r
2310         else if (!this._tail) {\r
2311             throw new Error('Invalid list');\r
2312         }\r
2313         else {\r
2314             item.previous = this._tail;\r
2315             this._tail.next = item;\r
2316         }\r
2317         this._tail = item;\r
2318     }\r
2319     removeItem(item) {\r
2320         if (item === this._head && item === this._tail) {\r
2321             this._head = undefined;\r
2322             this._tail = undefined;\r
2323         }\r
2324         else if (item === this._head) {\r
2325             this._head = item.next;\r
2326         }\r
2327         else if (item === this._tail) {\r
2328             this._tail = item.previous;\r
2329         }\r
2330         else {\r
2331             const next = item.next;\r
2332             const previous = item.previous;\r
2333             if (!next || !previous) {\r
2334                 throw new Error('Invalid list');\r
2335             }\r
2336             next.previous = previous;\r
2337             previous.next = next;\r
2338         }\r
2339     }\r
2340     touch(item, touch) {\r
2341         if (!this._head || !this._tail) {\r
2342             throw new Error('Invalid list');\r
2343         }\r
2344         if ((touch !== Touch.First && touch !== Touch.Last)) {\r
2345             return;\r
2346         }\r
2347         if (touch === Touch.First) {\r
2348             if (item === this._head) {\r
2349                 return;\r
2350             }\r
2351             const next = item.next;\r
2352             const previous = item.previous;\r
2353             // Unlink the item\r
2354             if (item === this._tail) {\r
2355                 // previous must be defined since item was not head but is tail\r
2356                 // So there are more than on item in the map\r
2357                 previous.next = undefined;\r
2358                 this._tail = previous;\r
2359             }\r
2360             else {\r
2361                 // Both next and previous are not undefined since item was neither head nor tail.\r
2362                 next.previous = previous;\r
2363                 previous.next = next;\r
2364             }\r
2365             // Insert the node at head\r
2366             item.previous = undefined;\r
2367             item.next = this._head;\r
2368             this._head.previous = item;\r
2369             this._head = item;\r
2370         }\r
2371         else if (touch === Touch.Last) {\r
2372             if (item === this._tail) {\r
2373                 return;\r
2374             }\r
2375             const next = item.next;\r
2376             const previous = item.previous;\r
2377             // Unlink the item.\r
2378             if (item === this._head) {\r
2379                 // next must be defined since item was not tail but is head\r
2380                 // So there are more than on item in the map\r
2381                 next.previous = undefined;\r
2382                 this._head = next;\r
2383             }\r
2384             else {\r
2385                 // Both next and previous are not undefined since item was neither head nor tail.\r
2386                 next.previous = previous;\r
2387                 previous.next = next;\r
2388             }\r
2389             item.next = undefined;\r
2390             item.previous = this._tail;\r
2391             this._tail.next = item;\r
2392             this._tail = item;\r
2393         }\r
2394     }\r
2395 }\r
2396 exports.LinkedMap = LinkedMap;\r
2397
2398
2399 /***/ }),
2400 /* 13 */
2401 /***/ (function(module, exports, __webpack_require__) {
2402
2403 "use strict";
2404 /* --------------------------------------------------------------------------------------------\r
2405  * Copyright (c) Microsoft Corporation. All rights reserved.\r
2406  * Licensed under the MIT License. See License.txt in the project root for license information.\r
2407  * ------------------------------------------------------------------------------------------ */\r
2408 \r
2409 Object.defineProperty(exports, "__esModule", { value: true });\r
2410 const path_1 = __webpack_require__(3);\r
2411 const os_1 = __webpack_require__(14);\r
2412 const crypto_1 = __webpack_require__(15);\r
2413 const net_1 = __webpack_require__(16);\r
2414 const messageReader_1 = __webpack_require__(8);\r
2415 const messageWriter_1 = __webpack_require__(10);\r
2416 function generateRandomPipeName() {\r
2417     const randomSuffix = crypto_1.randomBytes(21).toString('hex');\r
2418     if (process.platform === 'win32') {\r
2419         return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;\r
2420     }\r
2421     else {\r
2422         // Mac/Unix: use socket file\r
2423         return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);\r
2424     }\r
2425 }\r
2426 exports.generateRandomPipeName = generateRandomPipeName;\r
2427 function createClientPipeTransport(pipeName, encoding = 'utf-8') {\r
2428     let connectResolve;\r
2429     let connected = new Promise((resolve, _reject) => {\r
2430         connectResolve = resolve;\r
2431     });\r
2432     return new Promise((resolve, reject) => {\r
2433         let server = net_1.createServer((socket) => {\r
2434             server.close();\r
2435             connectResolve([\r
2436                 new messageReader_1.SocketMessageReader(socket, encoding),\r
2437                 new messageWriter_1.SocketMessageWriter(socket, encoding)\r
2438             ]);\r
2439         });\r
2440         server.on('error', reject);\r
2441         server.listen(pipeName, () => {\r
2442             server.removeListener('error', reject);\r
2443             resolve({\r
2444                 onConnected: () => { return connected; }\r
2445             });\r
2446         });\r
2447     });\r
2448 }\r
2449 exports.createClientPipeTransport = createClientPipeTransport;\r
2450 function createServerPipeTransport(pipeName, encoding = 'utf-8') {\r
2451     const socket = net_1.createConnection(pipeName);\r
2452     return [\r
2453         new messageReader_1.SocketMessageReader(socket, encoding),\r
2454         new messageWriter_1.SocketMessageWriter(socket, encoding)\r
2455     ];\r
2456 }\r
2457 exports.createServerPipeTransport = createServerPipeTransport;\r
2458
2459
2460 /***/ }),
2461 /* 14 */
2462 /***/ (function(module, exports) {
2463
2464 module.exports = require("os");
2465
2466 /***/ }),
2467 /* 15 */
2468 /***/ (function(module, exports) {
2469
2470 module.exports = require("crypto");
2471
2472 /***/ }),
2473 /* 16 */
2474 /***/ (function(module, exports) {
2475
2476 module.exports = require("net");
2477
2478 /***/ }),
2479 /* 17 */
2480 /***/ (function(module, exports, __webpack_require__) {
2481
2482 "use strict";
2483 /* --------------------------------------------------------------------------------------------\r
2484  * Copyright (c) Microsoft Corporation. All rights reserved.\r
2485  * Licensed under the MIT License. See License.txt in the project root for license information.\r
2486  * ------------------------------------------------------------------------------------------ */\r
2487 \r
2488 Object.defineProperty(exports, "__esModule", { value: true });\r
2489 const net_1 = __webpack_require__(16);\r
2490 const messageReader_1 = __webpack_require__(8);\r
2491 const messageWriter_1 = __webpack_require__(10);\r
2492 function createClientSocketTransport(port, encoding = 'utf-8') {\r
2493     let connectResolve;\r
2494     let connected = new Promise((resolve, _reject) => {\r
2495         connectResolve = resolve;\r
2496     });\r
2497     return new Promise((resolve, reject) => {\r
2498         let server = net_1.createServer((socket) => {\r
2499             server.close();\r
2500             connectResolve([\r
2501                 new messageReader_1.SocketMessageReader(socket, encoding),\r
2502                 new messageWriter_1.SocketMessageWriter(socket, encoding)\r
2503             ]);\r
2504         });\r
2505         server.on('error', reject);\r
2506         server.listen(port, '127.0.0.1', () => {\r
2507             server.removeListener('error', reject);\r
2508             resolve({\r
2509                 onConnected: () => { return connected; }\r
2510             });\r
2511         });\r
2512     });\r
2513 }\r
2514 exports.createClientSocketTransport = createClientSocketTransport;\r
2515 function createServerSocketTransport(port, encoding = 'utf-8') {\r
2516     const socket = net_1.createConnection(port, '127.0.0.1');\r
2517     return [\r
2518         new messageReader_1.SocketMessageReader(socket, encoding),\r
2519         new messageWriter_1.SocketMessageWriter(socket, encoding)\r
2520     ];\r
2521 }\r
2522 exports.createServerSocketTransport = createServerSocketTransport;\r
2523
2524
2525 /***/ }),
2526 /* 18 */
2527 /***/ (function(module, __webpack_exports__, __webpack_require__) {
2528
2529 "use strict";
2530 __webpack_require__.r(__webpack_exports__);
2531 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
2532 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
2533 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
2534 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
2535 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
2536 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
2537 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
2538 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
2539 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
2540 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
2541 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
2542 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
2543 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
2544 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
2545 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
2546 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
2547 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
2548 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
2549 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
2550 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
2551 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
2552 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
2553 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
2554 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
2555 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
2556 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
2557 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
2558 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
2559 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemTag", function() { return CompletionItemTag; });
2560 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
2561 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
2562 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
2563 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
2564 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
2565 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
2566 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
2567 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
2568 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
2569 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolTag", function() { return SymbolTag; });
2570 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
2571 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
2572 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
2573 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
2574 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
2575 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
2576 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
2577 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
2578 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
2579 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
2580 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
2581 /* --------------------------------------------------------------------------------------------\r
2582  * Copyright (c) Microsoft Corporation. All rights reserved.\r
2583  * Licensed under the MIT License. See License.txt in the project root for license information.\r
2584  * ------------------------------------------------------------------------------------------ */\r
2585 \r
2586 /**\r
2587  * The Position namespace provides helper functions to work with\r
2588  * [Position](#Position) literals.\r
2589  */\r
2590 var Position;\r
2591 (function (Position) {\r
2592     /**\r
2593      * Creates a new Position literal from the given line and character.\r
2594      * @param line The position's line.\r
2595      * @param character The position's character.\r
2596      */\r
2597     function create(line, character) {\r
2598         return { line: line, character: character };\r
2599     }\r
2600     Position.create = create;\r
2601     /**\r
2602      * Checks whether the given liternal conforms to the [Position](#Position) interface.\r
2603      */\r
2604     function is(value) {\r
2605         var candidate = value;\r
2606         return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);\r
2607     }\r
2608     Position.is = is;\r
2609 })(Position || (Position = {}));\r
2610 /**\r
2611  * The Range namespace provides helper functions to work with\r
2612  * [Range](#Range) literals.\r
2613  */\r
2614 var Range;\r
2615 (function (Range) {\r
2616     function create(one, two, three, four) {\r
2617         if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {\r
2618             return { start: Position.create(one, two), end: Position.create(three, four) };\r
2619         }\r
2620         else if (Position.is(one) && Position.is(two)) {\r
2621             return { start: one, end: two };\r
2622         }\r
2623         else {\r
2624             throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");\r
2625         }\r
2626     }\r
2627     Range.create = create;\r
2628     /**\r
2629      * Checks whether the given literal conforms to the [Range](#Range) interface.\r
2630      */\r
2631     function is(value) {\r
2632         var candidate = value;\r
2633         return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);\r
2634     }\r
2635     Range.is = is;\r
2636 })(Range || (Range = {}));\r
2637 /**\r
2638  * The Location namespace provides helper functions to work with\r
2639  * [Location](#Location) literals.\r
2640  */\r
2641 var Location;\r
2642 (function (Location) {\r
2643     /**\r
2644      * Creates a Location literal.\r
2645      * @param uri The location's uri.\r
2646      * @param range The location's range.\r
2647      */\r
2648     function create(uri, range) {\r
2649         return { uri: uri, range: range };\r
2650     }\r
2651     Location.create = create;\r
2652     /**\r
2653      * Checks whether the given literal conforms to the [Location](#Location) interface.\r
2654      */\r
2655     function is(value) {\r
2656         var candidate = value;\r
2657         return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));\r
2658     }\r
2659     Location.is = is;\r
2660 })(Location || (Location = {}));\r
2661 /**\r
2662  * The LocationLink namespace provides helper functions to work with\r
2663  * [LocationLink](#LocationLink) literals.\r
2664  */\r
2665 var LocationLink;\r
2666 (function (LocationLink) {\r
2667     /**\r
2668      * Creates a LocationLink literal.\r
2669      * @param targetUri The definition's uri.\r
2670      * @param targetRange The full range of the definition.\r
2671      * @param targetSelectionRange The span of the symbol definition at the target.\r
2672      * @param originSelectionRange The span of the symbol being defined in the originating source file.\r
2673      */\r
2674     function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {\r
2675         return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };\r
2676     }\r
2677     LocationLink.create = create;\r
2678     /**\r
2679      * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.\r
2680      */\r
2681     function is(value) {\r
2682         var candidate = value;\r
2683         return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)\r
2684             && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))\r
2685             && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));\r
2686     }\r
2687     LocationLink.is = is;\r
2688 })(LocationLink || (LocationLink = {}));\r
2689 /**\r
2690  * The Color namespace provides helper functions to work with\r
2691  * [Color](#Color) literals.\r
2692  */\r
2693 var Color;\r
2694 (function (Color) {\r
2695     /**\r
2696      * Creates a new Color literal.\r
2697      */\r
2698     function create(red, green, blue, alpha) {\r
2699         return {\r
2700             red: red,\r
2701             green: green,\r
2702             blue: blue,\r
2703             alpha: alpha,\r
2704         };\r
2705     }\r
2706     Color.create = create;\r
2707     /**\r
2708      * Checks whether the given literal conforms to the [Color](#Color) interface.\r
2709      */\r
2710     function is(value) {\r
2711         var candidate = value;\r
2712         return Is.number(candidate.red)\r
2713             && Is.number(candidate.green)\r
2714             && Is.number(candidate.blue)\r
2715             && Is.number(candidate.alpha);\r
2716     }\r
2717     Color.is = is;\r
2718 })(Color || (Color = {}));\r
2719 /**\r
2720  * The ColorInformation namespace provides helper functions to work with\r
2721  * [ColorInformation](#ColorInformation) literals.\r
2722  */\r
2723 var ColorInformation;\r
2724 (function (ColorInformation) {\r
2725     /**\r
2726      * Creates a new ColorInformation literal.\r
2727      */\r
2728     function create(range, color) {\r
2729         return {\r
2730             range: range,\r
2731             color: color,\r
2732         };\r
2733     }\r
2734     ColorInformation.create = create;\r
2735     /**\r
2736      * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.\r
2737      */\r
2738     function is(value) {\r
2739         var candidate = value;\r
2740         return Range.is(candidate.range) && Color.is(candidate.color);\r
2741     }\r
2742     ColorInformation.is = is;\r
2743 })(ColorInformation || (ColorInformation = {}));\r
2744 /**\r
2745  * The Color namespace provides helper functions to work with\r
2746  * [ColorPresentation](#ColorPresentation) literals.\r
2747  */\r
2748 var ColorPresentation;\r
2749 (function (ColorPresentation) {\r
2750     /**\r
2751      * Creates a new ColorInformation literal.\r
2752      */\r
2753     function create(label, textEdit, additionalTextEdits) {\r
2754         return {\r
2755             label: label,\r
2756             textEdit: textEdit,\r
2757             additionalTextEdits: additionalTextEdits,\r
2758         };\r
2759     }\r
2760     ColorPresentation.create = create;\r
2761     /**\r
2762      * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.\r
2763      */\r
2764     function is(value) {\r
2765         var candidate = value;\r
2766         return Is.string(candidate.label)\r
2767             && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))\r
2768             && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));\r
2769     }\r
2770     ColorPresentation.is = is;\r
2771 })(ColorPresentation || (ColorPresentation = {}));\r
2772 /**\r
2773  * Enum of known range kinds\r
2774  */\r
2775 var FoldingRangeKind;\r
2776 (function (FoldingRangeKind) {\r
2777     /**\r
2778      * Folding range for a comment\r
2779      */\r
2780     FoldingRangeKind["Comment"] = "comment";\r
2781     /**\r
2782      * Folding range for a imports or includes\r
2783      */\r
2784     FoldingRangeKind["Imports"] = "imports";\r
2785     /**\r
2786      * Folding range for a region (e.g. `#region`)\r
2787      */\r
2788     FoldingRangeKind["Region"] = "region";\r
2789 })(FoldingRangeKind || (FoldingRangeKind = {}));\r
2790 /**\r
2791  * The folding range namespace provides helper functions to work with\r
2792  * [FoldingRange](#FoldingRange) literals.\r
2793  */\r
2794 var FoldingRange;\r
2795 (function (FoldingRange) {\r
2796     /**\r
2797      * Creates a new FoldingRange literal.\r
2798      */\r
2799     function create(startLine, endLine, startCharacter, endCharacter, kind) {\r
2800         var result = {\r
2801             startLine: startLine,\r
2802             endLine: endLine\r
2803         };\r
2804         if (Is.defined(startCharacter)) {\r
2805             result.startCharacter = startCharacter;\r
2806         }\r
2807         if (Is.defined(endCharacter)) {\r
2808             result.endCharacter = endCharacter;\r
2809         }\r
2810         if (Is.defined(kind)) {\r
2811             result.kind = kind;\r
2812         }\r
2813         return result;\r
2814     }\r
2815     FoldingRange.create = create;\r
2816     /**\r
2817      * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.\r
2818      */\r
2819     function is(value) {\r
2820         var candidate = value;\r
2821         return Is.number(candidate.startLine) && Is.number(candidate.startLine)\r
2822             && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))\r
2823             && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))\r
2824             && (Is.undefined(candidate.kind) || Is.string(candidate.kind));\r
2825     }\r
2826     FoldingRange.is = is;\r
2827 })(FoldingRange || (FoldingRange = {}));\r
2828 /**\r
2829  * The DiagnosticRelatedInformation namespace provides helper functions to work with\r
2830  * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.\r
2831  */\r
2832 var DiagnosticRelatedInformation;\r
2833 (function (DiagnosticRelatedInformation) {\r
2834     /**\r
2835      * Creates a new DiagnosticRelatedInformation literal.\r
2836      */\r
2837     function create(location, message) {\r
2838         return {\r
2839             location: location,\r
2840             message: message\r
2841         };\r
2842     }\r
2843     DiagnosticRelatedInformation.create = create;\r
2844     /**\r
2845      * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.\r
2846      */\r
2847     function is(value) {\r
2848         var candidate = value;\r
2849         return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);\r
2850     }\r
2851     DiagnosticRelatedInformation.is = is;\r
2852 })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));\r
2853 /**\r
2854  * The diagnostic's severity.\r
2855  */\r
2856 var DiagnosticSeverity;\r
2857 (function (DiagnosticSeverity) {\r
2858     /**\r
2859      * Reports an error.\r
2860      */\r
2861     DiagnosticSeverity.Error = 1;\r
2862     /**\r
2863      * Reports a warning.\r
2864      */\r
2865     DiagnosticSeverity.Warning = 2;\r
2866     /**\r
2867      * Reports an information.\r
2868      */\r
2869     DiagnosticSeverity.Information = 3;\r
2870     /**\r
2871      * Reports a hint.\r
2872      */\r
2873     DiagnosticSeverity.Hint = 4;\r
2874 })(DiagnosticSeverity || (DiagnosticSeverity = {}));\r
2875 /**\r
2876  * The diagnostic tags.\r
2877  *\r
2878  * @since 3.15.0\r
2879  */\r
2880 var DiagnosticTag;\r
2881 (function (DiagnosticTag) {\r
2882     /**\r
2883      * Unused or unnecessary code.\r
2884      *\r
2885      * Clients are allowed to render diagnostics with this tag faded out instead of having\r
2886      * an error squiggle.\r
2887      */\r
2888     DiagnosticTag.Unnecessary = 1;\r
2889     /**\r
2890      * Deprecated or obsolete code.\r
2891      *\r
2892      * Clients are allowed to rendered diagnostics with this tag strike through.\r
2893      */\r
2894     DiagnosticTag.Deprecated = 2;\r
2895 })(DiagnosticTag || (DiagnosticTag = {}));\r
2896 /**\r
2897  * The Diagnostic namespace provides helper functions to work with\r
2898  * [Diagnostic](#Diagnostic) literals.\r
2899  */\r
2900 var Diagnostic;\r
2901 (function (Diagnostic) {\r
2902     /**\r
2903      * Creates a new Diagnostic literal.\r
2904      */\r
2905     function create(range, message, severity, code, source, relatedInformation) {\r
2906         var result = { range: range, message: message };\r
2907         if (Is.defined(severity)) {\r
2908             result.severity = severity;\r
2909         }\r
2910         if (Is.defined(code)) {\r
2911             result.code = code;\r
2912         }\r
2913         if (Is.defined(source)) {\r
2914             result.source = source;\r
2915         }\r
2916         if (Is.defined(relatedInformation)) {\r
2917             result.relatedInformation = relatedInformation;\r
2918         }\r
2919         return result;\r
2920     }\r
2921     Diagnostic.create = create;\r
2922     /**\r
2923      * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.\r
2924      */\r
2925     function is(value) {\r
2926         var candidate = value;\r
2927         return Is.defined(candidate)\r
2928             && Range.is(candidate.range)\r
2929             && Is.string(candidate.message)\r
2930             && (Is.number(candidate.severity) || Is.undefined(candidate.severity))\r
2931             && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))\r
2932             && (Is.string(candidate.source) || Is.undefined(candidate.source))\r
2933             && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));\r
2934     }\r
2935     Diagnostic.is = is;\r
2936 })(Diagnostic || (Diagnostic = {}));\r
2937 /**\r
2938  * The Command namespace provides helper functions to work with\r
2939  * [Command](#Command) literals.\r
2940  */\r
2941 var Command;\r
2942 (function (Command) {\r
2943     /**\r
2944      * Creates a new Command literal.\r
2945      */\r
2946     function create(title, command) {\r
2947         var args = [];\r
2948         for (var _i = 2; _i < arguments.length; _i++) {\r
2949             args[_i - 2] = arguments[_i];\r
2950         }\r
2951         var result = { title: title, command: command };\r
2952         if (Is.defined(args) && args.length > 0) {\r
2953             result.arguments = args;\r
2954         }\r
2955         return result;\r
2956     }\r
2957     Command.create = create;\r
2958     /**\r
2959      * Checks whether the given literal conforms to the [Command](#Command) interface.\r
2960      */\r
2961     function is(value) {\r
2962         var candidate = value;\r
2963         return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);\r
2964     }\r
2965     Command.is = is;\r
2966 })(Command || (Command = {}));\r
2967 /**\r
2968  * The TextEdit namespace provides helper function to create replace,\r
2969  * insert and delete edits more easily.\r
2970  */\r
2971 var TextEdit;\r
2972 (function (TextEdit) {\r
2973     /**\r
2974      * Creates a replace text edit.\r
2975      * @param range The range of text to be replaced.\r
2976      * @param newText The new text.\r
2977      */\r
2978     function replace(range, newText) {\r
2979         return { range: range, newText: newText };\r
2980     }\r
2981     TextEdit.replace = replace;\r
2982     /**\r
2983      * Creates a insert text edit.\r
2984      * @param position The position to insert the text at.\r
2985      * @param newText The text to be inserted.\r
2986      */\r
2987     function insert(position, newText) {\r
2988         return { range: { start: position, end: position }, newText: newText };\r
2989     }\r
2990     TextEdit.insert = insert;\r
2991     /**\r
2992      * Creates a delete text edit.\r
2993      * @param range The range of text to be deleted.\r
2994      */\r
2995     function del(range) {\r
2996         return { range: range, newText: '' };\r
2997     }\r
2998     TextEdit.del = del;\r
2999     function is(value) {\r
3000         var candidate = value;\r
3001         return Is.objectLiteral(candidate)\r
3002             && Is.string(candidate.newText)\r
3003             && Range.is(candidate.range);\r
3004     }\r
3005     TextEdit.is = is;\r
3006 })(TextEdit || (TextEdit = {}));\r
3007 /**\r
3008  * The TextDocumentEdit namespace provides helper function to create\r
3009  * an edit that manipulates a text document.\r
3010  */\r
3011 var TextDocumentEdit;\r
3012 (function (TextDocumentEdit) {\r
3013     /**\r
3014      * Creates a new `TextDocumentEdit`\r
3015      */\r
3016     function create(textDocument, edits) {\r
3017         return { textDocument: textDocument, edits: edits };\r
3018     }\r
3019     TextDocumentEdit.create = create;\r
3020     function is(value) {\r
3021         var candidate = value;\r
3022         return Is.defined(candidate)\r
3023             && VersionedTextDocumentIdentifier.is(candidate.textDocument)\r
3024             && Array.isArray(candidate.edits);\r
3025     }\r
3026     TextDocumentEdit.is = is;\r
3027 })(TextDocumentEdit || (TextDocumentEdit = {}));\r
3028 var CreateFile;\r
3029 (function (CreateFile) {\r
3030     function create(uri, options) {\r
3031         var result = {\r
3032             kind: 'create',\r
3033             uri: uri\r
3034         };\r
3035         if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {\r
3036             result.options = options;\r
3037         }\r
3038         return result;\r
3039     }\r
3040     CreateFile.create = create;\r
3041     function is(value) {\r
3042         var candidate = value;\r
3043         return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&\r
3044             (candidate.options === void 0 ||\r
3045                 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));\r
3046     }\r
3047     CreateFile.is = is;\r
3048 })(CreateFile || (CreateFile = {}));\r
3049 var RenameFile;\r
3050 (function (RenameFile) {\r
3051     function create(oldUri, newUri, options) {\r
3052         var result = {\r
3053             kind: 'rename',\r
3054             oldUri: oldUri,\r
3055             newUri: newUri\r
3056         };\r
3057         if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {\r
3058             result.options = options;\r
3059         }\r
3060         return result;\r
3061     }\r
3062     RenameFile.create = create;\r
3063     function is(value) {\r
3064         var candidate = value;\r
3065         return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&\r
3066             (candidate.options === void 0 ||\r
3067                 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));\r
3068     }\r
3069     RenameFile.is = is;\r
3070 })(RenameFile || (RenameFile = {}));\r
3071 var DeleteFile;\r
3072 (function (DeleteFile) {\r
3073     function create(uri, options) {\r
3074         var result = {\r
3075             kind: 'delete',\r
3076             uri: uri\r
3077         };\r
3078         if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {\r
3079             result.options = options;\r
3080         }\r
3081         return result;\r
3082     }\r
3083     DeleteFile.create = create;\r
3084     function is(value) {\r
3085         var candidate = value;\r
3086         return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&\r
3087             (candidate.options === void 0 ||\r
3088                 ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));\r
3089     }\r
3090     DeleteFile.is = is;\r
3091 })(DeleteFile || (DeleteFile = {}));\r
3092 var WorkspaceEdit;\r
3093 (function (WorkspaceEdit) {\r
3094     function is(value) {\r
3095         var candidate = value;\r
3096         return candidate &&\r
3097             (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&\r
3098             (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {\r
3099                 if (Is.string(change.kind)) {\r
3100                     return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);\r
3101                 }\r
3102                 else {\r
3103                     return TextDocumentEdit.is(change);\r
3104                 }\r
3105             }));\r
3106     }\r
3107     WorkspaceEdit.is = is;\r
3108 })(WorkspaceEdit || (WorkspaceEdit = {}));\r
3109 var TextEditChangeImpl = /** @class */ (function () {\r
3110     function TextEditChangeImpl(edits) {\r
3111         this.edits = edits;\r
3112     }\r
3113     TextEditChangeImpl.prototype.insert = function (position, newText) {\r
3114         this.edits.push(TextEdit.insert(position, newText));\r
3115     };\r
3116     TextEditChangeImpl.prototype.replace = function (range, newText) {\r
3117         this.edits.push(TextEdit.replace(range, newText));\r
3118     };\r
3119     TextEditChangeImpl.prototype.delete = function (range) {\r
3120         this.edits.push(TextEdit.del(range));\r
3121     };\r
3122     TextEditChangeImpl.prototype.add = function (edit) {\r
3123         this.edits.push(edit);\r
3124     };\r
3125     TextEditChangeImpl.prototype.all = function () {\r
3126         return this.edits;\r
3127     };\r
3128     TextEditChangeImpl.prototype.clear = function () {\r
3129         this.edits.splice(0, this.edits.length);\r
3130     };\r
3131     return TextEditChangeImpl;\r
3132 }());\r
3133 /**\r
3134  * A workspace change helps constructing changes to a workspace.\r
3135  */\r
3136 var WorkspaceChange = /** @class */ (function () {\r
3137     function WorkspaceChange(workspaceEdit) {\r
3138         var _this = this;\r
3139         this._textEditChanges = Object.create(null);\r
3140         if (workspaceEdit) {\r
3141             this._workspaceEdit = workspaceEdit;\r
3142             if (workspaceEdit.documentChanges) {\r
3143                 workspaceEdit.documentChanges.forEach(function (change) {\r
3144                     if (TextDocumentEdit.is(change)) {\r
3145                         var textEditChange = new TextEditChangeImpl(change.edits);\r
3146                         _this._textEditChanges[change.textDocument.uri] = textEditChange;\r
3147                     }\r
3148                 });\r
3149             }\r
3150             else if (workspaceEdit.changes) {\r
3151                 Object.keys(workspaceEdit.changes).forEach(function (key) {\r
3152                     var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);\r
3153                     _this._textEditChanges[key] = textEditChange;\r
3154                 });\r
3155             }\r
3156         }\r
3157     }\r
3158     Object.defineProperty(WorkspaceChange.prototype, "edit", {\r
3159         /**\r
3160          * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal\r
3161          * use to be returned from a workspace edit operation like rename.\r
3162          */\r
3163         get: function () {\r
3164             return this._workspaceEdit;\r
3165         },\r
3166         enumerable: true,\r
3167         configurable: true\r
3168     });\r
3169     WorkspaceChange.prototype.getTextEditChange = function (key) {\r
3170         if (VersionedTextDocumentIdentifier.is(key)) {\r
3171             if (!this._workspaceEdit) {\r
3172                 this._workspaceEdit = {\r
3173                     documentChanges: []\r
3174                 };\r
3175             }\r
3176             if (!this._workspaceEdit.documentChanges) {\r
3177                 throw new Error('Workspace edit is not configured for document changes.');\r
3178             }\r
3179             var textDocument = key;\r
3180             var result = this._textEditChanges[textDocument.uri];\r
3181             if (!result) {\r
3182                 var edits = [];\r
3183                 var textDocumentEdit = {\r
3184                     textDocument: textDocument,\r
3185                     edits: edits\r
3186                 };\r
3187                 this._workspaceEdit.documentChanges.push(textDocumentEdit);\r
3188                 result = new TextEditChangeImpl(edits);\r
3189                 this._textEditChanges[textDocument.uri] = result;\r
3190             }\r
3191             return result;\r
3192         }\r
3193         else {\r
3194             if (!this._workspaceEdit) {\r
3195                 this._workspaceEdit = {\r
3196                     changes: Object.create(null)\r
3197                 };\r
3198             }\r
3199             if (!this._workspaceEdit.changes) {\r
3200                 throw new Error('Workspace edit is not configured for normal text edit changes.');\r
3201             }\r
3202             var result = this._textEditChanges[key];\r
3203             if (!result) {\r
3204                 var edits = [];\r
3205                 this._workspaceEdit.changes[key] = edits;\r
3206                 result = new TextEditChangeImpl(edits);\r
3207                 this._textEditChanges[key] = result;\r
3208             }\r
3209             return result;\r
3210         }\r
3211     };\r
3212     WorkspaceChange.prototype.createFile = function (uri, options) {\r
3213         this.checkDocumentChanges();\r
3214         this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));\r
3215     };\r
3216     WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {\r
3217         this.checkDocumentChanges();\r
3218         this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));\r
3219     };\r
3220     WorkspaceChange.prototype.deleteFile = function (uri, options) {\r
3221         this.checkDocumentChanges();\r
3222         this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));\r
3223     };\r
3224     WorkspaceChange.prototype.checkDocumentChanges = function () {\r
3225         if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {\r
3226             throw new Error('Workspace edit is not configured for document changes.');\r
3227         }\r
3228     };\r
3229     return WorkspaceChange;\r
3230 }());\r
3231 \r
3232 /**\r
3233  * The TextDocumentIdentifier namespace provides helper functions to work with\r
3234  * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.\r
3235  */\r
3236 var TextDocumentIdentifier;\r
3237 (function (TextDocumentIdentifier) {\r
3238     /**\r
3239      * Creates a new TextDocumentIdentifier literal.\r
3240      * @param uri The document's uri.\r
3241      */\r
3242     function create(uri) {\r
3243         return { uri: uri };\r
3244     }\r
3245     TextDocumentIdentifier.create = create;\r
3246     /**\r
3247      * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.\r
3248      */\r
3249     function is(value) {\r
3250         var candidate = value;\r
3251         return Is.defined(candidate) && Is.string(candidate.uri);\r
3252     }\r
3253     TextDocumentIdentifier.is = is;\r
3254 })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));\r
3255 /**\r
3256  * The VersionedTextDocumentIdentifier namespace provides helper functions to work with\r
3257  * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.\r
3258  */\r
3259 var VersionedTextDocumentIdentifier;\r
3260 (function (VersionedTextDocumentIdentifier) {\r
3261     /**\r
3262      * Creates a new VersionedTextDocumentIdentifier literal.\r
3263      * @param uri The document's uri.\r
3264      * @param uri The document's text.\r
3265      */\r
3266     function create(uri, version) {\r
3267         return { uri: uri, version: version };\r
3268     }\r
3269     VersionedTextDocumentIdentifier.create = create;\r
3270     /**\r
3271      * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.\r
3272      */\r
3273     function is(value) {\r
3274         var candidate = value;\r
3275         return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));\r
3276     }\r
3277     VersionedTextDocumentIdentifier.is = is;\r
3278 })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));\r
3279 /**\r
3280  * The TextDocumentItem namespace provides helper functions to work with\r
3281  * [TextDocumentItem](#TextDocumentItem) literals.\r
3282  */\r
3283 var TextDocumentItem;\r
3284 (function (TextDocumentItem) {\r
3285     /**\r
3286      * Creates a new TextDocumentItem literal.\r
3287      * @param uri The document's uri.\r
3288      * @param languageId The document's language identifier.\r
3289      * @param version The document's version number.\r
3290      * @param text The document's text.\r
3291      */\r
3292     function create(uri, languageId, version, text) {\r
3293         return { uri: uri, languageId: languageId, version: version, text: text };\r
3294     }\r
3295     TextDocumentItem.create = create;\r
3296     /**\r
3297      * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.\r
3298      */\r
3299     function is(value) {\r
3300         var candidate = value;\r
3301         return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);\r
3302     }\r
3303     TextDocumentItem.is = is;\r
3304 })(TextDocumentItem || (TextDocumentItem = {}));\r
3305 /**\r
3306  * Describes the content type that a client supports in various\r
3307  * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\r
3308  *\r
3309  * Please note that `MarkupKinds` must not start with a `$`. This kinds\r
3310  * are reserved for internal usage.\r
3311  */\r
3312 var MarkupKind;\r
3313 (function (MarkupKind) {\r
3314     /**\r
3315      * Plain text is supported as a content format\r
3316      */\r
3317     MarkupKind.PlainText = 'plaintext';\r
3318     /**\r
3319      * Markdown is supported as a content format\r
3320      */\r
3321     MarkupKind.Markdown = 'markdown';\r
3322 })(MarkupKind || (MarkupKind = {}));\r
3323 (function (MarkupKind) {\r
3324     /**\r
3325      * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.\r
3326      */\r
3327     function is(value) {\r
3328         var candidate = value;\r
3329         return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;\r
3330     }\r
3331     MarkupKind.is = is;\r
3332 })(MarkupKind || (MarkupKind = {}));\r
3333 var MarkupContent;\r
3334 (function (MarkupContent) {\r
3335     /**\r
3336      * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.\r
3337      */\r
3338     function is(value) {\r
3339         var candidate = value;\r
3340         return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);\r
3341     }\r
3342     MarkupContent.is = is;\r
3343 })(MarkupContent || (MarkupContent = {}));\r
3344 /**\r
3345  * The kind of a completion entry.\r
3346  */\r
3347 var CompletionItemKind;\r
3348 (function (CompletionItemKind) {\r
3349     CompletionItemKind.Text = 1;\r
3350     CompletionItemKind.Method = 2;\r
3351     CompletionItemKind.Function = 3;\r
3352     CompletionItemKind.Constructor = 4;\r
3353     CompletionItemKind.Field = 5;\r
3354     CompletionItemKind.Variable = 6;\r
3355     CompletionItemKind.Class = 7;\r
3356     CompletionItemKind.Interface = 8;\r
3357     CompletionItemKind.Module = 9;\r
3358     CompletionItemKind.Property = 10;\r
3359     CompletionItemKind.Unit = 11;\r
3360     CompletionItemKind.Value = 12;\r
3361     CompletionItemKind.Enum = 13;\r
3362     CompletionItemKind.Keyword = 14;\r
3363     CompletionItemKind.Snippet = 15;\r
3364     CompletionItemKind.Color = 16;\r
3365     CompletionItemKind.File = 17;\r
3366     CompletionItemKind.Reference = 18;\r
3367     CompletionItemKind.Folder = 19;\r
3368     CompletionItemKind.EnumMember = 20;\r
3369     CompletionItemKind.Constant = 21;\r
3370     CompletionItemKind.Struct = 22;\r
3371     CompletionItemKind.Event = 23;\r
3372     CompletionItemKind.Operator = 24;\r
3373     CompletionItemKind.TypeParameter = 25;\r
3374 })(CompletionItemKind || (CompletionItemKind = {}));\r
3375 /**\r
3376  * Defines whether the insert text in a completion item should be interpreted as\r
3377  * plain text or a snippet.\r
3378  */\r
3379 var InsertTextFormat;\r
3380 (function (InsertTextFormat) {\r
3381     /**\r
3382      * The primary text to be inserted is treated as a plain string.\r
3383      */\r
3384     InsertTextFormat.PlainText = 1;\r
3385     /**\r
3386      * The primary text to be inserted is treated as a snippet.\r
3387      *\r
3388      * A snippet can define tab stops and placeholders with `$1`, `$2`\r
3389      * and `${3:foo}`. `$0` defines the final tab stop, it defaults to\r
3390      * the end of the snippet. Placeholders with equal identifiers are linked,\r
3391      * that is typing in one will update others too.\r
3392      *\r
3393      * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md\r
3394      */\r
3395     InsertTextFormat.Snippet = 2;\r
3396 })(InsertTextFormat || (InsertTextFormat = {}));\r
3397 /**\r
3398  * Completion item tags are extra annotations that tweak the rendering of a completion\r
3399  * item.\r
3400  *\r
3401  * @since 3.15.0\r
3402  */\r
3403 var CompletionItemTag;\r
3404 (function (CompletionItemTag) {\r
3405     /**\r
3406      * Render a completion as obsolete, usually using a strike-out.\r
3407      */\r
3408     CompletionItemTag.Deprecated = 1;\r
3409 })(CompletionItemTag || (CompletionItemTag = {}));\r
3410 /**\r
3411  * The CompletionItem namespace provides functions to deal with\r
3412  * completion items.\r
3413  */\r
3414 var CompletionItem;\r
3415 (function (CompletionItem) {\r
3416     /**\r
3417      * Create a completion item and seed it with a label.\r
3418      * @param label The completion item's label\r
3419      */\r
3420     function create(label) {\r
3421         return { label: label };\r
3422     }\r
3423     CompletionItem.create = create;\r
3424 })(CompletionItem || (CompletionItem = {}));\r
3425 /**\r
3426  * The CompletionList namespace provides functions to deal with\r
3427  * completion lists.\r
3428  */\r
3429 var CompletionList;\r
3430 (function (CompletionList) {\r
3431     /**\r
3432      * Creates a new completion list.\r
3433      *\r
3434      * @param items The completion items.\r
3435      * @param isIncomplete The list is not complete.\r
3436      */\r
3437     function create(items, isIncomplete) {\r
3438         return { items: items ? items : [], isIncomplete: !!isIncomplete };\r
3439     }\r
3440     CompletionList.create = create;\r
3441 })(CompletionList || (CompletionList = {}));\r
3442 var MarkedString;\r
3443 (function (MarkedString) {\r
3444     /**\r
3445      * Creates a marked string from plain text.\r
3446      *\r
3447      * @param plainText The plain text.\r
3448      */\r
3449     function fromPlainText(plainText) {\r
3450         return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash\r
3451     }\r
3452     MarkedString.fromPlainText = fromPlainText;\r
3453     /**\r
3454      * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.\r
3455      */\r
3456     function is(value) {\r
3457         var candidate = value;\r
3458         return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));\r
3459     }\r
3460     MarkedString.is = is;\r
3461 })(MarkedString || (MarkedString = {}));\r
3462 var Hover;\r
3463 (function (Hover) {\r
3464     /**\r
3465      * Checks whether the given value conforms to the [Hover](#Hover) interface.\r
3466      */\r
3467     function is(value) {\r
3468         var candidate = value;\r
3469         return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||\r
3470             MarkedString.is(candidate.contents) ||\r
3471             Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));\r
3472     }\r
3473     Hover.is = is;\r
3474 })(Hover || (Hover = {}));\r
3475 /**\r
3476  * The ParameterInformation namespace provides helper functions to work with\r
3477  * [ParameterInformation](#ParameterInformation) literals.\r
3478  */\r
3479 var ParameterInformation;\r
3480 (function (ParameterInformation) {\r
3481     /**\r
3482      * Creates a new parameter information literal.\r
3483      *\r
3484      * @param label A label string.\r
3485      * @param documentation A doc string.\r
3486      */\r
3487     function create(label, documentation) {\r
3488         return documentation ? { label: label, documentation: documentation } : { label: label };\r
3489     }\r
3490     ParameterInformation.create = create;\r
3491 })(ParameterInformation || (ParameterInformation = {}));\r
3492 /**\r
3493  * The SignatureInformation namespace provides helper functions to work with\r
3494  * [SignatureInformation](#SignatureInformation) literals.\r
3495  */\r
3496 var SignatureInformation;\r
3497 (function (SignatureInformation) {\r
3498     function create(label, documentation) {\r
3499         var parameters = [];\r
3500         for (var _i = 2; _i < arguments.length; _i++) {\r
3501             parameters[_i - 2] = arguments[_i];\r
3502         }\r
3503         var result = { label: label };\r
3504         if (Is.defined(documentation)) {\r
3505             result.documentation = documentation;\r
3506         }\r
3507         if (Is.defined(parameters)) {\r
3508             result.parameters = parameters;\r
3509         }\r
3510         else {\r
3511             result.parameters = [];\r
3512         }\r
3513         return result;\r
3514     }\r
3515     SignatureInformation.create = create;\r
3516 })(SignatureInformation || (SignatureInformation = {}));\r
3517 /**\r
3518  * A document highlight kind.\r
3519  */\r
3520 var DocumentHighlightKind;\r
3521 (function (DocumentHighlightKind) {\r
3522     /**\r
3523      * A textual occurrence.\r
3524      */\r
3525     DocumentHighlightKind.Text = 1;\r
3526     /**\r
3527      * Read-access of a symbol, like reading a variable.\r
3528      */\r
3529     DocumentHighlightKind.Read = 2;\r
3530     /**\r
3531      * Write-access of a symbol, like writing to a variable.\r
3532      */\r
3533     DocumentHighlightKind.Write = 3;\r
3534 })(DocumentHighlightKind || (DocumentHighlightKind = {}));\r
3535 /**\r
3536  * DocumentHighlight namespace to provide helper functions to work with\r
3537  * [DocumentHighlight](#DocumentHighlight) literals.\r
3538  */\r
3539 var DocumentHighlight;\r
3540 (function (DocumentHighlight) {\r
3541     /**\r
3542      * Create a DocumentHighlight object.\r
3543      * @param range The range the highlight applies to.\r
3544      */\r
3545     function create(range, kind) {\r
3546         var result = { range: range };\r
3547         if (Is.number(kind)) {\r
3548             result.kind = kind;\r
3549         }\r
3550         return result;\r
3551     }\r
3552     DocumentHighlight.create = create;\r
3553 })(DocumentHighlight || (DocumentHighlight = {}));\r
3554 /**\r
3555  * A symbol kind.\r
3556  */\r
3557 var SymbolKind;\r
3558 (function (SymbolKind) {\r
3559     SymbolKind.File = 1;\r
3560     SymbolKind.Module = 2;\r
3561     SymbolKind.Namespace = 3;\r
3562     SymbolKind.Package = 4;\r
3563     SymbolKind.Class = 5;\r
3564     SymbolKind.Method = 6;\r
3565     SymbolKind.Property = 7;\r
3566     SymbolKind.Field = 8;\r
3567     SymbolKind.Constructor = 9;\r
3568     SymbolKind.Enum = 10;\r
3569     SymbolKind.Interface = 11;\r
3570     SymbolKind.Function = 12;\r
3571     SymbolKind.Variable = 13;\r
3572     SymbolKind.Constant = 14;\r
3573     SymbolKind.String = 15;\r
3574     SymbolKind.Number = 16;\r
3575     SymbolKind.Boolean = 17;\r
3576     SymbolKind.Array = 18;\r
3577     SymbolKind.Object = 19;\r
3578     SymbolKind.Key = 20;\r
3579     SymbolKind.Null = 21;\r
3580     SymbolKind.EnumMember = 22;\r
3581     SymbolKind.Struct = 23;\r
3582     SymbolKind.Event = 24;\r
3583     SymbolKind.Operator = 25;\r
3584     SymbolKind.TypeParameter = 26;\r
3585 })(SymbolKind || (SymbolKind = {}));\r
3586 /**\r
3587  * Symbol tags are extra annotations that tweak the rendering of a symbol.\r
3588  * @since 3.15\r
3589  */\r
3590 var SymbolTag;\r
3591 (function (SymbolTag) {\r
3592     /**\r
3593      * Render a symbol as obsolete, usually using a strike-out.\r
3594      */\r
3595     SymbolTag.Deprecated = 1;\r
3596 })(SymbolTag || (SymbolTag = {}));\r
3597 var SymbolInformation;\r
3598 (function (SymbolInformation) {\r
3599     /**\r
3600      * Creates a new symbol information literal.\r
3601      *\r
3602      * @param name The name of the symbol.\r
3603      * @param kind The kind of the symbol.\r
3604      * @param range The range of the location of the symbol.\r
3605      * @param uri The resource of the location of symbol, defaults to the current document.\r
3606      * @param containerName The name of the symbol containing the symbol.\r
3607      */\r
3608     function create(name, kind, range, uri, containerName) {\r
3609         var result = {\r
3610             name: name,\r
3611             kind: kind,\r
3612             location: { uri: uri, range: range }\r
3613         };\r
3614         if (containerName) {\r
3615             result.containerName = containerName;\r
3616         }\r
3617         return result;\r
3618     }\r
3619     SymbolInformation.create = create;\r
3620 })(SymbolInformation || (SymbolInformation = {}));\r
3621 var DocumentSymbol;\r
3622 (function (DocumentSymbol) {\r
3623     /**\r
3624      * Creates a new symbol information literal.\r
3625      *\r
3626      * @param name The name of the symbol.\r
3627      * @param detail The detail of the symbol.\r
3628      * @param kind The kind of the symbol.\r
3629      * @param range The range of the symbol.\r
3630      * @param selectionRange The selectionRange of the symbol.\r
3631      * @param children Children of the symbol.\r
3632      */\r
3633     function create(name, detail, kind, range, selectionRange, children) {\r
3634         var result = {\r
3635             name: name,\r
3636             detail: detail,\r
3637             kind: kind,\r
3638             range: range,\r
3639             selectionRange: selectionRange\r
3640         };\r
3641         if (children !== void 0) {\r
3642             result.children = children;\r
3643         }\r
3644         return result;\r
3645     }\r
3646     DocumentSymbol.create = create;\r
3647     /**\r
3648      * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.\r
3649      */\r
3650     function is(value) {\r
3651         var candidate = value;\r
3652         return candidate &&\r
3653             Is.string(candidate.name) && Is.number(candidate.kind) &&\r
3654             Range.is(candidate.range) && Range.is(candidate.selectionRange) &&\r
3655             (candidate.detail === void 0 || Is.string(candidate.detail)) &&\r
3656             (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&\r
3657             (candidate.children === void 0 || Array.isArray(candidate.children));\r
3658     }\r
3659     DocumentSymbol.is = is;\r
3660 })(DocumentSymbol || (DocumentSymbol = {}));\r
3661 /**\r
3662  * A set of predefined code action kinds\r
3663  */\r
3664 var CodeActionKind;\r
3665 (function (CodeActionKind) {\r
3666     /**\r
3667      * Empty kind.\r
3668      */\r
3669     CodeActionKind.Empty = '';\r
3670     /**\r
3671      * Base kind for quickfix actions: 'quickfix'\r
3672      */\r
3673     CodeActionKind.QuickFix = 'quickfix';\r
3674     /**\r
3675      * Base kind for refactoring actions: 'refactor'\r
3676      */\r
3677     CodeActionKind.Refactor = 'refactor';\r
3678     /**\r
3679      * Base kind for refactoring extraction actions: 'refactor.extract'\r
3680      *\r
3681      * Example extract actions:\r
3682      *\r
3683      * - Extract method\r
3684      * - Extract function\r
3685      * - Extract variable\r
3686      * - Extract interface from class\r
3687      * - ...\r
3688      */\r
3689     CodeActionKind.RefactorExtract = 'refactor.extract';\r
3690     /**\r
3691      * Base kind for refactoring inline actions: 'refactor.inline'\r
3692      *\r
3693      * Example inline actions:\r
3694      *\r
3695      * - Inline function\r
3696      * - Inline variable\r
3697      * - Inline constant\r
3698      * - ...\r
3699      */\r
3700     CodeActionKind.RefactorInline = 'refactor.inline';\r
3701     /**\r
3702      * Base kind for refactoring rewrite actions: 'refactor.rewrite'\r
3703      *\r
3704      * Example rewrite actions:\r
3705      *\r
3706      * - Convert JavaScript function to class\r
3707      * - Add or remove parameter\r
3708      * - Encapsulate field\r
3709      * - Make method static\r
3710      * - Move method to base class\r
3711      * - ...\r
3712      */\r
3713     CodeActionKind.RefactorRewrite = 'refactor.rewrite';\r
3714     /**\r
3715      * Base kind for source actions: `source`\r
3716      *\r
3717      * Source code actions apply to the entire file.\r
3718      */\r
3719     CodeActionKind.Source = 'source';\r
3720     /**\r
3721      * Base kind for an organize imports source action: `source.organizeImports`\r
3722      */\r
3723     CodeActionKind.SourceOrganizeImports = 'source.organizeImports';\r
3724     /**\r
3725      * Base kind for auto-fix source actions: `source.fixAll`.\r
3726      *\r
3727      * Fix all actions automatically fix errors that have a clear fix that do not require user input.\r
3728      * They should not suppress errors or perform unsafe fixes such as generating new types or classes.\r
3729      *\r
3730      * @since 3.15.0\r
3731      */\r
3732     CodeActionKind.SourceFixAll = 'source.fixAll';\r
3733 })(CodeActionKind || (CodeActionKind = {}));\r
3734 /**\r
3735  * The CodeActionContext namespace provides helper functions to work with\r
3736  * [CodeActionContext](#CodeActionContext) literals.\r
3737  */\r
3738 var CodeActionContext;\r
3739 (function (CodeActionContext) {\r
3740     /**\r
3741      * Creates a new CodeActionContext literal.\r
3742      */\r
3743     function create(diagnostics, only) {\r
3744         var result = { diagnostics: diagnostics };\r
3745         if (only !== void 0 && only !== null) {\r
3746             result.only = only;\r
3747         }\r
3748         return result;\r
3749     }\r
3750     CodeActionContext.create = create;\r
3751     /**\r
3752      * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.\r
3753      */\r
3754     function is(value) {\r
3755         var candidate = value;\r
3756         return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));\r
3757     }\r
3758     CodeActionContext.is = is;\r
3759 })(CodeActionContext || (CodeActionContext = {}));\r
3760 var CodeAction;\r
3761 (function (CodeAction) {\r
3762     function create(title, commandOrEdit, kind) {\r
3763         var result = { title: title };\r
3764         if (Command.is(commandOrEdit)) {\r
3765             result.command = commandOrEdit;\r
3766         }\r
3767         else {\r
3768             result.edit = commandOrEdit;\r
3769         }\r
3770         if (kind !== void 0) {\r
3771             result.kind = kind;\r
3772         }\r
3773         return result;\r
3774     }\r
3775     CodeAction.create = create;\r
3776     function is(value) {\r
3777         var candidate = value;\r
3778         return candidate && Is.string(candidate.title) &&\r
3779             (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&\r
3780             (candidate.kind === void 0 || Is.string(candidate.kind)) &&\r
3781             (candidate.edit !== void 0 || candidate.command !== void 0) &&\r
3782             (candidate.command === void 0 || Command.is(candidate.command)) &&\r
3783             (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&\r
3784             (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));\r
3785     }\r
3786     CodeAction.is = is;\r
3787 })(CodeAction || (CodeAction = {}));\r
3788 /**\r
3789  * The CodeLens namespace provides helper functions to work with\r
3790  * [CodeLens](#CodeLens) literals.\r
3791  */\r
3792 var CodeLens;\r
3793 (function (CodeLens) {\r
3794     /**\r
3795      * Creates a new CodeLens literal.\r
3796      */\r
3797     function create(range, data) {\r
3798         var result = { range: range };\r
3799         if (Is.defined(data)) {\r
3800             result.data = data;\r
3801         }\r
3802         return result;\r
3803     }\r
3804     CodeLens.create = create;\r
3805     /**\r
3806      * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.\r
3807      */\r
3808     function is(value) {\r
3809         var candidate = value;\r
3810         return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));\r
3811     }\r
3812     CodeLens.is = is;\r
3813 })(CodeLens || (CodeLens = {}));\r
3814 /**\r
3815  * The FormattingOptions namespace provides helper functions to work with\r
3816  * [FormattingOptions](#FormattingOptions) literals.\r
3817  */\r
3818 var FormattingOptions;\r
3819 (function (FormattingOptions) {\r
3820     /**\r
3821      * Creates a new FormattingOptions literal.\r
3822      */\r
3823     function create(tabSize, insertSpaces) {\r
3824         return { tabSize: tabSize, insertSpaces: insertSpaces };\r
3825     }\r
3826     FormattingOptions.create = create;\r
3827     /**\r
3828      * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.\r
3829      */\r
3830     function is(value) {\r
3831         var candidate = value;\r
3832         return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);\r
3833     }\r
3834     FormattingOptions.is = is;\r
3835 })(FormattingOptions || (FormattingOptions = {}));\r
3836 /**\r
3837  * The DocumentLink namespace provides helper functions to work with\r
3838  * [DocumentLink](#DocumentLink) literals.\r
3839  */\r
3840 var DocumentLink;\r
3841 (function (DocumentLink) {\r
3842     /**\r
3843      * Creates a new DocumentLink literal.\r
3844      */\r
3845     function create(range, target, data) {\r
3846         return { range: range, target: target, data: data };\r
3847     }\r
3848     DocumentLink.create = create;\r
3849     /**\r
3850      * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.\r
3851      */\r
3852     function is(value) {\r
3853         var candidate = value;\r
3854         return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));\r
3855     }\r
3856     DocumentLink.is = is;\r
3857 })(DocumentLink || (DocumentLink = {}));\r
3858 /**\r
3859  * The SelectionRange namespace provides helper function to work with\r
3860  * SelectionRange literals.\r
3861  */\r
3862 var SelectionRange;\r
3863 (function (SelectionRange) {\r
3864     /**\r
3865      * Creates a new SelectionRange\r
3866      * @param range the range.\r
3867      * @param parent an optional parent.\r
3868      */\r
3869     function create(range, parent) {\r
3870         return { range: range, parent: parent };\r
3871     }\r
3872     SelectionRange.create = create;\r
3873     function is(value) {\r
3874         var candidate = value;\r
3875         return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));\r
3876     }\r
3877     SelectionRange.is = is;\r
3878 })(SelectionRange || (SelectionRange = {}));\r
3879 var EOL = ['\n', '\r\n', '\r'];\r
3880 /**\r
3881  * @deprecated Use the text document from the new vscode-languageserver-textdocument package.\r
3882  */\r
3883 var TextDocument;\r
3884 (function (TextDocument) {\r
3885     /**\r
3886      * Creates a new ITextDocument literal from the given uri and content.\r
3887      * @param uri The document's uri.\r
3888      * @param languageId  The document's language Id.\r
3889      * @param content The document's content.\r
3890      */\r
3891     function create(uri, languageId, version, content) {\r
3892         return new FullTextDocument(uri, languageId, version, content);\r
3893     }\r
3894     TextDocument.create = create;\r
3895     /**\r
3896      * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.\r
3897      */\r
3898     function is(value) {\r
3899         var candidate = value;\r
3900         return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)\r
3901             && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;\r
3902     }\r
3903     TextDocument.is = is;\r
3904     function applyEdits(document, edits) {\r
3905         var text = document.getText();\r
3906         var sortedEdits = mergeSort(edits, function (a, b) {\r
3907             var diff = a.range.start.line - b.range.start.line;\r
3908             if (diff === 0) {\r
3909                 return a.range.start.character - b.range.start.character;\r
3910             }\r
3911             return diff;\r
3912         });\r
3913         var lastModifiedOffset = text.length;\r
3914         for (var i = sortedEdits.length - 1; i >= 0; i--) {\r
3915             var e = sortedEdits[i];\r
3916             var startOffset = document.offsetAt(e.range.start);\r
3917             var endOffset = document.offsetAt(e.range.end);\r
3918             if (endOffset <= lastModifiedOffset) {\r
3919                 text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);\r
3920             }\r
3921             else {\r
3922                 throw new Error('Overlapping edit');\r
3923             }\r
3924             lastModifiedOffset = startOffset;\r
3925         }\r
3926         return text;\r
3927     }\r
3928     TextDocument.applyEdits = applyEdits;\r
3929     function mergeSort(data, compare) {\r
3930         if (data.length <= 1) {\r
3931             // sorted\r
3932             return data;\r
3933         }\r
3934         var p = (data.length / 2) | 0;\r
3935         var left = data.slice(0, p);\r
3936         var right = data.slice(p);\r
3937         mergeSort(left, compare);\r
3938         mergeSort(right, compare);\r
3939         var leftIdx = 0;\r
3940         var rightIdx = 0;\r
3941         var i = 0;\r
3942         while (leftIdx < left.length && rightIdx < right.length) {\r
3943             var ret = compare(left[leftIdx], right[rightIdx]);\r
3944             if (ret <= 0) {\r
3945                 // smaller_equal -> take left to preserve order\r
3946                 data[i++] = left[leftIdx++];\r
3947             }\r
3948             else {\r
3949                 // greater -> take right\r
3950                 data[i++] = right[rightIdx++];\r
3951             }\r
3952         }\r
3953         while (leftIdx < left.length) {\r
3954             data[i++] = left[leftIdx++];\r
3955         }\r
3956         while (rightIdx < right.length) {\r
3957             data[i++] = right[rightIdx++];\r
3958         }\r
3959         return data;\r
3960     }\r
3961 })(TextDocument || (TextDocument = {}));\r
3962 var FullTextDocument = /** @class */ (function () {\r
3963     function FullTextDocument(uri, languageId, version, content) {\r
3964         this._uri = uri;\r
3965         this._languageId = languageId;\r
3966         this._version = version;\r
3967         this._content = content;\r
3968         this._lineOffsets = undefined;\r
3969     }\r
3970     Object.defineProperty(FullTextDocument.prototype, "uri", {\r
3971         get: function () {\r
3972             return this._uri;\r
3973         },\r
3974         enumerable: true,\r
3975         configurable: true\r
3976     });\r
3977     Object.defineProperty(FullTextDocument.prototype, "languageId", {\r
3978         get: function () {\r
3979             return this._languageId;\r
3980         },\r
3981         enumerable: true,\r
3982         configurable: true\r
3983     });\r
3984     Object.defineProperty(FullTextDocument.prototype, "version", {\r
3985         get: function () {\r
3986             return this._version;\r
3987         },\r
3988         enumerable: true,\r
3989         configurable: true\r
3990     });\r
3991     FullTextDocument.prototype.getText = function (range) {\r
3992         if (range) {\r
3993             var start = this.offsetAt(range.start);\r
3994             var end = this.offsetAt(range.end);\r
3995             return this._content.substring(start, end);\r
3996         }\r
3997         return this._content;\r
3998     };\r
3999     FullTextDocument.prototype.update = function (event, version) {\r
4000         this._content = event.text;\r
4001         this._version = version;\r
4002         this._lineOffsets = undefined;\r
4003     };\r
4004     FullTextDocument.prototype.getLineOffsets = function () {\r
4005         if (this._lineOffsets === undefined) {\r
4006             var lineOffsets = [];\r
4007             var text = this._content;\r
4008             var isLineStart = true;\r
4009             for (var i = 0; i < text.length; i++) {\r
4010                 if (isLineStart) {\r
4011                     lineOffsets.push(i);\r
4012                     isLineStart = false;\r
4013                 }\r
4014                 var ch = text.charAt(i);\r
4015                 isLineStart = (ch === '\r' || ch === '\n');\r
4016                 if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {\r
4017                     i++;\r
4018                 }\r
4019             }\r
4020             if (isLineStart && text.length > 0) {\r
4021                 lineOffsets.push(text.length);\r
4022             }\r
4023             this._lineOffsets = lineOffsets;\r
4024         }\r
4025         return this._lineOffsets;\r
4026     };\r
4027     FullTextDocument.prototype.positionAt = function (offset) {\r
4028         offset = Math.max(Math.min(offset, this._content.length), 0);\r
4029         var lineOffsets = this.getLineOffsets();\r
4030         var low = 0, high = lineOffsets.length;\r
4031         if (high === 0) {\r
4032             return Position.create(0, offset);\r
4033         }\r
4034         while (low < high) {\r
4035             var mid = Math.floor((low + high) / 2);\r
4036             if (lineOffsets[mid] > offset) {\r
4037                 high = mid;\r
4038             }\r
4039             else {\r
4040                 low = mid + 1;\r
4041             }\r
4042         }\r
4043         // low is the least x for which the line offset is larger than the current offset\r
4044         // or array.length if no line offset is larger than the current offset\r
4045         var line = low - 1;\r
4046         return Position.create(line, offset - lineOffsets[line]);\r
4047     };\r
4048     FullTextDocument.prototype.offsetAt = function (position) {\r
4049         var lineOffsets = this.getLineOffsets();\r
4050         if (position.line >= lineOffsets.length) {\r
4051             return this._content.length;\r
4052         }\r
4053         else if (position.line < 0) {\r
4054             return 0;\r
4055         }\r
4056         var lineOffset = lineOffsets[position.line];\r
4057         var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;\r
4058         return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);\r
4059     };\r
4060     Object.defineProperty(FullTextDocument.prototype, "lineCount", {\r
4061         get: function () {\r
4062             return this.getLineOffsets().length;\r
4063         },\r
4064         enumerable: true,\r
4065         configurable: true\r
4066     });\r
4067     return FullTextDocument;\r
4068 }());\r
4069 var Is;\r
4070 (function (Is) {\r
4071     var toString = Object.prototype.toString;\r
4072     function defined(value) {\r
4073         return typeof value !== 'undefined';\r
4074     }\r
4075     Is.defined = defined;\r
4076     function undefined(value) {\r
4077         return typeof value === 'undefined';\r
4078     }\r
4079     Is.undefined = undefined;\r
4080     function boolean(value) {\r
4081         return value === true || value === false;\r
4082     }\r
4083     Is.boolean = boolean;\r
4084     function string(value) {\r
4085         return toString.call(value) === '[object String]';\r
4086     }\r
4087     Is.string = string;\r
4088     function number(value) {\r
4089         return toString.call(value) === '[object Number]';\r
4090     }\r
4091     Is.number = number;\r
4092     function func(value) {\r
4093         return toString.call(value) === '[object Function]';\r
4094     }\r
4095     Is.func = func;\r
4096     function objectLiteral(value) {\r
4097         // Strictly speaking class instances pass this check as well. Since the LSP\r
4098         // doesn't use classes we ignore this for now. If we do we need to add something\r
4099         // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`\r
4100         return value !== null && typeof value === 'object';\r
4101     }\r
4102     Is.objectLiteral = objectLiteral;\r
4103     function typedArray(value, check) {\r
4104         return Array.isArray(value) && value.every(check);\r
4105     }\r
4106     Is.typedArray = typedArray;\r
4107 })(Is || (Is = {}));\r
4108
4109
4110 /***/ }),
4111 /* 19 */
4112 /***/ (function(module, exports, __webpack_require__) {
4113
4114 "use strict";
4115 /* --------------------------------------------------------------------------------------------\r
4116  * Copyright (c) Microsoft Corporation. All rights reserved.\r
4117  * Licensed under the MIT License. See License.txt in the project root for license information.\r
4118  * ------------------------------------------------------------------------------------------ */\r
4119 \r
4120 Object.defineProperty(exports, "__esModule", { value: true });\r
4121 const Is = __webpack_require__(20);\r
4122 const vscode_jsonrpc_1 = __webpack_require__(5);\r
4123 const messages_1 = __webpack_require__(21);\r
4124 const protocol_implementation_1 = __webpack_require__(22);\r
4125 exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;\r
4126 const protocol_typeDefinition_1 = __webpack_require__(23);\r
4127 exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;\r
4128 const protocol_workspaceFolders_1 = __webpack_require__(24);\r
4129 exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;\r
4130 exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;\r
4131 const protocol_configuration_1 = __webpack_require__(25);\r
4132 exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;\r
4133 const protocol_colorProvider_1 = __webpack_require__(26);\r
4134 exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;\r
4135 exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;\r
4136 const protocol_foldingRange_1 = __webpack_require__(27);\r
4137 exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;\r
4138 const protocol_declaration_1 = __webpack_require__(28);\r
4139 exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;\r
4140 const protocol_selectionRange_1 = __webpack_require__(29);\r
4141 exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;\r
4142 const protocol_progress_1 = __webpack_require__(30);\r
4143 exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;\r
4144 exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;\r
4145 exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;\r
4146 // @ts-ignore: to avoid inlining LocatioLink as dynamic import\r
4147 let __noDynamicImport;\r
4148 /**\r
4149  * The DocumentFilter namespace provides helper functions to work with\r
4150  * [DocumentFilter](#DocumentFilter) literals.\r
4151  */\r
4152 var DocumentFilter;\r
4153 (function (DocumentFilter) {\r
4154     function is(value) {\r
4155         const candidate = value;\r
4156         return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);\r
4157     }\r
4158     DocumentFilter.is = is;\r
4159 })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));\r
4160 /**\r
4161  * The DocumentSelector namespace provides helper functions to work with\r
4162  * [DocumentSelector](#DocumentSelector)s.\r
4163  */\r
4164 var DocumentSelector;\r
4165 (function (DocumentSelector) {\r
4166     function is(value) {\r
4167         if (!Array.isArray(value)) {\r
4168             return false;\r
4169         }\r
4170         for (let elem of value) {\r
4171             if (!Is.string(elem) && !DocumentFilter.is(elem)) {\r
4172                 return false;\r
4173             }\r
4174         }\r
4175         return true;\r
4176     }\r
4177     DocumentSelector.is = is;\r
4178 })(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));\r
4179 /**\r
4180  * The `client/registerCapability` request is sent from the server to the client to register a new capability\r
4181  * handler on the client side.\r
4182  */\r
4183 var RegistrationRequest;\r
4184 (function (RegistrationRequest) {\r
4185     RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability');\r
4186 })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));\r
4187 /**\r
4188  * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability\r
4189  * handler on the client side.\r
4190  */\r
4191 var UnregistrationRequest;\r
4192 (function (UnregistrationRequest) {\r
4193     UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability');\r
4194 })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));\r
4195 var ResourceOperationKind;\r
4196 (function (ResourceOperationKind) {\r
4197     /**\r
4198      * Supports creating new files and folders.\r
4199      */\r
4200     ResourceOperationKind.Create = 'create';\r
4201     /**\r
4202      * Supports renaming existing files and folders.\r
4203      */\r
4204     ResourceOperationKind.Rename = 'rename';\r
4205     /**\r
4206      * Supports deleting existing files and folders.\r
4207      */\r
4208     ResourceOperationKind.Delete = 'delete';\r
4209 })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));\r
4210 var FailureHandlingKind;\r
4211 (function (FailureHandlingKind) {\r
4212     /**\r
4213      * Applying the workspace change is simply aborted if one of the changes provided\r
4214      * fails. All operations executed before the failing operation stay executed.\r
4215      */\r
4216     FailureHandlingKind.Abort = 'abort';\r
4217     /**\r
4218      * All operations are executed transactional. That means they either all\r
4219      * succeed or no changes at all are applied to the workspace.\r
4220      */\r
4221     FailureHandlingKind.Transactional = 'transactional';\r
4222     /**\r
4223      * If the workspace edit contains only textual file changes they are executed transactional.\r
4224      * If resource changes (create, rename or delete file) are part of the change the failure\r
4225      * handling startegy is abort.\r
4226      */\r
4227     FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';\r
4228     /**\r
4229      * The client tries to undo the operations already executed. But there is no\r
4230      * guarantee that this is succeeding.\r
4231      */\r
4232     FailureHandlingKind.Undo = 'undo';\r
4233 })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));\r
4234 /**\r
4235  * The StaticRegistrationOptions namespace provides helper functions to work with\r
4236  * [StaticRegistrationOptions](#StaticRegistrationOptions) literals.\r
4237  */\r
4238 var StaticRegistrationOptions;\r
4239 (function (StaticRegistrationOptions) {\r
4240     function hasId(value) {\r
4241         const candidate = value;\r
4242         return candidate && Is.string(candidate.id) && candidate.id.length > 0;\r
4243     }\r
4244     StaticRegistrationOptions.hasId = hasId;\r
4245 })(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));\r
4246 /**\r
4247  * The TextDocumentRegistrationOptions namespace provides helper functions to work with\r
4248  * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals.\r
4249  */\r
4250 var TextDocumentRegistrationOptions;\r
4251 (function (TextDocumentRegistrationOptions) {\r
4252     function is(value) {\r
4253         const candidate = value;\r
4254         return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));\r
4255     }\r
4256     TextDocumentRegistrationOptions.is = is;\r
4257 })(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));\r
4258 /**\r
4259  * The WorkDoneProgressOptions namespace provides helper functions to work with\r
4260  * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals.\r
4261  */\r
4262 var WorkDoneProgressOptions;\r
4263 (function (WorkDoneProgressOptions) {\r
4264     function is(value) {\r
4265         const candidate = value;\r
4266         return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));\r
4267     }\r
4268     WorkDoneProgressOptions.is = is;\r
4269     function hasWorkDoneProgress(value) {\r
4270         const candidate = value;\r
4271         return candidate && Is.boolean(candidate.workDoneProgress);\r
4272     }\r
4273     WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;\r
4274 })(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));\r
4275 /**\r
4276  * The initialize request is sent from the client to the server.\r
4277  * It is sent once as the request after starting up the server.\r
4278  * The requests parameter is of type [InitializeParams](#InitializeParams)\r
4279  * the response if of type [InitializeResult](#InitializeResult) of a Thenable that\r
4280  * resolves to such.\r
4281  */\r
4282 var InitializeRequest;\r
4283 (function (InitializeRequest) {\r
4284     InitializeRequest.type = new messages_1.ProtocolRequestType('initialize');\r
4285 })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));\r
4286 /**\r
4287  * Known error codes for an `InitializeError`;\r
4288  */\r
4289 var InitializeError;\r
4290 (function (InitializeError) {\r
4291     /**\r
4292      * If the protocol version provided by the client can't be handled by the server.\r
4293      * @deprecated This initialize error got replaced by client capabilities. There is\r
4294      * no version handshake in version 3.0x\r
4295      */\r
4296     InitializeError.unknownProtocolVersion = 1;\r
4297 })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));\r
4298 /**\r
4299  * The intialized notification is sent from the client to the\r
4300  * server after the client is fully initialized and the server\r
4301  * is allowed to send requests from the server to the client.\r
4302  */\r
4303 var InitializedNotification;\r
4304 (function (InitializedNotification) {\r
4305     InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized');\r
4306 })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));\r
4307 //---- Shutdown Method ----\r
4308 /**\r
4309  * A shutdown request is sent from the client to the server.\r
4310  * It is sent once when the client decides to shutdown the\r
4311  * server. The only notification that is sent after a shutdown request\r
4312  * is the exit event.\r
4313  */\r
4314 var ShutdownRequest;\r
4315 (function (ShutdownRequest) {\r
4316     ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown');\r
4317 })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));\r
4318 //---- Exit Notification ----\r
4319 /**\r
4320  * The exit event is sent from the client to the server to\r
4321  * ask the server to exit its process.\r
4322  */\r
4323 var ExitNotification;\r
4324 (function (ExitNotification) {\r
4325     ExitNotification.type = new messages_1.ProtocolNotificationType0('exit');\r
4326 })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));\r
4327 /**\r
4328  * The configuration change notification is sent from the client to the server\r
4329  * when the client's configuration has changed. The notification contains\r
4330  * the changed configuration as defined by the language client.\r
4331  */\r
4332 var DidChangeConfigurationNotification;\r
4333 (function (DidChangeConfigurationNotification) {\r
4334     DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration');\r
4335 })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));\r
4336 //---- Message show and log notifications ----\r
4337 /**\r
4338  * The message type\r
4339  */\r
4340 var MessageType;\r
4341 (function (MessageType) {\r
4342     /**\r
4343      * An error message.\r
4344      */\r
4345     MessageType.Error = 1;\r
4346     /**\r
4347      * A warning message.\r
4348      */\r
4349     MessageType.Warning = 2;\r
4350     /**\r
4351      * An information message.\r
4352      */\r
4353     MessageType.Info = 3;\r
4354     /**\r
4355      * A log message.\r
4356      */\r
4357     MessageType.Log = 4;\r
4358 })(MessageType = exports.MessageType || (exports.MessageType = {}));\r
4359 /**\r
4360  * The show message notification is sent from a server to a client to ask\r
4361  * the client to display a particular message in the user interface.\r
4362  */\r
4363 var ShowMessageNotification;\r
4364 (function (ShowMessageNotification) {\r
4365     ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage');\r
4366 })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));\r
4367 /**\r
4368  * The show message request is sent from the server to the client to show a message\r
4369  * and a set of options actions to the user.\r
4370  */\r
4371 var ShowMessageRequest;\r
4372 (function (ShowMessageRequest) {\r
4373     ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest');\r
4374 })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));\r
4375 /**\r
4376  * The log message notification is sent from the server to the client to ask\r
4377  * the client to log a particular message.\r
4378  */\r
4379 var LogMessageNotification;\r
4380 (function (LogMessageNotification) {\r
4381     LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage');\r
4382 })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));\r
4383 //---- Telemetry notification\r
4384 /**\r
4385  * The telemetry event notification is sent from the server to the client to ask\r
4386  * the client to log telemetry data.\r
4387  */\r
4388 var TelemetryEventNotification;\r
4389 (function (TelemetryEventNotification) {\r
4390     TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event');\r
4391 })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));\r
4392 /**\r
4393  * Defines how the host (editor) should sync\r
4394  * document changes to the language server.\r
4395  */\r
4396 var TextDocumentSyncKind;\r
4397 (function (TextDocumentSyncKind) {\r
4398     /**\r
4399      * Documents should not be synced at all.\r
4400      */\r
4401     TextDocumentSyncKind.None = 0;\r
4402     /**\r
4403      * Documents are synced by always sending the full content\r
4404      * of the document.\r
4405      */\r
4406     TextDocumentSyncKind.Full = 1;\r
4407     /**\r
4408      * Documents are synced by sending the full content on open.\r
4409      * After that only incremental updates to the document are\r
4410      * send.\r
4411      */\r
4412     TextDocumentSyncKind.Incremental = 2;\r
4413 })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));\r
4414 /**\r
4415  * The document open notification is sent from the client to the server to signal\r
4416  * newly opened text documents. The document's truth is now managed by the client\r
4417  * and the server must not try to read the document's truth using the document's\r
4418  * uri. Open in this sense means it is managed by the client. It doesn't necessarily\r
4419  * mean that its content is presented in an editor. An open notification must not\r
4420  * be sent more than once without a corresponding close notification send before.\r
4421  * This means open and close notification must be balanced and the max open count\r
4422  * is one.\r
4423  */\r
4424 var DidOpenTextDocumentNotification;\r
4425 (function (DidOpenTextDocumentNotification) {\r
4426     DidOpenTextDocumentNotification.method = 'textDocument/didOpen';\r
4427     DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);\r
4428 })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));\r
4429 /**\r
4430  * The document change notification is sent from the client to the server to signal\r
4431  * changes to a text document.\r
4432  */\r
4433 var DidChangeTextDocumentNotification;\r
4434 (function (DidChangeTextDocumentNotification) {\r
4435     DidChangeTextDocumentNotification.method = 'textDocument/didChange';\r
4436     DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);\r
4437 })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));\r
4438 /**\r
4439  * The document close notification is sent from the client to the server when\r
4440  * the document got closed in the client. The document's truth now exists where\r
4441  * the document's uri points to (e.g. if the document's uri is a file uri the\r
4442  * truth now exists on disk). As with the open notification the close notification\r
4443  * is about managing the document's content. Receiving a close notification\r
4444  * doesn't mean that the document was open in an editor before. A close\r
4445  * notification requires a previous open notification to be sent.\r
4446  */\r
4447 var DidCloseTextDocumentNotification;\r
4448 (function (DidCloseTextDocumentNotification) {\r
4449     DidCloseTextDocumentNotification.method = 'textDocument/didClose';\r
4450     DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);\r
4451 })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));\r
4452 /**\r
4453  * The document save notification is sent from the client to the server when\r
4454  * the document got saved in the client.\r
4455  */\r
4456 var DidSaveTextDocumentNotification;\r
4457 (function (DidSaveTextDocumentNotification) {\r
4458     DidSaveTextDocumentNotification.method = 'textDocument/didSave';\r
4459     DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);\r
4460 })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));\r
4461 /**\r
4462  * Represents reasons why a text document is saved.\r
4463  */\r
4464 var TextDocumentSaveReason;\r
4465 (function (TextDocumentSaveReason) {\r
4466     /**\r
4467      * Manually triggered, e.g. by the user pressing save, by starting debugging,\r
4468      * or by an API call.\r
4469      */\r
4470     TextDocumentSaveReason.Manual = 1;\r
4471     /**\r
4472      * Automatic after a delay.\r
4473      */\r
4474     TextDocumentSaveReason.AfterDelay = 2;\r
4475     /**\r
4476      * When the editor lost focus.\r
4477      */\r
4478     TextDocumentSaveReason.FocusOut = 3;\r
4479 })(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));\r
4480 /**\r
4481  * A document will save notification is sent from the client to the server before\r
4482  * the document is actually saved.\r
4483  */\r
4484 var WillSaveTextDocumentNotification;\r
4485 (function (WillSaveTextDocumentNotification) {\r
4486     WillSaveTextDocumentNotification.method = 'textDocument/willSave';\r
4487     WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);\r
4488 })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));\r
4489 /**\r
4490  * A document will save request is sent from the client to the server before\r
4491  * the document is actually saved. The request can return an array of TextEdits\r
4492  * which will be applied to the text document before it is saved. Please note that\r
4493  * clients might drop results if computing the text edits took too long or if a\r
4494  * server constantly fails on this request. This is done to keep the save fast and\r
4495  * reliable.\r
4496  */\r
4497 var WillSaveTextDocumentWaitUntilRequest;\r
4498 (function (WillSaveTextDocumentWaitUntilRequest) {\r
4499     WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';\r
4500     WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);\r
4501 })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));\r
4502 /**\r
4503  * The watched files notification is sent from the client to the server when\r
4504  * the client detects changes to file watched by the language client.\r
4505  */\r
4506 var DidChangeWatchedFilesNotification;\r
4507 (function (DidChangeWatchedFilesNotification) {\r
4508     DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles');\r
4509 })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));\r
4510 /**\r
4511  * The file event type\r
4512  */\r
4513 var FileChangeType;\r
4514 (function (FileChangeType) {\r
4515     /**\r
4516      * The file got created.\r
4517      */\r
4518     FileChangeType.Created = 1;\r
4519     /**\r
4520      * The file got changed.\r
4521      */\r
4522     FileChangeType.Changed = 2;\r
4523     /**\r
4524      * The file got deleted.\r
4525      */\r
4526     FileChangeType.Deleted = 3;\r
4527 })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));\r
4528 var WatchKind;\r
4529 (function (WatchKind) {\r
4530     /**\r
4531      * Interested in create events.\r
4532      */\r
4533     WatchKind.Create = 1;\r
4534     /**\r
4535      * Interested in change events\r
4536      */\r
4537     WatchKind.Change = 2;\r
4538     /**\r
4539      * Interested in delete events\r
4540      */\r
4541     WatchKind.Delete = 4;\r
4542 })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));\r
4543 /**\r
4544  * Diagnostics notification are sent from the server to the client to signal\r
4545  * results of validation runs.\r
4546  */\r
4547 var PublishDiagnosticsNotification;\r
4548 (function (PublishDiagnosticsNotification) {\r
4549     PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics');\r
4550 })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));\r
4551 /**\r
4552  * How a completion was triggered\r
4553  */\r
4554 var CompletionTriggerKind;\r
4555 (function (CompletionTriggerKind) {\r
4556     /**\r
4557      * Completion was triggered by typing an identifier (24x7 code\r
4558      * complete), manual invocation (e.g Ctrl+Space) or via API.\r
4559      */\r
4560     CompletionTriggerKind.Invoked = 1;\r
4561     /**\r
4562      * Completion was triggered by a trigger character specified by\r
4563      * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.\r
4564      */\r
4565     CompletionTriggerKind.TriggerCharacter = 2;\r
4566     /**\r
4567      * Completion was re-triggered as current completion list is incomplete\r
4568      */\r
4569     CompletionTriggerKind.TriggerForIncompleteCompletions = 3;\r
4570 })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));\r
4571 /**\r
4572  * Request to request completion at a given text document position. The request's\r
4573  * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response\r
4574  * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)\r
4575  * or a Thenable that resolves to such.\r
4576  *\r
4577  * The request can delay the computation of the [`detail`](#CompletionItem.detail)\r
4578  * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`\r
4579  * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,\r
4580  * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.\r
4581  */\r
4582 var CompletionRequest;\r
4583 (function (CompletionRequest) {\r
4584     CompletionRequest.method = 'textDocument/completion';\r
4585     CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);\r
4586     /** @deprecated Use CompletionRequest.type */\r
4587     CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4588 })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));\r
4589 /**\r
4590  * Request to resolve additional information for a given completion item.The request's\r
4591  * parameter is of type [CompletionItem](#CompletionItem) the response\r
4592  * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.\r
4593  */\r
4594 var CompletionResolveRequest;\r
4595 (function (CompletionResolveRequest) {\r
4596     CompletionResolveRequest.method = 'completionItem/resolve';\r
4597     CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);\r
4598 })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));\r
4599 /**\r
4600  * Request to request hover information at a given text document position. The request's\r
4601  * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of\r
4602  * type [Hover](#Hover) or a Thenable that resolves to such.\r
4603  */\r
4604 var HoverRequest;\r
4605 (function (HoverRequest) {\r
4606     HoverRequest.method = 'textDocument/hover';\r
4607     HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);\r
4608 })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));\r
4609 /**\r
4610  * How a signature help was triggered.\r
4611  *\r
4612  * @since 3.15.0\r
4613  */\r
4614 var SignatureHelpTriggerKind;\r
4615 (function (SignatureHelpTriggerKind) {\r
4616     /**\r
4617      * Signature help was invoked manually by the user or by a command.\r
4618      */\r
4619     SignatureHelpTriggerKind.Invoked = 1;\r
4620     /**\r
4621      * Signature help was triggered by a trigger character.\r
4622      */\r
4623     SignatureHelpTriggerKind.TriggerCharacter = 2;\r
4624     /**\r
4625      * Signature help was triggered by the cursor moving or by the document content changing.\r
4626      */\r
4627     SignatureHelpTriggerKind.ContentChange = 3;\r
4628 })(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));\r
4629 var SignatureHelpRequest;\r
4630 (function (SignatureHelpRequest) {\r
4631     SignatureHelpRequest.method = 'textDocument/signatureHelp';\r
4632     SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);\r
4633 })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));\r
4634 /**\r
4635  * A request to resolve the definition location of a symbol at a given text\r
4636  * document position. The request's parameter is of type [TextDocumentPosition]\r
4637  * (#TextDocumentPosition) the response is of either type [Definition](#Definition)\r
4638  * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves\r
4639  * to such.\r
4640  */\r
4641 var DefinitionRequest;\r
4642 (function (DefinitionRequest) {\r
4643     DefinitionRequest.method = 'textDocument/definition';\r
4644     DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);\r
4645     /** @deprecated Use DefinitionRequest.type */\r
4646     DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4647 })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));\r
4648 /**\r
4649  * A request to resolve project-wide references for the symbol denoted\r
4650  * by the given text document position. The request's parameter is of\r
4651  * type [ReferenceParams](#ReferenceParams) the response is of type\r
4652  * [Location[]](#Location) or a Thenable that resolves to such.\r
4653  */\r
4654 var ReferencesRequest;\r
4655 (function (ReferencesRequest) {\r
4656     ReferencesRequest.method = 'textDocument/references';\r
4657     ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);\r
4658     /** @deprecated Use ReferencesRequest.type */\r
4659     ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4660 })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));\r
4661 /**\r
4662  * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given\r
4663  * text document position. The request's parameter is of type [TextDocumentPosition]\r
4664  * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]\r
4665  * (#DocumentHighlight) or a Thenable that resolves to such.\r
4666  */\r
4667 var DocumentHighlightRequest;\r
4668 (function (DocumentHighlightRequest) {\r
4669     DocumentHighlightRequest.method = 'textDocument/documentHighlight';\r
4670     DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);\r
4671     /** @deprecated Use DocumentHighlightRequest.type */\r
4672     DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4673 })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));\r
4674 /**\r
4675  * A request to list all symbols found in a given text document. The request's\r
4676  * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the\r
4677  * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable\r
4678  * that resolves to such.\r
4679  */\r
4680 var DocumentSymbolRequest;\r
4681 (function (DocumentSymbolRequest) {\r
4682     DocumentSymbolRequest.method = 'textDocument/documentSymbol';\r
4683     DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);\r
4684     /** @deprecated Use DocumentSymbolRequest.type */\r
4685     DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4686 })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));\r
4687 /**\r
4688  * A request to provide commands for the given text document and range.\r
4689  */\r
4690 var CodeActionRequest;\r
4691 (function (CodeActionRequest) {\r
4692     CodeActionRequest.method = 'textDocument/codeAction';\r
4693     CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);\r
4694     /** @deprecated Use CodeActionRequest.type */\r
4695     CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4696 })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));\r
4697 /**\r
4698  * A request to list project-wide symbols matching the query string given\r
4699  * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is\r
4700  * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that\r
4701  * resolves to such.\r
4702  */\r
4703 var WorkspaceSymbolRequest;\r
4704 (function (WorkspaceSymbolRequest) {\r
4705     WorkspaceSymbolRequest.method = 'workspace/symbol';\r
4706     WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);\r
4707     /** @deprecated Use WorkspaceSymbolRequest.type */\r
4708     WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4709 })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));\r
4710 /**\r
4711  * A request to provide code lens for the given text document.\r
4712  */\r
4713 var CodeLensRequest;\r
4714 (function (CodeLensRequest) {\r
4715     CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens');\r
4716     /** @deprecated Use CodeLensRequest.type */\r
4717     CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4718 })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));\r
4719 /**\r
4720  * A request to resolve a command for a given code lens.\r
4721  */\r
4722 var CodeLensResolveRequest;\r
4723 (function (CodeLensResolveRequest) {\r
4724     CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve');\r
4725 })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));\r
4726 /**\r
4727  * A request to provide document links\r
4728  */\r
4729 var DocumentLinkRequest;\r
4730 (function (DocumentLinkRequest) {\r
4731     DocumentLinkRequest.method = 'textDocument/documentLink';\r
4732     DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);\r
4733     /** @deprecated Use DocumentLinkRequest.type */\r
4734     DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4735 })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));\r
4736 /**\r
4737  * Request to resolve additional information for a given document link. The request's\r
4738  * parameter is of type [DocumentLink](#DocumentLink) the response\r
4739  * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.\r
4740  */\r
4741 var DocumentLinkResolveRequest;\r
4742 (function (DocumentLinkResolveRequest) {\r
4743     DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve');\r
4744 })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));\r
4745 /**\r
4746  * A request to to format a whole document.\r
4747  */\r
4748 var DocumentFormattingRequest;\r
4749 (function (DocumentFormattingRequest) {\r
4750     DocumentFormattingRequest.method = 'textDocument/formatting';\r
4751     DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);\r
4752 })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));\r
4753 /**\r
4754  * A request to to format a range in a document.\r
4755  */\r
4756 var DocumentRangeFormattingRequest;\r
4757 (function (DocumentRangeFormattingRequest) {\r
4758     DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';\r
4759     DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);\r
4760 })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));\r
4761 /**\r
4762  * A request to format a document on type.\r
4763  */\r
4764 var DocumentOnTypeFormattingRequest;\r
4765 (function (DocumentOnTypeFormattingRequest) {\r
4766     DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';\r
4767     DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);\r
4768 })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));\r
4769 /**\r
4770  * A request to rename a symbol.\r
4771  */\r
4772 var RenameRequest;\r
4773 (function (RenameRequest) {\r
4774     RenameRequest.method = 'textDocument/rename';\r
4775     RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);\r
4776 })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));\r
4777 /**\r
4778  * A request to test and perform the setup necessary for a rename.\r
4779  */\r
4780 var PrepareRenameRequest;\r
4781 (function (PrepareRenameRequest) {\r
4782     PrepareRenameRequest.method = 'textDocument/prepareRename';\r
4783     PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);\r
4784 })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));\r
4785 /**\r
4786  * A request send from the client to the server to execute a command. The request might return\r
4787  * a workspace edit which the client will apply to the workspace.\r
4788  */\r
4789 var ExecuteCommandRequest;\r
4790 (function (ExecuteCommandRequest) {\r
4791     ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand');\r
4792 })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));\r
4793 /**\r
4794  * A request sent from the server to the client to modified certain resources.\r
4795  */\r
4796 var ApplyWorkspaceEditRequest;\r
4797 (function (ApplyWorkspaceEditRequest) {\r
4798     ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');\r
4799 })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));\r
4800
4801
4802 /***/ }),
4803 /* 20 */
4804 /***/ (function(module, exports, __webpack_require__) {
4805
4806 "use strict";
4807 /* --------------------------------------------------------------------------------------------\r
4808  * Copyright (c) Microsoft Corporation. All rights reserved.\r
4809  * Licensed under the MIT License. See License.txt in the project root for license information.\r
4810  * ------------------------------------------------------------------------------------------ */\r
4811 \r
4812 Object.defineProperty(exports, "__esModule", { value: true });\r
4813 function boolean(value) {\r
4814     return value === true || value === false;\r
4815 }\r
4816 exports.boolean = boolean;\r
4817 function string(value) {\r
4818     return typeof value === 'string' || value instanceof String;\r
4819 }\r
4820 exports.string = string;\r
4821 function number(value) {\r
4822     return typeof value === 'number' || value instanceof Number;\r
4823 }\r
4824 exports.number = number;\r
4825 function error(value) {\r
4826     return value instanceof Error;\r
4827 }\r
4828 exports.error = error;\r
4829 function func(value) {\r
4830     return typeof value === 'function';\r
4831 }\r
4832 exports.func = func;\r
4833 function array(value) {\r
4834     return Array.isArray(value);\r
4835 }\r
4836 exports.array = array;\r
4837 function stringArray(value) {\r
4838     return array(value) && value.every(elem => string(elem));\r
4839 }\r
4840 exports.stringArray = stringArray;\r
4841 function typedArray(value, check) {\r
4842     return Array.isArray(value) && value.every(check);\r
4843 }\r
4844 exports.typedArray = typedArray;\r
4845 function objectLiteral(value) {\r
4846     // Strictly speaking class instances pass this check as well. Since the LSP\r
4847     // doesn't use classes we ignore this for now. If we do we need to add something\r
4848     // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`\r
4849     return value !== null && typeof value === 'object';\r
4850 }\r
4851 exports.objectLiteral = objectLiteral;\r
4852
4853
4854 /***/ }),
4855 /* 21 */
4856 /***/ (function(module, exports, __webpack_require__) {
4857
4858 "use strict";
4859 /* --------------------------------------------------------------------------------------------\r
4860  * Copyright (c) Microsoft Corporation. All rights reserved.\r
4861  * Licensed under the MIT License. See License.txt in the project root for license information.\r
4862  * ------------------------------------------------------------------------------------------ */\r
4863 \r
4864 Object.defineProperty(exports, "__esModule", { value: true });\r
4865 const vscode_jsonrpc_1 = __webpack_require__(5);\r
4866 class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {\r
4867     constructor(method) {\r
4868         super(method);\r
4869     }\r
4870 }\r
4871 exports.ProtocolRequestType0 = ProtocolRequestType0;\r
4872 class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {\r
4873     constructor(method) {\r
4874         super(method);\r
4875     }\r
4876 }\r
4877 exports.ProtocolRequestType = ProtocolRequestType;\r
4878 class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {\r
4879     constructor(method) {\r
4880         super(method);\r
4881     }\r
4882 }\r
4883 exports.ProtocolNotificationType = ProtocolNotificationType;\r
4884 class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {\r
4885     constructor(method) {\r
4886         super(method);\r
4887     }\r
4888 }\r
4889 exports.ProtocolNotificationType0 = ProtocolNotificationType0;\r
4890
4891
4892 /***/ }),
4893 /* 22 */
4894 /***/ (function(module, exports, __webpack_require__) {
4895
4896 "use strict";
4897 /* --------------------------------------------------------------------------------------------\r
4898  * Copyright (c) Microsoft Corporation. All rights reserved.\r
4899  * Licensed under the MIT License. See License.txt in the project root for license information.\r
4900  * ------------------------------------------------------------------------------------------ */\r
4901 \r
4902 Object.defineProperty(exports, "__esModule", { value: true });\r
4903 const vscode_jsonrpc_1 = __webpack_require__(5);\r
4904 const messages_1 = __webpack_require__(21);\r
4905 // @ts-ignore: to avoid inlining LocatioLink as dynamic import\r
4906 let __noDynamicImport;\r
4907 /**\r
4908  * A request to resolve the implementation locations of a symbol at a given text\r
4909  * document position. The request's parameter is of type [TextDocumentPositioParams]\r
4910  * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a\r
4911  * Thenable that resolves to such.\r
4912  */\r
4913 var ImplementationRequest;\r
4914 (function (ImplementationRequest) {\r
4915     ImplementationRequest.method = 'textDocument/implementation';\r
4916     ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);\r
4917     /** @deprecated Use ImplementationRequest.type */\r
4918     ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4919 })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));\r
4920
4921
4922 /***/ }),
4923 /* 23 */
4924 /***/ (function(module, exports, __webpack_require__) {
4925
4926 "use strict";
4927 /* --------------------------------------------------------------------------------------------\r
4928  * Copyright (c) Microsoft Corporation. All rights reserved.\r
4929  * Licensed under the MIT License. See License.txt in the project root for license information.\r
4930  * ------------------------------------------------------------------------------------------ */\r
4931 \r
4932 Object.defineProperty(exports, "__esModule", { value: true });\r
4933 const vscode_jsonrpc_1 = __webpack_require__(5);\r
4934 const messages_1 = __webpack_require__(21);\r
4935 // @ts-ignore: to avoid inlining LocatioLink as dynamic import\r
4936 let __noDynamicImport;\r
4937 /**\r
4938  * A request to resolve the type definition locations of a symbol at a given text\r
4939  * document position. The request's parameter is of type [TextDocumentPositioParams]\r
4940  * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a\r
4941  * Thenable that resolves to such.\r
4942  */\r
4943 var TypeDefinitionRequest;\r
4944 (function (TypeDefinitionRequest) {\r
4945     TypeDefinitionRequest.method = 'textDocument/typeDefinition';\r
4946     TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);\r
4947     /** @deprecated Use TypeDefinitionRequest.type */\r
4948     TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4949 })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));\r
4950
4951
4952 /***/ }),
4953 /* 24 */
4954 /***/ (function(module, exports, __webpack_require__) {
4955
4956 "use strict";
4957 /* --------------------------------------------------------------------------------------------\r
4958  * Copyright (c) Microsoft Corporation. All rights reserved.\r
4959  * Licensed under the MIT License. See License.txt in the project root for license information.\r
4960  * ------------------------------------------------------------------------------------------ */\r
4961 \r
4962 Object.defineProperty(exports, "__esModule", { value: true });\r
4963 const messages_1 = __webpack_require__(21);\r
4964 /**\r
4965  * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.\r
4966  */\r
4967 var WorkspaceFoldersRequest;\r
4968 (function (WorkspaceFoldersRequest) {\r
4969     WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders');\r
4970 })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));\r
4971 /**\r
4972  * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace\r
4973  * folder configuration changes.\r
4974  */\r
4975 var DidChangeWorkspaceFoldersNotification;\r
4976 (function (DidChangeWorkspaceFoldersNotification) {\r
4977     DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders');\r
4978 })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));\r
4979
4980
4981 /***/ }),
4982 /* 25 */
4983 /***/ (function(module, exports, __webpack_require__) {
4984
4985 "use strict";
4986 /* --------------------------------------------------------------------------------------------\r
4987  * Copyright (c) Microsoft Corporation. All rights reserved.\r
4988  * Licensed under the MIT License. See License.txt in the project root for license information.\r
4989  * ------------------------------------------------------------------------------------------ */\r
4990 \r
4991 Object.defineProperty(exports, "__esModule", { value: true });\r
4992 const messages_1 = __webpack_require__(21);\r
4993 /**\r
4994  * The 'workspace/configuration' request is sent from the server to the client to fetch a certain\r
4995  * configuration setting.\r
4996  *\r
4997  * This pull model replaces the old push model were the client signaled configuration change via an\r
4998  * event. If the server still needs to react to configuration changes (since the server caches the\r
4999  * result of `workspace/configuration` requests) the server should register for an empty configuration\r
5000  * change event and empty the cache if such an event is received.\r
5001  */\r
5002 var ConfigurationRequest;\r
5003 (function (ConfigurationRequest) {\r
5004     ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration');\r
5005 })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));\r
5006
5007
5008 /***/ }),
5009 /* 26 */
5010 /***/ (function(module, exports, __webpack_require__) {
5011
5012 "use strict";
5013 /* --------------------------------------------------------------------------------------------\r
5014  * Copyright (c) Microsoft Corporation. All rights reserved.\r
5015  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5016  * ------------------------------------------------------------------------------------------ */\r
5017 \r
5018 Object.defineProperty(exports, "__esModule", { value: true });\r
5019 const vscode_jsonrpc_1 = __webpack_require__(5);\r
5020 const messages_1 = __webpack_require__(21);\r
5021 /**\r
5022  * A request to list all color symbols found in a given text document. The request's\r
5023  * parameter is of type [DocumentColorParams](#DocumentColorParams) the\r
5024  * response is of type [ColorInformation[]](#ColorInformation) or a Thenable\r
5025  * that resolves to such.\r
5026  */\r
5027 var DocumentColorRequest;\r
5028 (function (DocumentColorRequest) {\r
5029     DocumentColorRequest.method = 'textDocument/documentColor';\r
5030     DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);\r
5031     /** @deprecated Use DocumentColorRequest.type */\r
5032     DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
5033 })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));\r
5034 /**\r
5035  * A request to list all presentation for a color. The request's\r
5036  * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the\r
5037  * response is of type [ColorInformation[]](#ColorInformation) or a Thenable\r
5038  * that resolves to such.\r
5039  */\r
5040 var ColorPresentationRequest;\r
5041 (function (ColorPresentationRequest) {\r
5042     ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation');\r
5043 })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));\r
5044
5045
5046 /***/ }),
5047 /* 27 */
5048 /***/ (function(module, exports, __webpack_require__) {
5049
5050 "use strict";
5051 \r
5052 /*---------------------------------------------------------------------------------------------\r
5053  *  Copyright (c) Microsoft Corporation. All rights reserved.\r
5054  *  Licensed under the MIT License. See License.txt in the project root for license information.\r
5055  *--------------------------------------------------------------------------------------------*/\r
5056 Object.defineProperty(exports, "__esModule", { value: true });\r
5057 const vscode_jsonrpc_1 = __webpack_require__(5);\r
5058 const messages_1 = __webpack_require__(21);\r
5059 /**\r
5060  * Enum of known range kinds\r
5061  */\r
5062 var FoldingRangeKind;\r
5063 (function (FoldingRangeKind) {\r
5064     /**\r
5065      * Folding range for a comment\r
5066      */\r
5067     FoldingRangeKind["Comment"] = "comment";\r
5068     /**\r
5069      * Folding range for a imports or includes\r
5070      */\r
5071     FoldingRangeKind["Imports"] = "imports";\r
5072     /**\r
5073      * Folding range for a region (e.g. `#region`)\r
5074      */\r
5075     FoldingRangeKind["Region"] = "region";\r
5076 })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));\r
5077 /**\r
5078  * A request to provide folding ranges in a document. The request's\r
5079  * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the\r
5080  * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable\r
5081  * that resolves to such.\r
5082  */\r
5083 var FoldingRangeRequest;\r
5084 (function (FoldingRangeRequest) {\r
5085     FoldingRangeRequest.method = 'textDocument/foldingRange';\r
5086     FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);\r
5087     /** @deprecated Use FoldingRangeRequest.type */\r
5088     FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
5089 })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));\r
5090
5091
5092 /***/ }),
5093 /* 28 */
5094 /***/ (function(module, exports, __webpack_require__) {
5095
5096 "use strict";
5097 /* --------------------------------------------------------------------------------------------\r
5098  * Copyright (c) Microsoft Corporation. All rights reserved.\r
5099  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5100  * ------------------------------------------------------------------------------------------ */\r
5101 \r
5102 Object.defineProperty(exports, "__esModule", { value: true });\r
5103 const vscode_jsonrpc_1 = __webpack_require__(5);\r
5104 const messages_1 = __webpack_require__(21);\r
5105 // @ts-ignore: to avoid inlining LocatioLink as dynamic import\r
5106 let __noDynamicImport;\r
5107 /**\r
5108  * A request to resolve the type definition locations of a symbol at a given text\r
5109  * document position. The request's parameter is of type [TextDocumentPositioParams]\r
5110  * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)\r
5111  * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves\r
5112  * to such.\r
5113  */\r
5114 var DeclarationRequest;\r
5115 (function (DeclarationRequest) {\r
5116     DeclarationRequest.method = 'textDocument/declaration';\r
5117     DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);\r
5118     /** @deprecated Use DeclarationRequest.type */\r
5119     DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
5120 })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));\r
5121
5122
5123 /***/ }),
5124 /* 29 */
5125 /***/ (function(module, exports, __webpack_require__) {
5126
5127 "use strict";
5128 \r
5129 /*---------------------------------------------------------------------------------------------\r
5130  *  Copyright (c) Microsoft Corporation. All rights reserved.\r
5131  *  Licensed under the MIT License. See License.txt in the project root for license information.\r
5132  *--------------------------------------------------------------------------------------------*/\r
5133 Object.defineProperty(exports, "__esModule", { value: true });\r
5134 const vscode_jsonrpc_1 = __webpack_require__(5);\r
5135 const messages_1 = __webpack_require__(21);\r
5136 /**\r
5137  * A request to provide selection ranges in a document. The request's\r
5138  * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the\r
5139  * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable\r
5140  * that resolves to such.\r
5141  */\r
5142 var SelectionRangeRequest;\r
5143 (function (SelectionRangeRequest) {\r
5144     SelectionRangeRequest.method = 'textDocument/selectionRange';\r
5145     SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);\r
5146     /** @deprecated  Use SelectionRangeRequest.type */\r
5147     SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
5148 })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));\r
5149
5150
5151 /***/ }),
5152 /* 30 */
5153 /***/ (function(module, exports, __webpack_require__) {
5154
5155 "use strict";
5156 /* --------------------------------------------------------------------------------------------\r
5157  * Copyright (c) Microsoft Corporation. All rights reserved.\r
5158  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5159  * ------------------------------------------------------------------------------------------ */\r
5160 \r
5161 Object.defineProperty(exports, "__esModule", { value: true });\r
5162 const vscode_jsonrpc_1 = __webpack_require__(5);\r
5163 const messages_1 = __webpack_require__(21);\r
5164 var WorkDoneProgress;\r
5165 (function (WorkDoneProgress) {\r
5166     WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();\r
5167 })(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));\r
5168 /**\r
5169  * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress\r
5170  * reporting from the server.\r
5171  */\r
5172 var WorkDoneProgressCreateRequest;\r
5173 (function (WorkDoneProgressCreateRequest) {\r
5174     WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create');\r
5175 })(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));\r
5176 /**\r
5177  * The `window/workDoneProgress/cancel` notification is sent from  the client to the server to cancel a progress\r
5178  * initiated on the server side.\r
5179  */\r
5180 var WorkDoneProgressCancelNotification;\r
5181 (function (WorkDoneProgressCancelNotification) {\r
5182     WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel');\r
5183 })(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));\r
5184
5185
5186 /***/ }),
5187 /* 31 */
5188 /***/ (function(module, exports, __webpack_require__) {
5189
5190 "use strict";
5191 /* --------------------------------------------------------------------------------------------\r
5192  * Copyright (c) TypeFox and others. All rights reserved.\r
5193  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5194  * ------------------------------------------------------------------------------------------ */\r
5195 \r
5196 Object.defineProperty(exports, "__esModule", { value: true });\r
5197 const messages_1 = __webpack_require__(21);\r
5198 /**\r
5199  * A request to result a `CallHierarchyItem` in a document at a given position.\r
5200  * Can be used as an input to a incoming or outgoing call hierarchy.\r
5201  *\r
5202  * @since 3.16.0 - Proposed state\r
5203  */\r
5204 var CallHierarchyPrepareRequest;\r
5205 (function (CallHierarchyPrepareRequest) {\r
5206     CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';\r
5207     CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);\r
5208 })(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));\r
5209 /**\r
5210  * A request to resolve the incoming calls for a given `CallHierarchyItem`.\r
5211  *\r
5212  * @since 3.16.0 - Proposed state\r
5213  */\r
5214 var CallHierarchyIncomingCallsRequest;\r
5215 (function (CallHierarchyIncomingCallsRequest) {\r
5216     CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';\r
5217     CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);\r
5218 })(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));\r
5219 /**\r
5220  * A request to resolve the outgoing calls for a given `CallHierarchyItem`.\r
5221  *\r
5222  * @since 3.16.0 - Proposed state\r
5223  */\r
5224 var CallHierarchyOutgoingCallsRequest;\r
5225 (function (CallHierarchyOutgoingCallsRequest) {\r
5226     CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';\r
5227     CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);\r
5228 })(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));\r
5229
5230
5231 /***/ }),
5232 /* 32 */
5233 /***/ (function(module, exports, __webpack_require__) {
5234
5235 "use strict";
5236 /* --------------------------------------------------------------------------------------------\r
5237  * Copyright (c) Microsoft Corporation. All rights reserved.\r
5238  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5239  * ------------------------------------------------------------------------------------------ */\r
5240 \r
5241 Object.defineProperty(exports, "__esModule", { value: true });\r
5242 const messages_1 = __webpack_require__(21);\r
5243 /**\r
5244  * A set of predefined token types. This set is not fixed\r
5245  * an clients can specify additional token types via the\r
5246  * corresponding client capabilities.\r
5247  *\r
5248  * @since 3.16.0 - Proposed state\r
5249  */\r
5250 var SemanticTokenTypes;\r
5251 (function (SemanticTokenTypes) {\r
5252     SemanticTokenTypes["comment"] = "comment";\r
5253     SemanticTokenTypes["keyword"] = "keyword";\r
5254     SemanticTokenTypes["string"] = "string";\r
5255     SemanticTokenTypes["number"] = "number";\r
5256     SemanticTokenTypes["regexp"] = "regexp";\r
5257     SemanticTokenTypes["operator"] = "operator";\r
5258     SemanticTokenTypes["namespace"] = "namespace";\r
5259     SemanticTokenTypes["type"] = "type";\r
5260     SemanticTokenTypes["struct"] = "struct";\r
5261     SemanticTokenTypes["class"] = "class";\r
5262     SemanticTokenTypes["interface"] = "interface";\r
5263     SemanticTokenTypes["enum"] = "enum";\r
5264     SemanticTokenTypes["typeParameter"] = "typeParameter";\r
5265     SemanticTokenTypes["function"] = "function";\r
5266     SemanticTokenTypes["member"] = "member";\r
5267     SemanticTokenTypes["property"] = "property";\r
5268     SemanticTokenTypes["macro"] = "macro";\r
5269     SemanticTokenTypes["variable"] = "variable";\r
5270     SemanticTokenTypes["parameter"] = "parameter";\r
5271     SemanticTokenTypes["label"] = "label";\r
5272 })(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {}));\r
5273 /**\r
5274  * A set of predefined token modifiers. This set is not fixed\r
5275  * an clients can specify additional token types via the\r
5276  * corresponding client capabilities.\r
5277  *\r
5278  * @since 3.16.0 - Proposed state\r
5279  */\r
5280 var SemanticTokenModifiers;\r
5281 (function (SemanticTokenModifiers) {\r
5282     SemanticTokenModifiers["documentation"] = "documentation";\r
5283     SemanticTokenModifiers["declaration"] = "declaration";\r
5284     SemanticTokenModifiers["definition"] = "definition";\r
5285     SemanticTokenModifiers["reference"] = "reference";\r
5286     SemanticTokenModifiers["static"] = "static";\r
5287     SemanticTokenModifiers["abstract"] = "abstract";\r
5288     SemanticTokenModifiers["deprecated"] = "deprecated";\r
5289     SemanticTokenModifiers["async"] = "async";\r
5290     SemanticTokenModifiers["volatile"] = "volatile";\r
5291     SemanticTokenModifiers["readonly"] = "readonly";\r
5292 })(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {}));\r
5293 /**\r
5294  * @since 3.16.0 - Proposed state\r
5295  */\r
5296 var SemanticTokens;\r
5297 (function (SemanticTokens) {\r
5298     function is(value) {\r
5299         const candidate = value;\r
5300         return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&\r
5301             Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');\r
5302     }\r
5303     SemanticTokens.is = is;\r
5304 })(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {}));\r
5305 /**\r
5306  * @since 3.16.0 - Proposed state\r
5307  */\r
5308 var SemanticTokensRequest;\r
5309 (function (SemanticTokensRequest) {\r
5310     SemanticTokensRequest.method = 'textDocument/semanticTokens';\r
5311     SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);\r
5312 })(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));\r
5313 /**\r
5314  * @since 3.16.0 - Proposed state\r
5315  */\r
5316 var SemanticTokensEditsRequest;\r
5317 (function (SemanticTokensEditsRequest) {\r
5318     SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits';\r
5319     SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method);\r
5320 })(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {}));\r
5321 /**\r
5322  * @since 3.16.0 - Proposed state\r
5323  */\r
5324 var SemanticTokensRangeRequest;\r
5325 (function (SemanticTokensRangeRequest) {\r
5326     SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';\r
5327     SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);\r
5328 })(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));\r
5329
5330
5331 /***/ }),
5332 /* 33 */,
5333 /* 34 */,
5334 /* 35 */,
5335 /* 36 */,
5336 /* 37 */,
5337 /* 38 */
5338 /***/ (function(module, exports, __webpack_require__) {
5339
5340 "use strict";
5341 /* --------------------------------------------------------------------------------------------
5342  * Copyright (c) Microsoft Corporation. All rights reserved.
5343  * Licensed under the MIT License. See License.txt in the project root for license information.
5344  * ------------------------------------------------------------------------------------------ */
5345
5346 var __importStar = (this && this.__importStar) || function (mod) {
5347     if (mod && mod.__esModule) return mod;
5348     var result = {};
5349     if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
5350     result["default"] = mod;
5351     return result;
5352 };
5353 Object.defineProperty(exports, "__esModule", { value: true });
5354 const os = __importStar(__webpack_require__(14));
5355 const path = __importStar(__webpack_require__(3));
5356 const vscode_languageserver_1 = __webpack_require__(39);
5357 const vscode_uri_1 = __webpack_require__(50);
5358 const types_1 = __webpack_require__(51);
5359 const util_1 = __webpack_require__(52);
5360 const vscode_languageserver_textdocument_1 = __webpack_require__(54);
5361 const requireFunc =  true ? require : undefined;
5362 var CommandIds;
5363 (function (CommandIds) {
5364     CommandIds.applySingleFix = 'eslint.applySingleFix';
5365     CommandIds.applySameFixes = 'eslint.applySameFixes';
5366     CommandIds.applyAllFixes = 'eslint.applyAllFixes';
5367     CommandIds.applyAutoFix = 'eslint.applyAutoFix';
5368     CommandIds.applyDisableLine = 'eslint.applyDisableLine';
5369     CommandIds.applyDisableFile = 'eslint.applyDisableFile';
5370     CommandIds.openRuleDoc = 'eslint.openRuleDoc';
5371 })(CommandIds || (CommandIds = {}));
5372 var OpenESLintDocRequest;
5373 (function (OpenESLintDocRequest) {
5374     OpenESLintDocRequest.type = new vscode_languageserver_1.RequestType('eslint/openDoc');
5375 })(OpenESLintDocRequest || (OpenESLintDocRequest = {}));
5376 var Status;
5377 (function (Status) {
5378     Status[Status["ok"] = 1] = "ok";
5379     Status[Status["warn"] = 2] = "warn";
5380     Status[Status["error"] = 3] = "error";
5381 })(Status || (Status = {}));
5382 var StatusNotification;
5383 (function (StatusNotification) {
5384     StatusNotification.type = new vscode_languageserver_1.NotificationType('eslint/status');
5385 })(StatusNotification || (StatusNotification = {}));
5386 var NoConfigRequest;
5387 (function (NoConfigRequest) {
5388     NoConfigRequest.type = new vscode_languageserver_1.RequestType('eslint/noConfig');
5389 })(NoConfigRequest || (NoConfigRequest = {}));
5390 var NoESLintLibraryRequest;
5391 (function (NoESLintLibraryRequest) {
5392     NoESLintLibraryRequest.type = new vscode_languageserver_1.RequestType('eslint/noLibrary');
5393 })(NoESLintLibraryRequest || (NoESLintLibraryRequest = {}));
5394 class CodeActionResult {
5395     constructor() {
5396         this._actions = new Map();
5397     }
5398     get(ruleId) {
5399         let result = this._actions.get(ruleId);
5400         if (result === undefined) {
5401             result = { fixes: [] };
5402             this._actions.set(ruleId, result);
5403         }
5404         return result;
5405     }
5406     set fixAll(action) {
5407         this._fixAll = action;
5408     }
5409     all() {
5410         let result = [];
5411         for (let actions of this._actions.values()) {
5412             result.push(...actions.fixes);
5413             if (actions.disable) {
5414                 result.push(actions.disable);
5415             }
5416             if (actions.fixAll) {
5417                 result.push(actions.fixAll);
5418             }
5419             if (actions.disableFile) {
5420                 result.push(actions.disableFile);
5421             }
5422             if (actions.showDocumentation) {
5423                 result.push(actions.showDocumentation);
5424             }
5425         }
5426         if (this._fixAll !== undefined) {
5427             result.push(this._fixAll);
5428         }
5429         return result;
5430     }
5431     get length() {
5432         let result = 0;
5433         for (let actions of this._actions.values()) {
5434             result += actions.fixes.length;
5435         }
5436         return result;
5437     }
5438 }
5439 function makeDiagnostic(problem) {
5440     let message = problem.ruleId != null
5441         ? `${problem.message} (${problem.ruleId})`
5442         : `${problem.message}`;
5443     let startLine = Math.max(0, problem.line - 1);
5444     let startChar = Math.max(0, problem.column - 1);
5445     let endLine = problem.endLine != null ? Math.max(0, problem.endLine - 1) : startLine;
5446     let endChar = problem.endColumn != null ? Math.max(0, problem.endColumn - 1) : startChar;
5447     return {
5448         message,
5449         severity: convertSeverity(problem.severity),
5450         source: 'eslint',
5451         range: {
5452             start: { line: startLine, character: startChar },
5453             end: { line: endLine, character: endChar }
5454         },
5455         code: problem.ruleId
5456     };
5457 }
5458 function computeKey(diagnostic) {
5459     let range = diagnostic.range;
5460     return `[${range.start.line},${range.start.character},${range.end.line},${range.end.character}]-${diagnostic.code}`;
5461 }
5462 let codeActions = new Map();
5463 function recordCodeAction(document, diagnostic, problem) {
5464     if (!problem.ruleId) {
5465         return;
5466     }
5467     let uri = document.uri;
5468     let edits = codeActions.get(uri);
5469     if (!edits) {
5470         edits = new Map();
5471         codeActions.set(uri, edits);
5472     }
5473     edits.set(computeKey(diagnostic), { label: `Fix this ${problem.ruleId} problem`, documentVersion: document.version, ruleId: problem.ruleId, edit: problem.fix, line: problem.line });
5474 }
5475 function convertSeverity(severity) {
5476     switch (severity) {
5477         // Eslint 1 is warning
5478         case 1:
5479             return vscode_languageserver_1.DiagnosticSeverity.Warning;
5480         case 2:
5481             return vscode_languageserver_1.DiagnosticSeverity.Error;
5482         default:
5483             return vscode_languageserver_1.DiagnosticSeverity.Error;
5484     }
5485 }
5486 const exitCalled = new vscode_languageserver_1.NotificationType('eslint/exitCalled');
5487 const nodeExit = process.exit;
5488 process.exit = ((code) => {
5489     let stack = new Error('stack');
5490     connection.sendNotification(exitCalled, [code ? code : 0, stack.stack]);
5491     setTimeout(() => {
5492         nodeExit(code);
5493     }, 1000);
5494 });
5495 process.on('uncaughtException', (error) => {
5496     let message;
5497     if (error) {
5498         if (typeof error.stack === 'string') {
5499             message = error.stack;
5500         }
5501         else if (typeof error.message === 'string') {
5502             message = error.message;
5503         }
5504         else if (typeof error === 'string') {
5505             message = error;
5506         }
5507         if (!message) {
5508             try {
5509                 message = JSON.stringify(error, undefined, 4);
5510             }
5511             catch (e) {
5512                 // Should not happen.
5513             }
5514         }
5515     }
5516     connection.console.error(`Uncaught exception recevied.
5517   ${message || ''}`);
5518 });
5519 let connection = vscode_languageserver_1.createConnection();
5520 connection.console.info(`ESLint server running in node ${process.version}`);
5521 let documents = new vscode_languageserver_1.TextDocuments(vscode_languageserver_textdocument_1.TextDocument);
5522 let _globalNpmPath;
5523 function globalNpmPath() {
5524     if (_globalNpmPath === void 0) {
5525         _globalNpmPath = vscode_languageserver_1.Files.resolveGlobalNodePath(trace);
5526         if (_globalNpmPath === void 0) {
5527             _globalNpmPath = null;
5528         }
5529     }
5530     if (_globalNpmPath === null) {
5531         return undefined;
5532     }
5533     return _globalNpmPath;
5534 }
5535 let _globalYarnPath;
5536 function globalYarnPath() {
5537     if (_globalYarnPath === void 0) {
5538         _globalYarnPath = vscode_languageserver_1.Files.resolveGlobalYarnPath(trace);
5539         if (_globalYarnPath === void 0) {
5540             _globalYarnPath = null;
5541         }
5542     }
5543     if (_globalYarnPath === null) {
5544         return undefined;
5545     }
5546     return _globalYarnPath;
5547 }
5548 let path2Library = new Map();
5549 let document2Settings = new Map();
5550 let ruleDocData = {
5551     handled: new Set(),
5552     urls: new Map()
5553 };
5554 function resolveSettings(document) {
5555     let uri = document.uri;
5556     let resultPromise = document2Settings.get(uri);
5557     if (resultPromise) {
5558         return resultPromise;
5559     }
5560     resultPromise = connection.workspace
5561         .getConfiguration({ scopeUri: uri, section: '' })
5562         .then((settings) => {
5563         let nodePath;
5564         if (settings.nodePath) {
5565             nodePath = settings.nodePath;
5566             if (nodePath.startsWith('~')) {
5567                 nodePath = nodePath.replace(/^~/, os.homedir());
5568             }
5569             if (!path.isAbsolute(nodePath)) {
5570                 nodePath = path.join(vscode_uri_1.URI.parse(settings.workspaceFolder.uri).fsPath, nodePath);
5571             }
5572         }
5573         let resolvedGlobalPackageManagerPath;
5574         if (settings.packageManager === 'npm') {
5575             resolvedGlobalPackageManagerPath = globalNpmPath();
5576         }
5577         else if (settings.packageManager === 'yarn') {
5578             resolvedGlobalPackageManagerPath = globalYarnPath();
5579         }
5580         let uri = vscode_uri_1.URI.parse(document.uri);
5581         let promise;
5582         let directory;
5583         if (uri.scheme === 'file') {
5584             directory = path.dirname(uri.fsPath);
5585         }
5586         else {
5587             directory = settings.workspaceFolder ? vscode_uri_1.URI.parse(settings.workspaceFolder.uri).fsPath : undefined;
5588         }
5589         if (nodePath !== undefined) {
5590             promise = vscode_languageserver_1.Files.resolve('eslint', nodePath, nodePath, trace).then(undefined, () => {
5591                 return vscode_languageserver_1.Files.resolve('eslint', resolvedGlobalPackageManagerPath, directory, trace);
5592             });
5593         }
5594         else {
5595             promise = vscode_languageserver_1.Files.resolve('eslint', resolvedGlobalPackageManagerPath, directory, trace);
5596         }
5597         return promise.then(path => {
5598             let library = path2Library.get(path);
5599             if (!library) {
5600                 library = requireFunc(path);
5601                 if (!library.CLIEngine) {
5602                     settings.validate = false;
5603                     connection.console.error(`The eslint library loaded from ${path} doesn\'t export a CLIEngine. You need at least eslint@1.0.0`);
5604                 }
5605                 else {
5606                     connection.console.info(`ESLint library loaded from: ${path}`);
5607                     settings.library = library;
5608                 }
5609                 path2Library.set(path, library);
5610             }
5611             else {
5612                 settings.library = library;
5613             }
5614             return settings;
5615         }, () => {
5616             settings.validate = false;
5617             connection.sendRequest(NoESLintLibraryRequest.type, {
5618                 source: { uri: document.uri }
5619             });
5620             return settings;
5621         });
5622     });
5623     document2Settings.set(uri, resultPromise);
5624     return resultPromise;
5625 }
5626 var Request;
5627 (function (Request) {
5628     function is(value) {
5629         let candidate = value;
5630         return (candidate &&
5631             !!candidate.token &&
5632             !!candidate.resolve &&
5633             !!candidate.reject);
5634     }
5635     Request.is = is;
5636 })(Request || (Request = {}));
5637 var Thenable;
5638 (function (Thenable) {
5639     function is(value) {
5640         let candidate = value;
5641         return candidate && typeof candidate.then === 'function';
5642     }
5643     Thenable.is = is;
5644 })(Thenable || (Thenable = {}));
5645 class BufferedMessageQueue {
5646     constructor(connection) {
5647         this.connection = connection;
5648         this.queue = [];
5649         this.requestHandlers = new Map();
5650         this.notificationHandlers = new Map();
5651     }
5652     registerRequest(type, handler, versionProvider) {
5653         this.connection.onRequest(type, (params, token) => {
5654             return new Promise((resolve, reject) => {
5655                 this.queue.push({
5656                     method: type.method,
5657                     params,
5658                     documentVersion: versionProvider
5659                         ? versionProvider(params)
5660                         : undefined,
5661                     resolve,
5662                     reject,
5663                     token
5664                 });
5665                 this.trigger();
5666             });
5667         });
5668         this.requestHandlers.set(type.method, { handler, versionProvider });
5669     }
5670     registerNotification(type, handler, versionProvider) {
5671         connection.onNotification(type, params => {
5672             this.queue.push({
5673                 method: type.method,
5674                 params,
5675                 documentVersion: versionProvider ? versionProvider(params) : undefined
5676             });
5677             this.trigger();
5678         });
5679         this.notificationHandlers.set(type.method, { handler, versionProvider });
5680     }
5681     addNotificationMessage(type, params, version) {
5682         this.queue.push({
5683             method: type.method,
5684             params,
5685             documentVersion: version
5686         });
5687         this.trigger();
5688     }
5689     onNotification(type, handler, versionProvider) {
5690         this.notificationHandlers.set(type.method, { handler, versionProvider });
5691     }
5692     trigger() {
5693         if (this.timer || this.queue.length === 0) {
5694             return;
5695         }
5696         this.timer = setImmediate(() => {
5697             this.timer = undefined;
5698             this.processQueue();
5699         });
5700     }
5701     processQueue() {
5702         let message = this.queue.shift();
5703         if (!message) {
5704             return;
5705         }
5706         if (Request.is(message)) {
5707             let requestMessage = message;
5708             if (requestMessage.token.isCancellationRequested) {
5709                 requestMessage.reject(
5710                 // tslint:disable-next-line: no-inferred-empty-object-type
5711                 new vscode_languageserver_1.ResponseError(vscode_languageserver_1.ErrorCodes.RequestCancelled, 'Request got cancelled'));
5712                 return;
5713             }
5714             let elem = this.requestHandlers.get(requestMessage.method);
5715             if (elem.versionProvider &&
5716                 requestMessage.documentVersion !== void 0 &&
5717                 requestMessage.documentVersion !==
5718                     elem.versionProvider(requestMessage.params)) {
5719                 requestMessage.reject(
5720                 // tslint:disable-next-line: no-inferred-empty-object-type
5721                 new vscode_languageserver_1.ResponseError(vscode_languageserver_1.ErrorCodes.RequestCancelled, 'Request got cancelled'));
5722                 return;
5723             }
5724             let result = elem.handler(requestMessage.params, requestMessage.token);
5725             if (Thenable.is(result)) {
5726                 result.then(value => {
5727                     requestMessage.resolve(value);
5728                 }, error => {
5729                     requestMessage.reject(error);
5730                 });
5731             }
5732             else {
5733                 requestMessage.resolve(result);
5734             }
5735         }
5736         else {
5737             let notificationMessage = message;
5738             let elem = this.notificationHandlers.get(notificationMessage.method);
5739             if (elem.versionProvider &&
5740                 notificationMessage.documentVersion !== void 0 &&
5741                 notificationMessage.documentVersion !==
5742                     elem.versionProvider(notificationMessage.params)) {
5743                 return;
5744             }
5745             elem.handler(notificationMessage.params);
5746         }
5747         this.trigger();
5748     }
5749 }
5750 let messageQueue = new BufferedMessageQueue(connection);
5751 var ValidateNotification;
5752 (function (ValidateNotification) {
5753     ValidateNotification.type = new vscode_languageserver_1.NotificationType('eslint/validate');
5754 })(ValidateNotification || (ValidateNotification = {}));
5755 messageQueue.onNotification(ValidateNotification.type, document => {
5756     validateSingle(document, true);
5757 }, (document) => {
5758     return document.version;
5759 });
5760 // The documents manager listen for text document create, change
5761 // and close on the connection
5762 documents.listen(connection);
5763 documents.onDidOpen(event => {
5764     resolveSettings(event.document).then(settings => {
5765         if (!settings.validate) {
5766             return;
5767         }
5768         if (settings.run === 'onSave') {
5769             messageQueue.addNotificationMessage(ValidateNotification.type, event.document, event.document.version);
5770         }
5771     });
5772 });
5773 // A text document has changed. Validate the document according the run setting.
5774 documents.onDidChangeContent(event => {
5775     resolveSettings(event.document).then(settings => {
5776         if (!settings.validate || settings.run !== 'onType') {
5777             return;
5778         }
5779         messageQueue.addNotificationMessage(ValidateNotification.type, event.document, event.document.version);
5780     });
5781 });
5782 documents.onWillSaveWaitUntil(event => {
5783     if (event.reason === vscode_languageserver_1.TextDocumentSaveReason.AfterDelay) {
5784         return [];
5785     }
5786     let document = event.document;
5787     return resolveSettings(document).then(settings => {
5788         if (!settings.autoFixOnSave) {
5789             return [];
5790         }
5791         // If we validate on save and want to apply fixes on will save
5792         // we need to validate the file.
5793         if (settings.run === 'onSave') {
5794             // Do not queue this since we want to get the fixes as fast as possible.
5795             return validateSingle(document, false).then(() => util_1.getAllFixEdits(document, settings));
5796         }
5797         else {
5798             return util_1.getAllFixEdits(document, settings);
5799         }
5800     });
5801 });
5802 // A text document has been saved. Validate the document according the run setting.
5803 documents.onDidSave(event => {
5804     resolveSettings(event.document).then(settings => {
5805         if (!settings.validate || settings.run !== 'onSave') {
5806             return;
5807         }
5808         messageQueue.addNotificationMessage(ValidateNotification.type, event.document, event.document.version);
5809     });
5810 });
5811 documents.onDidClose(event => {
5812     resolveSettings(event.document).then(settings => {
5813         let uri = event.document.uri;
5814         document2Settings.delete(uri);
5815         codeActions.delete(uri);
5816         if (settings.validate) {
5817             connection.sendDiagnostics({ uri, diagnostics: [] });
5818         }
5819     });
5820 });
5821 function environmentChanged() {
5822     document2Settings.clear();
5823     for (let document of documents.all()) {
5824         messageQueue.addNotificationMessage(ValidateNotification.type, document, document.version);
5825     }
5826 }
5827 function trace(message, verbose) {
5828     connection.tracer.log(message, verbose);
5829 }
5830 connection.onInitialize(_params => {
5831     return {
5832         capabilities: {
5833             textDocumentSync: {
5834                 openClose: true,
5835                 change: vscode_languageserver_1.TextDocumentSyncKind.Full,
5836                 willSaveWaitUntil: true,
5837                 save: {
5838                     includeText: false
5839                 }
5840             },
5841             codeActionProvider: true,
5842             executeCommandProvider: {
5843                 commands: [
5844                     CommandIds.applySingleFix,
5845                     CommandIds.applySameFixes,
5846                     CommandIds.applyAllFixes,
5847                     CommandIds.applyAutoFix,
5848                     CommandIds.applyDisableLine,
5849                     CommandIds.applyDisableFile,
5850                     CommandIds.openRuleDoc,
5851                 ]
5852             }
5853         }
5854     };
5855 });
5856 connection.onInitialized(() => {
5857     connection.client.register(vscode_languageserver_1.DidChangeConfigurationNotification.type, undefined);
5858 });
5859 messageQueue.registerNotification(vscode_languageserver_1.DidChangeConfigurationNotification.type, _params => {
5860     environmentChanged();
5861 });
5862 // messageQueue.registerNotification(
5863 //   DidChangeWorkspaceFoldersNotification.type,
5864 //   _params => {
5865 //     environmentChanged()
5866 //   }
5867 // )
5868 const singleErrorHandlers = [
5869     tryHandleNoConfig,
5870     tryHandleConfigError,
5871     tryHandleMissingModule,
5872     showErrorMessage
5873 ];
5874 function validateSingle(document, publishDiagnostics = true) {
5875     // We validate document in a queue but open / close documents directly. So we need to deal with the
5876     // fact that a document might be gone from the server.
5877     if (!documents.get(document.uri)) {
5878         return Promise.resolve(undefined);
5879     }
5880     return resolveSettings(document).then(settings => {
5881         if (!settings.validate) {
5882             return;
5883         }
5884         try {
5885             validate(document, settings, publishDiagnostics);
5886             connection.sendNotification(StatusNotification.type, { state: Status.ok });
5887         }
5888         catch (err) {
5889             let status;
5890             for (let handler of singleErrorHandlers) {
5891                 status = handler(err, document, settings.library);
5892                 if (status) {
5893                     break;
5894                 }
5895             }
5896             status = status || Status.error;
5897             connection.sendNotification(StatusNotification.type, { state: status });
5898         }
5899     });
5900 }
5901 function validateMany(documents) {
5902     documents.forEach(document => {
5903         messageQueue.addNotificationMessage(ValidateNotification.type, document, document.version);
5904     });
5905 }
5906 function getMessage(err, document) {
5907     let result = null;
5908     if (typeof err.message === 'string' || err.message instanceof String) {
5909         result = err.message;
5910         result = result.replace(/\r?\n/g, ' ');
5911         if (/^CLI: /.test(result)) {
5912             result = result.substr(5);
5913         }
5914     }
5915     else {
5916         result = `An unknown error occured while validating document: ${document.uri}`;
5917     }
5918     return result;
5919 }
5920 function validate(document, settings, publishDiagnostics = true) {
5921     const uri = document.uri;
5922     const content = document.getText();
5923     const newOptions = Object.assign(Object.create(null), settings.options);
5924     util_1.executeInWorkspaceDirectory(document, settings, newOptions, (file, options) => {
5925         const cli = new settings.library.CLIEngine(options);
5926         // Clean previously computed code actions.
5927         codeActions.delete(uri);
5928         const report = cli.executeOnText(content, file);
5929         const diagnostics = [];
5930         if (report && report.results && Array.isArray(report.results) && report.results.length > 0) {
5931             const docReport = report.results[0];
5932             if (docReport.messages && Array.isArray(docReport.messages)) {
5933                 docReport.messages.forEach(problem => {
5934                     if (problem) {
5935                         const isWarning = convertSeverity(problem.severity) === vscode_languageserver_1.DiagnosticSeverity.Warning;
5936                         if (settings.quiet && isWarning) {
5937                             // Filter out warnings when quiet mode is enabled
5938                             return;
5939                         }
5940                         const diagnostic = makeDiagnostic(problem);
5941                         diagnostics.push(diagnostic);
5942                         if (settings.autoFix) {
5943                             if (typeof cli.getRules === 'function' && problem.ruleId !== undefined && problem.fix !== undefined) {
5944                                 const rule = cli.getRules().get(problem.ruleId);
5945                                 if (rule !== undefined && rule.meta && typeof rule.meta.fixable == 'string') {
5946                                     recordCodeAction(document, diagnostic, problem);
5947                                 }
5948                             }
5949                             else {
5950                                 recordCodeAction(document, diagnostic, problem);
5951                             }
5952                         }
5953                     }
5954                 });
5955             }
5956         }
5957         if (publishDiagnostics) {
5958             connection.sendDiagnostics({ uri, diagnostics });
5959         }
5960         // cache documentation urls for all rules
5961         if (typeof cli.getRules === 'function' && !ruleDocData.handled.has(uri)) {
5962             ruleDocData.handled.add(uri);
5963             cli.getRules().forEach((rule, key) => {
5964                 if (rule.meta && rule.meta.docs && types_1.Is.string(rule.meta.docs.url)) {
5965                     ruleDocData.urls.set(key, rule.meta.docs.url);
5966                 }
5967             });
5968         }
5969     });
5970 }
5971 let noConfigReported = new Map();
5972 function isNoConfigFoundError(error) {
5973     let candidate = error;
5974     return (candidate.messageTemplate === 'no-config-found' ||
5975         candidate.message === 'No ESLint configuration found.');
5976 }
5977 function tryHandleNoConfig(error, document, library) {
5978     if (!isNoConfigFoundError(error)) {
5979         return undefined;
5980     }
5981     if (!noConfigReported.has(document.uri)) {
5982         connection
5983             .sendRequest(NoConfigRequest.type, {
5984             message: getMessage(error, document),
5985             document: {
5986                 uri: document.uri
5987             }
5988         })
5989             .then(undefined, () => {
5990             // noop
5991         });
5992         noConfigReported.set(document.uri, library);
5993     }
5994     return Status.warn;
5995 }
5996 let configErrorReported = new Map();
5997 function tryHandleConfigError(error, document, library) {
5998     if (!error.message) {
5999         return undefined;
6000     }
6001     function handleFileName(filename) {
6002         if (!configErrorReported.has(filename)) {
6003             connection.console.error(getMessage(error, document));
6004             if (!documents.get(vscode_uri_1.URI.file(filename).toString())) {
6005                 connection.window.showInformationMessage(getMessage(error, document));
6006             }
6007             configErrorReported.set(filename, library);
6008         }
6009         return Status.warn;
6010     }
6011     let matches = /Cannot read config file:\s+(.*)\nError:\s+(.*)/.exec(error.message);
6012     if (matches && matches.length === 3) {
6013         return handleFileName(matches[1]);
6014     }
6015     matches = /(.*):\n\s*Configuration for rule \"(.*)\" is /.exec(error.message);
6016     if (matches && matches.length === 3) {
6017         return handleFileName(matches[1]);
6018     }
6019     matches = /Cannot find module '([^']*)'\nReferenced from:\s+(.*)/.exec(error.message);
6020     if (matches && matches.length === 3) {
6021         return handleFileName(matches[2]);
6022     }
6023     return undefined;
6024 }
6025 let missingModuleReported = new Map();
6026 function tryHandleMissingModule(error, document, library) {
6027     if (!error.message) {
6028         return undefined;
6029     }
6030     function handleMissingModule(plugin, module, error) {
6031         if (!missingModuleReported.has(plugin)) {
6032             let fsPath = util_1.getFilePath(document);
6033             missingModuleReported.set(plugin, library);
6034             if (error.messageTemplate === 'plugin-missing') {
6035                 connection.console.error([
6036                     '',
6037                     `${error.message.toString()}`,
6038                     `Happened while validating ${fsPath ? fsPath : document.uri}`,
6039                     `This can happen for a couple of reasons:`,
6040                     `1. The plugin name is spelled incorrectly in an ESLint configuration file (e.g. .eslintrc).`,
6041                     `2. If ESLint is installed globally, then make sure ${module} is installed globally as well.`,
6042                     `3. If ESLint is installed locally, then ${module} isn't installed correctly.`,
6043                     '',
6044                     `Consider running eslint --debug ${fsPath ? fsPath : document.uri} from a terminal to obtain a trace about the configuration files used.`
6045                 ].join('\n'));
6046             }
6047             else {
6048                 connection.console.error([
6049                     `${error.message.toString()}`,
6050                     `Happend while validating ${fsPath ? fsPath : document.uri}`
6051                 ].join('\n'));
6052             }
6053         }
6054         return Status.warn;
6055     }
6056     let matches = /Failed to load plugin (.*): Cannot find module (.*)/.exec(error.message);
6057     if (matches && matches.length === 3) {
6058         return handleMissingModule(matches[1], matches[2], error);
6059     }
6060     return undefined;
6061 }
6062 function showErrorMessage(error, document) {
6063     connection.window.showErrorMessage(`ESLint: ${getMessage(error, document)}. Please see the 'ESLint' output channel for details.`);
6064     if (types_1.Is.string(error.stack)) {
6065         connection.console.error('ESLint stack trace:');
6066         connection.console.error(error.stack);
6067     }
6068     return Status.error;
6069 }
6070 messageQueue.registerNotification(vscode_languageserver_1.DidChangeWatchedFilesNotification.type, params => {
6071     // A .eslintrc has change. No smartness here.
6072     // Simply revalidate all file.
6073     noConfigReported = new Map();
6074     missingModuleReported = new Map();
6075     params.changes.forEach(change => {
6076         let fsPath = util_1.getFilePath(change.uri);
6077         if (!fsPath || util_1.isUNC(fsPath)) {
6078             return;
6079         }
6080         let dirname = path.dirname(fsPath);
6081         if (dirname) {
6082             let library = configErrorReported.get(fsPath);
6083             if (library) {
6084                 let cli = new library.CLIEngine({});
6085                 try {
6086                     cli.executeOnText('', path.join(dirname, '___test___.js'));
6087                     configErrorReported.delete(fsPath);
6088                 }
6089                 catch (error) {
6090                     // noop
6091                 }
6092             }
6093         }
6094     });
6095     validateMany(documents.all());
6096 });
6097 class Fixes {
6098     constructor(edits) {
6099         this.edits = edits;
6100     }
6101     static overlaps(lastEdit, newEdit) {
6102         return !!lastEdit && lastEdit.edit.range[1] > newEdit.edit.range[0];
6103     }
6104     isEmpty() {
6105         return this.edits.size === 0;
6106     }
6107     getDocumentVersion() {
6108         if (this.isEmpty()) {
6109             throw new Error('No edits recorded.');
6110         }
6111         return this.edits.values().next().value.documentVersion;
6112     }
6113     getScoped(diagnostics) {
6114         let result = [];
6115         for (let diagnostic of diagnostics) {
6116             let key = computeKey(diagnostic);
6117             let editInfo = this.edits.get(key);
6118             if (editInfo) {
6119                 result.push(editInfo);
6120             }
6121         }
6122         return result;
6123     }
6124     getAllSorted() {
6125         let result = [];
6126         this.edits.forEach(value => {
6127             if (value.edit != null) {
6128                 result.push(value);
6129             }
6130         });
6131         return result.sort((a, b) => {
6132             let d = a.edit.range[0] - b.edit.range[0];
6133             if (d !== 0) {
6134                 return d;
6135             }
6136             if (a.edit.range[1] === 0) {
6137                 return -1;
6138             }
6139             if (b.edit.range[1] === 0) {
6140                 return 1;
6141             }
6142             return a.edit.range[1] - b.edit.range[1];
6143         });
6144     }
6145     getOverlapFree() {
6146         let sorted = this.getAllSorted();
6147         if (sorted.length <= 1) {
6148             return sorted;
6149         }
6150         let result = [];
6151         let last = sorted[0];
6152         result.push(last);
6153         for (let i = 1; i < sorted.length; i++) {
6154             let current = sorted[i];
6155             if (!Fixes.overlaps(last, current)) {
6156                 result.push(current);
6157                 last = current;
6158             }
6159         }
6160         return result;
6161     }
6162 }
6163 let commands;
6164 messageQueue.registerRequest(vscode_languageserver_1.CodeActionRequest.type, params => {
6165     commands = new Map();
6166     let result = new CodeActionResult();
6167     let uri = params.textDocument.uri;
6168     let edits = codeActions.get(uri);
6169     if (!edits)
6170         return [];
6171     let fixes = new Fixes(edits);
6172     if (fixes.isEmpty())
6173         return [];
6174     let textDocument = documents.get(uri);
6175     let documentVersion = -1;
6176     let allFixableRuleIds = [];
6177     function createTextEdit(editInfo) {
6178         return vscode_languageserver_1.TextEdit.replace(vscode_languageserver_1.Range.create(textDocument.positionAt(editInfo.edit.range[0]), textDocument.positionAt(editInfo.edit.range[1])), editInfo.edit.text || '');
6179     }
6180     function createDisableLineTextEdit(editInfo, indentationText) {
6181         return vscode_languageserver_1.TextEdit.insert(vscode_languageserver_1.Position.create(editInfo.line - 1, 0), `${indentationText}// eslint-disable-next-line ${editInfo.ruleId}\n`);
6182     }
6183     function createDisableSameLineTextEdit(editInfo) {
6184         return vscode_languageserver_1.TextEdit.insert(vscode_languageserver_1.Position.create(editInfo.line - 1, Number.MAX_VALUE), ` // eslint-disable-line ${editInfo.ruleId}`);
6185     }
6186     function createDisableFileTextEdit(editInfo) {
6187         var _a;
6188         // If firts line contains a shebang, insert on the next line instead.
6189         const shebang = (_a = textDocument) === null || _a === void 0 ? void 0 : _a.getText(vscode_languageserver_1.Range.create(vscode_languageserver_1.Position.create(0, 0), vscode_languageserver_1.Position.create(0, 2)));
6190         const line = shebang === '#!' ? 1 : 0;
6191         return vscode_languageserver_1.TextEdit.insert(vscode_languageserver_1.Position.create(line, 0), `/* eslint-disable ${editInfo.ruleId} */\n`);
6192     }
6193     function getLastEdit(array) {
6194         let length = array.length;
6195         if (length === 0) {
6196             return undefined;
6197         }
6198         return array[length - 1];
6199     }
6200     return resolveSettings(textDocument).then(settings => {
6201         for (let editInfo of fixes.getScoped(params.context.diagnostics)) {
6202             documentVersion = editInfo.documentVersion;
6203             let ruleId = editInfo.ruleId;
6204             allFixableRuleIds.push(ruleId);
6205             if (editInfo.edit != null) {
6206                 let workspaceChange = new vscode_languageserver_1.WorkspaceChange();
6207                 workspaceChange.getTextEditChange({ uri, version: documentVersion }).add(createTextEdit(editInfo));
6208                 commands.set(`${CommandIds.applySingleFix}:${ruleId}`, workspaceChange);
6209                 let action = vscode_languageserver_1.CodeAction.create(editInfo.label, vscode_languageserver_1.Command.create(editInfo.label, CommandIds.applySingleFix, ruleId), vscode_languageserver_1.CodeActionKind.QuickFix);
6210                 action.isPreferred = true;
6211                 result.get(ruleId).fixes.push(action);
6212             }
6213             if (settings.codeAction.disableRuleComment.enable) {
6214                 let workspaceChange = new vscode_languageserver_1.WorkspaceChange();
6215                 if (settings.codeAction.disableRuleComment.location === 'sameLine') {
6216                     workspaceChange.getTextEditChange({ uri, version: documentVersion }).add(createDisableSameLineTextEdit(editInfo));
6217                 }
6218                 else {
6219                     let lineText = textDocument.getText(vscode_languageserver_1.Range.create(vscode_languageserver_1.Position.create(editInfo.line - 1, 0), vscode_languageserver_1.Position.create(editInfo.line - 1, Number.MAX_VALUE)));
6220                     let indentationText = /^([ \t]*)/.exec(lineText)[1];
6221                     workspaceChange.getTextEditChange({ uri, version: documentVersion }).add(createDisableLineTextEdit(editInfo, indentationText));
6222                 }
6223                 commands.set(`${CommandIds.applyDisableLine}:${ruleId}`, workspaceChange);
6224                 let title = `Disable ${ruleId} for this line`;
6225                 result.get(ruleId).disable = vscode_languageserver_1.CodeAction.create(title, vscode_languageserver_1.Command.create(title, CommandIds.applyDisableLine, ruleId), vscode_languageserver_1.CodeActionKind.QuickFix);
6226                 if (result.get(ruleId).disableFile === undefined) {
6227                     workspaceChange = new vscode_languageserver_1.WorkspaceChange();
6228                     workspaceChange.getTextEditChange({ uri, version: documentVersion }).add(createDisableFileTextEdit(editInfo));
6229                     commands.set(`${CommandIds.applyDisableFile}:${ruleId}`, workspaceChange);
6230                     title = `Disable ${ruleId} for the entire file`;
6231                     result.get(ruleId).disableFile = vscode_languageserver_1.CodeAction.create(title, vscode_languageserver_1.Command.create(title, CommandIds.applyDisableFile, ruleId), vscode_languageserver_1.CodeActionKind.QuickFix);
6232                 }
6233             }
6234             if (settings.codeAction.showDocumentation.enable && result.get(ruleId).showDocumentation === undefined) {
6235                 if (ruleDocData.urls.has(ruleId)) {
6236                     let title = `Show documentation for ${ruleId}`;
6237                     result.get(ruleId).showDocumentation = vscode_languageserver_1.CodeAction.create(title, vscode_languageserver_1.Command.create(title, CommandIds.openRuleDoc, ruleId), vscode_languageserver_1.CodeActionKind.QuickFix);
6238                 }
6239             }
6240         }
6241         if (result.length > 0) {
6242             let sameProblems = new Map(allFixableRuleIds.map(s => [s, []]));
6243             let all = [];
6244             for (let editInfo of fixes.getAllSorted()) {
6245                 if (documentVersion === -1) {
6246                     documentVersion = editInfo.documentVersion;
6247                 }
6248                 if (sameProblems.has(editInfo.ruleId)) {
6249                     let same = sameProblems.get(editInfo.ruleId);
6250                     if (!Fixes.overlaps(getLastEdit(same), editInfo)) {
6251                         same.push(editInfo);
6252                     }
6253                 }
6254                 if (!Fixes.overlaps(getLastEdit(all), editInfo)) {
6255                     all.push(editInfo);
6256                 }
6257             }
6258             sameProblems.forEach((same, ruleId) => {
6259                 if (same.length > 1) {
6260                     let sameFixes = new vscode_languageserver_1.WorkspaceChange();
6261                     let sameTextChange = sameFixes.getTextEditChange({ uri, version: documentVersion });
6262                     same.map(createTextEdit).forEach(edit => sameTextChange.add(edit));
6263                     commands.set(CommandIds.applySameFixes, sameFixes);
6264                     let title = `Fix all ${ruleId} problems`;
6265                     let command = vscode_languageserver_1.Command.create(title, CommandIds.applySameFixes);
6266                     result.get(ruleId).fixAll = vscode_languageserver_1.CodeAction.create(title, command, vscode_languageserver_1.CodeActionKind.QuickFix);
6267                 }
6268             });
6269             if (all.length > 1) {
6270                 let allFixes = new vscode_languageserver_1.WorkspaceChange();
6271                 let allTextChange = allFixes.getTextEditChange({ uri, version: documentVersion });
6272                 all.map(createTextEdit).forEach(edit => allTextChange.add(edit));
6273                 commands.set(CommandIds.applyAllFixes, allFixes);
6274                 let title = `Fix all auto-fixable problems`;
6275                 let command = vscode_languageserver_1.Command.create(title, CommandIds.applyAllFixes);
6276                 result.fixAll = vscode_languageserver_1.CodeAction.create(title, command, vscode_languageserver_1.CodeActionKind.SourceFixAll);
6277             }
6278         }
6279         return result.all();
6280     });
6281 }, (params) => {
6282     let document = documents.get(params.textDocument.uri);
6283     return document ? document.version : undefined;
6284 });
6285 messageQueue.registerRequest(vscode_languageserver_1.ExecuteCommandRequest.type, async (params) => {
6286     let workspaceChange;
6287     if (params.command === CommandIds.applyAutoFix) {
6288         let identifier = params.arguments[0];
6289         if (!identifier.uri.startsWith('file:')) {
6290             return {};
6291         }
6292         let textDocument = documents.get(identifier.uri);
6293         let settings = await Promise.resolve(resolveSettings(textDocument));
6294         let edits = util_1.getAllFixEdits(textDocument, settings);
6295         if (edits && edits.length) {
6296             workspaceChange = new vscode_languageserver_1.WorkspaceChange();
6297             let textChange = workspaceChange.getTextEditChange(identifier);
6298             edits.forEach(edit => textChange.add(edit));
6299         }
6300     }
6301     else {
6302         if ([CommandIds.applySingleFix, CommandIds.applyDisableLine, CommandIds.applyDisableFile].indexOf(params.command) !== -1) {
6303             let ruleId = params.arguments[0];
6304             workspaceChange = commands.get(`${params.command}:${ruleId}`);
6305         }
6306         else if (params.command === CommandIds.openRuleDoc) {
6307             let ruleId = params.arguments[0];
6308             let url = ruleDocData.urls.get(ruleId);
6309             if (url) {
6310                 await connection.sendRequest(OpenESLintDocRequest.type, { url });
6311             }
6312         }
6313         else {
6314             workspaceChange = commands.get(params.command);
6315         }
6316     }
6317     if (!workspaceChange) {
6318         return {};
6319     }
6320     try {
6321         let response = await Promise.resolve(connection.workspace.applyEdit(workspaceChange.edit));
6322         if (!response.applied) {
6323             connection.console.error(`Failed to apply command: ${params.command}`);
6324         }
6325     }
6326     catch (e) {
6327         connection.console.error(`Failed to apply command: ${params.command}`);
6328     }
6329     return {};
6330 }, (params) => {
6331     if (params.command === CommandIds.applyAutoFix) {
6332         let identifier = params.arguments[0];
6333         return identifier.version;
6334     }
6335     else {
6336         return undefined;
6337     }
6338 });
6339 connection.tracer.connection.listen();
6340
6341
6342 /***/ }),
6343 /* 39 */
6344 /***/ (function(module, exports, __webpack_require__) {
6345
6346 "use strict";
6347 /* --------------------------------------------------------------------------------------------\r
6348  * Copyright (c) Microsoft Corporation. All rights reserved.\r
6349  * Licensed under the MIT License. See License.txt in the project root for license information.\r
6350  * ------------------------------------------------------------------------------------------ */\r
6351 /// <reference path="../typings/thenable.d.ts" />\r
6352 \r
6353 function __export(m) {\r
6354     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r
6355 }\r
6356 Object.defineProperty(exports, "__esModule", { value: true });\r
6357 const vscode_languageserver_protocol_1 = __webpack_require__(4);\r
6358 exports.Event = vscode_languageserver_protocol_1.Event;\r
6359 const configuration_1 = __webpack_require__(40);\r
6360 const workspaceFolders_1 = __webpack_require__(42);\r
6361 const progress_1 = __webpack_require__(43);\r
6362 const Is = __webpack_require__(41);\r
6363 const UUID = __webpack_require__(44);\r
6364 // ------------- Reexport the API surface of the language worker API ----------------------\r
6365 __export(__webpack_require__(4));\r
6366 const fm = __webpack_require__(45);\r
6367 var Files;\r
6368 (function (Files) {\r
6369     Files.uriToFilePath = fm.uriToFilePath;\r
6370     Files.resolveGlobalNodePath = fm.resolveGlobalNodePath;\r
6371     Files.resolveGlobalYarnPath = fm.resolveGlobalYarnPath;\r
6372     Files.resolve = fm.resolve;\r
6373     Files.resolveModulePath = fm.resolveModulePath;\r
6374 })(Files = exports.Files || (exports.Files = {}));\r
6375 let shutdownReceived = false;\r
6376 let exitTimer = undefined;\r
6377 function setupExitTimer() {\r
6378     const argName = '--clientProcessId';\r
6379     function runTimer(value) {\r
6380         try {\r
6381             let processId = parseInt(value);\r
6382             if (!isNaN(processId)) {\r
6383                 exitTimer = setInterval(() => {\r
6384                     try {\r
6385                         process.kill(processId, 0);\r
6386                     }\r
6387                     catch (ex) {\r
6388                         // Parent process doesn't exist anymore. Exit the server.\r
6389                         process.exit(shutdownReceived ? 0 : 1);\r
6390                     }\r
6391                 }, 3000);\r
6392             }\r
6393         }\r
6394         catch (e) {\r
6395             // Ignore errors;\r
6396         }\r
6397     }\r
6398     for (let i = 2; i < process.argv.length; i++) {\r
6399         let arg = process.argv[i];\r
6400         if (arg === argName && i + 1 < process.argv.length) {\r
6401             runTimer(process.argv[i + 1]);\r
6402             return;\r
6403         }\r
6404         else {\r
6405             let args = arg.split('=');\r
6406             if (args[0] === argName) {\r
6407                 runTimer(args[1]);\r
6408             }\r
6409         }\r
6410     }\r
6411 }\r
6412 setupExitTimer();\r
6413 function null2Undefined(value) {\r
6414     if (value === null) {\r
6415         return void 0;\r
6416     }\r
6417     return value;\r
6418 }\r
6419 /**\r
6420  * A manager for simple text documents\r
6421  */\r
6422 class TextDocuments {\r
6423     /**\r
6424      * Create a new text document manager.\r
6425      */\r
6426     constructor(configuration) {\r
6427         this._documents = Object.create(null);\r
6428         this._configuration = configuration;\r
6429         this._onDidChangeContent = new vscode_languageserver_protocol_1.Emitter();\r
6430         this._onDidOpen = new vscode_languageserver_protocol_1.Emitter();\r
6431         this._onDidClose = new vscode_languageserver_protocol_1.Emitter();\r
6432         this._onDidSave = new vscode_languageserver_protocol_1.Emitter();\r
6433         this._onWillSave = new vscode_languageserver_protocol_1.Emitter();\r
6434     }\r
6435     /**\r
6436      * An event that fires when a text document managed by this manager\r
6437      * has been opened or the content changes.\r
6438      */\r
6439     get onDidChangeContent() {\r
6440         return this._onDidChangeContent.event;\r
6441     }\r
6442     /**\r
6443      * An event that fires when a text document managed by this manager\r
6444      * has been opened.\r
6445      */\r
6446     get onDidOpen() {\r
6447         return this._onDidOpen.event;\r
6448     }\r
6449     /**\r
6450      * An event that fires when a text document managed by this manager\r
6451      * will be saved.\r
6452      */\r
6453     get onWillSave() {\r
6454         return this._onWillSave.event;\r
6455     }\r
6456     /**\r
6457      * Sets a handler that will be called if a participant wants to provide\r
6458      * edits during a text document save.\r
6459      */\r
6460     onWillSaveWaitUntil(handler) {\r
6461         this._willSaveWaitUntil = handler;\r
6462     }\r
6463     /**\r
6464      * An event that fires when a text document managed by this manager\r
6465      * has been saved.\r
6466      */\r
6467     get onDidSave() {\r
6468         return this._onDidSave.event;\r
6469     }\r
6470     /**\r
6471      * An event that fires when a text document managed by this manager\r
6472      * has been closed.\r
6473      */\r
6474     get onDidClose() {\r
6475         return this._onDidClose.event;\r
6476     }\r
6477     /**\r
6478      * Returns the document for the given URI. Returns undefined if\r
6479      * the document is not mananged by this instance.\r
6480      *\r
6481      * @param uri The text document's URI to retrieve.\r
6482      * @return the text document or `undefined`.\r
6483      */\r
6484     get(uri) {\r
6485         return this._documents[uri];\r
6486     }\r
6487     /**\r
6488      * Returns all text documents managed by this instance.\r
6489      *\r
6490      * @return all text documents.\r
6491      */\r
6492     all() {\r
6493         return Object.keys(this._documents).map(key => this._documents[key]);\r
6494     }\r
6495     /**\r
6496      * Returns the URIs of all text documents managed by this instance.\r
6497      *\r
6498      * @return the URI's of all text documents.\r
6499      */\r
6500     keys() {\r
6501         return Object.keys(this._documents);\r
6502     }\r
6503     /**\r
6504      * Listens for `low level` notification on the given connection to\r
6505      * update the text documents managed by this instance.\r
6506      *\r
6507      * @param connection The connection to listen on.\r
6508      */\r
6509     listen(connection) {\r
6510         connection.__textDocumentSync = vscode_languageserver_protocol_1.TextDocumentSyncKind.Full;\r
6511         connection.onDidOpenTextDocument((event) => {\r
6512             let td = event.textDocument;\r
6513             let document = this._configuration.create(td.uri, td.languageId, td.version, td.text);\r
6514             this._documents[td.uri] = document;\r
6515             let toFire = Object.freeze({ document });\r
6516             this._onDidOpen.fire(toFire);\r
6517             this._onDidChangeContent.fire(toFire);\r
6518         });\r
6519         connection.onDidChangeTextDocument((event) => {\r
6520             let td = event.textDocument;\r
6521             let changes = event.contentChanges;\r
6522             if (changes.length === 0) {\r
6523                 return;\r
6524             }\r
6525             let document = this._documents[td.uri];\r
6526             const { version } = td;\r
6527             if (version === null || version === void 0) {\r
6528                 throw new Error(`Received document change event for ${td.uri} without valid version identifier`);\r
6529             }\r
6530             document = this._configuration.update(document, changes, version);\r
6531             this._documents[td.uri] = document;\r
6532             this._onDidChangeContent.fire(Object.freeze({ document }));\r
6533         });\r
6534         connection.onDidCloseTextDocument((event) => {\r
6535             let document = this._documents[event.textDocument.uri];\r
6536             if (document) {\r
6537                 delete this._documents[event.textDocument.uri];\r
6538                 this._onDidClose.fire(Object.freeze({ document }));\r
6539             }\r
6540         });\r
6541         connection.onWillSaveTextDocument((event) => {\r
6542             let document = this._documents[event.textDocument.uri];\r
6543             if (document) {\r
6544                 this._onWillSave.fire(Object.freeze({ document, reason: event.reason }));\r
6545             }\r
6546         });\r
6547         connection.onWillSaveTextDocumentWaitUntil((event, token) => {\r
6548             let document = this._documents[event.textDocument.uri];\r
6549             if (document && this._willSaveWaitUntil) {\r
6550                 return this._willSaveWaitUntil(Object.freeze({ document, reason: event.reason }), token);\r
6551             }\r
6552             else {\r
6553                 return [];\r
6554             }\r
6555         });\r
6556         connection.onDidSaveTextDocument((event) => {\r
6557             let document = this._documents[event.textDocument.uri];\r
6558             if (document) {\r
6559                 this._onDidSave.fire(Object.freeze({ document }));\r
6560             }\r
6561         });\r
6562     }\r
6563 }\r
6564 exports.TextDocuments = TextDocuments;\r
6565 /**\r
6566  * Helps tracking error message. Equal occurences of the same\r
6567  * message are only stored once. This class is for example\r
6568  * useful if text documents are validated in a loop and equal\r
6569  * error message should be folded into one.\r
6570  */\r
6571 class ErrorMessageTracker {\r
6572     constructor() {\r
6573         this._messages = Object.create(null);\r
6574     }\r
6575     /**\r
6576      * Add a message to the tracker.\r
6577      *\r
6578      * @param message The message to add.\r
6579      */\r
6580     add(message) {\r
6581         let count = this._messages[message];\r
6582         if (!count) {\r
6583             count = 0;\r
6584         }\r
6585         count++;\r
6586         this._messages[message] = count;\r
6587     }\r
6588     /**\r
6589      * Send all tracked messages to the connection's window.\r
6590      *\r
6591      * @param connection The connection established between client and server.\r
6592      */\r
6593     sendErrors(connection) {\r
6594         Object.keys(this._messages).forEach(message => {\r
6595             connection.window.showErrorMessage(message);\r
6596         });\r
6597     }\r
6598 }\r
6599 exports.ErrorMessageTracker = ErrorMessageTracker;\r
6600 class RemoteConsoleImpl {\r
6601     constructor() {\r
6602     }\r
6603     rawAttach(connection) {\r
6604         this._rawConnection = connection;\r
6605     }\r
6606     attach(connection) {\r
6607         this._connection = connection;\r
6608     }\r
6609     get connection() {\r
6610         if (!this._connection) {\r
6611             throw new Error('Remote is not attached to a connection yet.');\r
6612         }\r
6613         return this._connection;\r
6614     }\r
6615     fillServerCapabilities(_capabilities) {\r
6616     }\r
6617     initialize(_capabilities) {\r
6618     }\r
6619     error(message) {\r
6620         this.send(vscode_languageserver_protocol_1.MessageType.Error, message);\r
6621     }\r
6622     warn(message) {\r
6623         this.send(vscode_languageserver_protocol_1.MessageType.Warning, message);\r
6624     }\r
6625     info(message) {\r
6626         this.send(vscode_languageserver_protocol_1.MessageType.Info, message);\r
6627     }\r
6628     log(message) {\r
6629         this.send(vscode_languageserver_protocol_1.MessageType.Log, message);\r
6630     }\r
6631     send(type, message) {\r
6632         if (this._rawConnection) {\r
6633             this._rawConnection.sendNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, { type, message });\r
6634         }\r
6635     }\r
6636 }\r
6637 class _RemoteWindowImpl {\r
6638     constructor() {\r
6639     }\r
6640     attach(connection) {\r
6641         this._connection = connection;\r
6642     }\r
6643     get connection() {\r
6644         if (!this._connection) {\r
6645             throw new Error('Remote is not attached to a connection yet.');\r
6646         }\r
6647         return this._connection;\r
6648     }\r
6649     initialize(_capabilities) {\r
6650     }\r
6651     fillServerCapabilities(_capabilities) {\r
6652     }\r
6653     showErrorMessage(message, ...actions) {\r
6654         let params = { type: vscode_languageserver_protocol_1.MessageType.Error, message, actions };\r
6655         return this._connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);\r
6656     }\r
6657     showWarningMessage(message, ...actions) {\r
6658         let params = { type: vscode_languageserver_protocol_1.MessageType.Warning, message, actions };\r
6659         return this._connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);\r
6660     }\r
6661     showInformationMessage(message, ...actions) {\r
6662         let params = { type: vscode_languageserver_protocol_1.MessageType.Info, message, actions };\r
6663         return this._connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);\r
6664     }\r
6665 }\r
6666 const RemoteWindowImpl = progress_1.ProgressFeature(_RemoteWindowImpl);\r
6667 var BulkRegistration;\r
6668 (function (BulkRegistration) {\r
6669     /**\r
6670      * Creates a new bulk registration.\r
6671      * @return an empty bulk registration.\r
6672      */\r
6673     function create() {\r
6674         return new BulkRegistrationImpl();\r
6675     }\r
6676     BulkRegistration.create = create;\r
6677 })(BulkRegistration = exports.BulkRegistration || (exports.BulkRegistration = {}));\r
6678 class BulkRegistrationImpl {\r
6679     constructor() {\r
6680         this._registrations = [];\r
6681         this._registered = new Set();\r
6682     }\r
6683     add(type, registerOptions) {\r
6684         const method = Is.string(type) ? type : type.method;\r
6685         if (this._registered.has(method)) {\r
6686             throw new Error(`${method} is already added to this registration`);\r
6687         }\r
6688         const id = UUID.generateUuid();\r
6689         this._registrations.push({\r
6690             id: id,\r
6691             method: method,\r
6692             registerOptions: registerOptions || {}\r
6693         });\r
6694         this._registered.add(method);\r
6695     }\r
6696     asRegistrationParams() {\r
6697         return {\r
6698             registrations: this._registrations\r
6699         };\r
6700     }\r
6701 }\r
6702 var BulkUnregistration;\r
6703 (function (BulkUnregistration) {\r
6704     function create() {\r
6705         return new BulkUnregistrationImpl(undefined, []);\r
6706     }\r
6707     BulkUnregistration.create = create;\r
6708 })(BulkUnregistration = exports.BulkUnregistration || (exports.BulkUnregistration = {}));\r
6709 class BulkUnregistrationImpl {\r
6710     constructor(_connection, unregistrations) {\r
6711         this._connection = _connection;\r
6712         this._unregistrations = new Map();\r
6713         unregistrations.forEach(unregistration => {\r
6714             this._unregistrations.set(unregistration.method, unregistration);\r
6715         });\r
6716     }\r
6717     get isAttached() {\r
6718         return !!this._connection;\r
6719     }\r
6720     attach(connection) {\r
6721         this._connection = connection;\r
6722     }\r
6723     add(unregistration) {\r
6724         this._unregistrations.set(unregistration.method, unregistration);\r
6725     }\r
6726     dispose() {\r
6727         let unregistrations = [];\r
6728         for (let unregistration of this._unregistrations.values()) {\r
6729             unregistrations.push(unregistration);\r
6730         }\r
6731         let params = {\r
6732             unregisterations: unregistrations\r
6733         };\r
6734         this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(undefined, (_error) => {\r
6735             this._connection.console.info(`Bulk unregistration failed.`);\r
6736         });\r
6737     }\r
6738     disposeSingle(arg) {\r
6739         const method = Is.string(arg) ? arg : arg.method;\r
6740         const unregistration = this._unregistrations.get(method);\r
6741         if (!unregistration) {\r
6742             return false;\r
6743         }\r
6744         let params = {\r
6745             unregisterations: [unregistration]\r
6746         };\r
6747         this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(() => {\r
6748             this._unregistrations.delete(method);\r
6749         }, (_error) => {\r
6750             this._connection.console.info(`Unregistering request handler for ${unregistration.id} failed.`);\r
6751         });\r
6752         return true;\r
6753     }\r
6754 }\r
6755 class RemoteClientImpl {\r
6756     attach(connection) {\r
6757         this._connection = connection;\r
6758     }\r
6759     get connection() {\r
6760         if (!this._connection) {\r
6761             throw new Error('Remote is not attached to a connection yet.');\r
6762         }\r
6763         return this._connection;\r
6764     }\r
6765     initialize(_capabilities) {\r
6766     }\r
6767     fillServerCapabilities(_capabilities) {\r
6768     }\r
6769     register(typeOrRegistrations, registerOptionsOrType, registerOptions) {\r
6770         if (typeOrRegistrations instanceof BulkRegistrationImpl) {\r
6771             return this.registerMany(typeOrRegistrations);\r
6772         }\r
6773         else if (typeOrRegistrations instanceof BulkUnregistrationImpl) {\r
6774             return this.registerSingle1(typeOrRegistrations, registerOptionsOrType, registerOptions);\r
6775         }\r
6776         else {\r
6777             return this.registerSingle2(typeOrRegistrations, registerOptionsOrType);\r
6778         }\r
6779     }\r
6780     registerSingle1(unregistration, type, registerOptions) {\r
6781         const method = Is.string(type) ? type : type.method;\r
6782         const id = UUID.generateUuid();\r
6783         let params = {\r
6784             registrations: [{ id, method, registerOptions: registerOptions || {} }]\r
6785         };\r
6786         if (!unregistration.isAttached) {\r
6787             unregistration.attach(this._connection);\r
6788         }\r
6789         return this._connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {\r
6790             unregistration.add({ id: id, method: method });\r
6791             return unregistration;\r
6792         }, (_error) => {\r
6793             this.connection.console.info(`Registering request handler for ${method} failed.`);\r
6794             return Promise.reject(_error);\r
6795         });\r
6796     }\r
6797     registerSingle2(type, registerOptions) {\r
6798         const method = Is.string(type) ? type : type.method;\r
6799         const id = UUID.generateUuid();\r
6800         let params = {\r
6801             registrations: [{ id, method, registerOptions: registerOptions || {} }]\r
6802         };\r
6803         return this._connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {\r
6804             return vscode_languageserver_protocol_1.Disposable.create(() => {\r
6805                 this.unregisterSingle(id, method);\r
6806             });\r
6807         }, (_error) => {\r
6808             this.connection.console.info(`Registering request handler for ${method} failed.`);\r
6809             return Promise.reject(_error);\r
6810         });\r
6811     }\r
6812     unregisterSingle(id, method) {\r
6813         let params = {\r
6814             unregisterations: [{ id, method }]\r
6815         };\r
6816         return this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(undefined, (_error) => {\r
6817             this.connection.console.info(`Unregistering request handler for ${id} failed.`);\r
6818         });\r
6819     }\r
6820     registerMany(registrations) {\r
6821         let params = registrations.asRegistrationParams();\r
6822         return this._connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then(() => {\r
6823             return new BulkUnregistrationImpl(this._connection, params.registrations.map(registration => { return { id: registration.id, method: registration.method }; }));\r
6824         }, (_error) => {\r
6825             this.connection.console.info(`Bulk registration failed.`);\r
6826             return Promise.reject(_error);\r
6827         });\r
6828     }\r
6829 }\r
6830 class _RemoteWorkspaceImpl {\r
6831     constructor() {\r
6832     }\r
6833     attach(connection) {\r
6834         this._connection = connection;\r
6835     }\r
6836     get connection() {\r
6837         if (!this._connection) {\r
6838             throw new Error('Remote is not attached to a connection yet.');\r
6839         }\r
6840         return this._connection;\r
6841     }\r
6842     initialize(_capabilities) {\r
6843     }\r
6844     fillServerCapabilities(_capabilities) {\r
6845     }\r
6846     applyEdit(paramOrEdit) {\r
6847         function isApplyWorkspaceEditParams(value) {\r
6848             return value && !!value.edit;\r
6849         }\r
6850         let params = isApplyWorkspaceEditParams(paramOrEdit) ? paramOrEdit : { edit: paramOrEdit };\r
6851         return this._connection.sendRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, params);\r
6852     }\r
6853 }\r
6854 const RemoteWorkspaceImpl = workspaceFolders_1.WorkspaceFoldersFeature(configuration_1.ConfigurationFeature(_RemoteWorkspaceImpl));\r
6855 class TelemetryImpl {\r
6856     constructor() {\r
6857     }\r
6858     attach(connection) {\r
6859         this._connection = connection;\r
6860     }\r
6861     get connection() {\r
6862         if (!this._connection) {\r
6863             throw new Error('Remote is not attached to a connection yet.');\r
6864         }\r
6865         return this._connection;\r
6866     }\r
6867     initialize(_capabilities) {\r
6868     }\r
6869     fillServerCapabilities(_capabilities) {\r
6870     }\r
6871     logEvent(data) {\r
6872         this._connection.sendNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, data);\r
6873     }\r
6874 }\r
6875 class TracerImpl {\r
6876     constructor() {\r
6877         this._trace = vscode_languageserver_protocol_1.Trace.Off;\r
6878     }\r
6879     attach(connection) {\r
6880         this._connection = connection;\r
6881     }\r
6882     get connection() {\r
6883         if (!this._connection) {\r
6884             throw new Error('Remote is not attached to a connection yet.');\r
6885         }\r
6886         return this._connection;\r
6887     }\r
6888     initialize(_capabilities) {\r
6889     }\r
6890     fillServerCapabilities(_capabilities) {\r
6891     }\r
6892     set trace(value) {\r
6893         this._trace = value;\r
6894     }\r
6895     log(message, verbose) {\r
6896         if (this._trace === vscode_languageserver_protocol_1.Trace.Off) {\r
6897             return;\r
6898         }\r
6899         this._connection.sendNotification(vscode_languageserver_protocol_1.LogTraceNotification.type, {\r
6900             message: message,\r
6901             verbose: this._trace === vscode_languageserver_protocol_1.Trace.Verbose ? verbose : undefined\r
6902         });\r
6903     }\r
6904 }\r
6905 class LanguagesImpl {\r
6906     constructor() {\r
6907     }\r
6908     attach(connection) {\r
6909         this._connection = connection;\r
6910     }\r
6911     get connection() {\r
6912         if (!this._connection) {\r
6913             throw new Error('Remote is not attached to a connection yet.');\r
6914         }\r
6915         return this._connection;\r
6916     }\r
6917     initialize(_capabilities) {\r
6918     }\r
6919     fillServerCapabilities(_capabilities) {\r
6920     }\r
6921     attachWorkDoneProgress(params) {\r
6922         return progress_1.attachWorkDone(this.connection, params);\r
6923     }\r
6924     attachPartialResultProgress(_type, params) {\r
6925         return progress_1.attachPartialResult(this.connection, params);\r
6926     }\r
6927 }\r
6928 exports.LanguagesImpl = LanguagesImpl;\r
6929 function combineConsoleFeatures(one, two) {\r
6930     return function (Base) {\r
6931         return two(one(Base));\r
6932     };\r
6933 }\r
6934 exports.combineConsoleFeatures = combineConsoleFeatures;\r
6935 function combineTelemetryFeatures(one, two) {\r
6936     return function (Base) {\r
6937         return two(one(Base));\r
6938     };\r
6939 }\r
6940 exports.combineTelemetryFeatures = combineTelemetryFeatures;\r
6941 function combineTracerFeatures(one, two) {\r
6942     return function (Base) {\r
6943         return two(one(Base));\r
6944     };\r
6945 }\r
6946 exports.combineTracerFeatures = combineTracerFeatures;\r
6947 function combineClientFeatures(one, two) {\r
6948     return function (Base) {\r
6949         return two(one(Base));\r
6950     };\r
6951 }\r
6952 exports.combineClientFeatures = combineClientFeatures;\r
6953 function combineWindowFeatures(one, two) {\r
6954     return function (Base) {\r
6955         return two(one(Base));\r
6956     };\r
6957 }\r
6958 exports.combineWindowFeatures = combineWindowFeatures;\r
6959 function combineWorkspaceFeatures(one, two) {\r
6960     return function (Base) {\r
6961         return two(one(Base));\r
6962     };\r
6963 }\r
6964 exports.combineWorkspaceFeatures = combineWorkspaceFeatures;\r
6965 function combineLanguagesFeatures(one, two) {\r
6966     return function (Base) {\r
6967         return two(one(Base));\r
6968     };\r
6969 }\r
6970 exports.combineLanguagesFeatures = combineLanguagesFeatures;\r
6971 function combineFeatures(one, two) {\r
6972     function combine(one, two, func) {\r
6973         if (one && two) {\r
6974             return func(one, two);\r
6975         }\r
6976         else if (one) {\r
6977             return one;\r
6978         }\r
6979         else {\r
6980             return two;\r
6981         }\r
6982     }\r
6983     let result = {\r
6984         __brand: 'features',\r
6985         console: combine(one.console, two.console, combineConsoleFeatures),\r
6986         tracer: combine(one.tracer, two.tracer, combineTracerFeatures),\r
6987         telemetry: combine(one.telemetry, two.telemetry, combineTelemetryFeatures),\r
6988         client: combine(one.client, two.client, combineClientFeatures),\r
6989         window: combine(one.window, two.window, combineWindowFeatures),\r
6990         workspace: combine(one.workspace, two.workspace, combineWorkspaceFeatures)\r
6991     };\r
6992     return result;\r
6993 }\r
6994 exports.combineFeatures = combineFeatures;\r
6995 function createConnection(arg1, arg2, arg3, arg4) {\r
6996     let factories;\r
6997     let input;\r
6998     let output;\r
6999     let strategy;\r
7000     if (arg1 !== void 0 && arg1.__brand === 'features') {\r
7001         factories = arg1;\r
7002         arg1 = arg2;\r
7003         arg2 = arg3;\r
7004         arg3 = arg4;\r
7005     }\r
7006     if (vscode_languageserver_protocol_1.ConnectionStrategy.is(arg1)) {\r
7007         strategy = arg1;\r
7008     }\r
7009     else {\r
7010         input = arg1;\r
7011         output = arg2;\r
7012         strategy = arg3;\r
7013     }\r
7014     return _createConnection(input, output, strategy, factories);\r
7015 }\r
7016 exports.createConnection = createConnection;\r
7017 function _createConnection(input, output, strategy, factories) {\r
7018     if (!input && !output && process.argv.length > 2) {\r
7019         let port = void 0;\r
7020         let pipeName = void 0;\r
7021         let argv = process.argv.slice(2);\r
7022         for (let i = 0; i < argv.length; i++) {\r
7023             let arg = argv[i];\r
7024             if (arg === '--node-ipc') {\r
7025                 input = new vscode_languageserver_protocol_1.IPCMessageReader(process);\r
7026                 output = new vscode_languageserver_protocol_1.IPCMessageWriter(process);\r
7027                 break;\r
7028             }\r
7029             else if (arg === '--stdio') {\r
7030                 input = process.stdin;\r
7031                 output = process.stdout;\r
7032                 break;\r
7033             }\r
7034             else if (arg === '--socket') {\r
7035                 port = parseInt(argv[i + 1]);\r
7036                 break;\r
7037             }\r
7038             else if (arg === '--pipe') {\r
7039                 pipeName = argv[i + 1];\r
7040                 break;\r
7041             }\r
7042             else {\r
7043                 var args = arg.split('=');\r
7044                 if (args[0] === '--socket') {\r
7045                     port = parseInt(args[1]);\r
7046                     break;\r
7047                 }\r
7048                 else if (args[0] === '--pipe') {\r
7049                     pipeName = args[1];\r
7050                     break;\r
7051                 }\r
7052             }\r
7053         }\r
7054         if (port) {\r
7055             let transport = vscode_languageserver_protocol_1.createServerSocketTransport(port);\r
7056             input = transport[0];\r
7057             output = transport[1];\r
7058         }\r
7059         else if (pipeName) {\r
7060             let transport = vscode_languageserver_protocol_1.createServerPipeTransport(pipeName);\r
7061             input = transport[0];\r
7062             output = transport[1];\r
7063         }\r
7064     }\r
7065     var commandLineMessage = 'Use arguments of createConnection or set command line parameters: \'--node-ipc\', \'--stdio\' or \'--socket={number}\'';\r
7066     if (!input) {\r
7067         throw new Error('Connection input stream is not set. ' + commandLineMessage);\r
7068     }\r
7069     if (!output) {\r
7070         throw new Error('Connection output stream is not set. ' + commandLineMessage);\r
7071     }\r
7072     // Backwards compatibility\r
7073     if (Is.func(input.read) && Is.func(input.on)) {\r
7074         let inputStream = input;\r
7075         inputStream.on('end', () => {\r
7076             process.exit(shutdownReceived ? 0 : 1);\r
7077         });\r
7078         inputStream.on('close', () => {\r
7079             process.exit(shutdownReceived ? 0 : 1);\r
7080         });\r
7081     }\r
7082     const logger = (factories && factories.console ? new (factories.console(RemoteConsoleImpl))() : new RemoteConsoleImpl());\r
7083     const connection = vscode_languageserver_protocol_1.createProtocolConnection(input, output, logger, strategy);\r
7084     logger.rawAttach(connection);\r
7085     const tracer = (factories && factories.tracer ? new (factories.tracer(TracerImpl))() : new TracerImpl());\r
7086     const telemetry = (factories && factories.telemetry ? new (factories.telemetry(TelemetryImpl))() : new TelemetryImpl());\r
7087     const client = (factories && factories.client ? new (factories.client(RemoteClientImpl))() : new RemoteClientImpl());\r
7088     const remoteWindow = (factories && factories.window ? new (factories.window(RemoteWindowImpl))() : new RemoteWindowImpl());\r
7089     const workspace = (factories && factories.workspace ? new (factories.workspace(RemoteWorkspaceImpl))() : new RemoteWorkspaceImpl());\r
7090     const languages = (factories && factories.languages ? new (factories.languages(LanguagesImpl))() : new LanguagesImpl());\r
7091     const allRemotes = [logger, tracer, telemetry, client, remoteWindow, workspace, languages];\r
7092     function asPromise(value) {\r
7093         if (value instanceof Promise) {\r
7094             return value;\r
7095         }\r
7096         else if (Is.thenable(value)) {\r
7097             return new Promise((resolve, reject) => {\r
7098                 value.then((resolved) => resolve(resolved), (error) => reject(error));\r
7099             });\r
7100         }\r
7101         else {\r
7102             return Promise.resolve(value);\r
7103         }\r
7104     }\r
7105     let shutdownHandler = undefined;\r
7106     let initializeHandler = undefined;\r
7107     let exitHandler = undefined;\r
7108     let protocolConnection = {\r
7109         listen: () => connection.listen(),\r
7110         sendRequest: (type, ...params) => connection.sendRequest(Is.string(type) ? type : type.method, ...params),\r
7111         onRequest: (type, handler) => connection.onRequest(type, handler),\r
7112         sendNotification: (type, param) => {\r
7113             const method = Is.string(type) ? type : type.method;\r
7114             if (arguments.length === 1) {\r
7115                 connection.sendNotification(method);\r
7116             }\r
7117             else {\r
7118                 connection.sendNotification(method, param);\r
7119             }\r
7120         },\r
7121         onNotification: (type, handler) => connection.onNotification(type, handler),\r
7122         onProgress: connection.onProgress,\r
7123         sendProgress: connection.sendProgress,\r
7124         onInitialize: (handler) => initializeHandler = handler,\r
7125         onInitialized: (handler) => connection.onNotification(vscode_languageserver_protocol_1.InitializedNotification.type, handler),\r
7126         onShutdown: (handler) => shutdownHandler = handler,\r
7127         onExit: (handler) => exitHandler = handler,\r
7128         get console() { return logger; },\r
7129         get telemetry() { return telemetry; },\r
7130         get tracer() { return tracer; },\r
7131         get client() { return client; },\r
7132         get window() { return remoteWindow; },\r
7133         get workspace() { return workspace; },\r
7134         get languages() { return languages; },\r
7135         onDidChangeConfiguration: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, handler),\r
7136         onDidChangeWatchedFiles: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, handler),\r
7137         __textDocumentSync: undefined,\r
7138         onDidOpenTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, handler),\r
7139         onDidChangeTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, handler),\r
7140         onDidCloseTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, handler),\r
7141         onWillSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, handler),\r
7142         onWillSaveTextDocumentWaitUntil: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, handler),\r
7143         onDidSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, handler),\r
7144         sendDiagnostics: (params) => connection.sendNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, params),\r
7145         onHover: (handler) => connection.onRequest(vscode_languageserver_protocol_1.HoverRequest.type, (params, cancel) => {\r
7146             return handler(params, cancel, progress_1.attachWorkDone(connection, params), undefined);\r
7147         }),\r
7148         onCompletion: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionRequest.type, (params, cancel) => {\r
7149             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7150         }),\r
7151         onCompletionResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, handler),\r
7152         onSignatureHelp: (handler) => connection.onRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, (params, cancel) => {\r
7153             return handler(params, cancel, progress_1.attachWorkDone(connection, params), undefined);\r
7154         }),\r
7155         onDeclaration: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, (params, cancel) => {\r
7156             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7157         }),\r
7158         onDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, (params, cancel) => {\r
7159             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7160         }),\r
7161         onTypeDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, (params, cancel) => {\r
7162             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7163         }),\r
7164         onImplementation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, (params, cancel) => {\r
7165             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7166         }),\r
7167         onReferences: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, (params, cancel) => {\r
7168             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7169         }),\r
7170         onDocumentHighlight: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, (params, cancel) => {\r
7171             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7172         }),\r
7173         onDocumentSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, (params, cancel) => {\r
7174             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7175         }),\r
7176         onWorkspaceSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, (params, cancel) => {\r
7177             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7178         }),\r
7179         onCodeAction: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, (params, cancel) => {\r
7180             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7181         }),\r
7182         onCodeLens: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, (params, cancel) => {\r
7183             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7184         }),\r
7185         onCodeLensResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, (params, cancel) => {\r
7186             return handler(params, cancel);\r
7187         }),\r
7188         onDocumentFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, (params, cancel) => {\r
7189             return handler(params, cancel, progress_1.attachWorkDone(connection, params), undefined);\r
7190         }),\r
7191         onDocumentRangeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, (params, cancel) => {\r
7192             return handler(params, cancel, progress_1.attachWorkDone(connection, params), undefined);\r
7193         }),\r
7194         onDocumentOnTypeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, (params, cancel) => {\r
7195             return handler(params, cancel);\r
7196         }),\r
7197         onRenameRequest: (handler) => connection.onRequest(vscode_languageserver_protocol_1.RenameRequest.type, (params, cancel) => {\r
7198             return handler(params, cancel, progress_1.attachWorkDone(connection, params), undefined);\r
7199         }),\r
7200         onPrepareRename: (handler) => connection.onRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, (params, cancel) => {\r
7201             return handler(params, cancel);\r
7202         }),\r
7203         onDocumentLinks: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, (params, cancel) => {\r
7204             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7205         }),\r
7206         onDocumentLinkResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, (params, cancel) => {\r
7207             return handler(params, cancel);\r
7208         }),\r
7209         onDocumentColor: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, (params, cancel) => {\r
7210             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7211         }),\r
7212         onColorPresentation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, (params, cancel) => {\r
7213             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7214         }),\r
7215         onFoldingRanges: (handler) => connection.onRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, (params, cancel) => {\r
7216             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7217         }),\r
7218         onSelectionRanges: (handler) => connection.onRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, (params, cancel) => {\r
7219             return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));\r
7220         }),\r
7221         onExecuteCommand: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, (params, cancel) => {\r
7222             return handler(params, cancel, progress_1.attachWorkDone(connection, params), undefined);\r
7223         }),\r
7224         dispose: () => connection.dispose()\r
7225     };\r
7226     for (let remote of allRemotes) {\r
7227         remote.attach(protocolConnection);\r
7228     }\r
7229     connection.onRequest(vscode_languageserver_protocol_1.InitializeRequest.type, (params) => {\r
7230         const processId = params.processId;\r
7231         if (Is.number(processId) && exitTimer === void 0) {\r
7232             // We received a parent process id. Set up a timer to periodically check\r
7233             // if the parent is still alive.\r
7234             setInterval(() => {\r
7235                 try {\r
7236                     process.kill(processId, 0);\r
7237                 }\r
7238                 catch (ex) {\r
7239                     // Parent process doesn't exist anymore. Exit the server.\r
7240                     process.exit(shutdownReceived ? 0 : 1);\r
7241                 }\r
7242             }, 3000);\r
7243         }\r
7244         if (Is.string(params.trace)) {\r
7245             tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.trace);\r
7246         }\r
7247         for (let remote of allRemotes) {\r
7248             remote.initialize(params.capabilities);\r
7249         }\r
7250         if (initializeHandler) {\r
7251             let result = initializeHandler(params, new vscode_languageserver_protocol_1.CancellationTokenSource().token, progress_1.attachWorkDone(connection, params), undefined);\r
7252             return asPromise(result).then((value) => {\r
7253                 if (value instanceof vscode_languageserver_protocol_1.ResponseError) {\r
7254                     return value;\r
7255                 }\r
7256                 let result = value;\r
7257                 if (!result) {\r
7258                     result = { capabilities: {} };\r
7259                 }\r
7260                 let capabilities = result.capabilities;\r
7261                 if (!capabilities) {\r
7262                     capabilities = {};\r
7263                     result.capabilities = capabilities;\r
7264                 }\r
7265                 if (capabilities.textDocumentSync === void 0 || capabilities.textDocumentSync === null) {\r
7266                     capabilities.textDocumentSync = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;\r
7267                 }\r
7268                 else if (!Is.number(capabilities.textDocumentSync) && !Is.number(capabilities.textDocumentSync.change)) {\r
7269                     capabilities.textDocumentSync.change = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;\r
7270                 }\r
7271                 for (let remote of allRemotes) {\r
7272                     remote.fillServerCapabilities(capabilities);\r
7273                 }\r
7274                 return result;\r
7275             });\r
7276         }\r
7277         else {\r
7278             let result = { capabilities: { textDocumentSync: vscode_languageserver_protocol_1.TextDocumentSyncKind.None } };\r
7279             for (let remote of allRemotes) {\r
7280                 remote.fillServerCapabilities(result.capabilities);\r
7281             }\r
7282             return result;\r
7283         }\r
7284     });\r
7285     connection.onRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, () => {\r
7286         shutdownReceived = true;\r
7287         if (shutdownHandler) {\r
7288             return shutdownHandler(new vscode_languageserver_protocol_1.CancellationTokenSource().token);\r
7289         }\r
7290         else {\r
7291             return undefined;\r
7292         }\r
7293     });\r
7294     connection.onNotification(vscode_languageserver_protocol_1.ExitNotification.type, () => {\r
7295         try {\r
7296             if (exitHandler) {\r
7297                 exitHandler();\r
7298             }\r
7299         }\r
7300         finally {\r
7301             if (shutdownReceived) {\r
7302                 process.exit(0);\r
7303             }\r
7304             else {\r
7305                 process.exit(1);\r
7306             }\r
7307         }\r
7308     });\r
7309     connection.onNotification(vscode_languageserver_protocol_1.SetTraceNotification.type, (params) => {\r
7310         tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.value);\r
7311     });\r
7312     return protocolConnection;\r
7313 }\r
7314 // Export the protocol currently in proposed state.\r
7315 const callHierarchy_proposed_1 = __webpack_require__(48);\r
7316 const st = __webpack_require__(49);\r
7317 var ProposedFeatures;\r
7318 (function (ProposedFeatures) {\r
7319     ProposedFeatures.all = {\r
7320         __brand: 'features',\r
7321         languages: combineLanguagesFeatures(callHierarchy_proposed_1.CallHierarchyFeature, st.SemanticTokensFeature)\r
7322     };\r
7323     ProposedFeatures.SemanticTokensBuilder = st.SemanticTokensBuilder;\r
7324 })(ProposedFeatures = exports.ProposedFeatures || (exports.ProposedFeatures = {}));\r
7325 //# sourceMappingURL=main.js.map
7326
7327 /***/ }),
7328 /* 40 */
7329 /***/ (function(module, exports, __webpack_require__) {
7330
7331 "use strict";
7332 /* --------------------------------------------------------------------------------------------\r
7333  * Copyright (c) Microsoft Corporation. All rights reserved.\r
7334  * Licensed under the MIT License. See License.txt in the project root for license information.\r
7335  * ------------------------------------------------------------------------------------------ */\r
7336 \r
7337 Object.defineProperty(exports, "__esModule", { value: true });\r
7338 const vscode_languageserver_protocol_1 = __webpack_require__(4);\r
7339 const Is = __webpack_require__(41);\r
7340 exports.ConfigurationFeature = (Base) => {\r
7341     return class extends Base {\r
7342         getConfiguration(arg) {\r
7343             if (!arg) {\r
7344                 return this._getConfiguration({});\r
7345             }\r
7346             else if (Is.string(arg)) {\r
7347                 return this._getConfiguration({ section: arg });\r
7348             }\r
7349             else {\r
7350                 return this._getConfiguration(arg);\r
7351             }\r
7352         }\r
7353         _getConfiguration(arg) {\r
7354             let params = {\r
7355                 items: Array.isArray(arg) ? arg : [arg]\r
7356             };\r
7357             return this.connection.sendRequest(vscode_languageserver_protocol_1.ConfigurationRequest.type, params).then((result) => {\r
7358                 return Array.isArray(arg) ? result : result[0];\r
7359             });\r
7360         }\r
7361     };\r
7362 };\r
7363 //# sourceMappingURL=configuration.js.map
7364
7365 /***/ }),
7366 /* 41 */
7367 /***/ (function(module, exports, __webpack_require__) {
7368
7369 "use strict";
7370 /* --------------------------------------------------------------------------------------------\r
7371  * Copyright (c) Microsoft Corporation. All rights reserved.\r
7372  * Licensed under the MIT License. See License.txt in the project root for license information.\r
7373  * ------------------------------------------------------------------------------------------ */\r
7374 \r
7375 Object.defineProperty(exports, "__esModule", { value: true });\r
7376 function boolean(value) {\r
7377     return value === true || value === false;\r
7378 }\r
7379 exports.boolean = boolean;\r
7380 function string(value) {\r
7381     return typeof value === 'string' || value instanceof String;\r
7382 }\r
7383 exports.string = string;\r
7384 function number(value) {\r
7385     return typeof value === 'number' || value instanceof Number;\r
7386 }\r
7387 exports.number = number;\r
7388 function error(value) {\r
7389     return value instanceof Error;\r
7390 }\r
7391 exports.error = error;\r
7392 function func(value) {\r
7393     return typeof value === 'function';\r
7394 }\r
7395 exports.func = func;\r
7396 function array(value) {\r
7397     return Array.isArray(value);\r
7398 }\r
7399 exports.array = array;\r
7400 function stringArray(value) {\r
7401     return array(value) && value.every(elem => string(elem));\r
7402 }\r
7403 exports.stringArray = stringArray;\r
7404 function typedArray(value, check) {\r
7405     return Array.isArray(value) && value.every(check);\r
7406 }\r
7407 exports.typedArray = typedArray;\r
7408 function thenable(value) {\r
7409     return value && func(value.then);\r
7410 }\r
7411 exports.thenable = thenable;\r
7412 //# sourceMappingURL=is.js.map
7413
7414 /***/ }),
7415 /* 42 */
7416 /***/ (function(module, exports, __webpack_require__) {
7417
7418 "use strict";
7419 /* --------------------------------------------------------------------------------------------\r
7420  * Copyright (c) Microsoft Corporation. All rights reserved.\r
7421  * Licensed under the MIT License. See License.txt in the project root for license information.\r
7422  * ------------------------------------------------------------------------------------------ */\r
7423 \r
7424 Object.defineProperty(exports, "__esModule", { value: true });\r
7425 const vscode_languageserver_protocol_1 = __webpack_require__(4);\r
7426 exports.WorkspaceFoldersFeature = (Base) => {\r
7427     return class extends Base {\r
7428         initialize(capabilities) {\r
7429             let workspaceCapabilities = capabilities.workspace;\r
7430             if (workspaceCapabilities && workspaceCapabilities.workspaceFolders) {\r
7431                 this._onDidChangeWorkspaceFolders = new vscode_languageserver_protocol_1.Emitter();\r
7432                 this.connection.onNotification(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type, (params) => {\r
7433                     this._onDidChangeWorkspaceFolders.fire(params.event);\r
7434                 });\r
7435             }\r
7436         }\r
7437         getWorkspaceFolders() {\r
7438             return this.connection.sendRequest(vscode_languageserver_protocol_1.WorkspaceFoldersRequest.type);\r
7439         }\r
7440         get onDidChangeWorkspaceFolders() {\r
7441             if (!this._onDidChangeWorkspaceFolders) {\r
7442                 throw new Error('Client doesn\'t support sending workspace folder change events.');\r
7443             }\r
7444             if (!this._unregistration) {\r
7445                 this._unregistration = this.connection.client.register(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type);\r
7446             }\r
7447             return this._onDidChangeWorkspaceFolders.event;\r
7448         }\r
7449     };\r
7450 };\r
7451 //# sourceMappingURL=workspaceFolders.js.map
7452
7453 /***/ }),
7454 /* 43 */
7455 /***/ (function(module, exports, __webpack_require__) {
7456
7457 "use strict";
7458 /* --------------------------------------------------------------------------------------------\r
7459  * Copyright (c) Microsoft Corporation. All rights reserved.\r
7460  * Licensed under the MIT License. See License.txt in the project root for license information.\r
7461  * ------------------------------------------------------------------------------------------ */\r
7462 \r
7463 Object.defineProperty(exports, "__esModule", { value: true });\r
7464 const vscode_languageserver_protocol_1 = __webpack_require__(4);\r
7465 const uuid_1 = __webpack_require__(44);\r
7466 class WorkDoneProgressImpl {\r
7467     constructor(_connection, _token) {\r
7468         this._connection = _connection;\r
7469         this._token = _token;\r
7470         WorkDoneProgressImpl.Instances.set(this._token, this);\r
7471         this._source = new vscode_languageserver_protocol_1.CancellationTokenSource();\r
7472     }\r
7473     get token() {\r
7474         return this._source.token;\r
7475     }\r
7476     begin(title, percentage, message, cancellable) {\r
7477         let param = {\r
7478             kind: 'begin',\r
7479             title,\r
7480             percentage,\r
7481             message,\r
7482             cancellable\r
7483         };\r
7484         this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, param);\r
7485     }\r
7486     report(arg0, arg1) {\r
7487         let param = {\r
7488             kind: 'report'\r
7489         };\r
7490         if (typeof arg0 === 'number') {\r
7491             param.percentage = arg0;\r
7492             if (arg1 !== undefined) {\r
7493                 param.message = arg1;\r
7494             }\r
7495         }\r
7496         else {\r
7497             param.message = arg0;\r
7498         }\r
7499         this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, param);\r
7500     }\r
7501     done() {\r
7502         WorkDoneProgressImpl.Instances.delete(this._token);\r
7503         this._source.dispose();\r
7504         this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, { kind: 'end' });\r
7505     }\r
7506     cancel() {\r
7507         this._source.cancel();\r
7508     }\r
7509 }\r
7510 WorkDoneProgressImpl.Instances = new Map();\r
7511 class NullProgress {\r
7512     constructor() {\r
7513         this._source = new vscode_languageserver_protocol_1.CancellationTokenSource();\r
7514     }\r
7515     get token() {\r
7516         return this._source.token;\r
7517     }\r
7518     begin() {\r
7519     }\r
7520     report() {\r
7521     }\r
7522     done() {\r
7523     }\r
7524 }\r
7525 function attachWorkDone(connection, params) {\r
7526     if (params === undefined || params.workDoneToken === undefined) {\r
7527         return new NullProgress();\r
7528     }\r
7529     const token = params.workDoneToken;\r
7530     delete params.workDoneToken;\r
7531     return new WorkDoneProgressImpl(connection, token);\r
7532 }\r
7533 exports.attachWorkDone = attachWorkDone;\r
7534 exports.ProgressFeature = (Base) => {\r
7535     return class extends Base {\r
7536         initialize(capabilities) {\r
7537             var _a;\r
7538             if (((_a = capabilities === null || capabilities === void 0 ? void 0 : capabilities.window) === null || _a === void 0 ? void 0 : _a.workDoneProgress) === true) {\r
7539                 this._progressSupported = true;\r
7540                 this.connection.onNotification(vscode_languageserver_protocol_1.WorkDoneProgressCancelNotification.type, (params) => {\r
7541                     let progress = WorkDoneProgressImpl.Instances.get(params.token);\r
7542                     if (progress !== undefined) {\r
7543                         progress.cancel();\r
7544                     }\r
7545                 });\r
7546             }\r
7547         }\r
7548         attachWorkDoneProgress(token) {\r
7549             if (token === undefined) {\r
7550                 return new NullProgress();\r
7551             }\r
7552             else {\r
7553                 return new WorkDoneProgressImpl(this.connection, token);\r
7554             }\r
7555         }\r
7556         createWorkDoneProgress() {\r
7557             if (this._progressSupported) {\r
7558                 const token = uuid_1.generateUuid();\r
7559                 return this.connection.sendRequest(vscode_languageserver_protocol_1.WorkDoneProgressCreateRequest.type, { token }).then(() => {\r
7560                     const result = new WorkDoneProgressImpl(this.connection, token);\r
7561                     return result;\r
7562                 });\r
7563             }\r
7564             else {\r
7565                 return Promise.resolve(new NullProgress());\r
7566             }\r
7567         }\r
7568     };\r
7569 };\r
7570 var ResultProgress;\r
7571 (function (ResultProgress) {\r
7572     ResultProgress.type = new vscode_languageserver_protocol_1.ProgressType();\r
7573 })(ResultProgress || (ResultProgress = {}));\r
7574 class ResultProgressImpl {\r
7575     constructor(_connection, _token) {\r
7576         this._connection = _connection;\r
7577         this._token = _token;\r
7578     }\r
7579     report(data) {\r
7580         this._connection.sendProgress(ResultProgress.type, this._token, data);\r
7581     }\r
7582 }\r
7583 function attachPartialResult(connection, params) {\r
7584     if (params === undefined || params.partialResultToken === undefined) {\r
7585         return undefined;\r
7586     }\r
7587     const token = params.partialResultToken;\r
7588     delete params.partialResultToken;\r
7589     return new ResultProgressImpl(connection, token);\r
7590 }\r
7591 exports.attachPartialResult = attachPartialResult;\r
7592 //# sourceMappingURL=progress.js.map
7593
7594 /***/ }),
7595 /* 44 */
7596 /***/ (function(module, exports, __webpack_require__) {
7597
7598 "use strict";
7599 /*---------------------------------------------------------------------------------------------\r
7600  *  Copyright (c) Microsoft Corporation. All rights reserved.\r
7601  *  Licensed under the MIT License. See License.txt in the project root for license information.\r
7602  *--------------------------------------------------------------------------------------------*/\r
7603 \r
7604 Object.defineProperty(exports, "__esModule", { value: true });\r
7605 class ValueUUID {\r
7606     constructor(_value) {\r
7607         this._value = _value;\r
7608         // empty\r
7609     }\r
7610     asHex() {\r
7611         return this._value;\r
7612     }\r
7613     equals(other) {\r
7614         return this.asHex() === other.asHex();\r
7615     }\r
7616 }\r
7617 class V4UUID extends ValueUUID {\r
7618     constructor() {\r
7619         super([\r
7620             V4UUID._randomHex(),\r
7621             V4UUID._randomHex(),\r
7622             V4UUID._randomHex(),\r
7623             V4UUID._randomHex(),\r
7624             V4UUID._randomHex(),\r
7625             V4UUID._randomHex(),\r
7626             V4UUID._randomHex(),\r
7627             V4UUID._randomHex(),\r
7628             '-',\r
7629             V4UUID._randomHex(),\r
7630             V4UUID._randomHex(),\r
7631             V4UUID._randomHex(),\r
7632             V4UUID._randomHex(),\r
7633             '-',\r
7634             '4',\r
7635             V4UUID._randomHex(),\r
7636             V4UUID._randomHex(),\r
7637             V4UUID._randomHex(),\r
7638             '-',\r
7639             V4UUID._oneOf(V4UUID._timeHighBits),\r
7640             V4UUID._randomHex(),\r
7641             V4UUID._randomHex(),\r
7642             V4UUID._randomHex(),\r
7643             '-',\r
7644             V4UUID._randomHex(),\r
7645             V4UUID._randomHex(),\r
7646             V4UUID._randomHex(),\r
7647             V4UUID._randomHex(),\r
7648             V4UUID._randomHex(),\r
7649             V4UUID._randomHex(),\r
7650             V4UUID._randomHex(),\r
7651             V4UUID._randomHex(),\r
7652             V4UUID._randomHex(),\r
7653             V4UUID._randomHex(),\r
7654             V4UUID._randomHex(),\r
7655             V4UUID._randomHex(),\r
7656         ].join(''));\r
7657     }\r
7658     static _oneOf(array) {\r
7659         return array[Math.floor(array.length * Math.random())];\r
7660     }\r
7661     static _randomHex() {\r
7662         return V4UUID._oneOf(V4UUID._chars);\r
7663     }\r
7664 }\r
7665 V4UUID._chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];\r
7666 V4UUID._timeHighBits = ['8', '9', 'a', 'b'];\r
7667 /**\r
7668  * An empty UUID that contains only zeros.\r
7669  */\r
7670 exports.empty = new ValueUUID('00000000-0000-0000-0000-000000000000');\r
7671 function v4() {\r
7672     return new V4UUID();\r
7673 }\r
7674 exports.v4 = v4;\r
7675 const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\r
7676 function isUUID(value) {\r
7677     return _UUIDPattern.test(value);\r
7678 }\r
7679 exports.isUUID = isUUID;\r
7680 /**\r
7681  * Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.\r
7682  * @param value A uuid string.\r
7683  */\r
7684 function parse(value) {\r
7685     if (!isUUID(value)) {\r
7686         throw new Error('invalid uuid');\r
7687     }\r
7688     return new ValueUUID(value);\r
7689 }\r
7690 exports.parse = parse;\r
7691 function generateUuid() {\r
7692     return v4().asHex();\r
7693 }\r
7694 exports.generateUuid = generateUuid;\r
7695 //# sourceMappingURL=uuid.js.map
7696
7697 /***/ }),
7698 /* 45 */
7699 /***/ (function(module, exports, __webpack_require__) {
7700
7701 "use strict";
7702 /* WEBPACK VAR INJECTION */(function(__filename) {/* --------------------------------------------------------------------------------------------\r
7703  * Copyright (c) Microsoft Corporation. All rights reserved.\r
7704  * Licensed under the MIT License. See License.txt in the project root for license information.\r
7705  * ------------------------------------------------------------------------------------------ */\r
7706 \r
7707 Object.defineProperty(exports, "__esModule", { value: true });\r
7708 const url = __webpack_require__(46);\r
7709 const path = __webpack_require__(3);\r
7710 const fs = __webpack_require__(2);\r
7711 const child_process_1 = __webpack_require__(47);\r
7712 /**\r
7713  * @deprecated Use the `vscode-uri` npm module which provides a more\r
7714  * complete implementation of handling VS Code URIs.\r
7715  */\r
7716 function uriToFilePath(uri) {\r
7717     let parsed = url.parse(uri);\r
7718     if (parsed.protocol !== 'file:' || !parsed.path) {\r
7719         return undefined;\r
7720     }\r
7721     let segments = parsed.path.split('/');\r
7722     for (var i = 0, len = segments.length; i < len; i++) {\r
7723         segments[i] = decodeURIComponent(segments[i]);\r
7724     }\r
7725     if (process.platform === 'win32' && segments.length > 1) {\r
7726         let first = segments[0];\r
7727         let second = segments[1];\r
7728         // Do we have a drive letter and we started with a / which is the\r
7729         // case if the first segement is empty (see split above)\r
7730         if (first.length === 0 && second.length > 1 && second[1] === ':') {\r
7731             // Remove first slash\r
7732             segments.shift();\r
7733         }\r
7734     }\r
7735     return path.normalize(segments.join('/'));\r
7736 }\r
7737 exports.uriToFilePath = uriToFilePath;\r
7738 function isWindows() {\r
7739     return process.platform === 'win32';\r
7740 }\r
7741 function resolve(moduleName, nodePath, cwd, tracer) {\r
7742     const nodePathKey = 'NODE_PATH';\r
7743     const app = [\r
7744         'var p = process;',\r
7745         'p.on(\'message\',function(m){',\r
7746         'if(m.c===\'e\'){',\r
7747         'p.exit(0);',\r
7748         '}',\r
7749         'else if(m.c===\'rs\'){',\r
7750         'try{',\r
7751         'var r=require.resolve(m.a);',\r
7752         'p.send({c:\'r\',s:true,r:r});',\r
7753         '}',\r
7754         'catch(err){',\r
7755         'p.send({c:\'r\',s:false});',\r
7756         '}',\r
7757         '}',\r
7758         '});'\r
7759     ].join('');\r
7760     return new Promise((resolve, reject) => {\r
7761         let env = process.env;\r
7762         let newEnv = Object.create(null);\r
7763         Object.keys(env).forEach(key => newEnv[key] = env[key]);\r
7764         if (nodePath && fs.existsSync(nodePath) /* see issue 545 */) {\r
7765             if (newEnv[nodePathKey]) {\r
7766                 newEnv[nodePathKey] = nodePath + path.delimiter + newEnv[nodePathKey];\r
7767             }\r
7768             else {\r
7769                 newEnv[nodePathKey] = nodePath;\r
7770             }\r
7771             if (tracer) {\r
7772                 tracer(`NODE_PATH value is: ${newEnv[nodePathKey]}`);\r
7773             }\r
7774         }\r
7775         newEnv['ELECTRON_RUN_AS_NODE'] = '1';\r
7776         try {\r
7777             let cp = child_process_1.fork('', [], {\r
7778                 cwd: cwd,\r
7779                 env: newEnv,\r
7780                 execArgv: ['-e', app]\r
7781             });\r
7782             if (cp.pid === void 0) {\r
7783                 reject(new Error(`Starting process to resolve node module  ${moduleName} failed`));\r
7784                 return;\r
7785             }\r
7786             cp.on('error', (error) => {\r
7787                 reject(error);\r
7788             });\r
7789             cp.on('message', (message) => {\r
7790                 if (message.c === 'r') {\r
7791                     cp.send({ c: 'e' });\r
7792                     if (message.s) {\r
7793                         resolve(message.r);\r
7794                     }\r
7795                     else {\r
7796                         reject(new Error(`Failed to resolve module: ${moduleName}`));\r
7797                     }\r
7798                 }\r
7799             });\r
7800             let message = {\r
7801                 c: 'rs',\r
7802                 a: moduleName\r
7803             };\r
7804             cp.send(message);\r
7805         }\r
7806         catch (error) {\r
7807             reject(error);\r
7808         }\r
7809     });\r
7810 }\r
7811 exports.resolve = resolve;\r
7812 /**\r
7813  * Resolve the global npm package path.\r
7814  * @deprecated Since this depends on the used package manager and their version the best is that servers\r
7815  * implement this themselves since they know best what kind of package managers to support.\r
7816  * @param tracer the tracer to use\r
7817  */\r
7818 function resolveGlobalNodePath(tracer) {\r
7819     let npmCommand = 'npm';\r
7820     const env = Object.create(null);\r
7821     Object.keys(process.env).forEach(key => env[key] = process.env[key]);\r
7822     env['NO_UPDATE_NOTIFIER'] = 'true';\r
7823     const options = {\r
7824         encoding: 'utf8',\r
7825         env\r
7826     };\r
7827     if (isWindows()) {\r
7828         npmCommand = 'npm.cmd';\r
7829         options.shell = true;\r
7830     }\r
7831     let handler = () => { };\r
7832     try {\r
7833         process.on('SIGPIPE', handler);\r
7834         let stdout = child_process_1.spawnSync(npmCommand, ['config', 'get', 'prefix'], options).stdout;\r
7835         if (!stdout) {\r
7836             if (tracer) {\r
7837                 tracer(`'npm config get prefix' didn't return a value.`);\r
7838             }\r
7839             return undefined;\r
7840         }\r
7841         let prefix = stdout.trim();\r
7842         if (tracer) {\r
7843             tracer(`'npm config get prefix' value is: ${prefix}`);\r
7844         }\r
7845         if (prefix.length > 0) {\r
7846             if (isWindows()) {\r
7847                 return path.join(prefix, 'node_modules');\r
7848             }\r
7849             else {\r
7850                 return path.join(prefix, 'lib', 'node_modules');\r
7851             }\r
7852         }\r
7853         return undefined;\r
7854     }\r
7855     catch (err) {\r
7856         return undefined;\r
7857     }\r
7858     finally {\r
7859         process.removeListener('SIGPIPE', handler);\r
7860     }\r
7861 }\r
7862 exports.resolveGlobalNodePath = resolveGlobalNodePath;\r
7863 /*\r
7864  * Resolve the global yarn pakage path.\r
7865  * @deprecated Since this depends on the used package manager and their version the best is that servers\r
7866  * implement this themselves since they know best what kind of package managers to support.\r
7867  * @param tracer the tracer to use\r
7868  */\r
7869 function resolveGlobalYarnPath(tracer) {\r
7870     let yarnCommand = 'yarn';\r
7871     let options = {\r
7872         encoding: 'utf8'\r
7873     };\r
7874     if (isWindows()) {\r
7875         yarnCommand = 'yarn.cmd';\r
7876         options.shell = true;\r
7877     }\r
7878     let handler = () => { };\r
7879     try {\r
7880         process.on('SIGPIPE', handler);\r
7881         let results = child_process_1.spawnSync(yarnCommand, ['global', 'dir', '--json'], options);\r
7882         let stdout = results.stdout;\r
7883         if (!stdout) {\r
7884             if (tracer) {\r
7885                 tracer(`'yarn global dir' didn't return a value.`);\r
7886                 if (results.stderr) {\r
7887                     tracer(results.stderr);\r
7888                 }\r
7889             }\r
7890             return undefined;\r
7891         }\r
7892         let lines = stdout.trim().split(/\r?\n/);\r
7893         for (let line of lines) {\r
7894             try {\r
7895                 let yarn = JSON.parse(line);\r
7896                 if (yarn.type === 'log') {\r
7897                     return path.join(yarn.data, 'node_modules');\r
7898                 }\r
7899             }\r
7900             catch (e) {\r
7901                 // Do nothing. Ignore the line\r
7902             }\r
7903         }\r
7904         return undefined;\r
7905     }\r
7906     catch (err) {\r
7907         return undefined;\r
7908     }\r
7909     finally {\r
7910         process.removeListener('SIGPIPE', handler);\r
7911     }\r
7912 }\r
7913 exports.resolveGlobalYarnPath = resolveGlobalYarnPath;\r
7914 var FileSystem;\r
7915 (function (FileSystem) {\r
7916     let _isCaseSensitive = undefined;\r
7917     function isCaseSensitive() {\r
7918         if (_isCaseSensitive !== void 0) {\r
7919             return _isCaseSensitive;\r
7920         }\r
7921         if (process.platform === 'win32') {\r
7922             _isCaseSensitive = false;\r
7923         }\r
7924         else {\r
7925             // convert current file name to upper case / lower case and check if file exists\r
7926             // (guards against cases when name is already all uppercase or lowercase)\r
7927             _isCaseSensitive = !fs.existsSync(__filename.toUpperCase()) || !fs.existsSync(__filename.toLowerCase());\r
7928         }\r
7929         return _isCaseSensitive;\r
7930     }\r
7931     FileSystem.isCaseSensitive = isCaseSensitive;\r
7932     function isParent(parent, child) {\r
7933         if (isCaseSensitive()) {\r
7934             return path.normalize(child).indexOf(path.normalize(parent)) === 0;\r
7935         }\r
7936         else {\r
7937             return path.normalize(child).toLowerCase().indexOf(path.normalize(parent).toLowerCase()) === 0;\r
7938         }\r
7939     }\r
7940     FileSystem.isParent = isParent;\r
7941 })(FileSystem = exports.FileSystem || (exports.FileSystem = {}));\r
7942 function resolveModulePath(workspaceRoot, moduleName, nodePath, tracer) {\r
7943     if (nodePath) {\r
7944         if (!path.isAbsolute(nodePath)) {\r
7945             nodePath = path.join(workspaceRoot, nodePath);\r
7946         }\r
7947         return resolve(moduleName, nodePath, nodePath, tracer).then((value) => {\r
7948             if (FileSystem.isParent(nodePath, value)) {\r
7949                 return value;\r
7950             }\r
7951             else {\r
7952                 return Promise.reject(new Error(`Failed to load ${moduleName} from node path location.`));\r
7953             }\r
7954         }).then(undefined, (_error) => {\r
7955             return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer);\r
7956         });\r
7957     }\r
7958     else {\r
7959         return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer);\r
7960     }\r
7961 }\r
7962 exports.resolveModulePath = resolveModulePath;\r
7963 //# sourceMappingURL=files.js.map
7964 /* WEBPACK VAR INJECTION */}.call(this, "/index.js"))
7965
7966 /***/ }),
7967 /* 46 */
7968 /***/ (function(module, exports) {
7969
7970 module.exports = require("url");
7971
7972 /***/ }),
7973 /* 47 */
7974 /***/ (function(module, exports) {
7975
7976 module.exports = require("child_process");
7977
7978 /***/ }),
7979 /* 48 */
7980 /***/ (function(module, exports, __webpack_require__) {
7981
7982 "use strict";
7983 /* --------------------------------------------------------------------------------------------\r
7984  * Copyright (c) Microsoft Corporation. All rights reserved.\r
7985  * Licensed under the MIT License. See License.txt in the project root for license information.\r
7986  * ------------------------------------------------------------------------------------------ */\r
7987 \r
7988 Object.defineProperty(exports, "__esModule", { value: true });\r
7989 const vscode_languageserver_protocol_1 = __webpack_require__(4);\r
7990 exports.CallHierarchyFeature = (Base) => {\r
7991     return class extends Base {\r
7992         get callHierarchy() {\r
7993             return {\r
7994                 onPrepare: (handler) => {\r
7995                     this.connection.onRequest(vscode_languageserver_protocol_1.Proposed.CallHierarchyPrepareRequest.type, (params, cancel) => {\r
7996                         return handler(params, cancel, this.attachWorkDoneProgress(params), undefined);\r
7997                     });\r
7998                 },\r
7999                 onIncomingCalls: (handler) => {\r
8000                     const type = vscode_languageserver_protocol_1.Proposed.CallHierarchyIncomingCallsRequest.type;\r
8001                     this.connection.onRequest(type, (params, cancel) => {\r
8002                         return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));\r
8003                     });\r
8004                 },\r
8005                 onOutgoingCalls: (handler) => {\r
8006                     const type = vscode_languageserver_protocol_1.Proposed.CallHierarchyOutgoingCallsRequest.type;\r
8007                     this.connection.onRequest(type, (params, cancel) => {\r
8008                         return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));\r
8009                     });\r
8010                 }\r
8011             };\r
8012         }\r
8013     };\r
8014 };\r
8015 //# sourceMappingURL=callHierarchy.proposed.js.map
8016
8017 /***/ }),
8018 /* 49 */
8019 /***/ (function(module, exports, __webpack_require__) {
8020
8021 "use strict";
8022 /* --------------------------------------------------------------------------------------------\r
8023  * Copyright (c) Microsoft Corporation. All rights reserved.\r
8024  * Licensed under the MIT License. See License.txt in the project root for license information.\r
8025  * ------------------------------------------------------------------------------------------ */\r
8026 \r
8027 Object.defineProperty(exports, "__esModule", { value: true });\r
8028 const vscode_languageserver_protocol_1 = __webpack_require__(4);\r
8029 exports.SemanticTokensFeature = (Base) => {\r
8030     return class extends Base {\r
8031         get semanticTokens() {\r
8032             return {\r
8033                 on: (handler) => {\r
8034                     const type = vscode_languageserver_protocol_1.Proposed.SemanticTokensRequest.type;\r
8035                     this.connection.onRequest(type, (params, cancel) => {\r
8036                         return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));\r
8037                     });\r
8038                 },\r
8039                 onEdits: (handler) => {\r
8040                     const type = vscode_languageserver_protocol_1.Proposed.SemanticTokensEditsRequest.type;\r
8041                     this.connection.onRequest(type, (params, cancel) => {\r
8042                         return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));\r
8043                     });\r
8044                 },\r
8045                 onRange: (handler) => {\r
8046                     const type = vscode_languageserver_protocol_1.Proposed.SemanticTokensRangeRequest.type;\r
8047                     this.connection.onRequest(type, (params, cancel) => {\r
8048                         return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));\r
8049                     });\r
8050                 }\r
8051             };\r
8052         }\r
8053     };\r
8054 };\r
8055 class SemanticTokensBuilder {\r
8056     constructor() {\r
8057         this._prevData = undefined;\r
8058         this.initialize();\r
8059     }\r
8060     initialize() {\r
8061         this._id = Date.now();\r
8062         this._prevLine = 0;\r
8063         this._prevChar = 0;\r
8064         this._data = [];\r
8065         this._dataLen = 0;\r
8066     }\r
8067     push(line, char, length, tokenType, tokenModifiers) {\r
8068         let pushLine = line;\r
8069         let pushChar = char;\r
8070         if (this._dataLen > 0) {\r
8071             pushLine -= this._prevLine;\r
8072             if (pushLine === 0) {\r
8073                 pushChar -= this._prevChar;\r
8074             }\r
8075         }\r
8076         this._data[this._dataLen++] = pushLine;\r
8077         this._data[this._dataLen++] = pushChar;\r
8078         this._data[this._dataLen++] = length;\r
8079         this._data[this._dataLen++] = tokenType;\r
8080         this._data[this._dataLen++] = tokenModifiers;\r
8081         this._prevLine = line;\r
8082         this._prevChar = char;\r
8083     }\r
8084     get id() {\r
8085         return this._id.toString();\r
8086     }\r
8087     previousResult(id) {\r
8088         if (this.id === id) {\r
8089             this._prevData = this._data;\r
8090         }\r
8091         this.initialize();\r
8092     }\r
8093     build() {\r
8094         this._prevData = undefined;\r
8095         return {\r
8096             resultId: this.id,\r
8097             data: this._data\r
8098         };\r
8099     }\r
8100     canBuildEdits() {\r
8101         return this._prevData !== undefined;\r
8102     }\r
8103     buildEdits() {\r
8104         if (this._prevData !== undefined) {\r
8105             const prevDataLength = this._prevData.length;\r
8106             const dataLength = this._data.length;\r
8107             let startIndex = 0;\r
8108             while (startIndex < dataLength && startIndex < prevDataLength && this._prevData[startIndex] === this._data[startIndex]) {\r
8109                 startIndex++;\r
8110             }\r
8111             if (startIndex < dataLength && startIndex < prevDataLength) {\r
8112                 // Find end index\r
8113                 let endIndex = 0;\r
8114                 while (endIndex < dataLength && endIndex < prevDataLength && this._prevData[prevDataLength - 1 - endIndex] === this._data[dataLength - 1 - endIndex]) {\r
8115                     endIndex++;\r
8116                 }\r
8117                 const newData = this._data.slice(startIndex, dataLength - endIndex);\r
8118                 const result = {\r
8119                     resultId: this.id,\r
8120                     edits: [\r
8121                         { start: startIndex, deleteCount: prevDataLength - endIndex - startIndex, data: newData }\r
8122                     ]\r
8123                 };\r
8124                 return result;\r
8125             }\r
8126             else if (startIndex < dataLength) {\r
8127                 return { resultId: this.id, edits: [\r
8128                         { start: startIndex, deleteCount: 0, data: this._data.slice(startIndex) }\r
8129                     ] };\r
8130             }\r
8131             else if (startIndex < prevDataLength) {\r
8132                 return { resultId: this.id, edits: [\r
8133                         { start: startIndex, deleteCount: prevDataLength - startIndex }\r
8134                     ] };\r
8135             }\r
8136             else {\r
8137                 return { resultId: this.id, edits: [] };\r
8138             }\r
8139         }\r
8140         else {\r
8141             return this.build();\r
8142         }\r
8143     }\r
8144 }\r
8145 exports.SemanticTokensBuilder = SemanticTokensBuilder;\r
8146 //# sourceMappingURL=sematicTokens.proposed.js.map
8147
8148 /***/ }),
8149 /* 50 */
8150 /***/ (function(module, __webpack_exports__, __webpack_require__) {
8151
8152 "use strict";
8153 __webpack_require__.r(__webpack_exports__);
8154 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return URI; });
8155 /*---------------------------------------------------------------------------------------------
8156  *  Copyright (c) Microsoft Corporation. All rights reserved.
8157  *  Licensed under the MIT License. See License.txt in the project root for license information.
8158  *--------------------------------------------------------------------------------------------*/
8159
8160 var __extends = (undefined && undefined.__extends) || (function () {
8161     var extendStatics = function (d, b) {
8162         extendStatics = Object.setPrototypeOf ||
8163             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
8164             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
8165         return extendStatics(d, b);
8166     };
8167     return function (d, b) {
8168         extendStatics(d, b);
8169         function __() { this.constructor = d; }
8170         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8171     };
8172 })();
8173 var _a;
8174 var isWindows;
8175 if (typeof process === 'object') {
8176     isWindows = process.platform === 'win32';
8177 }
8178 else if (typeof navigator === 'object') {
8179     var userAgent = navigator.userAgent;
8180     isWindows = userAgent.indexOf('Windows') >= 0;
8181 }
8182 function isHighSurrogate(charCode) {
8183     return (0xD800 <= charCode && charCode <= 0xDBFF);
8184 }
8185 function isLowSurrogate(charCode) {
8186     return (0xDC00 <= charCode && charCode <= 0xDFFF);
8187 }
8188 function isLowerAsciiHex(code) {
8189     return code >= 97 /* a */ && code <= 102 /* f */;
8190 }
8191 function isLowerAsciiLetter(code) {
8192     return code >= 97 /* a */ && code <= 122 /* z */;
8193 }
8194 function isUpperAsciiLetter(code) {
8195     return code >= 65 /* A */ && code <= 90 /* Z */;
8196 }
8197 function isAsciiLetter(code) {
8198     return isLowerAsciiLetter(code) || isUpperAsciiLetter(code);
8199 }
8200 //#endregion
8201 var _schemePattern = /^\w[\w\d+.-]*$/;
8202 var _singleSlashStart = /^\//;
8203 var _doubleSlashStart = /^\/\//;
8204 function _validateUri(ret, _strict) {
8205     // scheme, must be set
8206     if (!ret.scheme && _strict) {
8207         throw new Error("[UriError]: Scheme is missing: {scheme: \"\", authority: \"" + ret.authority + "\", path: \"" + ret.path + "\", query: \"" + ret.query + "\", fragment: \"" + ret.fragment + "\"}");
8208     }
8209     // scheme, https://tools.ietf.org/html/rfc3986#section-3.1
8210     // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
8211     if (ret.scheme && !_schemePattern.test(ret.scheme)) {
8212         throw new Error('[UriError]: Scheme contains illegal characters.');
8213     }
8214     // path, http://tools.ietf.org/html/rfc3986#section-3.3
8215     // If a URI contains an authority component, then the path component
8216     // must either be empty or begin with a slash ("/") character.  If a URI
8217     // does not contain an authority component, then the path cannot begin
8218     // with two slash characters ("//").
8219     if (ret.path) {
8220         if (ret.authority) {
8221             if (!_singleSlashStart.test(ret.path)) {
8222                 throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
8223             }
8224         }
8225         else {
8226             if (_doubleSlashStart.test(ret.path)) {
8227                 throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
8228             }
8229         }
8230     }
8231 }
8232 // for a while we allowed uris *without* schemes and this is the migration
8233 // for them, e.g. an uri without scheme and without strict-mode warns and falls
8234 // back to the file-scheme. that should cause the least carnage and still be a
8235 // clear warning
8236 function _schemeFix(scheme, _strict) {
8237     if (!scheme && !_strict) {
8238         return 'file';
8239     }
8240     return scheme;
8241 }
8242 // implements a bit of https://tools.ietf.org/html/rfc3986#section-5
8243 function _referenceResolution(scheme, path) {
8244     // the slash-character is our 'default base' as we don't
8245     // support constructing URIs relative to other URIs. This
8246     // also means that we alter and potentially break paths.
8247     // see https://tools.ietf.org/html/rfc3986#section-5.1.4
8248     switch (scheme) {
8249         case 'https':
8250         case 'http':
8251         case 'file':
8252             if (!path) {
8253                 path = _slash;
8254             }
8255             else if (path[0] !== _slash) {
8256                 path = _slash + path;
8257             }
8258             break;
8259     }
8260     return path;
8261 }
8262 var _empty = '';
8263 var _slash = '/';
8264 var _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
8265 /**
8266  * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
8267  * This class is a simple parser which creates the basic component parts
8268  * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
8269  * and encoding.
8270  *
8271  *       foo://example.com:8042/over/there?name=ferret#nose
8272  *       \_/   \______________/\_________/ \_________/ \__/
8273  *        |           |            |            |        |
8274  *     scheme     authority       path        query   fragment
8275  *        |   _____________________|__
8276  *       / \ /                        \
8277  *       urn:example:animal:ferret:nose
8278  */
8279 var URI = /** @class */ (function () {
8280     /**
8281      * @internal
8282      */
8283     function URI(schemeOrData, authority, path, query, fragment, _strict) {
8284         if (_strict === void 0) { _strict = false; }
8285         if (typeof schemeOrData === 'object') {
8286             this.scheme = schemeOrData.scheme || _empty;
8287             this.authority = schemeOrData.authority || _empty;
8288             this.path = schemeOrData.path || _empty;
8289             this.query = schemeOrData.query || _empty;
8290             this.fragment = schemeOrData.fragment || _empty;
8291             // no validation because it's this URI
8292             // that creates uri components.
8293             // _validateUri(this);
8294         }
8295         else {
8296             this.scheme = _schemeFix(schemeOrData, _strict);
8297             this.authority = authority || _empty;
8298             this.path = _referenceResolution(this.scheme, path || _empty);
8299             this.query = query || _empty;
8300             this.fragment = fragment || _empty;
8301             _validateUri(this, _strict);
8302         }
8303     }
8304     URI.isUri = function (thing) {
8305         if (thing instanceof URI) {
8306             return true;
8307         }
8308         if (!thing) {
8309             return false;
8310         }
8311         return typeof thing.authority === 'string'
8312             && typeof thing.fragment === 'string'
8313             && typeof thing.path === 'string'
8314             && typeof thing.query === 'string'
8315             && typeof thing.scheme === 'string'
8316             && typeof thing.fsPath === 'function'
8317             && typeof thing.with === 'function'
8318             && typeof thing.toString === 'function';
8319     };
8320     Object.defineProperty(URI.prototype, "fsPath", {
8321         // ---- filesystem path -----------------------
8322         /**
8323          * Returns a string representing the corresponding file system path of this URI.
8324          * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
8325          * platform specific path separator.
8326          *
8327          * * Will *not* validate the path for invalid characters and semantics.
8328          * * Will *not* look at the scheme of this URI.
8329          * * The result shall *not* be used for display purposes but for accessing a file on disk.
8330          *
8331          *
8332          * The *difference* to `URI#path` is the use of the platform specific separator and the handling
8333          * of UNC paths. See the below sample of a file-uri with an authority (UNC path).
8334          *
8335          * ```ts
8336             const u = URI.parse('file://server/c$/folder/file.txt')
8337             u.authority === 'server'
8338             u.path === '/shares/c$/file.txt'
8339             u.fsPath === '\\server\c$\folder\file.txt'
8340         ```
8341          *
8342          * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,
8343          * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working
8344          * with URIs that represent files on disk (`file` scheme).
8345          */
8346         get: function () {
8347             // if (this.scheme !== 'file') {
8348             //  console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
8349             // }
8350             return _makeFsPath(this);
8351         },
8352         enumerable: true,
8353         configurable: true
8354     });
8355     // ---- modify to new -------------------------
8356     URI.prototype.with = function (change) {
8357         if (!change) {
8358             return this;
8359         }
8360         var scheme = change.scheme, authority = change.authority, path = change.path, query = change.query, fragment = change.fragment;
8361         if (scheme === undefined) {
8362             scheme = this.scheme;
8363         }
8364         else if (scheme === null) {
8365             scheme = _empty;
8366         }
8367         if (authority === undefined) {
8368             authority = this.authority;
8369         }
8370         else if (authority === null) {
8371             authority = _empty;
8372         }
8373         if (path === undefined) {
8374             path = this.path;
8375         }
8376         else if (path === null) {
8377             path = _empty;
8378         }
8379         if (query === undefined) {
8380             query = this.query;
8381         }
8382         else if (query === null) {
8383             query = _empty;
8384         }
8385         if (fragment === undefined) {
8386             fragment = this.fragment;
8387         }
8388         else if (fragment === null) {
8389             fragment = _empty;
8390         }
8391         if (scheme === this.scheme
8392             && authority === this.authority
8393             && path === this.path
8394             && query === this.query
8395             && fragment === this.fragment) {
8396             return this;
8397         }
8398         return new _URI(scheme, authority, path, query, fragment);
8399     };
8400     // ---- parse & validate ------------------------
8401     /**
8402      * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`,
8403      * `file:///usr/home`, or `scheme:with/path`.
8404      *
8405      * @param value A string which represents an URI (see `URI#toString`).
8406      */
8407     URI.parse = function (value, _strict) {
8408         if (_strict === void 0) { _strict = false; }
8409         var match = _regexp.exec(value);
8410         if (!match) {
8411             return new _URI(_empty, _empty, _empty, _empty, _empty);
8412         }
8413         return new _URI(match[2] || _empty, decodeURIComponent(match[4] || _empty), decodeURIComponent(match[5] || _empty), decodeURIComponent(match[7] || _empty), decodeURIComponent(match[9] || _empty), _strict);
8414     };
8415     /**
8416      * Creates a new URI from a file system path, e.g. `c:\my\files`,
8417      * `/usr/home`, or `\\server\share\some\path`.
8418      *
8419      * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
8420      * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
8421      * `URI.parse('file://' + path)` because the path might contain characters that are
8422      * interpreted (# and ?). See the following sample:
8423      * ```ts
8424     const good = URI.file('/coding/c#/project1');
8425     good.scheme === 'file';
8426     good.path === '/coding/c#/project1';
8427     good.fragment === '';
8428     const bad = URI.parse('file://' + '/coding/c#/project1');
8429     bad.scheme === 'file';
8430     bad.path === '/coding/c'; // path is now broken
8431     bad.fragment === '/project1';
8432     ```
8433      *
8434      * @param path A file system path (see `URI#fsPath`)
8435      */
8436     URI.file = function (path) {
8437         var authority = _empty;
8438         // normalize to fwd-slashes on windows,
8439         // on other systems bwd-slashes are valid
8440         // filename character, eg /f\oo/ba\r.txt
8441         if (isWindows) {
8442             path = path.replace(/\\/g, _slash);
8443         }
8444         // check for authority as used in UNC shares
8445         // or use the path as given
8446         if (path[0] === _slash && path[1] === _slash) {
8447             var idx = path.indexOf(_slash, 2);
8448             if (idx === -1) {
8449                 authority = path.substring(2);
8450                 path = _slash;
8451             }
8452             else {
8453                 authority = path.substring(2, idx);
8454                 path = path.substring(idx) || _slash;
8455             }
8456         }
8457         return new _URI('file', authority, path, _empty, _empty);
8458     };
8459     URI.from = function (components) {
8460         return new _URI(components.scheme, components.authority, components.path, components.query, components.fragment);
8461     };
8462     // ---- printing/externalize ---------------------------
8463     /**
8464      * Creates a string representation for this URI. It's guaranteed that calling
8465      * `URI.parse` with the result of this function creates an URI which is equal
8466      * to this URI.
8467      *
8468      * * The result shall *not* be used for display purposes but for externalization or transport.
8469      * * The result will be encoded using the percentage encoding and encoding happens mostly
8470      * ignore the scheme-specific encoding rules.
8471      *
8472      * @param skipEncoding Do not encode the result, default is `false`
8473      */
8474     URI.prototype.toString = function (skipEncoding) {
8475         if (skipEncoding === void 0) { skipEncoding = false; }
8476         return _asFormatted(this, skipEncoding);
8477     };
8478     URI.prototype.toJSON = function () {
8479         return this;
8480     };
8481     URI.revive = function (data) {
8482         if (!data) {
8483             return data;
8484         }
8485         else if (data instanceof URI) {
8486             return data;
8487         }
8488         else {
8489             var result = new _URI(data);
8490             result._formatted = data.external;
8491             result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null;
8492             return result;
8493         }
8494     };
8495     return URI;
8496 }());
8497
8498 var _pathSepMarker = isWindows ? 1 : undefined;
8499 // tslint:disable-next-line:class-name
8500 var _URI = /** @class */ (function (_super) {
8501     __extends(_URI, _super);
8502     function _URI() {
8503         var _this = _super !== null && _super.apply(this, arguments) || this;
8504         _this._formatted = null;
8505         _this._fsPath = null;
8506         return _this;
8507     }
8508     Object.defineProperty(_URI.prototype, "fsPath", {
8509         get: function () {
8510             if (!this._fsPath) {
8511                 this._fsPath = _makeFsPath(this);
8512             }
8513             return this._fsPath;
8514         },
8515         enumerable: true,
8516         configurable: true
8517     });
8518     _URI.prototype.toString = function (skipEncoding) {
8519         if (skipEncoding === void 0) { skipEncoding = false; }
8520         if (!skipEncoding) {
8521             if (!this._formatted) {
8522                 this._formatted = _asFormatted(this, false);
8523             }
8524             return this._formatted;
8525         }
8526         else {
8527             // we don't cache that
8528             return _asFormatted(this, true);
8529         }
8530     };
8531     _URI.prototype.toJSON = function () {
8532         var res = {
8533             $mid: 1
8534         };
8535         // cached state
8536         if (this._fsPath) {
8537             res.fsPath = this._fsPath;
8538             res._sep = _pathSepMarker;
8539         }
8540         if (this._formatted) {
8541             res.external = this._formatted;
8542         }
8543         // uri components
8544         if (this.path) {
8545             res.path = this.path;
8546         }
8547         if (this.scheme) {
8548             res.scheme = this.scheme;
8549         }
8550         if (this.authority) {
8551             res.authority = this.authority;
8552         }
8553         if (this.query) {
8554             res.query = this.query;
8555         }
8556         if (this.fragment) {
8557             res.fragment = this.fragment;
8558         }
8559         return res;
8560     };
8561     return _URI;
8562 }(URI));
8563 // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
8564 var encodeTable = (_a = {},
8565     _a[58 /* Colon */] = '%3A',
8566     _a[47 /* Slash */] = '%2F',
8567     _a[63 /* QuestionMark */] = '%3F',
8568     _a[35 /* Hash */] = '%23',
8569     _a[91 /* OpenSquareBracket */] = '%5B',
8570     _a[93 /* CloseSquareBracket */] = '%5D',
8571     _a[64 /* AtSign */] = '%40',
8572     _a[33 /* ExclamationMark */] = '%21',
8573     _a[36 /* DollarSign */] = '%24',
8574     _a[38 /* Ampersand */] = '%26',
8575     _a[39 /* SingleQuote */] = '%27',
8576     _a[40 /* OpenParen */] = '%28',
8577     _a[41 /* CloseParen */] = '%29',
8578     _a[42 /* Asterisk */] = '%2A',
8579     _a[43 /* Plus */] = '%2B',
8580     _a[44 /* Comma */] = '%2C',
8581     _a[59 /* Semicolon */] = '%3B',
8582     _a[61 /* Equals */] = '%3D',
8583     _a[32 /* Space */] = '%20',
8584     _a);
8585 function encodeURIComponentFast(uriComponent, allowSlash) {
8586     var res = undefined;
8587     var nativeEncodePos = -1;
8588     for (var pos = 0; pos < uriComponent.length; pos++) {
8589         var code = uriComponent.charCodeAt(pos);
8590         // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3
8591         if ((code >= 97 /* a */ && code <= 122 /* z */)
8592             || (code >= 65 /* A */ && code <= 90 /* Z */)
8593             || (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */)
8594             || code === 45 /* Dash */
8595             || code === 46 /* Period */
8596             || code === 95 /* Underline */
8597             || code === 126 /* Tilde */
8598             || (allowSlash && code === 47 /* Slash */)) {
8599             // check if we are delaying native encode
8600             if (nativeEncodePos !== -1) {
8601                 res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
8602                 nativeEncodePos = -1;
8603             }
8604             // check if we write into a new string (by default we try to return the param)
8605             if (res !== undefined) {
8606                 res += uriComponent.charAt(pos);
8607             }
8608         }
8609         else {
8610             // encoding needed, we need to allocate a new string
8611             if (res === undefined) {
8612                 res = uriComponent.substr(0, pos);
8613             }
8614             // check with default table first
8615             var escaped = encodeTable[code];
8616             if (escaped !== undefined) {
8617                 // check if we are delaying native encode
8618                 if (nativeEncodePos !== -1) {
8619                     res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
8620                     nativeEncodePos = -1;
8621                 }
8622                 // append escaped variant to result
8623                 res += escaped;
8624             }
8625             else if (nativeEncodePos === -1) {
8626                 // use native encode only when needed
8627                 nativeEncodePos = pos;
8628             }
8629         }
8630     }
8631     if (nativeEncodePos !== -1) {
8632         res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
8633     }
8634     return res !== undefined ? res : uriComponent;
8635 }
8636 function encodeURIComponentMinimal(path) {
8637     var res = undefined;
8638     for (var pos = 0; pos < path.length; pos++) {
8639         var code = path.charCodeAt(pos);
8640         if (code === 35 /* Hash */ || code === 63 /* QuestionMark */) {
8641             if (res === undefined) {
8642                 res = path.substr(0, pos);
8643             }
8644             res += encodeTable[code];
8645         }
8646         else {
8647             if (res !== undefined) {
8648                 res += path[pos];
8649             }
8650         }
8651     }
8652     return res !== undefined ? res : path;
8653 }
8654 /**
8655  * Compute `fsPath` for the given uri
8656  */
8657 function _makeFsPath(uri) {
8658     var value;
8659     if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') {
8660         // unc path: file://shares/c$/far/boo
8661         value = "//" + uri.authority + uri.path;
8662     }
8663     else if (uri.path.charCodeAt(0) === 47 /* Slash */
8664         && (uri.path.charCodeAt(1) >= 65 /* A */ && uri.path.charCodeAt(1) <= 90 /* Z */ || uri.path.charCodeAt(1) >= 97 /* a */ && uri.path.charCodeAt(1) <= 122 /* z */)
8665         && uri.path.charCodeAt(2) === 58 /* Colon */) {
8666         // windows drive letter: file:///c:/far/boo
8667         value = uri.path[1].toLowerCase() + uri.path.substr(2);
8668     }
8669     else {
8670         // other path
8671         value = uri.path;
8672     }
8673     if (isWindows) {
8674         value = value.replace(/\//g, '\\');
8675     }
8676     return value;
8677 }
8678 /**
8679  * Create the external version of a uri
8680  */
8681 function _asFormatted(uri, skipEncoding) {
8682     var encoder = !skipEncoding
8683         ? encodeURIComponentFast
8684         : encodeURIComponentMinimal;
8685     var res = '';
8686     var scheme = uri.scheme, authority = uri.authority, path = uri.path, query = uri.query, fragment = uri.fragment;
8687     if (scheme) {
8688         res += scheme;
8689         res += ':';
8690     }
8691     if (authority || scheme === 'file') {
8692         res += _slash;
8693         res += _slash;
8694     }
8695     if (authority) {
8696         var idx = authority.indexOf('@');
8697         if (idx !== -1) {
8698             // <user>@<auth>
8699             var userinfo = authority.substr(0, idx);
8700             authority = authority.substr(idx + 1);
8701             idx = userinfo.indexOf(':');
8702             if (idx === -1) {
8703                 res += encoder(userinfo, false);
8704             }
8705             else {
8706                 // <user>:<pass>@<auth>
8707                 res += encoder(userinfo.substr(0, idx), false);
8708                 res += ':';
8709                 res += encoder(userinfo.substr(idx + 1), false);
8710             }
8711             res += '@';
8712         }
8713         authority = authority.toLowerCase();
8714         idx = authority.indexOf(':');
8715         if (idx === -1) {
8716             res += encoder(authority, false);
8717         }
8718         else {
8719             // <auth>:<port>
8720             res += encoder(authority.substr(0, idx), false);
8721             res += authority.substr(idx);
8722         }
8723     }
8724     if (path) {
8725         // lower-case windows drive letters in /C:/fff or C:/fff
8726         if (path.length >= 3 && path.charCodeAt(0) === 47 /* Slash */ && path.charCodeAt(2) === 58 /* Colon */) {
8727             var code = path.charCodeAt(1);
8728             if (code >= 65 /* A */ && code <= 90 /* Z */) {
8729                 path = "/" + String.fromCharCode(code + 32) + ":" + path.substr(3); // "/c:".length === 3
8730             }
8731         }
8732         else if (path.length >= 2 && path.charCodeAt(1) === 58 /* Colon */) {
8733             var code = path.charCodeAt(0);
8734             if (code >= 65 /* A */ && code <= 90 /* Z */) {
8735                 path = String.fromCharCode(code + 32) + ":" + path.substr(2); // "/c:".length === 3
8736             }
8737         }
8738         // encode the rest of the path
8739         res += encoder(path, true);
8740     }
8741     if (query) {
8742         res += '?';
8743         res += encoder(query, false);
8744     }
8745     if (fragment) {
8746         res += '#';
8747         res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment;
8748     }
8749     return res;
8750 }
8751
8752
8753 /***/ }),
8754 /* 51 */
8755 /***/ (function(module, exports, __webpack_require__) {
8756
8757 "use strict";
8758
8759 Object.defineProperty(exports, "__esModule", { value: true });
8760 var Is;
8761 (function (Is) {
8762     const toString = Object.prototype.toString;
8763     function boolean(value) {
8764         return value === true || value === false;
8765     }
8766     Is.boolean = boolean;
8767     function string(value) {
8768         return toString.call(value) === '[object String]';
8769     }
8770     Is.string = string;
8771 })(Is = exports.Is || (exports.Is = {}));
8772 var DirectoryItem;
8773 (function (DirectoryItem) {
8774     function is(item) {
8775         let candidate = item;
8776         return (candidate &&
8777             Is.string(candidate.directory) &&
8778             (Is.boolean(candidate.changeProcessCWD) ||
8779                 candidate.changeProcessCWD === void 0));
8780     }
8781     DirectoryItem.is = is;
8782 })(DirectoryItem = exports.DirectoryItem || (exports.DirectoryItem = {}));
8783
8784
8785 /***/ }),
8786 /* 52 */
8787 /***/ (function(module, exports, __webpack_require__) {
8788
8789 "use strict";
8790
8791 var __importStar = (this && this.__importStar) || function (mod) {
8792     if (mod && mod.__esModule) return mod;
8793     var result = {};
8794     if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
8795     result["default"] = mod;
8796     return result;
8797 };
8798 var __importDefault = (this && this.__importDefault) || function (mod) {
8799     return (mod && mod.__esModule) ? mod : { "default": mod };
8800 };
8801 Object.defineProperty(exports, "__esModule", { value: true });
8802 const path = __importStar(__webpack_require__(3));
8803 const fast_diff_1 = __importDefault(__webpack_require__(53));
8804 const types_1 = __webpack_require__(51);
8805 const vscode_uri_1 = __webpack_require__(50);
8806 /**
8807  * Check if the path follows this pattern: `\\hostname\sharename`.
8808  *
8809  * @see https://msdn.microsoft.com/en-us/library/gg465305.aspx
8810  * @return A boolean indication if the path is a UNC path, on none-windows
8811  * always false.
8812  */
8813 function isUNC(path) {
8814     if (process.platform !== 'win32') {
8815         // UNC is a windows concept
8816         return false;
8817     }
8818     if (!path || path.length < 5) {
8819         // at least \\a\b
8820         return false;
8821     }
8822     let code = path.charCodeAt(0);
8823     if (code !== 92 /* Backslash */) {
8824         return false;
8825     }
8826     code = path.charCodeAt(1);
8827     if (code !== 92 /* Backslash */) {
8828         return false;
8829     }
8830     let pos = 2;
8831     let start = pos;
8832     for (; pos < path.length; pos++) {
8833         code = path.charCodeAt(pos);
8834         if (code === 92 /* Backslash */) {
8835             break;
8836         }
8837     }
8838     if (start === pos) {
8839         return false;
8840     }
8841     code = path.charCodeAt(pos + 1);
8842     if (isNaN(code) || code === 92 /* Backslash */) {
8843         return false;
8844     }
8845     return true;
8846 }
8847 exports.isUNC = isUNC;
8848 function getFileSystemPath(uri) {
8849     let result = uri.fsPath;
8850     if (process.platform === 'win32' && result.length >= 2 && result[1] === ':') {
8851         // Node by default uses an upper case drive letter and ESLint uses
8852         // === to compare pathes which results in the equal check failing
8853         // if the drive letter is lower case in th URI. Ensure upper case.
8854         return result[0].toUpperCase() + result.substr(1);
8855     }
8856     else {
8857         return result;
8858     }
8859 }
8860 function getFilePath(documentOrUri) {
8861     if (!documentOrUri) {
8862         return undefined;
8863     }
8864     let uri = types_1.Is.string(documentOrUri)
8865         ? vscode_uri_1.URI.parse(documentOrUri)
8866         : vscode_uri_1.URI.parse(documentOrUri.uri);
8867     if (uri.scheme !== 'file') {
8868         return undefined;
8869     }
8870     return getFileSystemPath(uri);
8871 }
8872 exports.getFilePath = getFilePath;
8873 function getAllFixEdits(document, settings) {
8874     const uri = vscode_uri_1.URI.parse(document.uri);
8875     if (uri.scheme != 'file')
8876         return [];
8877     const content = document.getText();
8878     const fixRule = (problem) => {
8879         return settings.autoFixSkipRules.indexOf(problem.ruleId) === -1;
8880     };
8881     const newOptions = Object.assign(Object.assign({}, settings.options), { fix: fixRule });
8882     return executeInWorkspaceDirectory(document, settings, newOptions, (filename, options) => {
8883         if (!settings.validate) {
8884             return [];
8885         }
8886         const engine = new settings.library.CLIEngine(options);
8887         const res = engine.executeOnText(content, filename);
8888         if (!res.results.length)
8889             return [];
8890         const { output } = res.results[0];
8891         if (output == null)
8892             return [];
8893         const change = getChange(content, output);
8894         return [{
8895                 range: {
8896                     start: document.positionAt(change.start),
8897                     end: document.positionAt(change.end)
8898                 },
8899                 newText: change.newText
8900             }];
8901     });
8902 }
8903 exports.getAllFixEdits = getAllFixEdits;
8904 function getChange(oldStr, newStr) {
8905     let result = fast_diff_1.default(oldStr, newStr, 1);
8906     let curr = 0;
8907     let start = -1;
8908     let end = -1;
8909     let newText = '';
8910     let remain = '';
8911     for (let item of result) {
8912         let [t, str] = item;
8913         // equal
8914         if (t == 0) {
8915             curr = curr + str.length;
8916             if (start != -1)
8917                 remain = remain + str;
8918         }
8919         else {
8920             if (start == -1)
8921                 start = curr;
8922             if (t == 1) {
8923                 newText = newText + remain + str;
8924                 end = curr;
8925             }
8926             else {
8927                 newText = newText + remain;
8928                 end = curr + str.length;
8929             }
8930             remain = '';
8931             if (t == -1)
8932                 curr = curr + str.length;
8933         }
8934     }
8935     return { start, end, newText };
8936 }
8937 exports.getChange = getChange;
8938 function executeInWorkspaceDirectory(document, settings, newOptions, callback) {
8939     const filename = getFilePath(document);
8940     const cwd = process.cwd();
8941     try {
8942         if (filename) {
8943             if (settings.workingDirectory) {
8944                 newOptions.cwd = settings.workingDirectory.directory;
8945                 if (settings.workingDirectory.changeProcessCWD) {
8946                     process.chdir(settings.workingDirectory.directory);
8947                 }
8948             }
8949             else if (settings.workspaceFolder) {
8950                 const workspaceFolderUri = vscode_uri_1.URI.parse(settings.workspaceFolder.uri);
8951                 if (workspaceFolderUri.scheme === 'file') {
8952                     const fsPath = getFileSystemPath(workspaceFolderUri);
8953                     newOptions.cwd = fsPath;
8954                     process.chdir(fsPath);
8955                 }
8956             }
8957             else if (!settings.workspaceFolder && !isUNC(filename)) {
8958                 const directory = path.dirname(filename);
8959                 if (directory && path.isAbsolute(directory))
8960                     newOptions.cwd = directory;
8961             }
8962         }
8963         return callback(filename, newOptions);
8964     }
8965     finally {
8966         if (cwd !== process.cwd())
8967             process.chdir(cwd);
8968     }
8969 }
8970 exports.executeInWorkspaceDirectory = executeInWorkspaceDirectory;
8971
8972
8973 /***/ }),
8974 /* 53 */
8975 /***/ (function(module, exports) {
8976
8977 /**
8978  * This library modifies the diff-patch-match library by Neil Fraser
8979  * by removing the patch and match functionality and certain advanced
8980  * options in the diff function. The original license is as follows:
8981  *
8982  * ===
8983  *
8984  * Diff Match and Patch
8985  *
8986  * Copyright 2006 Google Inc.
8987  * http://code.google.com/p/google-diff-match-patch/
8988  *
8989  * Licensed under the Apache License, Version 2.0 (the "License");
8990  * you may not use this file except in compliance with the License.
8991  * You may obtain a copy of the License at
8992  *
8993  *   http://www.apache.org/licenses/LICENSE-2.0
8994  *
8995  * Unless required by applicable law or agreed to in writing, software
8996  * distributed under the License is distributed on an "AS IS" BASIS,
8997  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8998  * See the License for the specific language governing permissions and
8999  * limitations under the License.
9000  */
9001
9002
9003 /**
9004  * The data structure representing a diff is an array of tuples:
9005  * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
9006  * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
9007  */
9008 var DIFF_DELETE = -1;
9009 var DIFF_INSERT = 1;
9010 var DIFF_EQUAL = 0;
9011
9012
9013 /**
9014  * Find the differences between two texts.  Simplifies the problem by stripping
9015  * any common prefix or suffix off the texts before diffing.
9016  * @param {string} text1 Old string to be diffed.
9017  * @param {string} text2 New string to be diffed.
9018  * @param {Int|Object} [cursor_pos] Edit position in text1 or object with more info
9019  * @return {Array} Array of diff tuples.
9020  */
9021 function diff_main(text1, text2, cursor_pos, _fix_unicode) {
9022   // Check for equality
9023   if (text1 === text2) {
9024     if (text1) {
9025       return [[DIFF_EQUAL, text1]];
9026     }
9027     return [];
9028   }
9029
9030   if (cursor_pos != null) {
9031     var editdiff = find_cursor_edit_diff(text1, text2, cursor_pos);
9032     if (editdiff) {
9033       return editdiff;
9034     }
9035   }
9036
9037   // Trim off common prefix (speedup).
9038   var commonlength = diff_commonPrefix(text1, text2);
9039   var commonprefix = text1.substring(0, commonlength);
9040   text1 = text1.substring(commonlength);
9041   text2 = text2.substring(commonlength);
9042
9043   // Trim off common suffix (speedup).
9044   commonlength = diff_commonSuffix(text1, text2);
9045   var commonsuffix = text1.substring(text1.length - commonlength);
9046   text1 = text1.substring(0, text1.length - commonlength);
9047   text2 = text2.substring(0, text2.length - commonlength);
9048
9049   // Compute the diff on the middle block.
9050   var diffs = diff_compute_(text1, text2);
9051
9052   // Restore the prefix and suffix.
9053   if (commonprefix) {
9054     diffs.unshift([DIFF_EQUAL, commonprefix]);
9055   }
9056   if (commonsuffix) {
9057     diffs.push([DIFF_EQUAL, commonsuffix]);
9058   }
9059   diff_cleanupMerge(diffs, _fix_unicode);
9060   return diffs;
9061 };
9062
9063
9064 /**
9065  * Find the differences between two texts.  Assumes that the texts do not
9066  * have any common prefix or suffix.
9067  * @param {string} text1 Old string to be diffed.
9068  * @param {string} text2 New string to be diffed.
9069  * @return {Array} Array of diff tuples.
9070  */
9071 function diff_compute_(text1, text2) {
9072   var diffs;
9073
9074   if (!text1) {
9075     // Just add some text (speedup).
9076     return [[DIFF_INSERT, text2]];
9077   }
9078
9079   if (!text2) {
9080     // Just delete some text (speedup).
9081     return [[DIFF_DELETE, text1]];
9082   }
9083
9084   var longtext = text1.length > text2.length ? text1 : text2;
9085   var shorttext = text1.length > text2.length ? text2 : text1;
9086   var i = longtext.indexOf(shorttext);
9087   if (i !== -1) {
9088     // Shorter text is inside the longer text (speedup).
9089     diffs = [
9090       [DIFF_INSERT, longtext.substring(0, i)],
9091       [DIFF_EQUAL, shorttext],
9092       [DIFF_INSERT, longtext.substring(i + shorttext.length)]
9093     ];
9094     // Swap insertions for deletions if diff is reversed.
9095     if (text1.length > text2.length) {
9096       diffs[0][0] = diffs[2][0] = DIFF_DELETE;
9097     }
9098     return diffs;
9099   }
9100
9101   if (shorttext.length === 1) {
9102     // Single character string.
9103     // After the previous speedup, the character can't be an equality.
9104     return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
9105   }
9106
9107   // Check to see if the problem can be split in two.
9108   var hm = diff_halfMatch_(text1, text2);
9109   if (hm) {
9110     // A half-match was found, sort out the return data.
9111     var text1_a = hm[0];
9112     var text1_b = hm[1];
9113     var text2_a = hm[2];
9114     var text2_b = hm[3];
9115     var mid_common = hm[4];
9116     // Send both pairs off for separate processing.
9117     var diffs_a = diff_main(text1_a, text2_a);
9118     var diffs_b = diff_main(text1_b, text2_b);
9119     // Merge the results.
9120     return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b);
9121   }
9122
9123   return diff_bisect_(text1, text2);
9124 };
9125
9126
9127 /**
9128  * Find the 'middle snake' of a diff, split the problem in two
9129  * and return the recursively constructed diff.
9130  * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
9131  * @param {string} text1 Old string to be diffed.
9132  * @param {string} text2 New string to be diffed.
9133  * @return {Array} Array of diff tuples.
9134  * @private
9135  */
9136 function diff_bisect_(text1, text2) {
9137   // Cache the text lengths to prevent multiple calls.
9138   var text1_length = text1.length;
9139   var text2_length = text2.length;
9140   var max_d = Math.ceil((text1_length + text2_length) / 2);
9141   var v_offset = max_d;
9142   var v_length = 2 * max_d;
9143   var v1 = new Array(v_length);
9144   var v2 = new Array(v_length);
9145   // Setting all elements to -1 is faster in Chrome & Firefox than mixing
9146   // integers and undefined.
9147   for (var x = 0; x < v_length; x++) {
9148     v1[x] = -1;
9149     v2[x] = -1;
9150   }
9151   v1[v_offset + 1] = 0;
9152   v2[v_offset + 1] = 0;
9153   var delta = text1_length - text2_length;
9154   // If the total number of characters is odd, then the front path will collide
9155   // with the reverse path.
9156   var front = (delta % 2 !== 0);
9157   // Offsets for start and end of k loop.
9158   // Prevents mapping of space beyond the grid.
9159   var k1start = 0;
9160   var k1end = 0;
9161   var k2start = 0;
9162   var k2end = 0;
9163   for (var d = 0; d < max_d; d++) {
9164     // Walk the front path one step.
9165     for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
9166       var k1_offset = v_offset + k1;
9167       var x1;
9168       if (k1 === -d || (k1 !== d && v1[k1_offset - 1] < v1[k1_offset + 1])) {
9169         x1 = v1[k1_offset + 1];
9170       } else {
9171         x1 = v1[k1_offset - 1] + 1;
9172       }
9173       var y1 = x1 - k1;
9174       while (
9175         x1 < text1_length && y1 < text2_length &&
9176         text1.charAt(x1) === text2.charAt(y1)
9177       ) {
9178         x1++;
9179         y1++;
9180       }
9181       v1[k1_offset] = x1;
9182       if (x1 > text1_length) {
9183         // Ran off the right of the graph.
9184         k1end += 2;
9185       } else if (y1 > text2_length) {
9186         // Ran off the bottom of the graph.
9187         k1start += 2;
9188       } else if (front) {
9189         var k2_offset = v_offset + delta - k1;
9190         if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] !== -1) {
9191           // Mirror x2 onto top-left coordinate system.
9192           var x2 = text1_length - v2[k2_offset];
9193           if (x1 >= x2) {
9194             // Overlap detected.
9195             return diff_bisectSplit_(text1, text2, x1, y1);
9196           }
9197         }
9198       }
9199     }
9200
9201     // Walk the reverse path one step.
9202     for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
9203       var k2_offset = v_offset + k2;
9204       var x2;
9205       if (k2 === -d || (k2 !== d && v2[k2_offset - 1] < v2[k2_offset + 1])) {
9206         x2 = v2[k2_offset + 1];
9207       } else {
9208         x2 = v2[k2_offset - 1] + 1;
9209       }
9210       var y2 = x2 - k2;
9211       while (
9212         x2 < text1_length && y2 < text2_length &&
9213         text1.charAt(text1_length - x2 - 1) === text2.charAt(text2_length - y2 - 1)
9214       ) {
9215         x2++;
9216         y2++;
9217       }
9218       v2[k2_offset] = x2;
9219       if (x2 > text1_length) {
9220         // Ran off the left of the graph.
9221         k2end += 2;
9222       } else if (y2 > text2_length) {
9223         // Ran off the top of the graph.
9224         k2start += 2;
9225       } else if (!front) {
9226         var k1_offset = v_offset + delta - k2;
9227         if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] !== -1) {
9228           var x1 = v1[k1_offset];
9229           var y1 = v_offset + x1 - k1_offset;
9230           // Mirror x2 onto top-left coordinate system.
9231           x2 = text1_length - x2;
9232           if (x1 >= x2) {
9233             // Overlap detected.
9234             return diff_bisectSplit_(text1, text2, x1, y1);
9235           }
9236         }
9237       }
9238     }
9239   }
9240   // Diff took too long and hit the deadline or
9241   // number of diffs equals number of characters, no commonality at all.
9242   return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
9243 };
9244
9245
9246 /**
9247  * Given the location of the 'middle snake', split the diff in two parts
9248  * and recurse.
9249  * @param {string} text1 Old string to be diffed.
9250  * @param {string} text2 New string to be diffed.
9251  * @param {number} x Index of split point in text1.
9252  * @param {number} y Index of split point in text2.
9253  * @return {Array} Array of diff tuples.
9254  */
9255 function diff_bisectSplit_(text1, text2, x, y) {
9256   var text1a = text1.substring(0, x);
9257   var text2a = text2.substring(0, y);
9258   var text1b = text1.substring(x);
9259   var text2b = text2.substring(y);
9260
9261   // Compute both diffs serially.
9262   var diffs = diff_main(text1a, text2a);
9263   var diffsb = diff_main(text1b, text2b);
9264
9265   return diffs.concat(diffsb);
9266 };
9267
9268
9269 /**
9270  * Determine the common prefix of two strings.
9271  * @param {string} text1 First string.
9272  * @param {string} text2 Second string.
9273  * @return {number} The number of characters common to the start of each
9274  *     string.
9275  */
9276 function diff_commonPrefix(text1, text2) {
9277   // Quick check for common null cases.
9278   if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {
9279     return 0;
9280   }
9281   // Binary search.
9282   // Performance analysis: http://neil.fraser.name/news/2007/10/09/
9283   var pointermin = 0;
9284   var pointermax = Math.min(text1.length, text2.length);
9285   var pointermid = pointermax;
9286   var pointerstart = 0;
9287   while (pointermin < pointermid) {
9288     if (
9289       text1.substring(pointerstart, pointermid) ==
9290       text2.substring(pointerstart, pointermid)
9291     ) {
9292       pointermin = pointermid;
9293       pointerstart = pointermin;
9294     } else {
9295       pointermax = pointermid;
9296     }
9297     pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
9298   }
9299
9300   if (is_surrogate_pair_start(text1.charCodeAt(pointermid - 1))) {
9301     pointermid--;
9302   }
9303
9304   return pointermid;
9305 };
9306
9307
9308 /**
9309  * Determine the common suffix of two strings.
9310  * @param {string} text1 First string.
9311  * @param {string} text2 Second string.
9312  * @return {number} The number of characters common to the end of each string.
9313  */
9314 function diff_commonSuffix(text1, text2) {
9315   // Quick check for common null cases.
9316   if (!text1 || !text2 || text1.slice(-1) !== text2.slice(-1)) {
9317     return 0;
9318   }
9319   // Binary search.
9320   // Performance analysis: http://neil.fraser.name/news/2007/10/09/
9321   var pointermin = 0;
9322   var pointermax = Math.min(text1.length, text2.length);
9323   var pointermid = pointermax;
9324   var pointerend = 0;
9325   while (pointermin < pointermid) {
9326     if (
9327       text1.substring(text1.length - pointermid, text1.length - pointerend) ==
9328       text2.substring(text2.length - pointermid, text2.length - pointerend)
9329     ) {
9330       pointermin = pointermid;
9331       pointerend = pointermin;
9332     } else {
9333       pointermax = pointermid;
9334     }
9335     pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
9336   }
9337
9338   if (is_surrogate_pair_end(text1.charCodeAt(text1.length - pointermid))) {
9339     pointermid--;
9340   }
9341
9342   return pointermid;
9343 };
9344
9345
9346 /**
9347  * Do the two texts share a substring which is at least half the length of the
9348  * longer text?
9349  * This speedup can produce non-minimal diffs.
9350  * @param {string} text1 First string.
9351  * @param {string} text2 Second string.
9352  * @return {Array.<string>} Five element Array, containing the prefix of
9353  *     text1, the suffix of text1, the prefix of text2, the suffix of
9354  *     text2 and the common middle.  Or null if there was no match.
9355  */
9356 function diff_halfMatch_(text1, text2) {
9357   var longtext = text1.length > text2.length ? text1 : text2;
9358   var shorttext = text1.length > text2.length ? text2 : text1;
9359   if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
9360     return null;  // Pointless.
9361   }
9362
9363   /**
9364    * Does a substring of shorttext exist within longtext such that the substring
9365    * is at least half the length of longtext?
9366    * Closure, but does not reference any external variables.
9367    * @param {string} longtext Longer string.
9368    * @param {string} shorttext Shorter string.
9369    * @param {number} i Start index of quarter length substring within longtext.
9370    * @return {Array.<string>} Five element Array, containing the prefix of
9371    *     longtext, the suffix of longtext, the prefix of shorttext, the suffix
9372    *     of shorttext and the common middle.  Or null if there was no match.
9373    * @private
9374    */
9375   function diff_halfMatchI_(longtext, shorttext, i) {
9376     // Start with a 1/4 length substring at position i as a seed.
9377     var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
9378     var j = -1;
9379     var best_common = '';
9380     var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;
9381     while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {
9382       var prefixLength = diff_commonPrefix(
9383         longtext.substring(i), shorttext.substring(j));
9384       var suffixLength = diff_commonSuffix(
9385         longtext.substring(0, i), shorttext.substring(0, j));
9386       if (best_common.length < suffixLength + prefixLength) {
9387         best_common = shorttext.substring(
9388           j - suffixLength, j) + shorttext.substring(j, j + prefixLength);
9389         best_longtext_a = longtext.substring(0, i - suffixLength);
9390         best_longtext_b = longtext.substring(i + prefixLength);
9391         best_shorttext_a = shorttext.substring(0, j - suffixLength);
9392         best_shorttext_b = shorttext.substring(j + prefixLength);
9393       }
9394     }
9395     if (best_common.length * 2 >= longtext.length) {
9396       return [
9397         best_longtext_a, best_longtext_b,
9398         best_shorttext_a, best_shorttext_b, best_common
9399       ];
9400     } else {
9401       return null;
9402     }
9403   }
9404
9405   // First check if the second quarter is the seed for a half-match.
9406   var hm1 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 4));
9407   // Check again based on the third quarter.
9408   var hm2 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 2));
9409   var hm;
9410   if (!hm1 && !hm2) {
9411     return null;
9412   } else if (!hm2) {
9413     hm = hm1;
9414   } else if (!hm1) {
9415     hm = hm2;
9416   } else {
9417     // Both matched.  Select the longest.
9418     hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
9419   }
9420
9421   // A half-match was found, sort out the return data.
9422   var text1_a, text1_b, text2_a, text2_b;
9423   if (text1.length > text2.length) {
9424     text1_a = hm[0];
9425     text1_b = hm[1];
9426     text2_a = hm[2];
9427     text2_b = hm[3];
9428   } else {
9429     text2_a = hm[0];
9430     text2_b = hm[1];
9431     text1_a = hm[2];
9432     text1_b = hm[3];
9433   }
9434   var mid_common = hm[4];
9435   return [text1_a, text1_b, text2_a, text2_b, mid_common];
9436 };
9437
9438
9439 /**
9440  * Reorder and merge like edit sections.  Merge equalities.
9441  * Any edit section can move as long as it doesn't cross an equality.
9442  * @param {Array} diffs Array of diff tuples.
9443  * @param {boolean} fix_unicode Whether to normalize to a unicode-correct diff
9444  */
9445 function diff_cleanupMerge(diffs, fix_unicode) {
9446   diffs.push([DIFF_EQUAL, '']);  // Add a dummy entry at the end.
9447   var pointer = 0;
9448   var count_delete = 0;
9449   var count_insert = 0;
9450   var text_delete = '';
9451   var text_insert = '';
9452   var commonlength;
9453   while (pointer < diffs.length) {
9454     if (pointer < diffs.length - 1 && !diffs[pointer][1]) {
9455       diffs.splice(pointer, 1);
9456       continue;
9457     }
9458     switch (diffs[pointer][0]) {
9459       case DIFF_INSERT:
9460
9461         count_insert++;
9462         text_insert += diffs[pointer][1];
9463         pointer++;
9464         break;
9465       case DIFF_DELETE:
9466         count_delete++;
9467         text_delete += diffs[pointer][1];
9468         pointer++;
9469         break;
9470       case DIFF_EQUAL:
9471         var previous_equality = pointer - count_insert - count_delete - 1;
9472         if (fix_unicode) {
9473           // prevent splitting of unicode surrogate pairs.  when fix_unicode is true,
9474           // we assume that the old and new text in the diff are complete and correct
9475           // unicode-encoded JS strings, but the tuple boundaries may fall between
9476           // surrogate pairs.  we fix this by shaving off stray surrogates from the end
9477           // of the previous equality and the beginning of this equality.  this may create
9478           // empty equalities or a common prefix or suffix.  for example, if AB and AC are
9479           // emojis, `[[0, 'A'], [-1, 'BA'], [0, 'C']]` would turn into deleting 'ABAC' and
9480           // inserting 'AC', and then the common suffix 'AC' will be eliminated.  in this
9481           // particular case, both equalities go away, we absorb any previous inequalities,
9482           // and we keep scanning for the next equality before rewriting the tuples.
9483           if (previous_equality >= 0 && ends_with_pair_start(diffs[previous_equality][1])) {
9484             var stray = diffs[previous_equality][1].slice(-1);
9485             diffs[previous_equality][1] = diffs[previous_equality][1].slice(0, -1);
9486             text_delete = stray + text_delete;
9487             text_insert = stray + text_insert;
9488             if (!diffs[previous_equality][1]) {
9489               // emptied out previous equality, so delete it and include previous delete/insert
9490               diffs.splice(previous_equality, 1);
9491               pointer--;
9492               var k = previous_equality - 1;
9493               if (diffs[k] && diffs[k][0] === DIFF_INSERT) {
9494                 count_insert++;
9495                 text_insert = diffs[k][1] + text_insert;
9496                 k--;
9497               }
9498               if (diffs[k] && diffs[k][0] === DIFF_DELETE) {
9499                 count_delete++;
9500                 text_delete = diffs[k][1] + text_delete;
9501                 k--;
9502               }
9503               previous_equality = k;
9504             }
9505           }
9506           if (starts_with_pair_end(diffs[pointer][1])) {
9507             var stray = diffs[pointer][1].charAt(0);
9508             diffs[pointer][1] = diffs[pointer][1].slice(1);
9509             text_delete += stray;
9510             text_insert += stray;
9511           }
9512         }
9513         if (pointer < diffs.length - 1 && !diffs[pointer][1]) {
9514           // for empty equality not at end, wait for next equality
9515           diffs.splice(pointer, 1);
9516           break;
9517         }
9518         if (text_delete.length > 0 || text_insert.length > 0) {
9519           // note that diff_commonPrefix and diff_commonSuffix are unicode-aware
9520           if (text_delete.length > 0 && text_insert.length > 0) {
9521             // Factor out any common prefixes.
9522             commonlength = diff_commonPrefix(text_insert, text_delete);
9523             if (commonlength !== 0) {
9524               if (previous_equality >= 0) {
9525                 diffs[previous_equality][1] += text_insert.substring(0, commonlength);
9526               } else {
9527                 diffs.splice(0, 0, [DIFF_EQUAL, text_insert.substring(0, commonlength)]);
9528                 pointer++;
9529               }
9530               text_insert = text_insert.substring(commonlength);
9531               text_delete = text_delete.substring(commonlength);
9532             }
9533             // Factor out any common suffixes.
9534             commonlength = diff_commonSuffix(text_insert, text_delete);
9535             if (commonlength !== 0) {
9536               diffs[pointer][1] =
9537                 text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1];
9538               text_insert = text_insert.substring(0, text_insert.length - commonlength);
9539               text_delete = text_delete.substring(0, text_delete.length - commonlength);
9540             }
9541           }
9542           // Delete the offending records and add the merged ones.
9543           var n = count_insert + count_delete;
9544           if (text_delete.length === 0 && text_insert.length === 0) {
9545             diffs.splice(pointer - n, n);
9546             pointer = pointer - n;
9547           } else if (text_delete.length === 0) {
9548             diffs.splice(pointer - n, n, [DIFF_INSERT, text_insert]);
9549             pointer = pointer - n + 1;
9550           } else if (text_insert.length === 0) {
9551             diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete]);
9552             pointer = pointer - n + 1;
9553           } else {
9554             diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete], [DIFF_INSERT, text_insert]);
9555             pointer = pointer - n + 2;
9556           }
9557         }
9558         if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
9559           // Merge this equality with the previous one.
9560           diffs[pointer - 1][1] += diffs[pointer][1];
9561           diffs.splice(pointer, 1);
9562         } else {
9563           pointer++;
9564         }
9565         count_insert = 0;
9566         count_delete = 0;
9567         text_delete = '';
9568         text_insert = '';
9569         break;
9570     }
9571   }
9572   if (diffs[diffs.length - 1][1] === '') {
9573     diffs.pop();  // Remove the dummy entry at the end.
9574   }
9575
9576   // Second pass: look for single edits surrounded on both sides by equalities
9577   // which can be shifted sideways to eliminate an equality.
9578   // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
9579   var changes = false;
9580   pointer = 1;
9581   // Intentionally ignore the first and last element (don't need checking).
9582   while (pointer < diffs.length - 1) {
9583     if (diffs[pointer - 1][0] === DIFF_EQUAL &&
9584       diffs[pointer + 1][0] === DIFF_EQUAL) {
9585       // This is a single edit surrounded by equalities.
9586       if (diffs[pointer][1].substring(diffs[pointer][1].length -
9587         diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) {
9588         // Shift the edit over the previous equality.
9589         diffs[pointer][1] = diffs[pointer - 1][1] +
9590           diffs[pointer][1].substring(0, diffs[pointer][1].length -
9591             diffs[pointer - 1][1].length);
9592         diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
9593         diffs.splice(pointer - 1, 1);
9594         changes = true;
9595       } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==
9596         diffs[pointer + 1][1]) {
9597         // Shift the edit over the next equality.
9598         diffs[pointer - 1][1] += diffs[pointer + 1][1];
9599         diffs[pointer][1] =
9600           diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
9601           diffs[pointer + 1][1];
9602         diffs.splice(pointer + 1, 1);
9603         changes = true;
9604       }
9605     }
9606     pointer++;
9607   }
9608   // If shifts were made, the diff needs reordering and another shift sweep.
9609   if (changes) {
9610     diff_cleanupMerge(diffs, fix_unicode);
9611   }
9612 };
9613
9614 function is_surrogate_pair_start(charCode) {
9615   return charCode >= 0xD800 && charCode <= 0xDBFF;
9616 }
9617
9618 function is_surrogate_pair_end(charCode) {
9619   return charCode >= 0xDC00 && charCode <= 0xDFFF;
9620 }
9621
9622 function starts_with_pair_end(str) {
9623   return is_surrogate_pair_end(str.charCodeAt(0));
9624 }
9625
9626 function ends_with_pair_start(str) {
9627   return is_surrogate_pair_start(str.charCodeAt(str.length - 1));
9628 }
9629
9630 function remove_empty_tuples(tuples) {
9631   var ret = [];
9632   for (var i = 0; i < tuples.length; i++) {
9633     if (tuples[i][1].length > 0) {
9634       ret.push(tuples[i]);
9635     }
9636   }
9637   return ret;
9638 }
9639
9640 function make_edit_splice(before, oldMiddle, newMiddle, after) {
9641   if (ends_with_pair_start(before) || starts_with_pair_end(after)) {
9642     return null;
9643   }
9644   return remove_empty_tuples([
9645     [DIFF_EQUAL, before],
9646     [DIFF_DELETE, oldMiddle],
9647     [DIFF_INSERT, newMiddle],
9648     [DIFF_EQUAL, after]
9649   ]);
9650 }
9651
9652 function find_cursor_edit_diff(oldText, newText, cursor_pos) {
9653   // note: this runs after equality check has ruled out exact equality
9654   var oldRange = typeof cursor_pos === 'number' ?
9655     { index: cursor_pos, length: 0 } : cursor_pos.oldRange;
9656   var newRange = typeof cursor_pos === 'number' ?
9657     null : cursor_pos.newRange;
9658   // take into account the old and new selection to generate the best diff
9659   // possible for a text edit.  for example, a text change from "xxx" to "xx"
9660   // could be a delete or forwards-delete of any one of the x's, or the
9661   // result of selecting two of the x's and typing "x".
9662   var oldLength = oldText.length;
9663   var newLength = newText.length;
9664   if (oldRange.length === 0 && (newRange === null || newRange.length === 0)) {
9665     // see if we have an insert or delete before or after cursor
9666     var oldCursor = oldRange.index;
9667     var oldBefore = oldText.slice(0, oldCursor);
9668     var oldAfter = oldText.slice(oldCursor);
9669     var maybeNewCursor = newRange ? newRange.index : null;
9670     editBefore: {
9671       // is this an insert or delete right before oldCursor?
9672       var newCursor = oldCursor + newLength - oldLength;
9673       if (maybeNewCursor !== null && maybeNewCursor !== newCursor) {
9674         break editBefore;
9675       }
9676       if (newCursor < 0 || newCursor > newLength) {
9677         break editBefore;
9678       }
9679       var newBefore = newText.slice(0, newCursor);
9680       var newAfter = newText.slice(newCursor);
9681       if (newAfter !== oldAfter) {
9682         break editBefore;
9683       }
9684       var prefixLength = Math.min(oldCursor, newCursor);
9685       var oldPrefix = oldBefore.slice(0, prefixLength);
9686       var newPrefix = newBefore.slice(0, prefixLength);
9687       if (oldPrefix !== newPrefix) {
9688         break editBefore;
9689       }
9690       var oldMiddle = oldBefore.slice(prefixLength);
9691       var newMiddle = newBefore.slice(prefixLength);
9692       return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldAfter);
9693     }
9694     editAfter: {
9695       // is this an insert or delete right after oldCursor?
9696       if (maybeNewCursor !== null && maybeNewCursor !== oldCursor) {
9697         break editAfter;
9698       }
9699       var cursor = oldCursor;
9700       var newBefore = newText.slice(0, cursor);
9701       var newAfter = newText.slice(cursor);
9702       if (newBefore !== oldBefore) {
9703         break editAfter;
9704       }
9705       var suffixLength = Math.min(oldLength - cursor, newLength - cursor);
9706       var oldSuffix = oldAfter.slice(oldAfter.length - suffixLength);
9707       var newSuffix = newAfter.slice(newAfter.length - suffixLength);
9708       if (oldSuffix !== newSuffix) {
9709         break editAfter;
9710       }
9711       var oldMiddle = oldAfter.slice(0, oldAfter.length - suffixLength);
9712       var newMiddle = newAfter.slice(0, newAfter.length - suffixLength);
9713       return make_edit_splice(oldBefore, oldMiddle, newMiddle, oldSuffix);
9714     }
9715   }
9716   if (oldRange.length > 0 && newRange && newRange.length === 0) {
9717     replaceRange: {
9718       // see if diff could be a splice of the old selection range
9719       var oldPrefix = oldText.slice(0, oldRange.index);
9720       var oldSuffix = oldText.slice(oldRange.index + oldRange.length);
9721       var prefixLength = oldPrefix.length;
9722       var suffixLength = oldSuffix.length;
9723       if (newLength < prefixLength + suffixLength) {
9724         break replaceRange;
9725       }
9726       var newPrefix = newText.slice(0, prefixLength);
9727       var newSuffix = newText.slice(newLength - suffixLength);
9728       if (oldPrefix !== newPrefix || oldSuffix !== newSuffix) {
9729         break replaceRange;
9730       }
9731       var oldMiddle = oldText.slice(prefixLength, oldLength - suffixLength);
9732       var newMiddle = newText.slice(prefixLength, newLength - suffixLength);
9733       return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldSuffix);
9734     }
9735   }
9736
9737   return null;
9738 }
9739
9740 function diff(text1, text2, cursor_pos) {
9741   // only pass fix_unicode=true at the top level, not when diff_main is
9742   // recursively invoked
9743   return diff_main(text1, text2, cursor_pos, true);
9744 }
9745
9746 diff.INSERT = DIFF_INSERT;
9747 diff.DELETE = DIFF_DELETE;
9748 diff.EQUAL = DIFF_EQUAL;
9749
9750 module.exports = diff;
9751
9752
9753 /***/ }),
9754 /* 54 */
9755 /***/ (function(module, __webpack_exports__, __webpack_require__) {
9756
9757 "use strict";
9758 __webpack_require__.r(__webpack_exports__);
9759 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
9760 /* --------------------------------------------------------------------------------------------\r
9761  * Copyright (c) Microsoft Corporation. All rights reserved.\r
9762  * Licensed under the MIT License. See License.txt in the project root for license information.\r
9763  * ------------------------------------------------------------------------------------------ */\r
9764 \r
9765 var __spreadArrays = (undefined && undefined.__spreadArrays) || function () {\r
9766     for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r
9767     for (var r = Array(s), k = 0, i = 0; i < il; i++)\r
9768         for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r
9769             r[k] = a[j];\r
9770     return r;\r
9771 };\r
9772 var FullTextDocument = /** @class */ (function () {\r
9773     function FullTextDocument(uri, languageId, version, content) {\r
9774         this._uri = uri;\r
9775         this._languageId = languageId;\r
9776         this._version = version;\r
9777         this._content = content;\r
9778         this._lineOffsets = undefined;\r
9779     }\r
9780     Object.defineProperty(FullTextDocument.prototype, "uri", {\r
9781         get: function () {\r
9782             return this._uri;\r
9783         },\r
9784         enumerable: true,\r
9785         configurable: true\r
9786     });\r
9787     Object.defineProperty(FullTextDocument.prototype, "languageId", {\r
9788         get: function () {\r
9789             return this._languageId;\r
9790         },\r
9791         enumerable: true,\r
9792         configurable: true\r
9793     });\r
9794     Object.defineProperty(FullTextDocument.prototype, "version", {\r
9795         get: function () {\r
9796             return this._version;\r
9797         },\r
9798         enumerable: true,\r
9799         configurable: true\r
9800     });\r
9801     FullTextDocument.prototype.getText = function (range) {\r
9802         if (range) {\r
9803             var start = this.offsetAt(range.start);\r
9804             var end = this.offsetAt(range.end);\r
9805             return this._content.substring(start, end);\r
9806         }\r
9807         return this._content;\r
9808     };\r
9809     FullTextDocument.prototype.update = function (changes, version) {\r
9810         for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) {\r
9811             var change = changes_1[_i];\r
9812             if (FullTextDocument.isIncremental(change)) {\r
9813                 // makes sure start is before end\r
9814                 var range = getWellformedRange(change.range);\r
9815                 // update content\r
9816                 var startOffset = this.offsetAt(range.start);\r
9817                 var endOffset = this.offsetAt(range.end);\r
9818                 this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length);\r
9819                 // update the offsets\r
9820                 var startLine = Math.max(range.start.line, 0);\r
9821                 var endLine = Math.max(range.end.line, 0);\r
9822                 var lineOffsets = this._lineOffsets;\r
9823                 var addedLineOffsets = computeLineOffsets(change.text, false, startOffset);\r
9824                 if (endLine - startLine === addedLineOffsets.length) {\r
9825                     for (var i = 0, len = addedLineOffsets.length; i < len; i++) {\r
9826                         lineOffsets[i + startLine + 1] = addedLineOffsets[i];\r
9827                     }\r
9828                 }\r
9829                 else {\r
9830                     if (addedLineOffsets.length < 10000) {\r
9831                         lineOffsets.splice.apply(lineOffsets, __spreadArrays([startLine + 1, endLine - startLine], addedLineOffsets));\r
9832                     }\r
9833                     else { // avoid too many arguments for splice\r
9834                         this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1));\r
9835                     }\r
9836                 }\r
9837                 var diff = change.text.length - (endOffset - startOffset);\r
9838                 if (diff !== 0) {\r
9839                     for (var i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) {\r
9840                         lineOffsets[i] = lineOffsets[i] + diff;\r
9841                     }\r
9842                 }\r
9843             }\r
9844             else if (FullTextDocument.isFull(change)) {\r
9845                 this._content = change.text;\r
9846                 this._lineOffsets = undefined;\r
9847             }\r
9848             else {\r
9849                 throw new Error('Unknown change event received');\r
9850             }\r
9851         }\r
9852         this._version = version;\r
9853     };\r
9854     FullTextDocument.prototype.getLineOffsets = function () {\r
9855         if (this._lineOffsets === undefined) {\r
9856             this._lineOffsets = computeLineOffsets(this._content, true);\r
9857         }\r
9858         return this._lineOffsets;\r
9859     };\r
9860     FullTextDocument.prototype.positionAt = function (offset) {\r
9861         offset = Math.max(Math.min(offset, this._content.length), 0);\r
9862         var lineOffsets = this.getLineOffsets();\r
9863         var low = 0, high = lineOffsets.length;\r
9864         if (high === 0) {\r
9865             return { line: 0, character: offset };\r
9866         }\r
9867         while (low < high) {\r
9868             var mid = Math.floor((low + high) / 2);\r
9869             if (lineOffsets[mid] > offset) {\r
9870                 high = mid;\r
9871             }\r
9872             else {\r
9873                 low = mid + 1;\r
9874             }\r
9875         }\r
9876         // low is the least x for which the line offset is larger than the current offset\r
9877         // or array.length if no line offset is larger than the current offset\r
9878         var line = low - 1;\r
9879         return { line: line, character: offset - lineOffsets[line] };\r
9880     };\r
9881     FullTextDocument.prototype.offsetAt = function (position) {\r
9882         var lineOffsets = this.getLineOffsets();\r
9883         if (position.line >= lineOffsets.length) {\r
9884             return this._content.length;\r
9885         }\r
9886         else if (position.line < 0) {\r
9887             return 0;\r
9888         }\r
9889         var lineOffset = lineOffsets[position.line];\r
9890         var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;\r
9891         return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);\r
9892     };\r
9893     Object.defineProperty(FullTextDocument.prototype, "lineCount", {\r
9894         get: function () {\r
9895             return this.getLineOffsets().length;\r
9896         },\r
9897         enumerable: true,\r
9898         configurable: true\r
9899     });\r
9900     FullTextDocument.isIncremental = function (event) {\r
9901         var candidate = event;\r
9902         return candidate !== undefined && candidate !== null &&\r
9903             typeof candidate.text === 'string' && candidate.range !== undefined &&\r
9904             (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number');\r
9905     };\r
9906     FullTextDocument.isFull = function (event) {\r
9907         var candidate = event;\r
9908         return candidate !== undefined && candidate !== null &&\r
9909             typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined;\r
9910     };\r
9911     return FullTextDocument;\r
9912 }());\r
9913 var TextDocument;\r
9914 (function (TextDocument) {\r
9915     /**\r
9916      * Creates a new text document.\r
9917      *\r
9918      * @param uri The document's uri.\r
9919      * @param languageId  The document's language Id.\r
9920      * @param version The document's initial version number.\r
9921      * @param content The document's content.\r
9922      */\r
9923     function create(uri, languageId, version, content) {\r
9924         return new FullTextDocument(uri, languageId, version, content);\r
9925     }\r
9926     TextDocument.create = create;\r
9927     /**\r
9928      * Updates a TextDocument by modifing its content.\r
9929      *\r
9930      * @param document the document to update. Only documents created by TextDocument.create are valid inputs.\r
9931      * @param changes the changes to apply to the document.\r
9932      * @returns The updated TextDocument. Note: That's the same document instance passed in as first parameter.\r
9933      *\r
9934      */\r
9935     function update(document, changes, version) {\r
9936         if (document instanceof FullTextDocument) {\r
9937             document.update(changes, version);\r
9938             return document;\r
9939         }\r
9940         else {\r
9941             throw new Error('TextDocument.update: document must be created by TextDocument.create');\r
9942         }\r
9943     }\r
9944     TextDocument.update = update;\r
9945     function applyEdits(document, edits) {\r
9946         var text = document.getText();\r
9947         var sortedEdits = mergeSort(edits.map(getWellformedEdit), function (a, b) {\r
9948             var diff = a.range.start.line - b.range.start.line;\r
9949             if (diff === 0) {\r
9950                 return a.range.start.character - b.range.start.character;\r
9951             }\r
9952             return diff;\r
9953         });\r
9954         var lastModifiedOffset = text.length;\r
9955         for (var i = sortedEdits.length - 1; i >= 0; i--) {\r
9956             var e = sortedEdits[i];\r
9957             var startOffset = document.offsetAt(e.range.start);\r
9958             var endOffset = document.offsetAt(e.range.end);\r
9959             if (endOffset <= lastModifiedOffset) {\r
9960                 text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);\r
9961             }\r
9962             else {\r
9963                 throw new Error('Overlapping edit');\r
9964             }\r
9965             lastModifiedOffset = startOffset;\r
9966         }\r
9967         return text;\r
9968     }\r
9969     TextDocument.applyEdits = applyEdits;\r
9970 })(TextDocument || (TextDocument = {}));\r
9971 function mergeSort(data, compare) {\r
9972     if (data.length <= 1) {\r
9973         // sorted\r
9974         return data;\r
9975     }\r
9976     var p = (data.length / 2) | 0;\r
9977     var left = data.slice(0, p);\r
9978     var right = data.slice(p);\r
9979     mergeSort(left, compare);\r
9980     mergeSort(right, compare);\r
9981     var leftIdx = 0;\r
9982     var rightIdx = 0;\r
9983     var i = 0;\r
9984     while (leftIdx < left.length && rightIdx < right.length) {\r
9985         var ret = compare(left[leftIdx], right[rightIdx]);\r
9986         if (ret <= 0) {\r
9987             // smaller_equal -> take left to preserve order\r
9988             data[i++] = left[leftIdx++];\r
9989         }\r
9990         else {\r
9991             // greater -> take right\r
9992             data[i++] = right[rightIdx++];\r
9993         }\r
9994     }\r
9995     while (leftIdx < left.length) {\r
9996         data[i++] = left[leftIdx++];\r
9997     }\r
9998     while (rightIdx < right.length) {\r
9999         data[i++] = right[rightIdx++];\r
10000     }\r
10001     return data;\r
10002 }\r
10003 function computeLineOffsets(text, isAtLineStart, textOffset) {\r
10004     if (textOffset === void 0) { textOffset = 0; }\r
10005     var result = isAtLineStart ? [textOffset] : [];\r
10006     for (var i = 0; i < text.length; i++) {\r
10007         var ch = text.charCodeAt(i);\r
10008         if (ch === 13 /* CarriageReturn */ || ch === 10 /* LineFeed */) {\r
10009             if (ch === 13 /* CarriageReturn */ && i + 1 < text.length && text.charCodeAt(i + 1) === 10 /* LineFeed */) {\r
10010                 i++;\r
10011             }\r
10012             result.push(textOffset + i + 1);\r
10013         }\r
10014     }\r
10015     return result;\r
10016 }\r
10017 function getWellformedRange(range) {\r
10018     var start = range.start;\r
10019     var end = range.end;\r
10020     if (start.line > end.line || (start.line === end.line && start.character > end.character)) {\r
10021         return { start: end, end: start };\r
10022     }\r
10023     return range;\r
10024 }\r
10025 function getWellformedEdit(textEdit) {\r
10026     var range = getWellformedRange(textEdit.range);\r
10027     if (range !== textEdit.range) {\r
10028         return { newText: textEdit.newText, range: range };\r
10029     }\r
10030     return textEdit;\r
10031 }\r
10032
10033
10034 /***/ })
10035 /******/ ])));