1 (function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
2 /******/ // The module cache
3 /******/ var installedModules = {};
5 /******/ // The require function
6 /******/ function __webpack_require__(moduleId) {
8 /******/ // Check if module is in cache
9 /******/ if(installedModules[moduleId]) {
10 /******/ return installedModules[moduleId].exports;
12 /******/ // Create a new module (and put it into the cache)
13 /******/ var module = installedModules[moduleId] = {
19 /******/ // Execute the module function
20 /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
22 /******/ // Flag the module as loaded
23 /******/ module.l = true;
25 /******/ // Return the exports of the module
26 /******/ return module.exports;
30 /******/ // expose the modules object (__webpack_modules__)
31 /******/ __webpack_require__.m = modules;
33 /******/ // expose the module cache
34 /******/ __webpack_require__.c = installedModules;
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 });
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' });
48 /******/ Object.defineProperty(exports, '__esModule', { value: true });
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));
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;
76 /******/ // Object.prototype.hasOwnProperty.call
77 /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
79 /******/ // __webpack_public_path__
80 /******/ __webpack_require__.p = "";
83 /******/ // Load entry module and return exports
84 /******/ return __webpack_require__(__webpack_require__.s = 0);
86 /************************************************************************/
89 /***/ (function(module, exports, __webpack_require__) {
93 var __importDefault = (this && this.__importDefault) || function (mod) {
94 return (mod && mod.__esModule) ? mod : { "default": mod };
96 Object.defineProperty(exports, "__esModule", { value: true });
97 exports.activate = void 0;
98 const coc_nvim_1 = __webpack_require__(1);
99 const server_1 = __importDefault(__webpack_require__(2));
100 const commands_1 = __webpack_require__(141);
101 const organizeImports_1 = __webpack_require__(112);
102 const plugins_1 = __webpack_require__(142);
103 async function activate(context) {
104 let { subscriptions, logger } = context;
105 const config = coc_nvim_1.workspace.getConfiguration().get('tsserver', {});
108 const pluginManager = new plugins_1.PluginManager();
109 const service = new server_1.default(pluginManager);
110 function registCommand(cmd) {
111 let { id, execute } = cmd;
112 subscriptions.push(coc_nvim_1.commands.registerCommand(id, execute, cmd));
114 registCommand(new commands_1.ConfigurePluginCommand(pluginManager));
115 registCommand(new commands_1.AutoFixCommand(service));
116 registCommand(new commands_1.ReloadProjectsCommand(service));
117 registCommand(new commands_1.OpenTsServerLogCommand(service));
118 registCommand(new commands_1.TypeScriptGoToProjectConfigCommand(service));
119 registCommand(new organizeImports_1.OrganizeImportsCommand(service));
120 service.start().then(() => {
121 subscriptions.push(coc_nvim_1.services.regist(service));
122 registCommand(coc_nvim_1.commands.register({
123 id: 'tsserver.restart',
125 // tslint:disable-next-line:no-floating-promises
126 service.stop().then(() => {
134 logger.error(`Error on service start:`, e);
137 configurePlugin: (pluginId, configuration) => {
138 pluginManager.setConfiguration(pluginId, configuration);
142 exports.activate = activate;
147 /***/ (function(module, exports) {
149 module.exports = require("coc.nvim");
153 /***/ (function(module, exports, __webpack_require__) {
157 var __importDefault = (this && this.__importDefault) || function (mod) {
158 return (mod && mod.__esModule) ? mod : { "default": mod };
160 Object.defineProperty(exports, "__esModule", { value: true });
161 const coc_nvim_1 = __webpack_require__(1);
162 const vscode_languageserver_protocol_1 = __webpack_require__(3);
163 const typescriptServiceClientHost_1 = __importDefault(__webpack_require__(33));
164 const languageDescription_1 = __webpack_require__(140);
165 class TsserverService {
166 constructor(pluginManager) {
167 this.pluginManager = pluginManager;
168 this.id = 'tsserver';
169 this.name = 'tsserver';
170 this.state = coc_nvim_1.ServiceStat.Initial;
171 this._onDidServiceReady = new vscode_languageserver_protocol_1.Emitter();
172 this.onServiceReady = this._onDidServiceReady.event;
173 this.disposables = [];
174 this.descriptions = [];
175 const config = coc_nvim_1.workspace.getConfiguration('tsserver');
176 const enableJavascript = !!config.get('enableJavascript');
177 this.enable = config.get('enable');
178 this.descriptions = languageDescription_1.standardLanguageDescriptions.filter(o => {
179 return enableJavascript ? true : o.id != 'javascript';
181 this.selector = this.descriptions.reduce((arr, c) => {
182 return arr.concat(c.modeIds);
186 return coc_nvim_1.workspace.getConfiguration('tsserver');
189 * Get running client host.
192 if (this.state == coc_nvim_1.ServiceStat.Running)
193 return Promise.resolve(this.clientHost);
195 return new Promise((resolve, reject) => {
196 let timer = setTimeout(() => {
197 reject(new Error(`Server not started after 5s`));
199 let disposable = this.onServiceReady(() => {
201 disposable.dispose();
202 resolve(this.clientHost);
209 this.state = coc_nvim_1.ServiceStat.Starting;
210 this.clientHost = new typescriptServiceClientHost_1.default(this.descriptions, this.pluginManager);
211 this.disposables.push(this.clientHost);
212 let client = this.clientHost.serviceClient;
213 return new Promise(resolve => {
215 client.onTsServerStarted(() => {
216 Object.defineProperty(this, 'state', {
218 return this.clientHost.serviceClient.state;
221 this._onDidServiceReady.fire(void 0);
230 coc_nvim_1.disposeAll(this.disposables);
233 if (!this.clientHost)
235 let client = this.clientHost.serviceClient;
236 await client.restartTsServer();
239 if (!this.clientHost)
241 this.clientHost.reset();
242 let client = this.clientHost.serviceClient;
247 exports.default = TsserverService;
252 /***/ (function(module, exports, __webpack_require__) {
255 /* --------------------------------------------------------------------------------------------
\r
256 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
257 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
258 * ------------------------------------------------------------------------------------------ */
\r
260 function __export(m) {
\r
261 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
\r
263 Object.defineProperty(exports, "__esModule", { value: true });
\r
264 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
265 exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
\r
266 exports.ResponseError = vscode_jsonrpc_1.ResponseError;
\r
267 exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;
\r
268 exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
\r
269 exports.Disposable = vscode_jsonrpc_1.Disposable;
\r
270 exports.Event = vscode_jsonrpc_1.Event;
\r
271 exports.Emitter = vscode_jsonrpc_1.Emitter;
\r
272 exports.Trace = vscode_jsonrpc_1.Trace;
\r
273 exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;
\r
274 exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
\r
275 exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
\r
276 exports.RequestType = vscode_jsonrpc_1.RequestType;
\r
277 exports.RequestType0 = vscode_jsonrpc_1.RequestType0;
\r
278 exports.NotificationType = vscode_jsonrpc_1.NotificationType;
\r
279 exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
\r
280 exports.MessageReader = vscode_jsonrpc_1.MessageReader;
\r
281 exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;
\r
282 exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
\r
283 exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
\r
284 exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
\r
285 exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
\r
286 exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
\r
287 exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
\r
288 exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
\r
289 exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
\r
290 exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
\r
291 exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
\r
292 exports.ProgressType = vscode_jsonrpc_1.ProgressType;
\r
293 __export(__webpack_require__(18));
\r
294 __export(__webpack_require__(19));
\r
295 const callHierarchy = __webpack_require__(31);
\r
296 const st = __webpack_require__(32);
\r
298 (function (Proposed) {
\r
299 let CallHierarchyPrepareRequest;
\r
300 (function (CallHierarchyPrepareRequest) {
\r
301 CallHierarchyPrepareRequest.method = callHierarchy.CallHierarchyPrepareRequest.method;
\r
302 CallHierarchyPrepareRequest.type = callHierarchy.CallHierarchyPrepareRequest.type;
\r
303 })(CallHierarchyPrepareRequest = Proposed.CallHierarchyPrepareRequest || (Proposed.CallHierarchyPrepareRequest = {}));
\r
304 let CallHierarchyIncomingCallsRequest;
\r
305 (function (CallHierarchyIncomingCallsRequest) {
\r
306 CallHierarchyIncomingCallsRequest.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;
\r
307 CallHierarchyIncomingCallsRequest.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;
\r
308 })(CallHierarchyIncomingCallsRequest = Proposed.CallHierarchyIncomingCallsRequest || (Proposed.CallHierarchyIncomingCallsRequest = {}));
\r
309 let CallHierarchyOutgoingCallsRequest;
\r
310 (function (CallHierarchyOutgoingCallsRequest) {
\r
311 CallHierarchyOutgoingCallsRequest.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;
\r
312 CallHierarchyOutgoingCallsRequest.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;
\r
313 })(CallHierarchyOutgoingCallsRequest = Proposed.CallHierarchyOutgoingCallsRequest || (Proposed.CallHierarchyOutgoingCallsRequest = {}));
\r
314 Proposed.SemanticTokenTypes = st.SemanticTokenTypes;
\r
315 Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers;
\r
316 Proposed.SemanticTokens = st.SemanticTokens;
\r
317 let SemanticTokensRequest;
\r
318 (function (SemanticTokensRequest) {
\r
319 SemanticTokensRequest.method = st.SemanticTokensRequest.method;
\r
320 SemanticTokensRequest.type = st.SemanticTokensRequest.type;
\r
321 })(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {}));
\r
322 let SemanticTokensEditsRequest;
\r
323 (function (SemanticTokensEditsRequest) {
\r
324 SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method;
\r
325 SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type;
\r
326 })(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {}));
\r
327 let SemanticTokensRangeRequest;
\r
328 (function (SemanticTokensRangeRequest) {
\r
329 SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method;
\r
330 SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type;
\r
331 })(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {}));
\r
332 })(Proposed = exports.Proposed || (exports.Proposed = {}));
\r
333 function createProtocolConnection(reader, writer, logger, strategy) {
\r
334 return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
\r
336 exports.createProtocolConnection = createProtocolConnection;
\r
341 /***/ (function(module, exports, __webpack_require__) {
344 /* --------------------------------------------------------------------------------------------
\r
345 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
346 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
347 * ------------------------------------------------------------------------------------------ */
\r
348 /// <reference path="../typings/thenable.d.ts" />
\r
350 function __export(m) {
\r
351 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
\r
353 Object.defineProperty(exports, "__esModule", { value: true });
\r
354 const Is = __webpack_require__(5);
\r
355 const messages_1 = __webpack_require__(6);
\r
356 exports.RequestType = messages_1.RequestType;
\r
357 exports.RequestType0 = messages_1.RequestType0;
\r
358 exports.RequestType1 = messages_1.RequestType1;
\r
359 exports.RequestType2 = messages_1.RequestType2;
\r
360 exports.RequestType3 = messages_1.RequestType3;
\r
361 exports.RequestType4 = messages_1.RequestType4;
\r
362 exports.RequestType5 = messages_1.RequestType5;
\r
363 exports.RequestType6 = messages_1.RequestType6;
\r
364 exports.RequestType7 = messages_1.RequestType7;
\r
365 exports.RequestType8 = messages_1.RequestType8;
\r
366 exports.RequestType9 = messages_1.RequestType9;
\r
367 exports.ResponseError = messages_1.ResponseError;
\r
368 exports.ErrorCodes = messages_1.ErrorCodes;
\r
369 exports.NotificationType = messages_1.NotificationType;
\r
370 exports.NotificationType0 = messages_1.NotificationType0;
\r
371 exports.NotificationType1 = messages_1.NotificationType1;
\r
372 exports.NotificationType2 = messages_1.NotificationType2;
\r
373 exports.NotificationType3 = messages_1.NotificationType3;
\r
374 exports.NotificationType4 = messages_1.NotificationType4;
\r
375 exports.NotificationType5 = messages_1.NotificationType5;
\r
376 exports.NotificationType6 = messages_1.NotificationType6;
\r
377 exports.NotificationType7 = messages_1.NotificationType7;
\r
378 exports.NotificationType8 = messages_1.NotificationType8;
\r
379 exports.NotificationType9 = messages_1.NotificationType9;
\r
380 const messageReader_1 = __webpack_require__(7);
\r
381 exports.MessageReader = messageReader_1.MessageReader;
\r
382 exports.StreamMessageReader = messageReader_1.StreamMessageReader;
\r
383 exports.IPCMessageReader = messageReader_1.IPCMessageReader;
\r
384 exports.SocketMessageReader = messageReader_1.SocketMessageReader;
\r
385 const messageWriter_1 = __webpack_require__(9);
\r
386 exports.MessageWriter = messageWriter_1.MessageWriter;
\r
387 exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
\r
388 exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
\r
389 exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
\r
390 const events_1 = __webpack_require__(8);
\r
391 exports.Disposable = events_1.Disposable;
\r
392 exports.Event = events_1.Event;
\r
393 exports.Emitter = events_1.Emitter;
\r
394 const cancellation_1 = __webpack_require__(10);
\r
395 exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
\r
396 exports.CancellationToken = cancellation_1.CancellationToken;
\r
397 const linkedMap_1 = __webpack_require__(11);
\r
398 __export(__webpack_require__(12));
\r
399 __export(__webpack_require__(17));
\r
400 var CancelNotification;
\r
401 (function (CancelNotification) {
\r
402 CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
\r
403 })(CancelNotification || (CancelNotification = {}));
\r
404 var ProgressNotification;
\r
405 (function (ProgressNotification) {
\r
406 ProgressNotification.type = new messages_1.NotificationType('$/progress');
\r
407 })(ProgressNotification || (ProgressNotification = {}));
\r
408 class ProgressType {
\r
412 exports.ProgressType = ProgressType;
\r
413 exports.NullLogger = Object.freeze({
\r
420 (function (Trace) {
\r
421 Trace[Trace["Off"] = 0] = "Off";
\r
422 Trace[Trace["Messages"] = 1] = "Messages";
\r
423 Trace[Trace["Verbose"] = 2] = "Verbose";
\r
424 })(Trace = exports.Trace || (exports.Trace = {}));
\r
425 (function (Trace) {
\r
426 function fromString(value) {
\r
427 if (!Is.string(value)) {
\r
430 value = value.toLowerCase();
\r
435 return Trace.Messages;
\r
437 return Trace.Verbose;
\r
442 Trace.fromString = fromString;
\r
443 function toString(value) {
\r
447 case Trace.Messages:
\r
449 case Trace.Verbose:
\r
455 Trace.toString = toString;
\r
456 })(Trace = exports.Trace || (exports.Trace = {}));
\r
458 (function (TraceFormat) {
\r
459 TraceFormat["Text"] = "text";
\r
460 TraceFormat["JSON"] = "json";
\r
461 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
\r
462 (function (TraceFormat) {
\r
463 function fromString(value) {
\r
464 value = value.toLowerCase();
\r
465 if (value === 'json') {
\r
466 return TraceFormat.JSON;
\r
469 return TraceFormat.Text;
\r
472 TraceFormat.fromString = fromString;
\r
473 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
\r
474 var SetTraceNotification;
\r
475 (function (SetTraceNotification) {
\r
476 SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');
\r
477 })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
\r
478 var LogTraceNotification;
\r
479 (function (LogTraceNotification) {
\r
480 LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');
\r
481 })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
\r
482 var ConnectionErrors;
\r
483 (function (ConnectionErrors) {
\r
485 * The connection is closed.
\r
487 ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
\r
489 * The connection got disposed.
\r
491 ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
\r
493 * The connection is already in listening mode.
\r
495 ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
\r
496 })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
\r
497 class ConnectionError extends Error {
\r
498 constructor(code, message) {
\r
501 Object.setPrototypeOf(this, ConnectionError.prototype);
\r
504 exports.ConnectionError = ConnectionError;
\r
505 var ConnectionStrategy;
\r
506 (function (ConnectionStrategy) {
\r
507 function is(value) {
\r
508 let candidate = value;
\r
509 return candidate && Is.func(candidate.cancelUndispatched);
\r
511 ConnectionStrategy.is = is;
\r
512 })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
\r
513 var ConnectionState;
\r
514 (function (ConnectionState) {
\r
515 ConnectionState[ConnectionState["New"] = 1] = "New";
\r
516 ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
\r
517 ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
\r
518 ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
\r
519 })(ConnectionState || (ConnectionState = {}));
\r
520 function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
\r
521 let sequenceNumber = 0;
\r
522 let notificationSquenceNumber = 0;
\r
523 let unknownResponseSquenceNumber = 0;
\r
524 const version = '2.0';
\r
525 let starRequestHandler = undefined;
\r
526 let requestHandlers = Object.create(null);
\r
527 let starNotificationHandler = undefined;
\r
528 let notificationHandlers = Object.create(null);
\r
529 let progressHandlers = new Map();
\r
531 let messageQueue = new linkedMap_1.LinkedMap();
\r
532 let responsePromises = Object.create(null);
\r
533 let requestTokens = Object.create(null);
\r
534 let trace = Trace.Off;
\r
535 let traceFormat = TraceFormat.Text;
\r
537 let state = ConnectionState.New;
\r
538 let errorEmitter = new events_1.Emitter();
\r
539 let closeEmitter = new events_1.Emitter();
\r
540 let unhandledNotificationEmitter = new events_1.Emitter();
\r
541 let unhandledProgressEmitter = new events_1.Emitter();
\r
542 let disposeEmitter = new events_1.Emitter();
\r
543 function createRequestQueueKey(id) {
\r
544 return 'req-' + id.toString();
\r
546 function createResponseQueueKey(id) {
\r
548 return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
\r
551 return 'res-' + id.toString();
\r
554 function createNotificationQueueKey() {
\r
555 return 'not-' + (++notificationSquenceNumber).toString();
\r
557 function addMessageToQueue(queue, message) {
\r
558 if (messages_1.isRequestMessage(message)) {
\r
559 queue.set(createRequestQueueKey(message.id), message);
\r
561 else if (messages_1.isResponseMessage(message)) {
\r
562 queue.set(createResponseQueueKey(message.id), message);
\r
565 queue.set(createNotificationQueueKey(), message);
\r
568 function cancelUndispatched(_message) {
\r
571 function isListening() {
\r
572 return state === ConnectionState.Listening;
\r
574 function isClosed() {
\r
575 return state === ConnectionState.Closed;
\r
577 function isDisposed() {
\r
578 return state === ConnectionState.Disposed;
\r
580 function closeHandler() {
\r
581 if (state === ConnectionState.New || state === ConnectionState.Listening) {
\r
582 state = ConnectionState.Closed;
\r
583 closeEmitter.fire(undefined);
\r
585 // If the connection is disposed don't sent close events.
\r
587 function readErrorHandler(error) {
\r
588 errorEmitter.fire([error, undefined, undefined]);
\r
590 function writeErrorHandler(data) {
\r
591 errorEmitter.fire(data);
\r
593 messageReader.onClose(closeHandler);
\r
594 messageReader.onError(readErrorHandler);
\r
595 messageWriter.onClose(closeHandler);
\r
596 messageWriter.onError(writeErrorHandler);
\r
597 function triggerMessageQueue() {
\r
598 if (timer || messageQueue.size === 0) {
\r
601 timer = setImmediate(() => {
\r
603 processMessageQueue();
\r
606 function processMessageQueue() {
\r
607 if (messageQueue.size === 0) {
\r
610 let message = messageQueue.shift();
\r
612 if (messages_1.isRequestMessage(message)) {
\r
613 handleRequest(message);
\r
615 else if (messages_1.isNotificationMessage(message)) {
\r
616 handleNotification(message);
\r
618 else if (messages_1.isResponseMessage(message)) {
\r
619 handleResponse(message);
\r
622 handleInvalidMessage(message);
\r
626 triggerMessageQueue();
\r
629 let callback = (message) => {
\r
631 // We have received a cancellation message. Check if the message is still in the queue
\r
632 // and cancel it if allowed to do so.
\r
633 if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
\r
634 let key = createRequestQueueKey(message.params.id);
\r
635 let toCancel = messageQueue.get(key);
\r
636 if (messages_1.isRequestMessage(toCancel)) {
\r
637 let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
\r
638 if (response && (response.error !== void 0 || response.result !== void 0)) {
\r
639 messageQueue.delete(key);
\r
640 response.id = toCancel.id;
\r
641 traceSendingResponse(response, message.method, Date.now());
\r
642 messageWriter.write(response);
\r
647 addMessageToQueue(messageQueue, message);
\r
650 triggerMessageQueue();
\r
653 function handleRequest(requestMessage) {
\r
654 if (isDisposed()) {
\r
655 // we return here silently since we fired an event when the
\r
656 // connection got disposed.
\r
659 function reply(resultOrError, method, startTime) {
\r
662 id: requestMessage.id
\r
664 if (resultOrError instanceof messages_1.ResponseError) {
\r
665 message.error = resultOrError.toJson();
\r
668 message.result = resultOrError === void 0 ? null : resultOrError;
\r
670 traceSendingResponse(message, method, startTime);
\r
671 messageWriter.write(message);
\r
673 function replyError(error, method, startTime) {
\r
676 id: requestMessage.id,
\r
677 error: error.toJson()
\r
679 traceSendingResponse(message, method, startTime);
\r
680 messageWriter.write(message);
\r
682 function replySuccess(result, method, startTime) {
\r
683 // The JSON RPC defines that a response must either have a result or an error
\r
684 // So we can't treat undefined as a valid response result.
\r
685 if (result === void 0) {
\r
690 id: requestMessage.id,
\r
693 traceSendingResponse(message, method, startTime);
\r
694 messageWriter.write(message);
\r
696 traceReceivedRequest(requestMessage);
\r
697 let element = requestHandlers[requestMessage.method];
\r
699 let requestHandler;
\r
701 type = element.type;
\r
702 requestHandler = element.handler;
\r
704 let startTime = Date.now();
\r
705 if (requestHandler || starRequestHandler) {
\r
706 let cancellationSource = new cancellation_1.CancellationTokenSource();
\r
707 let tokenKey = String(requestMessage.id);
\r
708 requestTokens[tokenKey] = cancellationSource;
\r
711 if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
\r
712 handlerResult = requestHandler
\r
713 ? requestHandler(cancellationSource.token)
\r
714 : starRequestHandler(requestMessage.method, cancellationSource.token);
\r
716 else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
\r
717 handlerResult = requestHandler
\r
718 ? requestHandler(...requestMessage.params, cancellationSource.token)
\r
719 : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
\r
722 handlerResult = requestHandler
\r
723 ? requestHandler(requestMessage.params, cancellationSource.token)
\r
724 : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
\r
726 let promise = handlerResult;
\r
727 if (!handlerResult) {
\r
728 delete requestTokens[tokenKey];
\r
729 replySuccess(handlerResult, requestMessage.method, startTime);
\r
731 else if (promise.then) {
\r
732 promise.then((resultOrError) => {
\r
733 delete requestTokens[tokenKey];
\r
734 reply(resultOrError, requestMessage.method, startTime);
\r
736 delete requestTokens[tokenKey];
\r
737 if (error instanceof messages_1.ResponseError) {
\r
738 replyError(error, requestMessage.method, startTime);
\r
740 else if (error && Is.string(error.message)) {
\r
741 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
\r
744 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
\r
749 delete requestTokens[tokenKey];
\r
750 reply(handlerResult, requestMessage.method, startTime);
\r
754 delete requestTokens[tokenKey];
\r
755 if (error instanceof messages_1.ResponseError) {
\r
756 reply(error, requestMessage.method, startTime);
\r
758 else if (error && Is.string(error.message)) {
\r
759 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
\r
762 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
\r
767 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
\r
770 function handleResponse(responseMessage) {
\r
771 if (isDisposed()) {
\r
772 // See handle request.
\r
775 if (responseMessage.id === null) {
\r
776 if (responseMessage.error) {
\r
777 logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
\r
780 logger.error(`Received response message without id. No further error information provided.`);
\r
784 let key = String(responseMessage.id);
\r
785 let responsePromise = responsePromises[key];
\r
786 traceReceivedResponse(responseMessage, responsePromise);
\r
787 if (responsePromise) {
\r
788 delete responsePromises[key];
\r
790 if (responseMessage.error) {
\r
791 let error = responseMessage.error;
\r
792 responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
\r
794 else if (responseMessage.result !== void 0) {
\r
795 responsePromise.resolve(responseMessage.result);
\r
798 throw new Error('Should never happen.');
\r
802 if (error.message) {
\r
803 logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
\r
806 logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
\r
812 function handleNotification(message) {
\r
813 if (isDisposed()) {
\r
814 // See handle request.
\r
817 let type = undefined;
\r
818 let notificationHandler;
\r
819 if (message.method === CancelNotification.type.method) {
\r
820 notificationHandler = (params) => {
\r
821 let id = params.id;
\r
822 let source = requestTokens[String(id)];
\r
829 let element = notificationHandlers[message.method];
\r
831 notificationHandler = element.handler;
\r
832 type = element.type;
\r
835 if (notificationHandler || starNotificationHandler) {
\r
837 traceReceivedNotification(message);
\r
838 if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
\r
839 notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
\r
841 else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
\r
842 notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
\r
845 notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
\r
849 if (error.message) {
\r
850 logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
\r
853 logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
\r
858 unhandledNotificationEmitter.fire(message);
\r
861 function handleInvalidMessage(message) {
\r
863 logger.error('Received empty message.');
\r
866 logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
\r
867 // Test whether we find an id to reject the promise
\r
868 let responseMessage = message;
\r
869 if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
\r
870 let key = String(responseMessage.id);
\r
871 let responseHandler = responsePromises[key];
\r
872 if (responseHandler) {
\r
873 responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
\r
877 function traceSendingRequest(message) {
\r
878 if (trace === Trace.Off || !tracer) {
\r
881 if (traceFormat === TraceFormat.Text) {
\r
882 let data = undefined;
\r
883 if (trace === Trace.Verbose && message.params) {
\r
884 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
886 tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
\r
889 logLSPMessage('send-request', message);
\r
892 function traceSendingNotification(message) {
\r
893 if (trace === Trace.Off || !tracer) {
\r
896 if (traceFormat === TraceFormat.Text) {
\r
897 let data = undefined;
\r
898 if (trace === Trace.Verbose) {
\r
899 if (message.params) {
\r
900 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
903 data = 'No parameters provided.\n\n';
\r
906 tracer.log(`Sending notification '${message.method}'.`, data);
\r
909 logLSPMessage('send-notification', message);
\r
912 function traceSendingResponse(message, method, startTime) {
\r
913 if (trace === Trace.Off || !tracer) {
\r
916 if (traceFormat === TraceFormat.Text) {
\r
917 let data = undefined;
\r
918 if (trace === Trace.Verbose) {
\r
919 if (message.error && message.error.data) {
\r
920 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
\r
923 if (message.result) {
\r
924 data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
\r
926 else if (message.error === void 0) {
\r
927 data = 'No result returned.\n\n';
\r
931 tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
\r
934 logLSPMessage('send-response', message);
\r
937 function traceReceivedRequest(message) {
\r
938 if (trace === Trace.Off || !tracer) {
\r
941 if (traceFormat === TraceFormat.Text) {
\r
942 let data = undefined;
\r
943 if (trace === Trace.Verbose && message.params) {
\r
944 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
946 tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
\r
949 logLSPMessage('receive-request', message);
\r
952 function traceReceivedNotification(message) {
\r
953 if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
\r
956 if (traceFormat === TraceFormat.Text) {
\r
957 let data = undefined;
\r
958 if (trace === Trace.Verbose) {
\r
959 if (message.params) {
\r
960 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
963 data = 'No parameters provided.\n\n';
\r
966 tracer.log(`Received notification '${message.method}'.`, data);
\r
969 logLSPMessage('receive-notification', message);
\r
972 function traceReceivedResponse(message, responsePromise) {
\r
973 if (trace === Trace.Off || !tracer) {
\r
976 if (traceFormat === TraceFormat.Text) {
\r
977 let data = undefined;
\r
978 if (trace === Trace.Verbose) {
\r
979 if (message.error && message.error.data) {
\r
980 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
\r
983 if (message.result) {
\r
984 data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
\r
986 else if (message.error === void 0) {
\r
987 data = 'No result returned.\n\n';
\r
991 if (responsePromise) {
\r
992 let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
\r
993 tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
\r
996 tracer.log(`Received response ${message.id} without active response promise.`, data);
\r
1000 logLSPMessage('receive-response', message);
\r
1003 function logLSPMessage(type, message) {
\r
1004 if (!tracer || trace === Trace.Off) {
\r
1007 const lspMessage = {
\r
1008 isLSPMessage: true,
\r
1011 timestamp: Date.now()
\r
1013 tracer.log(lspMessage);
\r
1015 function throwIfClosedOrDisposed() {
\r
1017 throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
\r
1019 if (isDisposed()) {
\r
1020 throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
\r
1023 function throwIfListening() {
\r
1024 if (isListening()) {
\r
1025 throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
\r
1028 function throwIfNotListening() {
\r
1029 if (!isListening()) {
\r
1030 throw new Error('Call listen() first.');
\r
1033 function undefinedToNull(param) {
\r
1034 if (param === void 0) {
\r
1041 function computeMessageParams(type, params) {
\r
1043 let numberOfParams = type.numberOfParams;
\r
1044 switch (numberOfParams) {
\r
1049 result = undefinedToNull(params[0]);
\r
1053 for (let i = 0; i < params.length && i < numberOfParams; i++) {
\r
1054 result.push(undefinedToNull(params[i]));
\r
1056 if (params.length < numberOfParams) {
\r
1057 for (let i = params.length; i < numberOfParams; i++) {
\r
1058 result.push(null);
\r
1065 let connection = {
\r
1066 sendNotification: (type, ...params) => {
\r
1067 throwIfClosedOrDisposed();
\r
1069 let messageParams;
\r
1070 if (Is.string(type)) {
\r
1072 switch (params.length) {
\r
1074 messageParams = null;
\r
1077 messageParams = params[0];
\r
1080 messageParams = params;
\r
1085 method = type.method;
\r
1086 messageParams = computeMessageParams(type, params);
\r
1088 let notificationMessage = {
\r
1091 params: messageParams
\r
1093 traceSendingNotification(notificationMessage);
\r
1094 messageWriter.write(notificationMessage);
\r
1096 onNotification: (type, handler) => {
\r
1097 throwIfClosedOrDisposed();
\r
1098 if (Is.func(type)) {
\r
1099 starNotificationHandler = type;
\r
1101 else if (handler) {
\r
1102 if (Is.string(type)) {
\r
1103 notificationHandlers[type] = { type: undefined, handler };
\r
1106 notificationHandlers[type.method] = { type, handler };
\r
1110 onProgress: (_type, token, handler) => {
\r
1111 if (progressHandlers.has(token)) {
\r
1112 throw new Error(`Progress handler for token ${token} already registered`);
\r
1114 progressHandlers.set(token, handler);
\r
1117 progressHandlers.delete(token);
\r
1121 sendProgress: (_type, token, value) => {
\r
1122 connection.sendNotification(ProgressNotification.type, { token, value });
\r
1124 onUnhandledProgress: unhandledProgressEmitter.event,
\r
1125 sendRequest: (type, ...params) => {
\r
1126 throwIfClosedOrDisposed();
\r
1127 throwIfNotListening();
\r
1129 let messageParams;
\r
1130 let token = undefined;
\r
1131 if (Is.string(type)) {
\r
1133 switch (params.length) {
\r
1135 messageParams = null;
\r
1138 // The cancellation token is optional so it can also be undefined.
\r
1139 if (cancellation_1.CancellationToken.is(params[0])) {
\r
1140 messageParams = null;
\r
1141 token = params[0];
\r
1144 messageParams = undefinedToNull(params[0]);
\r
1148 const last = params.length - 1;
\r
1149 if (cancellation_1.CancellationToken.is(params[last])) {
\r
1150 token = params[last];
\r
1151 if (params.length === 2) {
\r
1152 messageParams = undefinedToNull(params[0]);
\r
1155 messageParams = params.slice(0, last).map(value => undefinedToNull(value));
\r
1159 messageParams = params.map(value => undefinedToNull(value));
\r
1165 method = type.method;
\r
1166 messageParams = computeMessageParams(type, params);
\r
1167 let numberOfParams = type.numberOfParams;
\r
1168 token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
\r
1170 let id = sequenceNumber++;
\r
1171 let result = new Promise((resolve, reject) => {
\r
1172 let requestMessage = {
\r
1176 params: messageParams
\r
1178 let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };
\r
1179 traceSendingRequest(requestMessage);
\r
1181 messageWriter.write(requestMessage);
\r
1184 // Writing the message failed. So we need to reject the promise.
\r
1185 responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
\r
1186 responsePromise = null;
\r
1188 if (responsePromise) {
\r
1189 responsePromises[String(id)] = responsePromise;
\r
1193 token.onCancellationRequested(() => {
\r
1194 connection.sendNotification(CancelNotification.type, { id });
\r
1199 onRequest: (type, handler) => {
\r
1200 throwIfClosedOrDisposed();
\r
1201 if (Is.func(type)) {
\r
1202 starRequestHandler = type;
\r
1204 else if (handler) {
\r
1205 if (Is.string(type)) {
\r
1206 requestHandlers[type] = { type: undefined, handler };
\r
1209 requestHandlers[type.method] = { type, handler };
\r
1213 trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
\r
1214 let _sendNotification = false;
\r
1215 let _traceFormat = TraceFormat.Text;
\r
1216 if (sendNotificationOrTraceOptions !== void 0) {
\r
1217 if (Is.boolean(sendNotificationOrTraceOptions)) {
\r
1218 _sendNotification = sendNotificationOrTraceOptions;
\r
1221 _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
\r
1222 _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
\r
1226 traceFormat = _traceFormat;
\r
1227 if (trace === Trace.Off) {
\r
1228 tracer = undefined;
\r
1233 if (_sendNotification && !isClosed() && !isDisposed()) {
\r
1234 connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
\r
1237 onError: errorEmitter.event,
\r
1238 onClose: closeEmitter.event,
\r
1239 onUnhandledNotification: unhandledNotificationEmitter.event,
\r
1240 onDispose: disposeEmitter.event,
\r
1242 if (isDisposed()) {
\r
1245 state = ConnectionState.Disposed;
\r
1246 disposeEmitter.fire(undefined);
\r
1247 let error = new Error('Connection got disposed.');
\r
1248 Object.keys(responsePromises).forEach((key) => {
\r
1249 responsePromises[key].reject(error);
\r
1251 responsePromises = Object.create(null);
\r
1252 requestTokens = Object.create(null);
\r
1253 messageQueue = new linkedMap_1.LinkedMap();
\r
1254 // Test for backwards compatibility
\r
1255 if (Is.func(messageWriter.dispose)) {
\r
1256 messageWriter.dispose();
\r
1258 if (Is.func(messageReader.dispose)) {
\r
1259 messageReader.dispose();
\r
1263 throwIfClosedOrDisposed();
\r
1264 throwIfListening();
\r
1265 state = ConnectionState.Listening;
\r
1266 messageReader.listen(callback);
\r
1269 // eslint-disable-next-line no-console
\r
1270 console.log('inspect');
\r
1273 connection.onNotification(LogTraceNotification.type, (params) => {
\r
1274 if (trace === Trace.Off || !tracer) {
\r
1277 tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
\r
1279 connection.onNotification(ProgressNotification.type, (params) => {
\r
1280 const handler = progressHandlers.get(params.token);
\r
1282 handler(params.value);
\r
1285 unhandledProgressEmitter.fire(params);
\r
1288 return connection;
\r
1290 function isMessageReader(value) {
\r
1291 return value.listen !== void 0 && value.read === void 0;
\r
1293 function isMessageWriter(value) {
\r
1294 return value.write !== void 0 && value.end === void 0;
\r
1296 function createMessageConnection(input, output, logger, strategy) {
\r
1298 logger = exports.NullLogger;
\r
1300 let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
\r
1301 let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
\r
1302 return _createMessageConnection(reader, writer, logger, strategy);
\r
1304 exports.createMessageConnection = createMessageConnection;
\r
1309 /***/ (function(module, exports, __webpack_require__) {
1312 /* --------------------------------------------------------------------------------------------
\r
1313 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1314 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1315 * ------------------------------------------------------------------------------------------ */
\r
1317 Object.defineProperty(exports, "__esModule", { value: true });
\r
1318 function boolean(value) {
\r
1319 return value === true || value === false;
\r
1321 exports.boolean = boolean;
\r
1322 function string(value) {
\r
1323 return typeof value === 'string' || value instanceof String;
\r
1325 exports.string = string;
\r
1326 function number(value) {
\r
1327 return typeof value === 'number' || value instanceof Number;
\r
1329 exports.number = number;
\r
1330 function error(value) {
\r
1331 return value instanceof Error;
\r
1333 exports.error = error;
\r
1334 function func(value) {
\r
1335 return typeof value === 'function';
\r
1337 exports.func = func;
\r
1338 function array(value) {
\r
1339 return Array.isArray(value);
\r
1341 exports.array = array;
\r
1342 function stringArray(value) {
\r
1343 return array(value) && value.every(elem => string(elem));
\r
1345 exports.stringArray = stringArray;
\r
1350 /***/ (function(module, exports, __webpack_require__) {
1353 /* --------------------------------------------------------------------------------------------
\r
1354 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1355 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1356 * ------------------------------------------------------------------------------------------ */
\r
1358 Object.defineProperty(exports, "__esModule", { value: true });
\r
1359 const is = __webpack_require__(5);
\r
1361 * Predefined error codes.
\r
1364 (function (ErrorCodes) {
\r
1365 // Defined by JSON RPC
\r
1366 ErrorCodes.ParseError = -32700;
\r
1367 ErrorCodes.InvalidRequest = -32600;
\r
1368 ErrorCodes.MethodNotFound = -32601;
\r
1369 ErrorCodes.InvalidParams = -32602;
\r
1370 ErrorCodes.InternalError = -32603;
\r
1371 ErrorCodes.serverErrorStart = -32099;
\r
1372 ErrorCodes.serverErrorEnd = -32000;
\r
1373 ErrorCodes.ServerNotInitialized = -32002;
\r
1374 ErrorCodes.UnknownErrorCode = -32001;
\r
1375 // Defined by the protocol.
\r
1376 ErrorCodes.RequestCancelled = -32800;
\r
1377 ErrorCodes.ContentModified = -32801;
\r
1378 // Defined by VSCode library.
\r
1379 ErrorCodes.MessageWriteError = 1;
\r
1380 ErrorCodes.MessageReadError = 2;
\r
1381 })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
\r
1383 * An error object return in a response in case a request
\r
1386 class ResponseError extends Error {
\r
1387 constructor(code, message, data) {
\r
1389 this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
\r
1391 Object.setPrototypeOf(this, ResponseError.prototype);
\r
1396 message: this.message,
\r
1401 exports.ResponseError = ResponseError;
\r
1403 * An abstract implementation of a MessageType.
\r
1405 class AbstractMessageType {
\r
1406 constructor(_method, _numberOfParams) {
\r
1407 this._method = _method;
\r
1408 this._numberOfParams = _numberOfParams;
\r
1411 return this._method;
\r
1413 get numberOfParams() {
\r
1414 return this._numberOfParams;
\r
1417 exports.AbstractMessageType = AbstractMessageType;
\r
1419 * Classes to type request response pairs
\r
1421 * The type parameter RO will be removed in the next major version
\r
1422 * of the JSON RPC library since it is a LSP concept and doesn't
\r
1423 * belong here. For now it is tagged as default never.
\r
1425 class RequestType0 extends AbstractMessageType {
\r
1426 constructor(method) {
\r
1430 exports.RequestType0 = RequestType0;
\r
1431 class RequestType extends AbstractMessageType {
\r
1432 constructor(method) {
\r
1436 exports.RequestType = RequestType;
\r
1437 class RequestType1 extends AbstractMessageType {
\r
1438 constructor(method) {
\r
1442 exports.RequestType1 = RequestType1;
\r
1443 class RequestType2 extends AbstractMessageType {
\r
1444 constructor(method) {
\r
1448 exports.RequestType2 = RequestType2;
\r
1449 class RequestType3 extends AbstractMessageType {
\r
1450 constructor(method) {
\r
1454 exports.RequestType3 = RequestType3;
\r
1455 class RequestType4 extends AbstractMessageType {
\r
1456 constructor(method) {
\r
1460 exports.RequestType4 = RequestType4;
\r
1461 class RequestType5 extends AbstractMessageType {
\r
1462 constructor(method) {
\r
1466 exports.RequestType5 = RequestType5;
\r
1467 class RequestType6 extends AbstractMessageType {
\r
1468 constructor(method) {
\r
1472 exports.RequestType6 = RequestType6;
\r
1473 class RequestType7 extends AbstractMessageType {
\r
1474 constructor(method) {
\r
1478 exports.RequestType7 = RequestType7;
\r
1479 class RequestType8 extends AbstractMessageType {
\r
1480 constructor(method) {
\r
1484 exports.RequestType8 = RequestType8;
\r
1485 class RequestType9 extends AbstractMessageType {
\r
1486 constructor(method) {
\r
1490 exports.RequestType9 = RequestType9;
\r
1492 * The type parameter RO will be removed in the next major version
\r
1493 * of the JSON RPC library since it is a LSP concept and doesn't
\r
1494 * belong here. For now it is tagged as default never.
\r
1496 class NotificationType extends AbstractMessageType {
\r
1497 constructor(method) {
\r
1499 this._ = undefined;
\r
1502 exports.NotificationType = NotificationType;
\r
1503 class NotificationType0 extends AbstractMessageType {
\r
1504 constructor(method) {
\r
1508 exports.NotificationType0 = NotificationType0;
\r
1509 class NotificationType1 extends AbstractMessageType {
\r
1510 constructor(method) {
\r
1514 exports.NotificationType1 = NotificationType1;
\r
1515 class NotificationType2 extends AbstractMessageType {
\r
1516 constructor(method) {
\r
1520 exports.NotificationType2 = NotificationType2;
\r
1521 class NotificationType3 extends AbstractMessageType {
\r
1522 constructor(method) {
\r
1526 exports.NotificationType3 = NotificationType3;
\r
1527 class NotificationType4 extends AbstractMessageType {
\r
1528 constructor(method) {
\r
1532 exports.NotificationType4 = NotificationType4;
\r
1533 class NotificationType5 extends AbstractMessageType {
\r
1534 constructor(method) {
\r
1538 exports.NotificationType5 = NotificationType5;
\r
1539 class NotificationType6 extends AbstractMessageType {
\r
1540 constructor(method) {
\r
1544 exports.NotificationType6 = NotificationType6;
\r
1545 class NotificationType7 extends AbstractMessageType {
\r
1546 constructor(method) {
\r
1550 exports.NotificationType7 = NotificationType7;
\r
1551 class NotificationType8 extends AbstractMessageType {
\r
1552 constructor(method) {
\r
1556 exports.NotificationType8 = NotificationType8;
\r
1557 class NotificationType9 extends AbstractMessageType {
\r
1558 constructor(method) {
\r
1562 exports.NotificationType9 = NotificationType9;
\r
1564 * Tests if the given message is a request message
\r
1566 function isRequestMessage(message) {
\r
1567 let candidate = message;
\r
1568 return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
\r
1570 exports.isRequestMessage = isRequestMessage;
\r
1572 * Tests if the given message is a notification message
\r
1574 function isNotificationMessage(message) {
\r
1575 let candidate = message;
\r
1576 return candidate && is.string(candidate.method) && message.id === void 0;
\r
1578 exports.isNotificationMessage = isNotificationMessage;
\r
1580 * Tests if the given message is a response message
\r
1582 function isResponseMessage(message) {
\r
1583 let candidate = message;
\r
1584 return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
\r
1586 exports.isResponseMessage = isResponseMessage;
\r
1591 /***/ (function(module, exports, __webpack_require__) {
1594 /* --------------------------------------------------------------------------------------------
\r
1595 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1596 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1597 * ------------------------------------------------------------------------------------------ */
\r
1599 Object.defineProperty(exports, "__esModule", { value: true });
\r
1600 const events_1 = __webpack_require__(8);
\r
1601 const Is = __webpack_require__(5);
\r
1602 let DefaultSize = 8192;
\r
1603 let CR = Buffer.from('\r', 'ascii')[0];
\r
1604 let LF = Buffer.from('\n', 'ascii')[0];
\r
1605 let CRLF = '\r\n';
\r
1606 class MessageBuffer {
\r
1607 constructor(encoding = 'utf8') {
\r
1608 this.encoding = encoding;
\r
1610 this.buffer = Buffer.allocUnsafe(DefaultSize);
\r
1613 var toAppend = chunk;
\r
1614 if (typeof (chunk) === 'string') {
\r
1616 var bufferLen = Buffer.byteLength(str, this.encoding);
\r
1617 toAppend = Buffer.allocUnsafe(bufferLen);
\r
1618 toAppend.write(str, 0, bufferLen, this.encoding);
\r
1620 if (this.buffer.length - this.index >= toAppend.length) {
\r
1621 toAppend.copy(this.buffer, this.index, 0, toAppend.length);
\r
1624 var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
\r
1625 if (this.index === 0) {
\r
1626 this.buffer = Buffer.allocUnsafe(newSize);
\r
1627 toAppend.copy(this.buffer, 0, 0, toAppend.length);
\r
1630 this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
\r
1633 this.index += toAppend.length;
\r
1635 tryReadHeaders() {
\r
1636 let result = undefined;
\r
1638 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
1641 // No header / body separator found (e.g CRLFCRLF)
\r
1642 if (current + 3 >= this.index) {
\r
1645 result = Object.create(null);
\r
1646 let headers = this.buffer.toString('ascii', 0, current).split(CRLF);
\r
1647 headers.forEach((header) => {
\r
1648 let index = header.indexOf(':');
\r
1649 if (index === -1) {
\r
1650 throw new Error('Message header must separate key and value using :');
\r
1652 let key = header.substr(0, index);
\r
1653 let value = header.substr(index + 1).trim();
\r
1654 result[key] = value;
\r
1656 let nextStart = current + 4;
\r
1657 this.buffer = this.buffer.slice(nextStart);
\r
1658 this.index = this.index - nextStart;
\r
1661 tryReadContent(length) {
\r
1662 if (this.index < length) {
\r
1665 let result = this.buffer.toString(this.encoding, 0, length);
\r
1666 let nextStart = length;
\r
1667 this.buffer.copy(this.buffer, 0, nextStart);
\r
1668 this.index = this.index - nextStart;
\r
1671 get numberOfBytes() {
\r
1672 return this.index;
\r
1675 var MessageReader;
\r
1676 (function (MessageReader) {
\r
1677 function is(value) {
\r
1678 let candidate = value;
\r
1679 return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
\r
1680 Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
\r
1682 MessageReader.is = is;
\r
1683 })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
\r
1684 class AbstractMessageReader {
\r
1686 this.errorEmitter = new events_1.Emitter();
\r
1687 this.closeEmitter = new events_1.Emitter();
\r
1688 this.partialMessageEmitter = new events_1.Emitter();
\r
1691 this.errorEmitter.dispose();
\r
1692 this.closeEmitter.dispose();
\r
1695 return this.errorEmitter.event;
\r
1697 fireError(error) {
\r
1698 this.errorEmitter.fire(this.asError(error));
\r
1701 return this.closeEmitter.event;
\r
1704 this.closeEmitter.fire(undefined);
\r
1706 get onPartialMessage() {
\r
1707 return this.partialMessageEmitter.event;
\r
1709 firePartialMessage(info) {
\r
1710 this.partialMessageEmitter.fire(info);
\r
1713 if (error instanceof Error) {
\r
1717 return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
\r
1721 exports.AbstractMessageReader = AbstractMessageReader;
\r
1722 class StreamMessageReader extends AbstractMessageReader {
\r
1723 constructor(readable, encoding = 'utf8') {
\r
1725 this.readable = readable;
\r
1726 this.buffer = new MessageBuffer(encoding);
\r
1727 this._partialMessageTimeout = 10000;
\r
1729 set partialMessageTimeout(timeout) {
\r
1730 this._partialMessageTimeout = timeout;
\r
1732 get partialMessageTimeout() {
\r
1733 return this._partialMessageTimeout;
\r
1735 listen(callback) {
\r
1736 this.nextMessageLength = -1;
\r
1737 this.messageToken = 0;
\r
1738 this.partialMessageTimer = undefined;
\r
1739 this.callback = callback;
\r
1740 this.readable.on('data', (data) => {
\r
1741 this.onData(data);
\r
1743 this.readable.on('error', (error) => this.fireError(error));
\r
1744 this.readable.on('close', () => this.fireClose());
\r
1747 this.buffer.append(data);
\r
1749 if (this.nextMessageLength === -1) {
\r
1750 let headers = this.buffer.tryReadHeaders();
\r
1754 let contentLength = headers['Content-Length'];
\r
1755 if (!contentLength) {
\r
1756 throw new Error('Header must provide a Content-Length property.');
\r
1758 let length = parseInt(contentLength);
\r
1759 if (isNaN(length)) {
\r
1760 throw new Error('Content-Length value must be a number.');
\r
1762 this.nextMessageLength = length;
\r
1763 // Take the encoding form the header. For compatibility
\r
1764 // treat both utf-8 and utf8 as node utf8
\r
1766 var msg = this.buffer.tryReadContent(this.nextMessageLength);
\r
1767 if (msg === null) {
\r
1768 /** We haven't received the full message yet. */
\r
1769 this.setPartialMessageTimer();
\r
1772 this.clearPartialMessageTimer();
\r
1773 this.nextMessageLength = -1;
\r
1774 this.messageToken++;
\r
1775 var json = JSON.parse(msg);
\r
1776 this.callback(json);
\r
1779 clearPartialMessageTimer() {
\r
1780 if (this.partialMessageTimer) {
\r
1781 clearTimeout(this.partialMessageTimer);
\r
1782 this.partialMessageTimer = undefined;
\r
1785 setPartialMessageTimer() {
\r
1786 this.clearPartialMessageTimer();
\r
1787 if (this._partialMessageTimeout <= 0) {
\r
1790 this.partialMessageTimer = setTimeout((token, timeout) => {
\r
1791 this.partialMessageTimer = undefined;
\r
1792 if (token === this.messageToken) {
\r
1793 this.firePartialMessage({ messageToken: token, waitingTime: timeout });
\r
1794 this.setPartialMessageTimer();
\r
1796 }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
\r
1799 exports.StreamMessageReader = StreamMessageReader;
\r
1800 class IPCMessageReader extends AbstractMessageReader {
\r
1801 constructor(process) {
\r
1803 this.process = process;
\r
1804 let eventEmitter = this.process;
\r
1805 eventEmitter.on('error', (error) => this.fireError(error));
\r
1806 eventEmitter.on('close', () => this.fireClose());
\r
1808 listen(callback) {
\r
1809 this.process.on('message', callback);
\r
1812 exports.IPCMessageReader = IPCMessageReader;
\r
1813 class SocketMessageReader extends StreamMessageReader {
\r
1814 constructor(socket, encoding = 'utf-8') {
\r
1815 super(socket, encoding);
\r
1818 exports.SocketMessageReader = SocketMessageReader;
\r
1823 /***/ (function(module, exports, __webpack_require__) {
1826 /* --------------------------------------------------------------------------------------------
\r
1827 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1828 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1829 * ------------------------------------------------------------------------------------------ */
\r
1831 Object.defineProperty(exports, "__esModule", { value: true });
\r
1833 (function (Disposable) {
\r
1834 function create(func) {
\r
1839 Disposable.create = create;
\r
1840 })(Disposable = exports.Disposable || (exports.Disposable = {}));
\r
1842 (function (Event) {
\r
1843 const _disposable = { dispose() { } };
\r
1844 Event.None = function () { return _disposable; };
\r
1845 })(Event = exports.Event || (exports.Event = {}));
\r
1846 class CallbackList {
\r
1847 add(callback, context = null, bucket) {
\r
1848 if (!this._callbacks) {
\r
1849 this._callbacks = [];
\r
1850 this._contexts = [];
\r
1852 this._callbacks.push(callback);
\r
1853 this._contexts.push(context);
\r
1854 if (Array.isArray(bucket)) {
\r
1855 bucket.push({ dispose: () => this.remove(callback, context) });
\r
1858 remove(callback, context = null) {
\r
1859 if (!this._callbacks) {
\r
1862 var foundCallbackWithDifferentContext = false;
\r
1863 for (var i = 0, len = this._callbacks.length; i < len; i++) {
\r
1864 if (this._callbacks[i] === callback) {
\r
1865 if (this._contexts[i] === context) {
\r
1866 // callback & context match => remove it
\r
1867 this._callbacks.splice(i, 1);
\r
1868 this._contexts.splice(i, 1);
\r
1872 foundCallbackWithDifferentContext = true;
\r
1876 if (foundCallbackWithDifferentContext) {
\r
1877 throw new Error('When adding a listener with a context, you should remove it with the same context');
\r
1881 if (!this._callbacks) {
\r
1884 var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
\r
1885 for (var i = 0, len = callbacks.length; i < len; i++) {
\r
1887 ret.push(callbacks[i].apply(contexts[i], args));
\r
1890 // eslint-disable-next-line no-console
\r
1897 return !this._callbacks || this._callbacks.length === 0;
\r
1900 this._callbacks = undefined;
\r
1901 this._contexts = undefined;
\r
1905 constructor(_options) {
\r
1906 this._options = _options;
\r
1909 * For the public to allow to subscribe
\r
1910 * to events from this Emitter
\r
1913 if (!this._event) {
\r
1914 this._event = (listener, thisArgs, disposables) => {
\r
1915 if (!this._callbacks) {
\r
1916 this._callbacks = new CallbackList();
\r
1918 if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
\r
1919 this._options.onFirstListenerAdd(this);
\r
1921 this._callbacks.add(listener, thisArgs);
\r
1925 this._callbacks.remove(listener, thisArgs);
\r
1926 result.dispose = Emitter._noop;
\r
1927 if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
\r
1928 this._options.onLastListenerRemove(this);
\r
1932 if (Array.isArray(disposables)) {
\r
1933 disposables.push(result);
\r
1938 return this._event;
\r
1941 * To be kept private to fire an event to
\r
1945 if (this._callbacks) {
\r
1946 this._callbacks.invoke.call(this._callbacks, event);
\r
1950 if (this._callbacks) {
\r
1951 this._callbacks.dispose();
\r
1952 this._callbacks = undefined;
\r
1956 exports.Emitter = Emitter;
\r
1957 Emitter._noop = function () { };
\r
1962 /***/ (function(module, exports, __webpack_require__) {
1965 /* --------------------------------------------------------------------------------------------
\r
1966 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1967 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1968 * ------------------------------------------------------------------------------------------ */
\r
1970 Object.defineProperty(exports, "__esModule", { value: true });
\r
1971 const events_1 = __webpack_require__(8);
\r
1972 const Is = __webpack_require__(5);
\r
1973 let ContentLength = 'Content-Length: ';
\r
1974 let CRLF = '\r\n';
\r
1975 var MessageWriter;
\r
1976 (function (MessageWriter) {
\r
1977 function is(value) {
\r
1978 let candidate = value;
\r
1979 return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
\r
1980 Is.func(candidate.onError) && Is.func(candidate.write);
\r
1982 MessageWriter.is = is;
\r
1983 })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
\r
1984 class AbstractMessageWriter {
\r
1986 this.errorEmitter = new events_1.Emitter();
\r
1987 this.closeEmitter = new events_1.Emitter();
\r
1990 this.errorEmitter.dispose();
\r
1991 this.closeEmitter.dispose();
\r
1994 return this.errorEmitter.event;
\r
1996 fireError(error, message, count) {
\r
1997 this.errorEmitter.fire([this.asError(error), message, count]);
\r
2000 return this.closeEmitter.event;
\r
2003 this.closeEmitter.fire(undefined);
\r
2006 if (error instanceof Error) {
\r
2010 return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
\r
2014 exports.AbstractMessageWriter = AbstractMessageWriter;
\r
2015 class StreamMessageWriter extends AbstractMessageWriter {
\r
2016 constructor(writable, encoding = 'utf8') {
\r
2018 this.writable = writable;
\r
2019 this.encoding = encoding;
\r
2020 this.errorCount = 0;
\r
2021 this.writable.on('error', (error) => this.fireError(error));
\r
2022 this.writable.on('close', () => this.fireClose());
\r
2025 let json = JSON.stringify(msg);
\r
2026 let contentLength = Buffer.byteLength(json, this.encoding);
\r
2028 ContentLength, contentLength.toString(), CRLF,
\r
2032 // Header must be written in ASCII encoding
\r
2033 this.writable.write(headers.join(''), 'ascii');
\r
2034 // Now write the content. This can be written in any encoding
\r
2035 this.writable.write(json, this.encoding);
\r
2036 this.errorCount = 0;
\r
2039 this.errorCount++;
\r
2040 this.fireError(error, msg, this.errorCount);
\r
2044 exports.StreamMessageWriter = StreamMessageWriter;
\r
2045 class IPCMessageWriter extends AbstractMessageWriter {
\r
2046 constructor(process) {
\r
2048 this.process = process;
\r
2049 this.errorCount = 0;
\r
2051 this.sending = false;
\r
2052 let eventEmitter = this.process;
\r
2053 eventEmitter.on('error', (error) => this.fireError(error));
\r
2054 eventEmitter.on('close', () => this.fireClose);
\r
2057 if (!this.sending && this.queue.length === 0) {
\r
2058 // See https://github.com/nodejs/node/issues/7657
\r
2059 this.doWriteMessage(msg);
\r
2062 this.queue.push(msg);
\r
2065 doWriteMessage(msg) {
\r
2067 if (this.process.send) {
\r
2068 this.sending = true;
\r
2069 this.process.send(msg, undefined, undefined, (error) => {
\r
2070 this.sending = false;
\r
2072 this.errorCount++;
\r
2073 this.fireError(error, msg, this.errorCount);
\r
2076 this.errorCount = 0;
\r
2078 if (this.queue.length > 0) {
\r
2079 this.doWriteMessage(this.queue.shift());
\r
2085 this.errorCount++;
\r
2086 this.fireError(error, msg, this.errorCount);
\r
2090 exports.IPCMessageWriter = IPCMessageWriter;
\r
2091 class SocketMessageWriter extends AbstractMessageWriter {
\r
2092 constructor(socket, encoding = 'utf8') {
\r
2094 this.socket = socket;
\r
2096 this.sending = false;
\r
2097 this.encoding = encoding;
\r
2098 this.errorCount = 0;
\r
2099 this.socket.on('error', (error) => this.fireError(error));
\r
2100 this.socket.on('close', () => this.fireClose());
\r
2104 this.socket.destroy();
\r
2107 if (!this.sending && this.queue.length === 0) {
\r
2108 // See https://github.com/nodejs/node/issues/7657
\r
2109 this.doWriteMessage(msg);
\r
2112 this.queue.push(msg);
\r
2115 doWriteMessage(msg) {
\r
2116 let json = JSON.stringify(msg);
\r
2117 let contentLength = Buffer.byteLength(json, this.encoding);
\r
2119 ContentLength, contentLength.toString(), CRLF,
\r
2123 // Header must be written in ASCII encoding
\r
2124 this.sending = true;
\r
2125 this.socket.write(headers.join(''), 'ascii', (error) => {
\r
2127 this.handleError(error, msg);
\r
2130 // Now write the content. This can be written in any encoding
\r
2131 this.socket.write(json, this.encoding, (error) => {
\r
2132 this.sending = false;
\r
2134 this.handleError(error, msg);
\r
2137 this.errorCount = 0;
\r
2139 if (this.queue.length > 0) {
\r
2140 this.doWriteMessage(this.queue.shift());
\r
2145 this.handleError(error, msg);
\r
2150 this.handleError(error, msg);
\r
2153 handleError(error, msg) {
\r
2154 this.errorCount++;
\r
2155 this.fireError(error, msg, this.errorCount);
\r
2158 exports.SocketMessageWriter = SocketMessageWriter;
\r
2163 /***/ (function(module, exports, __webpack_require__) {
2166 /*---------------------------------------------------------------------------------------------
\r
2167 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2168 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2169 *--------------------------------------------------------------------------------------------*/
\r
2171 Object.defineProperty(exports, "__esModule", { value: true });
\r
2172 const events_1 = __webpack_require__(8);
\r
2173 const Is = __webpack_require__(5);
\r
2174 var CancellationToken;
\r
2175 (function (CancellationToken) {
\r
2176 CancellationToken.None = Object.freeze({
\r
2177 isCancellationRequested: false,
\r
2178 onCancellationRequested: events_1.Event.None
\r
2180 CancellationToken.Cancelled = Object.freeze({
\r
2181 isCancellationRequested: true,
\r
2182 onCancellationRequested: events_1.Event.None
\r
2184 function is(value) {
\r
2185 let candidate = value;
\r
2186 return candidate && (candidate === CancellationToken.None
\r
2187 || candidate === CancellationToken.Cancelled
\r
2188 || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
\r
2190 CancellationToken.is = is;
\r
2191 })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
\r
2192 const shortcutEvent = Object.freeze(function (callback, context) {
\r
2193 let handle = setTimeout(callback.bind(context), 0);
\r
2194 return { dispose() { clearTimeout(handle); } };
\r
2196 class MutableToken {
\r
2198 this._isCancelled = false;
\r
2201 if (!this._isCancelled) {
\r
2202 this._isCancelled = true;
\r
2203 if (this._emitter) {
\r
2204 this._emitter.fire(undefined);
\r
2209 get isCancellationRequested() {
\r
2210 return this._isCancelled;
\r
2212 get onCancellationRequested() {
\r
2213 if (this._isCancelled) {
\r
2214 return shortcutEvent;
\r
2216 if (!this._emitter) {
\r
2217 this._emitter = new events_1.Emitter();
\r
2219 return this._emitter.event;
\r
2222 if (this._emitter) {
\r
2223 this._emitter.dispose();
\r
2224 this._emitter = undefined;
\r
2228 class CancellationTokenSource {
\r
2230 if (!this._token) {
\r
2231 // be lazy and create the token only when
\r
2232 // actually needed
\r
2233 this._token = new MutableToken();
\r
2235 return this._token;
\r
2238 if (!this._token) {
\r
2239 // save an object by returning the default
\r
2240 // cancelled token when cancellation happens
\r
2241 // before someone asks for the token
\r
2242 this._token = CancellationToken.Cancelled;
\r
2245 this._token.cancel();
\r
2249 if (!this._token) {
\r
2250 // ensure to initialize with an empty token if we had none
\r
2251 this._token = CancellationToken.None;
\r
2253 else if (this._token instanceof MutableToken) {
\r
2254 // actually dispose
\r
2255 this._token.dispose();
\r
2259 exports.CancellationTokenSource = CancellationTokenSource;
\r
2264 /***/ (function(module, exports, __webpack_require__) {
2268 /*---------------------------------------------------------------------------------------------
\r
2269 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2270 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2271 *--------------------------------------------------------------------------------------------*/
\r
2272 Object.defineProperty(exports, "__esModule", { value: true });
\r
2274 (function (Touch) {
\r
2278 })(Touch = exports.Touch || (exports.Touch = {}));
\r
2281 this._map = new Map();
\r
2282 this._head = undefined;
\r
2283 this._tail = undefined;
\r
2287 this._map.clear();
\r
2288 this._head = undefined;
\r
2289 this._tail = undefined;
\r
2293 return !this._head && !this._tail;
\r
2296 return this._size;
\r
2299 return this._map.has(key);
\r
2302 const item = this._map.get(key);
\r
2306 return item.value;
\r
2308 set(key, value, touch = Touch.None) {
\r
2309 let item = this._map.get(key);
\r
2311 item.value = value;
\r
2312 if (touch !== Touch.None) {
\r
2313 this.touch(item, touch);
\r
2317 item = { key, value, next: undefined, previous: undefined };
\r
2320 this.addItemLast(item);
\r
2323 this.addItemFirst(item);
\r
2326 this.addItemLast(item);
\r
2329 this.addItemLast(item);
\r
2332 this._map.set(key, item);
\r
2337 const item = this._map.get(key);
\r
2341 this._map.delete(key);
\r
2342 this.removeItem(item);
\r
2347 if (!this._head && !this._tail) {
\r
2350 if (!this._head || !this._tail) {
\r
2351 throw new Error('Invalid list');
\r
2353 const item = this._head;
\r
2354 this._map.delete(item.key);
\r
2355 this.removeItem(item);
\r
2357 return item.value;
\r
2359 forEach(callbackfn, thisArg) {
\r
2360 let current = this._head;
\r
2363 callbackfn.bind(thisArg)(current.value, current.key, this);
\r
2366 callbackfn(current.value, current.key, this);
\r
2368 current = current.next;
\r
2371 forEachReverse(callbackfn, thisArg) {
\r
2372 let current = this._tail;
\r
2375 callbackfn.bind(thisArg)(current.value, current.key, this);
\r
2378 callbackfn(current.value, current.key, this);
\r
2380 current = current.previous;
\r
2385 let current = this._head;
\r
2387 result.push(current.value);
\r
2388 current = current.next;
\r
2394 let current = this._head;
\r
2396 result.push(current.key);
\r
2397 current = current.next;
\r
2401 /* JSON RPC run on es5 which has no Symbol.iterator
\r
2402 public keys(): IterableIterator<K> {
\r
2403 let current = this._head;
\r
2404 let iterator: IterableIterator<K> = {
\r
2405 [Symbol.iterator]() {
\r
2408 next():IteratorResult<K> {
\r
2410 let result = { value: current.key, done: false };
\r
2411 current = current.next;
\r
2414 return { value: undefined, done: true };
\r
2421 public values(): IterableIterator<V> {
\r
2422 let current = this._head;
\r
2423 let iterator: IterableIterator<V> = {
\r
2424 [Symbol.iterator]() {
\r
2427 next():IteratorResult<V> {
\r
2429 let result = { value: current.value, done: false };
\r
2430 current = current.next;
\r
2433 return { value: undefined, done: true };
\r
2440 addItemFirst(item) {
\r
2441 // First time Insert
\r
2442 if (!this._head && !this._tail) {
\r
2443 this._tail = item;
\r
2445 else if (!this._head) {
\r
2446 throw new Error('Invalid list');
\r
2449 item.next = this._head;
\r
2450 this._head.previous = item;
\r
2452 this._head = item;
\r
2454 addItemLast(item) {
\r
2455 // First time Insert
\r
2456 if (!this._head && !this._tail) {
\r
2457 this._head = item;
\r
2459 else if (!this._tail) {
\r
2460 throw new Error('Invalid list');
\r
2463 item.previous = this._tail;
\r
2464 this._tail.next = item;
\r
2466 this._tail = item;
\r
2468 removeItem(item) {
\r
2469 if (item === this._head && item === this._tail) {
\r
2470 this._head = undefined;
\r
2471 this._tail = undefined;
\r
2473 else if (item === this._head) {
\r
2474 this._head = item.next;
\r
2476 else if (item === this._tail) {
\r
2477 this._tail = item.previous;
\r
2480 const next = item.next;
\r
2481 const previous = item.previous;
\r
2482 if (!next || !previous) {
\r
2483 throw new Error('Invalid list');
\r
2485 next.previous = previous;
\r
2486 previous.next = next;
\r
2489 touch(item, touch) {
\r
2490 if (!this._head || !this._tail) {
\r
2491 throw new Error('Invalid list');
\r
2493 if ((touch !== Touch.First && touch !== Touch.Last)) {
\r
2496 if (touch === Touch.First) {
\r
2497 if (item === this._head) {
\r
2500 const next = item.next;
\r
2501 const previous = item.previous;
\r
2502 // Unlink the item
\r
2503 if (item === this._tail) {
\r
2504 // previous must be defined since item was not head but is tail
\r
2505 // So there are more than on item in the map
\r
2506 previous.next = undefined;
\r
2507 this._tail = previous;
\r
2510 // Both next and previous are not undefined since item was neither head nor tail.
\r
2511 next.previous = previous;
\r
2512 previous.next = next;
\r
2514 // Insert the node at head
\r
2515 item.previous = undefined;
\r
2516 item.next = this._head;
\r
2517 this._head.previous = item;
\r
2518 this._head = item;
\r
2520 else if (touch === Touch.Last) {
\r
2521 if (item === this._tail) {
\r
2524 const next = item.next;
\r
2525 const previous = item.previous;
\r
2526 // Unlink the item.
\r
2527 if (item === this._head) {
\r
2528 // next must be defined since item was not tail but is head
\r
2529 // So there are more than on item in the map
\r
2530 next.previous = undefined;
\r
2531 this._head = next;
\r
2534 // Both next and previous are not undefined since item was neither head nor tail.
\r
2535 next.previous = previous;
\r
2536 previous.next = next;
\r
2538 item.next = undefined;
\r
2539 item.previous = this._tail;
\r
2540 this._tail.next = item;
\r
2541 this._tail = item;
\r
2545 exports.LinkedMap = LinkedMap;
\r
2550 /***/ (function(module, exports, __webpack_require__) {
2553 /* --------------------------------------------------------------------------------------------
\r
2554 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2555 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2556 * ------------------------------------------------------------------------------------------ */
\r
2558 Object.defineProperty(exports, "__esModule", { value: true });
\r
2559 const path_1 = __webpack_require__(13);
\r
2560 const os_1 = __webpack_require__(14);
\r
2561 const crypto_1 = __webpack_require__(15);
\r
2562 const net_1 = __webpack_require__(16);
\r
2563 const messageReader_1 = __webpack_require__(7);
\r
2564 const messageWriter_1 = __webpack_require__(9);
\r
2565 function generateRandomPipeName() {
\r
2566 const randomSuffix = crypto_1.randomBytes(21).toString('hex');
\r
2567 if (process.platform === 'win32') {
\r
2568 return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
\r
2571 // Mac/Unix: use socket file
\r
2572 return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
\r
2575 exports.generateRandomPipeName = generateRandomPipeName;
\r
2576 function createClientPipeTransport(pipeName, encoding = 'utf-8') {
\r
2577 let connectResolve;
\r
2578 let connected = new Promise((resolve, _reject) => {
\r
2579 connectResolve = resolve;
\r
2581 return new Promise((resolve, reject) => {
\r
2582 let server = net_1.createServer((socket) => {
\r
2585 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2586 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2589 server.on('error', reject);
\r
2590 server.listen(pipeName, () => {
\r
2591 server.removeListener('error', reject);
\r
2593 onConnected: () => { return connected; }
\r
2598 exports.createClientPipeTransport = createClientPipeTransport;
\r
2599 function createServerPipeTransport(pipeName, encoding = 'utf-8') {
\r
2600 const socket = net_1.createConnection(pipeName);
\r
2602 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2603 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2606 exports.createServerPipeTransport = createServerPipeTransport;
\r
2611 /***/ (function(module, exports) {
2613 module.exports = require("path");
2617 /***/ (function(module, exports) {
2619 module.exports = require("os");
2623 /***/ (function(module, exports) {
2625 module.exports = require("crypto");
2629 /***/ (function(module, exports) {
2631 module.exports = require("net");
2635 /***/ (function(module, exports, __webpack_require__) {
2638 /* --------------------------------------------------------------------------------------------
\r
2639 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2640 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2641 * ------------------------------------------------------------------------------------------ */
\r
2643 Object.defineProperty(exports, "__esModule", { value: true });
\r
2644 const net_1 = __webpack_require__(16);
\r
2645 const messageReader_1 = __webpack_require__(7);
\r
2646 const messageWriter_1 = __webpack_require__(9);
\r
2647 function createClientSocketTransport(port, encoding = 'utf-8') {
\r
2648 let connectResolve;
\r
2649 let connected = new Promise((resolve, _reject) => {
\r
2650 connectResolve = resolve;
\r
2652 return new Promise((resolve, reject) => {
\r
2653 let server = net_1.createServer((socket) => {
\r
2656 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2657 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2660 server.on('error', reject);
\r
2661 server.listen(port, '127.0.0.1', () => {
\r
2662 server.removeListener('error', reject);
\r
2664 onConnected: () => { return connected; }
\r
2669 exports.createClientSocketTransport = createClientSocketTransport;
\r
2670 function createServerSocketTransport(port, encoding = 'utf-8') {
\r
2671 const socket = net_1.createConnection(port, '127.0.0.1');
\r
2673 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2674 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2677 exports.createServerSocketTransport = createServerSocketTransport;
\r
2682 /***/ (function(module, __webpack_exports__, __webpack_require__) {
2685 __webpack_require__.r(__webpack_exports__);
2686 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
2687 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
2688 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
2689 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
2690 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
2691 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
2692 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
2693 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
2694 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
2695 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
2696 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
2697 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
2698 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
2699 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
2700 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
2701 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
2702 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
2703 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
2704 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
2705 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
2706 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
2707 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
2708 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
2709 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
2710 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
2711 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
2712 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
2713 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
2714 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemTag", function() { return CompletionItemTag; });
2715 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
2716 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
2717 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
2718 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
2719 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
2720 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
2721 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
2722 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
2723 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
2724 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolTag", function() { return SymbolTag; });
2725 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
2726 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
2727 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
2728 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
2729 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
2730 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
2731 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
2732 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
2733 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
2734 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
2735 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
2736 /* --------------------------------------------------------------------------------------------
\r
2737 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2738 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2739 * ------------------------------------------------------------------------------------------ */
\r
2742 * The Position namespace provides helper functions to work with
\r
2743 * [Position](#Position) literals.
\r
2746 (function (Position) {
\r
2748 * Creates a new Position literal from the given line and character.
\r
2749 * @param line The position's line.
\r
2750 * @param character The position's character.
\r
2752 function create(line, character) {
\r
2753 return { line: line, character: character };
\r
2755 Position.create = create;
\r
2757 * Checks whether the given liternal conforms to the [Position](#Position) interface.
\r
2759 function is(value) {
\r
2760 var candidate = value;
\r
2761 return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
\r
2764 })(Position || (Position = {}));
\r
2766 * The Range namespace provides helper functions to work with
\r
2767 * [Range](#Range) literals.
\r
2770 (function (Range) {
\r
2771 function create(one, two, three, four) {
\r
2772 if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
\r
2773 return { start: Position.create(one, two), end: Position.create(three, four) };
\r
2775 else if (Position.is(one) && Position.is(two)) {
\r
2776 return { start: one, end: two };
\r
2779 throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
\r
2782 Range.create = create;
\r
2784 * Checks whether the given literal conforms to the [Range](#Range) interface.
\r
2786 function is(value) {
\r
2787 var candidate = value;
\r
2788 return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
\r
2791 })(Range || (Range = {}));
\r
2793 * The Location namespace provides helper functions to work with
\r
2794 * [Location](#Location) literals.
\r
2797 (function (Location) {
\r
2799 * Creates a Location literal.
\r
2800 * @param uri The location's uri.
\r
2801 * @param range The location's range.
\r
2803 function create(uri, range) {
\r
2804 return { uri: uri, range: range };
\r
2806 Location.create = create;
\r
2808 * Checks whether the given literal conforms to the [Location](#Location) interface.
\r
2810 function is(value) {
\r
2811 var candidate = value;
\r
2812 return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
\r
2815 })(Location || (Location = {}));
\r
2817 * The LocationLink namespace provides helper functions to work with
\r
2818 * [LocationLink](#LocationLink) literals.
\r
2821 (function (LocationLink) {
\r
2823 * Creates a LocationLink literal.
\r
2824 * @param targetUri The definition's uri.
\r
2825 * @param targetRange The full range of the definition.
\r
2826 * @param targetSelectionRange The span of the symbol definition at the target.
\r
2827 * @param originSelectionRange The span of the symbol being defined in the originating source file.
\r
2829 function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
\r
2830 return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
\r
2832 LocationLink.create = create;
\r
2834 * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
\r
2836 function is(value) {
\r
2837 var candidate = value;
\r
2838 return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
\r
2839 && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
\r
2840 && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
\r
2842 LocationLink.is = is;
\r
2843 })(LocationLink || (LocationLink = {}));
\r
2845 * The Color namespace provides helper functions to work with
\r
2846 * [Color](#Color) literals.
\r
2849 (function (Color) {
\r
2851 * Creates a new Color literal.
\r
2853 function create(red, green, blue, alpha) {
\r
2861 Color.create = create;
\r
2863 * Checks whether the given literal conforms to the [Color](#Color) interface.
\r
2865 function is(value) {
\r
2866 var candidate = value;
\r
2867 return Is.number(candidate.red)
\r
2868 && Is.number(candidate.green)
\r
2869 && Is.number(candidate.blue)
\r
2870 && Is.number(candidate.alpha);
\r
2873 })(Color || (Color = {}));
\r
2875 * The ColorInformation namespace provides helper functions to work with
\r
2876 * [ColorInformation](#ColorInformation) literals.
\r
2878 var ColorInformation;
\r
2879 (function (ColorInformation) {
\r
2881 * Creates a new ColorInformation literal.
\r
2883 function create(range, color) {
\r
2889 ColorInformation.create = create;
\r
2891 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
\r
2893 function is(value) {
\r
2894 var candidate = value;
\r
2895 return Range.is(candidate.range) && Color.is(candidate.color);
\r
2897 ColorInformation.is = is;
\r
2898 })(ColorInformation || (ColorInformation = {}));
\r
2900 * The Color namespace provides helper functions to work with
\r
2901 * [ColorPresentation](#ColorPresentation) literals.
\r
2903 var ColorPresentation;
\r
2904 (function (ColorPresentation) {
\r
2906 * Creates a new ColorInformation literal.
\r
2908 function create(label, textEdit, additionalTextEdits) {
\r
2911 textEdit: textEdit,
\r
2912 additionalTextEdits: additionalTextEdits,
\r
2915 ColorPresentation.create = create;
\r
2917 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
\r
2919 function is(value) {
\r
2920 var candidate = value;
\r
2921 return Is.string(candidate.label)
\r
2922 && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
\r
2923 && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
\r
2925 ColorPresentation.is = is;
\r
2926 })(ColorPresentation || (ColorPresentation = {}));
\r
2928 * Enum of known range kinds
\r
2930 var FoldingRangeKind;
\r
2931 (function (FoldingRangeKind) {
\r
2933 * Folding range for a comment
\r
2935 FoldingRangeKind["Comment"] = "comment";
\r
2937 * Folding range for a imports or includes
\r
2939 FoldingRangeKind["Imports"] = "imports";
\r
2941 * Folding range for a region (e.g. `#region`)
\r
2943 FoldingRangeKind["Region"] = "region";
\r
2944 })(FoldingRangeKind || (FoldingRangeKind = {}));
\r
2946 * The folding range namespace provides helper functions to work with
\r
2947 * [FoldingRange](#FoldingRange) literals.
\r
2950 (function (FoldingRange) {
\r
2952 * Creates a new FoldingRange literal.
\r
2954 function create(startLine, endLine, startCharacter, endCharacter, kind) {
\r
2956 startLine: startLine,
\r
2959 if (Is.defined(startCharacter)) {
\r
2960 result.startCharacter = startCharacter;
\r
2962 if (Is.defined(endCharacter)) {
\r
2963 result.endCharacter = endCharacter;
\r
2965 if (Is.defined(kind)) {
\r
2966 result.kind = kind;
\r
2970 FoldingRange.create = create;
\r
2972 * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
\r
2974 function is(value) {
\r
2975 var candidate = value;
\r
2976 return Is.number(candidate.startLine) && Is.number(candidate.startLine)
\r
2977 && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
\r
2978 && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
\r
2979 && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
\r
2981 FoldingRange.is = is;
\r
2982 })(FoldingRange || (FoldingRange = {}));
\r
2984 * The DiagnosticRelatedInformation namespace provides helper functions to work with
\r
2985 * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
\r
2987 var DiagnosticRelatedInformation;
\r
2988 (function (DiagnosticRelatedInformation) {
\r
2990 * Creates a new DiagnosticRelatedInformation literal.
\r
2992 function create(location, message) {
\r
2994 location: location,
\r
2998 DiagnosticRelatedInformation.create = create;
\r
3000 * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
\r
3002 function is(value) {
\r
3003 var candidate = value;
\r
3004 return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
\r
3006 DiagnosticRelatedInformation.is = is;
\r
3007 })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
\r
3009 * The diagnostic's severity.
\r
3011 var DiagnosticSeverity;
\r
3012 (function (DiagnosticSeverity) {
\r
3014 * Reports an error.
\r
3016 DiagnosticSeverity.Error = 1;
\r
3018 * Reports a warning.
\r
3020 DiagnosticSeverity.Warning = 2;
\r
3022 * Reports an information.
\r
3024 DiagnosticSeverity.Information = 3;
\r
3028 DiagnosticSeverity.Hint = 4;
\r
3029 })(DiagnosticSeverity || (DiagnosticSeverity = {}));
\r
3031 * The diagnostic tags.
\r
3035 var DiagnosticTag;
\r
3036 (function (DiagnosticTag) {
\r
3038 * Unused or unnecessary code.
\r
3040 * Clients are allowed to render diagnostics with this tag faded out instead of having
\r
3041 * an error squiggle.
\r
3043 DiagnosticTag.Unnecessary = 1;
\r
3045 * Deprecated or obsolete code.
\r
3047 * Clients are allowed to rendered diagnostics with this tag strike through.
\r
3049 DiagnosticTag.Deprecated = 2;
\r
3050 })(DiagnosticTag || (DiagnosticTag = {}));
\r
3052 * The Diagnostic namespace provides helper functions to work with
\r
3053 * [Diagnostic](#Diagnostic) literals.
\r
3056 (function (Diagnostic) {
\r
3058 * Creates a new Diagnostic literal.
\r
3060 function create(range, message, severity, code, source, relatedInformation) {
\r
3061 var result = { range: range, message: message };
\r
3062 if (Is.defined(severity)) {
\r
3063 result.severity = severity;
\r
3065 if (Is.defined(code)) {
\r
3066 result.code = code;
\r
3068 if (Is.defined(source)) {
\r
3069 result.source = source;
\r
3071 if (Is.defined(relatedInformation)) {
\r
3072 result.relatedInformation = relatedInformation;
\r
3076 Diagnostic.create = create;
\r
3078 * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
\r
3080 function is(value) {
\r
3081 var candidate = value;
\r
3082 return Is.defined(candidate)
\r
3083 && Range.is(candidate.range)
\r
3084 && Is.string(candidate.message)
\r
3085 && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
\r
3086 && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
\r
3087 && (Is.string(candidate.source) || Is.undefined(candidate.source))
\r
3088 && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
\r
3090 Diagnostic.is = is;
\r
3091 })(Diagnostic || (Diagnostic = {}));
\r
3093 * The Command namespace provides helper functions to work with
\r
3094 * [Command](#Command) literals.
\r
3097 (function (Command) {
\r
3099 * Creates a new Command literal.
\r
3101 function create(title, command) {
\r
3103 for (var _i = 2; _i < arguments.length; _i++) {
\r
3104 args[_i - 2] = arguments[_i];
\r
3106 var result = { title: title, command: command };
\r
3107 if (Is.defined(args) && args.length > 0) {
\r
3108 result.arguments = args;
\r
3112 Command.create = create;
\r
3114 * Checks whether the given literal conforms to the [Command](#Command) interface.
\r
3116 function is(value) {
\r
3117 var candidate = value;
\r
3118 return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
\r
3121 })(Command || (Command = {}));
\r
3123 * The TextEdit namespace provides helper function to create replace,
\r
3124 * insert and delete edits more easily.
\r
3127 (function (TextEdit) {
\r
3129 * Creates a replace text edit.
\r
3130 * @param range The range of text to be replaced.
\r
3131 * @param newText The new text.
\r
3133 function replace(range, newText) {
\r
3134 return { range: range, newText: newText };
\r
3136 TextEdit.replace = replace;
\r
3138 * Creates a insert text edit.
\r
3139 * @param position The position to insert the text at.
\r
3140 * @param newText The text to be inserted.
\r
3142 function insert(position, newText) {
\r
3143 return { range: { start: position, end: position }, newText: newText };
\r
3145 TextEdit.insert = insert;
\r
3147 * Creates a delete text edit.
\r
3148 * @param range The range of text to be deleted.
\r
3150 function del(range) {
\r
3151 return { range: range, newText: '' };
\r
3153 TextEdit.del = del;
\r
3154 function is(value) {
\r
3155 var candidate = value;
\r
3156 return Is.objectLiteral(candidate)
\r
3157 && Is.string(candidate.newText)
\r
3158 && Range.is(candidate.range);
\r
3161 })(TextEdit || (TextEdit = {}));
\r
3163 * The TextDocumentEdit namespace provides helper function to create
\r
3164 * an edit that manipulates a text document.
\r
3166 var TextDocumentEdit;
\r
3167 (function (TextDocumentEdit) {
\r
3169 * Creates a new `TextDocumentEdit`
\r
3171 function create(textDocument, edits) {
\r
3172 return { textDocument: textDocument, edits: edits };
\r
3174 TextDocumentEdit.create = create;
\r
3175 function is(value) {
\r
3176 var candidate = value;
\r
3177 return Is.defined(candidate)
\r
3178 && VersionedTextDocumentIdentifier.is(candidate.textDocument)
\r
3179 && Array.isArray(candidate.edits);
\r
3181 TextDocumentEdit.is = is;
\r
3182 })(TextDocumentEdit || (TextDocumentEdit = {}));
\r
3184 (function (CreateFile) {
\r
3185 function create(uri, options) {
\r
3190 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
\r
3191 result.options = options;
\r
3195 CreateFile.create = create;
\r
3196 function is(value) {
\r
3197 var candidate = value;
\r
3198 return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
\r
3199 (candidate.options === void 0 ||
\r
3200 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
\r
3202 CreateFile.is = is;
\r
3203 })(CreateFile || (CreateFile = {}));
\r
3205 (function (RenameFile) {
\r
3206 function create(oldUri, newUri, options) {
\r
3212 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
\r
3213 result.options = options;
\r
3217 RenameFile.create = create;
\r
3218 function is(value) {
\r
3219 var candidate = value;
\r
3220 return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
\r
3221 (candidate.options === void 0 ||
\r
3222 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
\r
3224 RenameFile.is = is;
\r
3225 })(RenameFile || (RenameFile = {}));
\r
3227 (function (DeleteFile) {
\r
3228 function create(uri, options) {
\r
3233 if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
\r
3234 result.options = options;
\r
3238 DeleteFile.create = create;
\r
3239 function is(value) {
\r
3240 var candidate = value;
\r
3241 return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
\r
3242 (candidate.options === void 0 ||
\r
3243 ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
\r
3245 DeleteFile.is = is;
\r
3246 })(DeleteFile || (DeleteFile = {}));
\r
3247 var WorkspaceEdit;
\r
3248 (function (WorkspaceEdit) {
\r
3249 function is(value) {
\r
3250 var candidate = value;
\r
3251 return candidate &&
\r
3252 (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
\r
3253 (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
\r
3254 if (Is.string(change.kind)) {
\r
3255 return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
\r
3258 return TextDocumentEdit.is(change);
\r
3262 WorkspaceEdit.is = is;
\r
3263 })(WorkspaceEdit || (WorkspaceEdit = {}));
\r
3264 var TextEditChangeImpl = /** @class */ (function () {
\r
3265 function TextEditChangeImpl(edits) {
\r
3266 this.edits = edits;
\r
3268 TextEditChangeImpl.prototype.insert = function (position, newText) {
\r
3269 this.edits.push(TextEdit.insert(position, newText));
\r
3271 TextEditChangeImpl.prototype.replace = function (range, newText) {
\r
3272 this.edits.push(TextEdit.replace(range, newText));
\r
3274 TextEditChangeImpl.prototype.delete = function (range) {
\r
3275 this.edits.push(TextEdit.del(range));
\r
3277 TextEditChangeImpl.prototype.add = function (edit) {
\r
3278 this.edits.push(edit);
\r
3280 TextEditChangeImpl.prototype.all = function () {
\r
3281 return this.edits;
\r
3283 TextEditChangeImpl.prototype.clear = function () {
\r
3284 this.edits.splice(0, this.edits.length);
\r
3286 return TextEditChangeImpl;
\r
3289 * A workspace change helps constructing changes to a workspace.
\r
3291 var WorkspaceChange = /** @class */ (function () {
\r
3292 function WorkspaceChange(workspaceEdit) {
\r
3294 this._textEditChanges = Object.create(null);
\r
3295 if (workspaceEdit) {
\r
3296 this._workspaceEdit = workspaceEdit;
\r
3297 if (workspaceEdit.documentChanges) {
\r
3298 workspaceEdit.documentChanges.forEach(function (change) {
\r
3299 if (TextDocumentEdit.is(change)) {
\r
3300 var textEditChange = new TextEditChangeImpl(change.edits);
\r
3301 _this._textEditChanges[change.textDocument.uri] = textEditChange;
\r
3305 else if (workspaceEdit.changes) {
\r
3306 Object.keys(workspaceEdit.changes).forEach(function (key) {
\r
3307 var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
\r
3308 _this._textEditChanges[key] = textEditChange;
\r
3313 Object.defineProperty(WorkspaceChange.prototype, "edit", {
\r
3315 * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
\r
3316 * use to be returned from a workspace edit operation like rename.
\r
3318 get: function () {
\r
3319 return this._workspaceEdit;
\r
3322 configurable: true
\r
3324 WorkspaceChange.prototype.getTextEditChange = function (key) {
\r
3325 if (VersionedTextDocumentIdentifier.is(key)) {
\r
3326 if (!this._workspaceEdit) {
\r
3327 this._workspaceEdit = {
\r
3328 documentChanges: []
\r
3331 if (!this._workspaceEdit.documentChanges) {
\r
3332 throw new Error('Workspace edit is not configured for document changes.');
\r
3334 var textDocument = key;
\r
3335 var result = this._textEditChanges[textDocument.uri];
\r
3338 var textDocumentEdit = {
\r
3339 textDocument: textDocument,
\r
3342 this._workspaceEdit.documentChanges.push(textDocumentEdit);
\r
3343 result = new TextEditChangeImpl(edits);
\r
3344 this._textEditChanges[textDocument.uri] = result;
\r
3349 if (!this._workspaceEdit) {
\r
3350 this._workspaceEdit = {
\r
3351 changes: Object.create(null)
\r
3354 if (!this._workspaceEdit.changes) {
\r
3355 throw new Error('Workspace edit is not configured for normal text edit changes.');
\r
3357 var result = this._textEditChanges[key];
\r
3360 this._workspaceEdit.changes[key] = edits;
\r
3361 result = new TextEditChangeImpl(edits);
\r
3362 this._textEditChanges[key] = result;
\r
3367 WorkspaceChange.prototype.createFile = function (uri, options) {
\r
3368 this.checkDocumentChanges();
\r
3369 this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
\r
3371 WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
\r
3372 this.checkDocumentChanges();
\r
3373 this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
\r
3375 WorkspaceChange.prototype.deleteFile = function (uri, options) {
\r
3376 this.checkDocumentChanges();
\r
3377 this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
\r
3379 WorkspaceChange.prototype.checkDocumentChanges = function () {
\r
3380 if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
\r
3381 throw new Error('Workspace edit is not configured for document changes.');
\r
3384 return WorkspaceChange;
\r
3388 * The TextDocumentIdentifier namespace provides helper functions to work with
\r
3389 * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
\r
3391 var TextDocumentIdentifier;
\r
3392 (function (TextDocumentIdentifier) {
\r
3394 * Creates a new TextDocumentIdentifier literal.
\r
3395 * @param uri The document's uri.
\r
3397 function create(uri) {
\r
3398 return { uri: uri };
\r
3400 TextDocumentIdentifier.create = create;
\r
3402 * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
\r
3404 function is(value) {
\r
3405 var candidate = value;
\r
3406 return Is.defined(candidate) && Is.string(candidate.uri);
\r
3408 TextDocumentIdentifier.is = is;
\r
3409 })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
\r
3411 * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
\r
3412 * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
\r
3414 var VersionedTextDocumentIdentifier;
\r
3415 (function (VersionedTextDocumentIdentifier) {
\r
3417 * Creates a new VersionedTextDocumentIdentifier literal.
\r
3418 * @param uri The document's uri.
\r
3419 * @param uri The document's text.
\r
3421 function create(uri, version) {
\r
3422 return { uri: uri, version: version };
\r
3424 VersionedTextDocumentIdentifier.create = create;
\r
3426 * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
\r
3428 function is(value) {
\r
3429 var candidate = value;
\r
3430 return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
\r
3432 VersionedTextDocumentIdentifier.is = is;
\r
3433 })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
\r
3435 * The TextDocumentItem namespace provides helper functions to work with
\r
3436 * [TextDocumentItem](#TextDocumentItem) literals.
\r
3438 var TextDocumentItem;
\r
3439 (function (TextDocumentItem) {
\r
3441 * Creates a new TextDocumentItem literal.
\r
3442 * @param uri The document's uri.
\r
3443 * @param languageId The document's language identifier.
\r
3444 * @param version The document's version number.
\r
3445 * @param text The document's text.
\r
3447 function create(uri, languageId, version, text) {
\r
3448 return { uri: uri, languageId: languageId, version: version, text: text };
\r
3450 TextDocumentItem.create = create;
\r
3452 * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
\r
3454 function is(value) {
\r
3455 var candidate = value;
\r
3456 return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
\r
3458 TextDocumentItem.is = is;
\r
3459 })(TextDocumentItem || (TextDocumentItem = {}));
\r
3461 * Describes the content type that a client supports in various
\r
3462 * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
\r
3464 * Please note that `MarkupKinds` must not start with a `$`. This kinds
\r
3465 * are reserved for internal usage.
\r
3468 (function (MarkupKind) {
\r
3470 * Plain text is supported as a content format
\r
3472 MarkupKind.PlainText = 'plaintext';
\r
3474 * Markdown is supported as a content format
\r
3476 MarkupKind.Markdown = 'markdown';
\r
3477 })(MarkupKind || (MarkupKind = {}));
\r
3478 (function (MarkupKind) {
\r
3480 * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
\r
3482 function is(value) {
\r
3483 var candidate = value;
\r
3484 return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
\r
3486 MarkupKind.is = is;
\r
3487 })(MarkupKind || (MarkupKind = {}));
\r
3488 var MarkupContent;
\r
3489 (function (MarkupContent) {
\r
3491 * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
\r
3493 function is(value) {
\r
3494 var candidate = value;
\r
3495 return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
\r
3497 MarkupContent.is = is;
\r
3498 })(MarkupContent || (MarkupContent = {}));
\r
3500 * The kind of a completion entry.
\r
3502 var CompletionItemKind;
\r
3503 (function (CompletionItemKind) {
\r
3504 CompletionItemKind.Text = 1;
\r
3505 CompletionItemKind.Method = 2;
\r
3506 CompletionItemKind.Function = 3;
\r
3507 CompletionItemKind.Constructor = 4;
\r
3508 CompletionItemKind.Field = 5;
\r
3509 CompletionItemKind.Variable = 6;
\r
3510 CompletionItemKind.Class = 7;
\r
3511 CompletionItemKind.Interface = 8;
\r
3512 CompletionItemKind.Module = 9;
\r
3513 CompletionItemKind.Property = 10;
\r
3514 CompletionItemKind.Unit = 11;
\r
3515 CompletionItemKind.Value = 12;
\r
3516 CompletionItemKind.Enum = 13;
\r
3517 CompletionItemKind.Keyword = 14;
\r
3518 CompletionItemKind.Snippet = 15;
\r
3519 CompletionItemKind.Color = 16;
\r
3520 CompletionItemKind.File = 17;
\r
3521 CompletionItemKind.Reference = 18;
\r
3522 CompletionItemKind.Folder = 19;
\r
3523 CompletionItemKind.EnumMember = 20;
\r
3524 CompletionItemKind.Constant = 21;
\r
3525 CompletionItemKind.Struct = 22;
\r
3526 CompletionItemKind.Event = 23;
\r
3527 CompletionItemKind.Operator = 24;
\r
3528 CompletionItemKind.TypeParameter = 25;
\r
3529 })(CompletionItemKind || (CompletionItemKind = {}));
\r
3531 * Defines whether the insert text in a completion item should be interpreted as
\r
3532 * plain text or a snippet.
\r
3534 var InsertTextFormat;
\r
3535 (function (InsertTextFormat) {
\r
3537 * The primary text to be inserted is treated as a plain string.
\r
3539 InsertTextFormat.PlainText = 1;
\r
3541 * The primary text to be inserted is treated as a snippet.
\r
3543 * A snippet can define tab stops and placeholders with `$1`, `$2`
\r
3544 * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
\r
3545 * the end of the snippet. Placeholders with equal identifiers are linked,
\r
3546 * that is typing in one will update others too.
\r
3548 * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
\r
3550 InsertTextFormat.Snippet = 2;
\r
3551 })(InsertTextFormat || (InsertTextFormat = {}));
\r
3553 * Completion item tags are extra annotations that tweak the rendering of a completion
\r
3558 var CompletionItemTag;
\r
3559 (function (CompletionItemTag) {
\r
3561 * Render a completion as obsolete, usually using a strike-out.
\r
3563 CompletionItemTag.Deprecated = 1;
\r
3564 })(CompletionItemTag || (CompletionItemTag = {}));
\r
3566 * The CompletionItem namespace provides functions to deal with
\r
3567 * completion items.
\r
3569 var CompletionItem;
\r
3570 (function (CompletionItem) {
\r
3572 * Create a completion item and seed it with a label.
\r
3573 * @param label The completion item's label
\r
3575 function create(label) {
\r
3576 return { label: label };
\r
3578 CompletionItem.create = create;
\r
3579 })(CompletionItem || (CompletionItem = {}));
\r
3581 * The CompletionList namespace provides functions to deal with
\r
3582 * completion lists.
\r
3584 var CompletionList;
\r
3585 (function (CompletionList) {
\r
3587 * Creates a new completion list.
\r
3589 * @param items The completion items.
\r
3590 * @param isIncomplete The list is not complete.
\r
3592 function create(items, isIncomplete) {
\r
3593 return { items: items ? items : [], isIncomplete: !!isIncomplete };
\r
3595 CompletionList.create = create;
\r
3596 })(CompletionList || (CompletionList = {}));
\r
3598 (function (MarkedString) {
\r
3600 * Creates a marked string from plain text.
\r
3602 * @param plainText The plain text.
\r
3604 function fromPlainText(plainText) {
\r
3605 return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
\r
3607 MarkedString.fromPlainText = fromPlainText;
\r
3609 * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
\r
3611 function is(value) {
\r
3612 var candidate = value;
\r
3613 return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
\r
3615 MarkedString.is = is;
\r
3616 })(MarkedString || (MarkedString = {}));
\r
3618 (function (Hover) {
\r
3620 * Checks whether the given value conforms to the [Hover](#Hover) interface.
\r
3622 function is(value) {
\r
3623 var candidate = value;
\r
3624 return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
\r
3625 MarkedString.is(candidate.contents) ||
\r
3626 Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
\r
3629 })(Hover || (Hover = {}));
\r
3631 * The ParameterInformation namespace provides helper functions to work with
\r
3632 * [ParameterInformation](#ParameterInformation) literals.
\r
3634 var ParameterInformation;
\r
3635 (function (ParameterInformation) {
\r
3637 * Creates a new parameter information literal.
\r
3639 * @param label A label string.
\r
3640 * @param documentation A doc string.
\r
3642 function create(label, documentation) {
\r
3643 return documentation ? { label: label, documentation: documentation } : { label: label };
\r
3645 ParameterInformation.create = create;
\r
3646 })(ParameterInformation || (ParameterInformation = {}));
\r
3648 * The SignatureInformation namespace provides helper functions to work with
\r
3649 * [SignatureInformation](#SignatureInformation) literals.
\r
3651 var SignatureInformation;
\r
3652 (function (SignatureInformation) {
\r
3653 function create(label, documentation) {
\r
3654 var parameters = [];
\r
3655 for (var _i = 2; _i < arguments.length; _i++) {
\r
3656 parameters[_i - 2] = arguments[_i];
\r
3658 var result = { label: label };
\r
3659 if (Is.defined(documentation)) {
\r
3660 result.documentation = documentation;
\r
3662 if (Is.defined(parameters)) {
\r
3663 result.parameters = parameters;
\r
3666 result.parameters = [];
\r
3670 SignatureInformation.create = create;
\r
3671 })(SignatureInformation || (SignatureInformation = {}));
\r
3673 * A document highlight kind.
\r
3675 var DocumentHighlightKind;
\r
3676 (function (DocumentHighlightKind) {
\r
3678 * A textual occurrence.
\r
3680 DocumentHighlightKind.Text = 1;
\r
3682 * Read-access of a symbol, like reading a variable.
\r
3684 DocumentHighlightKind.Read = 2;
\r
3686 * Write-access of a symbol, like writing to a variable.
\r
3688 DocumentHighlightKind.Write = 3;
\r
3689 })(DocumentHighlightKind || (DocumentHighlightKind = {}));
\r
3691 * DocumentHighlight namespace to provide helper functions to work with
\r
3692 * [DocumentHighlight](#DocumentHighlight) literals.
\r
3694 var DocumentHighlight;
\r
3695 (function (DocumentHighlight) {
\r
3697 * Create a DocumentHighlight object.
\r
3698 * @param range The range the highlight applies to.
\r
3700 function create(range, kind) {
\r
3701 var result = { range: range };
\r
3702 if (Is.number(kind)) {
\r
3703 result.kind = kind;
\r
3707 DocumentHighlight.create = create;
\r
3708 })(DocumentHighlight || (DocumentHighlight = {}));
\r
3713 (function (SymbolKind) {
\r
3714 SymbolKind.File = 1;
\r
3715 SymbolKind.Module = 2;
\r
3716 SymbolKind.Namespace = 3;
\r
3717 SymbolKind.Package = 4;
\r
3718 SymbolKind.Class = 5;
\r
3719 SymbolKind.Method = 6;
\r
3720 SymbolKind.Property = 7;
\r
3721 SymbolKind.Field = 8;
\r
3722 SymbolKind.Constructor = 9;
\r
3723 SymbolKind.Enum = 10;
\r
3724 SymbolKind.Interface = 11;
\r
3725 SymbolKind.Function = 12;
\r
3726 SymbolKind.Variable = 13;
\r
3727 SymbolKind.Constant = 14;
\r
3728 SymbolKind.String = 15;
\r
3729 SymbolKind.Number = 16;
\r
3730 SymbolKind.Boolean = 17;
\r
3731 SymbolKind.Array = 18;
\r
3732 SymbolKind.Object = 19;
\r
3733 SymbolKind.Key = 20;
\r
3734 SymbolKind.Null = 21;
\r
3735 SymbolKind.EnumMember = 22;
\r
3736 SymbolKind.Struct = 23;
\r
3737 SymbolKind.Event = 24;
\r
3738 SymbolKind.Operator = 25;
\r
3739 SymbolKind.TypeParameter = 26;
\r
3740 })(SymbolKind || (SymbolKind = {}));
\r
3742 * Symbol tags are extra annotations that tweak the rendering of a symbol.
\r
3746 (function (SymbolTag) {
\r
3748 * Render a symbol as obsolete, usually using a strike-out.
\r
3750 SymbolTag.Deprecated = 1;
\r
3751 })(SymbolTag || (SymbolTag = {}));
\r
3752 var SymbolInformation;
\r
3753 (function (SymbolInformation) {
\r
3755 * Creates a new symbol information literal.
\r
3757 * @param name The name of the symbol.
\r
3758 * @param kind The kind of the symbol.
\r
3759 * @param range The range of the location of the symbol.
\r
3760 * @param uri The resource of the location of symbol, defaults to the current document.
\r
3761 * @param containerName The name of the symbol containing the symbol.
\r
3763 function create(name, kind, range, uri, containerName) {
\r
3767 location: { uri: uri, range: range }
\r
3769 if (containerName) {
\r
3770 result.containerName = containerName;
\r
3774 SymbolInformation.create = create;
\r
3775 })(SymbolInformation || (SymbolInformation = {}));
\r
3776 var DocumentSymbol;
\r
3777 (function (DocumentSymbol) {
\r
3779 * Creates a new symbol information literal.
\r
3781 * @param name The name of the symbol.
\r
3782 * @param detail The detail of the symbol.
\r
3783 * @param kind The kind of the symbol.
\r
3784 * @param range The range of the symbol.
\r
3785 * @param selectionRange The selectionRange of the symbol.
\r
3786 * @param children Children of the symbol.
\r
3788 function create(name, detail, kind, range, selectionRange, children) {
\r
3794 selectionRange: selectionRange
\r
3796 if (children !== void 0) {
\r
3797 result.children = children;
\r
3801 DocumentSymbol.create = create;
\r
3803 * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
\r
3805 function is(value) {
\r
3806 var candidate = value;
\r
3807 return candidate &&
\r
3808 Is.string(candidate.name) && Is.number(candidate.kind) &&
\r
3809 Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
\r
3810 (candidate.detail === void 0 || Is.string(candidate.detail)) &&
\r
3811 (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
\r
3812 (candidate.children === void 0 || Array.isArray(candidate.children));
\r
3814 DocumentSymbol.is = is;
\r
3815 })(DocumentSymbol || (DocumentSymbol = {}));
\r
3817 * A set of predefined code action kinds
\r
3819 var CodeActionKind;
\r
3820 (function (CodeActionKind) {
\r
3824 CodeActionKind.Empty = '';
\r
3826 * Base kind for quickfix actions: 'quickfix'
\r
3828 CodeActionKind.QuickFix = 'quickfix';
\r
3830 * Base kind for refactoring actions: 'refactor'
\r
3832 CodeActionKind.Refactor = 'refactor';
\r
3834 * Base kind for refactoring extraction actions: 'refactor.extract'
\r
3836 * Example extract actions:
\r
3838 * - Extract method
\r
3839 * - Extract function
\r
3840 * - Extract variable
\r
3841 * - Extract interface from class
\r
3844 CodeActionKind.RefactorExtract = 'refactor.extract';
\r
3846 * Base kind for refactoring inline actions: 'refactor.inline'
\r
3848 * Example inline actions:
\r
3850 * - Inline function
\r
3851 * - Inline variable
\r
3852 * - Inline constant
\r
3855 CodeActionKind.RefactorInline = 'refactor.inline';
\r
3857 * Base kind for refactoring rewrite actions: 'refactor.rewrite'
\r
3859 * Example rewrite actions:
\r
3861 * - Convert JavaScript function to class
\r
3862 * - Add or remove parameter
\r
3863 * - Encapsulate field
\r
3864 * - Make method static
\r
3865 * - Move method to base class
\r
3868 CodeActionKind.RefactorRewrite = 'refactor.rewrite';
\r
3870 * Base kind for source actions: `source`
\r
3872 * Source code actions apply to the entire file.
\r
3874 CodeActionKind.Source = 'source';
\r
3876 * Base kind for an organize imports source action: `source.organizeImports`
\r
3878 CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
\r
3880 * Base kind for auto-fix source actions: `source.fixAll`.
\r
3882 * Fix all actions automatically fix errors that have a clear fix that do not require user input.
\r
3883 * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
\r
3887 CodeActionKind.SourceFixAll = 'source.fixAll';
\r
3888 })(CodeActionKind || (CodeActionKind = {}));
\r
3890 * The CodeActionContext namespace provides helper functions to work with
\r
3891 * [CodeActionContext](#CodeActionContext) literals.
\r
3893 var CodeActionContext;
\r
3894 (function (CodeActionContext) {
\r
3896 * Creates a new CodeActionContext literal.
\r
3898 function create(diagnostics, only) {
\r
3899 var result = { diagnostics: diagnostics };
\r
3900 if (only !== void 0 && only !== null) {
\r
3901 result.only = only;
\r
3905 CodeActionContext.create = create;
\r
3907 * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
\r
3909 function is(value) {
\r
3910 var candidate = value;
\r
3911 return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
\r
3913 CodeActionContext.is = is;
\r
3914 })(CodeActionContext || (CodeActionContext = {}));
\r
3916 (function (CodeAction) {
\r
3917 function create(title, commandOrEdit, kind) {
\r
3918 var result = { title: title };
\r
3919 if (Command.is(commandOrEdit)) {
\r
3920 result.command = commandOrEdit;
\r
3923 result.edit = commandOrEdit;
\r
3925 if (kind !== void 0) {
\r
3926 result.kind = kind;
\r
3930 CodeAction.create = create;
\r
3931 function is(value) {
\r
3932 var candidate = value;
\r
3933 return candidate && Is.string(candidate.title) &&
\r
3934 (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
\r
3935 (candidate.kind === void 0 || Is.string(candidate.kind)) &&
\r
3936 (candidate.edit !== void 0 || candidate.command !== void 0) &&
\r
3937 (candidate.command === void 0 || Command.is(candidate.command)) &&
\r
3938 (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&
\r
3939 (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
\r
3941 CodeAction.is = is;
\r
3942 })(CodeAction || (CodeAction = {}));
\r
3944 * The CodeLens namespace provides helper functions to work with
\r
3945 * [CodeLens](#CodeLens) literals.
\r
3948 (function (CodeLens) {
\r
3950 * Creates a new CodeLens literal.
\r
3952 function create(range, data) {
\r
3953 var result = { range: range };
\r
3954 if (Is.defined(data)) {
\r
3955 result.data = data;
\r
3959 CodeLens.create = create;
\r
3961 * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
\r
3963 function is(value) {
\r
3964 var candidate = value;
\r
3965 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
\r
3968 })(CodeLens || (CodeLens = {}));
\r
3970 * The FormattingOptions namespace provides helper functions to work with
\r
3971 * [FormattingOptions](#FormattingOptions) literals.
\r
3973 var FormattingOptions;
\r
3974 (function (FormattingOptions) {
\r
3976 * Creates a new FormattingOptions literal.
\r
3978 function create(tabSize, insertSpaces) {
\r
3979 return { tabSize: tabSize, insertSpaces: insertSpaces };
\r
3981 FormattingOptions.create = create;
\r
3983 * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
\r
3985 function is(value) {
\r
3986 var candidate = value;
\r
3987 return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
\r
3989 FormattingOptions.is = is;
\r
3990 })(FormattingOptions || (FormattingOptions = {}));
\r
3992 * The DocumentLink namespace provides helper functions to work with
\r
3993 * [DocumentLink](#DocumentLink) literals.
\r
3996 (function (DocumentLink) {
\r
3998 * Creates a new DocumentLink literal.
\r
4000 function create(range, target, data) {
\r
4001 return { range: range, target: target, data: data };
\r
4003 DocumentLink.create = create;
\r
4005 * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
\r
4007 function is(value) {
\r
4008 var candidate = value;
\r
4009 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
\r
4011 DocumentLink.is = is;
\r
4012 })(DocumentLink || (DocumentLink = {}));
\r
4014 * The SelectionRange namespace provides helper function to work with
\r
4015 * SelectionRange literals.
\r
4017 var SelectionRange;
\r
4018 (function (SelectionRange) {
\r
4020 * Creates a new SelectionRange
\r
4021 * @param range the range.
\r
4022 * @param parent an optional parent.
\r
4024 function create(range, parent) {
\r
4025 return { range: range, parent: parent };
\r
4027 SelectionRange.create = create;
\r
4028 function is(value) {
\r
4029 var candidate = value;
\r
4030 return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
\r
4032 SelectionRange.is = is;
\r
4033 })(SelectionRange || (SelectionRange = {}));
\r
4034 var EOL = ['\n', '\r\n', '\r'];
\r
4036 * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
\r
4039 (function (TextDocument) {
\r
4041 * Creates a new ITextDocument literal from the given uri and content.
\r
4042 * @param uri The document's uri.
\r
4043 * @param languageId The document's language Id.
\r
4044 * @param content The document's content.
\r
4046 function create(uri, languageId, version, content) {
\r
4047 return new FullTextDocument(uri, languageId, version, content);
\r
4049 TextDocument.create = create;
\r
4051 * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
\r
4053 function is(value) {
\r
4054 var candidate = value;
\r
4055 return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
\r
4056 && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
\r
4058 TextDocument.is = is;
\r
4059 function applyEdits(document, edits) {
\r
4060 var text = document.getText();
\r
4061 var sortedEdits = mergeSort(edits, function (a, b) {
\r
4062 var diff = a.range.start.line - b.range.start.line;
\r
4064 return a.range.start.character - b.range.start.character;
\r
4068 var lastModifiedOffset = text.length;
\r
4069 for (var i = sortedEdits.length - 1; i >= 0; i--) {
\r
4070 var e = sortedEdits[i];
\r
4071 var startOffset = document.offsetAt(e.range.start);
\r
4072 var endOffset = document.offsetAt(e.range.end);
\r
4073 if (endOffset <= lastModifiedOffset) {
\r
4074 text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
\r
4077 throw new Error('Overlapping edit');
\r
4079 lastModifiedOffset = startOffset;
\r
4083 TextDocument.applyEdits = applyEdits;
\r
4084 function mergeSort(data, compare) {
\r
4085 if (data.length <= 1) {
\r
4089 var p = (data.length / 2) | 0;
\r
4090 var left = data.slice(0, p);
\r
4091 var right = data.slice(p);
\r
4092 mergeSort(left, compare);
\r
4093 mergeSort(right, compare);
\r
4097 while (leftIdx < left.length && rightIdx < right.length) {
\r
4098 var ret = compare(left[leftIdx], right[rightIdx]);
\r
4100 // smaller_equal -> take left to preserve order
\r
4101 data[i++] = left[leftIdx++];
\r
4104 // greater -> take right
\r
4105 data[i++] = right[rightIdx++];
\r
4108 while (leftIdx < left.length) {
\r
4109 data[i++] = left[leftIdx++];
\r
4111 while (rightIdx < right.length) {
\r
4112 data[i++] = right[rightIdx++];
\r
4116 })(TextDocument || (TextDocument = {}));
\r
4117 var FullTextDocument = /** @class */ (function () {
\r
4118 function FullTextDocument(uri, languageId, version, content) {
\r
4120 this._languageId = languageId;
\r
4121 this._version = version;
\r
4122 this._content = content;
\r
4123 this._lineOffsets = undefined;
\r
4125 Object.defineProperty(FullTextDocument.prototype, "uri", {
\r
4126 get: function () {
\r
4130 configurable: true
\r
4132 Object.defineProperty(FullTextDocument.prototype, "languageId", {
\r
4133 get: function () {
\r
4134 return this._languageId;
\r
4137 configurable: true
\r
4139 Object.defineProperty(FullTextDocument.prototype, "version", {
\r
4140 get: function () {
\r
4141 return this._version;
\r
4144 configurable: true
\r
4146 FullTextDocument.prototype.getText = function (range) {
\r
4148 var start = this.offsetAt(range.start);
\r
4149 var end = this.offsetAt(range.end);
\r
4150 return this._content.substring(start, end);
\r
4152 return this._content;
\r
4154 FullTextDocument.prototype.update = function (event, version) {
\r
4155 this._content = event.text;
\r
4156 this._version = version;
\r
4157 this._lineOffsets = undefined;
\r
4159 FullTextDocument.prototype.getLineOffsets = function () {
\r
4160 if (this._lineOffsets === undefined) {
\r
4161 var lineOffsets = [];
\r
4162 var text = this._content;
\r
4163 var isLineStart = true;
\r
4164 for (var i = 0; i < text.length; i++) {
\r
4165 if (isLineStart) {
\r
4166 lineOffsets.push(i);
\r
4167 isLineStart = false;
\r
4169 var ch = text.charAt(i);
\r
4170 isLineStart = (ch === '\r' || ch === '\n');
\r
4171 if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
\r
4175 if (isLineStart && text.length > 0) {
\r
4176 lineOffsets.push(text.length);
\r
4178 this._lineOffsets = lineOffsets;
\r
4180 return this._lineOffsets;
\r
4182 FullTextDocument.prototype.positionAt = function (offset) {
\r
4183 offset = Math.max(Math.min(offset, this._content.length), 0);
\r
4184 var lineOffsets = this.getLineOffsets();
\r
4185 var low = 0, high = lineOffsets.length;
\r
4187 return Position.create(0, offset);
\r
4189 while (low < high) {
\r
4190 var mid = Math.floor((low + high) / 2);
\r
4191 if (lineOffsets[mid] > offset) {
\r
4198 // low is the least x for which the line offset is larger than the current offset
\r
4199 // or array.length if no line offset is larger than the current offset
\r
4200 var line = low - 1;
\r
4201 return Position.create(line, offset - lineOffsets[line]);
\r
4203 FullTextDocument.prototype.offsetAt = function (position) {
\r
4204 var lineOffsets = this.getLineOffsets();
\r
4205 if (position.line >= lineOffsets.length) {
\r
4206 return this._content.length;
\r
4208 else if (position.line < 0) {
\r
4211 var lineOffset = lineOffsets[position.line];
\r
4212 var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
\r
4213 return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
\r
4215 Object.defineProperty(FullTextDocument.prototype, "lineCount", {
\r
4216 get: function () {
\r
4217 return this.getLineOffsets().length;
\r
4220 configurable: true
\r
4222 return FullTextDocument;
\r
4226 var toString = Object.prototype.toString;
\r
4227 function defined(value) {
\r
4228 return typeof value !== 'undefined';
\r
4230 Is.defined = defined;
\r
4231 function undefined(value) {
\r
4232 return typeof value === 'undefined';
\r
4234 Is.undefined = undefined;
\r
4235 function boolean(value) {
\r
4236 return value === true || value === false;
\r
4238 Is.boolean = boolean;
\r
4239 function string(value) {
\r
4240 return toString.call(value) === '[object String]';
\r
4242 Is.string = string;
\r
4243 function number(value) {
\r
4244 return toString.call(value) === '[object Number]';
\r
4246 Is.number = number;
\r
4247 function func(value) {
\r
4248 return toString.call(value) === '[object Function]';
\r
4251 function objectLiteral(value) {
\r
4252 // Strictly speaking class instances pass this check as well. Since the LSP
\r
4253 // doesn't use classes we ignore this for now. If we do we need to add something
\r
4254 // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
\r
4255 return value !== null && typeof value === 'object';
\r
4257 Is.objectLiteral = objectLiteral;
\r
4258 function typedArray(value, check) {
\r
4259 return Array.isArray(value) && value.every(check);
\r
4261 Is.typedArray = typedArray;
\r
4262 })(Is || (Is = {}));
\r
4267 /***/ (function(module, exports, __webpack_require__) {
4270 /* --------------------------------------------------------------------------------------------
\r
4271 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4272 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4273 * ------------------------------------------------------------------------------------------ */
\r
4275 Object.defineProperty(exports, "__esModule", { value: true });
\r
4276 const Is = __webpack_require__(20);
\r
4277 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
4278 const messages_1 = __webpack_require__(21);
\r
4279 const protocol_implementation_1 = __webpack_require__(22);
\r
4280 exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
\r
4281 const protocol_typeDefinition_1 = __webpack_require__(23);
\r
4282 exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
\r
4283 const protocol_workspaceFolders_1 = __webpack_require__(24);
\r
4284 exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
\r
4285 exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
\r
4286 const protocol_configuration_1 = __webpack_require__(25);
\r
4287 exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
\r
4288 const protocol_colorProvider_1 = __webpack_require__(26);
\r
4289 exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
\r
4290 exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
\r
4291 const protocol_foldingRange_1 = __webpack_require__(27);
\r
4292 exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
\r
4293 const protocol_declaration_1 = __webpack_require__(28);
\r
4294 exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
\r
4295 const protocol_selectionRange_1 = __webpack_require__(29);
\r
4296 exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;
\r
4297 const protocol_progress_1 = __webpack_require__(30);
\r
4298 exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;
\r
4299 exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;
\r
4300 exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;
\r
4301 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
4302 let __noDynamicImport;
\r
4304 * The DocumentFilter namespace provides helper functions to work with
\r
4305 * [DocumentFilter](#DocumentFilter) literals.
\r
4307 var DocumentFilter;
\r
4308 (function (DocumentFilter) {
\r
4309 function is(value) {
\r
4310 const candidate = value;
\r
4311 return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
\r
4313 DocumentFilter.is = is;
\r
4314 })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));
\r
4316 * The DocumentSelector namespace provides helper functions to work with
\r
4317 * [DocumentSelector](#DocumentSelector)s.
\r
4319 var DocumentSelector;
\r
4320 (function (DocumentSelector) {
\r
4321 function is(value) {
\r
4322 if (!Array.isArray(value)) {
\r
4325 for (let elem of value) {
\r
4326 if (!Is.string(elem) && !DocumentFilter.is(elem)) {
\r
4332 DocumentSelector.is = is;
\r
4333 })(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));
\r
4335 * The `client/registerCapability` request is sent from the server to the client to register a new capability
\r
4336 * handler on the client side.
\r
4338 var RegistrationRequest;
\r
4339 (function (RegistrationRequest) {
\r
4340 RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability');
\r
4341 })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
\r
4343 * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
\r
4344 * handler on the client side.
\r
4346 var UnregistrationRequest;
\r
4347 (function (UnregistrationRequest) {
\r
4348 UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability');
\r
4349 })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
\r
4350 var ResourceOperationKind;
\r
4351 (function (ResourceOperationKind) {
\r
4353 * Supports creating new files and folders.
\r
4355 ResourceOperationKind.Create = 'create';
\r
4357 * Supports renaming existing files and folders.
\r
4359 ResourceOperationKind.Rename = 'rename';
\r
4361 * Supports deleting existing files and folders.
\r
4363 ResourceOperationKind.Delete = 'delete';
\r
4364 })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
\r
4365 var FailureHandlingKind;
\r
4366 (function (FailureHandlingKind) {
\r
4368 * Applying the workspace change is simply aborted if one of the changes provided
\r
4369 * fails. All operations executed before the failing operation stay executed.
\r
4371 FailureHandlingKind.Abort = 'abort';
\r
4373 * All operations are executed transactional. That means they either all
\r
4374 * succeed or no changes at all are applied to the workspace.
\r
4376 FailureHandlingKind.Transactional = 'transactional';
\r
4378 * If the workspace edit contains only textual file changes they are executed transactional.
\r
4379 * If resource changes (create, rename or delete file) are part of the change the failure
\r
4380 * handling startegy is abort.
\r
4382 FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
\r
4384 * The client tries to undo the operations already executed. But there is no
\r
4385 * guarantee that this is succeeding.
\r
4387 FailureHandlingKind.Undo = 'undo';
\r
4388 })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
\r
4390 * The StaticRegistrationOptions namespace provides helper functions to work with
\r
4391 * [StaticRegistrationOptions](#StaticRegistrationOptions) literals.
\r
4393 var StaticRegistrationOptions;
\r
4394 (function (StaticRegistrationOptions) {
\r
4395 function hasId(value) {
\r
4396 const candidate = value;
\r
4397 return candidate && Is.string(candidate.id) && candidate.id.length > 0;
\r
4399 StaticRegistrationOptions.hasId = hasId;
\r
4400 })(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));
\r
4402 * The TextDocumentRegistrationOptions namespace provides helper functions to work with
\r
4403 * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals.
\r
4405 var TextDocumentRegistrationOptions;
\r
4406 (function (TextDocumentRegistrationOptions) {
\r
4407 function is(value) {
\r
4408 const candidate = value;
\r
4409 return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
\r
4411 TextDocumentRegistrationOptions.is = is;
\r
4412 })(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));
\r
4414 * The WorkDoneProgressOptions namespace provides helper functions to work with
\r
4415 * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals.
\r
4417 var WorkDoneProgressOptions;
\r
4418 (function (WorkDoneProgressOptions) {
\r
4419 function is(value) {
\r
4420 const candidate = value;
\r
4421 return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));
\r
4423 WorkDoneProgressOptions.is = is;
\r
4424 function hasWorkDoneProgress(value) {
\r
4425 const candidate = value;
\r
4426 return candidate && Is.boolean(candidate.workDoneProgress);
\r
4428 WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;
\r
4429 })(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));
\r
4431 * The initialize request is sent from the client to the server.
\r
4432 * It is sent once as the request after starting up the server.
\r
4433 * The requests parameter is of type [InitializeParams](#InitializeParams)
\r
4434 * the response if of type [InitializeResult](#InitializeResult) of a Thenable that
\r
4435 * resolves to such.
\r
4437 var InitializeRequest;
\r
4438 (function (InitializeRequest) {
\r
4439 InitializeRequest.type = new messages_1.ProtocolRequestType('initialize');
\r
4440 })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
\r
4442 * Known error codes for an `InitializeError`;
\r
4444 var InitializeError;
\r
4445 (function (InitializeError) {
\r
4447 * If the protocol version provided by the client can't be handled by the server.
\r
4448 * @deprecated This initialize error got replaced by client capabilities. There is
\r
4449 * no version handshake in version 3.0x
\r
4451 InitializeError.unknownProtocolVersion = 1;
\r
4452 })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));
\r
4454 * The intialized notification is sent from the client to the
\r
4455 * server after the client is fully initialized and the server
\r
4456 * is allowed to send requests from the server to the client.
\r
4458 var InitializedNotification;
\r
4459 (function (InitializedNotification) {
\r
4460 InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized');
\r
4461 })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
\r
4462 //---- Shutdown Method ----
\r
4464 * A shutdown request is sent from the client to the server.
\r
4465 * It is sent once when the client decides to shutdown the
\r
4466 * server. The only notification that is sent after a shutdown request
\r
4467 * is the exit event.
\r
4469 var ShutdownRequest;
\r
4470 (function (ShutdownRequest) {
\r
4471 ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown');
\r
4472 })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
\r
4473 //---- Exit Notification ----
\r
4475 * The exit event is sent from the client to the server to
\r
4476 * ask the server to exit its process.
\r
4478 var ExitNotification;
\r
4479 (function (ExitNotification) {
\r
4480 ExitNotification.type = new messages_1.ProtocolNotificationType0('exit');
\r
4481 })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
\r
4483 * The configuration change notification is sent from the client to the server
\r
4484 * when the client's configuration has changed. The notification contains
\r
4485 * the changed configuration as defined by the language client.
\r
4487 var DidChangeConfigurationNotification;
\r
4488 (function (DidChangeConfigurationNotification) {
\r
4489 DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration');
\r
4490 })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
\r
4491 //---- Message show and log notifications ----
\r
4493 * The message type
\r
4496 (function (MessageType) {
\r
4498 * An error message.
\r
4500 MessageType.Error = 1;
\r
4502 * A warning message.
\r
4504 MessageType.Warning = 2;
\r
4506 * An information message.
\r
4508 MessageType.Info = 3;
\r
4512 MessageType.Log = 4;
\r
4513 })(MessageType = exports.MessageType || (exports.MessageType = {}));
\r
4515 * The show message notification is sent from a server to a client to ask
\r
4516 * the client to display a particular message in the user interface.
\r
4518 var ShowMessageNotification;
\r
4519 (function (ShowMessageNotification) {
\r
4520 ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage');
\r
4521 })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
\r
4523 * The show message request is sent from the server to the client to show a message
\r
4524 * and a set of options actions to the user.
\r
4526 var ShowMessageRequest;
\r
4527 (function (ShowMessageRequest) {
\r
4528 ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest');
\r
4529 })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
\r
4531 * The log message notification is sent from the server to the client to ask
\r
4532 * the client to log a particular message.
\r
4534 var LogMessageNotification;
\r
4535 (function (LogMessageNotification) {
\r
4536 LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage');
\r
4537 })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
\r
4538 //---- Telemetry notification
\r
4540 * The telemetry event notification is sent from the server to the client to ask
\r
4541 * the client to log telemetry data.
\r
4543 var TelemetryEventNotification;
\r
4544 (function (TelemetryEventNotification) {
\r
4545 TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event');
\r
4546 })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
\r
4548 * Defines how the host (editor) should sync
\r
4549 * document changes to the language server.
\r
4551 var TextDocumentSyncKind;
\r
4552 (function (TextDocumentSyncKind) {
\r
4554 * Documents should not be synced at all.
\r
4556 TextDocumentSyncKind.None = 0;
\r
4558 * Documents are synced by always sending the full content
\r
4559 * of the document.
\r
4561 TextDocumentSyncKind.Full = 1;
\r
4563 * Documents are synced by sending the full content on open.
\r
4564 * After that only incremental updates to the document are
\r
4567 TextDocumentSyncKind.Incremental = 2;
\r
4568 })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
\r
4570 * The document open notification is sent from the client to the server to signal
\r
4571 * newly opened text documents. The document's truth is now managed by the client
\r
4572 * and the server must not try to read the document's truth using the document's
\r
4573 * uri. Open in this sense means it is managed by the client. It doesn't necessarily
\r
4574 * mean that its content is presented in an editor. An open notification must not
\r
4575 * be sent more than once without a corresponding close notification send before.
\r
4576 * This means open and close notification must be balanced and the max open count
\r
4579 var DidOpenTextDocumentNotification;
\r
4580 (function (DidOpenTextDocumentNotification) {
\r
4581 DidOpenTextDocumentNotification.method = 'textDocument/didOpen';
\r
4582 DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);
\r
4583 })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
\r
4585 * The document change notification is sent from the client to the server to signal
\r
4586 * changes to a text document.
\r
4588 var DidChangeTextDocumentNotification;
\r
4589 (function (DidChangeTextDocumentNotification) {
\r
4590 DidChangeTextDocumentNotification.method = 'textDocument/didChange';
\r
4591 DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);
\r
4592 })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
\r
4594 * The document close notification is sent from the client to the server when
\r
4595 * the document got closed in the client. The document's truth now exists where
\r
4596 * the document's uri points to (e.g. if the document's uri is a file uri the
\r
4597 * truth now exists on disk). As with the open notification the close notification
\r
4598 * is about managing the document's content. Receiving a close notification
\r
4599 * doesn't mean that the document was open in an editor before. A close
\r
4600 * notification requires a previous open notification to be sent.
\r
4602 var DidCloseTextDocumentNotification;
\r
4603 (function (DidCloseTextDocumentNotification) {
\r
4604 DidCloseTextDocumentNotification.method = 'textDocument/didClose';
\r
4605 DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);
\r
4606 })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
\r
4608 * The document save notification is sent from the client to the server when
\r
4609 * the document got saved in the client.
\r
4611 var DidSaveTextDocumentNotification;
\r
4612 (function (DidSaveTextDocumentNotification) {
\r
4613 DidSaveTextDocumentNotification.method = 'textDocument/didSave';
\r
4614 DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);
\r
4615 })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
\r
4617 * Represents reasons why a text document is saved.
\r
4619 var TextDocumentSaveReason;
\r
4620 (function (TextDocumentSaveReason) {
\r
4622 * Manually triggered, e.g. by the user pressing save, by starting debugging,
\r
4623 * or by an API call.
\r
4625 TextDocumentSaveReason.Manual = 1;
\r
4627 * Automatic after a delay.
\r
4629 TextDocumentSaveReason.AfterDelay = 2;
\r
4631 * When the editor lost focus.
\r
4633 TextDocumentSaveReason.FocusOut = 3;
\r
4634 })(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));
\r
4636 * A document will save notification is sent from the client to the server before
\r
4637 * the document is actually saved.
\r
4639 var WillSaveTextDocumentNotification;
\r
4640 (function (WillSaveTextDocumentNotification) {
\r
4641 WillSaveTextDocumentNotification.method = 'textDocument/willSave';
\r
4642 WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);
\r
4643 })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
\r
4645 * A document will save request is sent from the client to the server before
\r
4646 * the document is actually saved. The request can return an array of TextEdits
\r
4647 * which will be applied to the text document before it is saved. Please note that
\r
4648 * clients might drop results if computing the text edits took too long or if a
\r
4649 * server constantly fails on this request. This is done to keep the save fast and
\r
4652 var WillSaveTextDocumentWaitUntilRequest;
\r
4653 (function (WillSaveTextDocumentWaitUntilRequest) {
\r
4654 WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';
\r
4655 WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);
\r
4656 })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
\r
4658 * The watched files notification is sent from the client to the server when
\r
4659 * the client detects changes to file watched by the language client.
\r
4661 var DidChangeWatchedFilesNotification;
\r
4662 (function (DidChangeWatchedFilesNotification) {
\r
4663 DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles');
\r
4664 })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
\r
4666 * The file event type
\r
4668 var FileChangeType;
\r
4669 (function (FileChangeType) {
\r
4671 * The file got created.
\r
4673 FileChangeType.Created = 1;
\r
4675 * The file got changed.
\r
4677 FileChangeType.Changed = 2;
\r
4679 * The file got deleted.
\r
4681 FileChangeType.Deleted = 3;
\r
4682 })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
\r
4684 (function (WatchKind) {
\r
4686 * Interested in create events.
\r
4688 WatchKind.Create = 1;
\r
4690 * Interested in change events
\r
4692 WatchKind.Change = 2;
\r
4694 * Interested in delete events
\r
4696 WatchKind.Delete = 4;
\r
4697 })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
\r
4699 * Diagnostics notification are sent from the server to the client to signal
\r
4700 * results of validation runs.
\r
4702 var PublishDiagnosticsNotification;
\r
4703 (function (PublishDiagnosticsNotification) {
\r
4704 PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics');
\r
4705 })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
\r
4707 * How a completion was triggered
\r
4709 var CompletionTriggerKind;
\r
4710 (function (CompletionTriggerKind) {
\r
4712 * Completion was triggered by typing an identifier (24x7 code
\r
4713 * complete), manual invocation (e.g Ctrl+Space) or via API.
\r
4715 CompletionTriggerKind.Invoked = 1;
\r
4717 * Completion was triggered by a trigger character specified by
\r
4718 * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
\r
4720 CompletionTriggerKind.TriggerCharacter = 2;
\r
4722 * Completion was re-triggered as current completion list is incomplete
\r
4724 CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
\r
4725 })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
\r
4727 * Request to request completion at a given text document position. The request's
\r
4728 * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response
\r
4729 * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)
\r
4730 * or a Thenable that resolves to such.
\r
4732 * The request can delay the computation of the [`detail`](#CompletionItem.detail)
\r
4733 * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`
\r
4734 * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
\r
4735 * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
\r
4737 var CompletionRequest;
\r
4738 (function (CompletionRequest) {
\r
4739 CompletionRequest.method = 'textDocument/completion';
\r
4740 CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);
\r
4741 /** @deprecated Use CompletionRequest.type */
\r
4742 CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4743 })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
\r
4745 * Request to resolve additional information for a given completion item.The request's
\r
4746 * parameter is of type [CompletionItem](#CompletionItem) the response
\r
4747 * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.
\r
4749 var CompletionResolveRequest;
\r
4750 (function (CompletionResolveRequest) {
\r
4751 CompletionResolveRequest.method = 'completionItem/resolve';
\r
4752 CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);
\r
4753 })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
\r
4755 * Request to request hover information at a given text document position. The request's
\r
4756 * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of
\r
4757 * type [Hover](#Hover) or a Thenable that resolves to such.
\r
4760 (function (HoverRequest) {
\r
4761 HoverRequest.method = 'textDocument/hover';
\r
4762 HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);
\r
4763 })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
\r
4765 * How a signature help was triggered.
\r
4769 var SignatureHelpTriggerKind;
\r
4770 (function (SignatureHelpTriggerKind) {
\r
4772 * Signature help was invoked manually by the user or by a command.
\r
4774 SignatureHelpTriggerKind.Invoked = 1;
\r
4776 * Signature help was triggered by a trigger character.
\r
4778 SignatureHelpTriggerKind.TriggerCharacter = 2;
\r
4780 * Signature help was triggered by the cursor moving or by the document content changing.
\r
4782 SignatureHelpTriggerKind.ContentChange = 3;
\r
4783 })(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));
\r
4784 var SignatureHelpRequest;
\r
4785 (function (SignatureHelpRequest) {
\r
4786 SignatureHelpRequest.method = 'textDocument/signatureHelp';
\r
4787 SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);
\r
4788 })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
\r
4790 * A request to resolve the definition location of a symbol at a given text
\r
4791 * document position. The request's parameter is of type [TextDocumentPosition]
\r
4792 * (#TextDocumentPosition) the response is of either type [Definition](#Definition)
\r
4793 * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves
\r
4796 var DefinitionRequest;
\r
4797 (function (DefinitionRequest) {
\r
4798 DefinitionRequest.method = 'textDocument/definition';
\r
4799 DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);
\r
4800 /** @deprecated Use DefinitionRequest.type */
\r
4801 DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4802 })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
\r
4804 * A request to resolve project-wide references for the symbol denoted
\r
4805 * by the given text document position. The request's parameter is of
\r
4806 * type [ReferenceParams](#ReferenceParams) the response is of type
\r
4807 * [Location[]](#Location) or a Thenable that resolves to such.
\r
4809 var ReferencesRequest;
\r
4810 (function (ReferencesRequest) {
\r
4811 ReferencesRequest.method = 'textDocument/references';
\r
4812 ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);
\r
4813 /** @deprecated Use ReferencesRequest.type */
\r
4814 ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4815 })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
\r
4817 * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given
\r
4818 * text document position. The request's parameter is of type [TextDocumentPosition]
\r
4819 * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
\r
4820 * (#DocumentHighlight) or a Thenable that resolves to such.
\r
4822 var DocumentHighlightRequest;
\r
4823 (function (DocumentHighlightRequest) {
\r
4824 DocumentHighlightRequest.method = 'textDocument/documentHighlight';
\r
4825 DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);
\r
4826 /** @deprecated Use DocumentHighlightRequest.type */
\r
4827 DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4828 })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
\r
4830 * A request to list all symbols found in a given text document. The request's
\r
4831 * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the
\r
4832 * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable
\r
4833 * that resolves to such.
\r
4835 var DocumentSymbolRequest;
\r
4836 (function (DocumentSymbolRequest) {
\r
4837 DocumentSymbolRequest.method = 'textDocument/documentSymbol';
\r
4838 DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);
\r
4839 /** @deprecated Use DocumentSymbolRequest.type */
\r
4840 DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4841 })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
\r
4843 * A request to provide commands for the given text document and range.
\r
4845 var CodeActionRequest;
\r
4846 (function (CodeActionRequest) {
\r
4847 CodeActionRequest.method = 'textDocument/codeAction';
\r
4848 CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);
\r
4849 /** @deprecated Use CodeActionRequest.type */
\r
4850 CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4851 })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
\r
4853 * A request to list project-wide symbols matching the query string given
\r
4854 * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is
\r
4855 * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that
\r
4856 * resolves to such.
\r
4858 var WorkspaceSymbolRequest;
\r
4859 (function (WorkspaceSymbolRequest) {
\r
4860 WorkspaceSymbolRequest.method = 'workspace/symbol';
\r
4861 WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);
\r
4862 /** @deprecated Use WorkspaceSymbolRequest.type */
\r
4863 WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4864 })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
\r
4866 * A request to provide code lens for the given text document.
\r
4868 var CodeLensRequest;
\r
4869 (function (CodeLensRequest) {
\r
4870 CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens');
\r
4871 /** @deprecated Use CodeLensRequest.type */
\r
4872 CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4873 })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
\r
4875 * A request to resolve a command for a given code lens.
\r
4877 var CodeLensResolveRequest;
\r
4878 (function (CodeLensResolveRequest) {
\r
4879 CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve');
\r
4880 })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
\r
4882 * A request to provide document links
\r
4884 var DocumentLinkRequest;
\r
4885 (function (DocumentLinkRequest) {
\r
4886 DocumentLinkRequest.method = 'textDocument/documentLink';
\r
4887 DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);
\r
4888 /** @deprecated Use DocumentLinkRequest.type */
\r
4889 DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4890 })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
\r
4892 * Request to resolve additional information for a given document link. The request's
\r
4893 * parameter is of type [DocumentLink](#DocumentLink) the response
\r
4894 * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.
\r
4896 var DocumentLinkResolveRequest;
\r
4897 (function (DocumentLinkResolveRequest) {
\r
4898 DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve');
\r
4899 })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
\r
4901 * A request to to format a whole document.
\r
4903 var DocumentFormattingRequest;
\r
4904 (function (DocumentFormattingRequest) {
\r
4905 DocumentFormattingRequest.method = 'textDocument/formatting';
\r
4906 DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);
\r
4907 })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
\r
4909 * A request to to format a range in a document.
\r
4911 var DocumentRangeFormattingRequest;
\r
4912 (function (DocumentRangeFormattingRequest) {
\r
4913 DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';
\r
4914 DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);
\r
4915 })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
\r
4917 * A request to format a document on type.
\r
4919 var DocumentOnTypeFormattingRequest;
\r
4920 (function (DocumentOnTypeFormattingRequest) {
\r
4921 DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';
\r
4922 DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);
\r
4923 })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
\r
4925 * A request to rename a symbol.
\r
4927 var RenameRequest;
\r
4928 (function (RenameRequest) {
\r
4929 RenameRequest.method = 'textDocument/rename';
\r
4930 RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);
\r
4931 })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
\r
4933 * A request to test and perform the setup necessary for a rename.
\r
4935 var PrepareRenameRequest;
\r
4936 (function (PrepareRenameRequest) {
\r
4937 PrepareRenameRequest.method = 'textDocument/prepareRename';
\r
4938 PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);
\r
4939 })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
\r
4941 * A request send from the client to the server to execute a command. The request might return
\r
4942 * a workspace edit which the client will apply to the workspace.
\r
4944 var ExecuteCommandRequest;
\r
4945 (function (ExecuteCommandRequest) {
\r
4946 ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand');
\r
4947 })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
\r
4949 * A request sent from the server to the client to modified certain resources.
\r
4951 var ApplyWorkspaceEditRequest;
\r
4952 (function (ApplyWorkspaceEditRequest) {
\r
4953 ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');
\r
4954 })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
\r
4959 /***/ (function(module, exports, __webpack_require__) {
4962 /* --------------------------------------------------------------------------------------------
\r
4963 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4964 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4965 * ------------------------------------------------------------------------------------------ */
\r
4967 Object.defineProperty(exports, "__esModule", { value: true });
\r
4968 function boolean(value) {
\r
4969 return value === true || value === false;
\r
4971 exports.boolean = boolean;
\r
4972 function string(value) {
\r
4973 return typeof value === 'string' || value instanceof String;
\r
4975 exports.string = string;
\r
4976 function number(value) {
\r
4977 return typeof value === 'number' || value instanceof Number;
\r
4979 exports.number = number;
\r
4980 function error(value) {
\r
4981 return value instanceof Error;
\r
4983 exports.error = error;
\r
4984 function func(value) {
\r
4985 return typeof value === 'function';
\r
4987 exports.func = func;
\r
4988 function array(value) {
\r
4989 return Array.isArray(value);
\r
4991 exports.array = array;
\r
4992 function stringArray(value) {
\r
4993 return array(value) && value.every(elem => string(elem));
\r
4995 exports.stringArray = stringArray;
\r
4996 function typedArray(value, check) {
\r
4997 return Array.isArray(value) && value.every(check);
\r
4999 exports.typedArray = typedArray;
\r
5000 function objectLiteral(value) {
\r
5001 // Strictly speaking class instances pass this check as well. Since the LSP
\r
5002 // doesn't use classes we ignore this for now. If we do we need to add something
\r
5003 // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
\r
5004 return value !== null && typeof value === 'object';
\r
5006 exports.objectLiteral = objectLiteral;
\r
5011 /***/ (function(module, exports, __webpack_require__) {
5014 /* --------------------------------------------------------------------------------------------
\r
5015 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5016 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5017 * ------------------------------------------------------------------------------------------ */
\r
5019 Object.defineProperty(exports, "__esModule", { value: true });
\r
5020 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5021 class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
\r
5022 constructor(method) {
\r
5026 exports.ProtocolRequestType0 = ProtocolRequestType0;
\r
5027 class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
\r
5028 constructor(method) {
\r
5032 exports.ProtocolRequestType = ProtocolRequestType;
\r
5033 class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
\r
5034 constructor(method) {
\r
5038 exports.ProtocolNotificationType = ProtocolNotificationType;
\r
5039 class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
\r
5040 constructor(method) {
\r
5044 exports.ProtocolNotificationType0 = ProtocolNotificationType0;
\r
5049 /***/ (function(module, exports, __webpack_require__) {
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
5057 Object.defineProperty(exports, "__esModule", { value: true });
\r
5058 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5059 const messages_1 = __webpack_require__(21);
\r
5060 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
5061 let __noDynamicImport;
\r
5063 * A request to resolve the implementation locations of a symbol at a given text
\r
5064 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
5065 * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
\r
5066 * Thenable that resolves to such.
\r
5068 var ImplementationRequest;
\r
5069 (function (ImplementationRequest) {
\r
5070 ImplementationRequest.method = 'textDocument/implementation';
\r
5071 ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);
\r
5072 /** @deprecated Use ImplementationRequest.type */
\r
5073 ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5074 })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
\r
5079 /***/ (function(module, exports, __webpack_require__) {
5082 /* --------------------------------------------------------------------------------------------
\r
5083 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5084 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5085 * ------------------------------------------------------------------------------------------ */
\r
5087 Object.defineProperty(exports, "__esModule", { value: true });
\r
5088 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5089 const messages_1 = __webpack_require__(21);
\r
5090 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
5091 let __noDynamicImport;
\r
5093 * A request to resolve the type definition locations of a symbol at a given text
\r
5094 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
5095 * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
\r
5096 * Thenable that resolves to such.
\r
5098 var TypeDefinitionRequest;
\r
5099 (function (TypeDefinitionRequest) {
\r
5100 TypeDefinitionRequest.method = 'textDocument/typeDefinition';
\r
5101 TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);
\r
5102 /** @deprecated Use TypeDefinitionRequest.type */
\r
5103 TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5104 })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
\r
5109 /***/ (function(module, exports, __webpack_require__) {
5112 /* --------------------------------------------------------------------------------------------
\r
5113 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5114 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5115 * ------------------------------------------------------------------------------------------ */
\r
5117 Object.defineProperty(exports, "__esModule", { value: true });
\r
5118 const messages_1 = __webpack_require__(21);
\r
5120 * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
\r
5122 var WorkspaceFoldersRequest;
\r
5123 (function (WorkspaceFoldersRequest) {
\r
5124 WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders');
\r
5125 })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
\r
5127 * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
\r
5128 * folder configuration changes.
\r
5130 var DidChangeWorkspaceFoldersNotification;
\r
5131 (function (DidChangeWorkspaceFoldersNotification) {
\r
5132 DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders');
\r
5133 })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
\r
5138 /***/ (function(module, exports, __webpack_require__) {
5141 /* --------------------------------------------------------------------------------------------
\r
5142 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5143 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5144 * ------------------------------------------------------------------------------------------ */
\r
5146 Object.defineProperty(exports, "__esModule", { value: true });
\r
5147 const messages_1 = __webpack_require__(21);
\r
5149 * The 'workspace/configuration' request is sent from the server to the client to fetch a certain
\r
5150 * configuration setting.
\r
5152 * This pull model replaces the old push model were the client signaled configuration change via an
\r
5153 * event. If the server still needs to react to configuration changes (since the server caches the
\r
5154 * result of `workspace/configuration` requests) the server should register for an empty configuration
\r
5155 * change event and empty the cache if such an event is received.
\r
5157 var ConfigurationRequest;
\r
5158 (function (ConfigurationRequest) {
\r
5159 ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration');
\r
5160 })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
\r
5165 /***/ (function(module, exports, __webpack_require__) {
5168 /* --------------------------------------------------------------------------------------------
\r
5169 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5170 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5171 * ------------------------------------------------------------------------------------------ */
\r
5173 Object.defineProperty(exports, "__esModule", { value: true });
\r
5174 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5175 const messages_1 = __webpack_require__(21);
\r
5177 * A request to list all color symbols found in a given text document. The request's
\r
5178 * parameter is of type [DocumentColorParams](#DocumentColorParams) the
\r
5179 * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
\r
5180 * that resolves to such.
\r
5182 var DocumentColorRequest;
\r
5183 (function (DocumentColorRequest) {
\r
5184 DocumentColorRequest.method = 'textDocument/documentColor';
\r
5185 DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);
\r
5186 /** @deprecated Use DocumentColorRequest.type */
\r
5187 DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5188 })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
\r
5190 * A request to list all presentation for a color. The request's
\r
5191 * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the
\r
5192 * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
\r
5193 * that resolves to such.
\r
5195 var ColorPresentationRequest;
\r
5196 (function (ColorPresentationRequest) {
\r
5197 ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation');
\r
5198 })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
\r
5203 /***/ (function(module, exports, __webpack_require__) {
5207 /*---------------------------------------------------------------------------------------------
\r
5208 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5209 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5210 *--------------------------------------------------------------------------------------------*/
\r
5211 Object.defineProperty(exports, "__esModule", { value: true });
\r
5212 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5213 const messages_1 = __webpack_require__(21);
\r
5215 * Enum of known range kinds
\r
5217 var FoldingRangeKind;
\r
5218 (function (FoldingRangeKind) {
\r
5220 * Folding range for a comment
\r
5222 FoldingRangeKind["Comment"] = "comment";
\r
5224 * Folding range for a imports or includes
\r
5226 FoldingRangeKind["Imports"] = "imports";
\r
5228 * Folding range for a region (e.g. `#region`)
\r
5230 FoldingRangeKind["Region"] = "region";
\r
5231 })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
\r
5233 * A request to provide folding ranges in a document. The request's
\r
5234 * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the
\r
5235 * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable
\r
5236 * that resolves to such.
\r
5238 var FoldingRangeRequest;
\r
5239 (function (FoldingRangeRequest) {
\r
5240 FoldingRangeRequest.method = 'textDocument/foldingRange';
\r
5241 FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);
\r
5242 /** @deprecated Use FoldingRangeRequest.type */
\r
5243 FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5244 })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
\r
5249 /***/ (function(module, exports, __webpack_require__) {
5252 /* --------------------------------------------------------------------------------------------
\r
5253 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5254 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5255 * ------------------------------------------------------------------------------------------ */
\r
5257 Object.defineProperty(exports, "__esModule", { value: true });
\r
5258 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5259 const messages_1 = __webpack_require__(21);
\r
5260 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
5261 let __noDynamicImport;
\r
5263 * A request to resolve the type definition locations of a symbol at a given text
\r
5264 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
5265 * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)
\r
5266 * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves
\r
5269 var DeclarationRequest;
\r
5270 (function (DeclarationRequest) {
\r
5271 DeclarationRequest.method = 'textDocument/declaration';
\r
5272 DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);
\r
5273 /** @deprecated Use DeclarationRequest.type */
\r
5274 DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5275 })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
\r
5280 /***/ (function(module, exports, __webpack_require__) {
5284 /*---------------------------------------------------------------------------------------------
\r
5285 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5286 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5287 *--------------------------------------------------------------------------------------------*/
\r
5288 Object.defineProperty(exports, "__esModule", { value: true });
\r
5289 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5290 const messages_1 = __webpack_require__(21);
\r
5292 * A request to provide selection ranges in a document. The request's
\r
5293 * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the
\r
5294 * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable
\r
5295 * that resolves to such.
\r
5297 var SelectionRangeRequest;
\r
5298 (function (SelectionRangeRequest) {
\r
5299 SelectionRangeRequest.method = 'textDocument/selectionRange';
\r
5300 SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);
\r
5301 /** @deprecated Use SelectionRangeRequest.type */
\r
5302 SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5303 })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
\r
5308 /***/ (function(module, exports, __webpack_require__) {
5311 /* --------------------------------------------------------------------------------------------
\r
5312 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5313 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5314 * ------------------------------------------------------------------------------------------ */
\r
5316 Object.defineProperty(exports, "__esModule", { value: true });
\r
5317 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5318 const messages_1 = __webpack_require__(21);
\r
5319 var WorkDoneProgress;
\r
5320 (function (WorkDoneProgress) {
\r
5321 WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();
\r
5322 })(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));
\r
5324 * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
\r
5325 * reporting from the server.
\r
5327 var WorkDoneProgressCreateRequest;
\r
5328 (function (WorkDoneProgressCreateRequest) {
\r
5329 WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create');
\r
5330 })(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));
\r
5332 * The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress
\r
5333 * initiated on the server side.
\r
5335 var WorkDoneProgressCancelNotification;
\r
5336 (function (WorkDoneProgressCancelNotification) {
\r
5337 WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel');
\r
5338 })(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));
\r
5343 /***/ (function(module, exports, __webpack_require__) {
5346 /* --------------------------------------------------------------------------------------------
\r
5347 * Copyright (c) TypeFox and others. All rights reserved.
\r
5348 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5349 * ------------------------------------------------------------------------------------------ */
\r
5351 Object.defineProperty(exports, "__esModule", { value: true });
\r
5352 const messages_1 = __webpack_require__(21);
\r
5354 * A request to result a `CallHierarchyItem` in a document at a given position.
\r
5355 * Can be used as an input to a incoming or outgoing call hierarchy.
\r
5357 * @since 3.16.0 - Proposed state
\r
5359 var CallHierarchyPrepareRequest;
\r
5360 (function (CallHierarchyPrepareRequest) {
\r
5361 CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';
\r
5362 CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);
\r
5363 })(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));
\r
5365 * A request to resolve the incoming calls for a given `CallHierarchyItem`.
\r
5367 * @since 3.16.0 - Proposed state
\r
5369 var CallHierarchyIncomingCallsRequest;
\r
5370 (function (CallHierarchyIncomingCallsRequest) {
\r
5371 CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';
\r
5372 CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);
\r
5373 })(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));
\r
5375 * A request to resolve the outgoing calls for a given `CallHierarchyItem`.
\r
5377 * @since 3.16.0 - Proposed state
\r
5379 var CallHierarchyOutgoingCallsRequest;
\r
5380 (function (CallHierarchyOutgoingCallsRequest) {
\r
5381 CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';
\r
5382 CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);
\r
5383 })(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));
\r
5388 /***/ (function(module, exports, __webpack_require__) {
5391 /* --------------------------------------------------------------------------------------------
\r
5392 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5393 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5394 * ------------------------------------------------------------------------------------------ */
\r
5396 Object.defineProperty(exports, "__esModule", { value: true });
\r
5397 const messages_1 = __webpack_require__(21);
\r
5399 * A set of predefined token types. This set is not fixed
\r
5400 * an clients can specify additional token types via the
\r
5401 * corresponding client capabilities.
\r
5403 * @since 3.16.0 - Proposed state
\r
5405 var SemanticTokenTypes;
\r
5406 (function (SemanticTokenTypes) {
\r
5407 SemanticTokenTypes["comment"] = "comment";
\r
5408 SemanticTokenTypes["keyword"] = "keyword";
\r
5409 SemanticTokenTypes["string"] = "string";
\r
5410 SemanticTokenTypes["number"] = "number";
\r
5411 SemanticTokenTypes["regexp"] = "regexp";
\r
5412 SemanticTokenTypes["operator"] = "operator";
\r
5413 SemanticTokenTypes["namespace"] = "namespace";
\r
5414 SemanticTokenTypes["type"] = "type";
\r
5415 SemanticTokenTypes["struct"] = "struct";
\r
5416 SemanticTokenTypes["class"] = "class";
\r
5417 SemanticTokenTypes["interface"] = "interface";
\r
5418 SemanticTokenTypes["enum"] = "enum";
\r
5419 SemanticTokenTypes["typeParameter"] = "typeParameter";
\r
5420 SemanticTokenTypes["function"] = "function";
\r
5421 SemanticTokenTypes["member"] = "member";
\r
5422 SemanticTokenTypes["property"] = "property";
\r
5423 SemanticTokenTypes["macro"] = "macro";
\r
5424 SemanticTokenTypes["variable"] = "variable";
\r
5425 SemanticTokenTypes["parameter"] = "parameter";
\r
5426 SemanticTokenTypes["label"] = "label";
\r
5427 })(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {}));
\r
5429 * A set of predefined token modifiers. This set is not fixed
\r
5430 * an clients can specify additional token types via the
\r
5431 * corresponding client capabilities.
\r
5433 * @since 3.16.0 - Proposed state
\r
5435 var SemanticTokenModifiers;
\r
5436 (function (SemanticTokenModifiers) {
\r
5437 SemanticTokenModifiers["documentation"] = "documentation";
\r
5438 SemanticTokenModifiers["declaration"] = "declaration";
\r
5439 SemanticTokenModifiers["definition"] = "definition";
\r
5440 SemanticTokenModifiers["reference"] = "reference";
\r
5441 SemanticTokenModifiers["static"] = "static";
\r
5442 SemanticTokenModifiers["abstract"] = "abstract";
\r
5443 SemanticTokenModifiers["deprecated"] = "deprecated";
\r
5444 SemanticTokenModifiers["async"] = "async";
\r
5445 SemanticTokenModifiers["volatile"] = "volatile";
\r
5446 SemanticTokenModifiers["readonly"] = "readonly";
\r
5447 })(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {}));
\r
5449 * @since 3.16.0 - Proposed state
\r
5451 var SemanticTokens;
\r
5452 (function (SemanticTokens) {
\r
5453 function is(value) {
\r
5454 const candidate = value;
\r
5455 return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&
\r
5456 Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');
\r
5458 SemanticTokens.is = is;
\r
5459 })(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {}));
\r
5461 * @since 3.16.0 - Proposed state
\r
5463 var SemanticTokensRequest;
\r
5464 (function (SemanticTokensRequest) {
\r
5465 SemanticTokensRequest.method = 'textDocument/semanticTokens';
\r
5466 SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);
\r
5467 })(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));
\r
5469 * @since 3.16.0 - Proposed state
\r
5471 var SemanticTokensEditsRequest;
\r
5472 (function (SemanticTokensEditsRequest) {
\r
5473 SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits';
\r
5474 SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method);
\r
5475 })(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {}));
\r
5477 * @since 3.16.0 - Proposed state
\r
5479 var SemanticTokensRangeRequest;
\r
5480 (function (SemanticTokensRangeRequest) {
\r
5481 SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';
\r
5482 SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);
\r
5483 })(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));
\r
5488 /***/ (function(module, exports, __webpack_require__) {
5492 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5493 if (k2 === undefined) k2 = k;
5494 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5495 }) : (function(o, m, k, k2) {
5496 if (k2 === undefined) k2 = k;
5499 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
5500 Object.defineProperty(o, "default", { enumerable: true, value: v });
5501 }) : function(o, v) {
5504 var __importStar = (this && this.__importStar) || function (mod) {
5505 if (mod && mod.__esModule) return mod;
5507 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
5508 __setModuleDefault(result, mod);
5511 var __importDefault = (this && this.__importDefault) || function (mod) {
5512 return (mod && mod.__esModule) ? mod : { "default": mod };
5514 Object.defineProperty(exports, "__esModule", { value: true });
5515 /*---------------------------------------------------------------------------------------------
5516 * Copyright (c) Microsoft Corporation. All rights reserved.
5517 * Licensed under the MIT License. See License.txt in the project root for license information.
5518 *--------------------------------------------------------------------------------------------*/
5519 const coc_nvim_1 = __webpack_require__(1);
5520 const vscode_languageserver_protocol_1 = __webpack_require__(3);
5521 const languageProvider_1 = __importDefault(__webpack_require__(34));
5522 const PConst = __importStar(__webpack_require__(39));
5523 const fileConfigurationManager_1 = __importDefault(__webpack_require__(113));
5524 const typescriptServiceClient_1 = __importDefault(__webpack_require__(114));
5525 const typeConverters = __importStar(__webpack_require__(37));
5526 const typingsStatus_1 = __importStar(__webpack_require__(137));
5527 const arrays_1 = __webpack_require__(91);
5528 const watchBuild_1 = __importDefault(__webpack_require__(138));
5529 const workspaceSymbols_1 = __importDefault(__webpack_require__(139));
5530 // Style check diagnostics that can be reported as warnings
5531 const styleCheckDiagnostics = [
5537 7030 // not all code paths return a value
5539 class TypeScriptServiceClientHost {
5540 constructor(descriptions, pluginManager) {
5541 this.languagePerId = new Map();
5542 this.disposables = [];
5543 this.reportStyleCheckAsWarnings = true;
5545 const handleProjectChange = () => {
5547 clearTimeout(timer);
5548 timer = setTimeout(() => {
5549 this.triggerAllDiagnostics();
5552 const configFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/[tj]sconfig.json');
5553 this.disposables.push(configFileWatcher);
5554 configFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
5555 configFileWatcher.onDidDelete(this.reloadProjects, this, this.disposables);
5556 configFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
5557 const packageFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/package.json');
5558 packageFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
5559 packageFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
5560 const allModeIds = this.getAllModeIds(descriptions, pluginManager);
5561 this.client = new typescriptServiceClient_1.default(pluginManager, allModeIds);
5562 this.disposables.push(this.client);
5563 this.client.onDiagnosticsReceived(({ kind, resource, diagnostics }) => {
5564 this.diagnosticsReceived(kind, resource, diagnostics).catch(e => {
5567 }, null, this.disposables);
5569 this.disposables.push(new watchBuild_1.default(this.client));
5570 this.disposables.push(coc_nvim_1.languages.registerWorkspaceSymbolProvider(new workspaceSymbols_1.default(this.client, allModeIds)));
5571 this.client.onConfigDiagnosticsReceived(diag => {
5572 let { body } = diag;
5574 let { configFile, diagnostics } = body;
5575 let uri = coc_nvim_1.Uri.file(configFile);
5576 if (diagnostics.length == 0) {
5577 this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), []);
5580 let diagnosticList = diagnostics.map(o => {
5581 let { text, code, category, start, end } = o;
5583 if (!start || !end) {
5584 range = vscode_languageserver_protocol_1.Range.create(vscode_languageserver_protocol_1.Position.create(0, 0), vscode_languageserver_protocol_1.Position.create(0, 1));
5587 range = vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1);
5589 let severity = category == 'error' ? vscode_languageserver_protocol_1.DiagnosticSeverity.Error : vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
5590 return vscode_languageserver_protocol_1.Diagnostic.create(range, text, severity, code);
5592 this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), diagnosticList);
5595 }, null, this.disposables);
5596 this.typingsStatus = new typingsStatus_1.default(this.client);
5597 this.ataProgressReporter = new typingsStatus_1.AtaProgressReporter(this.client);
5598 this.fileConfigurationManager = new fileConfigurationManager_1.default(this.client);
5599 for (const description of descriptions) { // tslint:disable-line
5600 const manager = new languageProvider_1.default(this.client, this.fileConfigurationManager, description, this.typingsStatus);
5601 this.languagePerId.set(description.id, manager);
5603 const languageIds = new Set();
5604 for (const plugin of pluginManager.plugins) {
5605 if (plugin.configNamespace && plugin.languages.length) {
5606 this.registerExtensionLanguageProvider({
5607 id: plugin.configNamespace,
5608 modeIds: Array.from(plugin.languages),
5609 diagnosticSource: 'ts-plugin',
5610 diagnosticLanguage: 1 /* TypeScript */,
5611 diagnosticOwner: 'typescript',
5616 for (const language of plugin.languages) {
5617 languageIds.add(language);
5621 if (languageIds.size) {
5622 this.registerExtensionLanguageProvider({
5623 id: 'typescript-plugins',
5624 modeIds: Array.from(languageIds.values()),
5625 diagnosticSource: 'ts-plugin',
5626 diagnosticLanguage: 1 /* TypeScript */,
5627 diagnosticOwner: 'typescript',
5631 this.client.ensureServiceStarted();
5632 this.client.onTsServerStarted(() => {
5633 this.triggerAllDiagnostics();
5635 coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
5636 this.configurationChanged();
5638 registerExtensionLanguageProvider(description) {
5639 const manager = new languageProvider_1.default(this.client, this.fileConfigurationManager, description, this.typingsStatus);
5640 this.languagePerId.set(description.id, manager);
5643 coc_nvim_1.disposeAll(this.disposables);
5644 for (let language of this.languagePerId.values()) {
5647 this.languagePerId.clear();
5648 this.fileConfigurationManager.dispose();
5649 this.typingsStatus.dispose();
5650 this.ataProgressReporter.dispose();
5653 this.fileConfigurationManager.reset();
5655 get serviceClient() {
5659 this.client.diagnosticsManager.reInitialize();
5660 this.client.execute('reloadProjects', null, vscode_languageserver_protocol_1.CancellationToken.None);
5661 this.triggerAllDiagnostics();
5663 // typescript or javascript
5664 getProvider(languageId) {
5665 return this.languagePerId.get(languageId);
5667 configurationChanged() {
5668 const config = coc_nvim_1.workspace.getConfiguration('tsserver');
5669 this.reportStyleCheckAsWarnings = config.get('reportStyleChecksAsWarnings', true);
5671 async findLanguage(uri) {
5673 let doc = await coc_nvim_1.workspace.loadFile(uri);
5676 let languages = Array.from(this.languagePerId.values());
5677 return languages.find(language => language.handles(uri, doc.textDocument));
5683 async handles(doc) {
5684 let languages = Array.from(this.languagePerId.values());
5685 let idx = languages.findIndex(language => language.handles(doc.uri, doc));
5688 return this.client.bufferSyncSupport.handles(doc.uri);
5690 triggerAllDiagnostics() {
5691 for (const language of this.languagePerId.values()) {
5692 language.triggerAllDiagnostics();
5695 async diagnosticsReceived(kind, resource, diagnostics) {
5696 const language = await this.findLanguage(resource.toString());
5698 language.diagnosticsReceived(kind, resource, this.createMarkerDatas(diagnostics));
5701 createMarkerDatas(diagnostics) {
5702 return diagnostics.map(tsDiag => this.tsDiagnosticToLspDiagnostic(tsDiag));
5704 tsDiagnosticToLspDiagnostic(diagnostic) {
5705 const { start, end, text } = diagnostic;
5707 start: typeConverters.Position.fromLocation(start),
5708 end: typeConverters.Position.fromLocation(end)
5710 let relatedInformation;
5711 if (diagnostic.relatedInformation) {
5712 relatedInformation = diagnostic.relatedInformation.map(o => {
5713 let { span, message } = o;
5715 location: typeConverters.Location.fromTextSpan(this.client.toResource(span.file), span),
5723 code: diagnostic.code ? diagnostic.code : null,
5724 severity: this.getDiagnosticSeverity(diagnostic),
5725 reportUnnecessary: diagnostic.reportsUnnecessary,
5726 source: diagnostic.source || 'tsserver',
5730 getDiagnosticSeverity(diagnostic) {
5731 if (this.reportStyleCheckAsWarnings &&
5732 this.isStyleCheckDiagnostic(diagnostic.code) &&
5733 diagnostic.category === PConst.DiagnosticCategory.error) {
5734 return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
5736 switch (diagnostic.category) {
5737 case PConst.DiagnosticCategory.error:
5738 return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
5739 case PConst.DiagnosticCategory.warning:
5740 return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
5741 case PConst.DiagnosticCategory.suggestion:
5742 return vscode_languageserver_protocol_1.DiagnosticSeverity.Information;
5744 return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
5747 isStyleCheckDiagnostic(code) {
5748 return code ? styleCheckDiagnostics.indexOf(code) !== -1 : false;
5750 getAllModeIds(descriptions, pluginManager) {
5751 const allModeIds = arrays_1.flatten([
5752 ...descriptions.map(x => x.modeIds),
5753 ...pluginManager.plugins.map(x => x.languages)
5758 exports.default = TypeScriptServiceClientHost;
5763 /***/ (function(module, exports, __webpack_require__) {
5767 var __importDefault = (this && this.__importDefault) || function (mod) {
5768 return (mod && mod.__esModule) ? mod : { "default": mod };
5770 Object.defineProperty(exports, "__esModule", { value: true });
5771 /*---------------------------------------------------------------------------------------------
5772 * Copyright (c) Microsoft Corporation. All rights reserved.
5773 * Licensed under the MIT License. See License.txt in the project root for license information.
5774 *--------------------------------------------------------------------------------------------*/
5775 const coc_nvim_1 = __webpack_require__(1);
5776 const path_1 = __importDefault(__webpack_require__(13));
5777 const vscode_languageserver_protocol_1 = __webpack_require__(3);
5778 const baseCodeLensProvider_1 = __webpack_require__(35);
5779 const completionItemProvider_1 = __importDefault(__webpack_require__(38));
5780 const definitionProvider_1 = __importDefault(__webpack_require__(88));
5781 const directiveCommentCompletions_1 = __importDefault(__webpack_require__(89));
5782 const documentHighlight_1 = __importDefault(__webpack_require__(90));
5783 const documentSymbol_1 = __importDefault(__webpack_require__(92));
5784 const folding_1 = __importDefault(__webpack_require__(93));
5785 const formatting_1 = __importDefault(__webpack_require__(94));
5786 const hover_1 = __importDefault(__webpack_require__(95));
5787 const implementationsCodeLens_1 = __importDefault(__webpack_require__(96));
5788 const importFix_1 = __importDefault(__webpack_require__(97));
5789 const moduleInstall_1 = __importDefault(__webpack_require__(99));
5790 // import TagCompletionProvider from './features/tagCompletion'
5791 const quickfix_1 = __importDefault(__webpack_require__(103));
5792 const refactor_1 = __importDefault(__webpack_require__(104));
5793 const references_1 = __importDefault(__webpack_require__(105));
5794 const referencesCodeLens_1 = __importDefault(__webpack_require__(106));
5795 const rename_1 = __importDefault(__webpack_require__(107));
5796 const signatureHelp_1 = __importDefault(__webpack_require__(108));
5797 const smartSelect_1 = __importDefault(__webpack_require__(109));
5798 const updatePathOnRename_1 = __importDefault(__webpack_require__(110));
5799 const organizeImports_1 = __webpack_require__(112);
5800 const api_1 = __importDefault(__webpack_require__(40));
5801 const suggestionSetting = 'suggestionActions.enabled';
5802 class LanguageProvider {
5803 constructor(client, fileConfigurationManager, description, typingsStatus) {
5804 this.client = client;
5805 this.fileConfigurationManager = fileConfigurationManager;
5806 this.description = description;
5807 this.typingsStatus = typingsStatus;
5808 this.disposables = [];
5809 coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
5810 this.configurationChanged();
5811 let initialized = false;
5812 client.onTsServerStarted(async () => {
5815 this.registerProviders(client, typingsStatus);
5819 configurationChanged() {
5820 const config = coc_nvim_1.workspace.getConfiguration(this.id, null);
5821 this.client.diagnosticsManager.setEnableSuggestions(this.id, config.get(suggestionSetting, true));
5824 coc_nvim_1.disposeAll(this.disposables);
5826 _register(disposable) {
5827 this.disposables.push(disposable);
5829 registerProviders(client, typingsStatus) {
5830 let languageIds = this.description.modeIds;
5831 let clientId = `tsserver-${this.description.id}`;
5832 this._register(coc_nvim_1.languages.registerCompletionItemProvider(clientId, 'TSC', languageIds, new completionItemProvider_1.default(client, typingsStatus, this.fileConfigurationManager, this.description.id), completionItemProvider_1.default.triggerCharacters));
5833 if (this.client.apiVersion.gte(api_1.default.v230)) {
5834 this._register(coc_nvim_1.languages.registerCompletionItemProvider(`${this.description.id}-directive`, 'TSC', languageIds, new directiveCommentCompletions_1.default(client), ['@']));
5836 let definitionProvider = new definitionProvider_1.default(client);
5837 this._register(coc_nvim_1.languages.registerDefinitionProvider(languageIds, definitionProvider));
5838 this._register(coc_nvim_1.languages.registerTypeDefinitionProvider(languageIds, definitionProvider));
5839 this._register(coc_nvim_1.languages.registerImplementationProvider(languageIds, definitionProvider));
5840 this._register(coc_nvim_1.languages.registerReferencesProvider(languageIds, new references_1.default(client)));
5841 this._register(coc_nvim_1.languages.registerHoverProvider(languageIds, new hover_1.default(client)));
5842 this._register(coc_nvim_1.languages.registerDocumentHighlightProvider(languageIds, new documentHighlight_1.default(this.client)));
5843 this._register(coc_nvim_1.languages.registerSignatureHelpProvider(languageIds, new signatureHelp_1.default(client), ['(', ',', '<', ')']));
5844 this._register(coc_nvim_1.languages.registerDocumentSymbolProvider(languageIds, new documentSymbol_1.default(client)));
5845 this._register(coc_nvim_1.languages.registerRenameProvider(languageIds, new rename_1.default(client, this.fileConfigurationManager)));
5846 let formatProvider = new formatting_1.default(client, this.fileConfigurationManager);
5847 this._register(coc_nvim_1.languages.registerDocumentFormatProvider(languageIds, formatProvider));
5848 this._register(coc_nvim_1.languages.registerDocumentRangeFormatProvider(languageIds, formatProvider));
5849 this._register(coc_nvim_1.languages.registerOnTypeFormattingEditProvider(languageIds, formatProvider, [';', '}', '\n', String.fromCharCode(27)]));
5850 this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new moduleInstall_1.default(client), 'tsserver'));
5851 let { fileConfigurationManager } = this;
5852 let conf = fileConfigurationManager.getLanguageConfiguration(this.id);
5853 if (['javascript', 'typescript'].includes(this.id)) {
5854 if (this.client.apiVersion.gte(api_1.default.v290) && conf.get('updateImportsOnFileMove.enable')) {
5855 this._register(new updatePathOnRename_1.default(client, this.fileConfigurationManager, this.id));
5858 if (this.client.apiVersion.gte(api_1.default.v280)) {
5859 this._register(coc_nvim_1.languages.registerFoldingRangeProvider(languageIds, new folding_1.default(this.client)));
5860 this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new organizeImports_1.OrganizeImportsCodeActionProvider(this.client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]));
5862 if (this.client.apiVersion.gte(api_1.default.v240)) {
5863 this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new refactor_1.default(client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.Refactor]));
5865 this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new quickfix_1.default(client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
5866 this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new importFix_1.default(this.client.bufferSyncSupport), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
5867 let cachedResponse = new baseCodeLensProvider_1.CachedNavTreeResponse();
5868 if (this.client.apiVersion.gte(api_1.default.v206) && conf.get('referencesCodeLens.enable')) {
5869 this._register(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new referencesCodeLens_1.default(client, cachedResponse)));
5871 if (this.client.apiVersion.gte(api_1.default.v220) && conf.get('implementationsCodeLens.enable')) {
5872 this._register(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new implementationsCodeLens_1.default(client, cachedResponse)));
5874 if (this.client.apiVersion.gte(api_1.default.v350)) {
5875 this._register(coc_nvim_1.languages.registerSelectionRangeProvider(languageIds, new smartSelect_1.default(this.client)));
5877 // if (this.client.apiVersion.gte(API.v300)) {
5879 // languages.registerCompletionItemProvider(
5880 // `tsserver-${this.description.id}-tag`,
5883 // new TagCompletionProvider(client),
5889 handles(resource, doc) {
5890 if (doc && this.description.modeIds.indexOf(doc.languageId) >= 0) {
5893 const base = path_1.default.basename(coc_nvim_1.Uri.parse(resource).fsPath);
5894 return !!base && (!!this.description.configFilePattern && this.description.configFilePattern.test(base));
5897 return this.description.id;
5899 get diagnosticSource() {
5900 return this.description.diagnosticSource;
5902 triggerAllDiagnostics() {
5903 this.client.bufferSyncSupport.requestAllDiagnostics();
5905 diagnosticsReceived(diagnosticsKind, file, diagnostics) {
5906 const config = coc_nvim_1.workspace.getConfiguration(this.id, file.toString());
5907 const reportUnnecessary = config.get('showUnused', true);
5908 this.client.diagnosticsManager.diagnosticsReceived(diagnosticsKind, file.toString(), diagnostics.filter(diag => {
5909 if (!reportUnnecessary) {
5910 diag.tags = undefined;
5911 if (diag.reportUnnecessary && diag.severity === vscode_languageserver_protocol_1.DiagnosticSeverity.Information) {
5919 exports.default = LanguageProvider;
5924 /***/ (function(module, exports, __webpack_require__) {
5928 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5929 if (k2 === undefined) k2 = k;
5930 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5931 }) : (function(o, m, k, k2) {
5932 if (k2 === undefined) k2 = k;
5935 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
5936 Object.defineProperty(o, "default", { enumerable: true, value: v });
5937 }) : function(o, v) {
5940 var __importStar = (this && this.__importStar) || function (mod) {
5941 if (mod && mod.__esModule) return mod;
5943 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
5944 __setModuleDefault(result, mod);
5947 Object.defineProperty(exports, "__esModule", { value: true });
5948 exports.TypeScriptBaseCodeLensProvider = exports.CachedNavTreeResponse = void 0;
5949 /*---------------------------------------------------------------------------------------------
5950 * Copyright (c) Microsoft Corporation. All rights reserved.
5951 * Licensed under the MIT License. See License.txt in the project root for license information.
5952 *--------------------------------------------------------------------------------------------*/
5953 const vscode_languageserver_protocol_1 = __webpack_require__(3);
5954 const regexp_1 = __webpack_require__(36);
5955 const typeConverters = __importStar(__webpack_require__(37));
5956 class CachedNavTreeResponse {
5961 execute(document, f) {
5962 if (this.matches(document)) {
5963 return this.response;
5965 return this.update(document, f());
5968 return (this.version === document.version &&
5969 this.document === document.uri.toString());
5971 update(document, response) {
5972 this.response = response;
5973 this.version = document.version;
5974 this.document = document.uri.toString();
5978 exports.CachedNavTreeResponse = CachedNavTreeResponse;
5979 class TypeScriptBaseCodeLensProvider {
5980 constructor(client, cachedResponse) {
5981 this.client = client;
5982 this.cachedResponse = cachedResponse;
5983 this.onDidChangeCodeLensesEmitter = new vscode_languageserver_protocol_1.Emitter();
5985 get onDidChangeCodeLenses() {
5986 return this.onDidChangeCodeLensesEmitter.event;
5988 async provideCodeLenses(document, token) {
5989 const filepath = this.client.toPath(document.uri);
5994 const response = await this.cachedResponse.execute(document, () => this.client.execute('navtree', { file: filepath }, token));
5998 const tree = response.body;
5999 const referenceableSpans = [];
6000 if (tree && tree.childItems) {
6001 tree.childItems.forEach(item => this.walkNavTree(document, item, null, referenceableSpans));
6003 return referenceableSpans.map(range => {
6006 data: { uri: document.uri }
6014 walkNavTree(document, item, parent, results) {
6018 const range = this.extractSymbol(document, item, parent);
6020 results.push(range);
6022 if (item.childItems) {
6023 item.childItems.forEach(child => this.walkNavTree(document, child, item, results));
6026 getSymbolRange(document, item) {
6030 // TS 3.0+ provides a span for just the symbol
6031 if (item.nameSpan) {
6032 return typeConverters.Range.fromTextSpan(item.nameSpan);
6034 // In older versions, we have to calculate this manually. See #23924
6035 const span = item.spans && item.spans[0];
6039 const range = typeConverters.Range.fromTextSpan(span);
6040 const text = document.getText(range);
6041 const identifierMatch = new RegExp(`^(.*?(\\b|\\W))${regexp_1.escapeRegExp(item.text || '')}(\\b|\\W)`, 'gm');
6042 const match = identifierMatch.exec(text);
6043 const prefixLength = match ? match.index + match[1].length : 0;
6044 const startOffset = document.offsetAt(range.start) + prefixLength;
6046 start: document.positionAt(startOffset),
6047 end: document.positionAt(startOffset + item.text.length)
6051 exports.TypeScriptBaseCodeLensProvider = TypeScriptBaseCodeLensProvider;
6056 /***/ (function(module, exports, __webpack_require__) {
6060 /*---------------------------------------------------------------------------------------------
6061 * Copyright (c) Microsoft Corporation. All rights reserved.
6062 * Licensed under the MIT License. See License.txt in the project root for license information.
6063 *--------------------------------------------------------------------------------------------*/
6064 Object.defineProperty(exports, "__esModule", { value: true });
6065 exports.escapeRegExp = void 0;
6066 function escapeRegExp(text) {
6067 return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
6069 exports.escapeRegExp = escapeRegExp;
6074 /***/ (function(module, exports, __webpack_require__) {
6078 Object.defineProperty(exports, "__esModule", { value: true });
6079 exports.WorkspaceEdit = exports.TextEdit = exports.Location = exports.Position = exports.Range = void 0;
6082 Range.fromTextSpan = (span) => {
6085 line: span.start.line - 1,
6086 character: span.start.offset - 1
6089 line: span.end.line - 1,
6090 character: span.end.offset - 1
6094 Range.toFormattingRequestArgs = (file, range) => ({
6096 line: range.start.line + 1,
6097 offset: range.start.character + 1,
6098 endLine: range.end.line + 1,
6099 endOffset: range.end.character + 1
6101 Range.toFileRangeRequestArgs = (file, range) => ({
6103 startLine: range.start.line + 1,
6104 startOffset: range.start.character + 1,
6105 endLine: range.end.line + 1,
6106 endOffset: range.end.character + 1
6108 })(Range = exports.Range || (exports.Range = {}));
6110 (function (Position) {
6111 Position.fromLocation = (tslocation) => {
6113 line: tslocation.line - 1,
6114 character: tslocation.offset - 1
6117 Position.toLocation = (position) => ({
6118 line: position.line + 1,
6119 offset: position.character + 1,
6121 Position.toFileLocationRequestArgs = (file, position) => ({
6123 line: position.line + 1,
6124 offset: position.character + 1
6126 })(Position = exports.Position || (exports.Position = {}));
6128 (function (Location) {
6129 Location.fromTextSpan = (uri, tsTextSpan) => {
6132 range: Range.fromTextSpan(tsTextSpan)
6135 })(Location = exports.Location || (exports.Location = {}));
6137 (function (TextEdit) {
6138 TextEdit.fromCodeEdit = (edit) => {
6140 range: Range.fromTextSpan(edit),
6141 newText: edit.newText
6144 })(TextEdit = exports.TextEdit || (exports.TextEdit = {}));
6146 (function (WorkspaceEdit) {
6147 function fromFileCodeEdits(client, edits) {
6149 for (const edit of edits) {
6150 let uri = client.toResource(edit.fileName);
6151 changes[uri] = edit.textChanges.map(change => {
6152 return TextEdit.fromCodeEdit(change);
6157 WorkspaceEdit.fromFileCodeEdits = fromFileCodeEdits;
6158 })(WorkspaceEdit = exports.WorkspaceEdit || (exports.WorkspaceEdit = {}));
6163 /***/ (function(module, exports, __webpack_require__) {
6167 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6168 if (k2 === undefined) k2 = k;
6169 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
6170 }) : (function(o, m, k, k2) {
6171 if (k2 === undefined) k2 = k;
6174 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
6175 Object.defineProperty(o, "default", { enumerable: true, value: v });
6176 }) : function(o, v) {
6179 var __importStar = (this && this.__importStar) || function (mod) {
6180 if (mod && mod.__esModule) return mod;
6182 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
6183 __setModuleDefault(result, mod);
6186 var __importDefault = (this && this.__importDefault) || function (mod) {
6187 return (mod && mod.__esModule) ? mod : { "default": mod };
6189 Object.defineProperty(exports, "__esModule", { value: true });
6190 /*---------------------------------------------------------------------------------------------
6191 * Copyright (c) Microsoft Corporation. All rights reserved.
6192 * Licensed under the MIT License. See License.txt in the project root for license information.
6193 *--------------------------------------------------------------------------------------------*/
6194 const vscode_languageserver_protocol_1 = __webpack_require__(3);
6195 const coc_nvim_1 = __webpack_require__(1);
6196 const PConst = __importStar(__webpack_require__(39));
6197 const api_1 = __importDefault(__webpack_require__(40));
6198 const codeAction_1 = __webpack_require__(84);
6199 const completionItem_1 = __webpack_require__(85);
6200 const Previewer = __importStar(__webpack_require__(86));
6201 const typeConverters = __importStar(__webpack_require__(37));
6202 const SnippetString_1 = __importDefault(__webpack_require__(87));
6203 class ApplyCompletionCodeActionCommand {
6204 constructor(client) {
6205 this.client = client;
6206 this.id = ApplyCompletionCodeActionCommand.ID;
6208 // apply code action on complete
6209 async execute(codeActions) {
6210 if (codeActions.length === 0) {
6213 if (codeActions.length === 1) {
6214 await codeAction_1.applyCodeAction(this.client, codeActions[0]);
6217 const idx = await coc_nvim_1.workspace.showQuickpick(codeActions.map(o => o.description), 'Select code action to apply');
6220 const action = codeActions[idx];
6221 await codeAction_1.applyCodeAction(this.client, action);
6225 ApplyCompletionCodeActionCommand.ID = '_typescript.applyCompletionCodeAction';
6226 class TypeScriptCompletionItemProvider {
6227 constructor(client, typingsStatus, fileConfigurationManager, languageId) {
6228 this.client = client;
6229 this.typingsStatus = typingsStatus;
6230 this.fileConfigurationManager = fileConfigurationManager;
6231 this.setCompleteOption(languageId);
6232 coc_nvim_1.commands.register(new ApplyCompletionCodeActionCommand(this.client));
6233 coc_nvim_1.workspace.onDidChangeConfiguration(_e => {
6234 this.setCompleteOption(languageId);
6237 setCompleteOption(languageId) {
6238 this.completeOption = this.fileConfigurationManager.getCompleteOptions(languageId);
6241 * Get completionItems
6244 * @param {TextDocument} document
6245 * @param {Position} position
6246 * @param {CancellationToken} token
6247 * @param {string} triggerCharacter
6248 * @returns {Promise<CompletionItem[]>}
6250 async provideCompletionItems(document, position, token, context) {
6251 if (this.typingsStatus.isAcquiringTypings) {
6252 return Promise.resolve({
6255 label: 'Acquiring typings...',
6256 detail: 'Acquiring typings definitions for IntelliSense.'
6260 let { uri } = document;
6261 const file = this.client.toPath(document.uri);
6264 let preText = document.getText({
6265 start: { line: position.line, character: 0 },
6268 let { triggerCharacter, option } = context;
6269 if (!this.shouldTrigger(triggerCharacter, preText, option)) {
6272 await this.client.interruptGetErr(() => this.fileConfigurationManager.ensureConfigurationForDocument(document, token));
6273 const { completeOption } = this;
6274 const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { includeExternalModuleExports: completeOption.autoImports, includeInsertTextCompletions: true, triggerCharacter: this.getTsTriggerCharacter(context), includeAutomaticOptionalChainCompletions: completeOption.includeAutomaticOptionalChainCompletions });
6276 let dotAccessorContext;
6277 let isNewIdentifierLocation = true;
6278 let isMemberCompletion = false;
6279 let isIncomplete = false;
6280 const isInValidCommitCharacterContext = this.isInValidCommitCharacterContext(document, position);
6281 if (this.client.apiVersion.gte(api_1.default.v300)) {
6283 const response = await this.client.interruptGetErr(() => this.client.execute('completionInfo', args, token));
6284 if (response.type !== 'response' || !response.body) {
6287 isNewIdentifierLocation = response.body.isNewIdentifierLocation;
6288 isMemberCompletion = response.body.isMemberCompletion;
6289 if (isMemberCompletion) {
6290 const dotMatch = preText.slice(0, position.character).match(/\??\.\s*$/) || undefined;
6292 const range = vscode_languageserver_protocol_1.Range.create({
6293 line: position.line,
6294 character: position.character - dotMatch.length
6296 const text = document.getText(range);
6297 dotAccessorContext = { range, text };
6300 isIncomplete = response.metadata && response.metadata.isIncomplete;
6301 entries = response.body.entries;
6304 if (e.message == 'No content available.') {
6311 const response = await this.client.interruptGetErr(() => this.client.execute('completions', args, token));
6312 if (response.type !== 'response' || !response.body) {
6315 entries = response.body;
6317 const completionItems = [];
6318 for (const element of entries) {
6319 if (shouldExcludeCompletionEntry(element, completeOption)) {
6322 const item = completionItem_1.convertCompletionEntry(element, uri, position, {
6323 isNewIdentifierLocation,
6325 enableCallCompletions: completeOption.completeFunctionCalls,
6326 isInValidCommitCharacterContext,
6329 completionItems.push(item);
6331 return { isIncomplete, items: completionItems };
6333 getTsTriggerCharacter(context) {
6334 // return context.triggerCharacter as Proto.CompletionsTriggerCharacter
6335 switch (context.triggerCharacter) {
6336 case '@': // Workaround for https://github.com/Microsoft/TypeScript/issues/27321
6337 return this.client.apiVersion.gte(api_1.default.v310) && this.client.apiVersion.lt(api_1.default.v320) ? undefined : '@';
6338 case '#': // Workaround for https://github.com/microsoft/TypeScript/issues/36367
6339 return this.client.apiVersion.lt(api_1.default.v381) ? undefined : '#';
6346 return context.triggerCharacter;
6351 * Resolve complete item, could have documentation added
6354 * @param {CompletionItem} item
6355 * @param {CancellationToken} token
6356 * @returns {Promise<CompletionItem>}
6358 async resolveCompletionItem(item, token) {
6361 let { uri, position, source, name } = item.data;
6362 const filepath = this.client.toPath(uri);
6365 let document = coc_nvim_1.workspace.getDocument(uri);
6368 const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(filepath, position)), { entryNames: [source ? { name, source } : name] });
6371 response = await this.client.interruptGetErr(() => this.client.execute('completionEntryDetails', args, token));
6376 if (response.type !== 'response' || !response.body || !response.body.length) {
6379 const details = response.body;
6380 if (!details || !details.length || !details[0]) {
6383 const detail = details[0];
6384 if (!item.detail && detail.displayParts.length) {
6385 item.detail = Previewer.plain(detail.displayParts);
6387 item.documentation = this.getDocumentation(detail);
6388 const { command, additionalTextEdits } = this.getCodeActions(detail, filepath);
6390 item.command = command;
6391 item.additionalTextEdits = additionalTextEdits;
6392 if (detail && item.insertTextFormat == vscode_languageserver_protocol_1.InsertTextFormat.Snippet) {
6393 const shouldCompleteFunction = await this.isValidFunctionCompletionContext(filepath, position, token);
6394 if (shouldCompleteFunction) {
6395 this.createSnippetOfFunctionCall(item, detail);
6400 getCodeActions(detail, filepath) {
6401 if (!detail.codeActions || !detail.codeActions.length) {
6404 // Try to extract out the additionalTextEdits for the current file.
6405 // Also check if we still have to apply other workspace edits
6406 const additionalTextEdits = [];
6407 let hasRemainingCommandsOrEdits = false;
6408 for (const tsAction of detail.codeActions) {
6409 if (tsAction.commands) {
6410 hasRemainingCommandsOrEdits = true;
6412 // Convert all edits in the current file using `additionalTextEdits`
6413 if (tsAction.changes) {
6414 for (const change of tsAction.changes) {
6415 if (change.fileName === filepath) {
6416 additionalTextEdits.push(...change.textChanges.map(typeConverters.TextEdit.fromCodeEdit));
6419 hasRemainingCommandsOrEdits = true;
6425 if (hasRemainingCommandsOrEdits) {
6426 // Create command that applies all edits not in the current file.
6429 command: ApplyCompletionCodeActionCommand.ID,
6431 detail.codeActions.map((x) => ({
6432 commands: x.commands,
6433 description: x.description,
6434 changes: x.changes.filter(x => x.fileName !== filepath)
6441 additionalTextEdits: additionalTextEdits.length
6442 ? additionalTextEdits
6446 shouldTrigger(triggerCharacter, pre, option) {
6447 if (triggerCharacter && this.client.apiVersion.lt(api_1.default.v290)) {
6448 if (triggerCharacter === '@') {
6449 // trigger in string
6450 if (option.synname && /string/i.test(option.synname)) {
6453 // make sure we are in something that looks like the start of a jsdoc comment
6454 if (!pre.match(/^\s*\*[ ]?@/) && !pre.match(/\/\*\*+[ ]?@/)) {
6458 else if (triggerCharacter === '<') {
6464 // complete item documentation
6465 getDocumentation(detail) {
6466 let documentation = '';
6467 if (detail.source) {
6468 const importPath = `'${Previewer.plain(detail.source)}'`;
6469 const autoImportLabel = `Auto import from ${importPath}`;
6470 documentation += `${autoImportLabel}\n`;
6473 Previewer.plain(detail.documentation),
6474 Previewer.tagsMarkdownPreview(detail.tags)
6476 parts = parts.filter(s => s && s.trim() != '');
6477 documentation += parts.join('\n\n');
6478 if (documentation.length) {
6480 kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
6481 value: documentation
6486 createSnippetOfFunctionCall(item, detail) {
6487 let { displayParts } = detail;
6488 const parameterListParts = completionItem_1.getParameterListParts(displayParts);
6489 const snippet = new SnippetString_1.default();
6490 snippet.appendText(`${item.insertText || item.label}(`);
6491 appendJoinedPlaceholders(snippet, parameterListParts.parts, ', ');
6492 if (parameterListParts.hasOptionalParameters) {
6493 snippet.appendTabstop();
6495 snippet.appendText(')');
6496 snippet.appendTabstop(0);
6497 item.insertText = snippet.value;
6499 async isValidFunctionCompletionContext(filepath, position, token) {
6500 // Workaround for https://github.com/Microsoft/TypeScript/issues/12677
6501 // Don't complete function calls inside of destructive assigments or imports
6503 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
6504 const response = await this.client.execute('quickinfo', args, token);
6505 if (response.type !== 'response') {
6508 const { body } = response;
6509 switch (body && body.kind) {
6523 isInValidCommitCharacterContext(document, position) {
6524 if (this.client.apiVersion.lt(api_1.default.v320)) {
6525 // Workaround for https://github.com/Microsoft/TypeScript/issues/27742
6526 // Only enable dot completions when previous character not a dot preceded by whitespace.
6527 // Prevents incorrectly completing while typing spread operators.
6528 if (position.character > 1) {
6529 const preText = document.getText(vscode_languageserver_protocol_1.Range.create(position.line, 0, position.line, position.character));
6530 return preText.match(/(\s|^)\.$/ig) === null;
6536 exports.default = TypeScriptCompletionItemProvider;
6537 TypeScriptCompletionItemProvider.triggerCharacters = ['.', '"', '\'', '`', '/', '@', '<', '#'];
6538 function shouldExcludeCompletionEntry(element, completionConfiguration) {
6539 return ((!completionConfiguration.names && element.kind === PConst.Kind.warning)
6540 || (!completionConfiguration.paths &&
6541 (element.kind === PConst.Kind.directory || element.kind === PConst.Kind.script || element.kind === PConst.Kind.externalModuleName))
6542 || (!completionConfiguration.autoImports && element.hasAction));
6544 function appendJoinedPlaceholders(snippet, parts, joiner) {
6545 for (let i = 0; i < parts.length; ++i) {
6546 const paramterPart = parts[i];
6547 snippet.appendPlaceholder(paramterPart.text);
6548 if (i !== parts.length - 1) {
6549 snippet.appendText(joiner);
6557 /***/ (function(module, exports, __webpack_require__) {
6561 /*---------------------------------------------------------------------------------------------
6562 * Copyright (c) Microsoft Corporation. All rights reserved.
6563 * Licensed under the MIT License. See License.txt in the project root for license information.
6564 *--------------------------------------------------------------------------------------------*/
6565 Object.defineProperty(exports, "__esModule", { value: true });
6566 exports.DisplayPartKind = exports.KindModifiers = exports.DiagnosticCategory = exports.Kind = void 0;
6569 exports.Kind = Kind;
6570 Kind.alias = 'alias';
6571 Kind.callSignature = 'call';
6572 Kind.class = 'class';
6573 Kind.const = 'const';
6574 Kind.constructorImplementation = 'constructor';
6575 Kind.constructSignature = 'construct';
6576 Kind.directory = 'directory';
6578 Kind.enumMember = 'enum member';
6579 Kind.externalModuleName = 'external module name';
6580 Kind.function = 'function';
6581 Kind.indexSignature = 'index';
6582 Kind.interface = 'interface';
6583 Kind.keyword = 'keyword';
6585 Kind.localFunction = 'local function';
6586 Kind.localVariable = 'local var';
6587 Kind.method = 'method';
6588 Kind.memberGetAccessor = 'getter';
6589 Kind.memberSetAccessor = 'setter';
6590 Kind.memberVariable = 'property';
6591 Kind.module = 'module';
6592 Kind.primitiveType = 'primitive type';
6593 Kind.script = 'script';
6595 Kind.variable = 'var';
6596 Kind.warning = 'warning';
6597 Kind.string = 'string';
6598 Kind.parameter = 'parameter';
6599 Kind.typeParameter = 'type parameter';
6600 class DiagnosticCategory {
6602 exports.DiagnosticCategory = DiagnosticCategory;
6603 DiagnosticCategory.error = 'error';
6604 DiagnosticCategory.warning = 'warning';
6605 DiagnosticCategory.suggestion = 'suggestion';
6606 class KindModifiers {
6608 exports.KindModifiers = KindModifiers;
6609 KindModifiers.optional = 'optional';
6610 KindModifiers.color = 'color';
6611 KindModifiers.dtsFile = '.d.ts';
6612 KindModifiers.tsFile = '.ts';
6613 KindModifiers.tsxFile = '.tsx';
6614 KindModifiers.jsFile = '.js';
6615 KindModifiers.jsxFile = '.jsx';
6616 KindModifiers.jsonFile = '.json';
6617 KindModifiers.fileExtensionKindModifiers = [
6618 KindModifiers.dtsFile,
6619 KindModifiers.tsFile,
6620 KindModifiers.tsxFile,
6621 KindModifiers.jsFile,
6622 KindModifiers.jsxFile,
6623 KindModifiers.jsonFile,
6625 class DisplayPartKind {
6627 exports.DisplayPartKind = DisplayPartKind;
6628 DisplayPartKind.functionName = 'functionName';
6629 DisplayPartKind.methodName = 'methodName';
6630 DisplayPartKind.parameterName = 'parameterName';
6631 DisplayPartKind.propertyName = 'propertyName';
6632 DisplayPartKind.punctuation = 'punctuation';
6633 DisplayPartKind.text = 'text';
6638 /***/ (function(module, exports, __webpack_require__) {
6642 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6643 if (k2 === undefined) k2 = k;
6644 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
6645 }) : (function(o, m, k, k2) {
6646 if (k2 === undefined) k2 = k;
6649 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
6650 Object.defineProperty(o, "default", { enumerable: true, value: v });
6651 }) : function(o, v) {
6654 var __importStar = (this && this.__importStar) || function (mod) {
6655 if (mod && mod.__esModule) return mod;
6657 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
6658 __setModuleDefault(result, mod);
6661 Object.defineProperty(exports, "__esModule", { value: true });
6662 /*---------------------------------------------------------------------------------------------
6663 * Copyright (c) Microsoft Corporation. All rights reserved.
6664 * Licensed under the MIT License. See License.txt in the project root for license information.
6665 *--------------------------------------------------------------------------------------------*/
6666 const semver = __importStar(__webpack_require__(41));
6668 constructor(versionString, version) {
6669 this.versionString = versionString;
6670 this.version = version;
6672 static fromSimpleString(value) {
6673 return new API(value, value);
6675 static fromVersionString(versionString) {
6676 let version = semver.valid(versionString);
6678 return new API('invalid version', '1.0.0');
6680 // Cut off any prerelease tag since we sometimes consume those on purpose.
6681 const index = versionString.indexOf('-');
6683 version = version.substr(0, index);
6685 return new API(versionString, version);
6688 return semver.gte(this.version, other.version);
6691 return !this.gte(other);
6694 exports.default = API;
6695 API.defaultVersion = API.fromSimpleString('1.0.0');
6696 API.v203 = API.fromSimpleString('2.0.3');
6697 API.v206 = API.fromSimpleString('2.0.6');
6698 API.v208 = API.fromSimpleString('2.0.8');
6699 API.v213 = API.fromSimpleString('2.1.3');
6700 API.v220 = API.fromSimpleString('2.2.0');
6701 API.v222 = API.fromSimpleString('2.2.2');
6702 API.v230 = API.fromSimpleString('2.3.0');
6703 API.v234 = API.fromSimpleString('2.3.4');
6704 API.v240 = API.fromSimpleString('2.4.0');
6705 API.v250 = API.fromSimpleString('2.5.0');
6706 API.v260 = API.fromSimpleString('2.6.0');
6707 API.v270 = API.fromSimpleString('2.7.0');
6708 API.v280 = API.fromSimpleString('2.8.0');
6709 API.v290 = API.fromSimpleString('2.9.0');
6710 API.v291 = API.fromSimpleString('2.9.1');
6711 API.v292 = API.fromSimpleString('2.9.2');
6712 API.v300 = API.fromSimpleString('3.0.0');
6713 API.v310 = API.fromSimpleString('3.1.0');
6714 API.v314 = API.fromSimpleString('3.1.4');
6715 API.v320 = API.fromSimpleString('3.2.0');
6716 API.v330 = API.fromSimpleString('3.3.0');
6717 API.v333 = API.fromSimpleString('3.3.3');
6718 API.v340 = API.fromSimpleString('3.4.0');
6719 API.v345 = API.fromSimpleString('3.4.5');
6720 API.v350 = API.fromSimpleString('3.5.0');
6721 API.v380 = API.fromSimpleString('3.8.0');
6722 API.v381 = API.fromSimpleString('3.8.1');
6723 API.v390 = API.fromSimpleString('3.9.0');
6724 API.v400 = API.fromSimpleString('4.0.0');
6725 API.v401 = API.fromSimpleString('4.0.1');
6730 /***/ (function(module, exports, __webpack_require__) {
6732 // just pre-load all the stuff that index.js lazily exports
6733 const internalRe = __webpack_require__(42)
6736 src: internalRe.src,
6737 tokens: internalRe.t,
6738 SEMVER_SPEC_VERSION: __webpack_require__(43).SEMVER_SPEC_VERSION,
6739 SemVer: __webpack_require__(45),
6740 compareIdentifiers: __webpack_require__(46).compareIdentifiers,
6741 rcompareIdentifiers: __webpack_require__(46).rcompareIdentifiers,
6742 parse: __webpack_require__(47),
6743 valid: __webpack_require__(48),
6744 clean: __webpack_require__(49),
6745 inc: __webpack_require__(50),
6746 diff: __webpack_require__(51),
6747 major: __webpack_require__(54),
6748 minor: __webpack_require__(55),
6749 patch: __webpack_require__(56),
6750 prerelease: __webpack_require__(57),
6751 compare: __webpack_require__(53),
6752 rcompare: __webpack_require__(58),
6753 compareLoose: __webpack_require__(59),
6754 compareBuild: __webpack_require__(60),
6755 sort: __webpack_require__(61),
6756 rsort: __webpack_require__(62),
6757 gt: __webpack_require__(63),
6758 lt: __webpack_require__(64),
6759 eq: __webpack_require__(52),
6760 neq: __webpack_require__(65),
6761 gte: __webpack_require__(66),
6762 lte: __webpack_require__(67),
6763 cmp: __webpack_require__(68),
6764 coerce: __webpack_require__(69),
6765 Comparator: __webpack_require__(70),
6766 Range: __webpack_require__(71),
6767 satisfies: __webpack_require__(72),
6768 toComparators: __webpack_require__(73),
6769 maxSatisfying: __webpack_require__(74),
6770 minSatisfying: __webpack_require__(75),
6771 minVersion: __webpack_require__(76),
6772 validRange: __webpack_require__(77),
6773 outside: __webpack_require__(78),
6774 gtr: __webpack_require__(79),
6775 ltr: __webpack_require__(80),
6776 intersects: __webpack_require__(81),
6777 simplifyRange: __webpack_require__(82),
6778 subset: __webpack_require__(83),
6784 /***/ (function(module, exports, __webpack_require__) {
6786 const { MAX_SAFE_COMPONENT_LENGTH } = __webpack_require__(43)
6787 const debug = __webpack_require__(44)
6788 exports = module.exports = {}
6790 // The actual regexps go on exports.re
6791 const re = exports.re = []
6792 const src = exports.src = []
6793 const t = exports.t = {}
6796 const createToken = (name, value, isGlobal) => {
6801 re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
6804 // The following Regular Expressions can be used for tokenizing,
6805 // validating, and parsing SemVer version strings.
6807 // ## Numeric Identifier
6808 // A single `0`, or a non-zero digit followed by zero or more digits.
6810 createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
6811 createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+')
6813 // ## Non-numeric Identifier
6814 // Zero or more digits, followed by a letter or hyphen, and then zero or
6815 // more letters, digits, or hyphens.
6817 createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*')
6820 // Three dot-separated numeric identifiers.
6822 createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
6823 `(${src[t.NUMERICIDENTIFIER]})\\.` +
6824 `(${src[t.NUMERICIDENTIFIER]})`)
6826 createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
6827 `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
6828 `(${src[t.NUMERICIDENTIFIERLOOSE]})`)
6830 // ## Pre-release Version Identifier
6831 // A numeric identifier, or a non-numeric identifier.
6833 createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
6834 }|${src[t.NONNUMERICIDENTIFIER]})`)
6836 createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
6837 }|${src[t.NONNUMERICIDENTIFIER]})`)
6839 // ## Pre-release Version
6840 // Hyphen, followed by one or more dot-separated pre-release version
6843 createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
6844 }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
6846 createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
6847 }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
6849 // ## Build Metadata Identifier
6850 // Any combination of digits, letters, or hyphens.
6852 createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+')
6854 // ## Build Metadata
6855 // Plus sign, followed by one or more period-separated build metadata
6858 createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
6859 }(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
6861 // ## Full Version String
6862 // A main version, followed optionally by a pre-release version and
6865 // Note that the only major, minor, patch, and pre-release sections of
6866 // the version string are capturing groups. The build metadata is not a
6867 // capturing group, because it should not ever be used in version
6870 createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
6871 }${src[t.PRERELEASE]}?${
6874 createToken('FULL', `^${src[t.FULLPLAIN]}$`)
6876 // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
6877 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
6878 // common in the npm registry.
6879 createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
6880 }${src[t.PRERELEASELOOSE]}?${
6883 createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
6885 createToken('GTLT', '((?:<|>)?=?)')
6887 // Something like "2.*" or "1.2.x".
6888 // Note that "x.x" is a valid xRange identifer, meaning "any version"
6889 // Only the first item is strictly required.
6890 createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
6891 createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
6893 createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
6894 `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
6895 `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
6896 `(?:${src[t.PRERELEASE]})?${
6900 createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
6901 `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
6902 `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
6903 `(?:${src[t.PRERELEASELOOSE]})?${
6907 createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
6908 createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
6911 // Extract anything that could conceivably be a part of a valid semver
6912 createToken('COERCE', `${'(^|[^\\d])' +
6913 '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
6914 `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
6915 `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
6917 createToken('COERCERTL', src[t.COERCE], true)
6920 // Meaning is "reasonably at or greater than"
6921 createToken('LONETILDE', '(?:~>?)')
6923 createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
6924 exports.tildeTrimReplace = '$1~'
6926 createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
6927 createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
6930 // Meaning is "at least and backwards compatible with"
6931 createToken('LONECARET', '(?:\\^)')
6933 createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
6934 exports.caretTrimReplace = '$1^'
6936 createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
6937 createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
6939 // A simple gt/lt/eq thing, or just "" to indicate "any version"
6940 createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
6941 createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
6943 // An expression to strip any whitespace between the gtlt and the thing
6944 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
6945 createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
6946 }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
6947 exports.comparatorTrimReplace = '$1$2$3'
6949 // Something like `1.2.3 - 1.2.4`
6950 // Note that these all use the loose form, because they'll be
6951 // checked against either the strict or loose comparator form
6953 createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
6955 `(${src[t.XRANGEPLAIN]})` +
6958 createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
6960 `(${src[t.XRANGEPLAINLOOSE]})` +
6963 // Star ranges basically just allow anything at all.
6964 createToken('STAR', '(<|>)?=?\\s*\\*')
6965 // >=0.0.0 is like a star
6966 createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$')
6967 createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$')
6972 /***/ (function(module, exports) {
6974 // Note: this is the semver.org version of the spec that it implements
6975 // Not necessarily the package version of this code.
6976 const SEMVER_SPEC_VERSION = '2.0.0'
6978 const MAX_LENGTH = 256
6979 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
6980 /* istanbul ignore next */ 9007199254740991
6982 // Max safe segment length for coercion.
6983 const MAX_SAFE_COMPONENT_LENGTH = 16
6986 SEMVER_SPEC_VERSION,
6989 MAX_SAFE_COMPONENT_LENGTH
6995 /***/ (function(module, exports) {
6998 typeof process === 'object' &&
7000 process.env.NODE_DEBUG &&
7001 /\bsemver\b/i.test(process.env.NODE_DEBUG)
7002 ) ? (...args) => console.error('SEMVER', ...args)
7005 module.exports = debug
7010 /***/ (function(module, exports, __webpack_require__) {
7012 const debug = __webpack_require__(44)
7013 const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(43)
7014 const { re, t } = __webpack_require__(42)
7016 const { compareIdentifiers } = __webpack_require__(46)
7018 constructor (version, options) {
7019 if (!options || typeof options !== 'object') {
7022 includePrerelease: false
7025 if (version instanceof SemVer) {
7026 if (version.loose === !!options.loose &&
7027 version.includePrerelease === !!options.includePrerelease) {
7030 version = version.version
7032 } else if (typeof version !== 'string') {
7033 throw new TypeError(`Invalid Version: ${version}`)
7036 if (version.length > MAX_LENGTH) {
7037 throw new TypeError(
7038 `version is longer than ${MAX_LENGTH} characters`
7042 debug('SemVer', version, options)
7043 this.options = options
7044 this.loose = !!options.loose
7045 // this isn't actually relevant for versions, but keep it so that we
7046 // don't run into trouble passing this.options around.
7047 this.includePrerelease = !!options.includePrerelease
7049 const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
7052 throw new TypeError(`Invalid Version: ${version}`)
7057 // these are actually numbers
7062 if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
7063 throw new TypeError('Invalid major version')
7066 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
7067 throw new TypeError('Invalid minor version')
7070 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
7071 throw new TypeError('Invalid patch version')
7074 // numberify any prerelease numeric ids
7076 this.prerelease = []
7078 this.prerelease = m[4].split('.').map((id) => {
7079 if (/^[0-9]+$/.test(id)) {
7081 if (num >= 0 && num < MAX_SAFE_INTEGER) {
7089 this.build = m[5] ? m[5].split('.') : []
7094 this.version = `${this.major}.${this.minor}.${this.patch}`
7095 if (this.prerelease.length) {
7096 this.version += `-${this.prerelease.join('.')}`
7106 debug('SemVer.compare', this.version, this.options, other)
7107 if (!(other instanceof SemVer)) {
7108 if (typeof other === 'string' && other === this.version) {
7111 other = new SemVer(other, this.options)
7114 if (other.version === this.version) {
7118 return this.compareMain(other) || this.comparePre(other)
7121 compareMain (other) {
7122 if (!(other instanceof SemVer)) {
7123 other = new SemVer(other, this.options)
7127 compareIdentifiers(this.major, other.major) ||
7128 compareIdentifiers(this.minor, other.minor) ||
7129 compareIdentifiers(this.patch, other.patch)
7133 comparePre (other) {
7134 if (!(other instanceof SemVer)) {
7135 other = new SemVer(other, this.options)
7138 // NOT having a prerelease is > having one
7139 if (this.prerelease.length && !other.prerelease.length) {
7141 } else if (!this.prerelease.length && other.prerelease.length) {
7143 } else if (!this.prerelease.length && !other.prerelease.length) {
7149 const a = this.prerelease[i]
7150 const b = other.prerelease[i]
7151 debug('prerelease compare', i, a, b)
7152 if (a === undefined && b === undefined) {
7154 } else if (b === undefined) {
7156 } else if (a === undefined) {
7158 } else if (a === b) {
7161 return compareIdentifiers(a, b)
7166 compareBuild (other) {
7167 if (!(other instanceof SemVer)) {
7168 other = new SemVer(other, this.options)
7173 const a = this.build[i]
7174 const b = other.build[i]
7175 debug('prerelease compare', i, a, b)
7176 if (a === undefined && b === undefined) {
7178 } else if (b === undefined) {
7180 } else if (a === undefined) {
7182 } else if (a === b) {
7185 return compareIdentifiers(a, b)
7190 // preminor will bump the version up to the next minor release, and immediately
7191 // down to pre-release. premajor and prepatch work the same way.
7192 inc (release, identifier) {
7195 this.prerelease.length = 0
7199 this.inc('pre', identifier)
7202 this.prerelease.length = 0
7205 this.inc('pre', identifier)
7208 // If this is already a prerelease, it will bump to the next version
7209 // drop any prereleases that might already exist, since they are not
7210 // relevant at this point.
7211 this.prerelease.length = 0
7212 this.inc('patch', identifier)
7213 this.inc('pre', identifier)
7215 // If the input is a non-prerelease version, this acts the same as
7218 if (this.prerelease.length === 0) {
7219 this.inc('patch', identifier)
7221 this.inc('pre', identifier)
7225 // If this is a pre-major version, bump up to the same major version.
7226 // Otherwise increment major.
7227 // 1.0.0-5 bumps to 1.0.0
7228 // 1.1.0 bumps to 2.0.0
7232 this.prerelease.length === 0
7238 this.prerelease = []
7241 // If this is a pre-minor version, bump up to the same minor version.
7242 // Otherwise increment minor.
7243 // 1.2.0-5 bumps to 1.2.0
7244 // 1.2.1 bumps to 1.3.0
7245 if (this.patch !== 0 || this.prerelease.length === 0) {
7249 this.prerelease = []
7252 // If this is not a pre-release version, it will increment the patch.
7253 // If it is a pre-release it will bump up to the same patch version.
7254 // 1.2.0-5 patches to 1.2.0
7255 // 1.2.0 patches to 1.2.1
7256 if (this.prerelease.length === 0) {
7259 this.prerelease = []
7261 // This probably shouldn't be used publicly.
7262 // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
7264 if (this.prerelease.length === 0) {
7265 this.prerelease = [0]
7267 let i = this.prerelease.length
7269 if (typeof this.prerelease[i] === 'number') {
7270 this.prerelease[i]++
7275 // didn't increment anything
7276 this.prerelease.push(0)
7280 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
7281 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
7282 if (this.prerelease[0] === identifier) {
7283 if (isNaN(this.prerelease[1])) {
7284 this.prerelease = [identifier, 0]
7287 this.prerelease = [identifier, 0]
7293 throw new Error(`invalid increment argument: ${release}`)
7296 this.raw = this.version
7301 module.exports = SemVer
7306 /***/ (function(module, exports) {
7308 const numeric = /^[0-9]+$/
7309 const compareIdentifiers = (a, b) => {
7310 const anum = numeric.test(a)
7311 const bnum = numeric.test(b)
7319 : (anum && !bnum) ? -1
7320 : (bnum && !anum) ? 1
7325 const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
7335 /***/ (function(module, exports, __webpack_require__) {
7337 const {MAX_LENGTH} = __webpack_require__(43)
7338 const { re, t } = __webpack_require__(42)
7339 const SemVer = __webpack_require__(45)
7341 const parse = (version, options) => {
7342 if (!options || typeof options !== 'object') {
7345 includePrerelease: false
7349 if (version instanceof SemVer) {
7353 if (typeof version !== 'string') {
7357 if (version.length > MAX_LENGTH) {
7361 const r = options.loose ? re[t.LOOSE] : re[t.FULL]
7362 if (!r.test(version)) {
7367 return new SemVer(version, options)
7373 module.exports = parse
7378 /***/ (function(module, exports, __webpack_require__) {
7380 const parse = __webpack_require__(47)
7381 const valid = (version, options) => {
7382 const v = parse(version, options)
7383 return v ? v.version : null
7385 module.exports = valid
7390 /***/ (function(module, exports, __webpack_require__) {
7392 const parse = __webpack_require__(47)
7393 const clean = (version, options) => {
7394 const s = parse(version.trim().replace(/^[=v]+/, ''), options)
7395 return s ? s.version : null
7397 module.exports = clean
7402 /***/ (function(module, exports, __webpack_require__) {
7404 const SemVer = __webpack_require__(45)
7406 const inc = (version, release, options, identifier) => {
7407 if (typeof (options) === 'string') {
7408 identifier = options
7413 return new SemVer(version, options).inc(release, identifier).version
7418 module.exports = inc
7423 /***/ (function(module, exports, __webpack_require__) {
7425 const parse = __webpack_require__(47)
7426 const eq = __webpack_require__(52)
7428 const diff = (version1, version2) => {
7429 if (eq(version1, version2)) {
7432 const v1 = parse(version1)
7433 const v2 = parse(version2)
7434 const hasPre = v1.prerelease.length || v2.prerelease.length
7435 const prefix = hasPre ? 'pre' : ''
7436 const defaultResult = hasPre ? 'prerelease' : ''
7437 for (const key in v1) {
7438 if (key === 'major' || key === 'minor' || key === 'patch') {
7439 if (v1[key] !== v2[key]) {
7444 return defaultResult // may be undefined
7447 module.exports = diff
7452 /***/ (function(module, exports, __webpack_require__) {
7454 const compare = __webpack_require__(53)
7455 const eq = (a, b, loose) => compare(a, b, loose) === 0
7461 /***/ (function(module, exports, __webpack_require__) {
7463 const SemVer = __webpack_require__(45)
7464 const compare = (a, b, loose) =>
7465 new SemVer(a, loose).compare(new SemVer(b, loose))
7467 module.exports = compare
7472 /***/ (function(module, exports, __webpack_require__) {
7474 const SemVer = __webpack_require__(45)
7475 const major = (a, loose) => new SemVer(a, loose).major
7476 module.exports = major
7481 /***/ (function(module, exports, __webpack_require__) {
7483 const SemVer = __webpack_require__(45)
7484 const minor = (a, loose) => new SemVer(a, loose).minor
7485 module.exports = minor
7490 /***/ (function(module, exports, __webpack_require__) {
7492 const SemVer = __webpack_require__(45)
7493 const patch = (a, loose) => new SemVer(a, loose).patch
7494 module.exports = patch
7499 /***/ (function(module, exports, __webpack_require__) {
7501 const parse = __webpack_require__(47)
7502 const prerelease = (version, options) => {
7503 const parsed = parse(version, options)
7504 return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
7506 module.exports = prerelease
7511 /***/ (function(module, exports, __webpack_require__) {
7513 const compare = __webpack_require__(53)
7514 const rcompare = (a, b, loose) => compare(b, a, loose)
7515 module.exports = rcompare
7520 /***/ (function(module, exports, __webpack_require__) {
7522 const compare = __webpack_require__(53)
7523 const compareLoose = (a, b) => compare(a, b, true)
7524 module.exports = compareLoose
7529 /***/ (function(module, exports, __webpack_require__) {
7531 const SemVer = __webpack_require__(45)
7532 const compareBuild = (a, b, loose) => {
7533 const versionA = new SemVer(a, loose)
7534 const versionB = new SemVer(b, loose)
7535 return versionA.compare(versionB) || versionA.compareBuild(versionB)
7537 module.exports = compareBuild
7542 /***/ (function(module, exports, __webpack_require__) {
7544 const compareBuild = __webpack_require__(60)
7545 const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
7546 module.exports = sort
7551 /***/ (function(module, exports, __webpack_require__) {
7553 const compareBuild = __webpack_require__(60)
7554 const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
7555 module.exports = rsort
7560 /***/ (function(module, exports, __webpack_require__) {
7562 const compare = __webpack_require__(53)
7563 const gt = (a, b, loose) => compare(a, b, loose) > 0
7569 /***/ (function(module, exports, __webpack_require__) {
7571 const compare = __webpack_require__(53)
7572 const lt = (a, b, loose) => compare(a, b, loose) < 0
7578 /***/ (function(module, exports, __webpack_require__) {
7580 const compare = __webpack_require__(53)
7581 const neq = (a, b, loose) => compare(a, b, loose) !== 0
7582 module.exports = neq
7587 /***/ (function(module, exports, __webpack_require__) {
7589 const compare = __webpack_require__(53)
7590 const gte = (a, b, loose) => compare(a, b, loose) >= 0
7591 module.exports = gte
7596 /***/ (function(module, exports, __webpack_require__) {
7598 const compare = __webpack_require__(53)
7599 const lte = (a, b, loose) => compare(a, b, loose) <= 0
7600 module.exports = lte
7605 /***/ (function(module, exports, __webpack_require__) {
7607 const eq = __webpack_require__(52)
7608 const neq = __webpack_require__(65)
7609 const gt = __webpack_require__(63)
7610 const gte = __webpack_require__(66)
7611 const lt = __webpack_require__(64)
7612 const lte = __webpack_require__(67)
7614 const cmp = (a, op, b, loose) => {
7617 if (typeof a === 'object')
7619 if (typeof b === 'object')
7624 if (typeof a === 'object')
7626 if (typeof b === 'object')
7633 return eq(a, b, loose)
7636 return neq(a, b, loose)
7639 return gt(a, b, loose)
7642 return gte(a, b, loose)
7645 return lt(a, b, loose)
7648 return lte(a, b, loose)
7651 throw new TypeError(`Invalid operator: ${op}`)
7654 module.exports = cmp
7659 /***/ (function(module, exports, __webpack_require__) {
7661 const SemVer = __webpack_require__(45)
7662 const parse = __webpack_require__(47)
7663 const {re, t} = __webpack_require__(42)
7665 const coerce = (version, options) => {
7666 if (version instanceof SemVer) {
7670 if (typeof version === 'number') {
7671 version = String(version)
7674 if (typeof version !== 'string') {
7678 options = options || {}
7682 match = version.match(re[t.COERCE])
7684 // Find the right-most coercible string that does not share
7685 // a terminus with a more left-ward coercible string.
7686 // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
7688 // Walk through the string checking with a /g regexp
7689 // Manually set the index so as to pick up overlapping matches.
7690 // Stop when we get a match that ends at the string end, since no
7691 // coercible string can be more right-ward without the same terminus.
7693 while ((next = re[t.COERCERTL].exec(version)) &&
7694 (!match || match.index + match[0].length !== version.length)
7697 next.index + next[0].length !== match.index + match[0].length) {
7700 re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
7702 // leave it in a clean state
7703 re[t.COERCERTL].lastIndex = -1
7709 return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
7711 module.exports = coerce
7716 /***/ (function(module, exports, __webpack_require__) {
7718 const ANY = Symbol('SemVer ANY')
7719 // hoisted class for cyclic dependency
7724 constructor (comp, options) {
7725 if (!options || typeof options !== 'object') {
7728 includePrerelease: false
7732 if (comp instanceof Comparator) {
7733 if (comp.loose === !!options.loose) {
7740 debug('comparator', comp, options)
7741 this.options = options
7742 this.loose = !!options.loose
7745 if (this.semver === ANY) {
7748 this.value = this.operator + this.semver.version
7755 const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
7756 const m = comp.match(r)
7759 throw new TypeError(`Invalid comparator: ${comp}`)
7762 this.operator = m[1] !== undefined ? m[1] : ''
7763 if (this.operator === '=') {
7767 // if it literally is just '>' or '' then allow anything.
7771 this.semver = new SemVer(m[2], this.options.loose)
7780 debug('Comparator.test', version, this.options.loose)
7782 if (this.semver === ANY || version === ANY) {
7786 if (typeof version === 'string') {
7788 version = new SemVer(version, this.options)
7794 return cmp(version, this.operator, this.semver, this.options)
7797 intersects (comp, options) {
7798 if (!(comp instanceof Comparator)) {
7799 throw new TypeError('a Comparator is required')
7802 if (!options || typeof options !== 'object') {
7805 includePrerelease: false
7809 if (this.operator === '') {
7810 if (this.value === '') {
7813 return new Range(comp.value, options).test(this.value)
7814 } else if (comp.operator === '') {
7815 if (comp.value === '') {
7818 return new Range(this.value, options).test(comp.semver)
7821 const sameDirectionIncreasing =
7822 (this.operator === '>=' || this.operator === '>') &&
7823 (comp.operator === '>=' || comp.operator === '>')
7824 const sameDirectionDecreasing =
7825 (this.operator === '<=' || this.operator === '<') &&
7826 (comp.operator === '<=' || comp.operator === '<')
7827 const sameSemVer = this.semver.version === comp.semver.version
7828 const differentDirectionsInclusive =
7829 (this.operator === '>=' || this.operator === '<=') &&
7830 (comp.operator === '>=' || comp.operator === '<=')
7831 const oppositeDirectionsLessThan =
7832 cmp(this.semver, '<', comp.semver, options) &&
7833 (this.operator === '>=' || this.operator === '>') &&
7834 (comp.operator === '<=' || comp.operator === '<')
7835 const oppositeDirectionsGreaterThan =
7836 cmp(this.semver, '>', comp.semver, options) &&
7837 (this.operator === '<=' || this.operator === '<') &&
7838 (comp.operator === '>=' || comp.operator === '>')
7841 sameDirectionIncreasing ||
7842 sameDirectionDecreasing ||
7843 (sameSemVer && differentDirectionsInclusive) ||
7844 oppositeDirectionsLessThan ||
7845 oppositeDirectionsGreaterThan
7850 module.exports = Comparator
7852 const {re, t} = __webpack_require__(42)
7853 const cmp = __webpack_require__(68)
7854 const debug = __webpack_require__(44)
7855 const SemVer = __webpack_require__(45)
7856 const Range = __webpack_require__(71)
7861 /***/ (function(module, exports, __webpack_require__) {
7863 // hoisted class for cyclic dependency
7865 constructor (range, options) {
7866 if (!options || typeof options !== 'object') {
7869 includePrerelease: false
7873 if (range instanceof Range) {
7875 range.loose === !!options.loose &&
7876 range.includePrerelease === !!options.includePrerelease
7880 return new Range(range.raw, options)
7884 if (range instanceof Comparator) {
7885 // just put it in the set and return
7886 this.raw = range.value
7887 this.set = [[range]]
7892 this.options = options
7893 this.loose = !!options.loose
7894 this.includePrerelease = !!options.includePrerelease
7896 // First, split based on boolean or ||
7899 .split(/\s*\|\|\s*/)
7900 // map the range to a 2d array of comparators
7901 .map(range => this.parseRange(range.trim()))
7902 // throw out any comparator lists that are empty
7903 // this generally means that it was not a valid range, which is allowed
7904 // in loose mode, but will still throw if the WHOLE range is invalid.
7905 .filter(c => c.length)
7907 if (!this.set.length) {
7908 throw new TypeError(`Invalid SemVer Range: ${range}`)
7915 this.range = this.set
7917 return comps.join(' ').trim()
7928 parseRange (range) {
7929 const loose = this.options.loose
7930 range = range.trim()
7931 // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
7932 const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
7933 range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
7934 debug('hyphen replace', range)
7935 // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
7936 range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
7937 debug('comparator trim', range, re[t.COMPARATORTRIM])
7939 // `~ 1.2.3` => `~1.2.3`
7940 range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
7942 // `^ 1.2.3` => `^1.2.3`
7943 range = range.replace(re[t.CARETTRIM], caretTrimReplace)
7946 range = range.split(/\s+/).join(' ')
7948 // At this point, the range is completely trimmed and
7949 // ready to be split into comparators.
7951 const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
7954 .map(comp => parseComparator(comp, this.options))
7957 .map(comp => replaceGTE0(comp, this.options))
7958 // in loose mode, throw out any that are not valid comparators
7959 .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true)
7960 .map(comp => new Comparator(comp, this.options))
7963 intersects (range, options) {
7964 if (!(range instanceof Range)) {
7965 throw new TypeError('a Range is required')
7968 return this.set.some((thisComparators) => {
7970 isSatisfiable(thisComparators, options) &&
7971 range.set.some((rangeComparators) => {
7973 isSatisfiable(rangeComparators, options) &&
7974 thisComparators.every((thisComparator) => {
7975 return rangeComparators.every((rangeComparator) => {
7976 return thisComparator.intersects(rangeComparator, options)
7985 // if ANY of the sets match ALL of its comparators, then pass
7991 if (typeof version === 'string') {
7993 version = new SemVer(version, this.options)
7999 for (let i = 0; i < this.set.length; i++) {
8000 if (testSet(this.set[i], version, this.options)) {
8007 module.exports = Range
8009 const Comparator = __webpack_require__(70)
8010 const debug = __webpack_require__(44)
8011 const SemVer = __webpack_require__(45)
8015 comparatorTrimReplace,
8018 } = __webpack_require__(42)
8020 // take a set of comparators and determine whether there
8021 // exists a version which can satisfy it
8022 const isSatisfiable = (comparators, options) => {
8024 const remainingComparators = comparators.slice()
8025 let testComparator = remainingComparators.pop()
8027 while (result && remainingComparators.length) {
8028 result = remainingComparators.every((otherComparator) => {
8029 return testComparator.intersects(otherComparator, options)
8032 testComparator = remainingComparators.pop()
8038 // comprised of xranges, tildes, stars, and gtlt's at this point.
8039 // already replaced the hyphen ranges
8040 // turn into a set of JUST comparators.
8041 const parseComparator = (comp, options) => {
8042 debug('comp', comp, options)
8043 comp = replaceCarets(comp, options)
8044 debug('caret', comp)
8045 comp = replaceTildes(comp, options)
8046 debug('tildes', comp)
8047 comp = replaceXRanges(comp, options)
8048 debug('xrange', comp)
8049 comp = replaceStars(comp, options)
8050 debug('stars', comp)
8054 const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
8056 // ~, ~> --> * (any, kinda silly)
8057 // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
8058 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
8059 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
8060 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
8061 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
8062 const replaceTildes = (comp, options) =>
8063 comp.trim().split(/\s+/).map((comp) => {
8064 return replaceTilde(comp, options)
8067 const replaceTilde = (comp, options) => {
8068 const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
8069 return comp.replace(r, (_, M, m, p, pr) => {
8070 debug('tilde', comp, _, M, m, p, pr)
8075 } else if (isX(m)) {
8076 ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
8077 } else if (isX(p)) {
8078 // ~1.2 == >=1.2.0 <1.3.0-0
8079 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
8081 debug('replaceTilde pr', pr)
8082 ret = `>=${M}.${m}.${p}-${pr
8083 } <${M}.${+m + 1}.0-0`
8085 // ~1.2.3 == >=1.2.3 <1.3.0-0
8086 ret = `>=${M}.${m}.${p
8087 } <${M}.${+m + 1}.0-0`
8090 debug('tilde return', ret)
8095 // ^ --> * (any, kinda silly)
8096 // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
8097 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
8098 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
8099 // ^1.2.3 --> >=1.2.3 <2.0.0-0
8100 // ^1.2.0 --> >=1.2.0 <2.0.0-0
8101 const replaceCarets = (comp, options) =>
8102 comp.trim().split(/\s+/).map((comp) => {
8103 return replaceCaret(comp, options)
8106 const replaceCaret = (comp, options) => {
8107 debug('caret', comp, options)
8108 const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
8109 const z = options.includePrerelease ? '-0' : ''
8110 return comp.replace(r, (_, M, m, p, pr) => {
8111 debug('caret', comp, _, M, m, p, pr)
8116 } else if (isX(m)) {
8117 ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
8118 } else if (isX(p)) {
8120 ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
8122 ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
8125 debug('replaceCaret pr', pr)
8128 ret = `>=${M}.${m}.${p}-${pr
8129 } <${M}.${m}.${+p + 1}-0`
8131 ret = `>=${M}.${m}.${p}-${pr
8132 } <${M}.${+m + 1}.0-0`
8135 ret = `>=${M}.${m}.${p}-${pr
8142 ret = `>=${M}.${m}.${p
8143 }${z} <${M}.${m}.${+p + 1}-0`
8145 ret = `>=${M}.${m}.${p
8146 }${z} <${M}.${+m + 1}.0-0`
8149 ret = `>=${M}.${m}.${p
8154 debug('caret return', ret)
8159 const replaceXRanges = (comp, options) => {
8160 debug('replaceXRanges', comp, options)
8161 return comp.split(/\s+/).map((comp) => {
8162 return replaceXRange(comp, options)
8166 const replaceXRange = (comp, options) => {
8168 const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
8169 return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
8170 debug('xRange', comp, ret, gtlt, M, m, p, pr)
8172 const xm = xM || isX(m)
8173 const xp = xm || isX(p)
8176 if (gtlt === '=' && anyX) {
8180 // if we're including prereleases in the match, then we need
8181 // to fix this to -0, the lowest possible prerelease value
8182 pr = options.includePrerelease ? '-0' : ''
8185 if (gtlt === '>' || gtlt === '<') {
8186 // nothing is allowed
8189 // nothing is forbidden
8192 } else if (gtlt && anyX) {
8193 // we know patch is an x, because we have any x at all.
8212 } else if (gtlt === '<=') {
8213 // <=0.7.x is actually <0.8.0, since any 0.7.x should
8214 // pass. Similarly, <=7.x is actually <8.0.0, etc.
8226 ret = `${gtlt + M}.${m}.${p}${pr}`
8228 ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
8230 ret = `>=${M}.${m}.0${pr
8231 } <${M}.${+m + 1}.0-0`
8234 debug('xRange return', ret)
8240 // Because * is AND-ed with everything else in the comparator,
8241 // and '' means "any version", just remove the *s entirely.
8242 const replaceStars = (comp, options) => {
8243 debug('replaceStars', comp, options)
8244 // Looseness is ignored here. star is always as loose as it gets!
8245 return comp.trim().replace(re[t.STAR], '')
8248 const replaceGTE0 = (comp, options) => {
8249 debug('replaceGTE0', comp, options)
8251 .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
8254 // This function is passed to string.replace(re[t.HYPHENRANGE])
8255 // M, m, patch, prerelease, build
8256 // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
8257 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
8258 // 1.2 - 3.4 => >=1.2.0 <3.5.0-0
8259 const hyphenReplace = incPr => ($0,
8260 from, fM, fm, fp, fpr, fb,
8261 to, tM, tm, tp, tpr, tb) => {
8264 } else if (isX(fm)) {
8265 from = `>=${fM}.0.0${incPr ? '-0' : ''}`
8266 } else if (isX(fp)) {
8267 from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
8271 from = `>=${from}${incPr ? '-0' : ''}`
8276 } else if (isX(tm)) {
8277 to = `<${+tM + 1}.0.0-0`
8278 } else if (isX(tp)) {
8279 to = `<${tM}.${+tm + 1}.0-0`
8281 to = `<=${tM}.${tm}.${tp}-${tpr}`
8283 to = `<${tM}.${tm}.${+tp + 1}-0`
8288 return (`${from} ${to}`).trim()
8291 const testSet = (set, version, options) => {
8292 for (let i = 0; i < set.length; i++) {
8293 if (!set[i].test(version)) {
8298 if (version.prerelease.length && !options.includePrerelease) {
8299 // Find the set of versions that are allowed to have prereleases
8300 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
8301 // That should allow `1.2.3-pr.2` to pass.
8302 // However, `1.2.4-alpha.notready` should NOT be allowed,
8303 // even though it's within the range set by the comparators.
8304 for (let i = 0; i < set.length; i++) {
8305 debug(set[i].semver)
8306 if (set[i].semver === Comparator.ANY) {
8310 if (set[i].semver.prerelease.length > 0) {
8311 const allowed = set[i].semver
8312 if (allowed.major === version.major &&
8313 allowed.minor === version.minor &&
8314 allowed.patch === version.patch) {
8320 // Version has a -pre, but it's not one of the ones we like.
8330 /***/ (function(module, exports, __webpack_require__) {
8332 const Range = __webpack_require__(71)
8333 const satisfies = (version, range, options) => {
8335 range = new Range(range, options)
8339 return range.test(version)
8341 module.exports = satisfies
8346 /***/ (function(module, exports, __webpack_require__) {
8348 const Range = __webpack_require__(71)
8350 // Mostly just for testing and legacy API reasons
8351 const toComparators = (range, options) =>
8352 new Range(range, options).set
8353 .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
8355 module.exports = toComparators
8360 /***/ (function(module, exports, __webpack_require__) {
8362 const SemVer = __webpack_require__(45)
8363 const Range = __webpack_require__(71)
8365 const maxSatisfying = (versions, range, options) => {
8370 rangeObj = new Range(range, options)
8374 versions.forEach((v) => {
8375 if (rangeObj.test(v)) {
8376 // satisfies(v, range, options)
8377 if (!max || maxSV.compare(v) === -1) {
8378 // compare(max, v, true)
8380 maxSV = new SemVer(max, options)
8386 module.exports = maxSatisfying
8391 /***/ (function(module, exports, __webpack_require__) {
8393 const SemVer = __webpack_require__(45)
8394 const Range = __webpack_require__(71)
8395 const minSatisfying = (versions, range, options) => {
8400 rangeObj = new Range(range, options)
8404 versions.forEach((v) => {
8405 if (rangeObj.test(v)) {
8406 // satisfies(v, range, options)
8407 if (!min || minSV.compare(v) === 1) {
8408 // compare(min, v, true)
8410 minSV = new SemVer(min, options)
8416 module.exports = minSatisfying
8421 /***/ (function(module, exports, __webpack_require__) {
8423 const SemVer = __webpack_require__(45)
8424 const Range = __webpack_require__(71)
8425 const gt = __webpack_require__(63)
8427 const minVersion = (range, loose) => {
8428 range = new Range(range, loose)
8430 let minver = new SemVer('0.0.0')
8431 if (range.test(minver)) {
8435 minver = new SemVer('0.0.0-0')
8436 if (range.test(minver)) {
8441 for (let i = 0; i < range.set.length; ++i) {
8442 const comparators = range.set[i]
8444 comparators.forEach((comparator) => {
8445 // Clone to avoid manipulating the comparator's semver object.
8446 const compver = new SemVer(comparator.semver.version)
8447 switch (comparator.operator) {
8449 if (compver.prerelease.length === 0) {
8452 compver.prerelease.push(0)
8454 compver.raw = compver.format()
8458 if (!minver || gt(minver, compver)) {
8464 /* Ignore maximum versions */
8466 /* istanbul ignore next */
8468 throw new Error(`Unexpected operation: ${comparator.operator}`)
8473 if (minver && range.test(minver)) {
8479 module.exports = minVersion
8484 /***/ (function(module, exports, __webpack_require__) {
8486 const Range = __webpack_require__(71)
8487 const validRange = (range, options) => {
8489 // Return '*' instead of '' so that truthiness works.
8490 // This will throw if it's invalid anyway
8491 return new Range(range, options).range || '*'
8496 module.exports = validRange
8501 /***/ (function(module, exports, __webpack_require__) {
8503 const SemVer = __webpack_require__(45)
8504 const Comparator = __webpack_require__(70)
8505 const {ANY} = Comparator
8506 const Range = __webpack_require__(71)
8507 const satisfies = __webpack_require__(72)
8508 const gt = __webpack_require__(63)
8509 const lt = __webpack_require__(64)
8510 const lte = __webpack_require__(67)
8511 const gte = __webpack_require__(66)
8513 const outside = (version, range, hilo, options) => {
8514 version = new SemVer(version, options)
8515 range = new Range(range, options)
8517 let gtfn, ltefn, ltfn, comp, ecomp
8534 throw new TypeError('Must provide a hilo val of "<" or ">"')
8537 // If it satisifes the range it is not outside
8538 if (satisfies(version, range, options)) {
8542 // From now on, variable terms are as if we're in "gtr" mode.
8543 // but note that everything is flipped for the "ltr" function.
8545 for (let i = 0; i < range.set.length; ++i) {
8546 const comparators = range.set[i]
8551 comparators.forEach((comparator) => {
8552 if (comparator.semver === ANY) {
8553 comparator = new Comparator('>=0.0.0')
8555 high = high || comparator
8556 low = low || comparator
8557 if (gtfn(comparator.semver, high.semver, options)) {
8559 } else if (ltfn(comparator.semver, low.semver, options)) {
8564 // If the edge version comparator has a operator then our version
8566 if (high.operator === comp || high.operator === ecomp) {
8570 // If the lowest version comparator has an operator and our version
8571 // is less than it then it isn't higher than the range
8572 if ((!low.operator || low.operator === comp) &&
8573 ltefn(version, low.semver)) {
8575 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
8582 module.exports = outside
8587 /***/ (function(module, exports, __webpack_require__) {
8589 // Determine if version is greater than all the versions possible in the range.
8590 const outside = __webpack_require__(78)
8591 const gtr = (version, range, options) => outside(version, range, '>', options)
8592 module.exports = gtr
8597 /***/ (function(module, exports, __webpack_require__) {
8599 const outside = __webpack_require__(78)
8600 // Determine if version is less than all the versions possible in the range
8601 const ltr = (version, range, options) => outside(version, range, '<', options)
8602 module.exports = ltr
8607 /***/ (function(module, exports, __webpack_require__) {
8609 const Range = __webpack_require__(71)
8610 const intersects = (r1, r2, options) => {
8611 r1 = new Range(r1, options)
8612 r2 = new Range(r2, options)
8613 return r1.intersects(r2)
8615 module.exports = intersects
8620 /***/ (function(module, exports, __webpack_require__) {
8622 // given a set of versions and a range, create a "simplified" range
8623 // that includes the same versions that the original range does
8624 // If the original range is shorter than the simplified one, return that.
8625 const satisfies = __webpack_require__(72)
8626 const compare = __webpack_require__(53)
8627 module.exports = (versions, range, options) => {
8631 const v = versions.sort((a, b) => compare(a, b, options))
8632 for (const version of v) {
8633 const included = satisfies(version, range, options)
8640 set.push([min, prev])
8647 set.push([min, null])
8650 for (const [min, max] of set) {
8653 else if (!max && min === v[0])
8656 ranges.push(`>=${min}`)
8657 else if (min === v[0])
8658 ranges.push(`<=${max}`)
8660 ranges.push(`${min} - ${max}`)
8662 const simplified = ranges.join(' || ')
8663 const original = typeof range.raw === 'string' ? range.raw : String(range)
8664 return simplified.length < original.length ? simplified : range
8670 /***/ (function(module, exports, __webpack_require__) {
8672 const Range = __webpack_require__(71)
8673 const { ANY } = __webpack_require__(70)
8674 const satisfies = __webpack_require__(72)
8675 const compare = __webpack_require__(53)
8677 // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
8678 // - Every simple range `r1, r2, ...` is a subset of some `R1, R2, ...`
8680 // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
8681 // - If c is only the ANY comparator
8682 // - If C is only the ANY comparator, return true
8683 // - Else return false
8684 // - Let EQ be the set of = comparators in c
8685 // - If EQ is more than one, return true (null set)
8686 // - Let GT be the highest > or >= comparator in c
8687 // - Let LT be the lowest < or <= comparator in c
8688 // - If GT and LT, and GT.semver > LT.semver, return true (null set)
8690 // - If GT, and EQ does not satisfy GT, return true (null set)
8691 // - If LT, and EQ does not satisfy LT, return true (null set)
8692 // - If EQ satisfies every C, return true
8693 // - Else return false
8695 // - If GT is lower than any > or >= comp in C, return false
8696 // - If GT is >=, and GT.semver does not satisfy every C, return false
8698 // - If LT.semver is greater than that of any > comp in C, return false
8699 // - If LT is <=, and LT.semver does not satisfy every C, return false
8700 // - If any C is a = range, and GT or LT are set, return false
8701 // - Else return true
8703 const subset = (sub, dom, options) => {
8704 sub = new Range(sub, options)
8705 dom = new Range(dom, options)
8706 let sawNonNull = false
8708 OUTER: for (const simpleSub of sub.set) {
8709 for (const simpleDom of dom.set) {
8710 const isSub = simpleSubset(simpleSub, simpleDom, options)
8711 sawNonNull = sawNonNull || isSub !== null
8715 // the null set is a subset of everything, but null simple ranges in
8716 // a complex range should be ignored. so if we saw a non-null range,
8717 // then we know this isn't a subset, but if EVERY simple range was null,
8718 // then it is a subset.
8725 const simpleSubset = (sub, dom, options) => {
8726 if (sub.length === 1 && sub[0].semver === ANY)
8727 return dom.length === 1 && dom[0].semver === ANY
8729 const eqSet = new Set()
8731 for (const c of sub) {
8732 if (c.operator === '>' || c.operator === '>=')
8733 gt = higherGT(gt, c, options)
8734 else if (c.operator === '<' || c.operator === '<=')
8735 lt = lowerLT(lt, c, options)
8745 gtltComp = compare(gt.semver, lt.semver, options)
8748 else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<='))
8752 // will iterate one or zero times
8753 for (const eq of eqSet) {
8754 if (gt && !satisfies(eq, String(gt), options))
8757 if (lt && !satisfies(eq, String(lt), options))
8760 for (const c of dom) {
8761 if (!satisfies(eq, String(c), options))
8768 let hasDomLT, hasDomGT
8769 for (const c of dom) {
8770 hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
8771 hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
8773 if (c.operator === '>' || c.operator === '>=') {
8774 higher = higherGT(gt, c, options)
8777 } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options))
8781 if (c.operator === '<' || c.operator === '<=') {
8782 lower = lowerLT(lt, c, options)
8785 } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options))
8788 if (!c.operator && (lt || gt) && gtltComp !== 0)
8792 // if there was a < or >, and nothing in the dom, then must be false
8793 // UNLESS it was limited by another range in the other direction.
8794 // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
8795 if (gt && hasDomLT && !lt && gtltComp !== 0)
8798 if (lt && hasDomGT && !gt && gtltComp !== 0)
8804 // >=1.2.3 is lower than >1.2.3
8805 const higherGT = (a, b, options) => {
8808 const comp = compare(a.semver, b.semver, options)
8811 : b.operator === '>' && a.operator === '>=' ? b
8815 // <=1.2.3 is higher than <1.2.3
8816 const lowerLT = (a, b, options) => {
8819 const comp = compare(a.semver, b.semver, options)
8822 : b.operator === '<' && a.operator === '<=' ? b
8826 module.exports = subset
8831 /***/ (function(module, exports, __webpack_require__) {
8835 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8836 if (k2 === undefined) k2 = k;
8837 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
8838 }) : (function(o, m, k, k2) {
8839 if (k2 === undefined) k2 = k;
8842 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
8843 Object.defineProperty(o, "default", { enumerable: true, value: v });
8844 }) : function(o, v) {
8847 var __importStar = (this && this.__importStar) || function (mod) {
8848 if (mod && mod.__esModule) return mod;
8850 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
8851 __setModuleDefault(result, mod);
8854 Object.defineProperty(exports, "__esModule", { value: true });
8855 exports.applyCodeActionCommands = exports.applyCodeAction = exports.getEditForCodeAction = void 0;
8856 /*---------------------------------------------------------------------------------------------
8857 * Copyright (c) Microsoft Corporation. All rights reserved.
8858 * Licensed under the MIT License. See License.txt in the project root for license information.
8859 *--------------------------------------------------------------------------------------------*/
8860 const vscode_languageserver_protocol_1 = __webpack_require__(3);
8861 const coc_nvim_1 = __webpack_require__(1);
8862 const typeConverters = __importStar(__webpack_require__(37));
8863 function getEditForCodeAction(client, action) {
8864 return action.changes && action.changes.length
8865 ? typeConverters.WorkspaceEdit.fromFileCodeEdits(client, action.changes)
8868 exports.getEditForCodeAction = getEditForCodeAction;
8869 async function applyCodeAction(client, action) {
8870 const workspaceEdit = getEditForCodeAction(client, action);
8871 if (workspaceEdit) {
8872 if (!(await coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
8876 return applyCodeActionCommands(client, action);
8878 exports.applyCodeAction = applyCodeAction;
8879 async function applyCodeActionCommands(client, action) {
8880 // make sure there is command
8881 if (action.commands && action.commands.length) {
8882 for (const command of action.commands) {
8883 const response = await client.execute('applyCodeActionCommand', { command }, vscode_languageserver_protocol_1.CancellationToken.None);
8884 if (!response || response.type != 'response' || !response.body) {
8891 exports.applyCodeActionCommands = applyCodeActionCommands;
8896 /***/ (function(module, exports, __webpack_require__) {
8900 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8901 if (k2 === undefined) k2 = k;
8902 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
8903 }) : (function(o, m, k, k2) {
8904 if (k2 === undefined) k2 = k;
8907 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
8908 Object.defineProperty(o, "default", { enumerable: true, value: v });
8909 }) : function(o, v) {
8912 var __importStar = (this && this.__importStar) || function (mod) {
8913 if (mod && mod.__esModule) return mod;
8915 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
8916 __setModuleDefault(result, mod);
8919 Object.defineProperty(exports, "__esModule", { value: true });
8920 exports.getParameterListParts = exports.convertCompletionEntry = void 0;
8921 /*---------------------------------------------------------------------------------------------
8922 * Copyright (c) Microsoft Corporation. All rights reserved.
8923 * Licensed under the MIT License. See License.txt in the project root for license information.
8924 *--------------------------------------------------------------------------------------------*/
8925 const vscode_languageserver_protocol_1 = __webpack_require__(3);
8926 const PConst = __importStar(__webpack_require__(39));
8927 function convertCompletionEntry(tsEntry, uri, position, context) {
8928 let label = tsEntry.name;
8929 let sortText = tsEntry.sortText;
8930 let preselect = false;
8932 if (tsEntry.isRecommended) {
8935 if (tsEntry.source) {
8936 // De-prioritze auto-imports https://github.com/Microsoft/vscode/issues/40311
8937 sortText = '\uffff' + sortText;
8940 sortText = tsEntry.sortText;
8942 let kind = convertKind(tsEntry.kind);
8943 let insertTextFormat = (context.enableCallCompletions &&
8944 (kind === vscode_languageserver_protocol_1.CompletionItemKind.Function ||
8945 kind === vscode_languageserver_protocol_1.CompletionItemKind.Method)) ? vscode_languageserver_protocol_1.InsertTextFormat.Snippet : vscode_languageserver_protocol_1.InsertTextFormat.PlainText;
8946 let insertText = tsEntry.insertText;
8947 let commitCharacters = getCommitCharacters(tsEntry, context);
8948 let textEdit = null;
8949 if (tsEntry.replacementSpan) {
8950 let { start, end } = tsEntry.replacementSpan;
8951 if (start.line == end.line) {
8953 range: vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1),
8954 newText: insertText || label
8958 if (tsEntry.kindModifiers) {
8959 const kindModifiers = new Set(tsEntry.kindModifiers.split(/,|\s+/g));
8960 if (kindModifiers.has(PConst.KindModifiers.optional)) {
8964 if (kindModifiers.has(PConst.KindModifiers.color)) {
8965 kind = vscode_languageserver_protocol_1.CompletionItemKind.Color;
8967 if (tsEntry.kind === PConst.Kind.script) {
8968 for (const extModifier of PConst.KindModifiers.fileExtensionKindModifiers) {
8969 if (kindModifiers.has(extModifier)) {
8970 if (tsEntry.name.toLowerCase().endsWith(extModifier)) {
8971 detail = tsEntry.name;
8974 detail = tsEntry.name + extModifier;
8995 source: tsEntry.source || ''
8999 exports.convertCompletionEntry = convertCompletionEntry;
9000 function convertKind(kind) {
9002 case PConst.Kind.primitiveType:
9003 case PConst.Kind.keyword:
9004 return vscode_languageserver_protocol_1.CompletionItemKind.Keyword;
9005 case PConst.Kind.const:
9006 return vscode_languageserver_protocol_1.CompletionItemKind.Constant;
9007 case PConst.Kind.let:
9008 case PConst.Kind.variable:
9009 case PConst.Kind.localVariable:
9010 case PConst.Kind.alias:
9011 return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
9012 case PConst.Kind.memberVariable:
9013 case PConst.Kind.memberGetAccessor:
9014 case PConst.Kind.memberSetAccessor:
9015 return vscode_languageserver_protocol_1.CompletionItemKind.Field;
9016 case PConst.Kind.function:
9017 return vscode_languageserver_protocol_1.CompletionItemKind.Function;
9018 case PConst.Kind.method:
9019 case PConst.Kind.constructSignature:
9020 case PConst.Kind.callSignature:
9021 case PConst.Kind.indexSignature:
9022 return vscode_languageserver_protocol_1.CompletionItemKind.Method;
9023 case PConst.Kind.enum:
9024 return vscode_languageserver_protocol_1.CompletionItemKind.Enum;
9025 case PConst.Kind.module:
9026 case PConst.Kind.externalModuleName:
9027 return vscode_languageserver_protocol_1.CompletionItemKind.Module;
9028 case PConst.Kind.class:
9029 case PConst.Kind.type:
9030 return vscode_languageserver_protocol_1.CompletionItemKind.Class;
9031 case PConst.Kind.interface:
9032 return vscode_languageserver_protocol_1.CompletionItemKind.Interface;
9033 case PConst.Kind.warning:
9034 case PConst.Kind.script:
9035 return vscode_languageserver_protocol_1.CompletionItemKind.File;
9036 case PConst.Kind.directory:
9037 return vscode_languageserver_protocol_1.CompletionItemKind.Folder;
9039 return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
9041 function getCommitCharacters(tsEntry, context) {
9042 if (context.isNewIdentifierLocation || !context.isInValidCommitCharacterContext) {
9045 const commitCharacters = [];
9046 switch (tsEntry.kind) {
9047 case PConst.Kind.memberGetAccessor:
9048 case PConst.Kind.memberSetAccessor:
9049 case PConst.Kind.constructSignature:
9050 case PConst.Kind.callSignature:
9051 case PConst.Kind.indexSignature:
9052 case PConst.Kind.enum:
9053 case PConst.Kind.interface:
9054 commitCharacters.push('.', ';');
9056 case PConst.Kind.module:
9057 case PConst.Kind.alias:
9058 case PConst.Kind.const:
9059 case PConst.Kind.let:
9060 case PConst.Kind.variable:
9061 case PConst.Kind.localVariable:
9062 case PConst.Kind.memberVariable:
9063 case PConst.Kind.class:
9064 case PConst.Kind.function:
9065 case PConst.Kind.method:
9066 case PConst.Kind.keyword:
9067 case PConst.Kind.parameter:
9068 commitCharacters.push('.', ',', ';');
9069 if (context.enableCallCompletions) {
9070 commitCharacters.push('(');
9074 return commitCharacters.length === 0 ? undefined : commitCharacters;
9076 function getParameterListParts(displayParts) {
9078 let isInMethod = false;
9079 let hasOptionalParameters = false;
9082 outer: for (let i = 0; i < displayParts.length; ++i) {
9083 const part = displayParts[i];
9084 switch (part.kind) {
9085 case PConst.DisplayPartKind.methodName:
9086 case PConst.DisplayPartKind.functionName:
9087 case PConst.DisplayPartKind.text:
9088 case PConst.DisplayPartKind.propertyName:
9089 if (parenCount === 0 && braceCount === 0) {
9093 case PConst.DisplayPartKind.parameterName:
9094 if (parenCount === 1 && braceCount === 0 && isInMethod) {
9095 // Only take top level paren names
9096 const next = displayParts[i + 1];
9097 // Skip optional parameters
9098 const nameIsFollowedByOptionalIndicator = next && next.text === '?';
9099 // Skip this parameter
9100 const nameIsThis = part.text === 'this';
9101 if (!nameIsFollowedByOptionalIndicator && !nameIsThis) {
9104 hasOptionalParameters = hasOptionalParameters || nameIsFollowedByOptionalIndicator;
9107 case PConst.DisplayPartKind.punctuation:
9108 if (part.text === '(') {
9111 else if (part.text === ')') {
9113 if (parenCount <= 0 && isInMethod) {
9117 else if (part.text === '...' && parenCount === 1) {
9118 // Found rest parmeter. Do not fill in any further arguments
9119 hasOptionalParameters = true;
9122 else if (part.text === '{') {
9125 else if (part.text === '}') {
9131 return { hasOptionalParameters, parts };
9133 exports.getParameterListParts = getParameterListParts;
9138 /***/ (function(module, exports, __webpack_require__) {
9142 /*---------------------------------------------------------------------------------------------
9143 * Copyright (c) Microsoft Corporation. All rights reserved.
9144 * Licensed under the MIT License. See License.txt in the project root for license information.
9145 *--------------------------------------------------------------------------------------------*/
9146 Object.defineProperty(exports, "__esModule", { value: true });
9147 exports.markdownDocumentation = exports.tagsMarkdownPreview = exports.plain = void 0;
9148 const vscode_languageserver_protocol_1 = __webpack_require__(3);
9149 function getTagBodyText(tag) {
9156 // Convert to markdown code block if it not already one
9157 if (tag.text.match(/^\s*[~`]{3}/g)) {
9160 return '```\n' + tag.text + '\n```';
9164 function getTagDocumentation(tag) {
9167 const body = (tag.text || '').split(/^([\w\.]+)\s*/);
9168 if (body && body.length === 3) {
9169 const param = body[1];
9170 const doc = body[2];
9171 const label = `*@${tag.name}* \`${param}\``;
9175 return label + (doc.match(/\r\n|\n/g) ? '\n' + doc : ` — ${doc}`);
9179 const label = `*@${tag.name}*`;
9180 const text = getTagBodyText(tag);
9184 return label + (text.match(/\r\n|\n/g) ? '\n' + text : ` — ${text}`);
9186 function plain(parts) {
9187 if (!parts || !parts.length)
9189 return parts.map(part => part.text).join('');
9191 exports.plain = plain;
9192 function tagsMarkdownPreview(tags) {
9193 return (tags || []).map(getTagDocumentation).join(' \n\n');
9195 exports.tagsMarkdownPreview = tagsMarkdownPreview;
9196 function markdownDocumentation(documentation, tags) {
9197 let out = plain(documentation);
9198 const tagsPreview = tagsMarkdownPreview(tags);
9200 out = out + ('\n\n' + tagsPreview);
9203 kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
9207 exports.markdownDocumentation = markdownDocumentation;
9212 /***/ (function(module, exports, __webpack_require__) {
9216 Object.defineProperty(exports, "__esModule", { value: true });
9217 class SnippetString {
9218 constructor(value) {
9220 this.value = value || '';
9222 static isSnippetString(thing) {
9223 if (thing instanceof SnippetString) {
9229 return typeof thing.value === 'string';
9231 static _escape(value) {
9232 return value.replace(/\$|}|\\/g, '\\$&');
9235 this.value += SnippetString._escape(str);
9238 appendTabstop(n = this._tabstop++) {
9243 appendPlaceholder(value, n = this._tabstop++) {
9244 if (typeof value === 'function') {
9245 const nested = new SnippetString();
9246 nested._tabstop = this._tabstop;
9248 this._tabstop = nested._tabstop;
9249 value = nested.value;
9252 value = SnippetString._escape(value);
9257 this.value += value;
9261 appendVariable(name, defaultValue) {
9262 if (typeof defaultValue === 'function') {
9263 const nested = new SnippetString();
9264 nested._tabstop = this._tabstop;
9265 defaultValue(nested);
9266 this._tabstop = nested._tabstop;
9267 defaultValue = nested.value;
9269 else if (typeof defaultValue === 'string') {
9270 defaultValue = defaultValue.replace(/\$|}/g, '\\$&');
9276 this.value += defaultValue;
9282 exports.default = SnippetString;
9287 /***/ (function(module, exports, __webpack_require__) {
9291 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9292 if (k2 === undefined) k2 = k;
9293 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9294 }) : (function(o, m, k, k2) {
9295 if (k2 === undefined) k2 = k;
9298 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9299 Object.defineProperty(o, "default", { enumerable: true, value: v });
9300 }) : function(o, v) {
9303 var __importStar = (this && this.__importStar) || function (mod) {
9304 if (mod && mod.__esModule) return mod;
9306 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9307 __setModuleDefault(result, mod);
9310 Object.defineProperty(exports, "__esModule", { value: true });
9311 const typeConverters = __importStar(__webpack_require__(37));
9312 class TypeScriptDefinitionProvider {
9313 constructor(client) {
9314 this.client = client;
9316 async getSymbolLocations(definitionType, document, position, token) {
9317 const filepath = this.client.toPath(document.uri);
9321 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
9323 const response = await this.client.execute(definitionType, args, token);
9324 const locations = (response.type == 'response' && response.body) || [];
9325 return locations.map(location => typeConverters.Location.fromTextSpan(this.client.toResource(location.file), location));
9331 provideDefinition(document, position, token) {
9332 return this.getSymbolLocations('definition', document, position, token);
9334 provideTypeDefinition(document, position, token) {
9335 return this.getSymbolLocations('typeDefinition', document, position, token);
9337 provideImplementation(document, position, token) {
9338 return this.getSymbolLocations('implementation', document, position, token);
9341 exports.default = TypeScriptDefinitionProvider;
9346 /***/ (function(module, exports, __webpack_require__) {
9350 var __importDefault = (this && this.__importDefault) || function (mod) {
9351 return (mod && mod.__esModule) ? mod : { "default": mod };
9353 Object.defineProperty(exports, "__esModule", { value: true });
9354 /*---------------------------------------------------------------------------------------------
9355 * Copyright (c) Microsoft Corporation. All rights reserved.
9356 * Licensed under the MIT License. See License.txt in the project root for license information.
9357 *--------------------------------------------------------------------------------------------*/
9358 const vscode_languageserver_protocol_1 = __webpack_require__(3);
9359 const coc_nvim_1 = __webpack_require__(1);
9360 const api_1 = __importDefault(__webpack_require__(40));
9361 const tsDirectives = [
9364 description: 'Enables semantic checking in a JavaScript file. Must be at the top of a file.'
9367 value: '@ts-nocheck',
9368 description: 'Disables semantic checking in a JavaScript file. Must be at the top of a file.'
9371 value: '@ts-ignore',
9372 description: 'Suppresses @ts-check errors on the next line of a file.'
9375 const tsDirectives390 = [
9378 value: '@ts-expect-error',
9379 description: 'Suppresses @ts-check errors on the next line of a file, expecting at least one to exist.'
9382 class DirectiveCommentCompletionProvider {
9383 constructor(client) {
9384 this.client = client;
9386 provideCompletionItems(document, position, _token, context) {
9387 if (context.triggerCharacter != '@') {
9390 const file = this.client.toPath(document.uri);
9394 const doc = coc_nvim_1.workspace.getDocument(document.uri);
9395 const line = doc.getline(position.line);
9396 const prefix = line.slice(0, position.character);
9397 const match = prefix.match(/^\s*\/\/+\s?(@[a-zA-Z\-]*)?$/);
9399 const directives = this.client.apiVersion.gte(api_1.default.v390)
9402 let items = directives.map(directive => {
9403 const item = vscode_languageserver_protocol_1.CompletionItem.create(directive.value);
9404 item.kind = vscode_languageserver_protocol_1.CompletionItemKind.Snippet;
9405 item.detail = directive.description;
9407 range: vscode_languageserver_protocol_1.Range.create(position.line, Math.max(0, position.character - (match[1] ? match[1].length : 0)), position.line, position.character),
9408 newText: directive.value
9413 isIncomplete: false,
9416 res.startcol = doc.fixStartcol(position, ['@']);
9422 exports.default = DirectiveCommentCompletionProvider;
9427 /***/ (function(module, exports, __webpack_require__) {
9431 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9432 if (k2 === undefined) k2 = k;
9433 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9434 }) : (function(o, m, k, k2) {
9435 if (k2 === undefined) k2 = k;
9438 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9439 Object.defineProperty(o, "default", { enumerable: true, value: v });
9440 }) : function(o, v) {
9443 var __importStar = (this && this.__importStar) || function (mod) {
9444 if (mod && mod.__esModule) return mod;
9446 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9447 __setModuleDefault(result, mod);
9450 Object.defineProperty(exports, "__esModule", { value: true });
9451 /*---------------------------------------------------------------------------------------------
9452 * Copyright (c) Microsoft Corporation. All rights reserved.
9453 * Licensed under the MIT License. See License.txt in the project root for license information.
9454 *--------------------------------------------------------------------------------------------*/
9455 const vscode_languageserver_protocol_1 = __webpack_require__(3);
9456 const typeConverters = __importStar(__webpack_require__(37));
9457 const arrays_1 = __webpack_require__(91);
9458 class TypeScriptDocumentHighlightProvider {
9459 constructor(client) {
9460 this.client = client;
9462 async provideDocumentHighlights(resource, position, token) {
9463 const file = this.client.toPath(resource.uri);
9466 const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { filesToSearch: [file] });
9468 const response = await this.client.execute('documentHighlights', args, token);
9469 if (response.type !== 'response' || !response.body) {
9472 return arrays_1.flatten(response.body
9473 .filter(highlight => highlight.file === file)
9474 .map(convertDocumentHighlight));
9481 exports.default = TypeScriptDocumentHighlightProvider;
9482 function convertDocumentHighlight(highlight) {
9483 return highlight.highlightSpans.map(span => {
9485 range: typeConverters.Range.fromTextSpan(span),
9486 kind: span.kind === 'writtenReference' ? vscode_languageserver_protocol_1.DocumentHighlightKind.Write : vscode_languageserver_protocol_1.DocumentHighlightKind.Read
9494 /***/ (function(module, exports, __webpack_require__) {
9498 Object.defineProperty(exports, "__esModule", { value: true });
9499 exports.flatten = exports.equals = void 0;
9500 /*---------------------------------------------------------------------------------------------
9501 * Copyright (c) Microsoft Corporation. All rights reserved.
9502 * Licensed under the MIT License. See License.txt in the project root for license information.
9503 *--------------------------------------------------------------------------------------------*/
9504 function equals(one, other, itemEquals = (a, b) => a === b) {
9505 if (one.length !== other.length) {
9508 for (let i = 0, len = one.length; i < len; i++) {
9509 if (!itemEquals(one[i], other[i])) {
9515 exports.equals = equals;
9516 function flatten(arr) {
9517 return [].concat.apply([], arr);
9519 exports.flatten = flatten;
9524 /***/ (function(module, exports, __webpack_require__) {
9528 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9529 if (k2 === undefined) k2 = k;
9530 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9531 }) : (function(o, m, k, k2) {
9532 if (k2 === undefined) k2 = k;
9535 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9536 Object.defineProperty(o, "default", { enumerable: true, value: v });
9537 }) : function(o, v) {
9540 var __importStar = (this && this.__importStar) || function (mod) {
9541 if (mod && mod.__esModule) return mod;
9543 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9544 __setModuleDefault(result, mod);
9547 Object.defineProperty(exports, "__esModule", { value: true });
9548 /*---------------------------------------------------------------------------------------------
9549 * Copyright (c) Microsoft Corporation. All rights reserved.
9550 * Licensed under the MIT License. See License.txt in the project root for license information.
9551 *--------------------------------------------------------------------------------------------*/
9552 const vscode_languageserver_protocol_1 = __webpack_require__(3);
9553 const PConst = __importStar(__webpack_require__(39));
9554 const typeConverters = __importStar(__webpack_require__(37));
9555 const getSymbolKind = (kind) => {
9557 case PConst.Kind.module:
9558 return vscode_languageserver_protocol_1.SymbolKind.Module;
9559 case PConst.Kind.class:
9560 return vscode_languageserver_protocol_1.SymbolKind.Class;
9561 case PConst.Kind.enum:
9562 return vscode_languageserver_protocol_1.SymbolKind.Enum;
9563 case PConst.Kind.interface:
9564 return vscode_languageserver_protocol_1.SymbolKind.Interface;
9565 case PConst.Kind.method:
9566 return vscode_languageserver_protocol_1.SymbolKind.Method;
9567 case PConst.Kind.memberVariable:
9568 return vscode_languageserver_protocol_1.SymbolKind.Property;
9569 case PConst.Kind.memberGetAccessor:
9570 return vscode_languageserver_protocol_1.SymbolKind.Property;
9571 case PConst.Kind.memberSetAccessor:
9572 return vscode_languageserver_protocol_1.SymbolKind.Property;
9573 case PConst.Kind.variable:
9574 return vscode_languageserver_protocol_1.SymbolKind.Variable;
9575 case PConst.Kind.const:
9576 return vscode_languageserver_protocol_1.SymbolKind.Variable;
9577 case PConst.Kind.localVariable:
9578 return vscode_languageserver_protocol_1.SymbolKind.Variable;
9579 case PConst.Kind.variable:
9580 return vscode_languageserver_protocol_1.SymbolKind.Variable;
9581 case PConst.Kind.constructSignature:
9582 case PConst.Kind.constructorImplementation:
9583 case PConst.Kind.function:
9584 case PConst.Kind.localFunction:
9585 return vscode_languageserver_protocol_1.SymbolKind.Function;
9587 return vscode_languageserver_protocol_1.SymbolKind.Variable;
9589 class TypeScriptDocumentSymbolProvider {
9590 constructor(client) {
9591 this.client = client;
9593 async provideDocumentSymbols(resource, token) {
9594 const filepath = this.client.toPath(resource.uri);
9601 const response = await this.client.execute('navtree', args, token);
9602 if (response.type == 'response' && response.body) {
9603 // The root represents the file. Ignore this when showing in the UI
9604 const tree = response.body;
9605 if (tree.childItems) {
9606 const result = new Array();
9607 tree.childItems.forEach(item => TypeScriptDocumentSymbolProvider.convertNavTree(result, item));
9617 static convertNavTree(bucket, item) {
9618 let shouldInclude = TypeScriptDocumentSymbolProvider.shouldInclueEntry(item);
9619 const children = new Set(item.childItems || []);
9620 for (const span of item.spans) {
9621 const range = typeConverters.Range.fromTextSpan(span);
9622 const symbolInfo = vscode_languageserver_protocol_1.DocumentSymbol.create(item.text, '', getSymbolKind(item.kind), range, range);
9623 symbolInfo.children = children.size > 0 ? [] : null;
9624 for (const child of children) {
9625 if (child.spans.some(span => !!containsRange(range, typeConverters.Range.fromTextSpan(span)))) {
9626 const includedChild = TypeScriptDocumentSymbolProvider.convertNavTree(symbolInfo.children, child);
9627 shouldInclude = shouldInclude || includedChild;
9628 children.delete(child);
9631 if (shouldInclude) {
9632 bucket.push(symbolInfo);
9635 return shouldInclude;
9637 static shouldInclueEntry(item) {
9638 if (item.kind === PConst.Kind.alias) {
9641 return !!(item.text &&
9642 item.text !== '<function>' &&
9643 item.text !== '<class>');
9646 exports.default = TypeScriptDocumentSymbolProvider;
9647 function containsRange(range, otherRange) {
9648 if (otherRange.start.line < range.start.line || otherRange.end.line < range.start.line) {
9651 if (otherRange.start.line > range.end.line || otherRange.end.line > range.end.line) {
9654 if (otherRange.start.line === range.start.line && otherRange.start.character < range.start.character) {
9657 if (otherRange.end.line === range.end.line && otherRange.end.character > range.end.character) {
9666 /***/ (function(module, exports, __webpack_require__) {
9670 /*---------------------------------------------------------------------------------------------
9671 * Copyright (c) Microsoft Corporation. All rights reserved.
9672 * Licensed under the MIT License. See License.txt in the project root for license information.
9673 *--------------------------------------------------------------------------------------------*/
9674 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9675 if (k2 === undefined) k2 = k;
9676 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9677 }) : (function(o, m, k, k2) {
9678 if (k2 === undefined) k2 = k;
9681 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9682 Object.defineProperty(o, "default", { enumerable: true, value: v });
9683 }) : function(o, v) {
9686 var __importStar = (this && this.__importStar) || function (mod) {
9687 if (mod && mod.__esModule) return mod;
9689 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9690 __setModuleDefault(result, mod);
9693 Object.defineProperty(exports, "__esModule", { value: true });
9694 const vscode_languageserver_types_1 = __webpack_require__(18);
9695 const coc_nvim_1 = __webpack_require__(1);
9696 const typeConverters = __importStar(__webpack_require__(37));
9697 class TypeScriptFoldingProvider {
9698 constructor(client) {
9699 this.client = client;
9701 async provideFoldingRanges(document, _context, token) {
9702 const file = this.client.toPath(document.uri);
9706 const args = { file };
9707 const res = await this.client.execute('getOutliningSpans', args, token);
9708 if (res.type != 'response') {
9711 const { body } = res;
9716 .map(span => this.convertOutliningSpan(span, document))
9717 .filter(foldingRange => !!foldingRange);
9719 convertOutliningSpan(span, document) {
9720 const range = typeConverters.Range.fromTextSpan(span.textSpan);
9721 const kind = TypeScriptFoldingProvider.getFoldingRangeKind(span);
9722 // Workaround for #49904
9723 if (span.kind === 'comment') {
9724 let doc = coc_nvim_1.workspace.getDocument(document.uri);
9725 const line = doc.getline(range.start.line);
9726 if (line.match(/\/\/\s*#endregion/gi)) {
9730 let { start, end } = range;
9731 return vscode_languageserver_types_1.FoldingRange.create(start.line, end.line, start.character, end.character, kind);
9733 static getFoldingRangeKind(span) {
9734 switch (span.kind) {
9745 exports.default = TypeScriptFoldingProvider;
9750 /***/ (function(module, exports, __webpack_require__) {
9754 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9755 if (k2 === undefined) k2 = k;
9756 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9757 }) : (function(o, m, k, k2) {
9758 if (k2 === undefined) k2 = k;
9761 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9762 Object.defineProperty(o, "default", { enumerable: true, value: v });
9763 }) : function(o, v) {
9766 var __importStar = (this && this.__importStar) || function (mod) {
9767 if (mod && mod.__esModule) return mod;
9769 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9770 __setModuleDefault(result, mod);
9773 Object.defineProperty(exports, "__esModule", { value: true });
9774 /*---------------------------------------------------------------------------------------------
9775 * Copyright (c) Microsoft Corporation. All rights reserved.
9776 * Licensed under the MIT License. See License.txt in the project root for license information.
9777 *--------------------------------------------------------------------------------------------*/
9778 const coc_nvim_1 = __webpack_require__(1);
9779 const typeConverters = __importStar(__webpack_require__(37));
9780 class TypeScriptFormattingProvider {
9781 constructor(client, formattingOptionsManager) {
9782 this.client = client;
9783 this.formattingOptionsManager = formattingOptionsManager;
9786 return this.formattingOptionsManager.formatEnabled(document);
9788 async doFormat(document, options, args, token) {
9789 if (!this.enabled(document))
9791 await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token);
9793 const response = await this.client.execute('format', args, token);
9794 if (response.type == 'response' && response.body) {
9795 let edits = response.body.map(typeConverters.TextEdit.fromCodeEdit);
9804 async provideDocumentRangeFormattingEdits(document, range, options, token) {
9805 if (!this.enabled(document))
9807 const filepath = this.client.toPath(document.uri);
9812 line: range.start.line + 1,
9813 offset: range.start.character + 1,
9814 endLine: range.end.line + 1,
9815 endOffset: range.end.character + 1
9817 return this.doFormat(document, options, args, token);
9819 async provideDocumentFormattingEdits(document, options, token) {
9820 if (!this.enabled(document))
9822 const filepath = this.client.toPath(document.uri);
9829 endLine: document.lineCount + 1,
9832 return this.doFormat(document, options, args, token);
9834 async provideOnTypeFormattingEdits(document, position, ch, options, token) {
9835 if (!this.enabled(document))
9837 if (!this.client.configuration.formatOnType)
9839 const file = this.client.toPath(document.uri);
9842 await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token);
9843 const doc = coc_nvim_1.workspace.getDocument(document.uri);
9844 const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { key: ch });
9846 const res = await this.client.execute('formatonkey', args, token);
9847 if (res.type != 'response') {
9850 const { body } = res;
9856 for (const edit of edits) {
9857 const textEdit = typeConverters.TextEdit.fromCodeEdit(edit);
9858 const range = textEdit.range;
9859 // Work around for https://github.com/Microsoft/TypeScript/issues/6700.
9860 // Check if we have an edit at the beginning of the line which only removes white spaces and leaves
9861 // an empty line. Drop those edits
9862 if (range.start.character === 0 &&
9863 range.start.line === range.end.line &&
9864 textEdit.newText === '') {
9865 const lText = doc.getline(range.start.line);
9866 // If the edit leaves something on the line keep the edit (note that the end character is exclusive).
9867 // Keep it also if it removes something else than whitespace
9868 if (lText.trim().length > 0 || lText.length > range.end.character) {
9869 result.push(textEdit);
9873 result.push(textEdit);
9884 exports.default = TypeScriptFormattingProvider;
9889 /***/ (function(module, exports, __webpack_require__) {
9893 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9894 if (k2 === undefined) k2 = k;
9895 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9896 }) : (function(o, m, k, k2) {
9897 if (k2 === undefined) k2 = k;
9900 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9901 Object.defineProperty(o, "default", { enumerable: true, value: v });
9902 }) : function(o, v) {
9905 var __importStar = (this && this.__importStar) || function (mod) {
9906 if (mod && mod.__esModule) return mod;
9908 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9909 __setModuleDefault(result, mod);
9912 Object.defineProperty(exports, "__esModule", { value: true });
9913 const previewer_1 = __webpack_require__(86);
9914 const typeConverters = __importStar(__webpack_require__(37));
9915 class TypeScriptHoverProvider {
9916 constructor(client) {
9917 this.client = client;
9919 async provideHover(document, position, token) {
9920 const filepath = this.client.toPath(document.uri);
9924 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
9926 const response = await this.client.interruptGetErr(() => this.client.execute('quickinfo', args, token));
9927 if (response && response.type == 'response' && response.body) {
9928 const data = response.body;
9930 contents: TypeScriptHoverProvider.getContents(data),
9931 range: typeConverters.Range.fromTextSpan(data)
9940 static getContents(data) {
9942 if (data.displayString) {
9943 parts.push({ language: 'typescript', value: data.displayString });
9945 const tags = previewer_1.tagsMarkdownPreview(data.tags);
9946 parts.push(data.documentation + (tags ? '\n\n' + tags : ''));
9950 exports.default = TypeScriptHoverProvider;
9955 /***/ (function(module, exports, __webpack_require__) {
9959 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9960 if (k2 === undefined) k2 = k;
9961 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9962 }) : (function(o, m, k, k2) {
9963 if (k2 === undefined) k2 = k;
9966 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9967 Object.defineProperty(o, "default", { enumerable: true, value: v });
9968 }) : function(o, v) {
9971 var __importStar = (this && this.__importStar) || function (mod) {
9972 if (mod && mod.__esModule) return mod;
9974 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9975 __setModuleDefault(result, mod);
9978 Object.defineProperty(exports, "__esModule", { value: true });
9979 const PConst = __importStar(__webpack_require__(39));
9980 const typeConverters = __importStar(__webpack_require__(37));
9981 const baseCodeLensProvider_1 = __webpack_require__(35);
9982 class TypeScriptImplementationsCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
9983 async resolveCodeLens(codeLens, token) {
9984 let { uri } = codeLens.data;
9985 let filepath = this.client.toPath(uri);
9986 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
9988 const response = await this.client.execute('implementation', args, token, { lowPriority: true });
9989 if (response && response.type == 'response' && response.body) {
9990 const locations = response.body
9993 uri: this.client.toResource(reference.file),
9995 start: typeConverters.Position.fromLocation(reference.start),
9997 line: reference.start.line,
10003 // Exclude original from implementations
10004 .filter(location => !(location.uri.toString() === uri &&
10005 location.range.start.line === codeLens.range.start.line &&
10006 location.range.start.character ===
10007 codeLens.range.start.character));
10008 codeLens.command = this.getCommand(locations, codeLens);
10015 codeLens.command = {
10016 title: '0 implementations',
10021 getCommand(locations, codeLens) {
10022 let { uri } = codeLens.data;
10024 title: this.getTitle(locations),
10025 command: locations.length ? 'editor.action.showReferences' : '',
10026 arguments: [uri, codeLens.range.start, locations]
10029 getTitle(locations) {
10030 return locations.length === 1 ? '1 implementation' : `${locations.length} implementations`;
10032 extractSymbol(document, item, _parent) {
10033 switch (item.kind) {
10034 case PConst.Kind.interface:
10035 return super.getSymbolRange(document, item);
10036 case PConst.Kind.class:
10037 case PConst.Kind.method:
10038 case PConst.Kind.memberVariable:
10039 case PConst.Kind.memberGetAccessor:
10040 case PConst.Kind.memberSetAccessor:
10041 if (item.kindModifiers.match(/\babstract\b/g)) {
10042 return super.getSymbolRange(document, item);
10049 exports.default = TypeScriptImplementationsCodeLensProvider;
10054 /***/ (function(module, exports, __webpack_require__) {
10058 Object.defineProperty(exports, "__esModule", { value: true });
10059 const coc_nvim_1 = __webpack_require__(1);
10060 const vscode_languageserver_protocol_1 = __webpack_require__(3);
10061 const helper_1 = __webpack_require__(98);
10062 class ImportFixProvider {
10063 constructor(bufferSyncSupport) {
10064 this.bufferSyncSupport = bufferSyncSupport;
10066 async provideCodeActions(document, _range, context, _token) {
10067 if (this.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
10070 let diagnostics = context.diagnostics.filter(d => d.code == 2304);
10071 if (!diagnostics.length)
10075 let doc = coc_nvim_1.workspace.getDocument(document.uri);
10077 for (const diagnostic of diagnostics) {
10078 let { range } = diagnostic;
10079 let line = doc.getline(range.start.line);
10080 let name = line.slice(range.start.character, range.end.character);
10081 if (names.indexOf(name) !== -1)
10083 if (helper_1.nodeModules.indexOf(name) !== -1) {
10086 range: vscode_languageserver_protocol_1.Range.create(0, 0, 0, 0),
10087 newText: `import ${name} from '${name}'\n`
10089 command = 'tsserver.organizeImports';
10094 [document.uri]: edits
10100 title: `fix import`,
10101 command: 'tsserver.organizeImports'
10104 title: `Add import ${names.join(', ')}`,
10110 exports.default = ImportFixProvider;
10115 /***/ (function(module, exports, __webpack_require__) {
10119 Object.defineProperty(exports, "__esModule", { value: true });
10120 exports.nodeModules = void 0;
10121 exports.nodeModules = [
10155 /***/ (function(module, exports, __webpack_require__) {
10159 Object.defineProperty(exports, "__esModule", { value: true });
10160 const coc_nvim_1 = __webpack_require__(1);
10161 const vscode_languageserver_protocol_1 = __webpack_require__(3);
10162 const modules_1 = __webpack_require__(100);
10163 class InstallModuleCommand {
10165 this.id = InstallModuleCommand.ID;
10167 async execute(uri, name) {
10168 await modules_1.installModules(uri, [name]);
10171 InstallModuleCommand.ID = '_tsserver.installModule';
10172 class InstallModuleProvider {
10173 constructor(client) {
10174 this.client = client;
10175 coc_nvim_1.commands.register(new InstallModuleCommand(), true);
10177 async provideCodeActions(document, _range, context, _token) {
10178 const uri = coc_nvim_1.Uri.parse(document.uri);
10179 if (uri.scheme != 'file')
10181 let { diagnostics } = context;
10182 let diags = diagnostics.filter(s => s.code == 2307);
10183 let names = diags.map(o => {
10184 let ms = o.message.match(/module\s'(.+)'/);
10185 return ms ? ms[1] : null;
10187 names = names.filter(s => s != null);
10191 for (let name of names) {
10192 let title = `install ${name}`;
10194 title: `install ${name}`,
10195 command: InstallModuleCommand.ID,
10196 arguments: [document.uri, name]
10198 let codeAction = vscode_languageserver_protocol_1.CodeAction.create(title, command, vscode_languageserver_protocol_1.CodeActionKind.QuickFix);
10199 actions.push(codeAction);
10204 exports.default = InstallModuleProvider;
10209 /***/ (function(module, exports, __webpack_require__) {
10213 var __importDefault = (this && this.__importDefault) || function (mod) {
10214 return (mod && mod.__esModule) ? mod : { "default": mod };
10216 Object.defineProperty(exports, "__esModule", { value: true });
10217 exports.installModules = exports.distinct = exports.moduleExists = exports.runCommand = void 0;
10218 const child_process_1 = __webpack_require__(101);
10219 const coc_nvim_1 = __webpack_require__(1);
10220 const fs_1 = __importDefault(__webpack_require__(102));
10221 const path_1 = __importDefault(__webpack_require__(13));
10222 function runCommand(cmd, cwd, timeout) {
10223 return new Promise((resolve, reject) => {
10226 timer = setTimeout(() => {
10227 reject(new Error(`timeout after ${timeout}s`));
10228 }, timeout * 1000);
10230 child_process_1.exec(cmd, { cwd }, (err, stdout) => {
10232 clearTimeout(timer);
10234 reject(new Error(`exited with ${err.code}`));
10241 exports.runCommand = runCommand;
10242 async function getManager() {
10243 let res = await coc_nvim_1.workspace.findUp(['yarn.lock', 'package-lock.json']);
10246 return res.endsWith('yarn.lock') ? 'yarn' : 'npm';
10248 async function getRoot() {
10249 let res = await coc_nvim_1.workspace.findUp(['package.json']);
10252 return path_1.default.dirname(res);
10254 async function moduleExists(name) {
10256 let content = await runCommand(`npm info ${name} --json`, process.cwd());
10259 let obj = JSON.parse(content);
10260 if (obj.error != null)
10269 exports.moduleExists = moduleExists;
10271 * Removes duplicates from the given array. The optional keyFn allows to specify
10272 * how elements are checked for equalness by returning a unique string for each.
10274 function distinct(array, keyFn) {
10276 return array.filter((element, position) => {
10277 return array.indexOf(element) === position;
10280 const seen = Object.create(null);
10281 return array.filter(elem => {
10282 const key = keyFn(elem);
10290 exports.distinct = distinct;
10291 async function installModules(uri, names) {
10292 names = distinct(names);
10293 let workspaceFolder = coc_nvim_1.workspace.getWorkspaceFolder(uri);
10294 let root = workspaceFolder ? coc_nvim_1.Uri.parse(workspaceFolder.uri).fsPath : undefined;
10295 if (!root || !fs_1.default.existsSync(path_1.default.join(root, 'package.json'))) {
10296 coc_nvim_1.workspace.showMessage(`package.json not found from workspaceFolder: ${root}`, 'error');
10299 let arr = names.concat(names.map(s => `@types/${s}`));
10300 let statusItem = coc_nvim_1.workspace.createStatusBarItem(99, { progress: true });
10301 statusItem.text = `Checking module ${arr.join(' ')}`;
10303 let exists = await Promise.all(arr.map(name => {
10304 return moduleExists(name).then(exists => {
10305 return exists ? name : null;
10308 let manager = await getManager();
10309 exists = exists.filter(s => s != null);
10310 if (!exists.length)
10312 let devs = exists.filter(s => s.startsWith('@types'));
10313 let deps = exists.filter(s => devs.indexOf(s) == -1);
10314 statusItem.text = `Installing ${exists.join(' ')}`;
10316 let cmd = manager == 'npm' ? `npm i ${deps.join(' ')}` : `yarn add ${deps.join(' ')}`;
10317 await runCommand(cmd, root);
10318 cmd = manager == 'npm' ? `npm i ${deps.join(' ')} --save-dev` : `yarn add ${deps.join(' ')} --save-dev`;
10319 await runCommand(cmd, root);
10322 statusItem.dispose();
10323 coc_nvim_1.workspace.showMessage(`Install error ${e.message}`, 'error');
10326 statusItem.dispose();
10327 coc_nvim_1.workspace.showMessage(`Installed: ${exists.join(' ')}`, 'more');
10329 exports.installModules = installModules;
10334 /***/ (function(module, exports) {
10336 module.exports = require("child_process");
10340 /***/ (function(module, exports) {
10342 module.exports = require("fs");
10346 /***/ (function(module, exports, __webpack_require__) {
10350 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10351 if (k2 === undefined) k2 = k;
10352 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10353 }) : (function(o, m, k, k2) {
10354 if (k2 === undefined) k2 = k;
10357 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10358 Object.defineProperty(o, "default", { enumerable: true, value: v });
10359 }) : function(o, v) {
10362 var __importStar = (this && this.__importStar) || function (mod) {
10363 if (mod && mod.__esModule) return mod;
10365 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10366 __setModuleDefault(result, mod);
10369 var __importDefault = (this && this.__importDefault) || function (mod) {
10370 return (mod && mod.__esModule) ? mod : { "default": mod };
10372 Object.defineProperty(exports, "__esModule", { value: true });
10373 /*---------------------------------------------------------------------------------------------
10374 * Copyright (c) Microsoft Corporation. All rights reserved.
10375 * Licensed under the MIT License. See License.txt in the project root for license information.
10376 *--------------------------------------------------------------------------------------------*/
10377 const coc_nvim_1 = __webpack_require__(1);
10378 const vscode_languageserver_protocol_1 = __webpack_require__(3);
10379 const api_1 = __importDefault(__webpack_require__(40));
10380 const codeAction_1 = __webpack_require__(84);
10381 const typeConverters = __importStar(__webpack_require__(37));
10382 class ApplyCodeActionCommand {
10383 constructor(client, formattingConfigurationManager) {
10384 this.client = client;
10385 this.formattingConfigurationManager = formattingConfigurationManager;
10386 this.id = ApplyCodeActionCommand.ID;
10388 async execute(action) {
10389 return codeAction_1.applyCodeActionCommands(this.client, action);
10392 ApplyCodeActionCommand.ID = '_typescript.applyCodeActionCommand';
10393 class ApplyFixAllCodeAction {
10394 constructor(client, formattingConfigurationManager) {
10395 this.client = client;
10396 this.formattingConfigurationManager = formattingConfigurationManager;
10397 this.id = ApplyFixAllCodeAction.ID;
10399 async execute(document, file, tsAction) {
10400 if (!tsAction.fixId) {
10403 await this.formattingConfigurationManager.ensureConfigurationForDocument(document, vscode_languageserver_protocol_1.CancellationToken.None);
10409 fixId: tsAction.fixId
10412 const res = await this.client.execute('getCombinedCodeFix', args, vscode_languageserver_protocol_1.CancellationToken.None);
10413 if (res.type != 'response') {
10416 let { body } = res;
10417 const edit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.changes);
10418 await coc_nvim_1.workspace.applyEdit(edit);
10419 const token = vscode_languageserver_protocol_1.CancellationToken.None;
10420 const { commands } = body;
10421 if (commands && commands.length) {
10422 for (const command of commands) {
10423 await this.client.execute('applyCodeActionCommand', { command }, token);
10432 ApplyFixAllCodeAction.ID = '_typescript.applyFixAllCodeAction';
10434 * Unique set of diagnostics keyed on diagnostic range and error code.
10436 class DiagnosticsSet {
10437 constructor(_values) {
10438 this._values = _values;
10440 static from(diagnostics) {
10441 const values = new Map();
10442 for (const diagnostic of diagnostics) {
10443 values.set(DiagnosticsSet.key(diagnostic), diagnostic);
10445 return new DiagnosticsSet(values);
10447 static key(diagnostic) {
10448 const { start, end } = diagnostic.range;
10449 return `${diagnostic.code}-${start.line},${start.character}-${end.line},${end.character}`;
10452 return this._values.values();
10455 class SupportedCodeActionProvider {
10456 constructor(client) {
10457 this.client = client;
10459 async getFixableDiagnosticsForContext(context) {
10460 const supportedActions = await this.supportedCodeActions;
10461 const fixableDiagnostics = DiagnosticsSet.from(context.diagnostics.filter(diagnostic => supportedActions.has(+diagnostic.code)));
10462 return Array.from(fixableDiagnostics.values);
10464 get supportedCodeActions() {
10465 if (!this._supportedCodeActions) {
10466 return new Promise((resolve, reject) => {
10467 this.client.execute('getSupportedCodeFixes', null, vscode_languageserver_protocol_1.CancellationToken.None).then(res => {
10468 if (res.type !== 'response') {
10469 resolve(new Set());
10472 let codes = res.body.map(code => +code).filter(code => !isNaN(code));
10473 resolve(new Set(codes));
10477 return Promise.resolve(this._supportedCodeActions);
10480 class TypeScriptQuickFixProvider {
10481 constructor(client, formattingConfigurationManager) {
10482 this.client = client;
10483 this.formattingConfigurationManager = formattingConfigurationManager;
10484 coc_nvim_1.commands.register(new ApplyCodeActionCommand(client, formattingConfigurationManager));
10485 coc_nvim_1.commands.register(new ApplyFixAllCodeAction(client, formattingConfigurationManager));
10486 this.supportedCodeActionProvider = new SupportedCodeActionProvider(client);
10488 async provideCodeActions(document, _range, context, token) {
10489 const file = this.client.toPath(document.uri);
10493 await this.formattingConfigurationManager.ensureConfigurationForDocument(document, token);
10494 const fixableDiagnostics = await this.supportedCodeActionProvider.getFixableDiagnosticsForContext(context);
10495 if (!fixableDiagnostics.length) {
10498 if (this.client.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
10501 const results = [];
10502 for (const diagnostic of fixableDiagnostics) {
10503 results.push(...(await this.getFixesForDiagnostic(document, file, diagnostic, token)));
10507 async getFixesForDiagnostic(document, file, diagnostic, token) {
10508 const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+diagnostic.code] });
10509 const codeFixesResponse = await this.client.execute('getCodeFixes', args, token);
10510 if (codeFixesResponse.type != 'response') {
10513 if (codeFixesResponse.body) {
10514 const results = [];
10515 for (const tsCodeFix of codeFixesResponse.body) {
10516 results.push(...(await this.getAllFixesForTsCodeAction(document, file, diagnostic, tsCodeFix)));
10522 async getAllFixesForTsCodeAction(document, file, diagnostic, tsAction) {
10523 const singleFix = this.getSingleFixForTsCodeAction(diagnostic, tsAction);
10524 const fixAll = await this.getFixAllForTsCodeAction(document, file, diagnostic, tsAction);
10525 return fixAll ? [singleFix, fixAll] : [singleFix];
10527 getSingleFixForTsCodeAction(diagnostic, tsAction) {
10528 const codeAction = {
10529 title: tsAction.description,
10530 kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
10532 codeAction.edit = codeAction_1.getEditForCodeAction(this.client, tsAction);
10533 codeAction.diagnostics = [diagnostic];
10534 codeAction.isPreferred = true;
10535 if (tsAction.commands) {
10536 codeAction.command = {
10537 command: ApplyCodeActionCommand.ID,
10538 arguments: [tsAction],
10539 title: tsAction.description
10544 async getFixAllForTsCodeAction(document, file, diagnostic, tsAction) {
10545 if (!tsAction.fixId || !this.client.apiVersion.gte(api_1.default.v270)) {
10548 // Make sure there are multiple diagnostics of the same type in the file
10549 if (!this.client.diagnosticsManager
10550 .getDiagnostics(document.uri)
10551 .some(x => x.code === diagnostic.code && x !== diagnostic)) {
10555 title: tsAction.fixAllDescription || 'Fix all in file',
10556 kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
10558 action.diagnostics = [diagnostic];
10560 command: ApplyFixAllCodeAction.ID,
10561 arguments: [document, file, tsAction],
10567 exports.default = TypeScriptQuickFixProvider;
10572 /***/ (function(module, exports, __webpack_require__) {
10576 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10577 if (k2 === undefined) k2 = k;
10578 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10579 }) : (function(o, m, k, k2) {
10580 if (k2 === undefined) k2 = k;
10583 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10584 Object.defineProperty(o, "default", { enumerable: true, value: v });
10585 }) : function(o, v) {
10588 var __importStar = (this && this.__importStar) || function (mod) {
10589 if (mod && mod.__esModule) return mod;
10591 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10592 __setModuleDefault(result, mod);
10595 Object.defineProperty(exports, "__esModule", { value: true });
10596 /*---------------------------------------------------------------------------------------------
10597 * Copyright (c) Microsoft Corporation. All rights reserved.
10598 * Licensed under the MIT License. See License.txt in the project root for license information.
10599 *--------------------------------------------------------------------------------------------*/
10600 const vscode_languageserver_protocol_1 = __webpack_require__(3);
10601 const coc_nvim_1 = __webpack_require__(1);
10602 const typeConverters = __importStar(__webpack_require__(37));
10603 class ApplyRefactoringCommand {
10604 constructor(client) {
10605 this.client = client;
10606 this.id = ApplyRefactoringCommand.ID;
10608 async execute(document, file, refactor, action, range) {
10609 const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, range)), { refactor,
10611 const response = await this.client.execute('getEditsForRefactor', args, vscode_languageserver_protocol_1.CancellationToken.None);
10612 const body = response && response.body;
10613 if (!body || !body.edits.length) {
10616 const workspaceEdit = await this.toWorkspaceEdit(body);
10617 if (!(await coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
10620 const renameLocation = body.renameLocation;
10621 if (renameLocation) {
10622 coc_nvim_1.commands.executeCommand('editor.action.rename', document.uri, typeConverters.Position.fromLocation(renameLocation));
10626 async toWorkspaceEdit(body) {
10627 for (const edit of body.edits) {
10628 await coc_nvim_1.workspace.createFile(edit.fileName, { ignoreIfExists: true });
10630 let workspaceEdit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.edits);
10631 return workspaceEdit;
10634 ApplyRefactoringCommand.ID = '_typescript.applyRefactoring';
10635 class SelectRefactorCommand {
10636 constructor(doRefactoring) {
10637 this.doRefactoring = doRefactoring;
10638 this.id = SelectRefactorCommand.ID;
10640 async execute(document, file, info, range) {
10641 let { actions } = info;
10642 const idx = actions.length == 1 ? 0 : await coc_nvim_1.workspace.showQuickpick(actions.map(action => action.description || action.name));
10645 let label = info.actions[idx].name;
10648 return this.doRefactoring.execute(document, file, info.name, label, range);
10651 SelectRefactorCommand.ID = '_typescript.selectRefactoring';
10652 class TypeScriptRefactorProvider {
10653 constructor(client, formattingOptionsManager) {
10654 this.client = client;
10655 this.formattingOptionsManager = formattingOptionsManager;
10656 const doRefactoringCommand = coc_nvim_1.commands.register(new ApplyRefactoringCommand(this.client));
10657 coc_nvim_1.commands.register(new SelectRefactorCommand(doRefactoringCommand));
10659 async provideCodeActions(document, range, context, token) {
10660 if (!this.shouldTrigger(context)) {
10663 const file = this.client.toPath(document.uri);
10666 await this.formattingOptionsManager.ensureConfigurationForDocument(document, token);
10667 const args = typeConverters.Range.toFileRangeRequestArgs(file, range);
10670 response = await this.client.interruptGetErr(() => {
10671 return this.client.execute('getApplicableRefactors', args, token);
10673 if (!response || !response.body) {
10680 return this.convertApplicableRefactors(response.body, document, file, range, context.only && context.only.some(v => v.includes(vscode_languageserver_protocol_1.CodeActionKind.Refactor)));
10682 convertApplicableRefactors(body, document, file, rangeOrSelection, setPrefrred) {
10683 const actions = [];
10684 for (const info of body) {
10685 // ignore not refactor that not applicable
10686 if (info.notApplicableReason)
10688 if (!info.inlineable) {
10689 const codeAction = {
10690 title: info.description,
10691 kind: vscode_languageserver_protocol_1.CodeActionKind.Refactor
10693 codeAction.command = {
10694 title: info.description,
10695 command: SelectRefactorCommand.ID,
10696 arguments: [document, file, info, rangeOrSelection]
10698 actions.push(codeAction);
10701 for (const action of info.actions) {
10702 let codeAction = this.refactorActionToCodeAction(action, document, file, info, rangeOrSelection);
10704 codeAction.isPreferred = TypeScriptRefactorProvider.isPreferred(action, info.actions);
10706 actions.push(codeAction);
10712 refactorActionToCodeAction(action, document, file, info, rangeOrSelection) {
10713 const codeAction = {
10714 title: action.description,
10715 kind: TypeScriptRefactorProvider.getKind(action)
10717 codeAction.command = {
10718 title: action.description,
10719 command: ApplyRefactoringCommand.ID,
10720 arguments: [document, file, info.name, action.name, rangeOrSelection]
10724 shouldTrigger(context) {
10725 if (context.only &&
10726 context.only.every(o => !o.includes(vscode_languageserver_protocol_1.CodeActionKind.Refactor))) {
10731 static getKind(refactor) {
10732 if (refactor.name.startsWith('function_')) {
10733 return TypeScriptRefactorProvider.extractFunctionKind;
10735 else if (refactor.name.startsWith('constant_')) {
10736 return TypeScriptRefactorProvider.extractConstantKind;
10738 else if (refactor.name.startsWith('Move')) {
10739 return TypeScriptRefactorProvider.moveKind;
10741 return vscode_languageserver_protocol_1.CodeActionKind.Refactor;
10743 static isPreferred(action, allActions) {
10744 let kind = TypeScriptRefactorProvider.getKind(action);
10745 if (TypeScriptRefactorProvider.extractConstantKind == kind) {
10746 // Only mark the action with the lowest scope as preferred
10747 const getScope = (name) => {
10749 const scope = (_a = name.match(/scope_(\d)/)) === null || _a === void 0 ? void 0 : _a[1];
10750 return scope ? +scope : undefined;
10752 const scope = getScope(action.name);
10753 if (typeof scope !== 'number') {
10757 .filter(otherAtion => otherAtion !== action && otherAtion.name.startsWith('constant_'))
10758 .every(otherAction => {
10759 const otherScope = getScope(otherAction.name);
10760 return typeof otherScope === 'number' ? scope < otherScope : true;
10763 let { name } = action;
10764 if (name.startsWith('Extract to type alias') || name.startsWith('Extract to interface')) {
10770 exports.default = TypeScriptRefactorProvider;
10771 TypeScriptRefactorProvider.extractFunctionKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.function';
10772 TypeScriptRefactorProvider.extractConstantKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.constant';
10773 TypeScriptRefactorProvider.moveKind = vscode_languageserver_protocol_1.CodeActionKind.Refactor + '.move';
10774 TypeScriptRefactorProvider.metadata = {
10775 providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.Refactor]
10781 /***/ (function(module, exports, __webpack_require__) {
10785 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10786 if (k2 === undefined) k2 = k;
10787 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10788 }) : (function(o, m, k, k2) {
10789 if (k2 === undefined) k2 = k;
10792 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10793 Object.defineProperty(o, "default", { enumerable: true, value: v });
10794 }) : function(o, v) {
10797 var __importStar = (this && this.__importStar) || function (mod) {
10798 if (mod && mod.__esModule) return mod;
10800 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10801 __setModuleDefault(result, mod);
10804 Object.defineProperty(exports, "__esModule", { value: true });
10805 const typeConverters = __importStar(__webpack_require__(37));
10806 class TypeScriptReferences {
10807 constructor(client) {
10808 this.client = client;
10810 async provideReferences(document, position, context, token) {
10811 const filepath = this.client.toPath(document.uri);
10814 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
10816 const msg = await this.client.execute('references', args, token);
10817 if (!msg || msg.type != 'response' || !msg.body) {
10821 for (const ref of msg.body.refs) {
10822 if (!context.includeDeclaration && ref.isDefinition) {
10825 const url = this.client.toResource(ref.file);
10826 const location = typeConverters.Location.fromTextSpan(url, ref);
10827 result.push(location);
10836 exports.default = TypeScriptReferences;
10841 /***/ (function(module, exports, __webpack_require__) {
10845 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10846 if (k2 === undefined) k2 = k;
10847 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10848 }) : (function(o, m, k, k2) {
10849 if (k2 === undefined) k2 = k;
10852 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10853 Object.defineProperty(o, "default", { enumerable: true, value: v });
10854 }) : function(o, v) {
10857 var __importStar = (this && this.__importStar) || function (mod) {
10858 if (mod && mod.__esModule) return mod;
10860 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10861 __setModuleDefault(result, mod);
10864 Object.defineProperty(exports, "__esModule", { value: true });
10865 const PConst = __importStar(__webpack_require__(39));
10866 const typeConverters = __importStar(__webpack_require__(37));
10867 const baseCodeLensProvider_1 = __webpack_require__(35);
10868 class TypeScriptReferencesCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
10869 resolveCodeLens(codeLens, token) {
10870 let { uri } = codeLens.data;
10871 let filepath = this.client.toPath(uri);
10872 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
10874 .execute('references', args, token, {
10877 .then(response => {
10878 if (!response || response.type != 'response' || !response.body) {
10881 const locations = response.body.refs
10882 .map(reference => typeConverters.Location.fromTextSpan(this.client.toResource(reference.file), reference))
10883 .filter(location =>
10884 // Exclude original definition from references
10885 !(location.uri.toString() === uri &&
10886 location.range.start.line === codeLens.range.start.line &&
10887 location.range.start.character ===
10888 codeLens.range.start.character));
10889 codeLens.command = {
10890 title: locations.length === 1 ? '1 reference' : `${locations.length} references`,
10891 command: locations.length ? 'editor.action.showReferences' : '',
10892 arguments: [uri, codeLens.range.start, locations]
10897 codeLens.command = {
10898 title: '0 references',
10904 extractSymbol(document, item, parent) {
10905 if (parent && parent.kind === PConst.Kind.enum) {
10906 return super.getSymbolRange(document, item);
10908 switch (item.kind) {
10909 case PConst.Kind.const:
10910 case PConst.Kind.let:
10911 case PConst.Kind.variable:
10912 case PConst.Kind.function:
10913 // Only show references for exported variables
10914 if (!item.kindModifiers.match(/\bexport\b/)) {
10918 case PConst.Kind.class:
10919 if (item.text === '<class>') {
10923 case PConst.Kind.method:
10924 case PConst.Kind.memberVariable:
10925 case PConst.Kind.memberGetAccessor:
10926 case PConst.Kind.memberSetAccessor:
10927 case PConst.Kind.constructorImplementation:
10928 case PConst.Kind.interface:
10929 case PConst.Kind.type:
10930 case PConst.Kind.enum:
10931 return super.getSymbolRange(document, item);
10936 exports.default = TypeScriptReferencesCodeLensProvider;
10941 /***/ (function(module, exports, __webpack_require__) {
10945 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10946 if (k2 === undefined) k2 = k;
10947 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10948 }) : (function(o, m, k, k2) {
10949 if (k2 === undefined) k2 = k;
10952 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10953 Object.defineProperty(o, "default", { enumerable: true, value: v });
10954 }) : function(o, v) {
10957 var __importStar = (this && this.__importStar) || function (mod) {
10958 if (mod && mod.__esModule) return mod;
10960 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10961 __setModuleDefault(result, mod);
10964 var __importDefault = (this && this.__importDefault) || function (mod) {
10965 return (mod && mod.__esModule) ? mod : { "default": mod };
10967 Object.defineProperty(exports, "__esModule", { value: true });
10968 /*---------------------------------------------------------------------------------------------
10969 * Copyright (c) Microsoft Corporation. All rights reserved.
10970 * Licensed under the MIT License. See License.txt in the project root for license information.
10971 *--------------------------------------------------------------------------------------------*/
10972 const coc_nvim_1 = __webpack_require__(1);
10973 const path_1 = __importDefault(__webpack_require__(13));
10974 const api_1 = __importDefault(__webpack_require__(40));
10975 const typeConverters = __importStar(__webpack_require__(37));
10976 class TypeScriptRenameProvider {
10977 constructor(client, fileConfigurationManager) {
10978 this.client = client;
10979 this.fileConfigurationManager = fileConfigurationManager;
10981 async prepareRename(document, position, token) {
10982 const response = await this.execRename(document, position, token);
10983 if (!response || response.type !== 'response' || !response.body) {
10986 const renameInfo = response.body.info;
10987 if (!renameInfo.canRename) {
10988 return Promise.reject(new Error('Invalid location for rename.'));
10990 if (this.client.apiVersion.gte(api_1.default.v310)) {
10991 const triggerSpan = renameInfo.triggerSpan;
10993 const range = typeConverters.Range.fromTextSpan(triggerSpan);
10999 async provideRenameEdits(document, position, newName, token) {
11000 const response = await this.execRename(document, position, token);
11001 if (!response || response.type !== 'response' || !response.body) {
11004 const renameInfo = response.body.info;
11005 if (!renameInfo.canRename) {
11006 return Promise.reject(new Error('Invalid location for rename.'));
11008 if (this.client.apiVersion.gte(api_1.default.v310)) {
11009 if (renameInfo.fileToRename) {
11010 const edits = await this.renameFile(renameInfo.fileToRename, newName, token);
11015 return Promise.reject(new Error('An error occurred while renaming file'));
11019 return this.toWorkspaceEdit(response.body.locs, newName);
11021 async execRename(document, position, token) {
11022 const file = this.client.toPath(document.uri);
11025 const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { findInStrings: false, findInComments: false });
11026 await this.fileConfigurationManager.ensureConfigurationForDocument(document, token);
11027 return this.client.interruptGetErr(() => {
11028 return this.client.execute('rename', args, token);
11031 toWorkspaceEdit(locations, newName) {
11033 for (const spanGroup of locations) {
11034 const uri = this.client.toResource(spanGroup.file);
11037 for (const textSpan of spanGroup.locs) {
11038 changes[uri].push({
11039 range: typeConverters.Range.fromTextSpan(textSpan),
11040 newText: (textSpan.prefixText || '') + newName + (textSpan.suffixText || '')
11045 return { changes };
11047 async renameFile(fileToRename, newName, token) {
11048 // Make sure we preserve file exension if none provided
11049 if (!path_1.default.extname(newName)) {
11050 newName += path_1.default.extname(fileToRename);
11052 const dirname = path_1.default.dirname(fileToRename);
11053 const newFilePath = path_1.default.join(dirname, newName);
11055 file: fileToRename,
11056 oldFilePath: fileToRename,
11059 const response = await this.client.execute('getEditsForFileRename', args, token);
11060 if (response.type !== 'response' || !response.body) {
11063 const edits = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, response.body);
11064 edits.documentChanges = edits.documentChanges || [];
11065 edits.documentChanges.push({
11067 oldUri: coc_nvim_1.Uri.file(fileToRename).toString(),
11068 newUri: coc_nvim_1.Uri.file(newFilePath).toString(),
11071 ignoreIfExists: true
11077 exports.default = TypeScriptRenameProvider;
11082 /***/ (function(module, exports, __webpack_require__) {
11086 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11087 if (k2 === undefined) k2 = k;
11088 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11089 }) : (function(o, m, k, k2) {
11090 if (k2 === undefined) k2 = k;
11093 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11094 Object.defineProperty(o, "default", { enumerable: true, value: v });
11095 }) : function(o, v) {
11098 var __importStar = (this && this.__importStar) || function (mod) {
11099 if (mod && mod.__esModule) return mod;
11101 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11102 __setModuleDefault(result, mod);
11105 Object.defineProperty(exports, "__esModule", { value: true });
11106 const Previewer = __importStar(__webpack_require__(86));
11107 const typeConverters = __importStar(__webpack_require__(37));
11108 class TypeScriptSignatureHelpProvider {
11109 constructor(client) {
11110 this.client = client;
11112 async provideSignatureHelp(document, position, token) {
11113 const filepath = this.client.toPath(document.uri);
11117 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
11120 response = await this.client.interruptGetErr(() => this.client.execute('signatureHelp', args, token));
11125 if (response.type !== 'response' || !response.body) {
11128 let info = response.body;
11130 activeSignature: info.selectedItemIndex,
11131 activeParameter: this.getActiveParmeter(info),
11132 signatures: info.items.map(signature => {
11133 return this.convertSignature(signature);
11138 getActiveParmeter(info) {
11139 const activeSignature = info.items[info.selectedItemIndex];
11140 if (activeSignature && activeSignature.isVariadic) {
11141 return Math.min(info.argumentIndex, activeSignature.parameters.length - 1);
11143 return info.argumentIndex;
11145 convertSignature(item) {
11146 let parameters = item.parameters.map(p => {
11148 label: Previewer.plain(p.displayParts),
11149 documentation: Previewer.markdownDocumentation(p.documentation, [])
11152 let label = Previewer.plain(item.prefixDisplayParts);
11153 label += parameters.map(parameter => parameter.label).join(Previewer.plain(item.separatorDisplayParts));
11154 label += Previewer.plain(item.suffixDisplayParts);
11157 documentation: Previewer.markdownDocumentation(item.documentation, item.tags.filter(x => x.name !== 'param')),
11162 exports.default = TypeScriptSignatureHelpProvider;
11163 TypeScriptSignatureHelpProvider.triggerCharacters = ['(', ',', '<'];
11168 /***/ (function(module, exports, __webpack_require__) {
11172 /*---------------------------------------------------------------------------------------------
11173 * Copyright (c) Microsoft Corporation. All rights reserved.
11174 * Licensed under the MIT License. See License.txt in the project root for license information.
11175 *--------------------------------------------------------------------------------------------*/
11176 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11177 if (k2 === undefined) k2 = k;
11178 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11179 }) : (function(o, m, k, k2) {
11180 if (k2 === undefined) k2 = k;
11183 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11184 Object.defineProperty(o, "default", { enumerable: true, value: v });
11185 }) : function(o, v) {
11188 var __importStar = (this && this.__importStar) || function (mod) {
11189 if (mod && mod.__esModule) return mod;
11191 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11192 __setModuleDefault(result, mod);
11195 Object.defineProperty(exports, "__esModule", { value: true });
11196 const typeConverters = __importStar(__webpack_require__(37));
11197 class SmartSelection {
11198 constructor(client) {
11199 this.client = client;
11201 async provideSelectionRanges(document, positions, token) {
11202 const file = this.client.toPath(document.uri);
11208 locations: positions.map(typeConverters.Position.toLocation)
11210 const response = await this.client.execute('selectionRange', args, token);
11211 if (response.type !== 'response' || !response.body) {
11214 return response.body.map(SmartSelection.convertSelectionRange);
11216 static convertSelectionRange(selectionRange) {
11218 range: typeConverters.Range.fromTextSpan(selectionRange.textSpan),
11219 parent: selectionRange.parent ? SmartSelection.convertSelectionRange(selectionRange.parent) : undefined,
11223 exports.default = SmartSelection;
11228 /***/ (function(module, exports, __webpack_require__) {
11232 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11233 if (k2 === undefined) k2 = k;
11234 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11235 }) : (function(o, m, k, k2) {
11236 if (k2 === undefined) k2 = k;
11239 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11240 Object.defineProperty(o, "default", { enumerable: true, value: v });
11241 }) : function(o, v) {
11244 var __importStar = (this && this.__importStar) || function (mod) {
11245 if (mod && mod.__esModule) return mod;
11247 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11248 __setModuleDefault(result, mod);
11251 Object.defineProperty(exports, "__esModule", { value: true });
11252 /*---------------------------------------------------------------------------------------------
11253 * Copyright (c) Microsoft Corporation. All rights reserved.
11254 * Licensed under the MIT License. See License.txt in the project root for license information.
11255 *--------------------------------------------------------------------------------------------*/
11256 const vscode_languageserver_protocol_1 = __webpack_require__(3);
11257 const coc_nvim_1 = __webpack_require__(1);
11258 const typeConverters = __importStar(__webpack_require__(37));
11259 const mutex_1 = __webpack_require__(111);
11260 function wait(ms) {
11261 return new Promise(resolve => {
11267 class UpdateImportsOnFileRenameHandler {
11268 constructor(client, fileConfigurationManager, languageId) {
11269 this.client = client;
11270 this.fileConfigurationManager = fileConfigurationManager;
11271 this.disposables = [];
11272 let glob = languageId == 'typescript' ? '**/*.{ts,tsx}' : '**/*.{js,jsx}';
11273 const watcher = coc_nvim_1.workspace.createFileSystemWatcher(glob);
11274 this.disposables.push(watcher);
11275 let mutex = new mutex_1.Mutex();
11276 watcher.onDidRename(async (e) => {
11277 let release = await mutex.acquire();
11279 await this.doRename(e.oldUri, e.newUri);
11283 this.client.logger.error('Error on rename:', e);
11286 }, null, this.disposables);
11289 coc_nvim_1.disposeAll(this.disposables);
11291 async doRename(oldResource, newResource) {
11292 if (oldResource.scheme !== 'file' || newResource.scheme !== 'file') {
11295 const targetFile = newResource.fsPath;
11296 const oldFile = oldResource.fsPath;
11297 const newUri = newResource.toString();
11298 let oldDocument = coc_nvim_1.workspace.getDocument(oldResource.toString());
11300 await coc_nvim_1.workspace.nvim.command(`silent ${oldDocument.bufnr}bwipeout!`);
11302 let document = coc_nvim_1.workspace.getDocument(newUri);
11304 await coc_nvim_1.workspace.nvim.command(`silent ${document.bufnr}bwipeout!`);
11307 document = await coc_nvim_1.workspace.loadFile(newUri);
11311 const edits = await this.getEditsForFileRename(document.textDocument, oldFile, targetFile);
11314 if (await this.promptUser(newResource)) {
11315 await coc_nvim_1.workspace.applyEdit(edits);
11318 async promptUser(newResource) {
11319 return await coc_nvim_1.workspace.showPrompt(`Update imports for moved file: ${newResource.fsPath}?`);
11321 async getEditsForFileRename(document, oldFile, newFile) {
11322 await this.fileConfigurationManager.ensureConfigurationForDocument(document, vscode_languageserver_protocol_1.CancellationToken.None);
11323 const response = await this.client.interruptGetErr(() => {
11325 oldFilePath: oldFile,
11326 newFilePath: newFile,
11328 return this.client.execute('getEditsForFileRename', args, vscode_languageserver_protocol_1.CancellationToken.None);
11330 if (!response || response.type != 'response' || !response.body) {
11334 for (const edit of response.body) {
11335 // Workaround for https://github.com/Microsoft/vscode/issues/52675
11336 if (edit.fileName.match(/[\/\\]node_modules[\/\\]/gi)) {
11339 for (const change of edit.textChanges) {
11340 if (change.newText.match(/\/node_modules\//gi)) {
11346 return typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, edits);
11349 exports.default = UpdateImportsOnFileRenameHandler;
11354 /***/ (function(module, exports, __webpack_require__) {
11358 Object.defineProperty(exports, "__esModule", { value: true });
11359 exports.Mutex = void 0;
11366 if (this.count > 0 && this.tasks.length > 0) {
11368 let next = this.tasks.shift();
11373 return this.count == 0;
11375 // tslint:disable-next-line: typedef
11377 return new Promise(res => {
11379 let released = false;
11388 this.tasks.push(task);
11389 process.nextTick(this.sched.bind(this));
11393 return this.acquire()
11407 exports.Mutex = Mutex;
11412 /***/ (function(module, exports, __webpack_require__) {
11416 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11417 if (k2 === undefined) k2 = k;
11418 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11419 }) : (function(o, m, k, k2) {
11420 if (k2 === undefined) k2 = k;
11423 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11424 Object.defineProperty(o, "default", { enumerable: true, value: v });
11425 }) : function(o, v) {
11428 var __importStar = (this && this.__importStar) || function (mod) {
11429 if (mod && mod.__esModule) return mod;
11431 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11432 __setModuleDefault(result, mod);
11435 Object.defineProperty(exports, "__esModule", { value: true });
11436 exports.OrganizeImportsCodeActionProvider = exports.OrganizeImportsCommand = void 0;
11437 /*---------------------------------------------------------------------------------------------
11438 * Copyright (c) Microsoft Corporation. All rights reserved.
11439 * Licensed under the MIT License. See License.txt in the project root for license information.
11440 *--------------------------------------------------------------------------------------------*/
11441 const coc_nvim_1 = __webpack_require__(1);
11442 const vscode_languageserver_protocol_1 = __webpack_require__(3);
11443 const typeconverts = __importStar(__webpack_require__(37));
11444 class OrganizeImportsCommand {
11445 constructor(service) {
11446 this.service = service;
11447 this.id = 'tsserver.organizeImports';
11449 async _execute(client, document) {
11450 let file = client.toPath(document.uri);
11459 const response = await client.interruptGetErr(() => client.execute('organizeImports', args, vscode_languageserver_protocol_1.CancellationToken.None));
11460 if (!response || response.type != 'response' || !response.success) {
11463 const edit = typeconverts.WorkspaceEdit.fromFileCodeEdits(client, response.body);
11464 let keys = Object.keys(edit.changes);
11465 if (keys.length == 1) {
11466 let doc = coc_nvim_1.workspace.getDocument(keys[0]);
11468 await doc.applyEdits(edit.changes[keys[0]]);
11473 await coc_nvim_1.workspace.applyEdit(edit);
11475 async execute(document) {
11476 let client = await this.service.getClientHost();
11478 let doc = await coc_nvim_1.workspace.document;
11479 if (!doc.attached) {
11480 throw new Error(`Document not attached.`);
11482 if (client.serviceClient.modeIds.indexOf(doc.filetype) == -1) {
11483 throw new Error(`filetype "${doc.filetype}" not supported by tsserver.`);
11485 document = doc.textDocument;
11487 await this._execute(client.serviceClient, document);
11490 exports.OrganizeImportsCommand = OrganizeImportsCommand;
11491 class OrganizeImportsCodeActionProvider {
11492 // public static readonly minVersion = API.v280
11493 constructor(client, fileConfigManager) {
11494 this.client = client;
11495 this.fileConfigManager = fileConfigManager;
11497 providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]
11500 async provideCodeActions(document, _range, context, token) {
11501 if (this.client.modeIds.indexOf(document.languageId) == -1)
11503 if (!context.only || !context.only.includes(vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports)) {
11506 await this.fileConfigManager.ensureConfigurationForDocument(document, token);
11507 const action = vscode_languageserver_protocol_1.CodeAction.create('Organize Imports', {
11509 command: 'tsserver.organizeImports',
11510 arguments: [document]
11511 }, vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports);
11515 exports.OrganizeImportsCodeActionProvider = OrganizeImportsCodeActionProvider;
11520 /***/ (function(module, exports, __webpack_require__) {
11524 var __importDefault = (this && this.__importDefault) || function (mod) {
11525 return (mod && mod.__esModule) ? mod : { "default": mod };
11527 Object.defineProperty(exports, "__esModule", { value: true });
11528 /*---------------------------------------------------------------------------------------------
11529 * Copyright (c) Microsoft Corporation. All rights reserved.
11530 * Licensed under the MIT License. See License.txt in the project root for license information.
11531 *--------------------------------------------------------------------------------------------*/
11532 const coc_nvim_1 = __webpack_require__(1);
11533 const vscode_languageserver_protocol_1 = __webpack_require__(3);
11534 const api_1 = __importDefault(__webpack_require__(40));
11535 function objAreEqual(a, b) {
11536 let keys = Object.keys(a);
11537 for (let i = 0; i < keys.length; i++) { // tslint:disable-line
11539 if (a[key] !== b[key]) {
11545 class FileConfigurationManager {
11546 constructor(client) {
11547 this.client = client;
11548 this.cachedMap = new Map();
11549 this.disposables = [];
11550 coc_nvim_1.workspace.onDidCloseTextDocument(textDocument => {
11551 // When a document gets closed delete the cached formatting options.
11552 // This is necessary since the tsserver now closed a project when its
11553 // last file in it closes which drops the stored formatting options
11555 this.cachedMap.delete(textDocument.uri);
11556 }, undefined, this.disposables);
11558 async ensureConfigurationOptions(document, insertSpaces, tabSize, token) {
11559 const file = this.client.toPath(document.uri);
11564 let cachedOption = this.cachedMap.get(document.uri);
11565 const currentOptions = this.getFileOptions(options, document);
11567 && objAreEqual(cachedOption.formatOptions, currentOptions.formatOptions)
11568 && objAreEqual(cachedOption.preferences, currentOptions.preferences))
11570 this.cachedMap.set(document.uri, currentOptions);
11571 const args = Object.assign({ file }, currentOptions);
11572 await this.client.execute('configure', args, vscode_languageserver_protocol_1.CancellationToken.None);
11574 const response = await this.client.execute('configure', args, token);
11575 if (response.type !== 'response') {
11576 this.cachedMap.delete(document.uri);
11580 this.cachedMap.delete(document.uri);
11583 async ensureConfigurationForDocument(document, token) {
11584 let opts = await coc_nvim_1.workspace.getFormatOptions(document.uri);
11585 return this.ensureConfigurationOptions(document, opts.insertSpaces, opts.tabSize, token);
11588 this.cachedMap.clear();
11590 getLanguageConfiguration(languageId) {
11591 return coc_nvim_1.workspace.getConfiguration(languageId);
11593 isTypeScriptDocument(languageId) {
11594 return languageId.startsWith('typescript');
11596 formatEnabled(document) {
11597 let { languageId, uri } = document;
11598 let language = languageId.startsWith('typescript') ? 'typescript' : 'javascript';
11599 const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
11600 return config.get('enabled');
11602 enableJavascript() {
11603 const config = coc_nvim_1.workspace.getConfiguration('tsserver');
11604 return !!config.get('enableJavascript');
11606 getFileOptions(options, document) {
11607 const lang = this.isTypeScriptDocument(document.languageId) ? 'typescript' : 'javascript';
11609 formatOptions: this.getFormatOptions(options, lang, document.uri),
11610 preferences: this.getPreferences(lang, document.uri)
11613 getFormatOptions(options, language, uri) {
11614 const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
11616 tabSize: options.tabSize,
11617 indentSize: options.tabSize,
11618 convertTabsToSpaces: options.insertSpaces,
11619 // We can use \n here since the editor normalizes later on to its line endings.
11620 newLineCharacter: '\n',
11621 insertSpaceAfterCommaDelimiter: config.get('insertSpaceAfterCommaDelimiter'),
11622 insertSpaceAfterConstructor: config.get('insertSpaceAfterConstructor'),
11623 insertSpaceAfterSemicolonInForStatements: config.get('insertSpaceAfterSemicolonInForStatements'),
11624 insertSpaceBeforeAndAfterBinaryOperators: config.get('insertSpaceBeforeAndAfterBinaryOperators'),
11625 insertSpaceAfterKeywordsInControlFlowStatements: config.get('insertSpaceAfterKeywordsInControlFlowStatements'),
11626 insertSpaceAfterFunctionKeywordForAnonymousFunctions: config.get('insertSpaceAfterFunctionKeywordForAnonymousFunctions'),
11627 insertSpaceBeforeFunctionParenthesis: config.get('insertSpaceBeforeFunctionParenthesis'),
11628 insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis'),
11629 insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets'),
11630 insertSpaceAfterOpeningAndBeforeClosingEmptyBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingEmptyBraces'),
11631 insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces'),
11632 insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces'),
11633 insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces'),
11634 insertSpaceAfterTypeAssertion: config.get('insertSpaceAfterTypeAssertion'),
11635 placeOpenBraceOnNewLineForFunctions: config.get('placeOpenBraceOnNewLineForFunctions'),
11636 placeOpenBraceOnNewLineForControlBlocks: config.get('placeOpenBraceOnNewLineForControlBlocks'),
11637 semicolons: config.get('semicolons', undefined)
11640 getCompleteOptions(languageId) {
11641 const lang = this.isTypeScriptDocument(languageId) ? 'typescript' : 'javascript';
11642 const config = coc_nvim_1.workspace.getConfiguration(`${lang}.suggest`);
11644 enabled: config.get('enabled', true),
11645 names: config.get('names', true),
11646 paths: config.get('paths', true),
11647 completeFunctionCalls: config.get('completeFunctionCalls', true),
11648 autoImports: config.get('autoImports', true),
11649 includeAutomaticOptionalChainCompletions: config.get('includeAutomaticOptionalChainCompletions', true)
11652 getPreferences(language, uri) {
11653 if (this.client.apiVersion.lt(api_1.default.v290)) {
11656 const config = coc_nvim_1.workspace.getConfiguration(`${language}.preferences`, uri);
11657 // getImportModuleSpecifierEndingPreference available on ts 2.9.0
11658 const preferences = {
11659 quotePreference: this.getQuoteStyle(config),
11660 importModuleSpecifierPreference: getImportModuleSpecifier(config),
11661 importModuleSpecifierEnding: getImportModuleSpecifierEndingPreference(config),
11662 allowTextChangesInNewFiles: uri.startsWith('file:'),
11663 allowRenameOfImportPath: true,
11664 providePrefixAndSuffixTextForRename: config.get('renameShorthandProperties', true) === false ? false : config.get('useAliasesForRenames', true),
11666 return preferences;
11668 getQuoteStyle(config) {
11669 let quoteStyle = config.get('quoteStyle', 'auto');
11670 if (this.client.apiVersion.gte(api_1.default.v333) || quoteStyle != 'auto')
11675 coc_nvim_1.disposeAll(this.disposables);
11678 exports.default = FileConfigurationManager;
11679 function getImportModuleSpecifier(config) {
11680 let val = config.get('importModuleSpecifier');
11684 case 'non-relative':
11685 return 'non-relative';
11690 function getImportModuleSpecifierEndingPreference(config) {
11691 switch (config.get('importModuleSpecifierEnding')) {
11692 case 'minimal': return 'minimal';
11693 case 'index': return 'index';
11694 case 'js': return 'js';
11695 default: return 'auto';
11702 /***/ (function(module, exports, __webpack_require__) {
11706 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11707 if (k2 === undefined) k2 = k;
11708 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11709 }) : (function(o, m, k, k2) {
11710 if (k2 === undefined) k2 = k;
11713 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11714 Object.defineProperty(o, "default", { enumerable: true, value: v });
11715 }) : function(o, v) {
11718 var __importStar = (this && this.__importStar) || function (mod) {
11719 if (mod && mod.__esModule) return mod;
11721 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11722 __setModuleDefault(result, mod);
11725 var __importDefault = (this && this.__importDefault) || function (mod) {
11726 return (mod && mod.__esModule) ? mod : { "default": mod };
11728 Object.defineProperty(exports, "__esModule", { value: true });
11729 const coc_nvim_1 = __webpack_require__(1);
11730 const fs_1 = __importDefault(__webpack_require__(102));
11731 const os_1 = __importDefault(__webpack_require__(14));
11732 const path_1 = __importDefault(__webpack_require__(13));
11733 const vscode_languageserver_protocol_1 = __webpack_require__(3);
11734 const fileSchemes = __importStar(__webpack_require__(115));
11735 const callbackMap_1 = __webpack_require__(116);
11736 const bufferSyncSupport_1 = __importDefault(__webpack_require__(118));
11737 const diagnostics_1 = __webpack_require__(122);
11738 const fileConfigurationManager_1 = __importDefault(__webpack_require__(113));
11739 const requestQueue_1 = __webpack_require__(123);
11740 const typescriptService_1 = __webpack_require__(117);
11741 const api_1 = __importDefault(__webpack_require__(40));
11742 const configuration_1 = __webpack_require__(124);
11743 const logger_1 = __importDefault(__webpack_require__(129));
11744 const process_1 = __webpack_require__(131);
11745 const tracer_1 = __importDefault(__webpack_require__(132));
11746 const tsconfig_1 = __webpack_require__(133);
11747 const versionProvider_1 = __webpack_require__(134);
11748 const versionStatus_1 = __importDefault(__webpack_require__(135));
11749 const wireProtocol_1 = __webpack_require__(136);
11750 class ForkedTsServerProcess {
11751 constructor(childProcess) {
11752 this.childProcess = childProcess;
11753 this.toCancelOnResourceChange = new Set();
11756 this.childProcess.on('error', cb);
11759 this.childProcess.on('exit', cb);
11761 write(serverRequest) {
11762 this.childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8');
11764 createReader(callback, onError) {
11765 // tslint:disable-next-line:no-unused-expression
11766 new wireProtocol_1.Reader(this.childProcess.stdout, callback, onError);
11769 this.childProcess.kill();
11772 class TypeScriptServiceClient {
11773 constructor(pluginManager, modeIds) {
11774 this.pluginManager = pluginManager;
11775 this.modeIds = modeIds;
11776 this.state = coc_nvim_1.ServiceStat.Initial;
11777 this.logger = new logger_1.default();
11778 this.tsServerLogFile = null;
11779 this.cancellationPipeName = null;
11780 this._callbacks = new callbackMap_1.CallbackMap();
11781 this._requestQueue = new requestQueue_1.RequestQueue();
11782 this._pendingResponses = new Set();
11783 this._onTsServerStarted = new vscode_languageserver_protocol_1.Emitter();
11784 this._onProjectLanguageServiceStateChanged = new vscode_languageserver_protocol_1.Emitter();
11785 this._onDidBeginInstallTypings = new vscode_languageserver_protocol_1.Emitter();
11786 this._onDidEndInstallTypings = new vscode_languageserver_protocol_1.Emitter();
11787 this._onTypesInstallerInitializationFailed = new vscode_languageserver_protocol_1.Emitter();
11788 this.disposables = [];
11789 this.isRestarting = false;
11790 this._onDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
11791 this._onConfigDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
11792 this._onResendModelsRequested = new vscode_languageserver_protocol_1.Emitter();
11793 this.pathSeparator = path_1.default.sep;
11794 this.lastStart = Date.now();
11795 this.servicePromise = null;
11796 this.lastError = null;
11797 this.numberRestarts = 0;
11798 this.fileConfigurationManager = new fileConfigurationManager_1.default(this);
11799 this._configuration = configuration_1.TypeScriptServiceConfiguration.loadFromWorkspace();
11800 this.versionProvider = new versionProvider_1.TypeScriptVersionProvider(this._configuration);
11801 this._apiVersion = api_1.default.defaultVersion;
11802 this.tracer = new tracer_1.default(this.logger);
11803 this.versionStatus = new versionStatus_1.default(this.normalizePath.bind(this), this.fileConfigurationManager.enableJavascript());
11804 pluginManager.onDidUpdateConfig(update => {
11805 this.configurePlugin(update.pluginId, update.config);
11806 }, null, this.disposables);
11807 pluginManager.onDidChangePlugins(() => {
11808 this.restartTsServer();
11809 }, null, this.disposables);
11810 this.bufferSyncSupport = new bufferSyncSupport_1.default(this, modeIds);
11811 this.onTsServerStarted(() => {
11812 this.bufferSyncSupport.listen();
11814 this.diagnosticsManager = new diagnostics_1.DiagnosticsManager();
11815 this.bufferSyncSupport.onDelete(resource => {
11816 this.cancelInflightRequestsForResource(resource);
11817 this.diagnosticsManager.delete(resource);
11818 }, null, this.disposables);
11819 this.bufferSyncSupport.onWillChange(resource => {
11820 this.cancelInflightRequestsForResource(resource);
11823 get onDiagnosticsReceived() {
11824 return this._onDiagnosticsReceived.event;
11826 get onConfigDiagnosticsReceived() {
11827 return this._onConfigDiagnosticsReceived.event;
11829 get onResendModelsRequested() {
11830 return this._onResendModelsRequested.event;
11832 get configuration() {
11833 return this._configuration;
11836 if (this.servicePromise) {
11837 this.servicePromise
11838 .then(childProcess => {
11839 childProcess.kill();
11841 .then(undefined, () => void 0);
11843 this.bufferSyncSupport.dispose();
11844 this.logger.dispose();
11845 this._onTsServerStarted.dispose();
11846 this._onResendModelsRequested.dispose();
11847 this.versionStatus.dispose();
11849 info(message, data) {
11850 this.logger.info(message, data);
11852 error(message, data) {
11853 this.logger.error(message, data);
11855 restartTsServer() {
11856 const start = () => {
11857 this.servicePromise = this.startService(true);
11858 return this.servicePromise;
11860 if (this.servicePromise) {
11861 return Promise.resolve(this.servicePromise.then(childProcess => {
11862 this.state = coc_nvim_1.ServiceStat.Stopping;
11863 this.info('Killing TS Server');
11864 this.isRestarting = true;
11865 childProcess.kill();
11866 this.servicePromise = null;
11870 return Promise.resolve(start());
11874 if (!this.servicePromise)
11876 return new Promise((resolve, reject) => {
11877 this.servicePromise.then(childProcess => {
11878 if (this.state == coc_nvim_1.ServiceStat.Running) {
11879 this.info('Killing TS Server');
11880 childProcess.onExit(() => {
11883 childProcess.kill();
11884 this.servicePromise = null;
11892 get onTsServerStarted() {
11893 return this._onTsServerStarted.event;
11895 get onProjectLanguageServiceStateChanged() {
11896 return this._onProjectLanguageServiceStateChanged.event;
11898 get onDidBeginInstallTypings() {
11899 return this._onDidBeginInstallTypings.event;
11901 get onDidEndInstallTypings() {
11902 return this._onDidEndInstallTypings.event;
11904 get onTypesInstallerInitializationFailed() {
11905 return this._onTypesInstallerInitializationFailed.event;
11908 return this._apiVersion;
11911 return this._tscPath;
11914 if (this.servicePromise) {
11915 return this.servicePromise;
11917 if (this.lastError) {
11918 return Promise.reject(this.lastError);
11920 return this.startService().then(() => {
11921 if (this.servicePromise) {
11922 return this.servicePromise;
11926 ensureServiceStarted() {
11927 if (!this.servicePromise) {
11928 this.startService().catch(err => {
11929 coc_nvim_1.workspace.showMessage(`TSServer start failed: ${err.message}`, 'error');
11930 this.error(`Service start failed: ${err.stack}`);
11934 async startService(resendModels = false) {
11935 const { ignoreLocalTsserver } = this.configuration;
11936 let currentVersion;
11937 if (!ignoreLocalTsserver)
11938 currentVersion = this.versionProvider.getLocalVersion();
11939 if (!currentVersion || !fs_1.default.existsSync(currentVersion.tsServerPath)) {
11940 currentVersion = this.versionProvider.getDefaultVersion();
11942 if (!currentVersion || !currentVersion.isValid) {
11943 if (this.configuration.globalTsdk) {
11944 coc_nvim_1.workspace.showMessage(`Can not find typescript module, in 'tsserver.tsdk': ${this.configuration.globalTsdk}`, 'error');
11947 coc_nvim_1.workspace.showMessage(`Can not find typescript module, run ':CocInstall coc-tsserver' to fix it!`, 'error');
11951 this._apiVersion = currentVersion.version;
11952 this._tscPath = currentVersion.tscPath;
11953 this.versionStatus.onDidChangeTypeScriptVersion(currentVersion);
11954 this.lastError = null;
11955 const tsServerForkArgs = await this.getTsServerArgs(currentVersion);
11956 const debugPort = this._configuration.debugPort;
11957 const maxTsServerMemory = this._configuration.maxTsServerMemory;
11960 ...(debugPort ? [`--inspect=${debugPort}`] : []),
11961 ...(maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : []),
11963 cwd: coc_nvim_1.workspace.root
11965 this.servicePromise = this.startProcess(currentVersion, tsServerForkArgs, options, resendModels);
11966 return this.servicePromise;
11968 startProcess(currentVersion, args, options, resendModels) {
11969 this.state = coc_nvim_1.ServiceStat.Starting;
11970 return new Promise((resolve, reject) => {
11972 process_1.fork(currentVersion.tsServerPath, args, options, this.logger, (err, childProcess) => {
11973 if (err || !childProcess) {
11974 this.state = coc_nvim_1.ServiceStat.StartFailed;
11975 this.lastError = err;
11976 this.error('Starting TSServer failed with error.', err.stack);
11979 this.state = coc_nvim_1.ServiceStat.Running;
11980 this.info('Started TSServer', JSON.stringify(currentVersion, null, 2));
11981 const handle = new ForkedTsServerProcess(childProcess);
11982 this.tsServerProcess = handle;
11983 this.lastStart = Date.now();
11984 handle.onError((err) => {
11985 this.lastError = err;
11986 this.error('TSServer errored with error.', err);
11987 this.error(`TSServer log file: ${this.tsServerLogFile || ''}`);
11988 coc_nvim_1.workspace.showMessage(`TSServer errored with error. ${err.message}`, 'error');
11989 this.serviceExited(false);
11991 handle.onExit((code) => {
11992 if (code == null) {
11993 this.info('TSServer normal exit');
11996 this.error(`TSServer exited with code: ${code}`);
11998 this.info(`TSServer log file: ${this.tsServerLogFile || ''}`);
11999 this.serviceExited(!this.isRestarting);
12000 this.isRestarting = false;
12002 handle.createReader(msg => {
12003 this.dispatchMessage(msg);
12005 this.error('ReaderError', error);
12008 this.serviceStarted(resendModels);
12009 this._onTsServerStarted.fire(currentVersion.version);
12017 async openTsServerLogFile() {
12018 const isRoot = process.getuid && process.getuid() == 0;
12019 let echoErr = (msg) => {
12020 coc_nvim_1.workspace.showMessage(msg, 'error');
12023 echoErr('Log disabled for root user.');
12026 if (!this.apiVersion.gte(api_1.default.v222)) {
12027 echoErr('TS Server logging requires TS 2.2.2+');
12030 if (this._configuration.tsServerLogLevel === configuration_1.TsServerLogLevel.Off) {
12031 echoErr(`TS Server logging is off. Change 'tsserver.log' in 'coc-settings.json' to enable`);
12034 if (!this.tsServerLogFile) {
12035 echoErr('TS Server has not started logging.');
12039 await coc_nvim_1.workspace.nvim.command(`edit ${this.tsServerLogFile}`);
12043 echoErr('Could not open TS Server log file');
12047 serviceStarted(resendModels) {
12048 this.bufferSyncSupport.reset();
12049 const watchOptions = this.apiVersion.gte(api_1.default.v380)
12050 ? this.configuration.watchOptions
12052 const configureOptions = {
12053 hostInfo: 'coc-nvim',
12055 providePrefixAndSuffixTextForRename: true,
12056 allowRenameOfImportPath: true,
12060 this.executeWithoutWaitingForResponse('configure', configureOptions); // tslint:disable-line
12061 this.setCompilerOptionsForInferredProjects(this._configuration);
12062 if (resendModels) {
12063 this._onResendModelsRequested.fire(void 0);
12064 this.fileConfigurationManager.reset();
12065 this.diagnosticsManager.reInitialize();
12066 this.bufferSyncSupport.reinitialize();
12068 // Reconfigure any plugins
12069 for (const [config, pluginName] of this.pluginManager.configurations()) {
12070 this.configurePlugin(config, pluginName);
12073 setCompilerOptionsForInferredProjects(configuration) {
12074 if (!this.apiVersion.gte(api_1.default.v206))
12077 options: this.getCompilerOptionsForInferredProjects(configuration)
12079 this.executeWithoutWaitingForResponse('compilerOptionsForInferredProjects', args); // tslint:disable-line
12081 getCompilerOptionsForInferredProjects(configuration) {
12082 return Object.assign(Object.assign({}, tsconfig_1.inferredProjectConfig(configuration)), { allowJs: true, allowSyntheticDefaultImports: true, allowNonTsExtensions: true });
12084 serviceExited(restart) {
12085 this.state = coc_nvim_1.ServiceStat.Stopped;
12086 this.servicePromise = null;
12087 this.tsServerLogFile = null;
12088 this._callbacks.destroy('Service died.');
12089 this._callbacks = new callbackMap_1.CallbackMap();
12090 this._requestQueue = new requestQueue_1.RequestQueue();
12091 this._pendingResponses = new Set();
12093 const diff = Date.now() - this.lastStart;
12094 this.numberRestarts++;
12095 let startService = true;
12096 if (this.numberRestarts > 5) {
12097 this.numberRestarts = 0;
12098 if (diff < 10 * 1000 /* 10 seconds */) {
12099 this.lastStart = Date.now();
12100 startService = false;
12101 coc_nvim_1.workspace.showMessage('The TypeScript language service died 5 times right after it got started.', 'error'); // tslint:disable-line
12103 else if (diff < 60 * 1000 /* 1 Minutes */) {
12104 this.lastStart = Date.now();
12105 coc_nvim_1.workspace.showMessage('The TypeScript language service died unexpectedly 5 times in the last 5 Minutes.', 'error'); // tslint:disable-line
12108 if (startService) {
12109 this.startService(true); // tslint:disable-line
12114 return this.normalizePath(coc_nvim_1.Uri.parse(uri));
12116 toOpenedFilePath(uri, options = {}) {
12117 if (!this.bufferSyncSupport.ensureHasBuffer(uri)) {
12118 if (!options.suppressAlertOnFailure) {
12119 console.error(`Unexpected resource ${uri}`);
12123 return this.toPath(uri);
12125 toResource(filepath) {
12126 if (this._apiVersion.gte(api_1.default.v213)) {
12127 if (filepath.startsWith('untitled:')) {
12128 let resource = coc_nvim_1.Uri.parse(filepath);
12129 if (this.inMemoryResourcePrefix) {
12130 const dirName = path_1.default.dirname(resource.path);
12131 const fileName = path_1.default.basename(resource.path);
12132 if (fileName.startsWith(this.inMemoryResourcePrefix)) {
12133 resource = resource.with({ path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length)) });
12136 return resource.toString();
12139 return coc_nvim_1.Uri.file(filepath).toString();
12141 normalizePath(resource) {
12142 if (fileSchemes.disabledSchemes.has(resource.scheme)) {
12145 switch (resource.scheme) {
12146 case fileSchemes.file: {
12147 let result = resource.fsPath;
12150 result = path_1.default.normalize(result);
12151 // Both \ and / must be escaped in regular expressions
12152 return result.replace(new RegExp('\\' + this.pathSeparator, 'g'), '/');
12155 return this.inMemoryResourcePrefix + resource.toString(true);
12159 get inMemoryResourcePrefix() {
12160 return this._apiVersion.gte(api_1.default.v270) ? '^' : '';
12163 if (this._apiVersion.gte(api_1.default.v213)) {
12164 if (filepath.startsWith('untitled:')) {
12165 let resource = coc_nvim_1.Uri.parse(filepath);
12166 if (this.inMemoryResourcePrefix) {
12167 const dirName = path_1.default.dirname(resource.path);
12168 const fileName = path_1.default.basename(resource.path);
12169 if (fileName.startsWith(this.inMemoryResourcePrefix)) {
12170 resource = resource.with({
12171 path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length))
12178 return coc_nvim_1.Uri.file(filepath);
12180 execute(command, args, token, config) {
12183 if (config === null || config === void 0 ? void 0 : config.cancelOnResourceChange) {
12184 const source = new vscode_languageserver_protocol_1.CancellationTokenSource();
12185 token.onCancellationRequested(() => source.cancel());
12187 resource: config.cancelOnResourceChange,
12188 cancel: () => source.cancel(),
12190 (_a = this.tsServerProcess) === null || _a === void 0 ? void 0 : _a.toCancelOnResourceChange.add(inFlight);
12191 execution = this.executeImpl(command, args, Object.assign({ isAsync: false, token: source.token, expectsResult: true }, config)).finally(() => {
12193 (_a = this.tsServerProcess) === null || _a === void 0 ? void 0 : _a.toCancelOnResourceChange.delete(inFlight);
12198 execution = this.executeImpl(command, args, Object.assign({ isAsync: false, token, expectsResult: true }, config));
12200 if (config === null || config === void 0 ? void 0 : config.nonRecoverable) {
12201 execution.catch(err => this.fatalError(command, err));
12205 fatalError(command, error) {
12206 console.error(`A non-recoverable error occured while executing tsserver command: ${command}`);
12207 if (this.state === coc_nvim_1.ServiceStat.Running) {
12208 this.info('Killing TS Server by fatal error:', error);
12209 this.service().then(service => {
12214 executeAsync(command, args, token) {
12215 return this.executeImpl(command, args, {
12218 expectsResult: true
12221 executeWithoutWaitingForResponse(command, args) {
12222 this.executeImpl(command, args, {
12225 expectsResult: false
12228 executeImpl(command, args, executeInfo) {
12229 if (this.servicePromise == null) {
12230 return Promise.resolve(undefined);
12232 this.bufferSyncSupport.beforeCommand(command);
12233 const request = this._requestQueue.createRequest(command, args);
12234 const requestInfo = {
12236 expectsResponse: executeInfo.expectsResult,
12237 isAsync: executeInfo.isAsync,
12238 queueingType: getQueueingType(command, executeInfo.lowPriority)
12241 if (executeInfo.expectsResult) {
12242 result = new Promise((resolve, reject) => {
12243 this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync);
12244 if (executeInfo.token) {
12245 executeInfo.token.onCancellationRequested(() => {
12246 this.tryCancelRequest(request.seq, command);
12249 }).catch((err) => {
12253 this._requestQueue.enqueue(requestInfo);
12254 this.sendNextRequests();
12257 sendNextRequests() {
12258 while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
12259 const item = this._requestQueue.dequeue();
12261 this.sendRequest(item);
12265 sendRequest(requestItem) {
12266 const serverRequest = requestItem.request;
12267 this.tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length);
12268 if (requestItem.expectsResponse && !requestItem.isAsync) {
12269 this._pendingResponses.add(requestItem.request.seq);
12271 this.service().then(childProcess => {
12273 childProcess.write(serverRequest);
12276 const callback = this.fetchCallback(serverRequest.seq);
12278 callback.onError(err);
12283 tryCancelRequest(seq, command) {
12285 if (this._requestQueue.tryDeletePendingRequest(seq)) {
12286 this.tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
12289 if (this.cancellationPipeName) {
12290 this.tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
12292 fs_1.default.writeFileSync(this.cancellationPipeName + seq, '');
12299 this.tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
12303 const callback = this.fetchCallback(seq);
12305 callback.onSuccess(new typescriptService_1.ServerResponse.Cancelled(`Cancelled request ${seq} - ${command}`));
12309 fetchCallback(seq) {
12310 const callback = this._callbacks.fetch(seq);
12314 this._pendingResponses.delete(seq);
12317 dispatchMessage(message) {
12319 switch (message.type) {
12321 this.dispatchResponse(message);
12324 const event = message;
12325 if (event.event === 'requestCompleted') {
12326 const seq = event.body.request_seq;
12327 const p = this._callbacks.fetch(seq);
12329 this.tracer.traceRequestCompleted('requestCompleted', seq, p.startTime);
12330 p.onSuccess(undefined);
12334 this.tracer.traceEvent(event);
12335 this.dispatchEvent(event);
12339 throw new Error(`Unknown message type ${message.type} received`);
12343 this.sendNextRequests();
12346 dispatchResponse(response) {
12347 const callback = this.fetchCallback(response.request_seq);
12351 this.tracer.traceResponse(response, callback.startTime);
12352 if (response.success) {
12353 callback.onSuccess(response);
12355 else if (response.message === 'No content available.') {
12356 // Special case where response itself is successful but there is not any data to return.
12357 callback.onSuccess(typescriptService_1.ServerResponse.NoContent);
12360 callback.onError(new Error(response.message));
12363 dispatchEvent(event) {
12364 switch (event.event) {
12366 case 'semanticDiag':
12367 case 'suggestionDiag':
12368 const diagnosticEvent = event;
12369 if (diagnosticEvent.body && diagnosticEvent.body.diagnostics) {
12370 this._onDiagnosticsReceived.fire({
12371 kind: getDiagnosticsKind(event),
12372 resource: this.asUrl(diagnosticEvent.body.file),
12373 diagnostics: diagnosticEvent.body.diagnostics
12377 case 'configFileDiag':
12378 this._onConfigDiagnosticsReceived.fire(event);
12380 case 'projectLanguageServiceState':
12382 this._onProjectLanguageServiceStateChanged.fire(event.body);
12385 case 'beginInstallTypes':
12387 this._onDidBeginInstallTypings.fire(event.body);
12390 case 'endInstallTypes':
12392 this._onDidEndInstallTypings.fire(event.body);
12395 case 'projectsUpdatedInBackground':
12396 const body = event.body;
12397 const resources = body.openFiles.map(coc_nvim_1.Uri.file);
12398 this.bufferSyncSupport.getErr(resources);
12400 case 'typesInstallerInitializationFailed':
12402 this._onTypesInstallerInitializationFailed.fire(event.body);
12405 case 'projectLoadingStart':
12406 this.versionStatus.loading = true;
12408 case 'projectLoadingFinish':
12409 this.versionStatus.loading = false;
12413 async getTsServerArgs(currentVersion) {
12415 args.push('--allowLocalPluginLoads');
12416 if (this.apiVersion.gte(api_1.default.v250)) {
12417 args.push('--useInferredProjectPerProjectRoot');
12420 args.push('--useSingleInferredProject');
12422 if (this.apiVersion.gte(api_1.default.v206) && this._configuration.disableAutomaticTypeAcquisition) {
12423 args.push('--disableAutomaticTypingAcquisition');
12425 if (this.apiVersion.gte(api_1.default.v222)) {
12426 this.cancellationPipeName = process_1.getTempFile(`tscancellation-${process_1.makeRandomHexString(20)}`);
12427 args.push('--cancellationPipeName', this.cancellationPipeName + '*');
12429 if (this.apiVersion.gte(api_1.default.v222)) {
12430 const isRoot = process.getuid && process.getuid() == 0;
12431 if (this._configuration.tsServerLogLevel !== configuration_1.TsServerLogLevel.Off && !isRoot) {
12432 const logDir = process_1.getTempDirectory();
12434 this.tsServerLogFile = path_1.default.join(logDir, `tsserver.log`);
12435 this.info('TSServer log file :', this.tsServerLogFile);
12438 this.tsServerLogFile = null;
12439 this.error('Could not create TSServer log directory');
12441 if (this.tsServerLogFile) {
12442 args.push('--logVerbosity', configuration_1.TsServerLogLevel.toString(this._configuration.tsServerLogLevel));
12443 args.push('--logFile', this.tsServerLogFile);
12447 if (this.apiVersion.gte(api_1.default.v230)) {
12448 const pluginNames = this.pluginManager.plugins.map(x => x.name);
12449 let pluginPaths = this._configuration.tsServerPluginPaths;
12450 pluginPaths = pluginPaths.reduce((p, c) => {
12451 if (path_1.default.isAbsolute(c)) {
12455 let roots = coc_nvim_1.workspace.workspaceFolders.map(o => coc_nvim_1.Uri.parse(o.uri).fsPath);
12456 p.push(...roots.map(r => path_1.default.join(r, c)));
12460 if (pluginNames.length) {
12461 const isUsingBundledTypeScriptVersion = currentVersion.path == this.versionProvider.bundledVersion.path;
12462 args.push('--globalPlugins', pluginNames.join(','));
12463 for (const plugin of this.pluginManager.plugins) {
12464 if (isUsingBundledTypeScriptVersion || plugin.enableForWorkspaceTypeScriptVersions) {
12465 pluginPaths.push(plugin.path);
12469 if (pluginPaths.length) {
12470 args.push('--pluginProbeLocations', pluginPaths.join(','));
12473 if (this._configuration.locale) {
12474 args.push('--locale', this._configuration.locale);
12476 if (this._configuration.typingsCacheLocation) {
12477 args.push('--globalTypingsCacheLocation', `"${this._configuration.typingsCacheLocation}"`);
12479 if (this.apiVersion.gte(api_1.default.v234)) {
12480 let { npmLocation } = this._configuration;
12482 this.logger.info(`using npm from ${npmLocation}`);
12483 args.push('--npmLocation', `"${npmLocation}"`);
12486 if (this.apiVersion.gte(api_1.default.v291)) {
12487 args.push('--noGetErrOnBackgroundUpdate');
12489 if (this.apiVersion.gte(api_1.default.v345)) {
12490 args.push('--validateDefaultNpmLocation');
12494 getProjectRootPath(uri) {
12495 let root = coc_nvim_1.workspace.cwd;
12496 let u = coc_nvim_1.Uri.parse(uri);
12497 if (u.scheme !== 'file')
12499 let folder = coc_nvim_1.workspace.getWorkspaceFolder(uri);
12501 root = coc_nvim_1.Uri.parse(folder.uri).fsPath;
12504 let filepath = coc_nvim_1.Uri.parse(uri).fsPath;
12505 if (!filepath.startsWith(root)) {
12506 root = path_1.default.dirname(filepath);
12509 if (root == os_1.default.homedir())
12513 configurePlugin(pluginName, configuration) {
12514 if (this.apiVersion.gte(api_1.default.v314)) {
12515 if (!this.servicePromise)
12517 this.servicePromise.then(() => {
12518 // tslint:disable-next-line: no-floating-promises
12519 this.executeWithoutWaitingForResponse('configurePlugin', { pluginName, configuration });
12523 interruptGetErr(f) {
12524 return this.bufferSyncSupport.interuptGetErr(f);
12526 cancelInflightRequestsForResource(resource) {
12527 if (this.state !== coc_nvim_1.ServiceStat.Running || !this.tsServerProcess) {
12530 for (const request of this.tsServerProcess.toCancelOnResourceChange) {
12531 if (request.resource.toString() === resource.toString()) {
12537 exports.default = TypeScriptServiceClient;
12538 function getDiagnosticsKind(event) {
12539 switch (event.event) {
12541 return diagnostics_1.DiagnosticKind.Syntax;
12542 case 'semanticDiag':
12543 return diagnostics_1.DiagnosticKind.Semantic;
12544 case 'suggestionDiag':
12545 return diagnostics_1.DiagnosticKind.Suggestion;
12547 throw new Error('Unknown dignostics kind');
12549 const fenceCommands = new Set(['change', 'close', 'open']);
12550 function getQueueingType(command, lowPriority) {
12551 if (fenceCommands.has(command)) {
12552 return requestQueue_1.RequestQueueingType.Fence;
12554 return lowPriority ? requestQueue_1.RequestQueueingType.LowPriority : requestQueue_1.RequestQueueingType.Normal;
12560 /***/ (function(module, exports, __webpack_require__) {
12564 /*---------------------------------------------------------------------------------------------
12565 * Copyright (c) Microsoft Corporation. All rights reserved.
12566 * Licensed under the MIT License. See License.txt in the project root for license information.
12567 *--------------------------------------------------------------------------------------------*/
12568 Object.defineProperty(exports, "__esModule", { value: true });
12569 exports.disabledSchemes = exports.semanticSupportedSchemes = exports.walkThroughSnippet = exports.vsls = exports.git = exports.untitled = exports.file = void 0;
12570 exports.file = 'file';
12571 exports.untitled = 'untitled';
12572 exports.git = 'git';
12573 /** Live share scheme */
12574 exports.vsls = 'vsls';
12575 exports.walkThroughSnippet = 'walkThroughSnippet';
12576 exports.semanticSupportedSchemes = [
12579 exports.walkThroughSnippet,
12582 * File scheme for which JS/TS language feature should be disabled
12584 exports.disabledSchemes = new Set([
12592 /***/ (function(module, exports, __webpack_require__) {
12596 /*---------------------------------------------------------------------------------------------
12597 * Copyright (c) Microsoft Corporation. All rights reserved.
12598 * Licensed under the MIT License. See License.txt in the project root for license information.
12599 *--------------------------------------------------------------------------------------------*/
12600 Object.defineProperty(exports, "__esModule", { value: true });
12601 exports.CallbackMap = void 0;
12602 const typescriptService_1 = __webpack_require__(117);
12603 class CallbackMap {
12605 this._callbacks = new Map();
12606 this._asyncCallbacks = new Map();
12609 const cancellation = new typescriptService_1.ServerResponse.Cancelled(cause);
12610 for (const callback of this._callbacks.values()) {
12611 callback.onSuccess(cancellation);
12613 this._callbacks.clear();
12614 for (const callback of this._asyncCallbacks.values()) {
12615 callback.onSuccess(cancellation);
12617 this._asyncCallbacks.clear();
12619 add(seq, callback, isAsync) {
12621 this._asyncCallbacks.set(seq, callback);
12624 this._callbacks.set(seq, callback);
12628 const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
12633 if (!this._callbacks.delete(seq)) {
12634 this._asyncCallbacks.delete(seq);
12638 exports.CallbackMap = CallbackMap;
12643 /***/ (function(module, exports, __webpack_require__) {
12647 Object.defineProperty(exports, "__esModule", { value: true });
12648 exports.ExectuionTarget = exports.ServerResponse = void 0;
12649 var ServerResponse;
12650 (function (ServerResponse) {
12652 constructor(reason) {
12653 this.reason = reason;
12654 this.type = 'cancelled';
12657 ServerResponse.Cancelled = Cancelled;
12658 // tslint:disable-next-line: new-parens
12659 ServerResponse.NoContent = new class {
12661 this.type = 'noContent';
12664 })(ServerResponse = exports.ServerResponse || (exports.ServerResponse = {}));
12665 var ExectuionTarget;
12666 (function (ExectuionTarget) {
12667 ExectuionTarget[ExectuionTarget["Semantic"] = 0] = "Semantic";
12668 ExectuionTarget[ExectuionTarget["Syntax"] = 1] = "Syntax";
12669 })(ExectuionTarget = exports.ExectuionTarget || (exports.ExectuionTarget = {}));
12674 /***/ (function(module, exports, __webpack_require__) {
12678 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12679 if (k2 === undefined) k2 = k;
12680 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
12681 }) : (function(o, m, k, k2) {
12682 if (k2 === undefined) k2 = k;
12685 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
12686 Object.defineProperty(o, "default", { enumerable: true, value: v });
12687 }) : function(o, v) {
12690 var __importStar = (this && this.__importStar) || function (mod) {
12691 if (mod && mod.__esModule) return mod;
12693 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
12694 __setModuleDefault(result, mod);
12697 var __importDefault = (this && this.__importDefault) || function (mod) {
12698 return (mod && mod.__esModule) ? mod : { "default": mod };
12700 Object.defineProperty(exports, "__esModule", { value: true });
12701 /*---------------------------------------------------------------------------------------------
12702 * Copyright (c) Microsoft Corporation. All rights reserved.
12703 * Licensed under the MIT License. See License.txt in the project root for license information.
12704 *--------------------------------------------------------------------------------------------*/
12705 const coc_nvim_1 = __webpack_require__(1);
12706 const vscode_languageserver_protocol_1 = __webpack_require__(3);
12707 const api_1 = __importDefault(__webpack_require__(40));
12708 const async_1 = __webpack_require__(119);
12709 const typeConverters = __importStar(__webpack_require__(37));
12710 const languageModeIds_1 = __webpack_require__(120);
12711 const resourceMap_1 = __webpack_require__(121);
12712 class CloseOperation {
12713 constructor(args) {
12715 this.type = 0 /* Close */;
12718 class OpenOperation {
12719 constructor(args) {
12721 this.type = 1 /* Open */;
12724 class ChangeOperation {
12725 constructor(args) {
12727 this.type = 2 /* Change */;
12730 class SyncedBuffer {
12731 constructor(document, filepath, client, synchronizer) {
12732 this.document = document;
12733 this.filepath = filepath;
12734 this.client = client;
12735 this.synchronizer = synchronizer;
12736 this.state = 1 /* Initial */;
12740 file: this.filepath,
12741 fileContent: this.document.getText(),
12742 projectRootPath: this.client.getProjectRootPath(this.document.uri),
12744 const scriptKind = languageModeIds_1.mode2ScriptKind(this.document.languageId);
12746 args.scriptKindName = scriptKind;
12748 if (this.client.apiVersion.gte(api_1.default.v240)) {
12750 const tsPluginsForDocument = this.client.pluginManager.plugins
12751 .filter(x => x.languages.indexOf(this.document.languageId) >= 0);
12752 if (tsPluginsForDocument.length) {
12753 args.plugins = tsPluginsForDocument.map(plugin => plugin.name);
12756 this.synchronizer.open(this.resource, args);
12757 this.state = 2 /* Open */;
12760 return this.document.uri;
12763 return this.document.lineCount;
12766 if (this.document.languageId.startsWith('javascript')) {
12767 return 2 /* JavaScript */;
12769 return 1 /* TypeScript */;
12772 * @return Was the buffer open?
12775 if (this.state !== 2 /* Open */) {
12776 this.state = 2 /* Closed */;
12779 this.state = 2 /* Closed */;
12780 return this.synchronizer.close(this.resource, this.filepath);
12782 onContentChanged(events) {
12783 if (this.state !== 2 /* Open */) {
12784 console.error(`Unexpected buffer state: ${this.state}`);
12786 this.synchronizer.change(this.resource, this.filepath, events);
12789 class SyncedBufferMap extends resourceMap_1.ResourceMap {
12790 getForPath(filePath) {
12791 return this.get(coc_nvim_1.Uri.file(filePath).toString());
12794 return this.values;
12797 class PendingDiagnostics extends resourceMap_1.ResourceMap {
12798 getOrderedFileSet() {
12799 const orderedResources = Array.from(this.entries)
12800 .sort((a, b) => a.value - b.value)
12801 .map(entry => entry.uri);
12802 const map = new resourceMap_1.ResourceMap(this._normalizePath);
12803 for (const resource of orderedResources) {
12804 map.set(resource, undefined);
12810 * Manages synchronization of buffers with the TS server.
12812 * If supported, batches together file changes. This allows the TS server to more efficiently process changes.
12814 class BufferSynchronizer {
12815 constructor(client, pathNormalizer) {
12816 this.client = client;
12817 this._pending = new resourceMap_1.ResourceMap(pathNormalizer);
12819 open(resource, args) {
12820 if (this.supportsBatching) {
12821 this.updatePending(resource, new OpenOperation(args));
12824 this.client.executeWithoutWaitingForResponse('open', args);
12828 * @return Was the buffer open?
12830 close(resource, filepath) {
12831 if (this.supportsBatching) {
12832 return this.updatePending(resource, new CloseOperation(filepath));
12835 const args = { file: filepath };
12836 this.client.executeWithoutWaitingForResponse('close', args);
12840 change(resource, filepath, events) {
12841 if (!events.length) {
12844 if (this.supportsBatching) {
12845 this.updatePending(resource, new ChangeOperation({
12846 fileName: filepath,
12847 textChanges: events.map((change) => ({
12848 newText: change.text,
12849 start: typeConverters.Position.toLocation(change.range.start),
12850 end: typeConverters.Position.toLocation(change.range.end),
12855 for (const { range, text } of events) {
12856 const args = Object.assign({ insertString: text }, typeConverters.Range.toFormattingRequestArgs(filepath, range));
12857 this.client.executeWithoutWaitingForResponse('change', args);
12862 this._pending.clear();
12864 beforeCommand(command) {
12865 if (command === 'updateOpen') {
12871 if (!this.supportsBatching) {
12872 // We've already eagerly synchronized
12873 this._pending.clear();
12876 if (this._pending.size > 0) {
12877 const closedFiles = [];
12878 const openFiles = [];
12879 const changedFiles = [];
12880 for (const change of this._pending.values) {
12881 switch (change.type) {
12882 case 2 /* Change */:
12883 changedFiles.push(change.args);
12886 openFiles.push(change.args);
12888 case 0 /* Close */:
12889 closedFiles.push(change.args);
12893 this.client.execute('updateOpen', { changedFiles, closedFiles, openFiles }, vscode_languageserver_protocol_1.CancellationToken.None, { nonRecoverable: true });
12894 this._pending.clear();
12897 get supportsBatching() {
12898 return this.client.apiVersion.gte(api_1.default.v340);
12900 updatePending(resource, op) {
12902 case 0 /* Close */:
12903 const existing = this._pending.get(resource);
12904 switch (existing === null || existing === void 0 ? void 0 : existing.type) {
12906 this._pending.delete(resource);
12907 return false; // Open then close. No need to do anything
12911 if (this._pending.has(resource)) {
12912 // we saw this file before, make sure we flush before working with it again
12915 this._pending.set(resource, op);
12919 class GetErrRequest {
12920 constructor(client, uris, _token, onDone) {
12922 this._token = _token;
12923 this._done = false;
12924 let files = uris.map(uri => client.normalizePath(uri));
12929 const done = () => {
12936 client.executeAsync('geterr', args, _token.token).then(done, done);
12938 static executeGetErrRequest(client, uris, onDone) {
12939 const token = new vscode_languageserver_protocol_1.CancellationTokenSource();
12940 return new GetErrRequest(client, uris, token, onDone);
12944 this._token.cancel();
12946 this._token.dispose();
12949 class BufferSyncSupport {
12950 constructor(client, modeIds) {
12951 this.disposables = [];
12952 this._validateJavaScript = true;
12953 this._validateTypeScript = true;
12954 this.listening = false;
12955 this._onDelete = new vscode_languageserver_protocol_1.Emitter();
12956 this.onDelete = this._onDelete.event;
12957 this._onWillChange = new vscode_languageserver_protocol_1.Emitter();
12958 this.onWillChange = this._onWillChange.event;
12959 this.client = client;
12960 this.modeIds = new Set(modeIds);
12961 this.diagnosticDelayer = new async_1.Delayer(300);
12962 const pathNormalizer = (path) => this.client.toPath(path);
12963 this.syncedBuffers = new SyncedBufferMap(pathNormalizer);
12964 this.pendingDiagnostics = new PendingDiagnostics(pathNormalizer);
12965 this.synchronizer = new BufferSynchronizer(client, pathNormalizer);
12966 this.updateConfiguration();
12967 coc_nvim_1.workspace.onDidChangeConfiguration(this.updateConfiguration, this, this.disposables);
12970 if (this.listening) {
12973 this.listening = true;
12974 coc_nvim_1.workspace.onDidOpenTextDocument(this.openTextDocument, this, this.disposables);
12975 coc_nvim_1.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, this.disposables);
12976 coc_nvim_1.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, this.disposables);
12977 coc_nvim_1.workspace.textDocuments.forEach(this.openTextDocument, this);
12979 handles(resource) {
12980 return this.syncedBuffers.has(resource);
12983 this.pendingDiagnostics.clear();
12984 coc_nvim_1.disposeAll(this.disposables);
12985 this._onWillChange.dispose();
12986 this._onDelete.dispose();
12988 ensureHasBuffer(resource) {
12989 if (this.syncedBuffers.has(resource)) {
12992 const existingDocument = coc_nvim_1.workspace.textDocuments.find(doc => doc.uri.toString() === resource);
12993 if (existingDocument) {
12994 return this.openTextDocument(existingDocument);
12998 toResource(filePath) {
12999 const buffer = this.syncedBuffers.getForPath(filePath);
13001 return buffer.resource;
13002 return coc_nvim_1.Uri.file(filePath).toString();
13006 (_a = this.pendingGetErr) === null || _a === void 0 ? void 0 : _a.cancel();
13007 this.pendingDiagnostics.clear();
13008 this.synchronizer.reset();
13012 for (const buffer of this.syncedBuffers.allBuffers) {
13016 openTextDocument(document) {
13017 if (!this.modeIds.has(document.languageId)) {
13021 const resource = document.uri;
13022 const filepath = this.client.normalizePath(coc_nvim_1.Uri.parse(resource));
13026 if (this.syncedBuffers.has(resource)) {
13029 const syncedBuffer = new SyncedBuffer(document, filepath, this.client, this.synchronizer);
13030 this.syncedBuffers.set(resource, syncedBuffer);
13031 syncedBuffer.open();
13032 this.requestDiagnostic(syncedBuffer);
13035 closeResource(resource) {
13036 const syncedBuffer = this.syncedBuffers.get(resource);
13037 if (!syncedBuffer) {
13040 this.pendingDiagnostics.delete(resource);
13041 this.syncedBuffers.delete(resource);
13042 const wasBufferOpen = syncedBuffer.close();
13043 this._onDelete.fire(resource);
13044 if (wasBufferOpen) {
13045 this.requestAllDiagnostics();
13048 onDidCloseTextDocument(document) {
13049 this.closeResource(document.uri);
13051 onDidChangeTextDocument(e) {
13052 const syncedBuffer = this.syncedBuffers.get(e.textDocument.uri);
13053 if (!syncedBuffer) {
13056 this._onWillChange.fire(syncedBuffer.resource);
13057 syncedBuffer.onContentChanged(e.contentChanges);
13058 const didTrigger = this.requestDiagnostic(syncedBuffer);
13059 if (!didTrigger && this.pendingGetErr) {
13060 // In this case we always want to re-trigger all diagnostics
13061 this.pendingGetErr.cancel();
13062 this.pendingGetErr = undefined;
13063 this.triggerDiagnostics();
13066 beforeCommand(command) {
13067 this.synchronizer.beforeCommand(command);
13069 interuptGetErr(f) {
13070 if (!this.pendingGetErr) {
13073 this.pendingGetErr.cancel();
13074 this.pendingGetErr = undefined;
13075 const result = f();
13076 this.triggerDiagnostics();
13079 getErr(resources) {
13080 const handledResources = resources.filter(resource => {
13081 let syncedBuffer = this.syncedBuffers.get(resource.toString());
13082 return syncedBuffer && this.shouldValidate(syncedBuffer);
13084 if (!handledResources.length) {
13087 for (const resource of handledResources) {
13088 this.pendingDiagnostics.set(resource.toString(), Date.now());
13090 this.triggerDiagnostics();
13092 triggerDiagnostics(delay = 200) {
13093 this.diagnosticDelayer.trigger(() => {
13094 this.sendPendingDiagnostics();
13097 requestAllDiagnostics() {
13098 for (const buffer of this.syncedBuffers.allBuffers) {
13099 if (this.shouldValidate(buffer)) {
13100 this.pendingDiagnostics.set(buffer.resource, Date.now());
13103 this.triggerDiagnostics();
13105 requestDiagnostic(buffer) {
13106 if (!this.shouldValidate(buffer)) {
13109 this.pendingDiagnostics.set(buffer.resource, Date.now());
13110 const delay = Math.min(Math.max(Math.ceil(buffer.lineCount / 20), 300), 800);
13111 this.triggerDiagnostics(delay);
13114 hasPendingDiagnostics(uri) {
13115 return this.pendingDiagnostics.has(uri);
13117 sendPendingDiagnostics() {
13118 const orderedFileSet = this.pendingDiagnostics.getOrderedFileSet();
13119 if (this.pendingGetErr) {
13120 this.pendingGetErr.cancel();
13121 for (const uri of this.pendingGetErr.uris) {
13122 let resource = uri.toString();
13123 let syncedBuffer = this.syncedBuffers.get(resource);
13124 if (syncedBuffer && this.shouldValidate(syncedBuffer)) {
13125 orderedFileSet.set(resource, undefined);
13128 orderedFileSet.delete(resource);
13131 this.pendingGetErr = undefined;
13133 // Add all open TS buffers to the geterr request. They might be visible
13134 for (const buffer of this.syncedBuffers.values) {
13135 if (this.shouldValidate(buffer)) {
13136 orderedFileSet.set(buffer.resource, undefined);
13139 if (orderedFileSet.size) {
13140 let uris = Array.from(orderedFileSet.uris).map(uri => coc_nvim_1.Uri.parse(uri));
13141 const getErr = this.pendingGetErr = GetErrRequest.executeGetErrRequest(this.client, uris, () => {
13142 if (this.pendingGetErr === getErr) {
13143 this.pendingGetErr = undefined;
13147 this.pendingDiagnostics.clear();
13149 updateConfiguration() {
13150 const jsConfig = coc_nvim_1.workspace.getConfiguration('javascript', null);
13151 const tsConfig = coc_nvim_1.workspace.getConfiguration('typescript', null);
13152 this._validateJavaScript = jsConfig.get('validate.enable', true);
13153 this._validateTypeScript = tsConfig.get('validate.enable', true);
13155 shouldValidate(buffer) {
13156 switch (buffer.kind) {
13157 case 2 /* JavaScript */:
13158 return this._validateJavaScript;
13159 case 1 /* TypeScript */:
13161 return this._validateTypeScript;
13165 exports.default = BufferSyncSupport;
13170 /***/ (function(module, exports, __webpack_require__) {
13174 Object.defineProperty(exports, "__esModule", { value: true });
13175 exports.Delayer = void 0;
13177 constructor(defaultDelay) {
13178 this.defaultDelay = defaultDelay;
13179 this.timeout = null;
13180 this.completionPromise = null;
13181 this.onSuccess = null;
13184 trigger(task, delay = this.defaultDelay) {
13187 this.cancelTimeout();
13189 if (!this.completionPromise) {
13190 this.completionPromise = new Promise(resolve => {
13191 this.onSuccess = resolve;
13193 this.completionPromise = null;
13194 this.onSuccess = null;
13195 let result = this.task && this.task();
13200 if (delay >= 0 || this.timeout === null) {
13201 this.timeout = setTimeout(() => {
13202 this.timeout = null;
13203 if (this.onSuccess) {
13204 this.onSuccess(undefined);
13206 }, delay >= 0 ? delay : this.defaultDelay);
13208 return this.completionPromise;
13211 if (this.timeout !== null) {
13212 clearTimeout(this.timeout);
13213 this.timeout = null;
13217 exports.Delayer = Delayer;
13222 /***/ (function(module, exports, __webpack_require__) {
13226 /*---------------------------------------------------------------------------------------------
13227 * Copyright (c) Microsoft Corporation. All rights reserved.
13228 * Licensed under the MIT License. See License.txt in the project root for license information.
13229 *--------------------------------------------------------------------------------------------*/
13230 Object.defineProperty(exports, "__esModule", { value: true });
13231 exports.mode2ScriptKind = exports.languageIds = exports.jsxTags = exports.javascriptjsx = exports.javascriptreact = exports.javascript = exports.typescriptjsx = exports.typescripttsx = exports.typescriptreact = exports.typescript = void 0;
13232 exports.typescript = 'typescript';
13233 exports.typescriptreact = 'typescriptreact';
13234 exports.typescripttsx = 'typescript.tsx';
13235 exports.typescriptjsx = 'typescript.jsx';
13236 exports.javascript = 'javascript';
13237 exports.javascriptreact = 'javascriptreact';
13238 exports.javascriptjsx = 'javascript.jsx';
13239 exports.jsxTags = 'jsx-tags';
13240 exports.languageIds = [exports.typescript, exports.typescriptreact, exports.javascript, exports.javascriptreact, exports.javascriptjsx, exports.typescripttsx, exports.jsxTags];
13241 function mode2ScriptKind(mode) {
13243 case exports.typescript:
13245 case exports.typescripttsx:
13247 case exports.typescriptjsx:
13249 case exports.typescriptreact:
13251 case exports.javascript:
13253 case exports.javascriptreact:
13258 exports.mode2ScriptKind = mode2ScriptKind;
13263 /***/ (function(module, exports, __webpack_require__) {
13267 Object.defineProperty(exports, "__esModule", { value: true });
13268 exports.isWindowsPath = exports.ResourceMap = void 0;
13269 /*---------------------------------------------------------------------------------------------
13270 * Copyright (c) Microsoft Corporation. All rights reserved.
13271 * Licensed under the MIT License. See License.txt in the project root for license information.
13272 *--------------------------------------------------------------------------------------------*/
13273 const coc_nvim_1 = __webpack_require__(1);
13274 function defaultPathNormalizer(resource) {
13275 let u = coc_nvim_1.Uri.parse(resource);
13276 if (u.scheme === 'file') {
13279 return resource.toString();
13282 * Maps of file uris
13284 * Attempts to handle correct mapping on both case sensitive and case in-sensitive
13287 class ResourceMap {
13288 constructor(_normalizePath = defaultPathNormalizer) {
13289 this._normalizePath = _normalizePath;
13290 this._map = new Map();
13293 return this._map.size;
13296 return this._map.values();
13299 const file = this.toKey(uri);
13300 return !!file && this._map.has(file);
13303 const file = this.toKey(uri);
13306 let entry = this._map.get(file);
13307 return entry ? entry.value : undefined;
13310 const file = this.toKey(uri);
13312 this._map.set(file, { uri, value });
13316 const file = this.toKey(uri);
13318 this._map.delete(file);
13322 return Array.from(this._map.values()).map(x => x.value);
13325 return Array.from(this._map.values()).map(x => x.uri);
13331 const key = this._normalizePath
13332 ? this._normalizePath(uri)
13337 return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
13339 isCaseInsensitivePath(path) {
13340 if (isWindowsPath(path)) {
13343 return path[0] === '/' && this.onIsCaseInsenitiveFileSystem;
13345 get onIsCaseInsenitiveFileSystem() {
13346 if (process.platform === 'win32') {
13349 if (process.platform === 'darwin') {
13355 exports.ResourceMap = ResourceMap;
13356 function isWindowsPath(path) {
13357 return /^[a-zA-Z]:\\/.test(path);
13359 exports.isWindowsPath = isWindowsPath;
13364 /***/ (function(module, exports, __webpack_require__) {
13368 Object.defineProperty(exports, "__esModule", { value: true });
13369 exports.DiagnosticsManager = exports.DiagnosticKind = exports.DiagnosticSet = void 0;
13370 const coc_nvim_1 = __webpack_require__(1);
13371 const resourceMap_1 = __webpack_require__(121);
13372 class DiagnosticSet {
13374 this._map = new resourceMap_1.ResourceMap();
13376 set(uri, diagnostics) {
13377 this._map.set(uri, diagnostics);
13380 return this._map.get(uri) || [];
13383 this._map = new resourceMap_1.ResourceMap();
13386 exports.DiagnosticSet = DiagnosticSet;
13387 var DiagnosticKind;
13388 (function (DiagnosticKind) {
13389 DiagnosticKind[DiagnosticKind["Syntax"] = 0] = "Syntax";
13390 DiagnosticKind[DiagnosticKind["Semantic"] = 1] = "Semantic";
13391 DiagnosticKind[DiagnosticKind["Suggestion"] = 2] = "Suggestion";
13392 })(DiagnosticKind = exports.DiagnosticKind || (exports.DiagnosticKind = {}));
13393 const allDiagnosticKinds = [
13394 DiagnosticKind.Syntax,
13395 DiagnosticKind.Semantic,
13396 DiagnosticKind.Suggestion
13398 class DiagnosticsManager {
13400 this._diagnostics = new Map();
13401 this._pendingUpdates = new resourceMap_1.ResourceMap();
13402 this._enableJavascriptSuggestions = true;
13403 this._enableTypescriptSuggestions = true;
13404 this.updateDelay = 200;
13405 for (const kind of allDiagnosticKinds) {
13406 this._diagnostics.set(kind, new DiagnosticSet());
13408 this._currentDiagnostics = coc_nvim_1.languages.createDiagnosticCollection('tsserver');
13411 this._currentDiagnostics.dispose();
13412 for (const value of this._pendingUpdates.values) {
13413 clearTimeout(value);
13415 this._pendingUpdates = new resourceMap_1.ResourceMap();
13418 this._currentDiagnostics.clear();
13419 for (const diagnosticSet of this._diagnostics.values()) {
13420 diagnosticSet.clear();
13423 setEnableSuggestions(languageId, value) {
13424 let curr = languageId == 'javascript' ? this._enableJavascriptSuggestions : this._enableTypescriptSuggestions;
13425 if (curr == value) {
13428 if (languageId == 'javascript') {
13429 this._enableJavascriptSuggestions = value;
13432 this._enableTypescriptSuggestions = value;
13435 diagnosticsReceived(kind, uri, diagnostics) {
13436 const collection = this._diagnostics.get(kind);
13439 let doc = coc_nvim_1.workspace.getDocument(uri);
13442 if (diagnostics.length === 0) {
13443 const existing = collection.get(uri);
13444 if (existing.length === 0) {
13445 // No need to update
13449 collection.set(uri, diagnostics);
13450 this.scheduleDiagnosticsUpdate(uri);
13452 configFileDiagnosticsReceived(uri, diagnostics) {
13453 this._currentDiagnostics.set(uri, diagnostics);
13456 this._currentDiagnostics.delete(uri);
13458 getDiagnostics(uri) {
13459 return this._currentDiagnostics.get(uri) || [];
13462 scheduleDiagnosticsUpdate(uri) {
13463 if (!this._pendingUpdates.has(uri)) {
13464 this._pendingUpdates.set(uri, setTimeout(() => this.updateCurrentDiagnostics(uri), this.updateDelay));
13467 updateCurrentDiagnostics(uri) {
13468 if (this._pendingUpdates.has(uri)) {
13469 clearTimeout(this._pendingUpdates.get(uri));
13470 this._pendingUpdates.delete(uri);
13472 const allDiagnostics = [
13473 ...this._diagnostics.get(DiagnosticKind.Syntax).get(uri),
13474 ...this._diagnostics.get(DiagnosticKind.Semantic).get(uri),
13475 ...this.getSuggestionDiagnostics(uri)
13477 this._currentDiagnostics.set(uri, allDiagnostics);
13479 getSuggestionDiagnostics(uri) {
13480 const enabled = this.suggestionsEnabled(uri);
13481 return this._diagnostics
13482 .get(DiagnosticKind.Suggestion)
13486 // Still show unused
13487 return x.code == 6133;
13492 suggestionsEnabled(uri) {
13493 let doc = coc_nvim_1.workspace.getDocument(uri);
13496 if (doc.filetype.startsWith('javascript')) {
13497 return this._enableJavascriptSuggestions;
13499 if (doc.filetype.startsWith('typescript')) {
13500 return this._enableTypescriptSuggestions;
13505 exports.DiagnosticsManager = DiagnosticsManager;
13510 /***/ (function(module, exports, __webpack_require__) {
13514 /*---------------------------------------------------------------------------------------------
13515 * Copyright (c) Microsoft Corporation. All rights reserved.
13516 * Licensed under the MIT License. See License.txt in the project root for license information.
13517 *--------------------------------------------------------------------------------------------*/
13518 Object.defineProperty(exports, "__esModule", { value: true });
13519 exports.RequestQueue = exports.RequestQueueingType = void 0;
13520 var RequestQueueingType;
13521 (function (RequestQueueingType) {
13523 * Normal request that is executed in order.
13525 RequestQueueingType[RequestQueueingType["Normal"] = 1] = "Normal";
13527 * Request that normal requests jump in front of in the queue.
13529 RequestQueueingType[RequestQueueingType["LowPriority"] = 2] = "LowPriority";
13531 * A fence that blocks request reordering.
13533 * Fences are not reordered. Unlike a normal request, a fence will never jump in front of a low priority request
13534 * in the request queue.
13536 RequestQueueingType[RequestQueueingType["Fence"] = 3] = "Fence";
13537 })(RequestQueueingType = exports.RequestQueueingType || (exports.RequestQueueingType = {}));
13538 class RequestQueue {
13541 this.sequenceNumber = 0;
13544 return this.queue.length;
13547 if (item.queueingType === RequestQueueingType.Normal) {
13548 let index = this.queue.length - 1;
13549 while (index >= 0) {
13550 if (this.queue[index].queueingType !== RequestQueueingType.LowPriority) {
13555 this.queue.splice(index + 1, 0, item);
13558 // Only normal priority requests can be reordered. All other requests just go to the end.
13559 this.queue.push(item);
13563 return this.queue.shift();
13565 tryDeletePendingRequest(seq) {
13566 for (let i = 0; i < this.queue.length; i++) {
13567 if (this.queue[i].request.seq === seq) {
13568 this.queue.splice(i, 1);
13574 createRequest(command, args) {
13576 seq: this.sequenceNumber++,
13583 exports.RequestQueue = RequestQueue;
13588 /***/ (function(module, exports, __webpack_require__) {
13592 var __importDefault = (this && this.__importDefault) || function (mod) {
13593 return (mod && mod.__esModule) ? mod : { "default": mod };
13595 Object.defineProperty(exports, "__esModule", { value: true });
13596 exports.TypeScriptServiceConfiguration = exports.TsServerLogLevel = void 0;
13597 const coc_nvim_1 = __webpack_require__(1);
13598 const which_1 = __importDefault(__webpack_require__(125));
13599 var TsServerLogLevel;
13600 (function (TsServerLogLevel) {
13601 TsServerLogLevel[TsServerLogLevel["Off"] = 0] = "Off";
13602 TsServerLogLevel[TsServerLogLevel["Normal"] = 1] = "Normal";
13603 TsServerLogLevel[TsServerLogLevel["Terse"] = 2] = "Terse";
13604 TsServerLogLevel[TsServerLogLevel["Verbose"] = 3] = "Verbose";
13605 })(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
13606 (function (TsServerLogLevel) {
13607 function fromString(value) {
13608 switch (value && value.toLowerCase()) {
13610 return TsServerLogLevel.Normal;
13612 return TsServerLogLevel.Terse;
13614 return TsServerLogLevel.Verbose;
13617 return TsServerLogLevel.Off;
13620 TsServerLogLevel.fromString = fromString;
13621 function toString(value) {
13623 case TsServerLogLevel.Normal:
13625 case TsServerLogLevel.Terse:
13627 case TsServerLogLevel.Verbose:
13629 case TsServerLogLevel.Off:
13634 TsServerLogLevel.toString = toString;
13635 })(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
13636 class TypeScriptServiceConfiguration {
13638 this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
13639 coc_nvim_1.workspace.onDidChangeConfiguration(() => {
13640 this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
13644 return this._configuration.get('locale', null);
13647 return this._configuration.get('tsdk', null);
13649 get ignoreLocalTsserver() {
13650 return this._configuration.get('ignoreLocalTsserver', false);
13652 get tsServerLogLevel() {
13653 return TsServerLogLevel.fromString(this._configuration.get('log', null));
13655 // public readonly watchOptions: protocol.WatchOptions | undefined;
13656 get watchOptions() {
13657 return this._configuration.get('watchOptions');
13659 get typingsCacheLocation() {
13660 return this._configuration.get('typingsCacheLocation', '');
13662 get tsServerPluginPaths() {
13663 return this._configuration.get('pluginPaths', []);
13666 return this._configuration.get('implicitProjectConfig.checkJs', false);
13668 get experimentalDecorators() {
13669 return this._configuration.get('implicitProjectConfig.experimentalDecorators', false);
13671 get disableAutomaticTypeAcquisition() {
13672 return this._configuration.get('disableAutomaticTypeAcquisition', false);
13674 get formatOnType() {
13675 return this._configuration.get('formatOnType', false);
13677 get maxTsServerMemory() {
13678 return this._configuration.get('maxTsServerMemory', 0);
13681 return this._configuration.get('debugPort', parseInt(process.env['TSS_DEBUG'], 10));
13683 get npmLocation() {
13684 let path = this._configuration.get('npm', '');
13686 return coc_nvim_1.workspace.expand(path);
13688 path = which_1.default.sync('npm');
13695 static loadFromWorkspace() {
13696 return new TypeScriptServiceConfiguration();
13699 exports.TypeScriptServiceConfiguration = TypeScriptServiceConfiguration;
13704 /***/ (function(module, exports, __webpack_require__) {
13706 const isWindows = process.platform === 'win32' ||
13707 process.env.OSTYPE === 'cygwin' ||
13708 process.env.OSTYPE === 'msys'
13710 const path = __webpack_require__(13)
13711 const COLON = isWindows ? ';' : ':'
13712 const isexe = __webpack_require__(126)
13714 const getNotFoundError = (cmd) =>
13715 Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })
13717 const getPathInfo = (cmd, opt) => {
13718 const colon = opt.colon || COLON
13720 // If it has a slash, then we don't bother searching the pathenv.
13721 // just check the file itself, and that's it.
13722 const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
13725 // windows always checks the cwd first
13726 ...(isWindows ? [process.cwd()] : []),
13727 ...(opt.path || process.env.PATH ||
13728 /* istanbul ignore next: very unusual */ '').split(colon),
13731 const pathExtExe = isWindows
13732 ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
13734 const pathExt = isWindows ? pathExtExe.split(colon) : ['']
13737 if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
13738 pathExt.unshift('')
13748 const which = (cmd, opt, cb) => {
13749 if (typeof opt === 'function') {
13756 const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
13759 const step = i => new Promise((resolve, reject) => {
13760 if (i === pathEnv.length)
13761 return opt.all && found.length ? resolve(found)
13762 : reject(getNotFoundError(cmd))
13764 const ppRaw = pathEnv[i]
13765 const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
13767 const pCmd = path.join(pathPart, cmd)
13768 const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
13771 resolve(subStep(p, i, 0))
13774 const subStep = (p, i, ii) => new Promise((resolve, reject) => {
13775 if (ii === pathExt.length)
13776 return resolve(step(i + 1))
13777 const ext = pathExt[ii]
13778 isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
13781 found.push(p + ext)
13783 return resolve(p + ext)
13785 return resolve(subStep(p, i, ii + 1))
13789 return cb ? step(0).then(res => cb(null, res), cb) : step(0)
13792 const whichSync = (cmd, opt) => {
13795 const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
13798 for (let i = 0; i < pathEnv.length; i ++) {
13799 const ppRaw = pathEnv[i]
13800 const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
13802 const pCmd = path.join(pathPart, cmd)
13803 const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
13806 for (let j = 0; j < pathExt.length; j ++) {
13807 const cur = p + pathExt[j]
13809 const is = isexe.sync(cur, { pathExt: pathExtExe })
13820 if (opt.all && found.length)
13826 throw getNotFoundError(cmd)
13829 module.exports = which
13830 which.sync = whichSync
13835 /***/ (function(module, exports, __webpack_require__) {
13837 var fs = __webpack_require__(102)
13839 if (process.platform === 'win32' || global.TESTING_WINDOWS) {
13840 core = __webpack_require__(127)
13842 core = __webpack_require__(128)
13845 module.exports = isexe
13848 function isexe (path, options, cb) {
13849 if (typeof options === 'function') {
13855 if (typeof Promise !== 'function') {
13856 throw new TypeError('callback not provided')
13859 return new Promise(function (resolve, reject) {
13860 isexe(path, options || {}, function (er, is) {
13870 core(path, options || {}, function (er, is) {
13871 // ignore EACCES because that just means we aren't allowed to run it
13873 if (er.code === 'EACCES' || options && options.ignoreErrors) {
13882 function sync (path, options) {
13883 // my kingdom for a filtered catch
13885 return core.sync(path, options || {})
13887 if (options && options.ignoreErrors || er.code === 'EACCES') {
13898 /***/ (function(module, exports, __webpack_require__) {
13900 module.exports = isexe
13903 var fs = __webpack_require__(102)
13905 function checkPathExt (path, options) {
13906 var pathext = options.pathExt !== undefined ?
13907 options.pathExt : process.env.PATHEXT
13913 pathext = pathext.split(';')
13914 if (pathext.indexOf('') !== -1) {
13917 for (var i = 0; i < pathext.length; i++) {
13918 var p = pathext[i].toLowerCase()
13919 if (p && path.substr(-p.length).toLowerCase() === p) {
13926 function checkStat (stat, path, options) {
13927 if (!stat.isSymbolicLink() && !stat.isFile()) {
13930 return checkPathExt(path, options)
13933 function isexe (path, options, cb) {
13934 fs.stat(path, function (er, stat) {
13935 cb(er, er ? false : checkStat(stat, path, options))
13939 function sync (path, options) {
13940 return checkStat(fs.statSync(path), path, options)
13946 /***/ (function(module, exports, __webpack_require__) {
13948 module.exports = isexe
13951 var fs = __webpack_require__(102)
13953 function isexe (path, options, cb) {
13954 fs.stat(path, function (er, stat) {
13955 cb(er, er ? false : checkStat(stat, options))
13959 function sync (path, options) {
13960 return checkStat(fs.statSync(path), options)
13963 function checkStat (stat, options) {
13964 return stat.isFile() && checkMode(stat, options)
13967 function checkMode (stat, options) {
13968 var mod = stat.mode
13972 var myUid = options.uid !== undefined ?
13973 options.uid : process.getuid && process.getuid()
13974 var myGid = options.gid !== undefined ?
13975 options.gid : process.getgid && process.getgid()
13977 var u = parseInt('100', 8)
13978 var g = parseInt('010', 8)
13979 var o = parseInt('001', 8)
13982 var ret = (mod & o) ||
13983 (mod & g) && gid === myGid ||
13984 (mod & u) && uid === myUid ||
13985 (mod & ug) && myUid === 0
13993 /***/ (function(module, exports, __webpack_require__) {
13997 /*---------------------------------------------------------------------------------------------
13998 * Copyright (c) Microsoft Corporation. All rights reserved.
13999 * Licensed under the MIT License. See License.txt in the project root for license information.
14000 *--------------------------------------------------------------------------------------------*/
14001 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14002 if (k2 === undefined) k2 = k;
14003 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
14004 }) : (function(o, m, k, k2) {
14005 if (k2 === undefined) k2 = k;
14008 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14009 Object.defineProperty(o, "default", { enumerable: true, value: v });
14010 }) : function(o, v) {
14013 var __importStar = (this && this.__importStar) || function (mod) {
14014 if (mod && mod.__esModule) return mod;
14016 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
14017 __setModuleDefault(result, mod);
14020 Object.defineProperty(exports, "__esModule", { value: true });
14021 const coc_nvim_1 = __webpack_require__(1);
14022 const is = __importStar(__webpack_require__(130));
14025 if (this._channel) {
14026 return this._channel;
14028 this._channel = coc_nvim_1.workspace.createOutputChannel('tsserver');
14029 return this._channel;
14032 if (this._channel) {
14033 this._channel.dispose();
14036 data2String(data) {
14037 if (data instanceof Error) {
14038 if (is.string(data.stack)) {
14041 return data.message;
14043 if (is.boolean(data.success) && !data.success && is.string(data.message)) {
14044 return data.message;
14046 if (is.string(data)) {
14049 return data.toString();
14051 info(message, data) {
14052 this.logLevel('Info', message, data);
14054 warn(message, data) {
14055 this.logLevel('Warn', message, data);
14057 error(message, data) {
14058 // See https://github.com/Microsoft/TypeScript/issues/10496
14059 if (data && data.message === 'No content available.') {
14062 this.logLevel('Error', message, data);
14064 logLevel(level, message, data) {
14065 this.output.appendLine(`[${level} - ${new Date().toLocaleTimeString()}] ${message}`);
14067 this.output.appendLine(this.data2String(data));
14071 exports.default = Logger;
14076 /***/ (function(module, exports, __webpack_require__) {
14080 /*---------------------------------------------------------------------------------------------
14081 * Copyright (c) Microsoft Corporation. All rights reserved.
14082 * Licensed under the MIT License. See License.txt in the project root for license information.
14083 *--------------------------------------------------------------------------------------------*/
14084 Object.defineProperty(exports, "__esModule", { value: true });
14085 exports.string = exports.boolean = exports.defined = void 0;
14086 const toString = Object.prototype.toString;
14087 function defined(value) {
14088 return typeof value !== 'undefined';
14090 exports.defined = defined;
14091 function boolean(value) {
14092 return value === true || value === false;
14094 exports.boolean = boolean;
14095 function string(value) {
14096 return toString.call(value) === '[object String]';
14098 exports.string = string;
14103 /***/ (function(module, exports, __webpack_require__) {
14107 var __importDefault = (this && this.__importDefault) || function (mod) {
14108 return (mod && mod.__esModule) ? mod : { "default": mod };
14110 Object.defineProperty(exports, "__esModule", { value: true });
14111 exports.fork = exports.getTempFile = exports.getTempDirectory = exports.makeRandomHexString = void 0;
14112 /*---------------------------------------------------------------------------------------------
14113 * Copyright (c) Microsoft Corporation. All rights reserved.
14114 * Licensed under the MIT License. See License.txt in the project root for license information.
14115 *--------------------------------------------------------------------------------------------*/
14116 const child_process_1 = __importDefault(__webpack_require__(101));
14117 const net_1 = __importDefault(__webpack_require__(16));
14118 const os_1 = __importDefault(__webpack_require__(14));
14119 const path_1 = __importDefault(__webpack_require__(13));
14120 const fs_1 = __importDefault(__webpack_require__(102));
14121 function makeRandomHexString(length) {
14122 let chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
14124 for (let i = 0; i < length; i++) {
14125 const idx = Math.floor(chars.length * Math.random());
14126 result += chars[idx];
14130 exports.makeRandomHexString = makeRandomHexString;
14131 function getTempDirectory() {
14132 let dir = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`);
14133 if (!fs_1.default.existsSync(dir)) {
14134 fs_1.default.mkdirSync(dir);
14138 exports.getTempDirectory = getTempDirectory;
14139 function generatePipeName() {
14140 return getPipeName(makeRandomHexString(40));
14142 function getPipeName(name) {
14143 const fullName = 'coc-tsc-' + name;
14144 if (process.platform === 'win32') {
14145 return '\\\\.\\pipe\\' + fullName + '-sock';
14147 const tmpdir = getTempDirectory();
14148 // Mac/Unix: use socket file
14149 return path_1.default.join(tmpdir, fullName + '.sock');
14151 function getTempFile(name) {
14152 const fullName = 'coc-nvim-' + name;
14153 return path_1.default.join(getTempDirectory(), fullName + '.sock');
14155 exports.getTempFile = getTempFile;
14156 function generatePatchedEnv(env, stdInPipeName, stdOutPipeName, stdErrPipeName) {
14157 const newEnv = Object.assign({}, env);
14158 // Set the two unique pipe names and the electron flag as process env
14159 newEnv['STDIN_PIPE_NAME'] = stdInPipeName; // tslint:disable-line
14160 newEnv['STDOUT_PIPE_NAME'] = stdOutPipeName; // tslint:disable-line
14161 newEnv['STDERR_PIPE_NAME'] = stdErrPipeName; // tslint:disable-line
14162 newEnv['TSS_LOG'] = `-level verbose -file ${path_1.default.join(os_1.default.tmpdir(), 'coc-nvim-tsc.log')}`; // tslint:disable-line
14163 // Ensure we always have a PATH set
14164 newEnv['PATH'] = newEnv['PATH'] || process.env.PATH; // tslint:disable-line
14167 function fork(modulePath, args, options, logger, callback) {
14168 let callbackCalled = false;
14169 const resolve = (result) => {
14170 if (callbackCalled) {
14173 callbackCalled = true;
14174 callback(null, result);
14176 const reject = (err) => {
14177 if (callbackCalled) {
14180 callbackCalled = true;
14181 callback(err, null);
14183 // Generate three unique pipe names
14184 const stdInPipeName = generatePipeName();
14185 const stdOutPipeName = generatePipeName();
14186 const stdErrPipeName = generatePipeName();
14187 const newEnv = generatePatchedEnv(process.env, stdInPipeName, stdOutPipeName, stdErrPipeName);
14188 newEnv['NODE_PATH'] = path_1.default.join(modulePath, '..', '..', '..'); // tslint:disable-line
14190 // Begin listening to stderr pipe
14191 let stdErrServer = net_1.default.createServer(stdErrStream => {
14192 // From now on the childProcess.stderr is available for reading
14193 childProcess.stderr = stdErrStream;
14195 stdErrServer.listen(stdErrPipeName);
14196 // Begin listening to stdout pipe
14197 let stdOutServer = net_1.default.createServer(stdOutStream => {
14198 // The child process will write exactly one chunk with content `ready` when it has installed a listener to the stdin pipe
14199 stdOutStream.once('data', (_chunk) => {
14200 // The child process is sending me the `ready` chunk, time to connect to the stdin pipe
14201 childProcess.stdin = net_1.default.connect(stdInPipeName);
14202 // From now on the childProcess.stdout is available for reading
14203 childProcess.stdout = stdOutStream;
14204 resolve(childProcess);
14207 stdOutServer.listen(stdOutPipeName);
14208 let serverClosed = false;
14209 const closeServer = () => {
14210 if (serverClosed) {
14213 serverClosed = true;
14214 stdOutServer.close();
14215 stdErrServer.close();
14217 // Create the process
14218 logger.info('Forking TSServer', `PATH: ${newEnv['PATH']} `);
14219 const bootstrapperPath = path_1.default.resolve(__dirname, '../bin/tsserverForkStart');
14220 childProcess = child_process_1.default.fork(bootstrapperPath, [modulePath].concat(args), {
14223 execArgv: options.execArgv
14225 childProcess.once('error', (err) => {
14229 childProcess.once('exit', (err) => {
14234 exports.fork = fork;
14239 /***/ (function(module, exports, __webpack_require__) {
14243 Object.defineProperty(exports, "__esModule", { value: true });
14244 /*---------------------------------------------------------------------------------------------
14245 * Copyright (c) Microsoft Corporation. All rights reserved.
14246 * Licensed under the MIT License. See License.txt in the project root for license information.
14247 *--------------------------------------------------------------------------------------------*/
14248 const coc_nvim_1 = __webpack_require__(1);
14250 (function (Trace) {
14251 Trace[Trace["Off"] = 0] = "Off";
14252 Trace[Trace["Messages"] = 1] = "Messages";
14253 Trace[Trace["Verbose"] = 2] = "Verbose";
14254 })(Trace || (Trace = {}));
14255 (function (Trace) {
14256 function fromString(value) {
14257 value = value || '';
14258 value = value.toLowerCase();
14263 return Trace.Messages;
14265 return Trace.Verbose;
14270 Trace.fromString = fromString;
14271 })(Trace || (Trace = {}));
14273 constructor(logger) {
14274 this.logger = logger;
14275 this.trace = Tracer.readTrace();
14277 static readTrace() {
14278 let result = Trace.fromString(coc_nvim_1.workspace.getConfiguration('tsserver').get('trace.server', 'off'));
14279 if (result === Trace.Off && !!process.env.TSS_TRACE) {
14280 result = Trace.Messages;
14284 traceRequest(request, responseExpected, queueLength) {
14285 if (this.trace === Trace.Off)
14288 if (this.trace === Trace.Verbose && request.arguments) {
14289 data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`;
14291 this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? 'yes' : 'no'}. Current queue length: ${queueLength}`, data);
14293 traceResponse(response, startTime) {
14294 if (this.trace === Trace.Off) {
14298 if (this.trace === Trace.Verbose && response.body) {
14299 data = `Result: ${JSON.stringify(response.body, null, 4)}`;
14301 this.logTrace(`Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? '. Message: ' + response.message : ''}`, data);
14303 traceEvent(event) {
14304 if (this.trace === Trace.Off) {
14308 if (this.trace === Trace.Verbose && event.body) {
14309 data = `Data: ${JSON.stringify(event.body, null, 4)}`;
14311 this.logTrace(`Event received: ${event.event} (${event.seq}).`, data);
14313 logTrace(message, data) {
14314 if (this.trace !== Trace.Off) {
14315 this.logger.logLevel('Trace', message, data);
14318 traceRequestCompleted(command, request_seq, startTime) {
14319 if (this.trace === Trace.Off) {
14322 this.logTrace(`Async response received: ${command} (${request_seq}). Request took ${Date.now() - startTime} ms.`);
14325 exports.default = Tracer;
14330 /***/ (function(module, exports, __webpack_require__) {
14334 Object.defineProperty(exports, "__esModule", { value: true });
14335 exports.inferredProjectConfig = void 0;
14336 function inferredProjectConfig(config) {
14338 module: 'commonjs',
14342 if (config.checkJs) {
14343 base.checkJs = true;
14345 if (config.experimentalDecorators) {
14346 base.experimentalDecorators = true;
14350 exports.inferredProjectConfig = inferredProjectConfig;
14355 /***/ (function(module, exports, __webpack_require__) {
14359 var __importDefault = (this && this.__importDefault) || function (mod) {
14360 return (mod && mod.__esModule) ? mod : { "default": mod };
14362 Object.defineProperty(exports, "__esModule", { value: true });
14363 exports.TypeScriptVersionProvider = exports.TypeScriptVersion = void 0;
14364 /*---------------------------------------------------------------------------------------------
14365 * Copyright (c) Microsoft Corporation. All rights reserved.
14366 * Licensed under the MIT License. See License.txt in the project root for license information.
14367 *--------------------------------------------------------------------------------------------*/
14368 const fs_1 = __importDefault(__webpack_require__(102));
14369 const path_1 = __importDefault(__webpack_require__(13));
14370 const coc_nvim_1 = __webpack_require__(1);
14371 const api_1 = __importDefault(__webpack_require__(40));
14372 const requireFunc = true ? require : undefined;
14373 class TypeScriptVersion {
14374 constructor(path, _pathLabel) {
14376 this._pathLabel = _pathLabel;
14380 return path_1.default.resolve(this.path, '../bin/tsc');
14382 get tsServerPath() {
14383 return path_1.default.resolve(this.path, 'tsserver.js');
14386 return typeof this._pathLabel === 'undefined' ? this.path : this._pathLabel;
14389 return this.version != null;
14394 let api = this._api = this.getTypeScriptVersion(this.tsServerPath);
14397 get versionString() {
14398 const version = this.version;
14399 return version ? version.versionString : null;
14401 getTypeScriptVersion(serverPath) {
14402 if (!fs_1.default.existsSync(serverPath)) {
14405 const p = serverPath.split(path_1.default.sep);
14406 if (p.length <= 2) {
14409 const p2 = p.slice(0, -2);
14410 const modulePath = p2.join(path_1.default.sep);
14411 let fileName = path_1.default.join(modulePath, 'package.json');
14412 if (!fs_1.default.existsSync(fileName)) {
14413 // Special case for ts dev versions
14414 if (path_1.default.basename(modulePath) === 'built') {
14415 fileName = path_1.default.join(modulePath, '..', 'package.json');
14418 if (!fs_1.default.existsSync(fileName)) {
14421 const contents = fs_1.default.readFileSync(fileName).toString();
14424 desc = JSON.parse(contents);
14429 if (!desc || !desc.version) {
14432 return desc.version ? api_1.default.fromVersionString(desc.version) : undefined;
14435 exports.TypeScriptVersion = TypeScriptVersion;
14436 const MODULE_FOLDERS = ['node_modules/typescript/lib', '.vscode/pnpify/typescript/lib', '.yarn/sdks/typescript/lib'];
14437 class TypeScriptVersionProvider {
14438 constructor(configuration) {
14439 this.configuration = configuration;
14441 updateConfiguration(configuration) {
14442 this.configuration = configuration;
14444 getDefaultVersion() {
14445 // tsdk from configuration
14446 let { globalTsdk } = this.configuration;
14448 return new TypeScriptVersion(globalTsdk);
14449 return this.bundledVersion;
14451 get globalVersion() {
14452 let { globalTsdk } = this.configuration;
14454 return new TypeScriptVersion(coc_nvim_1.workspace.expand(globalTsdk));
14457 getLocalVersion() {
14458 let folders = coc_nvim_1.workspace.workspaceFolders.map(f => coc_nvim_1.Uri.parse(f.uri).fsPath);
14459 for (let p of folders) {
14460 for (let folder of MODULE_FOLDERS) {
14461 let libFolder = path_1.default.join(p, folder);
14462 if (fs_1.default.existsSync(libFolder)) {
14463 let version = new TypeScriptVersion(libFolder);
14464 if (version.isValid)
14471 get bundledVersion() {
14473 const file = requireFunc.resolve('typescript');
14474 const bundledVersion = new TypeScriptVersion(path_1.default.dirname(file), '');
14475 return bundledVersion;
14478 coc_nvim_1.workspace.showMessage('Bundled typescript module not found', 'error');
14483 exports.TypeScriptVersionProvider = TypeScriptVersionProvider;
14488 /***/ (function(module, exports, __webpack_require__) {
14492 Object.defineProperty(exports, "__esModule", { value: true });
14493 const coc_nvim_1 = __webpack_require__(1);
14494 class VersionStatus {
14495 constructor(_normalizePath, enableJavascript) {
14496 this._normalizePath = _normalizePath;
14497 this.enableJavascript = enableJavascript;
14498 this._versionBarEntry = coc_nvim_1.workspace.createStatusBarItem(99);
14499 this._onChangeEditorSub = coc_nvim_1.events.on('BufEnter', this.onBufEnter, this);
14500 this._versionBarEntry.show();
14503 this._versionBarEntry.dispose();
14504 this._onChangeEditorSub.dispose();
14506 onDidChangeTypeScriptVersion(_version) {
14507 this._versionBarEntry.text = `TSC`;
14509 set loading(isLoading) {
14510 this._versionBarEntry.isProgress = isLoading;
14512 checkFiletype(filetype) {
14513 if (filetype.startsWith('javascript') && this.enableJavascript) {
14516 return filetype.startsWith('typescript');
14518 async onBufEnter(bufnr) {
14519 let filetype = await coc_nvim_1.workspace.nvim.call('getbufvar', [bufnr, '&filetype', '']);
14520 if (this.checkFiletype(filetype)) {
14521 this._versionBarEntry.show();
14524 this._versionBarEntry.hide();
14528 exports.default = VersionStatus;
14533 /***/ (function(module, exports, __webpack_require__) {
14537 Object.defineProperty(exports, "__esModule", { value: true });
14538 exports.Reader = void 0;
14539 const DefaultSize = 8192;
14540 const ContentLength = 'Content-Length: ';
14541 const ContentLengthSize = Buffer.byteLength(ContentLength, 'utf8');
14542 const Blank = Buffer.from(' ', 'utf8')[0];
14543 const BackslashR = Buffer.from('\r', 'utf8')[0];
14544 const BackslashN = Buffer.from('\n', 'utf8')[0];
14545 class ProtocolBuffer {
14548 this.buffer = Buffer.allocUnsafe(DefaultSize);
14551 let toAppend = null;
14552 if (Buffer.isBuffer(data)) {
14556 toAppend = Buffer.from(data, 'utf8');
14558 if (this.buffer.length - this.index >= toAppend.length) {
14559 toAppend.copy(this.buffer, this.index, 0, toAppend.length);
14562 let newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) *
14564 if (this.index === 0) {
14565 this.buffer = Buffer.allocUnsafe(newSize);
14566 toAppend.copy(this.buffer, 0, 0, toAppend.length);
14569 this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
14572 this.index += toAppend.length;
14574 tryReadContentLength() {
14577 // we are utf8 encoding...
14578 while (current < this.index &&
14579 (this.buffer[current] === Blank ||
14580 this.buffer[current] === BackslashR ||
14581 this.buffer[current] === BackslashN)) {
14584 if (this.index < current + ContentLengthSize) {
14587 current += ContentLengthSize;
14588 let start = current;
14589 while (current < this.index && this.buffer[current] !== BackslashR) {
14592 if (current + 3 >= this.index ||
14593 this.buffer[current + 1] !== BackslashN ||
14594 this.buffer[current + 2] !== BackslashR ||
14595 this.buffer[current + 3] !== BackslashN) {
14598 let data = this.buffer.toString('utf8', start, current);
14599 result = parseInt(data, 10);
14600 this.buffer = this.buffer.slice(current + 4);
14601 this.index = this.index - (current + 4);
14604 tryReadContent(length) {
14605 if (this.index < length) {
14608 let result = this.buffer.toString('utf8', 0, length);
14609 let sourceStart = length;
14610 while (sourceStart < this.index &&
14611 (this.buffer[sourceStart] === BackslashR ||
14612 this.buffer[sourceStart] === BackslashN)) {
14615 this.buffer.copy(this.buffer, 0, sourceStart);
14616 this.index = this.index - sourceStart;
14621 constructor(readable, callback, onError) {
14622 this.readable = readable;
14623 this.callback = callback;
14624 this.onError = onError;
14625 this.buffer = new ProtocolBuffer();
14626 this.nextMessageLength = -1;
14627 this.readable.on('data', (data) => {
14628 this.onLengthData(data);
14631 onLengthData(data) {
14633 this.buffer.append(data);
14635 if (this.nextMessageLength === -1) {
14636 this.nextMessageLength = this.buffer.tryReadContentLength();
14637 if (this.nextMessageLength === -1) {
14641 const msg = this.buffer.tryReadContent(this.nextMessageLength);
14642 if (msg === null) {
14645 this.nextMessageLength = -1;
14646 const json = JSON.parse(msg);
14647 this.callback(json);
14655 exports.Reader = Reader;
14660 /***/ (function(module, exports, __webpack_require__) {
14664 Object.defineProperty(exports, "__esModule", { value: true });
14665 exports.AtaProgressReporter = void 0;
14666 /*---------------------------------------------------------------------------------------------
14667 * Copyright (c) Microsoft Corporation. All rights reserved.
14668 * Licensed under the MIT License. See License.txt in the project root for license information.
14669 *--------------------------------------------------------------------------------------------*/
14670 const vscode_languageserver_protocol_1 = __webpack_require__(3);
14671 const coc_nvim_1 = __webpack_require__(1);
14672 const typingsInstallTimeout = 30 * 1000;
14673 class TypingsStatus {
14674 constructor(client) {
14675 this._acquiringTypings = Object.create({});
14676 this._subscriptions = [];
14677 this._client = client;
14678 this._subscriptions.push(this._client.onDidBeginInstallTypings(event => this.onBeginInstallTypings(event.eventId)));
14679 this._subscriptions.push(this._client.onDidEndInstallTypings(event => this.onEndInstallTypings(event.eventId)));
14682 this._subscriptions.forEach(x => x.dispose());
14683 for (const eventId of Object.keys(this._acquiringTypings)) {
14684 clearTimeout(this._acquiringTypings[eventId]);
14687 get isAcquiringTypings() {
14688 return Object.keys(this._acquiringTypings).length > 0;
14690 onBeginInstallTypings(eventId) {
14691 if (this._acquiringTypings[eventId]) {
14694 this._acquiringTypings[eventId] = setTimeout(() => {
14695 this.onEndInstallTypings(eventId);
14696 }, typingsInstallTimeout);
14698 onEndInstallTypings(eventId) {
14699 const timer = this._acquiringTypings[eventId];
14701 clearTimeout(timer);
14703 delete this._acquiringTypings[eventId];
14706 exports.default = TypingsStatus;
14707 class AtaProgressReporter {
14708 constructor(client) {
14709 this._promises = new Map();
14710 this._invalid = false;
14711 this.statusItem = coc_nvim_1.workspace.createStatusBarItem(10, { progress: true });
14712 const disposables = [];
14713 disposables.push(client.onDidBeginInstallTypings(e => this._onBegin(e.eventId)));
14714 disposables.push(client.onDidEndInstallTypings(e => this._onEndOrTimeout(e.eventId)));
14715 disposables.push(client.onTypesInstallerInitializationFailed(_ => this.onTypesInstallerInitializationFailed()));
14716 this._disposable = vscode_languageserver_protocol_1.Disposable.create(() => {
14717 disposables.forEach(disposable => {
14718 disposable.dispose();
14723 this._disposable.dispose();
14724 this._promises.forEach(value => value());
14726 _onBegin(eventId) {
14727 const handle = setTimeout(() => this._onEndOrTimeout(eventId), typingsInstallTimeout);
14728 new Promise(resolve => {
14729 this._promises.set(eventId, () => {
14730 clearTimeout(handle);
14734 this.statusItem.text = 'Fetching data for better TypeScript IntelliSense';
14735 this.statusItem.show();
14737 _onEndOrTimeout(eventId) {
14738 this.statusItem.hide();
14739 const resolve = this._promises.get(eventId);
14741 this._promises.delete(eventId);
14745 onTypesInstallerInitializationFailed() {
14746 this.statusItem.hide();
14747 if (!this._invalid) {
14748 coc_nvim_1.workspace.showMessage('Could not install typings files for JavaScript language features. Please ensure that NPM is installed', 'error');
14750 this._invalid = true;
14753 exports.AtaProgressReporter = AtaProgressReporter;
14758 /***/ (function(module, exports, __webpack_require__) {
14762 var __importDefault = (this && this.__importDefault) || function (mod) {
14763 return (mod && mod.__esModule) ? mod : { "default": mod };
14765 Object.defineProperty(exports, "__esModule", { value: true });
14766 const coc_nvim_1 = __webpack_require__(1);
14767 const path_1 = __importDefault(__webpack_require__(13));
14768 const vscode_languageserver_protocol_1 = __webpack_require__(3);
14769 const countRegex = /Found\s+(\d+)\s+error/;
14770 const errorRegex = /^(.+)\((\d+),(\d+)\):\s(\w+)\sTS(\d+):\s*(.+)$/;
14772 (function (TscStatus) {
14773 TscStatus[TscStatus["INIT"] = 0] = "INIT";
14774 TscStatus[TscStatus["COMPILING"] = 1] = "COMPILING";
14775 TscStatus[TscStatus["RUNNING"] = 2] = "RUNNING";
14776 TscStatus[TscStatus["ERROR"] = 3] = "ERROR";
14777 })(TscStatus || (TscStatus = {}));
14778 class WatchProject {
14779 constructor(client) {
14780 this.client = client;
14781 this.disposables = [];
14782 this.statusItem = coc_nvim_1.workspace.createStatusBarItem(1, { progress: true });
14783 let task = this.task = coc_nvim_1.workspace.createTask('TSC');
14784 this.disposables.push(coc_nvim_1.commands.registerCommand(WatchProject.id, async () => {
14785 let opts = this.options = await this.getOptions();
14786 await this.start(opts);
14788 task.onExit(code => {
14790 coc_nvim_1.workspace.showMessage(`TSC exit with code ${code}`, 'warning');
14794 task.onStdout(lines => {
14795 for (let line of lines) {
14799 task.onStderr(lines => {
14800 coc_nvim_1.workspace.showMessage(`TSC error: ` + lines.join('\n'), 'error');
14802 this.disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => {
14805 this.check().catch(_e => {
14810 let running = await this.task.running;
14812 this.options = await this.getOptions();
14813 this.statusItem.isProgress = false;
14814 this.statusItem.text = '?';
14815 this.statusItem.show();
14821 async start(options) {
14822 await this.task.start(options);
14825 this.statusItem.hide();
14828 this.statusItem.text = 'compiling';
14829 this.statusItem.isProgress = true;
14830 this.statusItem.show();
14831 coc_nvim_1.workspace.nvim.call('setqflist', [[]], true);
14834 if (countRegex.test(line)) {
14835 let ms = line.match(countRegex);
14836 this.statusItem.text = ms[1] == '0' ? '✓' : '✗';
14837 this.statusItem.isProgress = false;
14839 else if (WatchProject.startTexts.findIndex(s => line.indexOf(s) !== -1) != -1) {
14843 let ms = line.match(errorRegex);
14846 let fullpath = path_1.default.join(this.options.cwd, ms[1]);
14847 let uri = coc_nvim_1.Uri.file(fullpath).toString();
14848 let doc = coc_nvim_1.workspace.getDocument(uri);
14849 let bufnr = doc ? doc.bufnr : null;
14851 filename: fullpath,
14852 lnum: Number(ms[2]),
14853 col: Number(ms[3]),
14854 text: `[tsc ${ms[5]}] ${ms[6]}`,
14855 type: /error/i.test(ms[4]) ? 'E' : 'W'
14858 item.bufnr = bufnr;
14859 coc_nvim_1.workspace.nvim.call('setqflist', [[item], 'a']);
14862 async getOptions() {
14863 let { tscPath } = this.client;
14865 coc_nvim_1.workspace.showMessage(`Local & global tsc not found`, 'error');
14868 let find = await coc_nvim_1.workspace.findUp(['tsconfig.json']);
14870 coc_nvim_1.workspace.showMessage('tsconfig.json not found!', 'error');
14873 let root = path_1.default.dirname(find);
14876 args: ['-p', 'tsconfig.json', '--watch', 'true', '--pretty', 'false'],
14881 coc_nvim_1.disposeAll(this.disposables);
14884 exports.default = WatchProject;
14885 WatchProject.id = 'tsserver.watchBuild';
14886 WatchProject.startTexts = ['Starting compilation in watch mode', 'Starting incremental compilation'];
14891 /***/ (function(module, exports, __webpack_require__) {
14895 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14896 if (k2 === undefined) k2 = k;
14897 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
14898 }) : (function(o, m, k, k2) {
14899 if (k2 === undefined) k2 = k;
14902 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14903 Object.defineProperty(o, "default", { enumerable: true, value: v });
14904 }) : function(o, v) {
14907 var __importStar = (this && this.__importStar) || function (mod) {
14908 if (mod && mod.__esModule) return mod;
14910 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
14911 __setModuleDefault(result, mod);
14914 var __importDefault = (this && this.__importDefault) || function (mod) {
14915 return (mod && mod.__esModule) ? mod : { "default": mod };
14917 Object.defineProperty(exports, "__esModule", { value: true });
14918 /*---------------------------------------------------------------------------------------------
14919 * Copyright (c) Microsoft Corporation. All rights reserved.
14920 * Licensed under the MIT License. See License.txt in the project root for license information.
14921 *--------------------------------------------------------------------------------------------*/
14922 const vscode_languageserver_protocol_1 = __webpack_require__(3);
14923 const coc_nvim_1 = __webpack_require__(1);
14924 const typeConverters = __importStar(__webpack_require__(37));
14925 const api_1 = __importDefault(__webpack_require__(40));
14926 function getSymbolKind(item) {
14927 switch (item.kind) {
14929 return vscode_languageserver_protocol_1.SymbolKind.Method;
14931 return vscode_languageserver_protocol_1.SymbolKind.Enum;
14933 return vscode_languageserver_protocol_1.SymbolKind.Function;
14935 return vscode_languageserver_protocol_1.SymbolKind.Class;
14937 return vscode_languageserver_protocol_1.SymbolKind.Interface;
14939 return vscode_languageserver_protocol_1.SymbolKind.Variable;
14941 return vscode_languageserver_protocol_1.SymbolKind.Variable;
14944 class TypeScriptWorkspaceSymbolProvider {
14945 constructor(client, languageIds) {
14946 this.client = client;
14947 this.languageIds = languageIds;
14949 async provideWorkspaceSymbols(search, token) {
14951 if (this.searchAllOpenProjects) {
14952 filepath = undefined;
14955 let uri = this.getUri();
14956 filepath = uri ? this.client.toPath(uri) : undefined;
14957 if (!filepath && this.client.apiVersion.lt(api_1.default.v390)) {
14963 searchValue: search,
14964 maxResultCount: 256,
14966 const response = await this.client.execute('navto', args, token);
14967 if (response.type !== 'response' || response.body == null)
14970 for (const item of response.body) {
14971 if (!item.containerName && item.kind === 'alias') {
14974 const label = TypeScriptWorkspaceSymbolProvider.getLabel(item);
14976 start: typeConverters.Position.fromLocation(item.start),
14977 end: typeConverters.Position.fromLocation(item.end),
14979 const symbolInfo = vscode_languageserver_protocol_1.SymbolInformation.create(label, getSymbolKind(item), range, this.client.toResource(item.file));
14980 result.push(symbolInfo);
14984 static getLabel(item) {
14985 let label = item.name;
14986 if (item.kind === 'method' || item.kind === 'function') {
14992 // typescript wants to have a resource even when asking
14993 // general questions so we check the active editor. If this
14994 // doesn't match we take the first TS document.
14995 const documents = coc_nvim_1.workspace.textDocuments;
14996 for (const document of documents) {
14997 if (this.languageIds.indexOf(document.languageId) >= 0) {
14998 return document.uri;
15003 get searchAllOpenProjects() {
15004 return this.client.apiVersion.gte(api_1.default.v390)
15005 && coc_nvim_1.workspace.getConfiguration('typescript').get('workspaceSymbols.scope', 'allOpenProjects') === 'allOpenProjects';
15008 exports.default = TypeScriptWorkspaceSymbolProvider;
15013 /***/ (function(module, exports, __webpack_require__) {
15017 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15018 if (k2 === undefined) k2 = k;
15019 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
15020 }) : (function(o, m, k, k2) {
15021 if (k2 === undefined) k2 = k;
15024 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15025 Object.defineProperty(o, "default", { enumerable: true, value: v });
15026 }) : function(o, v) {
15029 var __importStar = (this && this.__importStar) || function (mod) {
15030 if (mod && mod.__esModule) return mod;
15032 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
15033 __setModuleDefault(result, mod);
15036 Object.defineProperty(exports, "__esModule", { value: true });
15037 exports.standardLanguageDescriptions = void 0;
15038 /*---------------------------------------------------------------------------------------------
15039 * Copyright (c) Microsoft Corporation. All rights reserved.
15040 * Licensed under the MIT License. See License.txt in the project root for license information.
15041 *--------------------------------------------------------------------------------------------*/
15042 const languageModeIds = __importStar(__webpack_require__(120));
15043 exports.standardLanguageDescriptions = [
15046 diagnosticSource: 'ts',
15047 diagnosticOwner: 'typescript',
15048 modeIds: [languageModeIds.typescript, languageModeIds.typescriptreact,
15049 languageModeIds.typescripttsx, languageModeIds.typescriptjsx],
15050 diagnosticLanguage: 1 /* TypeScript */,
15051 configFile: 'tsconfig.json',
15052 configFilePattern: /^tsconfig(\..*)?\.json$/gi
15056 diagnosticSource: 'ts',
15057 diagnosticOwner: 'typescript',
15058 modeIds: [languageModeIds.javascript, languageModeIds.javascriptreact, languageModeIds.javascriptjsx],
15059 diagnosticLanguage: 0 /* JavaScript */,
15060 configFile: 'jsconfig.json',
15061 configFilePattern: /^jsconfig(\..*)?\.json$/gi
15068 /***/ (function(module, exports, __webpack_require__) {
15072 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15073 if (k2 === undefined) k2 = k;
15074 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
15075 }) : (function(o, m, k, k2) {
15076 if (k2 === undefined) k2 = k;
15079 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15080 Object.defineProperty(o, "default", { enumerable: true, value: v });
15081 }) : function(o, v) {
15084 var __importStar = (this && this.__importStar) || function (mod) {
15085 if (mod && mod.__esModule) return mod;
15087 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
15088 __setModuleDefault(result, mod);
15091 Object.defineProperty(exports, "__esModule", { value: true });
15092 exports.ConfigurePluginCommand = exports.AutoFixCommand = exports.TypeScriptGoToProjectConfigCommand = exports.OpenTsServerLogCommand = exports.ReloadProjectsCommand = void 0;
15093 const coc_nvim_1 = __webpack_require__(1);
15094 const vscode_languageserver_protocol_1 = __webpack_require__(3);
15095 const typeConverters = __importStar(__webpack_require__(37));
15096 const vscode_languageserver_types_1 = __webpack_require__(18);
15097 const modules_1 = __webpack_require__(100);
15098 const helper_1 = __webpack_require__(98);
15099 class ReloadProjectsCommand {
15100 constructor(service) {
15101 this.service = service;
15102 this.id = 'tsserver.reloadProjects';
15105 let client = await this.service.getClientHost();
15106 client.reloadProjects();
15107 coc_nvim_1.workspace.showMessage('projects reloaded');
15110 exports.ReloadProjectsCommand = ReloadProjectsCommand;
15111 class OpenTsServerLogCommand {
15112 constructor(service) {
15113 this.service = service;
15114 this.id = 'tsserver.openTsServerLog';
15117 let client = await this.service.getClientHost();
15118 client.serviceClient.openTsServerLogFile(); // tslint:disable-line
15121 exports.OpenTsServerLogCommand = OpenTsServerLogCommand;
15122 class TypeScriptGoToProjectConfigCommand {
15123 constructor(service) {
15124 this.service = service;
15125 this.id = 'tsserver.goToProjectConfig';
15128 let client = await this.service.getClientHost();
15129 let doc = await coc_nvim_1.workspace.document;
15130 let { languageId } = doc.textDocument;
15131 if (client.serviceClient.modeIds.indexOf(languageId) == -1) {
15132 throw new Error(`Could not determine TypeScript or JavaScript project. Unsupported file type: ${languageId}`);
15135 await goToProjectConfig(client, doc.uri);
15138 exports.TypeScriptGoToProjectConfigCommand = TypeScriptGoToProjectConfigCommand;
15139 async function goToProjectConfig(clientHost, uri) {
15140 const client = clientHost.serviceClient;
15141 const file = client.toPath(uri);
15144 res = await client.execute('projectInfo', { file, needFileNameList: false }, vscode_languageserver_protocol_1.CancellationToken.None);
15149 if (!res || !res.body) {
15150 coc_nvim_1.workspace.showMessage('Could not determine TypeScript or JavaScript project.', 'warning');
15153 const { configFileName } = res.body;
15154 if (configFileName && !isImplicitProjectConfigFile(configFileName)) {
15155 await coc_nvim_1.workspace.openResource(coc_nvim_1.Uri.file(configFileName).toString());
15158 coc_nvim_1.workspace.showMessage('Config file not found', 'warning');
15160 function isImplicitProjectConfigFile(configFileName) {
15161 return configFileName.indexOf('/dev/null/') === 0;
15163 const autoFixableDiagnosticCodes = new Set([
15168 class AutoFixCommand {
15169 constructor(service) {
15170 this.service = service;
15171 this.id = 'tsserver.executeAutofix';
15174 if (this.service.state != coc_nvim_1.ServiceStat.Running) {
15175 throw new Error('service not running');
15178 let client = await this.service.getClientHost();
15179 let document = await coc_nvim_1.workspace.document;
15180 let handles = await client.handles(document.textDocument);
15182 throw new Error(`Document ${document.uri} is not handled by tsserver.`);
15185 let file = client.serviceClient.toPath(document.uri);
15186 let diagnostics = coc_nvim_1.diagnosticManager.getDiagnostics(document.uri);
15187 let missingDiagnostics = diagnostics.filter(o => o.code == 2307);
15188 if (missingDiagnostics.length) {
15189 let names = missingDiagnostics.map(o => {
15190 let ms = o.message.match(/module\s'(.+)'\./);
15191 return ms ? ms[1] : null;
15193 names = names.filter(s => s != null);
15194 if (names.length) {
15195 modules_1.installModules(document.uri, names).catch(e => {
15196 console.error(e.message); // tslint:disable-line
15200 diagnostics = diagnostics.filter(x => autoFixableDiagnosticCodes.has(x.code));
15201 if (diagnostics.length == 0)
15203 diagnostics = diagnostics.reduce((arr, curr) => {
15204 if (curr.code == 2304 && arr.findIndex(o => o.message == curr.message) != -1)
15212 for (let diagnostic of diagnostics) {
15213 const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+(diagnostic.code)] });
15214 const response = await client.serviceClient.execute('getCodeFixes', args, vscode_languageserver_protocol_1.CancellationToken.None);
15215 if (response.type !== 'response' || !response.body || response.body.length < 1) {
15216 if (diagnostic.code == 2304) {
15217 let { range } = diagnostic;
15218 let line = document.getline(range.start.line);
15219 let name = line.slice(range.start.character, range.end.character);
15220 if (helper_1.nodeModules.indexOf(name) !== -1 && names.indexOf(name) == -1) {
15223 range: vscode_languageserver_types_1.Range.create(0, 0, 0, 0),
15224 newText: `import ${name} from '${name}'\n`
15226 command = 'tsserver.organizeImports';
15231 const fix = response.body[0];
15232 for (let change of fix.changes) {
15233 if (change.fileName != file)
15236 for (let ch of change.textChanges) {
15238 range: typeConverters.Range.fromTextSpan(ch),
15239 newText: ch.newText
15245 await document.applyEdits(edits);
15247 coc_nvim_1.commands.executeCommand(command);
15250 exports.AutoFixCommand = AutoFixCommand;
15251 class ConfigurePluginCommand {
15252 constructor(pluginManager) {
15253 this.pluginManager = pluginManager;
15254 this.id = '_typescript.configurePlugin';
15256 execute(pluginId, configuration) {
15257 this.pluginManager.setConfiguration(pluginId, configuration);
15260 exports.ConfigurePluginCommand = ConfigurePluginCommand;
15265 /***/ (function(module, exports, __webpack_require__) {
15269 /*---------------------------------------------------------------------------------------------
15270 * Copyright (c) Microsoft Corporation. All rights reserved.
15271 * Licensed under the MIT License. See License.txt in the project root for license information.
15272 *--------------------------------------------------------------------------------------------*/
15273 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15274 if (k2 === undefined) k2 = k;
15275 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
15276 }) : (function(o, m, k, k2) {
15277 if (k2 === undefined) k2 = k;
15280 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15281 Object.defineProperty(o, "default", { enumerable: true, value: v });
15282 }) : function(o, v) {
15285 var __importStar = (this && this.__importStar) || function (mod) {
15286 if (mod && mod.__esModule) return mod;
15288 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
15289 __setModuleDefault(result, mod);
15292 Object.defineProperty(exports, "__esModule", { value: true });
15293 exports.PluginManager = void 0;
15294 const coc_nvim_1 = __webpack_require__(1);
15295 const arrays = __importStar(__webpack_require__(91));
15296 const vscode_languageserver_protocol_1 = __webpack_require__(3);
15297 var TypeScriptServerPlugin;
15298 (function (TypeScriptServerPlugin) {
15299 function equals(a, b) {
15300 return a.path === b.path
15301 && a.name === b.name
15302 && a.enableForWorkspaceTypeScriptVersions === b.enableForWorkspaceTypeScriptVersions
15303 && arrays.equals(a.languages, b.languages);
15305 TypeScriptServerPlugin.equals = equals;
15306 })(TypeScriptServerPlugin || (TypeScriptServerPlugin = {}));
15307 class PluginManager {
15309 this._pluginConfigurations = new Map();
15310 this._disposables = [];
15311 this._onDidUpdatePlugins = this._register(new vscode_languageserver_protocol_1.Emitter());
15312 this.onDidChangePlugins = this._onDidUpdatePlugins.event;
15313 this._onDidUpdateConfig = this._register(new vscode_languageserver_protocol_1.Emitter());
15314 this.onDidUpdateConfig = this._onDidUpdateConfig.event;
15315 let loadPlugins = () => {
15316 if (!this._plugins) {
15319 const newPlugins = this.readPlugins();
15320 if (!arrays.equals(arrays.flatten(Array.from(this._plugins.values())), arrays.flatten(Array.from(newPlugins.values())), TypeScriptServerPlugin.equals)) {
15321 this._plugins = newPlugins;
15322 this._onDidUpdatePlugins.fire(this);
15325 coc_nvim_1.extensions.onDidActiveExtension(loadPlugins, undefined, this._disposables);
15326 coc_nvim_1.extensions.onDidUnloadExtension(loadPlugins, undefined, this._disposables);
15329 coc_nvim_1.disposeAll(this._disposables);
15332 if (!this._plugins) {
15333 this._plugins = this.readPlugins();
15335 return arrays.flatten(Array.from(this._plugins.values()));
15338 this._disposables.push(value);
15341 setConfiguration(pluginId, config) {
15342 this._pluginConfigurations.set(pluginId, config);
15343 this._onDidUpdateConfig.fire({ pluginId, config });
15346 return this._pluginConfigurations.entries();
15349 const pluginMap = new Map();
15350 for (const extension of coc_nvim_1.extensions.all) {
15351 const pack = extension.packageJSON;
15352 if (pack.contributes && Array.isArray(pack.contributes.typescriptServerPlugins)) {
15353 const plugins = [];
15354 for (const plugin of pack.contributes.typescriptServerPlugins) {
15357 enableForWorkspaceTypeScriptVersions: !!plugin.enableForWorkspaceTypeScriptVersions,
15358 path: extension.extensionPath,
15359 languages: Array.isArray(plugin.languages) ? plugin.languages : [],
15362 if (plugins.length) {
15363 pluginMap.set(extension.id, plugins);
15370 exports.PluginManager = PluginManager;