My dotfiles
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

15357 lines
571 KiB

  1. (function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
  2. /******/ // The module cache
  3. /******/ var installedModules = {};
  4. /******/
  5. /******/ // The require function
  6. /******/ function __webpack_require__(moduleId) {
  7. /******/
  8. /******/ // Check if module is in cache
  9. /******/ if(installedModules[moduleId]) {
  10. /******/ return installedModules[moduleId].exports;
  11. /******/ }
  12. /******/ // Create a new module (and put it into the cache)
  13. /******/ var module = installedModules[moduleId] = {
  14. /******/ i: moduleId,
  15. /******/ l: false,
  16. /******/ exports: {}
  17. /******/ };
  18. /******/
  19. /******/ // Execute the module function
  20. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  21. /******/
  22. /******/ // Flag the module as loaded
  23. /******/ module.l = true;
  24. /******/
  25. /******/ // Return the exports of the module
  26. /******/ return module.exports;
  27. /******/ }
  28. /******/
  29. /******/
  30. /******/ // expose the modules object (__webpack_modules__)
  31. /******/ __webpack_require__.m = modules;
  32. /******/
  33. /******/ // expose the module cache
  34. /******/ __webpack_require__.c = installedModules;
  35. /******/
  36. /******/ // define getter function for harmony exports
  37. /******/ __webpack_require__.d = function(exports, name, getter) {
  38. /******/ if(!__webpack_require__.o(exports, name)) {
  39. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  40. /******/ }
  41. /******/ };
  42. /******/
  43. /******/ // define __esModule on exports
  44. /******/ __webpack_require__.r = function(exports) {
  45. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  46. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  47. /******/ }
  48. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  49. /******/ };
  50. /******/
  51. /******/ // create a fake namespace object
  52. /******/ // mode & 1: value is a module id, require it
  53. /******/ // mode & 2: merge all properties of value into the ns
  54. /******/ // mode & 4: return value when already ns object
  55. /******/ // mode & 8|1: behave like require
  56. /******/ __webpack_require__.t = function(value, mode) {
  57. /******/ if(mode & 1) value = __webpack_require__(value);
  58. /******/ if(mode & 8) return value;
  59. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  60. /******/ var ns = Object.create(null);
  61. /******/ __webpack_require__.r(ns);
  62. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  63. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  64. /******/ return ns;
  65. /******/ };
  66. /******/
  67. /******/ // getDefaultExport function for compatibility with non-harmony modules
  68. /******/ __webpack_require__.n = function(module) {
  69. /******/ var getter = module && module.__esModule ?
  70. /******/ function getDefault() { return module['default']; } :
  71. /******/ function getModuleExports() { return module; };
  72. /******/ __webpack_require__.d(getter, 'a', getter);
  73. /******/ return getter;
  74. /******/ };
  75. /******/
  76. /******/ // Object.prototype.hasOwnProperty.call
  77. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  78. /******/
  79. /******/ // __webpack_public_path__
  80. /******/ __webpack_require__.p = "";
  81. /******/
  82. /******/
  83. /******/ // Load entry module and return exports
  84. /******/ return __webpack_require__(__webpack_require__.s = 0);
  85. /******/ })
  86. /************************************************************************/
  87. /******/ ([
  88. /* 0 */
  89. /***/ (function(module, exports, __webpack_require__) {
  90. "use strict";
  91. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  92. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  93. return new (P || (P = Promise))(function (resolve, reject) {
  94. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  95. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  96. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  97. step((generator = generator.apply(thisArg, _arguments || [])).next());
  98. });
  99. };
  100. var __importDefault = (this && this.__importDefault) || function (mod) {
  101. return (mod && mod.__esModule) ? mod : { "default": mod };
  102. };
  103. Object.defineProperty(exports, "__esModule", { value: true });
  104. exports.activate = void 0;
  105. const coc_nvim_1 = __webpack_require__(1);
  106. const server_1 = __importDefault(__webpack_require__(2));
  107. const commands_1 = __webpack_require__(140);
  108. const organizeImports_1 = __webpack_require__(114);
  109. const plugins_1 = __webpack_require__(141);
  110. function activate(context) {
  111. return __awaiter(this, void 0, void 0, function* () {
  112. let { subscriptions } = context;
  113. const config = coc_nvim_1.workspace.getConfiguration().get('tsserver', {});
  114. if (!config.enable)
  115. return;
  116. const pluginManager = new plugins_1.PluginManager();
  117. const service = new server_1.default(pluginManager);
  118. subscriptions.push(coc_nvim_1.services.regist(service));
  119. yield service.start();
  120. function registCommand(cmd) {
  121. let { id, execute } = cmd;
  122. subscriptions.push(coc_nvim_1.commands.registerCommand(id, execute, cmd));
  123. }
  124. registCommand(new commands_1.AutoFixCommand(service.clientHost));
  125. registCommand(new commands_1.ReloadProjectsCommand(service.clientHost));
  126. registCommand(new commands_1.OpenTsServerLogCommand(service.clientHost));
  127. registCommand(new commands_1.TypeScriptGoToProjectConfigCommand(service.clientHost));
  128. registCommand(new organizeImports_1.OrganizeImportsCommand(service.clientHost.serviceClient));
  129. registCommand(new commands_1.ConfigurePluginCommand(pluginManager));
  130. registCommand(coc_nvim_1.commands.register({
  131. id: 'tsserver.restart',
  132. execute: () => {
  133. // tslint:disable-next-line:no-floating-promises
  134. service.stop().then(() => {
  135. setTimeout(() => {
  136. service.restart();
  137. }, 100);
  138. });
  139. }
  140. }));
  141. return {
  142. configurePlugin: (pluginId, configuration) => {
  143. pluginManager.setConfiguration(pluginId, configuration);
  144. }
  145. };
  146. });
  147. }
  148. exports.activate = activate;
  149. /***/ }),
  150. /* 1 */
  151. /***/ (function(module, exports) {
  152. module.exports = require("coc.nvim");
  153. /***/ }),
  154. /* 2 */
  155. /***/ (function(module, exports, __webpack_require__) {
  156. "use strict";
  157. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  158. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  159. return new (P || (P = Promise))(function (resolve, reject) {
  160. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  161. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  162. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  163. step((generator = generator.apply(thisArg, _arguments || [])).next());
  164. });
  165. };
  166. var __importDefault = (this && this.__importDefault) || function (mod) {
  167. return (mod && mod.__esModule) ? mod : { "default": mod };
  168. };
  169. Object.defineProperty(exports, "__esModule", { value: true });
  170. const coc_nvim_1 = __webpack_require__(1);
  171. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  172. const typescriptServiceClientHost_1 = __importDefault(__webpack_require__(33));
  173. const languageDescription_1 = __webpack_require__(115);
  174. class TsserverService {
  175. constructor(pluginManager) {
  176. this.pluginManager = pluginManager;
  177. this.id = 'tsserver';
  178. this.name = 'tsserver';
  179. this.state = coc_nvim_1.ServiceStat.Initial;
  180. this._onDidServiceReady = new vscode_languageserver_protocol_1.Emitter();
  181. this.onServiceReady = this._onDidServiceReady.event;
  182. this.disposables = [];
  183. this.descriptions = [];
  184. const config = coc_nvim_1.workspace.getConfiguration('tsserver');
  185. const enableJavascript = !!config.get('enableJavascript');
  186. this.enable = config.get('enable');
  187. this.descriptions = languageDescription_1.standardLanguageDescriptions.filter(o => {
  188. return enableJavascript ? true : o.id != 'javascript';
  189. });
  190. this.selector = this.descriptions.reduce((arr, c) => {
  191. return arr.concat(c.modeIds);
  192. }, []);
  193. coc_nvim_1.workspace.onDidOpenTextDocument(doc => {
  194. this.ensureConfigurationForDocument(doc);
  195. }, null, this.disposables);
  196. }
  197. get config() {
  198. return coc_nvim_1.workspace.getConfiguration('tsserver');
  199. }
  200. ensureConfigurationForDocument(document) {
  201. let uri = coc_nvim_1.Uri.parse(document.uri);
  202. let language = this.clientHost.findLanguage(uri);
  203. if (!language)
  204. return;
  205. language.fileConfigurationManager.ensureConfigurationForDocument(document).catch(_e => {
  206. // noop
  207. });
  208. }
  209. start() {
  210. if (this.clientHost)
  211. return;
  212. this.state = coc_nvim_1.ServiceStat.Starting;
  213. this.clientHost = new typescriptServiceClientHost_1.default(this.descriptions, this.pluginManager);
  214. this.disposables.push(this.clientHost);
  215. let client = this.clientHost.serviceClient;
  216. return new Promise(resolve => {
  217. let started = false;
  218. client.onTsServerStarted(() => {
  219. Object.defineProperty(this, 'state', {
  220. get: () => {
  221. return this.clientHost.serviceClient.state;
  222. }
  223. });
  224. this._onDidServiceReady.fire(void 0);
  225. this.ensureConfiguration();
  226. if (!started) {
  227. started = true;
  228. resolve();
  229. }
  230. });
  231. });
  232. }
  233. ensureConfiguration() {
  234. if (!this.clientHost)
  235. return;
  236. for (let doc of coc_nvim_1.workspace.documents) {
  237. this.ensureConfigurationForDocument(doc.textDocument);
  238. }
  239. }
  240. dispose() {
  241. coc_nvim_1.disposeAll(this.disposables);
  242. }
  243. restart() {
  244. return __awaiter(this, void 0, void 0, function* () {
  245. if (!this.clientHost)
  246. return;
  247. let client = this.clientHost.serviceClient;
  248. yield client.restartTsServer();
  249. });
  250. }
  251. stop() {
  252. return __awaiter(this, void 0, void 0, function* () {
  253. if (!this.clientHost)
  254. return;
  255. this.clientHost.reset();
  256. let client = this.clientHost.serviceClient;
  257. yield client.stop();
  258. return;
  259. });
  260. }
  261. }
  262. exports.default = TsserverService;
  263. /***/ }),
  264. /* 3 */
  265. /***/ (function(module, exports, __webpack_require__) {
  266. "use strict";
  267. /* --------------------------------------------------------------------------------------------
  268. * Copyright (c) Microsoft Corporation. All rights reserved.
  269. * Licensed under the MIT License. See License.txt in the project root for license information.
  270. * ------------------------------------------------------------------------------------------ */
  271. function __export(m) {
  272. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  273. }
  274. Object.defineProperty(exports, "__esModule", { value: true });
  275. const vscode_jsonrpc_1 = __webpack_require__(4);
  276. exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
  277. exports.ResponseError = vscode_jsonrpc_1.ResponseError;
  278. exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;
  279. exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
  280. exports.Disposable = vscode_jsonrpc_1.Disposable;
  281. exports.Event = vscode_jsonrpc_1.Event;
  282. exports.Emitter = vscode_jsonrpc_1.Emitter;
  283. exports.Trace = vscode_jsonrpc_1.Trace;
  284. exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;
  285. exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
  286. exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
  287. exports.RequestType = vscode_jsonrpc_1.RequestType;
  288. exports.RequestType0 = vscode_jsonrpc_1.RequestType0;
  289. exports.NotificationType = vscode_jsonrpc_1.NotificationType;
  290. exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
  291. exports.MessageReader = vscode_jsonrpc_1.MessageReader;
  292. exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;
  293. exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
  294. exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
  295. exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
  296. exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
  297. exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
  298. exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
  299. exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
  300. exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
  301. exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
  302. exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
  303. exports.ProgressType = vscode_jsonrpc_1.ProgressType;
  304. __export(__webpack_require__(18));
  305. __export(__webpack_require__(19));
  306. const callHierarchy = __webpack_require__(31);
  307. const st = __webpack_require__(32);
  308. var Proposed;
  309. (function (Proposed) {
  310. let CallHierarchyPrepareRequest;
  311. (function (CallHierarchyPrepareRequest) {
  312. CallHierarchyPrepareRequest.method = callHierarchy.CallHierarchyPrepareRequest.method;
  313. CallHierarchyPrepareRequest.type = callHierarchy.CallHierarchyPrepareRequest.type;
  314. })(CallHierarchyPrepareRequest = Proposed.CallHierarchyPrepareRequest || (Proposed.CallHierarchyPrepareRequest = {}));
  315. let CallHierarchyIncomingCallsRequest;
  316. (function (CallHierarchyIncomingCallsRequest) {
  317. CallHierarchyIncomingCallsRequest.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;
  318. CallHierarchyIncomingCallsRequest.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;
  319. })(CallHierarchyIncomingCallsRequest = Proposed.CallHierarchyIncomingCallsRequest || (Proposed.CallHierarchyIncomingCallsRequest = {}));
  320. let CallHierarchyOutgoingCallsRequest;
  321. (function (CallHierarchyOutgoingCallsRequest) {
  322. CallHierarchyOutgoingCallsRequest.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;
  323. CallHierarchyOutgoingCallsRequest.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;
  324. })(CallHierarchyOutgoingCallsRequest = Proposed.CallHierarchyOutgoingCallsRequest || (Proposed.CallHierarchyOutgoingCallsRequest = {}));
  325. Proposed.SemanticTokenTypes = st.SemanticTokenTypes;
  326. Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers;
  327. Proposed.SemanticTokens = st.SemanticTokens;
  328. let SemanticTokensRequest;
  329. (function (SemanticTokensRequest) {
  330. SemanticTokensRequest.method = st.SemanticTokensRequest.method;
  331. SemanticTokensRequest.type = st.SemanticTokensRequest.type;
  332. })(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {}));
  333. let SemanticTokensEditsRequest;
  334. (function (SemanticTokensEditsRequest) {
  335. SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method;
  336. SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type;
  337. })(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {}));
  338. let SemanticTokensRangeRequest;
  339. (function (SemanticTokensRangeRequest) {
  340. SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method;
  341. SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type;
  342. })(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {}));
  343. })(Proposed = exports.Proposed || (exports.Proposed = {}));
  344. function createProtocolConnection(reader, writer, logger, strategy) {
  345. return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
  346. }
  347. exports.createProtocolConnection = createProtocolConnection;
  348. /***/ }),
  349. /* 4 */
  350. /***/ (function(module, exports, __webpack_require__) {
  351. "use strict";
  352. /* --------------------------------------------------------------------------------------------
  353. * Copyright (c) Microsoft Corporation. All rights reserved.
  354. * Licensed under the MIT License. See License.txt in the project root for license information.
  355. * ------------------------------------------------------------------------------------------ */
  356. /// <reference path="../typings/thenable.d.ts" />
  357. function __export(m) {
  358. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  359. }
  360. Object.defineProperty(exports, "__esModule", { value: true });
  361. const Is = __webpack_require__(5);
  362. const messages_1 = __webpack_require__(6);
  363. exports.RequestType = messages_1.RequestType;
  364. exports.RequestType0 = messages_1.RequestType0;
  365. exports.RequestType1 = messages_1.RequestType1;
  366. exports.RequestType2 = messages_1.RequestType2;
  367. exports.RequestType3 = messages_1.RequestType3;
  368. exports.RequestType4 = messages_1.RequestType4;
  369. exports.RequestType5 = messages_1.RequestType5;
  370. exports.RequestType6 = messages_1.RequestType6;
  371. exports.RequestType7 = messages_1.RequestType7;
  372. exports.RequestType8 = messages_1.RequestType8;
  373. exports.RequestType9 = messages_1.RequestType9;
  374. exports.ResponseError = messages_1.ResponseError;
  375. exports.ErrorCodes = messages_1.ErrorCodes;
  376. exports.NotificationType = messages_1.NotificationType;
  377. exports.NotificationType0 = messages_1.NotificationType0;
  378. exports.NotificationType1 = messages_1.NotificationType1;
  379. exports.NotificationType2 = messages_1.NotificationType2;
  380. exports.NotificationType3 = messages_1.NotificationType3;
  381. exports.NotificationType4 = messages_1.NotificationType4;
  382. exports.NotificationType5 = messages_1.NotificationType5;
  383. exports.NotificationType6 = messages_1.NotificationType6;
  384. exports.NotificationType7 = messages_1.NotificationType7;
  385. exports.NotificationType8 = messages_1.NotificationType8;
  386. exports.NotificationType9 = messages_1.NotificationType9;
  387. const messageReader_1 = __webpack_require__(7);
  388. exports.MessageReader = messageReader_1.MessageReader;
  389. exports.StreamMessageReader = messageReader_1.StreamMessageReader;
  390. exports.IPCMessageReader = messageReader_1.IPCMessageReader;
  391. exports.SocketMessageReader = messageReader_1.SocketMessageReader;
  392. const messageWriter_1 = __webpack_require__(9);
  393. exports.MessageWriter = messageWriter_1.MessageWriter;
  394. exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
  395. exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
  396. exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
  397. const events_1 = __webpack_require__(8);
  398. exports.Disposable = events_1.Disposable;
  399. exports.Event = events_1.Event;
  400. exports.Emitter = events_1.Emitter;
  401. const cancellation_1 = __webpack_require__(10);
  402. exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
  403. exports.CancellationToken = cancellation_1.CancellationToken;
  404. const linkedMap_1 = __webpack_require__(11);
  405. __export(__webpack_require__(12));
  406. __export(__webpack_require__(17));
  407. var CancelNotification;
  408. (function (CancelNotification) {
  409. CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
  410. })(CancelNotification || (CancelNotification = {}));
  411. var ProgressNotification;
  412. (function (ProgressNotification) {
  413. ProgressNotification.type = new messages_1.NotificationType('$/progress');
  414. })(ProgressNotification || (ProgressNotification = {}));
  415. class ProgressType {
  416. constructor() {
  417. }
  418. }
  419. exports.ProgressType = ProgressType;
  420. exports.NullLogger = Object.freeze({
  421. error: () => { },
  422. warn: () => { },
  423. info: () => { },
  424. log: () => { }
  425. });
  426. var Trace;
  427. (function (Trace) {
  428. Trace[Trace["Off"] = 0] = "Off";
  429. Trace[Trace["Messages"] = 1] = "Messages";
  430. Trace[Trace["Verbose"] = 2] = "Verbose";
  431. })(Trace = exports.Trace || (exports.Trace = {}));
  432. (function (Trace) {
  433. function fromString(value) {
  434. if (!Is.string(value)) {
  435. return Trace.Off;
  436. }
  437. value = value.toLowerCase();
  438. switch (value) {
  439. case 'off':
  440. return Trace.Off;
  441. case 'messages':
  442. return Trace.Messages;
  443. case 'verbose':
  444. return Trace.Verbose;
  445. default:
  446. return Trace.Off;
  447. }
  448. }
  449. Trace.fromString = fromString;
  450. function toString(value) {
  451. switch (value) {
  452. case Trace.Off:
  453. return 'off';
  454. case Trace.Messages:
  455. return 'messages';
  456. case Trace.Verbose:
  457. return 'verbose';
  458. default:
  459. return 'off';
  460. }
  461. }
  462. Trace.toString = toString;
  463. })(Trace = exports.Trace || (exports.Trace = {}));
  464. var TraceFormat;
  465. (function (TraceFormat) {
  466. TraceFormat["Text"] = "text";
  467. TraceFormat["JSON"] = "json";
  468. })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
  469. (function (TraceFormat) {
  470. function fromString(value) {
  471. value = value.toLowerCase();
  472. if (value === 'json') {
  473. return TraceFormat.JSON;
  474. }
  475. else {
  476. return TraceFormat.Text;
  477. }
  478. }
  479. TraceFormat.fromString = fromString;
  480. })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
  481. var SetTraceNotification;
  482. (function (SetTraceNotification) {
  483. SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');
  484. })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
  485. var LogTraceNotification;
  486. (function (LogTraceNotification) {
  487. LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');
  488. })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
  489. var ConnectionErrors;
  490. (function (ConnectionErrors) {
  491. /**
  492. * The connection is closed.
  493. */
  494. ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
  495. /**
  496. * The connection got disposed.
  497. */
  498. ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
  499. /**
  500. * The connection is already in listening mode.
  501. */
  502. ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
  503. })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
  504. class ConnectionError extends Error {
  505. constructor(code, message) {
  506. super(message);
  507. this.code = code;
  508. Object.setPrototypeOf(this, ConnectionError.prototype);
  509. }
  510. }
  511. exports.ConnectionError = ConnectionError;
  512. var ConnectionStrategy;
  513. (function (ConnectionStrategy) {
  514. function is(value) {
  515. let candidate = value;
  516. return candidate && Is.func(candidate.cancelUndispatched);
  517. }
  518. ConnectionStrategy.is = is;
  519. })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
  520. var ConnectionState;
  521. (function (ConnectionState) {
  522. ConnectionState[ConnectionState["New"] = 1] = "New";
  523. ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
  524. ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
  525. ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
  526. })(ConnectionState || (ConnectionState = {}));
  527. function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
  528. let sequenceNumber = 0;
  529. let notificationSquenceNumber = 0;
  530. let unknownResponseSquenceNumber = 0;
  531. const version = '2.0';
  532. let starRequestHandler = undefined;
  533. let requestHandlers = Object.create(null);
  534. let starNotificationHandler = undefined;
  535. let notificationHandlers = Object.create(null);
  536. let progressHandlers = new Map();
  537. let timer;
  538. let messageQueue = new linkedMap_1.LinkedMap();
  539. let responsePromises = Object.create(null);
  540. let requestTokens = Object.create(null);
  541. let trace = Trace.Off;
  542. let traceFormat = TraceFormat.Text;
  543. let tracer;
  544. let state = ConnectionState.New;
  545. let errorEmitter = new events_1.Emitter();
  546. let closeEmitter = new events_1.Emitter();
  547. let unhandledNotificationEmitter = new events_1.Emitter();
  548. let unhandledProgressEmitter = new events_1.Emitter();
  549. let disposeEmitter = new events_1.Emitter();
  550. function createRequestQueueKey(id) {
  551. return 'req-' + id.toString();
  552. }
  553. function createResponseQueueKey(id) {
  554. if (id === null) {
  555. return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
  556. }
  557. else {
  558. return 'res-' + id.toString();
  559. }
  560. }
  561. function createNotificationQueueKey() {
  562. return 'not-' + (++notificationSquenceNumber).toString();
  563. }
  564. function addMessageToQueue(queue, message) {
  565. if (messages_1.isRequestMessage(message)) {
  566. queue.set(createRequestQueueKey(message.id), message);
  567. }
  568. else if (messages_1.isResponseMessage(message)) {
  569. queue.set(createResponseQueueKey(message.id), message);
  570. }
  571. else {
  572. queue.set(createNotificationQueueKey(), message);
  573. }
  574. }
  575. function cancelUndispatched(_message) {
  576. return undefined;
  577. }
  578. function isListening() {
  579. return state === ConnectionState.Listening;
  580. }
  581. function isClosed() {
  582. return state === ConnectionState.Closed;
  583. }
  584. function isDisposed() {
  585. return state === ConnectionState.Disposed;
  586. }
  587. function closeHandler() {
  588. if (state === ConnectionState.New || state === ConnectionState.Listening) {
  589. state = ConnectionState.Closed;
  590. closeEmitter.fire(undefined);
  591. }
  592. // If the connection is disposed don't sent close events.
  593. }
  594. function readErrorHandler(error) {
  595. errorEmitter.fire([error, undefined, undefined]);
  596. }
  597. function writeErrorHandler(data) {
  598. errorEmitter.fire(data);
  599. }
  600. messageReader.onClose(closeHandler);
  601. messageReader.onError(readErrorHandler);
  602. messageWriter.onClose(closeHandler);
  603. messageWriter.onError(writeErrorHandler);
  604. function triggerMessageQueue() {
  605. if (timer || messageQueue.size === 0) {
  606. return;
  607. }
  608. timer = setImmediate(() => {
  609. timer = undefined;
  610. processMessageQueue();
  611. });
  612. }
  613. function processMessageQueue() {
  614. if (messageQueue.size === 0) {
  615. return;
  616. }
  617. let message = messageQueue.shift();
  618. try {
  619. if (messages_1.isRequestMessage(message)) {
  620. handleRequest(message);
  621. }
  622. else if (messages_1.isNotificationMessage(message)) {
  623. handleNotification(message);
  624. }
  625. else if (messages_1.isResponseMessage(message)) {
  626. handleResponse(message);
  627. }
  628. else {
  629. handleInvalidMessage(message);
  630. }
  631. }
  632. finally {
  633. triggerMessageQueue();
  634. }
  635. }
  636. let callback = (message) => {
  637. try {
  638. // We have received a cancellation message. Check if the message is still in the queue
  639. // and cancel it if allowed to do so.
  640. if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
  641. let key = createRequestQueueKey(message.params.id);
  642. let toCancel = messageQueue.get(key);
  643. if (messages_1.isRequestMessage(toCancel)) {
  644. let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
  645. if (response && (response.error !== void 0 || response.result !== void 0)) {
  646. messageQueue.delete(key);
  647. response.id = toCancel.id;
  648. traceSendingResponse(response, message.method, Date.now());
  649. messageWriter.write(response);
  650. return;
  651. }
  652. }
  653. }
  654. addMessageToQueue(messageQueue, message);
  655. }
  656. finally {
  657. triggerMessageQueue();
  658. }
  659. };
  660. function handleRequest(requestMessage) {
  661. if (isDisposed()) {
  662. // we return here silently since we fired an event when the
  663. // connection got disposed.
  664. return;
  665. }
  666. function reply(resultOrError, method, startTime) {
  667. let message = {
  668. jsonrpc: version,
  669. id: requestMessage.id
  670. };
  671. if (resultOrError instanceof messages_1.ResponseError) {
  672. message.error = resultOrError.toJson();
  673. }
  674. else {
  675. message.result = resultOrError === void 0 ? null : resultOrError;
  676. }
  677. traceSendingResponse(message, method, startTime);
  678. messageWriter.write(message);
  679. }
  680. function replyError(error, method, startTime) {
  681. let message = {
  682. jsonrpc: version,
  683. id: requestMessage.id,
  684. error: error.toJson()
  685. };
  686. traceSendingResponse(message, method, startTime);
  687. messageWriter.write(message);
  688. }
  689. function replySuccess(result, method, startTime) {
  690. // The JSON RPC defines that a response must either have a result or an error
  691. // So we can't treat undefined as a valid response result.
  692. if (result === void 0) {
  693. result = null;
  694. }
  695. let message = {
  696. jsonrpc: version,
  697. id: requestMessage.id,
  698. result: result
  699. };
  700. traceSendingResponse(message, method, startTime);
  701. messageWriter.write(message);
  702. }
  703. traceReceivedRequest(requestMessage);
  704. let element = requestHandlers[requestMessage.method];
  705. let type;
  706. let requestHandler;
  707. if (element) {
  708. type = element.type;
  709. requestHandler = element.handler;
  710. }
  711. let startTime = Date.now();
  712. if (requestHandler || starRequestHandler) {
  713. let cancellationSource = new cancellation_1.CancellationTokenSource();
  714. let tokenKey = String(requestMessage.id);
  715. requestTokens[tokenKey] = cancellationSource;
  716. try {
  717. let handlerResult;
  718. if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
  719. handlerResult = requestHandler
  720. ? requestHandler(cancellationSource.token)
  721. : starRequestHandler(requestMessage.method, cancellationSource.token);
  722. }
  723. else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
  724. handlerResult = requestHandler
  725. ? requestHandler(...requestMessage.params, cancellationSource.token)
  726. : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
  727. }
  728. else {
  729. handlerResult = requestHandler
  730. ? requestHandler(requestMessage.params, cancellationSource.token)
  731. : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
  732. }
  733. let promise = handlerResult;
  734. if (!handlerResult) {
  735. delete requestTokens[tokenKey];
  736. replySuccess(handlerResult, requestMessage.method, startTime);
  737. }
  738. else if (promise.then) {
  739. promise.then((resultOrError) => {
  740. delete requestTokens[tokenKey];
  741. reply(resultOrError, requestMessage.method, startTime);
  742. }, error => {
  743. delete requestTokens[tokenKey];
  744. if (error instanceof messages_1.ResponseError) {
  745. replyError(error, requestMessage.method, startTime);
  746. }
  747. else if (error && Is.string(error.message)) {
  748. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
  749. }
  750. else {
  751. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
  752. }
  753. });
  754. }
  755. else {
  756. delete requestTokens[tokenKey];
  757. reply(handlerResult, requestMessage.method, startTime);
  758. }
  759. }
  760. catch (error) {
  761. delete requestTokens[tokenKey];
  762. if (error instanceof messages_1.ResponseError) {
  763. reply(error, requestMessage.method, startTime);
  764. }
  765. else if (error && Is.string(error.message)) {
  766. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
  767. }
  768. else {
  769. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
  770. }
  771. }
  772. }
  773. else {
  774. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
  775. }
  776. }
  777. function handleResponse(responseMessage) {
  778. if (isDisposed()) {
  779. // See handle request.
  780. return;
  781. }
  782. if (responseMessage.id === null) {
  783. if (responseMessage.error) {
  784. logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
  785. }
  786. else {
  787. logger.error(`Received response message without id. No further error information provided.`);
  788. }
  789. }
  790. else {
  791. let key = String(responseMessage.id);
  792. let responsePromise = responsePromises[key];
  793. traceReceivedResponse(responseMessage, responsePromise);
  794. if (responsePromise) {
  795. delete responsePromises[key];
  796. try {
  797. if (responseMessage.error) {
  798. let error = responseMessage.error;
  799. responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
  800. }
  801. else if (responseMessage.result !== void 0) {
  802. responsePromise.resolve(responseMessage.result);
  803. }
  804. else {
  805. throw new Error('Should never happen.');
  806. }
  807. }
  808. catch (error) {
  809. if (error.message) {
  810. logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
  811. }
  812. else {
  813. logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
  814. }
  815. }
  816. }
  817. }
  818. }
  819. function handleNotification(message) {
  820. if (isDisposed()) {
  821. // See handle request.
  822. return;
  823. }
  824. let type = undefined;
  825. let notificationHandler;
  826. if (message.method === CancelNotification.type.method) {
  827. notificationHandler = (params) => {
  828. let id = params.id;
  829. let source = requestTokens[String(id)];
  830. if (source) {
  831. source.cancel();
  832. }
  833. };
  834. }
  835. else {
  836. let element = notificationHandlers[message.method];
  837. if (element) {
  838. notificationHandler = element.handler;
  839. type = element.type;
  840. }
  841. }
  842. if (notificationHandler || starNotificationHandler) {
  843. try {
  844. traceReceivedNotification(message);
  845. if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
  846. notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
  847. }
  848. else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
  849. notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
  850. }
  851. else {
  852. notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
  853. }
  854. }
  855. catch (error) {
  856. if (error.message) {
  857. logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
  858. }
  859. else {
  860. logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
  861. }
  862. }
  863. }
  864. else {
  865. unhandledNotificationEmitter.fire(message);
  866. }
  867. }
  868. function handleInvalidMessage(message) {
  869. if (!message) {
  870. logger.error('Received empty message.');
  871. return;
  872. }
  873. logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
  874. // Test whether we find an id to reject the promise
  875. let responseMessage = message;
  876. if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
  877. let key = String(responseMessage.id);
  878. let responseHandler = responsePromises[key];
  879. if (responseHandler) {
  880. responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
  881. }
  882. }
  883. }
  884. function traceSendingRequest(message) {
  885. if (trace === Trace.Off || !tracer) {
  886. return;
  887. }
  888. if (traceFormat === TraceFormat.Text) {
  889. let data = undefined;
  890. if (trace === Trace.Verbose && message.params) {
  891. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  892. }
  893. tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
  894. }
  895. else {
  896. logLSPMessage('send-request', message);
  897. }
  898. }
  899. function traceSendingNotification(message) {
  900. if (trace === Trace.Off || !tracer) {
  901. return;
  902. }
  903. if (traceFormat === TraceFormat.Text) {
  904. let data = undefined;
  905. if (trace === Trace.Verbose) {
  906. if (message.params) {
  907. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  908. }
  909. else {
  910. data = 'No parameters provided.\n\n';
  911. }
  912. }
  913. tracer.log(`Sending notification '${message.method}'.`, data);
  914. }
  915. else {
  916. logLSPMessage('send-notification', message);
  917. }
  918. }
  919. function traceSendingResponse(message, method, startTime) {
  920. if (trace === Trace.Off || !tracer) {
  921. return;
  922. }
  923. if (traceFormat === TraceFormat.Text) {
  924. let data = undefined;
  925. if (trace === Trace.Verbose) {
  926. if (message.error && message.error.data) {
  927. data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
  928. }
  929. else {
  930. if (message.result) {
  931. data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
  932. }
  933. else if (message.error === void 0) {
  934. data = 'No result returned.\n\n';
  935. }
  936. }
  937. }
  938. tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
  939. }
  940. else {
  941. logLSPMessage('send-response', message);
  942. }
  943. }
  944. function traceReceivedRequest(message) {
  945. if (trace === Trace.Off || !tracer) {
  946. return;
  947. }
  948. if (traceFormat === TraceFormat.Text) {
  949. let data = undefined;
  950. if (trace === Trace.Verbose && message.params) {
  951. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  952. }
  953. tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
  954. }
  955. else {
  956. logLSPMessage('receive-request', message);
  957. }
  958. }
  959. function traceReceivedNotification(message) {
  960. if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
  961. return;
  962. }
  963. if (traceFormat === TraceFormat.Text) {
  964. let data = undefined;
  965. if (trace === Trace.Verbose) {
  966. if (message.params) {
  967. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  968. }
  969. else {
  970. data = 'No parameters provided.\n\n';
  971. }
  972. }
  973. tracer.log(`Received notification '${message.method}'.`, data);
  974. }
  975. else {
  976. logLSPMessage('receive-notification', message);
  977. }
  978. }
  979. function traceReceivedResponse(message, responsePromise) {
  980. if (trace === Trace.Off || !tracer) {
  981. return;
  982. }
  983. if (traceFormat === TraceFormat.Text) {
  984. let data = undefined;
  985. if (trace === Trace.Verbose) {
  986. if (message.error && message.error.data) {
  987. data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
  988. }
  989. else {
  990. if (message.result) {
  991. data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
  992. }
  993. else if (message.error === void 0) {
  994. data = 'No result returned.\n\n';
  995. }
  996. }
  997. }
  998. if (responsePromise) {
  999. let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
  1000. tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
  1001. }
  1002. else {
  1003. tracer.log(`Received response ${message.id} without active response promise.`, data);
  1004. }
  1005. }
  1006. else {
  1007. logLSPMessage('receive-response', message);
  1008. }
  1009. }
  1010. function logLSPMessage(type, message) {
  1011. if (!tracer || trace === Trace.Off) {
  1012. return;
  1013. }
  1014. const lspMessage = {
  1015. isLSPMessage: true,
  1016. type,
  1017. message,
  1018. timestamp: Date.now()
  1019. };
  1020. tracer.log(lspMessage);
  1021. }
  1022. function throwIfClosedOrDisposed() {
  1023. if (isClosed()) {
  1024. throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
  1025. }
  1026. if (isDisposed()) {
  1027. throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
  1028. }
  1029. }
  1030. function throwIfListening() {
  1031. if (isListening()) {
  1032. throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
  1033. }
  1034. }
  1035. function throwIfNotListening() {
  1036. if (!isListening()) {
  1037. throw new Error('Call listen() first.');
  1038. }
  1039. }
  1040. function undefinedToNull(param) {
  1041. if (param === void 0) {
  1042. return null;
  1043. }
  1044. else {
  1045. return param;
  1046. }
  1047. }
  1048. function computeMessageParams(type, params) {
  1049. let result;
  1050. let numberOfParams = type.numberOfParams;
  1051. switch (numberOfParams) {
  1052. case 0:
  1053. result = null;
  1054. break;
  1055. case 1:
  1056. result = undefinedToNull(params[0]);
  1057. break;
  1058. default:
  1059. result = [];
  1060. for (let i = 0; i < params.length && i < numberOfParams; i++) {
  1061. result.push(undefinedToNull(params[i]));
  1062. }
  1063. if (params.length < numberOfParams) {
  1064. for (let i = params.length; i < numberOfParams; i++) {
  1065. result.push(null);
  1066. }
  1067. }
  1068. break;
  1069. }
  1070. return result;
  1071. }
  1072. let connection = {
  1073. sendNotification: (type, ...params) => {
  1074. throwIfClosedOrDisposed();
  1075. let method;
  1076. let messageParams;
  1077. if (Is.string(type)) {
  1078. method = type;
  1079. switch (params.length) {
  1080. case 0:
  1081. messageParams = null;
  1082. break;
  1083. case 1:
  1084. messageParams = params[0];
  1085. break;
  1086. default:
  1087. messageParams = params;
  1088. break;
  1089. }
  1090. }
  1091. else {
  1092. method = type.method;
  1093. messageParams = computeMessageParams(type, params);
  1094. }
  1095. let notificationMessage = {
  1096. jsonrpc: version,
  1097. method: method,
  1098. params: messageParams
  1099. };
  1100. traceSendingNotification(notificationMessage);
  1101. messageWriter.write(notificationMessage);
  1102. },
  1103. onNotification: (type, handler) => {
  1104. throwIfClosedOrDisposed();
  1105. if (Is.func(type)) {
  1106. starNotificationHandler = type;
  1107. }
  1108. else if (handler) {
  1109. if (Is.string(type)) {
  1110. notificationHandlers[type] = { type: undefined, handler };
  1111. }
  1112. else {
  1113. notificationHandlers[type.method] = { type, handler };
  1114. }
  1115. }
  1116. },
  1117. onProgress: (_type, token, handler) => {
  1118. if (progressHandlers.has(token)) {
  1119. throw new Error(`Progress handler for token ${token} already registered`);
  1120. }
  1121. progressHandlers.set(token, handler);
  1122. return {
  1123. dispose: () => {
  1124. progressHandlers.delete(token);
  1125. }
  1126. };
  1127. },
  1128. sendProgress: (_type, token, value) => {
  1129. connection.sendNotification(ProgressNotification.type, { token, value });
  1130. },
  1131. onUnhandledProgress: unhandledProgressEmitter.event,
  1132. sendRequest: (type, ...params) => {
  1133. throwIfClosedOrDisposed();
  1134. throwIfNotListening();
  1135. let method;
  1136. let messageParams;
  1137. let token = undefined;
  1138. if (Is.string(type)) {
  1139. method = type;
  1140. switch (params.length) {
  1141. case 0:
  1142. messageParams = null;
  1143. break;
  1144. case 1:
  1145. // The cancellation token is optional so it can also be undefined.
  1146. if (cancellation_1.CancellationToken.is(params[0])) {
  1147. messageParams = null;
  1148. token = params[0];
  1149. }
  1150. else {
  1151. messageParams = undefinedToNull(params[0]);
  1152. }
  1153. break;
  1154. default:
  1155. const last = params.length - 1;
  1156. if (cancellation_1.CancellationToken.is(params[last])) {
  1157. token = params[last];
  1158. if (params.length === 2) {
  1159. messageParams = undefinedToNull(params[0]);
  1160. }
  1161. else {
  1162. messageParams = params.slice(0, last).map(value => undefinedToNull(value));
  1163. }
  1164. }
  1165. else {
  1166. messageParams = params.map(value => undefinedToNull(value));
  1167. }
  1168. break;
  1169. }
  1170. }
  1171. else {
  1172. method = type.method;
  1173. messageParams = computeMessageParams(type, params);
  1174. let numberOfParams = type.numberOfParams;
  1175. token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
  1176. }
  1177. let id = sequenceNumber++;
  1178. let result = new Promise((resolve, reject) => {
  1179. let requestMessage = {
  1180. jsonrpc: version,
  1181. id: id,
  1182. method: method,
  1183. params: messageParams
  1184. };
  1185. let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };
  1186. traceSendingRequest(requestMessage);
  1187. try {
  1188. messageWriter.write(requestMessage);
  1189. }
  1190. catch (e) {
  1191. // Writing the message failed. So we need to reject the promise.
  1192. responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
  1193. responsePromise = null;
  1194. }
  1195. if (responsePromise) {
  1196. responsePromises[String(id)] = responsePromise;
  1197. }
  1198. });
  1199. if (token) {
  1200. token.onCancellationRequested(() => {
  1201. connection.sendNotification(CancelNotification.type, { id });
  1202. });
  1203. }
  1204. return result;
  1205. },
  1206. onRequest: (type, handler) => {
  1207. throwIfClosedOrDisposed();
  1208. if (Is.func(type)) {
  1209. starRequestHandler = type;
  1210. }
  1211. else if (handler) {
  1212. if (Is.string(type)) {
  1213. requestHandlers[type] = { type: undefined, handler };
  1214. }
  1215. else {
  1216. requestHandlers[type.method] = { type, handler };
  1217. }
  1218. }
  1219. },
  1220. trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
  1221. let _sendNotification = false;
  1222. let _traceFormat = TraceFormat.Text;
  1223. if (sendNotificationOrTraceOptions !== void 0) {
  1224. if (Is.boolean(sendNotificationOrTraceOptions)) {
  1225. _sendNotification = sendNotificationOrTraceOptions;
  1226. }
  1227. else {
  1228. _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
  1229. _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
  1230. }
  1231. }
  1232. trace = _value;
  1233. traceFormat = _traceFormat;
  1234. if (trace === Trace.Off) {
  1235. tracer = undefined;
  1236. }
  1237. else {
  1238. tracer = _tracer;
  1239. }
  1240. if (_sendNotification && !isClosed() && !isDisposed()) {
  1241. connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
  1242. }
  1243. },
  1244. onError: errorEmitter.event,
  1245. onClose: closeEmitter.event,
  1246. onUnhandledNotification: unhandledNotificationEmitter.event,
  1247. onDispose: disposeEmitter.event,
  1248. dispose: () => {
  1249. if (isDisposed()) {
  1250. return;
  1251. }
  1252. state = ConnectionState.Disposed;
  1253. disposeEmitter.fire(undefined);
  1254. let error = new Error('Connection got disposed.');
  1255. Object.keys(responsePromises).forEach((key) => {
  1256. responsePromises[key].reject(error);
  1257. });
  1258. responsePromises = Object.create(null);
  1259. requestTokens = Object.create(null);
  1260. messageQueue = new linkedMap_1.LinkedMap();
  1261. // Test for backwards compatibility
  1262. if (Is.func(messageWriter.dispose)) {
  1263. messageWriter.dispose();
  1264. }
  1265. if (Is.func(messageReader.dispose)) {
  1266. messageReader.dispose();
  1267. }
  1268. },
  1269. listen: () => {
  1270. throwIfClosedOrDisposed();
  1271. throwIfListening();
  1272. state = ConnectionState.Listening;
  1273. messageReader.listen(callback);
  1274. },
  1275. inspect: () => {
  1276. // eslint-disable-next-line no-console
  1277. console.log('inspect');
  1278. }
  1279. };
  1280. connection.onNotification(LogTraceNotification.type, (params) => {
  1281. if (trace === Trace.Off || !tracer) {
  1282. return;
  1283. }
  1284. tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
  1285. });
  1286. connection.onNotification(ProgressNotification.type, (params) => {
  1287. const handler = progressHandlers.get(params.token);
  1288. if (handler) {
  1289. handler(params.value);
  1290. }
  1291. else {
  1292. unhandledProgressEmitter.fire(params);
  1293. }
  1294. });
  1295. return connection;
  1296. }
  1297. function isMessageReader(value) {
  1298. return value.listen !== void 0 && value.read === void 0;
  1299. }
  1300. function isMessageWriter(value) {
  1301. return value.write !== void 0 && value.end === void 0;
  1302. }
  1303. function createMessageConnection(input, output, logger, strategy) {
  1304. if (!logger) {
  1305. logger = exports.NullLogger;
  1306. }
  1307. let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
  1308. let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
  1309. return _createMessageConnection(reader, writer, logger, strategy);
  1310. }
  1311. exports.createMessageConnection = createMessageConnection;
  1312. /***/ }),
  1313. /* 5 */
  1314. /***/ (function(module, exports, __webpack_require__) {
  1315. "use strict";
  1316. /* --------------------------------------------------------------------------------------------
  1317. * Copyright (c) Microsoft Corporation. All rights reserved.
  1318. * Licensed under the MIT License. See License.txt in the project root for license information.
  1319. * ------------------------------------------------------------------------------------------ */
  1320. Object.defineProperty(exports, "__esModule", { value: true });
  1321. function boolean(value) {
  1322. return value === true || value === false;
  1323. }
  1324. exports.boolean = boolean;
  1325. function string(value) {
  1326. return typeof value === 'string' || value instanceof String;
  1327. }
  1328. exports.string = string;
  1329. function number(value) {
  1330. return typeof value === 'number' || value instanceof Number;
  1331. }
  1332. exports.number = number;
  1333. function error(value) {
  1334. return value instanceof Error;
  1335. }
  1336. exports.error = error;
  1337. function func(value) {
  1338. return typeof value === 'function';
  1339. }
  1340. exports.func = func;
  1341. function array(value) {
  1342. return Array.isArray(value);
  1343. }
  1344. exports.array = array;
  1345. function stringArray(value) {
  1346. return array(value) && value.every(elem => string(elem));
  1347. }
  1348. exports.stringArray = stringArray;
  1349. /***/ }),
  1350. /* 6 */
  1351. /***/ (function(module, exports, __webpack_require__) {
  1352. "use strict";
  1353. /* --------------------------------------------------------------------------------------------
  1354. * Copyright (c) Microsoft Corporation. All rights reserved.
  1355. * Licensed under the MIT License. See License.txt in the project root for license information.
  1356. * ------------------------------------------------------------------------------------------ */
  1357. Object.defineProperty(exports, "__esModule", { value: true });
  1358. const is = __webpack_require__(5);
  1359. /**
  1360. * Predefined error codes.
  1361. */
  1362. var ErrorCodes;
  1363. (function (ErrorCodes) {
  1364. // Defined by JSON RPC
  1365. ErrorCodes.ParseError = -32700;
  1366. ErrorCodes.InvalidRequest = -32600;
  1367. ErrorCodes.MethodNotFound = -32601;
  1368. ErrorCodes.InvalidParams = -32602;
  1369. ErrorCodes.InternalError = -32603;
  1370. ErrorCodes.serverErrorStart = -32099;
  1371. ErrorCodes.serverErrorEnd = -32000;
  1372. ErrorCodes.ServerNotInitialized = -32002;
  1373. ErrorCodes.UnknownErrorCode = -32001;
  1374. // Defined by the protocol.
  1375. ErrorCodes.RequestCancelled = -32800;
  1376. ErrorCodes.ContentModified = -32801;
  1377. // Defined by VSCode library.
  1378. ErrorCodes.MessageWriteError = 1;
  1379. ErrorCodes.MessageReadError = 2;
  1380. })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
  1381. /**
  1382. * An error object return in a response in case a request
  1383. * has failed.
  1384. */
  1385. class ResponseError extends Error {
  1386. constructor(code, message, data) {
  1387. super(message);
  1388. this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
  1389. this.data = data;
  1390. Object.setPrototypeOf(this, ResponseError.prototype);
  1391. }
  1392. toJson() {
  1393. return {
  1394. code: this.code,
  1395. message: this.message,
  1396. data: this.data,
  1397. };
  1398. }
  1399. }
  1400. exports.ResponseError = ResponseError;
  1401. /**
  1402. * An abstract implementation of a MessageType.
  1403. */
  1404. class AbstractMessageType {
  1405. constructor(_method, _numberOfParams) {
  1406. this._method = _method;
  1407. this._numberOfParams = _numberOfParams;
  1408. }
  1409. get method() {
  1410. return this._method;
  1411. }
  1412. get numberOfParams() {
  1413. return this._numberOfParams;
  1414. }
  1415. }
  1416. exports.AbstractMessageType = AbstractMessageType;
  1417. /**
  1418. * Classes to type request response pairs
  1419. *
  1420. * The type parameter RO will be removed in the next major version
  1421. * of the JSON RPC library since it is a LSP concept and doesn't
  1422. * belong here. For now it is tagged as default never.
  1423. */
  1424. class RequestType0 extends AbstractMessageType {
  1425. constructor(method) {
  1426. super(method, 0);
  1427. }
  1428. }
  1429. exports.RequestType0 = RequestType0;
  1430. class RequestType extends AbstractMessageType {
  1431. constructor(method) {
  1432. super(method, 1);
  1433. }
  1434. }
  1435. exports.RequestType = RequestType;
  1436. class RequestType1 extends AbstractMessageType {
  1437. constructor(method) {
  1438. super(method, 1);
  1439. }
  1440. }
  1441. exports.RequestType1 = RequestType1;
  1442. class RequestType2 extends AbstractMessageType {
  1443. constructor(method) {
  1444. super(method, 2);
  1445. }
  1446. }
  1447. exports.RequestType2 = RequestType2;
  1448. class RequestType3 extends AbstractMessageType {
  1449. constructor(method) {
  1450. super(method, 3);
  1451. }
  1452. }
  1453. exports.RequestType3 = RequestType3;
  1454. class RequestType4 extends AbstractMessageType {
  1455. constructor(method) {
  1456. super(method, 4);
  1457. }
  1458. }
  1459. exports.RequestType4 = RequestType4;
  1460. class RequestType5 extends AbstractMessageType {
  1461. constructor(method) {
  1462. super(method, 5);
  1463. }
  1464. }
  1465. exports.RequestType5 = RequestType5;
  1466. class RequestType6 extends AbstractMessageType {
  1467. constructor(method) {
  1468. super(method, 6);
  1469. }
  1470. }
  1471. exports.RequestType6 = RequestType6;
  1472. class RequestType7 extends AbstractMessageType {
  1473. constructor(method) {
  1474. super(method, 7);
  1475. }
  1476. }
  1477. exports.RequestType7 = RequestType7;
  1478. class RequestType8 extends AbstractMessageType {
  1479. constructor(method) {
  1480. super(method, 8);
  1481. }
  1482. }
  1483. exports.RequestType8 = RequestType8;
  1484. class RequestType9 extends AbstractMessageType {
  1485. constructor(method) {
  1486. super(method, 9);
  1487. }
  1488. }
  1489. exports.RequestType9 = RequestType9;
  1490. /**
  1491. * The type parameter RO will be removed in the next major version
  1492. * of the JSON RPC library since it is a LSP concept and doesn't
  1493. * belong here. For now it is tagged as default never.
  1494. */
  1495. class NotificationType extends AbstractMessageType {
  1496. constructor(method) {
  1497. super(method, 1);
  1498. this._ = undefined;
  1499. }
  1500. }
  1501. exports.NotificationType = NotificationType;
  1502. class NotificationType0 extends AbstractMessageType {
  1503. constructor(method) {
  1504. super(method, 0);
  1505. }
  1506. }
  1507. exports.NotificationType0 = NotificationType0;
  1508. class NotificationType1 extends AbstractMessageType {
  1509. constructor(method) {
  1510. super(method, 1);
  1511. }
  1512. }
  1513. exports.NotificationType1 = NotificationType1;
  1514. class NotificationType2 extends AbstractMessageType {
  1515. constructor(method) {
  1516. super(method, 2);
  1517. }
  1518. }
  1519. exports.NotificationType2 = NotificationType2;
  1520. class NotificationType3 extends AbstractMessageType {
  1521. constructor(method) {
  1522. super(method, 3);
  1523. }
  1524. }
  1525. exports.NotificationType3 = NotificationType3;
  1526. class NotificationType4 extends AbstractMessageType {
  1527. constructor(method) {
  1528. super(method, 4);
  1529. }
  1530. }
  1531. exports.NotificationType4 = NotificationType4;
  1532. class NotificationType5 extends AbstractMessageType {
  1533. constructor(method) {
  1534. super(method, 5);
  1535. }
  1536. }
  1537. exports.NotificationType5 = NotificationType5;
  1538. class NotificationType6 extends AbstractMessageType {
  1539. constructor(method) {
  1540. super(method, 6);
  1541. }
  1542. }
  1543. exports.NotificationType6 = NotificationType6;
  1544. class NotificationType7 extends AbstractMessageType {
  1545. constructor(method) {
  1546. super(method, 7);
  1547. }
  1548. }
  1549. exports.NotificationType7 = NotificationType7;
  1550. class NotificationType8 extends AbstractMessageType {
  1551. constructor(method) {
  1552. super(method, 8);
  1553. }
  1554. }
  1555. exports.NotificationType8 = NotificationType8;
  1556. class NotificationType9 extends AbstractMessageType {
  1557. constructor(method) {
  1558. super(method, 9);
  1559. }
  1560. }
  1561. exports.NotificationType9 = NotificationType9;
  1562. /**
  1563. * Tests if the given message is a request message
  1564. */
  1565. function isRequestMessage(message) {
  1566. let candidate = message;
  1567. return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
  1568. }
  1569. exports.isRequestMessage = isRequestMessage;
  1570. /**
  1571. * Tests if the given message is a notification message
  1572. */
  1573. function isNotificationMessage(message) {
  1574. let candidate = message;
  1575. return candidate && is.string(candidate.method) && message.id === void 0;
  1576. }
  1577. exports.isNotificationMessage = isNotificationMessage;
  1578. /**
  1579. * Tests if the given message is a response message
  1580. */
  1581. function isResponseMessage(message) {
  1582. let candidate = message;
  1583. return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
  1584. }
  1585. exports.isResponseMessage = isResponseMessage;
  1586. /***/ }),
  1587. /* 7 */
  1588. /***/ (function(module, exports, __webpack_require__) {
  1589. "use strict";
  1590. /* --------------------------------------------------------------------------------------------
  1591. * Copyright (c) Microsoft Corporation. All rights reserved.
  1592. * Licensed under the MIT License. See License.txt in the project root for license information.
  1593. * ------------------------------------------------------------------------------------------ */
  1594. Object.defineProperty(exports, "__esModule", { value: true });
  1595. const events_1 = __webpack_require__(8);
  1596. const Is = __webpack_require__(5);
  1597. let DefaultSize = 8192;
  1598. let CR = Buffer.from('\r', 'ascii')[0];
  1599. let LF = Buffer.from('\n', 'ascii')[0];
  1600. let CRLF = '\r\n';
  1601. class MessageBuffer {
  1602. constructor(encoding = 'utf8') {
  1603. this.encoding = encoding;
  1604. this.index = 0;
  1605. this.buffer = Buffer.allocUnsafe(DefaultSize);
  1606. }
  1607. append(chunk) {
  1608. var toAppend = chunk;
  1609. if (typeof (chunk) === 'string') {
  1610. var str = chunk;
  1611. var bufferLen = Buffer.byteLength(str, this.encoding);
  1612. toAppend = Buffer.allocUnsafe(bufferLen);
  1613. toAppend.write(str, 0, bufferLen, this.encoding);
  1614. }
  1615. if (this.buffer.length - this.index >= toAppend.length) {
  1616. toAppend.copy(this.buffer, this.index, 0, toAppend.length);
  1617. }
  1618. else {
  1619. var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
  1620. if (this.index === 0) {
  1621. this.buffer = Buffer.allocUnsafe(newSize);
  1622. toAppend.copy(this.buffer, 0, 0, toAppend.length);
  1623. }
  1624. else {
  1625. this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
  1626. }
  1627. }
  1628. this.index += toAppend.length;
  1629. }
  1630. tryReadHeaders() {
  1631. let result = undefined;
  1632. let current = 0;
  1633. while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {
  1634. current++;
  1635. }
  1636. // No header / body separator found (e.g CRLFCRLF)
  1637. if (current + 3 >= this.index) {
  1638. return result;
  1639. }
  1640. result = Object.create(null);
  1641. let headers = this.buffer.toString('ascii', 0, current).split(CRLF);
  1642. headers.forEach((header) => {
  1643. let index = header.indexOf(':');
  1644. if (index === -1) {
  1645. throw new Error('Message header must separate key and value using :');
  1646. }
  1647. let key = header.substr(0, index);
  1648. let value = header.substr(index + 1).trim();
  1649. result[key] = value;
  1650. });
  1651. let nextStart = current + 4;
  1652. this.buffer = this.buffer.slice(nextStart);
  1653. this.index = this.index - nextStart;
  1654. return result;
  1655. }
  1656. tryReadContent(length) {
  1657. if (this.index < length) {
  1658. return null;
  1659. }
  1660. let result = this.buffer.toString(this.encoding, 0, length);
  1661. let nextStart = length;
  1662. this.buffer.copy(this.buffer, 0, nextStart);
  1663. this.index = this.index - nextStart;
  1664. return result;
  1665. }
  1666. get numberOfBytes() {
  1667. return this.index;
  1668. }
  1669. }
  1670. var MessageReader;
  1671. (function (MessageReader) {
  1672. function is(value) {
  1673. let candidate = value;
  1674. return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
  1675. Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
  1676. }
  1677. MessageReader.is = is;
  1678. })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
  1679. class AbstractMessageReader {
  1680. constructor() {
  1681. this.errorEmitter = new events_1.Emitter();
  1682. this.closeEmitter = new events_1.Emitter();
  1683. this.partialMessageEmitter = new events_1.Emitter();
  1684. }
  1685. dispose() {
  1686. this.errorEmitter.dispose();
  1687. this.closeEmitter.dispose();
  1688. }
  1689. get onError() {
  1690. return this.errorEmitter.event;
  1691. }
  1692. fireError(error) {
  1693. this.errorEmitter.fire(this.asError(error));
  1694. }
  1695. get onClose() {
  1696. return this.closeEmitter.event;
  1697. }
  1698. fireClose() {
  1699. this.closeEmitter.fire(undefined);
  1700. }
  1701. get onPartialMessage() {
  1702. return this.partialMessageEmitter.event;
  1703. }
  1704. firePartialMessage(info) {
  1705. this.partialMessageEmitter.fire(info);
  1706. }
  1707. asError(error) {
  1708. if (error instanceof Error) {
  1709. return error;
  1710. }
  1711. else {
  1712. return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
  1713. }
  1714. }
  1715. }
  1716. exports.AbstractMessageReader = AbstractMessageReader;
  1717. class StreamMessageReader extends AbstractMessageReader {
  1718. constructor(readable, encoding = 'utf8') {
  1719. super();
  1720. this.readable = readable;
  1721. this.buffer = new MessageBuffer(encoding);
  1722. this._partialMessageTimeout = 10000;
  1723. }
  1724. set partialMessageTimeout(timeout) {
  1725. this._partialMessageTimeout = timeout;
  1726. }
  1727. get partialMessageTimeout() {
  1728. return this._partialMessageTimeout;
  1729. }
  1730. listen(callback) {
  1731. this.nextMessageLength = -1;
  1732. this.messageToken = 0;
  1733. this.partialMessageTimer = undefined;
  1734. this.callback = callback;
  1735. this.readable.on('data', (data) => {
  1736. this.onData(data);
  1737. });
  1738. this.readable.on('error', (error) => this.fireError(error));
  1739. this.readable.on('close', () => this.fireClose());
  1740. }
  1741. onData(data) {
  1742. this.buffer.append(data);
  1743. while (true) {
  1744. if (this.nextMessageLength === -1) {
  1745. let headers = this.buffer.tryReadHeaders();
  1746. if (!headers) {
  1747. return;
  1748. }
  1749. let contentLength = headers['Content-Length'];
  1750. if (!contentLength) {
  1751. throw new Error('Header must provide a Content-Length property.');
  1752. }
  1753. let length = parseInt(contentLength);
  1754. if (isNaN(length)) {
  1755. throw new Error('Content-Length value must be a number.');
  1756. }
  1757. this.nextMessageLength = length;
  1758. // Take the encoding form the header. For compatibility
  1759. // treat both utf-8 and utf8 as node utf8
  1760. }
  1761. var msg = this.buffer.tryReadContent(this.nextMessageLength);
  1762. if (msg === null) {
  1763. /** We haven't received the full message yet. */
  1764. this.setPartialMessageTimer();
  1765. return;
  1766. }
  1767. this.clearPartialMessageTimer();
  1768. this.nextMessageLength = -1;
  1769. this.messageToken++;
  1770. var json = JSON.parse(msg);
  1771. this.callback(json);
  1772. }
  1773. }
  1774. clearPartialMessageTimer() {
  1775. if (this.partialMessageTimer) {
  1776. clearTimeout(this.partialMessageTimer);
  1777. this.partialMessageTimer = undefined;
  1778. }
  1779. }
  1780. setPartialMessageTimer() {
  1781. this.clearPartialMessageTimer();
  1782. if (this._partialMessageTimeout <= 0) {
  1783. return;
  1784. }
  1785. this.partialMessageTimer = setTimeout((token, timeout) => {
  1786. this.partialMessageTimer = undefined;
  1787. if (token === this.messageToken) {
  1788. this.firePartialMessage({ messageToken: token, waitingTime: timeout });
  1789. this.setPartialMessageTimer();
  1790. }
  1791. }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
  1792. }
  1793. }
  1794. exports.StreamMessageReader = StreamMessageReader;
  1795. class IPCMessageReader extends AbstractMessageReader {
  1796. constructor(process) {
  1797. super();
  1798. this.process = process;
  1799. let eventEmitter = this.process;
  1800. eventEmitter.on('error', (error) => this.fireError(error));
  1801. eventEmitter.on('close', () => this.fireClose());
  1802. }
  1803. listen(callback) {
  1804. this.process.on('message', callback);
  1805. }
  1806. }
  1807. exports.IPCMessageReader = IPCMessageReader;
  1808. class SocketMessageReader extends StreamMessageReader {
  1809. constructor(socket, encoding = 'utf-8') {
  1810. super(socket, encoding);
  1811. }
  1812. }
  1813. exports.SocketMessageReader = SocketMessageReader;
  1814. /***/ }),
  1815. /* 8 */
  1816. /***/ (function(module, exports, __webpack_require__) {
  1817. "use strict";
  1818. /* --------------------------------------------------------------------------------------------
  1819. * Copyright (c) Microsoft Corporation. All rights reserved.
  1820. * Licensed under the MIT License. See License.txt in the project root for license information.
  1821. * ------------------------------------------------------------------------------------------ */
  1822. Object.defineProperty(exports, "__esModule", { value: true });
  1823. var Disposable;
  1824. (function (Disposable) {
  1825. function create(func) {
  1826. return {
  1827. dispose: func
  1828. };
  1829. }
  1830. Disposable.create = create;
  1831. })(Disposable = exports.Disposable || (exports.Disposable = {}));
  1832. var Event;
  1833. (function (Event) {
  1834. const _disposable = { dispose() { } };
  1835. Event.None = function () { return _disposable; };
  1836. })(Event = exports.Event || (exports.Event = {}));
  1837. class CallbackList {
  1838. add(callback, context = null, bucket) {
  1839. if (!this._callbacks) {
  1840. this._callbacks = [];
  1841. this._contexts = [];
  1842. }
  1843. this._callbacks.push(callback);
  1844. this._contexts.push(context);
  1845. if (Array.isArray(bucket)) {
  1846. bucket.push({ dispose: () => this.remove(callback, context) });
  1847. }
  1848. }
  1849. remove(callback, context = null) {
  1850. if (!this._callbacks) {
  1851. return;
  1852. }
  1853. var foundCallbackWithDifferentContext = false;
  1854. for (var i = 0, len = this._callbacks.length; i < len; i++) {
  1855. if (this._callbacks[i] === callback) {
  1856. if (this._contexts[i] === context) {
  1857. // callback & context match => remove it
  1858. this._callbacks.splice(i, 1);
  1859. this._contexts.splice(i, 1);
  1860. return;
  1861. }
  1862. else {
  1863. foundCallbackWithDifferentContext = true;
  1864. }
  1865. }
  1866. }
  1867. if (foundCallbackWithDifferentContext) {
  1868. throw new Error('When adding a listener with a context, you should remove it with the same context');
  1869. }
  1870. }
  1871. invoke(...args) {
  1872. if (!this._callbacks) {
  1873. return [];
  1874. }
  1875. var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
  1876. for (var i = 0, len = callbacks.length; i < len; i++) {
  1877. try {
  1878. ret.push(callbacks[i].apply(contexts[i], args));
  1879. }
  1880. catch (e) {
  1881. // eslint-disable-next-line no-console
  1882. console.error(e);
  1883. }
  1884. }
  1885. return ret;
  1886. }
  1887. isEmpty() {
  1888. return !this._callbacks || this._callbacks.length === 0;
  1889. }
  1890. dispose() {
  1891. this._callbacks = undefined;
  1892. this._contexts = undefined;
  1893. }
  1894. }
  1895. class Emitter {
  1896. constructor(_options) {
  1897. this._options = _options;
  1898. }
  1899. /**
  1900. * For the public to allow to subscribe
  1901. * to events from this Emitter
  1902. */
  1903. get event() {
  1904. if (!this._event) {
  1905. this._event = (listener, thisArgs, disposables) => {
  1906. if (!this._callbacks) {
  1907. this._callbacks = new CallbackList();
  1908. }
  1909. if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
  1910. this._options.onFirstListenerAdd(this);
  1911. }
  1912. this._callbacks.add(listener, thisArgs);
  1913. let result;
  1914. result = {
  1915. dispose: () => {
  1916. this._callbacks.remove(listener, thisArgs);
  1917. result.dispose = Emitter._noop;
  1918. if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
  1919. this._options.onLastListenerRemove(this);
  1920. }
  1921. }
  1922. };
  1923. if (Array.isArray(disposables)) {
  1924. disposables.push(result);
  1925. }
  1926. return result;
  1927. };
  1928. }
  1929. return this._event;
  1930. }
  1931. /**
  1932. * To be kept private to fire an event to
  1933. * subscribers
  1934. */
  1935. fire(event) {
  1936. if (this._callbacks) {
  1937. this._callbacks.invoke.call(this._callbacks, event);
  1938. }
  1939. }
  1940. dispose() {
  1941. if (this._callbacks) {
  1942. this._callbacks.dispose();
  1943. this._callbacks = undefined;
  1944. }
  1945. }
  1946. }
  1947. exports.Emitter = Emitter;
  1948. Emitter._noop = function () { };
  1949. /***/ }),
  1950. /* 9 */
  1951. /***/ (function(module, exports, __webpack_require__) {
  1952. "use strict";
  1953. /* --------------------------------------------------------------------------------------------
  1954. * Copyright (c) Microsoft Corporation. All rights reserved.
  1955. * Licensed under the MIT License. See License.txt in the project root for license information.
  1956. * ------------------------------------------------------------------------------------------ */
  1957. Object.defineProperty(exports, "__esModule", { value: true });
  1958. const events_1 = __webpack_require__(8);
  1959. const Is = __webpack_require__(5);
  1960. let ContentLength = 'Content-Length: ';
  1961. let CRLF = '\r\n';
  1962. var MessageWriter;
  1963. (function (MessageWriter) {
  1964. function is(value) {
  1965. let candidate = value;
  1966. return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
  1967. Is.func(candidate.onError) && Is.func(candidate.write);
  1968. }
  1969. MessageWriter.is = is;
  1970. })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
  1971. class AbstractMessageWriter {
  1972. constructor() {
  1973. this.errorEmitter = new events_1.Emitter();
  1974. this.closeEmitter = new events_1.Emitter();
  1975. }
  1976. dispose() {
  1977. this.errorEmitter.dispose();
  1978. this.closeEmitter.dispose();
  1979. }
  1980. get onError() {
  1981. return this.errorEmitter.event;
  1982. }
  1983. fireError(error, message, count) {
  1984. this.errorEmitter.fire([this.asError(error), message, count]);
  1985. }
  1986. get onClose() {
  1987. return this.closeEmitter.event;
  1988. }
  1989. fireClose() {
  1990. this.closeEmitter.fire(undefined);
  1991. }
  1992. asError(error) {
  1993. if (error instanceof Error) {
  1994. return error;
  1995. }
  1996. else {
  1997. return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
  1998. }
  1999. }
  2000. }
  2001. exports.AbstractMessageWriter = AbstractMessageWriter;
  2002. class StreamMessageWriter extends AbstractMessageWriter {
  2003. constructor(writable, encoding = 'utf8') {
  2004. super();
  2005. this.writable = writable;
  2006. this.encoding = encoding;
  2007. this.errorCount = 0;
  2008. this.writable.on('error', (error) => this.fireError(error));
  2009. this.writable.on('close', () => this.fireClose());
  2010. }
  2011. write(msg) {
  2012. let json = JSON.stringify(msg);
  2013. let contentLength = Buffer.byteLength(json, this.encoding);
  2014. let headers = [
  2015. ContentLength, contentLength.toString(), CRLF,
  2016. CRLF
  2017. ];
  2018. try {
  2019. // Header must be written in ASCII encoding
  2020. this.writable.write(headers.join(''), 'ascii');
  2021. // Now write the content. This can be written in any encoding
  2022. this.writable.write(json, this.encoding);
  2023. this.errorCount = 0;
  2024. }
  2025. catch (error) {
  2026. this.errorCount++;
  2027. this.fireError(error, msg, this.errorCount);
  2028. }
  2029. }
  2030. }
  2031. exports.StreamMessageWriter = StreamMessageWriter;
  2032. class IPCMessageWriter extends AbstractMessageWriter {
  2033. constructor(process) {
  2034. super();
  2035. this.process = process;
  2036. this.errorCount = 0;
  2037. this.queue = [];
  2038. this.sending = false;
  2039. let eventEmitter = this.process;
  2040. eventEmitter.on('error', (error) => this.fireError(error));
  2041. eventEmitter.on('close', () => this.fireClose);
  2042. }
  2043. write(msg) {
  2044. if (!this.sending && this.queue.length === 0) {
  2045. // See https://github.com/nodejs/node/issues/7657
  2046. this.doWriteMessage(msg);
  2047. }
  2048. else {
  2049. this.queue.push(msg);
  2050. }
  2051. }
  2052. doWriteMessage(msg) {
  2053. try {
  2054. if (this.process.send) {
  2055. this.sending = true;
  2056. this.process.send(msg, undefined, undefined, (error) => {
  2057. this.sending = false;
  2058. if (error) {
  2059. this.errorCount++;
  2060. this.fireError(error, msg, this.errorCount);
  2061. }
  2062. else {
  2063. this.errorCount = 0;
  2064. }
  2065. if (this.queue.length > 0) {
  2066. this.doWriteMessage(this.queue.shift());
  2067. }
  2068. });
  2069. }
  2070. }
  2071. catch (error) {
  2072. this.errorCount++;
  2073. this.fireError(error, msg, this.errorCount);
  2074. }
  2075. }
  2076. }
  2077. exports.IPCMessageWriter = IPCMessageWriter;
  2078. class SocketMessageWriter extends AbstractMessageWriter {
  2079. constructor(socket, encoding = 'utf8') {
  2080. super();
  2081. this.socket = socket;
  2082. this.queue = [];
  2083. this.sending = false;
  2084. this.encoding = encoding;
  2085. this.errorCount = 0;
  2086. this.socket.on('error', (error) => this.fireError(error));
  2087. this.socket.on('close', () => this.fireClose());
  2088. }
  2089. dispose() {
  2090. super.dispose();
  2091. this.socket.destroy();
  2092. }
  2093. write(msg) {
  2094. if (!this.sending && this.queue.length === 0) {
  2095. // See https://github.com/nodejs/node/issues/7657
  2096. this.doWriteMessage(msg);
  2097. }
  2098. else {
  2099. this.queue.push(msg);
  2100. }
  2101. }
  2102. doWriteMessage(msg) {
  2103. let json = JSON.stringify(msg);
  2104. let contentLength = Buffer.byteLength(json, this.encoding);
  2105. let headers = [
  2106. ContentLength, contentLength.toString(), CRLF,
  2107. CRLF
  2108. ];
  2109. try {
  2110. // Header must be written in ASCII encoding
  2111. this.sending = true;
  2112. this.socket.write(headers.join(''), 'ascii', (error) => {
  2113. if (error) {
  2114. this.handleError(error, msg);
  2115. }
  2116. try {
  2117. // Now write the content. This can be written in any encoding
  2118. this.socket.write(json, this.encoding, (error) => {
  2119. this.sending = false;
  2120. if (error) {
  2121. this.handleError(error, msg);
  2122. }
  2123. else {
  2124. this.errorCount = 0;
  2125. }
  2126. if (this.queue.length > 0) {
  2127. this.doWriteMessage(this.queue.shift());
  2128. }
  2129. });
  2130. }
  2131. catch (error) {
  2132. this.handleError(error, msg);
  2133. }
  2134. });
  2135. }
  2136. catch (error) {
  2137. this.handleError(error, msg);
  2138. }
  2139. }
  2140. handleError(error, msg) {
  2141. this.errorCount++;
  2142. this.fireError(error, msg, this.errorCount);
  2143. }
  2144. }
  2145. exports.SocketMessageWriter = SocketMessageWriter;
  2146. /***/ }),
  2147. /* 10 */
  2148. /***/ (function(module, exports, __webpack_require__) {
  2149. "use strict";
  2150. /*---------------------------------------------------------------------------------------------
  2151. * Copyright (c) Microsoft Corporation. All rights reserved.
  2152. * Licensed under the MIT License. See License.txt in the project root for license information.
  2153. *--------------------------------------------------------------------------------------------*/
  2154. Object.defineProperty(exports, "__esModule", { value: true });
  2155. const events_1 = __webpack_require__(8);
  2156. const Is = __webpack_require__(5);
  2157. var CancellationToken;
  2158. (function (CancellationToken) {
  2159. CancellationToken.None = Object.freeze({
  2160. isCancellationRequested: false,
  2161. onCancellationRequested: events_1.Event.None
  2162. });
  2163. CancellationToken.Cancelled = Object.freeze({
  2164. isCancellationRequested: true,
  2165. onCancellationRequested: events_1.Event.None
  2166. });
  2167. function is(value) {
  2168. let candidate = value;
  2169. return candidate && (candidate === CancellationToken.None
  2170. || candidate === CancellationToken.Cancelled
  2171. || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
  2172. }
  2173. CancellationToken.is = is;
  2174. })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
  2175. const shortcutEvent = Object.freeze(function (callback, context) {
  2176. let handle = setTimeout(callback.bind(context), 0);
  2177. return { dispose() { clearTimeout(handle); } };
  2178. });
  2179. class MutableToken {
  2180. constructor() {
  2181. this._isCancelled = false;
  2182. }
  2183. cancel() {
  2184. if (!this._isCancelled) {
  2185. this._isCancelled = true;
  2186. if (this._emitter) {
  2187. this._emitter.fire(undefined);
  2188. this.dispose();
  2189. }
  2190. }
  2191. }
  2192. get isCancellationRequested() {
  2193. return this._isCancelled;
  2194. }
  2195. get onCancellationRequested() {
  2196. if (this._isCancelled) {
  2197. return shortcutEvent;
  2198. }
  2199. if (!this._emitter) {
  2200. this._emitter = new events_1.Emitter();
  2201. }
  2202. return this._emitter.event;
  2203. }
  2204. dispose() {
  2205. if (this._emitter) {
  2206. this._emitter.dispose();
  2207. this._emitter = undefined;
  2208. }
  2209. }
  2210. }
  2211. class CancellationTokenSource {
  2212. get token() {
  2213. if (!this._token) {
  2214. // be lazy and create the token only when
  2215. // actually needed
  2216. this._token = new MutableToken();
  2217. }
  2218. return this._token;
  2219. }
  2220. cancel() {
  2221. if (!this._token) {
  2222. // save an object by returning the default
  2223. // cancelled token when cancellation happens
  2224. // before someone asks for the token
  2225. this._token = CancellationToken.Cancelled;
  2226. }
  2227. else {
  2228. this._token.cancel();
  2229. }
  2230. }
  2231. dispose() {
  2232. if (!this._token) {
  2233. // ensure to initialize with an empty token if we had none
  2234. this._token = CancellationToken.None;
  2235. }
  2236. else if (this._token instanceof MutableToken) {
  2237. // actually dispose
  2238. this._token.dispose();
  2239. }
  2240. }
  2241. }
  2242. exports.CancellationTokenSource = CancellationTokenSource;
  2243. /***/ }),
  2244. /* 11 */
  2245. /***/ (function(module, exports, __webpack_require__) {
  2246. "use strict";
  2247. /*---------------------------------------------------------------------------------------------
  2248. * Copyright (c) Microsoft Corporation. All rights reserved.
  2249. * Licensed under the MIT License. See License.txt in the project root for license information.
  2250. *--------------------------------------------------------------------------------------------*/
  2251. Object.defineProperty(exports, "__esModule", { value: true });
  2252. var Touch;
  2253. (function (Touch) {
  2254. Touch.None = 0;
  2255. Touch.First = 1;
  2256. Touch.Last = 2;
  2257. })(Touch = exports.Touch || (exports.Touch = {}));
  2258. class LinkedMap {
  2259. constructor() {
  2260. this._map = new Map();
  2261. this._head = undefined;
  2262. this._tail = undefined;
  2263. this._size = 0;
  2264. }
  2265. clear() {
  2266. this._map.clear();
  2267. this._head = undefined;
  2268. this._tail = undefined;
  2269. this._size = 0;
  2270. }
  2271. isEmpty() {
  2272. return !this._head && !this._tail;
  2273. }
  2274. get size() {
  2275. return this._size;
  2276. }
  2277. has(key) {
  2278. return this._map.has(key);
  2279. }
  2280. get(key) {
  2281. const item = this._map.get(key);
  2282. if (!item) {
  2283. return undefined;
  2284. }
  2285. return item.value;
  2286. }
  2287. set(key, value, touch = Touch.None) {
  2288. let item = this._map.get(key);
  2289. if (item) {
  2290. item.value = value;
  2291. if (touch !== Touch.None) {
  2292. this.touch(item, touch);
  2293. }
  2294. }
  2295. else {
  2296. item = { key, value, next: undefined, previous: undefined };
  2297. switch (touch) {
  2298. case Touch.None:
  2299. this.addItemLast(item);
  2300. break;
  2301. case Touch.First:
  2302. this.addItemFirst(item);
  2303. break;
  2304. case Touch.Last:
  2305. this.addItemLast(item);
  2306. break;
  2307. default:
  2308. this.addItemLast(item);
  2309. break;
  2310. }
  2311. this._map.set(key, item);
  2312. this._size++;
  2313. }
  2314. }
  2315. delete(key) {
  2316. const item = this._map.get(key);
  2317. if (!item) {
  2318. return false;
  2319. }
  2320. this._map.delete(key);
  2321. this.removeItem(item);
  2322. this._size--;
  2323. return true;
  2324. }
  2325. shift() {
  2326. if (!this._head && !this._tail) {
  2327. return undefined;
  2328. }
  2329. if (!this._head || !this._tail) {
  2330. throw new Error('Invalid list');
  2331. }
  2332. const item = this._head;
  2333. this._map.delete(item.key);
  2334. this.removeItem(item);
  2335. this._size--;
  2336. return item.value;
  2337. }
  2338. forEach(callbackfn, thisArg) {
  2339. let current = this._head;
  2340. while (current) {
  2341. if (thisArg) {
  2342. callbackfn.bind(thisArg)(current.value, current.key, this);
  2343. }
  2344. else {
  2345. callbackfn(current.value, current.key, this);
  2346. }
  2347. current = current.next;
  2348. }
  2349. }
  2350. forEachReverse(callbackfn, thisArg) {
  2351. let current = this._tail;
  2352. while (current) {
  2353. if (thisArg) {
  2354. callbackfn.bind(thisArg)(current.value, current.key, this);
  2355. }
  2356. else {
  2357. callbackfn(current.value, current.key, this);
  2358. }
  2359. current = current.previous;
  2360. }
  2361. }
  2362. values() {
  2363. let result = [];
  2364. let current = this._head;
  2365. while (current) {
  2366. result.push(current.value);
  2367. current = current.next;
  2368. }
  2369. return result;
  2370. }
  2371. keys() {
  2372. let result = [];
  2373. let current = this._head;
  2374. while (current) {
  2375. result.push(current.key);
  2376. current = current.next;
  2377. }
  2378. return result;
  2379. }
  2380. /* JSON RPC run on es5 which has no Symbol.iterator
  2381. public keys(): IterableIterator<K> {
  2382. let current = this._head;
  2383. let iterator: IterableIterator<K> = {
  2384. [Symbol.iterator]() {
  2385. return iterator;
  2386. },
  2387. next():IteratorResult<K> {
  2388. if (current) {
  2389. let result = { value: current.key, done: false };
  2390. current = current.next;
  2391. return result;
  2392. } else {
  2393. return { value: undefined, done: true };
  2394. }
  2395. }
  2396. };
  2397. return iterator;
  2398. }
  2399. public values(): IterableIterator<V> {
  2400. let current = this._head;
  2401. let iterator: IterableIterator<V> = {
  2402. [Symbol.iterator]() {
  2403. return iterator;
  2404. },
  2405. next():IteratorResult<V> {
  2406. if (current) {
  2407. let result = { value: current.value, done: false };
  2408. current = current.next;
  2409. return result;
  2410. } else {
  2411. return { value: undefined, done: true };
  2412. }
  2413. }
  2414. };
  2415. return iterator;
  2416. }
  2417. */
  2418. addItemFirst(item) {
  2419. // First time Insert
  2420. if (!this._head && !this._tail) {
  2421. this._tail = item;
  2422. }
  2423. else if (!this._head) {
  2424. throw new Error('Invalid list');
  2425. }
  2426. else {
  2427. item.next = this._head;
  2428. this._head.previous = item;
  2429. }
  2430. this._head = item;
  2431. }
  2432. addItemLast(item) {
  2433. // First time Insert
  2434. if (!this._head && !this._tail) {
  2435. this._head = item;
  2436. }
  2437. else if (!this._tail) {
  2438. throw new Error('Invalid list');
  2439. }
  2440. else {
  2441. item.previous = this._tail;
  2442. this._tail.next = item;
  2443. }
  2444. this._tail = item;
  2445. }
  2446. removeItem(item) {
  2447. if (item === this._head && item === this._tail) {
  2448. this._head = undefined;
  2449. this._tail = undefined;
  2450. }
  2451. else if (item === this._head) {
  2452. this._head = item.next;
  2453. }
  2454. else if (item === this._tail) {
  2455. this._tail = item.previous;
  2456. }
  2457. else {
  2458. const next = item.next;
  2459. const previous = item.previous;
  2460. if (!next || !previous) {
  2461. throw new Error('Invalid list');
  2462. }
  2463. next.previous = previous;
  2464. previous.next = next;
  2465. }
  2466. }
  2467. touch(item, touch) {
  2468. if (!this._head || !this._tail) {
  2469. throw new Error('Invalid list');
  2470. }
  2471. if ((touch !== Touch.First && touch !== Touch.Last)) {
  2472. return;
  2473. }
  2474. if (touch === Touch.First) {
  2475. if (item === this._head) {
  2476. return;
  2477. }
  2478. const next = item.next;
  2479. const previous = item.previous;
  2480. // Unlink the item
  2481. if (item === this._tail) {
  2482. // previous must be defined since item was not head but is tail
  2483. // So there are more than on item in the map
  2484. previous.next = undefined;
  2485. this._tail = previous;
  2486. }
  2487. else {
  2488. // Both next and previous are not undefined since item was neither head nor tail.
  2489. next.previous = previous;
  2490. previous.next = next;
  2491. }
  2492. // Insert the node at head
  2493. item.previous = undefined;
  2494. item.next = this._head;
  2495. this._head.previous = item;
  2496. this._head = item;
  2497. }
  2498. else if (touch === Touch.Last) {
  2499. if (item === this._tail) {
  2500. return;
  2501. }
  2502. const next = item.next;
  2503. const previous = item.previous;
  2504. // Unlink the item.
  2505. if (item === this._head) {
  2506. // next must be defined since item was not tail but is head
  2507. // So there are more than on item in the map
  2508. next.previous = undefined;
  2509. this._head = next;
  2510. }
  2511. else {
  2512. // Both next and previous are not undefined since item was neither head nor tail.
  2513. next.previous = previous;
  2514. previous.next = next;
  2515. }
  2516. item.next = undefined;
  2517. item.previous = this._tail;
  2518. this._tail.next = item;
  2519. this._tail = item;
  2520. }
  2521. }
  2522. }
  2523. exports.LinkedMap = LinkedMap;
  2524. /***/ }),
  2525. /* 12 */
  2526. /***/ (function(module, exports, __webpack_require__) {
  2527. "use strict";
  2528. /* --------------------------------------------------------------------------------------------
  2529. * Copyright (c) Microsoft Corporation. All rights reserved.
  2530. * Licensed under the MIT License. See License.txt in the project root for license information.
  2531. * ------------------------------------------------------------------------------------------ */
  2532. Object.defineProperty(exports, "__esModule", { value: true });
  2533. const path_1 = __webpack_require__(13);
  2534. const os_1 = __webpack_require__(14);
  2535. const crypto_1 = __webpack_require__(15);
  2536. const net_1 = __webpack_require__(16);
  2537. const messageReader_1 = __webpack_require__(7);
  2538. const messageWriter_1 = __webpack_require__(9);
  2539. function generateRandomPipeName() {
  2540. const randomSuffix = crypto_1.randomBytes(21).toString('hex');
  2541. if (process.platform === 'win32') {
  2542. return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
  2543. }
  2544. else {
  2545. // Mac/Unix: use socket file
  2546. return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
  2547. }
  2548. }
  2549. exports.generateRandomPipeName = generateRandomPipeName;
  2550. function createClientPipeTransport(pipeName, encoding = 'utf-8') {
  2551. let connectResolve;
  2552. let connected = new Promise((resolve, _reject) => {
  2553. connectResolve = resolve;
  2554. });
  2555. return new Promise((resolve, reject) => {
  2556. let server = net_1.createServer((socket) => {
  2557. server.close();
  2558. connectResolve([
  2559. new messageReader_1.SocketMessageReader(socket, encoding),
  2560. new messageWriter_1.SocketMessageWriter(socket, encoding)
  2561. ]);
  2562. });
  2563. server.on('error', reject);
  2564. server.listen(pipeName, () => {
  2565. server.removeListener('error', reject);
  2566. resolve({
  2567. onConnected: () => { return connected; }
  2568. });
  2569. });
  2570. });
  2571. }
  2572. exports.createClientPipeTransport = createClientPipeTransport;
  2573. function createServerPipeTransport(pipeName, encoding = 'utf-8') {
  2574. const socket = net_1.createConnection(pipeName);
  2575. return [
  2576. new messageReader_1.SocketMessageReader(socket, encoding),
  2577. new messageWriter_1.SocketMessageWriter(socket, encoding)
  2578. ];
  2579. }
  2580. exports.createServerPipeTransport = createServerPipeTransport;
  2581. /***/ }),
  2582. /* 13 */
  2583. /***/ (function(module, exports) {
  2584. module.exports = require("path");
  2585. /***/ }),
  2586. /* 14 */
  2587. /***/ (function(module, exports) {
  2588. module.exports = require("os");
  2589. /***/ }),
  2590. /* 15 */
  2591. /***/ (function(module, exports) {
  2592. module.exports = require("crypto");
  2593. /***/ }),
  2594. /* 16 */
  2595. /***/ (function(module, exports) {
  2596. module.exports = require("net");
  2597. /***/ }),
  2598. /* 17 */
  2599. /***/ (function(module, exports, __webpack_require__) {
  2600. "use strict";
  2601. /* --------------------------------------------------------------------------------------------
  2602. * Copyright (c) Microsoft Corporation. All rights reserved.
  2603. * Licensed under the MIT License. See License.txt in the project root for license information.
  2604. * ------------------------------------------------------------------------------------------ */
  2605. Object.defineProperty(exports, "__esModule", { value: true });
  2606. const net_1 = __webpack_require__(16);
  2607. const messageReader_1 = __webpack_require__(7);
  2608. const messageWriter_1 = __webpack_require__(9);
  2609. function createClientSocketTransport(port, encoding = 'utf-8') {
  2610. let connectResolve;
  2611. let connected = new Promise((resolve, _reject) => {
  2612. connectResolve = resolve;
  2613. });
  2614. return new Promise((resolve, reject) => {
  2615. let server = net_1.createServer((socket) => {
  2616. server.close();
  2617. connectResolve([
  2618. new messageReader_1.SocketMessageReader(socket, encoding),
  2619. new messageWriter_1.SocketMessageWriter(socket, encoding)
  2620. ]);
  2621. });
  2622. server.on('error', reject);
  2623. server.listen(port, '127.0.0.1', () => {
  2624. server.removeListener('error', reject);
  2625. resolve({
  2626. onConnected: () => { return connected; }
  2627. });
  2628. });
  2629. });
  2630. }
  2631. exports.createClientSocketTransport = createClientSocketTransport;
  2632. function createServerSocketTransport(port, encoding = 'utf-8') {
  2633. const socket = net_1.createConnection(port, '127.0.0.1');
  2634. return [
  2635. new messageReader_1.SocketMessageReader(socket, encoding),
  2636. new messageWriter_1.SocketMessageWriter(socket, encoding)
  2637. ];
  2638. }
  2639. exports.createServerSocketTransport = createServerSocketTransport;
  2640. /***/ }),
  2641. /* 18 */
  2642. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  2643. "use strict";
  2644. __webpack_require__.r(__webpack_exports__);
  2645. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
  2646. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
  2647. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
  2648. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
  2649. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
  2650. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
  2651. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
  2652. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
  2653. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
  2654. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
  2655. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
  2656. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
  2657. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
  2658. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
  2659. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
  2660. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
  2661. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
  2662. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
  2663. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
  2664. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
  2665. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
  2666. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
  2667. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
  2668. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
  2669. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
  2670. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
  2671. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
  2672. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
  2673. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemTag", function() { return CompletionItemTag; });
  2674. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
  2675. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
  2676. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
  2677. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
  2678. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
  2679. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
  2680. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
  2681. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
  2682. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
  2683. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolTag", function() { return SymbolTag; });
  2684. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
  2685. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
  2686. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
  2687. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
  2688. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
  2689. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
  2690. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
  2691. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
  2692. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
  2693. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
  2694. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
  2695. /* --------------------------------------------------------------------------------------------
  2696. * Copyright (c) Microsoft Corporation. All rights reserved.
  2697. * Licensed under the MIT License. See License.txt in the project root for license information.
  2698. * ------------------------------------------------------------------------------------------ */
  2699. /**
  2700. * The Position namespace provides helper functions to work with
  2701. * [Position](#Position) literals.
  2702. */
  2703. var Position;
  2704. (function (Position) {
  2705. /**
  2706. * Creates a new Position literal from the given line and character.
  2707. * @param line The position's line.
  2708. * @param character The position's character.
  2709. */
  2710. function create(line, character) {
  2711. return { line: line, character: character };
  2712. }
  2713. Position.create = create;
  2714. /**
  2715. * Checks whether the given liternal conforms to the [Position](#Position) interface.
  2716. */
  2717. function is(value) {
  2718. var candidate = value;
  2719. return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
  2720. }
  2721. Position.is = is;
  2722. })(Position || (Position = {}));
  2723. /**
  2724. * The Range namespace provides helper functions to work with
  2725. * [Range](#Range) literals.
  2726. */
  2727. var Range;
  2728. (function (Range) {
  2729. function create(one, two, three, four) {
  2730. if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
  2731. return { start: Position.create(one, two), end: Position.create(three, four) };
  2732. }
  2733. else if (Position.is(one) && Position.is(two)) {
  2734. return { start: one, end: two };
  2735. }
  2736. else {
  2737. throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
  2738. }
  2739. }
  2740. Range.create = create;
  2741. /**
  2742. * Checks whether the given literal conforms to the [Range](#Range) interface.
  2743. */
  2744. function is(value) {
  2745. var candidate = value;
  2746. return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
  2747. }
  2748. Range.is = is;
  2749. })(Range || (Range = {}));
  2750. /**
  2751. * The Location namespace provides helper functions to work with
  2752. * [Location](#Location) literals.
  2753. */
  2754. var Location;
  2755. (function (Location) {
  2756. /**
  2757. * Creates a Location literal.
  2758. * @param uri The location's uri.
  2759. * @param range The location's range.
  2760. */
  2761. function create(uri, range) {
  2762. return { uri: uri, range: range };
  2763. }
  2764. Location.create = create;
  2765. /**
  2766. * Checks whether the given literal conforms to the [Location](#Location) interface.
  2767. */
  2768. function is(value) {
  2769. var candidate = value;
  2770. return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
  2771. }
  2772. Location.is = is;
  2773. })(Location || (Location = {}));
  2774. /**
  2775. * The LocationLink namespace provides helper functions to work with
  2776. * [LocationLink](#LocationLink) literals.
  2777. */
  2778. var LocationLink;
  2779. (function (LocationLink) {
  2780. /**
  2781. * Creates a LocationLink literal.
  2782. * @param targetUri The definition's uri.
  2783. * @param targetRange The full range of the definition.
  2784. * @param targetSelectionRange The span of the symbol definition at the target.
  2785. * @param originSelectionRange The span of the symbol being defined in the originating source file.
  2786. */
  2787. function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
  2788. return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
  2789. }
  2790. LocationLink.create = create;
  2791. /**
  2792. * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
  2793. */
  2794. function is(value) {
  2795. var candidate = value;
  2796. return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
  2797. && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
  2798. && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
  2799. }
  2800. LocationLink.is = is;
  2801. })(LocationLink || (LocationLink = {}));
  2802. /**
  2803. * The Color namespace provides helper functions to work with
  2804. * [Color](#Color) literals.
  2805. */
  2806. var Color;
  2807. (function (Color) {
  2808. /**
  2809. * Creates a new Color literal.
  2810. */
  2811. function create(red, green, blue, alpha) {
  2812. return {
  2813. red: red,
  2814. green: green,
  2815. blue: blue,
  2816. alpha: alpha,
  2817. };
  2818. }
  2819. Color.create = create;
  2820. /**
  2821. * Checks whether the given literal conforms to the [Color](#Color) interface.
  2822. */
  2823. function is(value) {
  2824. var candidate = value;
  2825. return Is.number(candidate.red)
  2826. && Is.number(candidate.green)
  2827. && Is.number(candidate.blue)
  2828. && Is.number(candidate.alpha);
  2829. }
  2830. Color.is = is;
  2831. })(Color || (Color = {}));
  2832. /**
  2833. * The ColorInformation namespace provides helper functions to work with
  2834. * [ColorInformation](#ColorInformation) literals.
  2835. */
  2836. var ColorInformation;
  2837. (function (ColorInformation) {
  2838. /**
  2839. * Creates a new ColorInformation literal.
  2840. */
  2841. function create(range, color) {
  2842. return {
  2843. range: range,
  2844. color: color,
  2845. };
  2846. }
  2847. ColorInformation.create = create;
  2848. /**
  2849. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  2850. */
  2851. function is(value) {
  2852. var candidate = value;
  2853. return Range.is(candidate.range) && Color.is(candidate.color);
  2854. }
  2855. ColorInformation.is = is;
  2856. })(ColorInformation || (ColorInformation = {}));
  2857. /**
  2858. * The Color namespace provides helper functions to work with
  2859. * [ColorPresentation](#ColorPresentation) literals.
  2860. */
  2861. var ColorPresentation;
  2862. (function (ColorPresentation) {
  2863. /**
  2864. * Creates a new ColorInformation literal.
  2865. */
  2866. function create(label, textEdit, additionalTextEdits) {
  2867. return {
  2868. label: label,
  2869. textEdit: textEdit,
  2870. additionalTextEdits: additionalTextEdits,
  2871. };
  2872. }
  2873. ColorPresentation.create = create;
  2874. /**
  2875. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  2876. */
  2877. function is(value) {
  2878. var candidate = value;
  2879. return Is.string(candidate.label)
  2880. && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
  2881. && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
  2882. }
  2883. ColorPresentation.is = is;
  2884. })(ColorPresentation || (ColorPresentation = {}));
  2885. /**
  2886. * Enum of known range kinds
  2887. */
  2888. var FoldingRangeKind;
  2889. (function (FoldingRangeKind) {
  2890. /**
  2891. * Folding range for a comment
  2892. */
  2893. FoldingRangeKind["Comment"] = "comment";
  2894. /**
  2895. * Folding range for a imports or includes
  2896. */
  2897. FoldingRangeKind["Imports"] = "imports";
  2898. /**
  2899. * Folding range for a region (e.g. `#region`)
  2900. */
  2901. FoldingRangeKind["Region"] = "region";
  2902. })(FoldingRangeKind || (FoldingRangeKind = {}));
  2903. /**
  2904. * The folding range namespace provides helper functions to work with
  2905. * [FoldingRange](#FoldingRange) literals.
  2906. */
  2907. var FoldingRange;
  2908. (function (FoldingRange) {
  2909. /**
  2910. * Creates a new FoldingRange literal.
  2911. */
  2912. function create(startLine, endLine, startCharacter, endCharacter, kind) {
  2913. var result = {
  2914. startLine: startLine,
  2915. endLine: endLine
  2916. };
  2917. if (Is.defined(startCharacter)) {
  2918. result.startCharacter = startCharacter;
  2919. }
  2920. if (Is.defined(endCharacter)) {
  2921. result.endCharacter = endCharacter;
  2922. }
  2923. if (Is.defined(kind)) {
  2924. result.kind = kind;
  2925. }
  2926. return result;
  2927. }
  2928. FoldingRange.create = create;
  2929. /**
  2930. * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
  2931. */
  2932. function is(value) {
  2933. var candidate = value;
  2934. return Is.number(candidate.startLine) && Is.number(candidate.startLine)
  2935. && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
  2936. && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
  2937. && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
  2938. }
  2939. FoldingRange.is = is;
  2940. })(FoldingRange || (FoldingRange = {}));
  2941. /**
  2942. * The DiagnosticRelatedInformation namespace provides helper functions to work with
  2943. * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
  2944. */
  2945. var DiagnosticRelatedInformation;
  2946. (function (DiagnosticRelatedInformation) {
  2947. /**
  2948. * Creates a new DiagnosticRelatedInformation literal.
  2949. */
  2950. function create(location, message) {
  2951. return {
  2952. location: location,
  2953. message: message
  2954. };
  2955. }
  2956. DiagnosticRelatedInformation.create = create;
  2957. /**
  2958. * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
  2959. */
  2960. function is(value) {
  2961. var candidate = value;
  2962. return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
  2963. }
  2964. DiagnosticRelatedInformation.is = is;
  2965. })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
  2966. /**
  2967. * The diagnostic's severity.
  2968. */
  2969. var DiagnosticSeverity;
  2970. (function (DiagnosticSeverity) {
  2971. /**
  2972. * Reports an error.
  2973. */
  2974. DiagnosticSeverity.Error = 1;
  2975. /**
  2976. * Reports a warning.
  2977. */
  2978. DiagnosticSeverity.Warning = 2;
  2979. /**
  2980. * Reports an information.
  2981. */
  2982. DiagnosticSeverity.Information = 3;
  2983. /**
  2984. * Reports a hint.
  2985. */
  2986. DiagnosticSeverity.Hint = 4;
  2987. })(DiagnosticSeverity || (DiagnosticSeverity = {}));
  2988. /**
  2989. * The diagnostic tags.
  2990. *
  2991. * @since 3.15.0
  2992. */
  2993. var DiagnosticTag;
  2994. (function (DiagnosticTag) {
  2995. /**
  2996. * Unused or unnecessary code.
  2997. *
  2998. * Clients are allowed to render diagnostics with this tag faded out instead of having
  2999. * an error squiggle.
  3000. */
  3001. DiagnosticTag.Unnecessary = 1;
  3002. /**
  3003. * Deprecated or obsolete code.
  3004. *
  3005. * Clients are allowed to rendered diagnostics with this tag strike through.
  3006. */
  3007. DiagnosticTag.Deprecated = 2;
  3008. })(DiagnosticTag || (DiagnosticTag = {}));
  3009. /**
  3010. * The Diagnostic namespace provides helper functions to work with
  3011. * [Diagnostic](#Diagnostic) literals.
  3012. */
  3013. var Diagnostic;
  3014. (function (Diagnostic) {
  3015. /**
  3016. * Creates a new Diagnostic literal.
  3017. */
  3018. function create(range, message, severity, code, source, relatedInformation) {
  3019. var result = { range: range, message: message };
  3020. if (Is.defined(severity)) {
  3021. result.severity = severity;
  3022. }
  3023. if (Is.defined(code)) {
  3024. result.code = code;
  3025. }
  3026. if (Is.defined(source)) {
  3027. result.source = source;
  3028. }
  3029. if (Is.defined(relatedInformation)) {
  3030. result.relatedInformation = relatedInformation;
  3031. }
  3032. return result;
  3033. }
  3034. Diagnostic.create = create;
  3035. /**
  3036. * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
  3037. */
  3038. function is(value) {
  3039. var candidate = value;
  3040. return Is.defined(candidate)
  3041. && Range.is(candidate.range)
  3042. && Is.string(candidate.message)
  3043. && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
  3044. && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
  3045. && (Is.string(candidate.source) || Is.undefined(candidate.source))
  3046. && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
  3047. }
  3048. Diagnostic.is = is;
  3049. })(Diagnostic || (Diagnostic = {}));
  3050. /**
  3051. * The Command namespace provides helper functions to work with
  3052. * [Command](#Command) literals.
  3053. */
  3054. var Command;
  3055. (function (Command) {
  3056. /**
  3057. * Creates a new Command literal.
  3058. */
  3059. function create(title, command) {
  3060. var args = [];
  3061. for (var _i = 2; _i < arguments.length; _i++) {
  3062. args[_i - 2] = arguments[_i];
  3063. }
  3064. var result = { title: title, command: command };
  3065. if (Is.defined(args) && args.length > 0) {
  3066. result.arguments = args;
  3067. }
  3068. return result;
  3069. }
  3070. Command.create = create;
  3071. /**
  3072. * Checks whether the given literal conforms to the [Command](#Command) interface.
  3073. */
  3074. function is(value) {
  3075. var candidate = value;
  3076. return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
  3077. }
  3078. Command.is = is;
  3079. })(Command || (Command = {}));
  3080. /**
  3081. * The TextEdit namespace provides helper function to create replace,
  3082. * insert and delete edits more easily.
  3083. */
  3084. var TextEdit;
  3085. (function (TextEdit) {
  3086. /**
  3087. * Creates a replace text edit.
  3088. * @param range The range of text to be replaced.
  3089. * @param newText The new text.
  3090. */
  3091. function replace(range, newText) {
  3092. return { range: range, newText: newText };
  3093. }
  3094. TextEdit.replace = replace;
  3095. /**
  3096. * Creates a insert text edit.
  3097. * @param position The position to insert the text at.
  3098. * @param newText The text to be inserted.
  3099. */
  3100. function insert(position, newText) {
  3101. return { range: { start: position, end: position }, newText: newText };
  3102. }
  3103. TextEdit.insert = insert;
  3104. /**
  3105. * Creates a delete text edit.
  3106. * @param range The range of text to be deleted.
  3107. */
  3108. function del(range) {
  3109. return { range: range, newText: '' };
  3110. }
  3111. TextEdit.del = del;
  3112. function is(value) {
  3113. var candidate = value;
  3114. return Is.objectLiteral(candidate)
  3115. && Is.string(candidate.newText)
  3116. && Range.is(candidate.range);
  3117. }
  3118. TextEdit.is = is;
  3119. })(TextEdit || (TextEdit = {}));
  3120. /**
  3121. * The TextDocumentEdit namespace provides helper function to create
  3122. * an edit that manipulates a text document.
  3123. */
  3124. var TextDocumentEdit;
  3125. (function (TextDocumentEdit) {
  3126. /**
  3127. * Creates a new `TextDocumentEdit`
  3128. */
  3129. function create(textDocument, edits) {
  3130. return { textDocument: textDocument, edits: edits };
  3131. }
  3132. TextDocumentEdit.create = create;
  3133. function is(value) {
  3134. var candidate = value;
  3135. return Is.defined(candidate)
  3136. && VersionedTextDocumentIdentifier.is(candidate.textDocument)
  3137. && Array.isArray(candidate.edits);
  3138. }
  3139. TextDocumentEdit.is = is;
  3140. })(TextDocumentEdit || (TextDocumentEdit = {}));
  3141. var CreateFile;
  3142. (function (CreateFile) {
  3143. function create(uri, options) {
  3144. var result = {
  3145. kind: 'create',
  3146. uri: uri
  3147. };
  3148. if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
  3149. result.options = options;
  3150. }
  3151. return result;
  3152. }
  3153. CreateFile.create = create;
  3154. function is(value) {
  3155. var candidate = value;
  3156. return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
  3157. (candidate.options === void 0 ||
  3158. ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
  3159. }
  3160. CreateFile.is = is;
  3161. })(CreateFile || (CreateFile = {}));
  3162. var RenameFile;
  3163. (function (RenameFile) {
  3164. function create(oldUri, newUri, options) {
  3165. var result = {
  3166. kind: 'rename',
  3167. oldUri: oldUri,
  3168. newUri: newUri
  3169. };
  3170. if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
  3171. result.options = options;
  3172. }
  3173. return result;
  3174. }
  3175. RenameFile.create = create;
  3176. function is(value) {
  3177. var candidate = value;
  3178. return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
  3179. (candidate.options === void 0 ||
  3180. ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
  3181. }
  3182. RenameFile.is = is;
  3183. })(RenameFile || (RenameFile = {}));
  3184. var DeleteFile;
  3185. (function (DeleteFile) {
  3186. function create(uri, options) {
  3187. var result = {
  3188. kind: 'delete',
  3189. uri: uri
  3190. };
  3191. if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
  3192. result.options = options;
  3193. }
  3194. return result;
  3195. }
  3196. DeleteFile.create = create;
  3197. function is(value) {
  3198. var candidate = value;
  3199. return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
  3200. (candidate.options === void 0 ||
  3201. ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
  3202. }
  3203. DeleteFile.is = is;
  3204. })(DeleteFile || (DeleteFile = {}));
  3205. var WorkspaceEdit;
  3206. (function (WorkspaceEdit) {
  3207. function is(value) {
  3208. var candidate = value;
  3209. return candidate &&
  3210. (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
  3211. (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
  3212. if (Is.string(change.kind)) {
  3213. return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
  3214. }
  3215. else {
  3216. return TextDocumentEdit.is(change);
  3217. }
  3218. }));
  3219. }
  3220. WorkspaceEdit.is = is;
  3221. })(WorkspaceEdit || (WorkspaceEdit = {}));
  3222. var TextEditChangeImpl = /** @class */ (function () {
  3223. function TextEditChangeImpl(edits) {
  3224. this.edits = edits;
  3225. }
  3226. TextEditChangeImpl.prototype.insert = function (position, newText) {
  3227. this.edits.push(TextEdit.insert(position, newText));
  3228. };
  3229. TextEditChangeImpl.prototype.replace = function (range, newText) {
  3230. this.edits.push(TextEdit.replace(range, newText));
  3231. };
  3232. TextEditChangeImpl.prototype.delete = function (range) {
  3233. this.edits.push(TextEdit.del(range));
  3234. };
  3235. TextEditChangeImpl.prototype.add = function (edit) {
  3236. this.edits.push(edit);
  3237. };
  3238. TextEditChangeImpl.prototype.all = function () {
  3239. return this.edits;
  3240. };
  3241. TextEditChangeImpl.prototype.clear = function () {
  3242. this.edits.splice(0, this.edits.length);
  3243. };
  3244. return TextEditChangeImpl;
  3245. }());
  3246. /**
  3247. * A workspace change helps constructing changes to a workspace.
  3248. */
  3249. var WorkspaceChange = /** @class */ (function () {
  3250. function WorkspaceChange(workspaceEdit) {
  3251. var _this = this;
  3252. this._textEditChanges = Object.create(null);
  3253. if (workspaceEdit) {
  3254. this._workspaceEdit = workspaceEdit;
  3255. if (workspaceEdit.documentChanges) {
  3256. workspaceEdit.documentChanges.forEach(function (change) {
  3257. if (TextDocumentEdit.is(change)) {
  3258. var textEditChange = new TextEditChangeImpl(change.edits);
  3259. _this._textEditChanges[change.textDocument.uri] = textEditChange;
  3260. }
  3261. });
  3262. }
  3263. else if (workspaceEdit.changes) {
  3264. Object.keys(workspaceEdit.changes).forEach(function (key) {
  3265. var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
  3266. _this._textEditChanges[key] = textEditChange;
  3267. });
  3268. }
  3269. }
  3270. }
  3271. Object.defineProperty(WorkspaceChange.prototype, "edit", {
  3272. /**
  3273. * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
  3274. * use to be returned from a workspace edit operation like rename.
  3275. */
  3276. get: function () {
  3277. return this._workspaceEdit;
  3278. },
  3279. enumerable: true,
  3280. configurable: true
  3281. });
  3282. WorkspaceChange.prototype.getTextEditChange = function (key) {
  3283. if (VersionedTextDocumentIdentifier.is(key)) {
  3284. if (!this._workspaceEdit) {
  3285. this._workspaceEdit = {
  3286. documentChanges: []
  3287. };
  3288. }
  3289. if (!this._workspaceEdit.documentChanges) {
  3290. throw new Error('Workspace edit is not configured for document changes.');
  3291. }
  3292. var textDocument = key;
  3293. var result = this._textEditChanges[textDocument.uri];
  3294. if (!result) {
  3295. var edits = [];
  3296. var textDocumentEdit = {
  3297. textDocument: textDocument,
  3298. edits: edits
  3299. };
  3300. this._workspaceEdit.documentChanges.push(textDocumentEdit);
  3301. result = new TextEditChangeImpl(edits);
  3302. this._textEditChanges[textDocument.uri] = result;
  3303. }
  3304. return result;
  3305. }
  3306. else {
  3307. if (!this._workspaceEdit) {
  3308. this._workspaceEdit = {
  3309. changes: Object.create(null)
  3310. };
  3311. }
  3312. if (!this._workspaceEdit.changes) {
  3313. throw new Error('Workspace edit is not configured for normal text edit changes.');
  3314. }
  3315. var result = this._textEditChanges[key];
  3316. if (!result) {
  3317. var edits = [];
  3318. this._workspaceEdit.changes[key] = edits;
  3319. result = new TextEditChangeImpl(edits);
  3320. this._textEditChanges[key] = result;
  3321. }
  3322. return result;
  3323. }
  3324. };
  3325. WorkspaceChange.prototype.createFile = function (uri, options) {
  3326. this.checkDocumentChanges();
  3327. this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
  3328. };
  3329. WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
  3330. this.checkDocumentChanges();
  3331. this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
  3332. };
  3333. WorkspaceChange.prototype.deleteFile = function (uri, options) {
  3334. this.checkDocumentChanges();
  3335. this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
  3336. };
  3337. WorkspaceChange.prototype.checkDocumentChanges = function () {
  3338. if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
  3339. throw new Error('Workspace edit is not configured for document changes.');
  3340. }
  3341. };
  3342. return WorkspaceChange;
  3343. }());
  3344. /**
  3345. * The TextDocumentIdentifier namespace provides helper functions to work with
  3346. * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
  3347. */
  3348. var TextDocumentIdentifier;
  3349. (function (TextDocumentIdentifier) {
  3350. /**
  3351. * Creates a new TextDocumentIdentifier literal.
  3352. * @param uri The document's uri.
  3353. */
  3354. function create(uri) {
  3355. return { uri: uri };
  3356. }
  3357. TextDocumentIdentifier.create = create;
  3358. /**
  3359. * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
  3360. */
  3361. function is(value) {
  3362. var candidate = value;
  3363. return Is.defined(candidate) && Is.string(candidate.uri);
  3364. }
  3365. TextDocumentIdentifier.is = is;
  3366. })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
  3367. /**
  3368. * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
  3369. * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
  3370. */
  3371. var VersionedTextDocumentIdentifier;
  3372. (function (VersionedTextDocumentIdentifier) {
  3373. /**
  3374. * Creates a new VersionedTextDocumentIdentifier literal.
  3375. * @param uri The document's uri.
  3376. * @param uri The document's text.
  3377. */
  3378. function create(uri, version) {
  3379. return { uri: uri, version: version };
  3380. }
  3381. VersionedTextDocumentIdentifier.create = create;
  3382. /**
  3383. * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
  3384. */
  3385. function is(value) {
  3386. var candidate = value;
  3387. return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
  3388. }
  3389. VersionedTextDocumentIdentifier.is = is;
  3390. })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
  3391. /**
  3392. * The TextDocumentItem namespace provides helper functions to work with
  3393. * [TextDocumentItem](#TextDocumentItem) literals.
  3394. */
  3395. var TextDocumentItem;
  3396. (function (TextDocumentItem) {
  3397. /**
  3398. * Creates a new TextDocumentItem literal.
  3399. * @param uri The document's uri.
  3400. * @param languageId The document's language identifier.
  3401. * @param version The document's version number.
  3402. * @param text The document's text.
  3403. */
  3404. function create(uri, languageId, version, text) {
  3405. return { uri: uri, languageId: languageId, version: version, text: text };
  3406. }
  3407. TextDocumentItem.create = create;
  3408. /**
  3409. * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
  3410. */
  3411. function is(value) {
  3412. var candidate = value;
  3413. return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
  3414. }
  3415. TextDocumentItem.is = is;
  3416. })(TextDocumentItem || (TextDocumentItem = {}));
  3417. /**
  3418. * Describes the content type that a client supports in various
  3419. * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
  3420. *
  3421. * Please note that `MarkupKinds` must not start with a `$`. This kinds
  3422. * are reserved for internal usage.
  3423. */
  3424. var MarkupKind;
  3425. (function (MarkupKind) {
  3426. /**
  3427. * Plain text is supported as a content format
  3428. */
  3429. MarkupKind.PlainText = 'plaintext';
  3430. /**
  3431. * Markdown is supported as a content format
  3432. */
  3433. MarkupKind.Markdown = 'markdown';
  3434. })(MarkupKind || (MarkupKind = {}));
  3435. (function (MarkupKind) {
  3436. /**
  3437. * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
  3438. */
  3439. function is(value) {
  3440. var candidate = value;
  3441. return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
  3442. }
  3443. MarkupKind.is = is;
  3444. })(MarkupKind || (MarkupKind = {}));
  3445. var MarkupContent;
  3446. (function (MarkupContent) {
  3447. /**
  3448. * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
  3449. */
  3450. function is(value) {
  3451. var candidate = value;
  3452. return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
  3453. }
  3454. MarkupContent.is = is;
  3455. })(MarkupContent || (MarkupContent = {}));
  3456. /**
  3457. * The kind of a completion entry.
  3458. */
  3459. var CompletionItemKind;
  3460. (function (CompletionItemKind) {
  3461. CompletionItemKind.Text = 1;
  3462. CompletionItemKind.Method = 2;
  3463. CompletionItemKind.Function = 3;
  3464. CompletionItemKind.Constructor = 4;
  3465. CompletionItemKind.Field = 5;
  3466. CompletionItemKind.Variable = 6;
  3467. CompletionItemKind.Class = 7;
  3468. CompletionItemKind.Interface = 8;
  3469. CompletionItemKind.Module = 9;
  3470. CompletionItemKind.Property = 10;
  3471. CompletionItemKind.Unit = 11;
  3472. CompletionItemKind.Value = 12;
  3473. CompletionItemKind.Enum = 13;
  3474. CompletionItemKind.Keyword = 14;
  3475. CompletionItemKind.Snippet = 15;
  3476. CompletionItemKind.Color = 16;
  3477. CompletionItemKind.File = 17;
  3478. CompletionItemKind.Reference = 18;
  3479. CompletionItemKind.Folder = 19;
  3480. CompletionItemKind.EnumMember = 20;
  3481. CompletionItemKind.Constant = 21;
  3482. CompletionItemKind.Struct = 22;
  3483. CompletionItemKind.Event = 23;
  3484. CompletionItemKind.Operator = 24;
  3485. CompletionItemKind.TypeParameter = 25;
  3486. })(CompletionItemKind || (CompletionItemKind = {}));
  3487. /**
  3488. * Defines whether the insert text in a completion item should be interpreted as
  3489. * plain text or a snippet.
  3490. */
  3491. var InsertTextFormat;
  3492. (function (InsertTextFormat) {
  3493. /**
  3494. * The primary text to be inserted is treated as a plain string.
  3495. */
  3496. InsertTextFormat.PlainText = 1;
  3497. /**
  3498. * The primary text to be inserted is treated as a snippet.
  3499. *
  3500. * A snippet can define tab stops and placeholders with `$1`, `$2`
  3501. * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
  3502. * the end of the snippet. Placeholders with equal identifiers are linked,
  3503. * that is typing in one will update others too.
  3504. *
  3505. * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
  3506. */
  3507. InsertTextFormat.Snippet = 2;
  3508. })(InsertTextFormat || (InsertTextFormat = {}));
  3509. /**
  3510. * Completion item tags are extra annotations that tweak the rendering of a completion
  3511. * item.
  3512. *
  3513. * @since 3.15.0
  3514. */
  3515. var CompletionItemTag;
  3516. (function (CompletionItemTag) {
  3517. /**
  3518. * Render a completion as obsolete, usually using a strike-out.
  3519. */
  3520. CompletionItemTag.Deprecated = 1;
  3521. })(CompletionItemTag || (CompletionItemTag = {}));
  3522. /**
  3523. * The CompletionItem namespace provides functions to deal with
  3524. * completion items.
  3525. */
  3526. var CompletionItem;
  3527. (function (CompletionItem) {
  3528. /**
  3529. * Create a completion item and seed it with a label.
  3530. * @param label The completion item's label
  3531. */
  3532. function create(label) {
  3533. return { label: label };
  3534. }
  3535. CompletionItem.create = create;
  3536. })(CompletionItem || (CompletionItem = {}));
  3537. /**
  3538. * The CompletionList namespace provides functions to deal with
  3539. * completion lists.
  3540. */
  3541. var CompletionList;
  3542. (function (CompletionList) {
  3543. /**
  3544. * Creates a new completion list.
  3545. *
  3546. * @param items The completion items.
  3547. * @param isIncomplete The list is not complete.
  3548. */
  3549. function create(items, isIncomplete) {
  3550. return { items: items ? items : [], isIncomplete: !!isIncomplete };
  3551. }
  3552. CompletionList.create = create;
  3553. })(CompletionList || (CompletionList = {}));
  3554. var MarkedString;
  3555. (function (MarkedString) {
  3556. /**
  3557. * Creates a marked string from plain text.
  3558. *
  3559. * @param plainText The plain text.
  3560. */
  3561. function fromPlainText(plainText) {
  3562. return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
  3563. }
  3564. MarkedString.fromPlainText = fromPlainText;
  3565. /**
  3566. * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
  3567. */
  3568. function is(value) {
  3569. var candidate = value;
  3570. return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
  3571. }
  3572. MarkedString.is = is;
  3573. })(MarkedString || (MarkedString = {}));
  3574. var Hover;
  3575. (function (Hover) {
  3576. /**
  3577. * Checks whether the given value conforms to the [Hover](#Hover) interface.
  3578. */
  3579. function is(value) {
  3580. var candidate = value;
  3581. return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
  3582. MarkedString.is(candidate.contents) ||
  3583. Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
  3584. }
  3585. Hover.is = is;
  3586. })(Hover || (Hover = {}));
  3587. /**
  3588. * The ParameterInformation namespace provides helper functions to work with
  3589. * [ParameterInformation](#ParameterInformation) literals.
  3590. */
  3591. var ParameterInformation;
  3592. (function (ParameterInformation) {
  3593. /**
  3594. * Creates a new parameter information literal.
  3595. *
  3596. * @param label A label string.
  3597. * @param documentation A doc string.
  3598. */
  3599. function create(label, documentation) {
  3600. return documentation ? { label: label, documentation: documentation } : { label: label };
  3601. }
  3602. ParameterInformation.create = create;
  3603. })(ParameterInformation || (ParameterInformation = {}));
  3604. /**
  3605. * The SignatureInformation namespace provides helper functions to work with
  3606. * [SignatureInformation](#SignatureInformation) literals.
  3607. */
  3608. var SignatureInformation;
  3609. (function (SignatureInformation) {
  3610. function create(label, documentation) {
  3611. var parameters = [];
  3612. for (var _i = 2; _i < arguments.length; _i++) {
  3613. parameters[_i - 2] = arguments[_i];
  3614. }
  3615. var result = { label: label };
  3616. if (Is.defined(documentation)) {
  3617. result.documentation = documentation;
  3618. }
  3619. if (Is.defined(parameters)) {
  3620. result.parameters = parameters;
  3621. }
  3622. else {
  3623. result.parameters = [];
  3624. }
  3625. return result;
  3626. }
  3627. SignatureInformation.create = create;
  3628. })(SignatureInformation || (SignatureInformation = {}));
  3629. /**
  3630. * A document highlight kind.
  3631. */
  3632. var DocumentHighlightKind;
  3633. (function (DocumentHighlightKind) {
  3634. /**
  3635. * A textual occurrence.
  3636. */
  3637. DocumentHighlightKind.Text = 1;
  3638. /**
  3639. * Read-access of a symbol, like reading a variable.
  3640. */
  3641. DocumentHighlightKind.Read = 2;
  3642. /**
  3643. * Write-access of a symbol, like writing to a variable.
  3644. */
  3645. DocumentHighlightKind.Write = 3;
  3646. })(DocumentHighlightKind || (DocumentHighlightKind = {}));
  3647. /**
  3648. * DocumentHighlight namespace to provide helper functions to work with
  3649. * [DocumentHighlight](#DocumentHighlight) literals.
  3650. */
  3651. var DocumentHighlight;
  3652. (function (DocumentHighlight) {
  3653. /**
  3654. * Create a DocumentHighlight object.
  3655. * @param range The range the highlight applies to.
  3656. */
  3657. function create(range, kind) {
  3658. var result = { range: range };
  3659. if (Is.number(kind)) {
  3660. result.kind = kind;
  3661. }
  3662. return result;
  3663. }
  3664. DocumentHighlight.create = create;
  3665. })(DocumentHighlight || (DocumentHighlight = {}));
  3666. /**
  3667. * A symbol kind.
  3668. */
  3669. var SymbolKind;
  3670. (function (SymbolKind) {
  3671. SymbolKind.File = 1;
  3672. SymbolKind.Module = 2;
  3673. SymbolKind.Namespace = 3;
  3674. SymbolKind.Package = 4;
  3675. SymbolKind.Class = 5;
  3676. SymbolKind.Method = 6;
  3677. SymbolKind.Property = 7;
  3678. SymbolKind.Field = 8;
  3679. SymbolKind.Constructor = 9;
  3680. SymbolKind.Enum = 10;
  3681. SymbolKind.Interface = 11;
  3682. SymbolKind.Function = 12;
  3683. SymbolKind.Variable = 13;
  3684. SymbolKind.Constant = 14;
  3685. SymbolKind.String = 15;
  3686. SymbolKind.Number = 16;
  3687. SymbolKind.Boolean = 17;
  3688. SymbolKind.Array = 18;
  3689. SymbolKind.Object = 19;
  3690. SymbolKind.Key = 20;
  3691. SymbolKind.Null = 21;
  3692. SymbolKind.EnumMember = 22;
  3693. SymbolKind.Struct = 23;
  3694. SymbolKind.Event = 24;
  3695. SymbolKind.Operator = 25;
  3696. SymbolKind.TypeParameter = 26;
  3697. })(SymbolKind || (SymbolKind = {}));
  3698. /**
  3699. * Symbol tags are extra annotations that tweak the rendering of a symbol.
  3700. * @since 3.15
  3701. */
  3702. var SymbolTag;
  3703. (function (SymbolTag) {
  3704. /**
  3705. * Render a symbol as obsolete, usually using a strike-out.
  3706. */
  3707. SymbolTag.Deprecated = 1;
  3708. })(SymbolTag || (SymbolTag = {}));
  3709. var SymbolInformation;
  3710. (function (SymbolInformation) {
  3711. /**
  3712. * Creates a new symbol information literal.
  3713. *
  3714. * @param name The name of the symbol.
  3715. * @param kind The kind of the symbol.
  3716. * @param range The range of the location of the symbol.
  3717. * @param uri The resource of the location of symbol, defaults to the current document.
  3718. * @param containerName The name of the symbol containing the symbol.
  3719. */
  3720. function create(name, kind, range, uri, containerName) {
  3721. var result = {
  3722. name: name,
  3723. kind: kind,
  3724. location: { uri: uri, range: range }
  3725. };
  3726. if (containerName) {
  3727. result.containerName = containerName;
  3728. }
  3729. return result;
  3730. }
  3731. SymbolInformation.create = create;
  3732. })(SymbolInformation || (SymbolInformation = {}));
  3733. var DocumentSymbol;
  3734. (function (DocumentSymbol) {
  3735. /**
  3736. * Creates a new symbol information literal.
  3737. *
  3738. * @param name The name of the symbol.
  3739. * @param detail The detail of the symbol.
  3740. * @param kind The kind of the symbol.
  3741. * @param range The range of the symbol.
  3742. * @param selectionRange The selectionRange of the symbol.
  3743. * @param children Children of the symbol.
  3744. */
  3745. function create(name, detail, kind, range, selectionRange, children) {
  3746. var result = {
  3747. name: name,
  3748. detail: detail,
  3749. kind: kind,
  3750. range: range,
  3751. selectionRange: selectionRange
  3752. };
  3753. if (children !== void 0) {
  3754. result.children = children;
  3755. }
  3756. return result;
  3757. }
  3758. DocumentSymbol.create = create;
  3759. /**
  3760. * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
  3761. */
  3762. function is(value) {
  3763. var candidate = value;
  3764. return candidate &&
  3765. Is.string(candidate.name) && Is.number(candidate.kind) &&
  3766. Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
  3767. (candidate.detail === void 0 || Is.string(candidate.detail)) &&
  3768. (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
  3769. (candidate.children === void 0 || Array.isArray(candidate.children));
  3770. }
  3771. DocumentSymbol.is = is;
  3772. })(DocumentSymbol || (DocumentSymbol = {}));
  3773. /**
  3774. * A set of predefined code action kinds
  3775. */
  3776. var CodeActionKind;
  3777. (function (CodeActionKind) {
  3778. /**
  3779. * Empty kind.
  3780. */
  3781. CodeActionKind.Empty = '';
  3782. /**
  3783. * Base kind for quickfix actions: 'quickfix'
  3784. */
  3785. CodeActionKind.QuickFix = 'quickfix';
  3786. /**
  3787. * Base kind for refactoring actions: 'refactor'
  3788. */
  3789. CodeActionKind.Refactor = 'refactor';
  3790. /**
  3791. * Base kind for refactoring extraction actions: 'refactor.extract'
  3792. *
  3793. * Example extract actions:
  3794. *
  3795. * - Extract method
  3796. * - Extract function
  3797. * - Extract variable
  3798. * - Extract interface from class
  3799. * - ...
  3800. */
  3801. CodeActionKind.RefactorExtract = 'refactor.extract';
  3802. /**
  3803. * Base kind for refactoring inline actions: 'refactor.inline'
  3804. *
  3805. * Example inline actions:
  3806. *
  3807. * - Inline function
  3808. * - Inline variable
  3809. * - Inline constant
  3810. * - ...
  3811. */
  3812. CodeActionKind.RefactorInline = 'refactor.inline';
  3813. /**
  3814. * Base kind for refactoring rewrite actions: 'refactor.rewrite'
  3815. *
  3816. * Example rewrite actions:
  3817. *
  3818. * - Convert JavaScript function to class
  3819. * - Add or remove parameter
  3820. * - Encapsulate field
  3821. * - Make method static
  3822. * - Move method to base class
  3823. * - ...
  3824. */
  3825. CodeActionKind.RefactorRewrite = 'refactor.rewrite';
  3826. /**
  3827. * Base kind for source actions: `source`
  3828. *
  3829. * Source code actions apply to the entire file.
  3830. */
  3831. CodeActionKind.Source = 'source';
  3832. /**
  3833. * Base kind for an organize imports source action: `source.organizeImports`
  3834. */
  3835. CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
  3836. /**
  3837. * Base kind for auto-fix source actions: `source.fixAll`.
  3838. *
  3839. * Fix all actions automatically fix errors that have a clear fix that do not require user input.
  3840. * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
  3841. *
  3842. * @since 3.15.0
  3843. */
  3844. CodeActionKind.SourceFixAll = 'source.fixAll';
  3845. })(CodeActionKind || (CodeActionKind = {}));
  3846. /**
  3847. * The CodeActionContext namespace provides helper functions to work with
  3848. * [CodeActionContext](#CodeActionContext) literals.
  3849. */
  3850. var CodeActionContext;
  3851. (function (CodeActionContext) {
  3852. /**
  3853. * Creates a new CodeActionContext literal.
  3854. */
  3855. function create(diagnostics, only) {
  3856. var result = { diagnostics: diagnostics };
  3857. if (only !== void 0 && only !== null) {
  3858. result.only = only;
  3859. }
  3860. return result;
  3861. }
  3862. CodeActionContext.create = create;
  3863. /**
  3864. * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
  3865. */
  3866. function is(value) {
  3867. var candidate = value;
  3868. return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
  3869. }
  3870. CodeActionContext.is = is;
  3871. })(CodeActionContext || (CodeActionContext = {}));
  3872. var CodeAction;
  3873. (function (CodeAction) {
  3874. function create(title, commandOrEdit, kind) {
  3875. var result = { title: title };
  3876. if (Command.is(commandOrEdit)) {
  3877. result.command = commandOrEdit;
  3878. }
  3879. else {
  3880. result.edit = commandOrEdit;
  3881. }
  3882. if (kind !== void 0) {
  3883. result.kind = kind;
  3884. }
  3885. return result;
  3886. }
  3887. CodeAction.create = create;
  3888. function is(value) {
  3889. var candidate = value;
  3890. return candidate && Is.string(candidate.title) &&
  3891. (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
  3892. (candidate.kind === void 0 || Is.string(candidate.kind)) &&
  3893. (candidate.edit !== void 0 || candidate.command !== void 0) &&
  3894. (candidate.command === void 0 || Command.is(candidate.command)) &&
  3895. (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&
  3896. (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
  3897. }
  3898. CodeAction.is = is;
  3899. })(CodeAction || (CodeAction = {}));
  3900. /**
  3901. * The CodeLens namespace provides helper functions to work with
  3902. * [CodeLens](#CodeLens) literals.
  3903. */
  3904. var CodeLens;
  3905. (function (CodeLens) {
  3906. /**
  3907. * Creates a new CodeLens literal.
  3908. */
  3909. function create(range, data) {
  3910. var result = { range: range };
  3911. if (Is.defined(data)) {
  3912. result.data = data;
  3913. }
  3914. return result;
  3915. }
  3916. CodeLens.create = create;
  3917. /**
  3918. * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
  3919. */
  3920. function is(value) {
  3921. var candidate = value;
  3922. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
  3923. }
  3924. CodeLens.is = is;
  3925. })(CodeLens || (CodeLens = {}));
  3926. /**
  3927. * The FormattingOptions namespace provides helper functions to work with
  3928. * [FormattingOptions](#FormattingOptions) literals.
  3929. */
  3930. var FormattingOptions;
  3931. (function (FormattingOptions) {
  3932. /**
  3933. * Creates a new FormattingOptions literal.
  3934. */
  3935. function create(tabSize, insertSpaces) {
  3936. return { tabSize: tabSize, insertSpaces: insertSpaces };
  3937. }
  3938. FormattingOptions.create = create;
  3939. /**
  3940. * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
  3941. */
  3942. function is(value) {
  3943. var candidate = value;
  3944. return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
  3945. }
  3946. FormattingOptions.is = is;
  3947. })(FormattingOptions || (FormattingOptions = {}));
  3948. /**
  3949. * The DocumentLink namespace provides helper functions to work with
  3950. * [DocumentLink](#DocumentLink) literals.
  3951. */
  3952. var DocumentLink;
  3953. (function (DocumentLink) {
  3954. /**
  3955. * Creates a new DocumentLink literal.
  3956. */
  3957. function create(range, target, data) {
  3958. return { range: range, target: target, data: data };
  3959. }
  3960. DocumentLink.create = create;
  3961. /**
  3962. * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
  3963. */
  3964. function is(value) {
  3965. var candidate = value;
  3966. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
  3967. }
  3968. DocumentLink.is = is;
  3969. })(DocumentLink || (DocumentLink = {}));
  3970. /**
  3971. * The SelectionRange namespace provides helper function to work with
  3972. * SelectionRange literals.
  3973. */
  3974. var SelectionRange;
  3975. (function (SelectionRange) {
  3976. /**
  3977. * Creates a new SelectionRange
  3978. * @param range the range.
  3979. * @param parent an optional parent.
  3980. */
  3981. function create(range, parent) {
  3982. return { range: range, parent: parent };
  3983. }
  3984. SelectionRange.create = create;
  3985. function is(value) {
  3986. var candidate = value;
  3987. return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
  3988. }
  3989. SelectionRange.is = is;
  3990. })(SelectionRange || (SelectionRange = {}));
  3991. var EOL = ['\n', '\r\n', '\r'];
  3992. /**
  3993. * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
  3994. */
  3995. var TextDocument;
  3996. (function (TextDocument) {
  3997. /**
  3998. * Creates a new ITextDocument literal from the given uri and content.
  3999. * @param uri The document's uri.
  4000. * @param languageId The document's language Id.
  4001. * @param content The document's content.
  4002. */
  4003. function create(uri, languageId, version, content) {
  4004. return new FullTextDocument(uri, languageId, version, content);
  4005. }
  4006. TextDocument.create = create;
  4007. /**
  4008. * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
  4009. */
  4010. function is(value) {
  4011. var candidate = value;
  4012. return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
  4013. && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
  4014. }
  4015. TextDocument.is = is;
  4016. function applyEdits(document, edits) {
  4017. var text = document.getText();
  4018. var sortedEdits = mergeSort(edits, function (a, b) {
  4019. var diff = a.range.start.line - b.range.start.line;
  4020. if (diff === 0) {
  4021. return a.range.start.character - b.range.start.character;
  4022. }
  4023. return diff;
  4024. });
  4025. var lastModifiedOffset = text.length;
  4026. for (var i = sortedEdits.length - 1; i >= 0; i--) {
  4027. var e = sortedEdits[i];
  4028. var startOffset = document.offsetAt(e.range.start);
  4029. var endOffset = document.offsetAt(e.range.end);
  4030. if (endOffset <= lastModifiedOffset) {
  4031. text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
  4032. }
  4033. else {
  4034. throw new Error('Overlapping edit');
  4035. }
  4036. lastModifiedOffset = startOffset;
  4037. }
  4038. return text;
  4039. }
  4040. TextDocument.applyEdits = applyEdits;
  4041. function mergeSort(data, compare) {
  4042. if (data.length <= 1) {
  4043. // sorted
  4044. return data;
  4045. }
  4046. var p = (data.length / 2) | 0;
  4047. var left = data.slice(0, p);
  4048. var right = data.slice(p);
  4049. mergeSort(left, compare);
  4050. mergeSort(right, compare);
  4051. var leftIdx = 0;
  4052. var rightIdx = 0;
  4053. var i = 0;
  4054. while (leftIdx < left.length && rightIdx < right.length) {
  4055. var ret = compare(left[leftIdx], right[rightIdx]);
  4056. if (ret <= 0) {
  4057. // smaller_equal -> take left to preserve order
  4058. data[i++] = left[leftIdx++];
  4059. }
  4060. else {
  4061. // greater -> take right
  4062. data[i++] = right[rightIdx++];
  4063. }
  4064. }
  4065. while (leftIdx < left.length) {
  4066. data[i++] = left[leftIdx++];
  4067. }
  4068. while (rightIdx < right.length) {
  4069. data[i++] = right[rightIdx++];
  4070. }
  4071. return data;
  4072. }
  4073. })(TextDocument || (TextDocument = {}));
  4074. var FullTextDocument = /** @class */ (function () {
  4075. function FullTextDocument(uri, languageId, version, content) {
  4076. this._uri = uri;
  4077. this._languageId = languageId;
  4078. this._version = version;
  4079. this._content = content;
  4080. this._lineOffsets = undefined;
  4081. }
  4082. Object.defineProperty(FullTextDocument.prototype, "uri", {
  4083. get: function () {
  4084. return this._uri;
  4085. },
  4086. enumerable: true,
  4087. configurable: true
  4088. });
  4089. Object.defineProperty(FullTextDocument.prototype, "languageId", {
  4090. get: function () {
  4091. return this._languageId;
  4092. },
  4093. enumerable: true,
  4094. configurable: true
  4095. });
  4096. Object.defineProperty(FullTextDocument.prototype, "version", {
  4097. get: function () {
  4098. return this._version;
  4099. },
  4100. enumerable: true,
  4101. configurable: true
  4102. });
  4103. FullTextDocument.prototype.getText = function (range) {
  4104. if (range) {
  4105. var start = this.offsetAt(range.start);
  4106. var end = this.offsetAt(range.end);
  4107. return this._content.substring(start, end);
  4108. }
  4109. return this._content;
  4110. };
  4111. FullTextDocument.prototype.update = function (event, version) {
  4112. this._content = event.text;
  4113. this._version = version;
  4114. this._lineOffsets = undefined;
  4115. };
  4116. FullTextDocument.prototype.getLineOffsets = function () {
  4117. if (this._lineOffsets === undefined) {
  4118. var lineOffsets = [];
  4119. var text = this._content;
  4120. var isLineStart = true;
  4121. for (var i = 0; i < text.length; i++) {
  4122. if (isLineStart) {
  4123. lineOffsets.push(i);
  4124. isLineStart = false;
  4125. }
  4126. var ch = text.charAt(i);
  4127. isLineStart = (ch === '\r' || ch === '\n');
  4128. if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
  4129. i++;
  4130. }
  4131. }
  4132. if (isLineStart && text.length > 0) {
  4133. lineOffsets.push(text.length);
  4134. }
  4135. this._lineOffsets = lineOffsets;
  4136. }
  4137. return this._lineOffsets;
  4138. };
  4139. FullTextDocument.prototype.positionAt = function (offset) {
  4140. offset = Math.max(Math.min(offset, this._content.length), 0);
  4141. var lineOffsets = this.getLineOffsets();
  4142. var low = 0, high = lineOffsets.length;
  4143. if (high === 0) {
  4144. return Position.create(0, offset);
  4145. }
  4146. while (low < high) {
  4147. var mid = Math.floor((low + high) / 2);
  4148. if (lineOffsets[mid] > offset) {
  4149. high = mid;
  4150. }
  4151. else {
  4152. low = mid + 1;
  4153. }
  4154. }
  4155. // low is the least x for which the line offset is larger than the current offset
  4156. // or array.length if no line offset is larger than the current offset
  4157. var line = low - 1;
  4158. return Position.create(line, offset - lineOffsets[line]);
  4159. };
  4160. FullTextDocument.prototype.offsetAt = function (position) {
  4161. var lineOffsets = this.getLineOffsets();
  4162. if (position.line >= lineOffsets.length) {
  4163. return this._content.length;
  4164. }
  4165. else if (position.line < 0) {
  4166. return 0;
  4167. }
  4168. var lineOffset = lineOffsets[position.line];
  4169. var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
  4170. return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
  4171. };
  4172. Object.defineProperty(FullTextDocument.prototype, "lineCount", {
  4173. get: function () {
  4174. return this.getLineOffsets().length;
  4175. },
  4176. enumerable: true,
  4177. configurable: true
  4178. });
  4179. return FullTextDocument;
  4180. }());
  4181. var Is;
  4182. (function (Is) {
  4183. var toString = Object.prototype.toString;
  4184. function defined(value) {
  4185. return typeof value !== 'undefined';
  4186. }
  4187. Is.defined = defined;
  4188. function undefined(value) {
  4189. return typeof value === 'undefined';
  4190. }
  4191. Is.undefined = undefined;
  4192. function boolean(value) {
  4193. return value === true || value === false;
  4194. }
  4195. Is.boolean = boolean;
  4196. function string(value) {
  4197. return toString.call(value) === '[object String]';
  4198. }
  4199. Is.string = string;
  4200. function number(value) {
  4201. return toString.call(value) === '[object Number]';
  4202. }
  4203. Is.number = number;
  4204. function func(value) {
  4205. return toString.call(value) === '[object Function]';
  4206. }
  4207. Is.func = func;
  4208. function objectLiteral(value) {
  4209. // Strictly speaking class instances pass this check as well. Since the LSP
  4210. // doesn't use classes we ignore this for now. If we do we need to add something
  4211. // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
  4212. return value !== null && typeof value === 'object';
  4213. }
  4214. Is.objectLiteral = objectLiteral;
  4215. function typedArray(value, check) {
  4216. return Array.isArray(value) && value.every(check);
  4217. }
  4218. Is.typedArray = typedArray;
  4219. })(Is || (Is = {}));
  4220. /***/ }),
  4221. /* 19 */
  4222. /***/ (function(module, exports, __webpack_require__) {
  4223. "use strict";
  4224. /* --------------------------------------------------------------------------------------------
  4225. * Copyright (c) Microsoft Corporation. All rights reserved.
  4226. * Licensed under the MIT License. See License.txt in the project root for license information.
  4227. * ------------------------------------------------------------------------------------------ */
  4228. Object.defineProperty(exports, "__esModule", { value: true });
  4229. const Is = __webpack_require__(20);
  4230. const vscode_jsonrpc_1 = __webpack_require__(4);
  4231. const messages_1 = __webpack_require__(21);
  4232. const protocol_implementation_1 = __webpack_require__(22);
  4233. exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
  4234. const protocol_typeDefinition_1 = __webpack_require__(23);
  4235. exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
  4236. const protocol_workspaceFolders_1 = __webpack_require__(24);
  4237. exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
  4238. exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
  4239. const protocol_configuration_1 = __webpack_require__(25);
  4240. exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
  4241. const protocol_colorProvider_1 = __webpack_require__(26);
  4242. exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
  4243. exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
  4244. const protocol_foldingRange_1 = __webpack_require__(27);
  4245. exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
  4246. const protocol_declaration_1 = __webpack_require__(28);
  4247. exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
  4248. const protocol_selectionRange_1 = __webpack_require__(29);
  4249. exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;
  4250. const protocol_progress_1 = __webpack_require__(30);
  4251. exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;
  4252. exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;
  4253. exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;
  4254. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  4255. let __noDynamicImport;
  4256. /**
  4257. * The DocumentFilter namespace provides helper functions to work with
  4258. * [DocumentFilter](#DocumentFilter) literals.
  4259. */
  4260. var DocumentFilter;
  4261. (function (DocumentFilter) {
  4262. function is(value) {
  4263. const candidate = value;
  4264. return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
  4265. }
  4266. DocumentFilter.is = is;
  4267. })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));
  4268. /**
  4269. * The DocumentSelector namespace provides helper functions to work with
  4270. * [DocumentSelector](#DocumentSelector)s.
  4271. */
  4272. var DocumentSelector;
  4273. (function (DocumentSelector) {
  4274. function is(value) {
  4275. if (!Array.isArray(value)) {
  4276. return false;
  4277. }
  4278. for (let elem of value) {
  4279. if (!Is.string(elem) && !DocumentFilter.is(elem)) {
  4280. return false;
  4281. }
  4282. }
  4283. return true;
  4284. }
  4285. DocumentSelector.is = is;
  4286. })(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));
  4287. /**
  4288. * The `client/registerCapability` request is sent from the server to the client to register a new capability
  4289. * handler on the client side.
  4290. */
  4291. var RegistrationRequest;
  4292. (function (RegistrationRequest) {
  4293. RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability');
  4294. })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
  4295. /**
  4296. * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
  4297. * handler on the client side.
  4298. */
  4299. var UnregistrationRequest;
  4300. (function (UnregistrationRequest) {
  4301. UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability');
  4302. })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
  4303. var ResourceOperationKind;
  4304. (function (ResourceOperationKind) {
  4305. /**
  4306. * Supports creating new files and folders.
  4307. */
  4308. ResourceOperationKind.Create = 'create';
  4309. /**
  4310. * Supports renaming existing files and folders.
  4311. */
  4312. ResourceOperationKind.Rename = 'rename';
  4313. /**
  4314. * Supports deleting existing files and folders.
  4315. */
  4316. ResourceOperationKind.Delete = 'delete';
  4317. })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
  4318. var FailureHandlingKind;
  4319. (function (FailureHandlingKind) {
  4320. /**
  4321. * Applying the workspace change is simply aborted if one of the changes provided
  4322. * fails. All operations executed before the failing operation stay executed.
  4323. */
  4324. FailureHandlingKind.Abort = 'abort';
  4325. /**
  4326. * All operations are executed transactional. That means they either all
  4327. * succeed or no changes at all are applied to the workspace.
  4328. */
  4329. FailureHandlingKind.Transactional = 'transactional';
  4330. /**
  4331. * If the workspace edit contains only textual file changes they are executed transactional.
  4332. * If resource changes (create, rename or delete file) are part of the change the failure
  4333. * handling startegy is abort.
  4334. */
  4335. FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
  4336. /**
  4337. * The client tries to undo the operations already executed. But there is no
  4338. * guarantee that this is succeeding.
  4339. */
  4340. FailureHandlingKind.Undo = 'undo';
  4341. })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
  4342. /**
  4343. * The StaticRegistrationOptions namespace provides helper functions to work with
  4344. * [StaticRegistrationOptions](#StaticRegistrationOptions) literals.
  4345. */
  4346. var StaticRegistrationOptions;
  4347. (function (StaticRegistrationOptions) {
  4348. function hasId(value) {
  4349. const candidate = value;
  4350. return candidate && Is.string(candidate.id) && candidate.id.length > 0;
  4351. }
  4352. StaticRegistrationOptions.hasId = hasId;
  4353. })(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));
  4354. /**
  4355. * The TextDocumentRegistrationOptions namespace provides helper functions to work with
  4356. * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals.
  4357. */
  4358. var TextDocumentRegistrationOptions;
  4359. (function (TextDocumentRegistrationOptions) {
  4360. function is(value) {
  4361. const candidate = value;
  4362. return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
  4363. }
  4364. TextDocumentRegistrationOptions.is = is;
  4365. })(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));
  4366. /**
  4367. * The WorkDoneProgressOptions namespace provides helper functions to work with
  4368. * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals.
  4369. */
  4370. var WorkDoneProgressOptions;
  4371. (function (WorkDoneProgressOptions) {
  4372. function is(value) {
  4373. const candidate = value;
  4374. return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));
  4375. }
  4376. WorkDoneProgressOptions.is = is;
  4377. function hasWorkDoneProgress(value) {
  4378. const candidate = value;
  4379. return candidate && Is.boolean(candidate.workDoneProgress);
  4380. }
  4381. WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;
  4382. })(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));
  4383. /**
  4384. * The initialize request is sent from the client to the server.
  4385. * It is sent once as the request after starting up the server.
  4386. * The requests parameter is of type [InitializeParams](#InitializeParams)
  4387. * the response if of type [InitializeResult](#InitializeResult) of a Thenable that
  4388. * resolves to such.
  4389. */
  4390. var InitializeRequest;
  4391. (function (InitializeRequest) {
  4392. InitializeRequest.type = new messages_1.ProtocolRequestType('initialize');
  4393. })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
  4394. /**
  4395. * Known error codes for an `InitializeError`;
  4396. */
  4397. var InitializeError;
  4398. (function (InitializeError) {
  4399. /**
  4400. * If the protocol version provided by the client can't be handled by the server.
  4401. * @deprecated This initialize error got replaced by client capabilities. There is
  4402. * no version handshake in version 3.0x
  4403. */
  4404. InitializeError.unknownProtocolVersion = 1;
  4405. })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));
  4406. /**
  4407. * The intialized notification is sent from the client to the
  4408. * server after the client is fully initialized and the server
  4409. * is allowed to send requests from the server to the client.
  4410. */
  4411. var InitializedNotification;
  4412. (function (InitializedNotification) {
  4413. InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized');
  4414. })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
  4415. //---- Shutdown Method ----
  4416. /**
  4417. * A shutdown request is sent from the client to the server.
  4418. * It is sent once when the client decides to shutdown the
  4419. * server. The only notification that is sent after a shutdown request
  4420. * is the exit event.
  4421. */
  4422. var ShutdownRequest;
  4423. (function (ShutdownRequest) {
  4424. ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown');
  4425. })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
  4426. //---- Exit Notification ----
  4427. /**
  4428. * The exit event is sent from the client to the server to
  4429. * ask the server to exit its process.
  4430. */
  4431. var ExitNotification;
  4432. (function (ExitNotification) {
  4433. ExitNotification.type = new messages_1.ProtocolNotificationType0('exit');
  4434. })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
  4435. /**
  4436. * The configuration change notification is sent from the client to the server
  4437. * when the client's configuration has changed. The notification contains
  4438. * the changed configuration as defined by the language client.
  4439. */
  4440. var DidChangeConfigurationNotification;
  4441. (function (DidChangeConfigurationNotification) {
  4442. DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration');
  4443. })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
  4444. //---- Message show and log notifications ----
  4445. /**
  4446. * The message type
  4447. */
  4448. var MessageType;
  4449. (function (MessageType) {
  4450. /**
  4451. * An error message.
  4452. */
  4453. MessageType.Error = 1;
  4454. /**
  4455. * A warning message.
  4456. */
  4457. MessageType.Warning = 2;
  4458. /**
  4459. * An information message.
  4460. */
  4461. MessageType.Info = 3;
  4462. /**
  4463. * A log message.
  4464. */
  4465. MessageType.Log = 4;
  4466. })(MessageType = exports.MessageType || (exports.MessageType = {}));
  4467. /**
  4468. * The show message notification is sent from a server to a client to ask
  4469. * the client to display a particular message in the user interface.
  4470. */
  4471. var ShowMessageNotification;
  4472. (function (ShowMessageNotification) {
  4473. ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage');
  4474. })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
  4475. /**
  4476. * The show message request is sent from the server to the client to show a message
  4477. * and a set of options actions to the user.
  4478. */
  4479. var ShowMessageRequest;
  4480. (function (ShowMessageRequest) {
  4481. ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest');
  4482. })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
  4483. /**
  4484. * The log message notification is sent from the server to the client to ask
  4485. * the client to log a particular message.
  4486. */
  4487. var LogMessageNotification;
  4488. (function (LogMessageNotification) {
  4489. LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage');
  4490. })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
  4491. //---- Telemetry notification
  4492. /**
  4493. * The telemetry event notification is sent from the server to the client to ask
  4494. * the client to log telemetry data.
  4495. */
  4496. var TelemetryEventNotification;
  4497. (function (TelemetryEventNotification) {
  4498. TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event');
  4499. })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
  4500. /**
  4501. * Defines how the host (editor) should sync
  4502. * document changes to the language server.
  4503. */
  4504. var TextDocumentSyncKind;
  4505. (function (TextDocumentSyncKind) {
  4506. /**
  4507. * Documents should not be synced at all.
  4508. */
  4509. TextDocumentSyncKind.None = 0;
  4510. /**
  4511. * Documents are synced by always sending the full content
  4512. * of the document.
  4513. */
  4514. TextDocumentSyncKind.Full = 1;
  4515. /**
  4516. * Documents are synced by sending the full content on open.
  4517. * After that only incremental updates to the document are
  4518. * send.
  4519. */
  4520. TextDocumentSyncKind.Incremental = 2;
  4521. })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
  4522. /**
  4523. * The document open notification is sent from the client to the server to signal
  4524. * newly opened text documents. The document's truth is now managed by the client
  4525. * and the server must not try to read the document's truth using the document's
  4526. * uri. Open in this sense means it is managed by the client. It doesn't necessarily
  4527. * mean that its content is presented in an editor. An open notification must not
  4528. * be sent more than once without a corresponding close notification send before.
  4529. * This means open and close notification must be balanced and the max open count
  4530. * is one.
  4531. */
  4532. var DidOpenTextDocumentNotification;
  4533. (function (DidOpenTextDocumentNotification) {
  4534. DidOpenTextDocumentNotification.method = 'textDocument/didOpen';
  4535. DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);
  4536. })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
  4537. /**
  4538. * The document change notification is sent from the client to the server to signal
  4539. * changes to a text document.
  4540. */
  4541. var DidChangeTextDocumentNotification;
  4542. (function (DidChangeTextDocumentNotification) {
  4543. DidChangeTextDocumentNotification.method = 'textDocument/didChange';
  4544. DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);
  4545. })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
  4546. /**
  4547. * The document close notification is sent from the client to the server when
  4548. * the document got closed in the client. The document's truth now exists where
  4549. * the document's uri points to (e.g. if the document's uri is a file uri the
  4550. * truth now exists on disk). As with the open notification the close notification
  4551. * is about managing the document's content. Receiving a close notification
  4552. * doesn't mean that the document was open in an editor before. A close
  4553. * notification requires a previous open notification to be sent.
  4554. */
  4555. var DidCloseTextDocumentNotification;
  4556. (function (DidCloseTextDocumentNotification) {
  4557. DidCloseTextDocumentNotification.method = 'textDocument/didClose';
  4558. DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);
  4559. })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
  4560. /**
  4561. * The document save notification is sent from the client to the server when
  4562. * the document got saved in the client.
  4563. */
  4564. var DidSaveTextDocumentNotification;
  4565. (function (DidSaveTextDocumentNotification) {
  4566. DidSaveTextDocumentNotification.method = 'textDocument/didSave';
  4567. DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);
  4568. })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
  4569. /**
  4570. * Represents reasons why a text document is saved.
  4571. */
  4572. var TextDocumentSaveReason;
  4573. (function (TextDocumentSaveReason) {
  4574. /**
  4575. * Manually triggered, e.g. by the user pressing save, by starting debugging,
  4576. * or by an API call.
  4577. */
  4578. TextDocumentSaveReason.Manual = 1;
  4579. /**
  4580. * Automatic after a delay.
  4581. */
  4582. TextDocumentSaveReason.AfterDelay = 2;
  4583. /**
  4584. * When the editor lost focus.
  4585. */
  4586. TextDocumentSaveReason.FocusOut = 3;
  4587. })(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));
  4588. /**
  4589. * A document will save notification is sent from the client to the server before
  4590. * the document is actually saved.
  4591. */
  4592. var WillSaveTextDocumentNotification;
  4593. (function (WillSaveTextDocumentNotification) {
  4594. WillSaveTextDocumentNotification.method = 'textDocument/willSave';
  4595. WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);
  4596. })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
  4597. /**
  4598. * A document will save request is sent from the client to the server before
  4599. * the document is actually saved. The request can return an array of TextEdits
  4600. * which will be applied to the text document before it is saved. Please note that
  4601. * clients might drop results if computing the text edits took too long or if a
  4602. * server constantly fails on this request. This is done to keep the save fast and
  4603. * reliable.
  4604. */
  4605. var WillSaveTextDocumentWaitUntilRequest;
  4606. (function (WillSaveTextDocumentWaitUntilRequest) {
  4607. WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';
  4608. WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);
  4609. })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
  4610. /**
  4611. * The watched files notification is sent from the client to the server when
  4612. * the client detects changes to file watched by the language client.
  4613. */
  4614. var DidChangeWatchedFilesNotification;
  4615. (function (DidChangeWatchedFilesNotification) {
  4616. DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles');
  4617. })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
  4618. /**
  4619. * The file event type
  4620. */
  4621. var FileChangeType;
  4622. (function (FileChangeType) {
  4623. /**
  4624. * The file got created.
  4625. */
  4626. FileChangeType.Created = 1;
  4627. /**
  4628. * The file got changed.
  4629. */
  4630. FileChangeType.Changed = 2;
  4631. /**
  4632. * The file got deleted.
  4633. */
  4634. FileChangeType.Deleted = 3;
  4635. })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
  4636. var WatchKind;
  4637. (function (WatchKind) {
  4638. /**
  4639. * Interested in create events.
  4640. */
  4641. WatchKind.Create = 1;
  4642. /**
  4643. * Interested in change events
  4644. */
  4645. WatchKind.Change = 2;
  4646. /**
  4647. * Interested in delete events
  4648. */
  4649. WatchKind.Delete = 4;
  4650. })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
  4651. /**
  4652. * Diagnostics notification are sent from the server to the client to signal
  4653. * results of validation runs.
  4654. */
  4655. var PublishDiagnosticsNotification;
  4656. (function (PublishDiagnosticsNotification) {
  4657. PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics');
  4658. })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
  4659. /**
  4660. * How a completion was triggered
  4661. */
  4662. var CompletionTriggerKind;
  4663. (function (CompletionTriggerKind) {
  4664. /**
  4665. * Completion was triggered by typing an identifier (24x7 code
  4666. * complete), manual invocation (e.g Ctrl+Space) or via API.
  4667. */
  4668. CompletionTriggerKind.Invoked = 1;
  4669. /**
  4670. * Completion was triggered by a trigger character specified by
  4671. * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
  4672. */
  4673. CompletionTriggerKind.TriggerCharacter = 2;
  4674. /**
  4675. * Completion was re-triggered as current completion list is incomplete
  4676. */
  4677. CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
  4678. })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
  4679. /**
  4680. * Request to request completion at a given text document position. The request's
  4681. * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response
  4682. * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)
  4683. * or a Thenable that resolves to such.
  4684. *
  4685. * The request can delay the computation of the [`detail`](#CompletionItem.detail)
  4686. * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`
  4687. * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
  4688. * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
  4689. */
  4690. var CompletionRequest;
  4691. (function (CompletionRequest) {
  4692. CompletionRequest.method = 'textDocument/completion';
  4693. CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);
  4694. /** @deprecated Use CompletionRequest.type */
  4695. CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  4696. })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
  4697. /**
  4698. * Request to resolve additional information for a given completion item.The request's
  4699. * parameter is of type [CompletionItem](#CompletionItem) the response
  4700. * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.
  4701. */
  4702. var CompletionResolveRequest;
  4703. (function (CompletionResolveRequest) {
  4704. CompletionResolveRequest.method = 'completionItem/resolve';
  4705. CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);
  4706. })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
  4707. /**
  4708. * Request to request hover information at a given text document position. The request's
  4709. * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of
  4710. * type [Hover](#Hover) or a Thenable that resolves to such.
  4711. */
  4712. var HoverRequest;
  4713. (function (HoverRequest) {
  4714. HoverRequest.method = 'textDocument/hover';
  4715. HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);
  4716. })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
  4717. /**
  4718. * How a signature help was triggered.
  4719. *
  4720. * @since 3.15.0
  4721. */
  4722. var SignatureHelpTriggerKind;
  4723. (function (SignatureHelpTriggerKind) {
  4724. /**
  4725. * Signature help was invoked manually by the user or by a command.
  4726. */
  4727. SignatureHelpTriggerKind.Invoked = 1;
  4728. /**
  4729. * Signature help was triggered by a trigger character.
  4730. */
  4731. SignatureHelpTriggerKind.TriggerCharacter = 2;
  4732. /**
  4733. * Signature help was triggered by the cursor moving or by the document content changing.
  4734. */
  4735. SignatureHelpTriggerKind.ContentChange = 3;
  4736. })(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));
  4737. var SignatureHelpRequest;
  4738. (function (SignatureHelpRequest) {
  4739. SignatureHelpRequest.method = 'textDocument/signatureHelp';
  4740. SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);
  4741. })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
  4742. /**
  4743. * A request to resolve the definition location of a symbol at a given text
  4744. * document position. The request's parameter is of type [TextDocumentPosition]
  4745. * (#TextDocumentPosition) the response is of either type [Definition](#Definition)
  4746. * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves
  4747. * to such.
  4748. */
  4749. var DefinitionRequest;
  4750. (function (DefinitionRequest) {
  4751. DefinitionRequest.method = 'textDocument/definition';
  4752. DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);
  4753. /** @deprecated Use DefinitionRequest.type */
  4754. DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  4755. })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
  4756. /**
  4757. * A request to resolve project-wide references for the symbol denoted
  4758. * by the given text document position. The request's parameter is of
  4759. * type [ReferenceParams](#ReferenceParams) the response is of type
  4760. * [Location[]](#Location) or a Thenable that resolves to such.
  4761. */
  4762. var ReferencesRequest;
  4763. (function (ReferencesRequest) {
  4764. ReferencesRequest.method = 'textDocument/references';
  4765. ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);
  4766. /** @deprecated Use ReferencesRequest.type */
  4767. ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  4768. })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
  4769. /**
  4770. * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given
  4771. * text document position. The request's parameter is of type [TextDocumentPosition]
  4772. * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
  4773. * (#DocumentHighlight) or a Thenable that resolves to such.
  4774. */
  4775. var DocumentHighlightRequest;
  4776. (function (DocumentHighlightRequest) {
  4777. DocumentHighlightRequest.method = 'textDocument/documentHighlight';
  4778. DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);
  4779. /** @deprecated Use DocumentHighlightRequest.type */
  4780. DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  4781. })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
  4782. /**
  4783. * A request to list all symbols found in a given text document. The request's
  4784. * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the
  4785. * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable
  4786. * that resolves to such.
  4787. */
  4788. var DocumentSymbolRequest;
  4789. (function (DocumentSymbolRequest) {
  4790. DocumentSymbolRequest.method = 'textDocument/documentSymbol';
  4791. DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);
  4792. /** @deprecated Use DocumentSymbolRequest.type */
  4793. DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  4794. })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
  4795. /**
  4796. * A request to provide commands for the given text document and range.
  4797. */
  4798. var CodeActionRequest;
  4799. (function (CodeActionRequest) {
  4800. CodeActionRequest.method = 'textDocument/codeAction';
  4801. CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);
  4802. /** @deprecated Use CodeActionRequest.type */
  4803. CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  4804. })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
  4805. /**
  4806. * A request to list project-wide symbols matching the query string given
  4807. * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is
  4808. * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that
  4809. * resolves to such.
  4810. */
  4811. var WorkspaceSymbolRequest;
  4812. (function (WorkspaceSymbolRequest) {
  4813. WorkspaceSymbolRequest.method = 'workspace/symbol';
  4814. WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);
  4815. /** @deprecated Use WorkspaceSymbolRequest.type */
  4816. WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  4817. })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
  4818. /**
  4819. * A request to provide code lens for the given text document.
  4820. */
  4821. var CodeLensRequest;
  4822. (function (CodeLensRequest) {
  4823. CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens');
  4824. /** @deprecated Use CodeLensRequest.type */
  4825. CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  4826. })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
  4827. /**
  4828. * A request to resolve a command for a given code lens.
  4829. */
  4830. var CodeLensResolveRequest;
  4831. (function (CodeLensResolveRequest) {
  4832. CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve');
  4833. })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
  4834. /**
  4835. * A request to provide document links
  4836. */
  4837. var DocumentLinkRequest;
  4838. (function (DocumentLinkRequest) {
  4839. DocumentLinkRequest.method = 'textDocument/documentLink';
  4840. DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);
  4841. /** @deprecated Use DocumentLinkRequest.type */
  4842. DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  4843. })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
  4844. /**
  4845. * Request to resolve additional information for a given document link. The request's
  4846. * parameter is of type [DocumentLink](#DocumentLink) the response
  4847. * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.
  4848. */
  4849. var DocumentLinkResolveRequest;
  4850. (function (DocumentLinkResolveRequest) {
  4851. DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve');
  4852. })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
  4853. /**
  4854. * A request to to format a whole document.
  4855. */
  4856. var DocumentFormattingRequest;
  4857. (function (DocumentFormattingRequest) {
  4858. DocumentFormattingRequest.method = 'textDocument/formatting';
  4859. DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);
  4860. })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
  4861. /**
  4862. * A request to to format a range in a document.
  4863. */
  4864. var DocumentRangeFormattingRequest;
  4865. (function (DocumentRangeFormattingRequest) {
  4866. DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';
  4867. DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);
  4868. })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
  4869. /**
  4870. * A request to format a document on type.
  4871. */
  4872. var DocumentOnTypeFormattingRequest;
  4873. (function (DocumentOnTypeFormattingRequest) {
  4874. DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';
  4875. DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);
  4876. })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
  4877. /**
  4878. * A request to rename a symbol.
  4879. */
  4880. var RenameRequest;
  4881. (function (RenameRequest) {
  4882. RenameRequest.method = 'textDocument/rename';
  4883. RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);
  4884. })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
  4885. /**
  4886. * A request to test and perform the setup necessary for a rename.
  4887. */
  4888. var PrepareRenameRequest;
  4889. (function (PrepareRenameRequest) {
  4890. PrepareRenameRequest.method = 'textDocument/prepareRename';
  4891. PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);
  4892. })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
  4893. /**
  4894. * A request send from the client to the server to execute a command. The request might return
  4895. * a workspace edit which the client will apply to the workspace.
  4896. */
  4897. var ExecuteCommandRequest;
  4898. (function (ExecuteCommandRequest) {
  4899. ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand');
  4900. })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
  4901. /**
  4902. * A request sent from the server to the client to modified certain resources.
  4903. */
  4904. var ApplyWorkspaceEditRequest;
  4905. (function (ApplyWorkspaceEditRequest) {
  4906. ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');
  4907. })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
  4908. /***/ }),
  4909. /* 20 */
  4910. /***/ (function(module, exports, __webpack_require__) {
  4911. "use strict";
  4912. /* --------------------------------------------------------------------------------------------
  4913. * Copyright (c) Microsoft Corporation. All rights reserved.
  4914. * Licensed under the MIT License. See License.txt in the project root for license information.
  4915. * ------------------------------------------------------------------------------------------ */
  4916. Object.defineProperty(exports, "__esModule", { value: true });
  4917. function boolean(value) {
  4918. return value === true || value === false;
  4919. }
  4920. exports.boolean = boolean;
  4921. function string(value) {
  4922. return typeof value === 'string' || value instanceof String;
  4923. }
  4924. exports.string = string;
  4925. function number(value) {
  4926. return typeof value === 'number' || value instanceof Number;
  4927. }
  4928. exports.number = number;
  4929. function error(value) {
  4930. return value instanceof Error;
  4931. }
  4932. exports.error = error;
  4933. function func(value) {
  4934. return typeof value === 'function';
  4935. }
  4936. exports.func = func;
  4937. function array(value) {
  4938. return Array.isArray(value);
  4939. }
  4940. exports.array = array;
  4941. function stringArray(value) {
  4942. return array(value) && value.every(elem => string(elem));
  4943. }
  4944. exports.stringArray = stringArray;
  4945. function typedArray(value, check) {
  4946. return Array.isArray(value) && value.every(check);
  4947. }
  4948. exports.typedArray = typedArray;
  4949. function objectLiteral(value) {
  4950. // Strictly speaking class instances pass this check as well. Since the LSP
  4951. // doesn't use classes we ignore this for now. If we do we need to add something
  4952. // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
  4953. return value !== null && typeof value === 'object';
  4954. }
  4955. exports.objectLiteral = objectLiteral;
  4956. /***/ }),
  4957. /* 21 */
  4958. /***/ (function(module, exports, __webpack_require__) {
  4959. "use strict";
  4960. /* --------------------------------------------------------------------------------------------
  4961. * Copyright (c) Microsoft Corporation. All rights reserved.
  4962. * Licensed under the MIT License. See License.txt in the project root for license information.
  4963. * ------------------------------------------------------------------------------------------ */
  4964. Object.defineProperty(exports, "__esModule", { value: true });
  4965. const vscode_jsonrpc_1 = __webpack_require__(4);
  4966. class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
  4967. constructor(method) {
  4968. super(method);
  4969. }
  4970. }
  4971. exports.ProtocolRequestType0 = ProtocolRequestType0;
  4972. class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
  4973. constructor(method) {
  4974. super(method);
  4975. }
  4976. }
  4977. exports.ProtocolRequestType = ProtocolRequestType;
  4978. class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
  4979. constructor(method) {
  4980. super(method);
  4981. }
  4982. }
  4983. exports.ProtocolNotificationType = ProtocolNotificationType;
  4984. class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
  4985. constructor(method) {
  4986. super(method);
  4987. }
  4988. }
  4989. exports.ProtocolNotificationType0 = ProtocolNotificationType0;
  4990. /***/ }),
  4991. /* 22 */
  4992. /***/ (function(module, exports, __webpack_require__) {
  4993. "use strict";
  4994. /* --------------------------------------------------------------------------------------------
  4995. * Copyright (c) Microsoft Corporation. All rights reserved.
  4996. * Licensed under the MIT License. See License.txt in the project root for license information.
  4997. * ------------------------------------------------------------------------------------------ */
  4998. Object.defineProperty(exports, "__esModule", { value: true });
  4999. const vscode_jsonrpc_1 = __webpack_require__(4);
  5000. const messages_1 = __webpack_require__(21);
  5001. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  5002. let __noDynamicImport;
  5003. /**
  5004. * A request to resolve the implementation locations of a symbol at a given text
  5005. * document position. The request's parameter is of type [TextDocumentPositioParams]
  5006. * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
  5007. * Thenable that resolves to such.
  5008. */
  5009. var ImplementationRequest;
  5010. (function (ImplementationRequest) {
  5011. ImplementationRequest.method = 'textDocument/implementation';
  5012. ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);
  5013. /** @deprecated Use ImplementationRequest.type */
  5014. ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5015. })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
  5016. /***/ }),
  5017. /* 23 */
  5018. /***/ (function(module, exports, __webpack_require__) {
  5019. "use strict";
  5020. /* --------------------------------------------------------------------------------------------
  5021. * Copyright (c) Microsoft Corporation. All rights reserved.
  5022. * Licensed under the MIT License. See License.txt in the project root for license information.
  5023. * ------------------------------------------------------------------------------------------ */
  5024. Object.defineProperty(exports, "__esModule", { value: true });
  5025. const vscode_jsonrpc_1 = __webpack_require__(4);
  5026. const messages_1 = __webpack_require__(21);
  5027. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  5028. let __noDynamicImport;
  5029. /**
  5030. * A request to resolve the type definition locations of a symbol at a given text
  5031. * document position. The request's parameter is of type [TextDocumentPositioParams]
  5032. * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
  5033. * Thenable that resolves to such.
  5034. */
  5035. var TypeDefinitionRequest;
  5036. (function (TypeDefinitionRequest) {
  5037. TypeDefinitionRequest.method = 'textDocument/typeDefinition';
  5038. TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);
  5039. /** @deprecated Use TypeDefinitionRequest.type */
  5040. TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5041. })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
  5042. /***/ }),
  5043. /* 24 */
  5044. /***/ (function(module, exports, __webpack_require__) {
  5045. "use strict";
  5046. /* --------------------------------------------------------------------------------------------
  5047. * Copyright (c) Microsoft Corporation. All rights reserved.
  5048. * Licensed under the MIT License. See License.txt in the project root for license information.
  5049. * ------------------------------------------------------------------------------------------ */
  5050. Object.defineProperty(exports, "__esModule", { value: true });
  5051. const messages_1 = __webpack_require__(21);
  5052. /**
  5053. * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
  5054. */
  5055. var WorkspaceFoldersRequest;
  5056. (function (WorkspaceFoldersRequest) {
  5057. WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders');
  5058. })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
  5059. /**
  5060. * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
  5061. * folder configuration changes.
  5062. */
  5063. var DidChangeWorkspaceFoldersNotification;
  5064. (function (DidChangeWorkspaceFoldersNotification) {
  5065. DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders');
  5066. })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
  5067. /***/ }),
  5068. /* 25 */
  5069. /***/ (function(module, exports, __webpack_require__) {
  5070. "use strict";
  5071. /* --------------------------------------------------------------------------------------------
  5072. * Copyright (c) Microsoft Corporation. All rights reserved.
  5073. * Licensed under the MIT License. See License.txt in the project root for license information.
  5074. * ------------------------------------------------------------------------------------------ */
  5075. Object.defineProperty(exports, "__esModule", { value: true });
  5076. const messages_1 = __webpack_require__(21);
  5077. /**
  5078. * The 'workspace/configuration' request is sent from the server to the client to fetch a certain
  5079. * configuration setting.
  5080. *
  5081. * This pull model replaces the old push model were the client signaled configuration change via an
  5082. * event. If the server still needs to react to configuration changes (since the server caches the
  5083. * result of `workspace/configuration` requests) the server should register for an empty configuration
  5084. * change event and empty the cache if such an event is received.
  5085. */
  5086. var ConfigurationRequest;
  5087. (function (ConfigurationRequest) {
  5088. ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration');
  5089. })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
  5090. /***/ }),
  5091. /* 26 */
  5092. /***/ (function(module, exports, __webpack_require__) {
  5093. "use strict";
  5094. /* --------------------------------------------------------------------------------------------
  5095. * Copyright (c) Microsoft Corporation. All rights reserved.
  5096. * Licensed under the MIT License. See License.txt in the project root for license information.
  5097. * ------------------------------------------------------------------------------------------ */
  5098. Object.defineProperty(exports, "__esModule", { value: true });
  5099. const vscode_jsonrpc_1 = __webpack_require__(4);
  5100. const messages_1 = __webpack_require__(21);
  5101. /**
  5102. * A request to list all color symbols found in a given text document. The request's
  5103. * parameter is of type [DocumentColorParams](#DocumentColorParams) the
  5104. * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
  5105. * that resolves to such.
  5106. */
  5107. var DocumentColorRequest;
  5108. (function (DocumentColorRequest) {
  5109. DocumentColorRequest.method = 'textDocument/documentColor';
  5110. DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);
  5111. /** @deprecated Use DocumentColorRequest.type */
  5112. DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5113. })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
  5114. /**
  5115. * A request to list all presentation for a color. The request's
  5116. * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the
  5117. * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
  5118. * that resolves to such.
  5119. */
  5120. var ColorPresentationRequest;
  5121. (function (ColorPresentationRequest) {
  5122. ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation');
  5123. })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
  5124. /***/ }),
  5125. /* 27 */
  5126. /***/ (function(module, exports, __webpack_require__) {
  5127. "use strict";
  5128. /*---------------------------------------------------------------------------------------------
  5129. * Copyright (c) Microsoft Corporation. All rights reserved.
  5130. * Licensed under the MIT License. See License.txt in the project root for license information.
  5131. *--------------------------------------------------------------------------------------------*/
  5132. Object.defineProperty(exports, "__esModule", { value: true });
  5133. const vscode_jsonrpc_1 = __webpack_require__(4);
  5134. const messages_1 = __webpack_require__(21);
  5135. /**
  5136. * Enum of known range kinds
  5137. */
  5138. var FoldingRangeKind;
  5139. (function (FoldingRangeKind) {
  5140. /**
  5141. * Folding range for a comment
  5142. */
  5143. FoldingRangeKind["Comment"] = "comment";
  5144. /**
  5145. * Folding range for a imports or includes
  5146. */
  5147. FoldingRangeKind["Imports"] = "imports";
  5148. /**
  5149. * Folding range for a region (e.g. `#region`)
  5150. */
  5151. FoldingRangeKind["Region"] = "region";
  5152. })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
  5153. /**
  5154. * A request to provide folding ranges in a document. The request's
  5155. * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the
  5156. * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable
  5157. * that resolves to such.
  5158. */
  5159. var FoldingRangeRequest;
  5160. (function (FoldingRangeRequest) {
  5161. FoldingRangeRequest.method = 'textDocument/foldingRange';
  5162. FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);
  5163. /** @deprecated Use FoldingRangeRequest.type */
  5164. FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5165. })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
  5166. /***/ }),
  5167. /* 28 */
  5168. /***/ (function(module, exports, __webpack_require__) {
  5169. "use strict";
  5170. /* --------------------------------------------------------------------------------------------
  5171. * Copyright (c) Microsoft Corporation. All rights reserved.
  5172. * Licensed under the MIT License. See License.txt in the project root for license information.
  5173. * ------------------------------------------------------------------------------------------ */
  5174. Object.defineProperty(exports, "__esModule", { value: true });
  5175. const vscode_jsonrpc_1 = __webpack_require__(4);
  5176. const messages_1 = __webpack_require__(21);
  5177. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  5178. let __noDynamicImport;
  5179. /**
  5180. * A request to resolve the type definition locations of a symbol at a given text
  5181. * document position. The request's parameter is of type [TextDocumentPositioParams]
  5182. * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)
  5183. * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves
  5184. * to such.
  5185. */
  5186. var DeclarationRequest;
  5187. (function (DeclarationRequest) {
  5188. DeclarationRequest.method = 'textDocument/declaration';
  5189. DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);
  5190. /** @deprecated Use DeclarationRequest.type */
  5191. DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5192. })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
  5193. /***/ }),
  5194. /* 29 */
  5195. /***/ (function(module, exports, __webpack_require__) {
  5196. "use strict";
  5197. /*---------------------------------------------------------------------------------------------
  5198. * Copyright (c) Microsoft Corporation. All rights reserved.
  5199. * Licensed under the MIT License. See License.txt in the project root for license information.
  5200. *--------------------------------------------------------------------------------------------*/
  5201. Object.defineProperty(exports, "__esModule", { value: true });
  5202. const vscode_jsonrpc_1 = __webpack_require__(4);
  5203. const messages_1 = __webpack_require__(21);
  5204. /**
  5205. * A request to provide selection ranges in a document. The request's
  5206. * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the
  5207. * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable
  5208. * that resolves to such.
  5209. */
  5210. var SelectionRangeRequest;
  5211. (function (SelectionRangeRequest) {
  5212. SelectionRangeRequest.method = 'textDocument/selectionRange';
  5213. SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);
  5214. /** @deprecated Use SelectionRangeRequest.type */
  5215. SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5216. })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
  5217. /***/ }),
  5218. /* 30 */
  5219. /***/ (function(module, exports, __webpack_require__) {
  5220. "use strict";
  5221. /* --------------------------------------------------------------------------------------------
  5222. * Copyright (c) Microsoft Corporation. All rights reserved.
  5223. * Licensed under the MIT License. See License.txt in the project root for license information.
  5224. * ------------------------------------------------------------------------------------------ */
  5225. Object.defineProperty(exports, "__esModule", { value: true });
  5226. const vscode_jsonrpc_1 = __webpack_require__(4);
  5227. const messages_1 = __webpack_require__(21);
  5228. var WorkDoneProgress;
  5229. (function (WorkDoneProgress) {
  5230. WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();
  5231. })(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));
  5232. /**
  5233. * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
  5234. * reporting from the server.
  5235. */
  5236. var WorkDoneProgressCreateRequest;
  5237. (function (WorkDoneProgressCreateRequest) {
  5238. WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create');
  5239. })(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));
  5240. /**
  5241. * The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress
  5242. * initiated on the server side.
  5243. */
  5244. var WorkDoneProgressCancelNotification;
  5245. (function (WorkDoneProgressCancelNotification) {
  5246. WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel');
  5247. })(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));
  5248. /***/ }),
  5249. /* 31 */
  5250. /***/ (function(module, exports, __webpack_require__) {
  5251. "use strict";
  5252. /* --------------------------------------------------------------------------------------------
  5253. * Copyright (c) TypeFox and others. All rights reserved.
  5254. * Licensed under the MIT License. See License.txt in the project root for license information.
  5255. * ------------------------------------------------------------------------------------------ */
  5256. Object.defineProperty(exports, "__esModule", { value: true });
  5257. const messages_1 = __webpack_require__(21);
  5258. /**
  5259. * A request to result a `CallHierarchyItem` in a document at a given position.
  5260. * Can be used as an input to a incoming or outgoing call hierarchy.
  5261. *
  5262. * @since 3.16.0 - Proposed state
  5263. */
  5264. var CallHierarchyPrepareRequest;
  5265. (function (CallHierarchyPrepareRequest) {
  5266. CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';
  5267. CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);
  5268. })(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));
  5269. /**
  5270. * A request to resolve the incoming calls for a given `CallHierarchyItem`.
  5271. *
  5272. * @since 3.16.0 - Proposed state
  5273. */
  5274. var CallHierarchyIncomingCallsRequest;
  5275. (function (CallHierarchyIncomingCallsRequest) {
  5276. CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';
  5277. CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);
  5278. })(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));
  5279. /**
  5280. * A request to resolve the outgoing calls for a given `CallHierarchyItem`.
  5281. *
  5282. * @since 3.16.0 - Proposed state
  5283. */
  5284. var CallHierarchyOutgoingCallsRequest;
  5285. (function (CallHierarchyOutgoingCallsRequest) {
  5286. CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';
  5287. CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);
  5288. })(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));
  5289. /***/ }),
  5290. /* 32 */
  5291. /***/ (function(module, exports, __webpack_require__) {
  5292. "use strict";
  5293. /* --------------------------------------------------------------------------------------------
  5294. * Copyright (c) Microsoft Corporation. All rights reserved.
  5295. * Licensed under the MIT License. See License.txt in the project root for license information.
  5296. * ------------------------------------------------------------------------------------------ */
  5297. Object.defineProperty(exports, "__esModule", { value: true });
  5298. const messages_1 = __webpack_require__(21);
  5299. /**
  5300. * A set of predefined token types. This set is not fixed
  5301. * an clients can specify additional token types via the
  5302. * corresponding client capabilities.
  5303. *
  5304. * @since 3.16.0 - Proposed state
  5305. */
  5306. var SemanticTokenTypes;
  5307. (function (SemanticTokenTypes) {
  5308. SemanticTokenTypes["comment"] = "comment";
  5309. SemanticTokenTypes["keyword"] = "keyword";
  5310. SemanticTokenTypes["string"] = "string";
  5311. SemanticTokenTypes["number"] = "number";
  5312. SemanticTokenTypes["regexp"] = "regexp";
  5313. SemanticTokenTypes["operator"] = "operator";
  5314. SemanticTokenTypes["namespace"] = "namespace";
  5315. SemanticTokenTypes["type"] = "type";
  5316. SemanticTokenTypes["struct"] = "struct";
  5317. SemanticTokenTypes["class"] = "class";
  5318. SemanticTokenTypes["interface"] = "interface";
  5319. SemanticTokenTypes["enum"] = "enum";
  5320. SemanticTokenTypes["typeParameter"] = "typeParameter";
  5321. SemanticTokenTypes["function"] = "function";
  5322. SemanticTokenTypes["member"] = "member";
  5323. SemanticTokenTypes["property"] = "property";
  5324. SemanticTokenTypes["macro"] = "macro";
  5325. SemanticTokenTypes["variable"] = "variable";
  5326. SemanticTokenTypes["parameter"] = "parameter";
  5327. SemanticTokenTypes["label"] = "label";
  5328. })(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {}));
  5329. /**
  5330. * A set of predefined token modifiers. This set is not fixed
  5331. * an clients can specify additional token types via the
  5332. * corresponding client capabilities.
  5333. *
  5334. * @since 3.16.0 - Proposed state
  5335. */
  5336. var SemanticTokenModifiers;
  5337. (function (SemanticTokenModifiers) {
  5338. SemanticTokenModifiers["documentation"] = "documentation";
  5339. SemanticTokenModifiers["declaration"] = "declaration";
  5340. SemanticTokenModifiers["definition"] = "definition";
  5341. SemanticTokenModifiers["reference"] = "reference";
  5342. SemanticTokenModifiers["static"] = "static";
  5343. SemanticTokenModifiers["abstract"] = "abstract";
  5344. SemanticTokenModifiers["deprecated"] = "deprecated";
  5345. SemanticTokenModifiers["async"] = "async";
  5346. SemanticTokenModifiers["volatile"] = "volatile";
  5347. SemanticTokenModifiers["readonly"] = "readonly";
  5348. })(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {}));
  5349. /**
  5350. * @since 3.16.0 - Proposed state
  5351. */
  5352. var SemanticTokens;
  5353. (function (SemanticTokens) {
  5354. function is(value) {
  5355. const candidate = value;
  5356. return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&
  5357. Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');
  5358. }
  5359. SemanticTokens.is = is;
  5360. })(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {}));
  5361. /**
  5362. * @since 3.16.0 - Proposed state
  5363. */
  5364. var SemanticTokensRequest;
  5365. (function (SemanticTokensRequest) {
  5366. SemanticTokensRequest.method = 'textDocument/semanticTokens';
  5367. SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);
  5368. })(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));
  5369. /**
  5370. * @since 3.16.0 - Proposed state
  5371. */
  5372. var SemanticTokensEditsRequest;
  5373. (function (SemanticTokensEditsRequest) {
  5374. SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits';
  5375. SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method);
  5376. })(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {}));
  5377. /**
  5378. * @since 3.16.0 - Proposed state
  5379. */
  5380. var SemanticTokensRangeRequest;
  5381. (function (SemanticTokensRangeRequest) {
  5382. SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';
  5383. SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);
  5384. })(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));
  5385. /***/ }),
  5386. /* 33 */
  5387. /***/ (function(module, exports, __webpack_require__) {
  5388. "use strict";
  5389. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  5390. if (k2 === undefined) k2 = k;
  5391. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  5392. }) : (function(o, m, k, k2) {
  5393. if (k2 === undefined) k2 = k;
  5394. o[k2] = m[k];
  5395. }));
  5396. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  5397. Object.defineProperty(o, "default", { enumerable: true, value: v });
  5398. }) : function(o, v) {
  5399. o["default"] = v;
  5400. });
  5401. var __importStar = (this && this.__importStar) || function (mod) {
  5402. if (mod && mod.__esModule) return mod;
  5403. var result = {};
  5404. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  5405. __setModuleDefault(result, mod);
  5406. return result;
  5407. };
  5408. var __importDefault = (this && this.__importDefault) || function (mod) {
  5409. return (mod && mod.__esModule) ? mod : { "default": mod };
  5410. };
  5411. Object.defineProperty(exports, "__esModule", { value: true });
  5412. /*---------------------------------------------------------------------------------------------
  5413. * Copyright (c) Microsoft Corporation. All rights reserved.
  5414. * Licensed under the MIT License. See License.txt in the project root for license information.
  5415. *--------------------------------------------------------------------------------------------*/
  5416. const coc_nvim_1 = __webpack_require__(1);
  5417. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  5418. const languageProvider_1 = __importDefault(__webpack_require__(34));
  5419. const PConst = __importStar(__webpack_require__(39));
  5420. const typescriptServiceClient_1 = __importDefault(__webpack_require__(117));
  5421. const typeConverters = __importStar(__webpack_require__(37));
  5422. const typingsStatus_1 = __importStar(__webpack_require__(139));
  5423. // Style check diagnostics that can be reported as warnings
  5424. const styleCheckDiagnostics = [
  5425. 6133,
  5426. 6138,
  5427. 7027,
  5428. 7028,
  5429. 7029,
  5430. 7030 // not all code paths return a value
  5431. ];
  5432. class TypeScriptServiceClientHost {
  5433. constructor(descriptions, pluginManager) {
  5434. this.languages = [];
  5435. this.languagePerId = new Map();
  5436. this.disposables = [];
  5437. this.reportStyleCheckAsWarnings = true;
  5438. let timer;
  5439. const handleProjectChange = () => {
  5440. if (timer)
  5441. clearTimeout(timer);
  5442. timer = setTimeout(() => {
  5443. this.triggerAllDiagnostics();
  5444. }, 1500);
  5445. };
  5446. const configFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/[tj]sconfig.json');
  5447. this.disposables.push(configFileWatcher);
  5448. configFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
  5449. configFileWatcher.onDidDelete(this.reloadProjects, this, this.disposables);
  5450. configFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
  5451. const packageFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/package.json');
  5452. packageFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
  5453. packageFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
  5454. this.client = new typescriptServiceClient_1.default(pluginManager);
  5455. this.disposables.push(this.client);
  5456. this.client.onDiagnosticsReceived(({ kind, resource, diagnostics }) => {
  5457. this.diagnosticsReceived(kind, resource, diagnostics);
  5458. }, null, this.disposables);
  5459. this.client.onConfigDiagnosticsReceived(diag => {
  5460. let { body } = diag;
  5461. if (body) {
  5462. let { configFile, diagnostics } = body;
  5463. let uri = coc_nvim_1.Uri.file(configFile);
  5464. if (diagnostics.length == 0) {
  5465. this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), []);
  5466. }
  5467. else {
  5468. let diagnosticList = diagnostics.map(o => {
  5469. let { text, code, category, start, end } = o;
  5470. let range;
  5471. if (!start || !end) {
  5472. range = vscode_languageserver_protocol_1.Range.create(vscode_languageserver_protocol_1.Position.create(0, 0), vscode_languageserver_protocol_1.Position.create(0, 1));
  5473. }
  5474. else {
  5475. range = vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1);
  5476. }
  5477. let severity = category == 'error' ? vscode_languageserver_protocol_1.DiagnosticSeverity.Error : vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
  5478. return vscode_languageserver_protocol_1.Diagnostic.create(range, text, severity, code);
  5479. });
  5480. this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), diagnosticList);
  5481. }
  5482. }
  5483. }, null, this.disposables);
  5484. this.typingsStatus = new typingsStatus_1.default(this.client);
  5485. this.ataProgressReporter = new typingsStatus_1.AtaProgressReporter(this.client);
  5486. for (const description of descriptions) { // tslint:disable-line
  5487. const manager = new languageProvider_1.default(this.client, description, this.typingsStatus);
  5488. this.languages.push(manager);
  5489. this.disposables.push(manager);
  5490. this.languagePerId.set(description.id, manager);
  5491. }
  5492. this.client.ensureServiceStarted();
  5493. this.client.onTsServerStarted(() => {
  5494. this.triggerAllDiagnostics();
  5495. });
  5496. coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
  5497. this.configurationChanged();
  5498. }
  5499. dispose() {
  5500. coc_nvim_1.disposeAll(this.disposables);
  5501. this.typingsStatus.dispose();
  5502. this.ataProgressReporter.dispose();
  5503. }
  5504. reset() {
  5505. for (let lang of this.languages) {
  5506. lang.fileConfigurationManager.reset();
  5507. }
  5508. }
  5509. get serviceClient() {
  5510. return this.client;
  5511. }
  5512. reloadProjects() {
  5513. this.client.execute('reloadProjects', null, vscode_languageserver_protocol_1.CancellationToken.None);
  5514. this.triggerAllDiagnostics();
  5515. }
  5516. // typescript or javascript
  5517. getProvider(languageId) {
  5518. return this.languagePerId.get(languageId);
  5519. }
  5520. configurationChanged() {
  5521. const config = coc_nvim_1.workspace.getConfiguration('tsserver');
  5522. this.reportStyleCheckAsWarnings = config.get('reportStyleChecksAsWarnings', true);
  5523. }
  5524. findLanguage(resource) {
  5525. try {
  5526. return this.languages.find(language => language.handles(resource));
  5527. }
  5528. catch (_a) {
  5529. return null;
  5530. }
  5531. }
  5532. handles(uri) {
  5533. return this.findLanguage(coc_nvim_1.Uri.parse(uri)) != null;
  5534. }
  5535. triggerAllDiagnostics() {
  5536. for (const language of this.languagePerId.values()) {
  5537. language.triggerAllDiagnostics();
  5538. }
  5539. }
  5540. diagnosticsReceived(kind, resource, diagnostics) {
  5541. const language = this.findLanguage(resource);
  5542. if (language) {
  5543. language.diagnosticsReceived(kind, resource, this.createMarkerDatas(diagnostics));
  5544. }
  5545. }
  5546. createMarkerDatas(diagnostics) {
  5547. return diagnostics.map(tsDiag => this.tsDiagnosticToLspDiagnostic(tsDiag));
  5548. }
  5549. tsDiagnosticToLspDiagnostic(diagnostic) {
  5550. const { start, end, text } = diagnostic;
  5551. const range = {
  5552. start: typeConverters.Position.fromLocation(start),
  5553. end: typeConverters.Position.fromLocation(end)
  5554. };
  5555. let relatedInformation;
  5556. if (diagnostic.relatedInformation) {
  5557. relatedInformation = diagnostic.relatedInformation.map(o => {
  5558. let { span, message } = o;
  5559. return {
  5560. location: typeConverters.Location.fromTextSpan(this.client.toResource(span.file), span),
  5561. message
  5562. };
  5563. });
  5564. }
  5565. return {
  5566. range,
  5567. message: text,
  5568. code: diagnostic.code ? diagnostic.code : null,
  5569. severity: this.getDiagnosticSeverity(diagnostic),
  5570. reportUnnecessary: diagnostic.reportsUnnecessary,
  5571. source: diagnostic.source || 'tsserver',
  5572. relatedInformation
  5573. };
  5574. }
  5575. getDiagnosticSeverity(diagnostic) {
  5576. if (this.reportStyleCheckAsWarnings &&
  5577. this.isStyleCheckDiagnostic(diagnostic.code) &&
  5578. diagnostic.category === PConst.DiagnosticCategory.error) {
  5579. return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
  5580. }
  5581. switch (diagnostic.category) {
  5582. case PConst.DiagnosticCategory.error:
  5583. return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
  5584. case PConst.DiagnosticCategory.warning:
  5585. return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
  5586. case PConst.DiagnosticCategory.suggestion:
  5587. return vscode_languageserver_protocol_1.DiagnosticSeverity.Information;
  5588. default:
  5589. return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
  5590. }
  5591. }
  5592. isStyleCheckDiagnostic(code) {
  5593. return code ? styleCheckDiagnostics.indexOf(code) !== -1 : false;
  5594. }
  5595. }
  5596. exports.default = TypeScriptServiceClientHost;
  5597. /***/ }),
  5598. /* 34 */
  5599. /***/ (function(module, exports, __webpack_require__) {
  5600. "use strict";
  5601. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  5602. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  5603. return new (P || (P = Promise))(function (resolve, reject) {
  5604. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5605. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  5606. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  5607. step((generator = generator.apply(thisArg, _arguments || [])).next());
  5608. });
  5609. };
  5610. var __importDefault = (this && this.__importDefault) || function (mod) {
  5611. return (mod && mod.__esModule) ? mod : { "default": mod };
  5612. };
  5613. Object.defineProperty(exports, "__esModule", { value: true });
  5614. /*---------------------------------------------------------------------------------------------
  5615. * Copyright (c) Microsoft Corporation. All rights reserved.
  5616. * Licensed under the MIT License. See License.txt in the project root for license information.
  5617. *--------------------------------------------------------------------------------------------*/
  5618. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  5619. const coc_nvim_1 = __webpack_require__(1);
  5620. const baseCodeLensProvider_1 = __webpack_require__(35);
  5621. const completionItemProvider_1 = __importDefault(__webpack_require__(38));
  5622. const definitionProvider_1 = __importDefault(__webpack_require__(88));
  5623. const directiveCommentCompletions_1 = __importDefault(__webpack_require__(89));
  5624. const documentHighlight_1 = __importDefault(__webpack_require__(90));
  5625. const documentSymbol_1 = __importDefault(__webpack_require__(92));
  5626. const fileConfigurationManager_1 = __importDefault(__webpack_require__(93));
  5627. const folding_1 = __importDefault(__webpack_require__(94));
  5628. const formatting_1 = __importDefault(__webpack_require__(95));
  5629. const hover_1 = __importDefault(__webpack_require__(96));
  5630. const implementationsCodeLens_1 = __importDefault(__webpack_require__(97));
  5631. // import TagCompletionProvider from './features/tagCompletion'
  5632. const quickfix_1 = __importDefault(__webpack_require__(98));
  5633. const importFix_1 = __importDefault(__webpack_require__(99));
  5634. const refactor_1 = __importDefault(__webpack_require__(101));
  5635. const references_1 = __importDefault(__webpack_require__(102));
  5636. const referencesCodeLens_1 = __importDefault(__webpack_require__(103));
  5637. const rename_1 = __importDefault(__webpack_require__(104));
  5638. const signatureHelp_1 = __importDefault(__webpack_require__(105));
  5639. const updatePathOnRename_1 = __importDefault(__webpack_require__(106));
  5640. const watchBuild_1 = __importDefault(__webpack_require__(108));
  5641. const workspaceSymbols_1 = __importDefault(__webpack_require__(109));
  5642. const smartSelect_1 = __importDefault(__webpack_require__(110));
  5643. const moduleInstall_1 = __importDefault(__webpack_require__(111));
  5644. const api_1 = __importDefault(__webpack_require__(40));
  5645. const organizeImports_1 = __webpack_require__(114);
  5646. const suggestionSetting = 'suggestionActions.enabled';
  5647. class LanguageProvider {
  5648. constructor(client, description, typingsStatus) {
  5649. this.client = client;
  5650. this.description = description;
  5651. this.disposables = [];
  5652. this.fileConfigurationManager = new fileConfigurationManager_1.default(client);
  5653. coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
  5654. this.configurationChanged();
  5655. let initialized = false;
  5656. client.onTsServerStarted(() => __awaiter(this, void 0, void 0, function* () {
  5657. if (!initialized) {
  5658. initialized = true;
  5659. this.registerProviders(client, typingsStatus);
  5660. }
  5661. else {
  5662. this.client.diagnosticsManager.reInitialize();
  5663. }
  5664. }));
  5665. }
  5666. configurationChanged() {
  5667. const config = coc_nvim_1.workspace.getConfiguration(this.id, null);
  5668. this.client.diagnosticsManager.setEnableSuggestions(this.id, config.get(suggestionSetting, true));
  5669. }
  5670. dispose() {
  5671. coc_nvim_1.disposeAll(this.disposables);
  5672. }
  5673. registerProviders(client, typingsStatus) {
  5674. let languageIds = this.description.modeIds;
  5675. this.disposables.push(coc_nvim_1.languages.registerCompletionItemProvider(`tsserver-${this.description.id}`, 'TSC', languageIds, new completionItemProvider_1.default(client, typingsStatus, this.fileConfigurationManager, this.description.id), completionItemProvider_1.default.triggerCharacters));
  5676. if (this.client.apiVersion.gte(api_1.default.v230)) {
  5677. this.disposables.push(coc_nvim_1.languages.registerCompletionItemProvider(`${this.description.id}-directive`, 'TSC', languageIds, new directiveCommentCompletions_1.default(client), ['@']));
  5678. }
  5679. let definitionProvider = new definitionProvider_1.default(client);
  5680. this.disposables.push(coc_nvim_1.languages.registerDefinitionProvider(languageIds, definitionProvider));
  5681. this.disposables.push(coc_nvim_1.languages.registerTypeDefinitionProvider(languageIds, definitionProvider));
  5682. this.disposables.push(coc_nvim_1.languages.registerImplementationProvider(languageIds, definitionProvider));
  5683. this.disposables.push(coc_nvim_1.languages.registerReferencesProvider(languageIds, new references_1.default(client)));
  5684. this.disposables.push(coc_nvim_1.languages.registerHoverProvider(languageIds, new hover_1.default(client)));
  5685. this.disposables.push(coc_nvim_1.languages.registerDocumentHighlightProvider(languageIds, new documentHighlight_1.default(this.client)));
  5686. this.disposables.push(coc_nvim_1.languages.registerSignatureHelpProvider(languageIds, new signatureHelp_1.default(client), ['(', ',', '<', ')']));
  5687. this.disposables.push(coc_nvim_1.languages.registerDocumentSymbolProvider(languageIds, new documentSymbol_1.default(client)));
  5688. this.disposables.push(coc_nvim_1.languages.registerWorkspaceSymbolProvider(languageIds, new workspaceSymbols_1.default(client, languageIds)));
  5689. this.disposables.push(coc_nvim_1.languages.registerRenameProvider(languageIds, new rename_1.default(client)));
  5690. let formatProvider = new formatting_1.default(client, this.fileConfigurationManager);
  5691. this.disposables.push(coc_nvim_1.languages.registerDocumentFormatProvider(languageIds, formatProvider));
  5692. this.disposables.push(coc_nvim_1.languages.registerDocumentRangeFormatProvider(languageIds, formatProvider));
  5693. this.disposables.push(coc_nvim_1.languages.registerOnTypeFormattingEditProvider(languageIds, formatProvider, [';', '}', '\n', String.fromCharCode(27)]));
  5694. // this.disposables.push(
  5695. // new ProjectError(client, commandManager)
  5696. // )
  5697. if (this.client.apiVersion.gte(api_1.default.v280)) {
  5698. this.disposables.push(coc_nvim_1.languages.registerFoldingRangeProvider(languageIds, new folding_1.default(this.client)));
  5699. this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new organizeImports_1.OrganizeImportsCodeActionProvider(this.client, this.fileConfigurationManager), `tsserver-${this.description.id}`, [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]));
  5700. }
  5701. let { fileConfigurationManager } = this;
  5702. let conf = fileConfigurationManager.getLanguageConfiguration(this.id);
  5703. if (this.client.apiVersion.gte(api_1.default.v290)
  5704. && conf.get('updateImportsOnFileMove.enable')) {
  5705. this.disposables.push(new updatePathOnRename_1.default(client, this.fileConfigurationManager, this.id));
  5706. }
  5707. if (this.client.apiVersion.gte(api_1.default.v240)) {
  5708. this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new refactor_1.default(client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.Refactor]));
  5709. }
  5710. this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new moduleInstall_1.default(client), 'tsserver'));
  5711. this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new quickfix_1.default(client), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
  5712. this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new importFix_1.default(this.client.bufferSyncSupport), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
  5713. let cachedResponse = new baseCodeLensProvider_1.CachedNavTreeResponse();
  5714. if (this.client.apiVersion.gte(api_1.default.v206)
  5715. && conf.get('referencesCodeLens.enable')) {
  5716. this.disposables.push(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new referencesCodeLens_1.default(client, cachedResponse)));
  5717. }
  5718. if (this.client.apiVersion.gte(api_1.default.v220)
  5719. && conf.get('implementationsCodeLens.enable')) {
  5720. this.disposables.push(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new implementationsCodeLens_1.default(client, cachedResponse)));
  5721. }
  5722. if (this.client.apiVersion.gte(api_1.default.v350)) {
  5723. this.disposables.push(coc_nvim_1.languages.registerSelectionRangeProvider(languageIds, new smartSelect_1.default(this.client)));
  5724. }
  5725. if (this.description.id == 'typescript') {
  5726. // this.client.apiVersion
  5727. this.disposables.push(new watchBuild_1.default(coc_nvim_1.commands, this.client));
  5728. }
  5729. // if (this.client.apiVersion.gte(API.v300)) {
  5730. // this.disposables.push(
  5731. // languages.registerCompletionItemProvider(
  5732. // `tsserver-${this.description.id}-tag`,
  5733. // 'TSC',
  5734. // languageIds,
  5735. // new TagCompletionProvider(client),
  5736. // ['>']
  5737. // )
  5738. // )
  5739. // }
  5740. }
  5741. handles(resource) {
  5742. let { modeIds, configFile } = this.description;
  5743. if (resource.toString().endsWith(configFile)) {
  5744. return true;
  5745. }
  5746. let doc = coc_nvim_1.workspace.getDocument(resource.toString());
  5747. if (doc && modeIds.indexOf(doc.filetype) !== -1) {
  5748. return true;
  5749. }
  5750. let str = resource.toString();
  5751. if (this.id === 'typescript' && /\.ts(x)?$/.test(str)) {
  5752. return true;
  5753. }
  5754. if (this.id === 'javascript' && /\.js(x)?$/.test(str)) {
  5755. return true;
  5756. }
  5757. return false;
  5758. }
  5759. get id() {
  5760. return this.description.id;
  5761. }
  5762. get diagnosticSource() {
  5763. return this.description.diagnosticSource;
  5764. }
  5765. triggerAllDiagnostics() {
  5766. this.client.bufferSyncSupport.requestAllDiagnostics();
  5767. }
  5768. diagnosticsReceived(diagnosticsKind, file, diagnostics) {
  5769. if (!this.client.bufferSyncSupport.shouldValidate(file.toString())) {
  5770. return;
  5771. }
  5772. const config = coc_nvim_1.workspace.getConfiguration(this.id, file.toString());
  5773. const reportUnnecessary = config.get('showUnused', true);
  5774. this.client.diagnosticsManager.diagnosticsReceived(diagnosticsKind, file.toString(), diagnostics.filter(diag => {
  5775. if (!reportUnnecessary) {
  5776. diag.tags = undefined;
  5777. if (diag.reportUnnecessary && diag.severity === vscode_languageserver_protocol_1.DiagnosticSeverity.Information) {
  5778. return false;
  5779. }
  5780. }
  5781. return true;
  5782. }));
  5783. }
  5784. }
  5785. exports.default = LanguageProvider;
  5786. /***/ }),
  5787. /* 35 */
  5788. /***/ (function(module, exports, __webpack_require__) {
  5789. "use strict";
  5790. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  5791. if (k2 === undefined) k2 = k;
  5792. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  5793. }) : (function(o, m, k, k2) {
  5794. if (k2 === undefined) k2 = k;
  5795. o[k2] = m[k];
  5796. }));
  5797. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  5798. Object.defineProperty(o, "default", { enumerable: true, value: v });
  5799. }) : function(o, v) {
  5800. o["default"] = v;
  5801. });
  5802. var __importStar = (this && this.__importStar) || function (mod) {
  5803. if (mod && mod.__esModule) return mod;
  5804. var result = {};
  5805. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  5806. __setModuleDefault(result, mod);
  5807. return result;
  5808. };
  5809. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  5810. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  5811. return new (P || (P = Promise))(function (resolve, reject) {
  5812. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5813. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  5814. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  5815. step((generator = generator.apply(thisArg, _arguments || [])).next());
  5816. });
  5817. };
  5818. Object.defineProperty(exports, "__esModule", { value: true });
  5819. exports.TypeScriptBaseCodeLensProvider = exports.CachedNavTreeResponse = void 0;
  5820. /*---------------------------------------------------------------------------------------------
  5821. * Copyright (c) Microsoft Corporation. All rights reserved.
  5822. * Licensed under the MIT License. See License.txt in the project root for license information.
  5823. *--------------------------------------------------------------------------------------------*/
  5824. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  5825. const regexp_1 = __webpack_require__(36);
  5826. const typeConverters = __importStar(__webpack_require__(37));
  5827. class CachedNavTreeResponse {
  5828. constructor() {
  5829. this.version = -1;
  5830. this.document = '';
  5831. }
  5832. execute(document, f) {
  5833. if (this.matches(document)) {
  5834. return this.response;
  5835. }
  5836. return this.update(document, f());
  5837. }
  5838. matches(document) {
  5839. return (this.version === document.version &&
  5840. this.document === document.uri.toString());
  5841. }
  5842. update(document, response) {
  5843. this.response = response;
  5844. this.version = document.version;
  5845. this.document = document.uri.toString();
  5846. return response;
  5847. }
  5848. }
  5849. exports.CachedNavTreeResponse = CachedNavTreeResponse;
  5850. class TypeScriptBaseCodeLensProvider {
  5851. constructor(client, cachedResponse) {
  5852. this.client = client;
  5853. this.cachedResponse = cachedResponse;
  5854. this.onDidChangeCodeLensesEmitter = new vscode_languageserver_protocol_1.Emitter();
  5855. }
  5856. get onDidChangeCodeLenses() {
  5857. return this.onDidChangeCodeLensesEmitter.event;
  5858. }
  5859. provideCodeLenses(document, token) {
  5860. return __awaiter(this, void 0, void 0, function* () {
  5861. const filepath = this.client.toPath(document.uri);
  5862. if (!filepath) {
  5863. return [];
  5864. }
  5865. try {
  5866. const response = yield this.cachedResponse.execute(document, () => this.client.execute('navtree', { file: filepath }, token));
  5867. if (!response) {
  5868. return [];
  5869. }
  5870. const tree = response.body;
  5871. const referenceableSpans = [];
  5872. if (tree && tree.childItems) {
  5873. tree.childItems.forEach(item => this.walkNavTree(document, item, null, referenceableSpans));
  5874. }
  5875. return referenceableSpans.map(range => {
  5876. return {
  5877. range,
  5878. data: { uri: document.uri }
  5879. };
  5880. });
  5881. }
  5882. catch (_a) {
  5883. return [];
  5884. }
  5885. });
  5886. }
  5887. walkNavTree(document, item, parent, results) {
  5888. if (!item) {
  5889. return;
  5890. }
  5891. const range = this.extractSymbol(document, item, parent);
  5892. if (range) {
  5893. results.push(range);
  5894. }
  5895. if (item.childItems) {
  5896. item.childItems.forEach(child => this.walkNavTree(document, child, item, results));
  5897. }
  5898. }
  5899. getSymbolRange(document, item) {
  5900. if (!item) {
  5901. return null;
  5902. }
  5903. // TS 3.0+ provides a span for just the symbol
  5904. if (item.nameSpan) {
  5905. return typeConverters.Range.fromTextSpan(item.nameSpan);
  5906. }
  5907. // In older versions, we have to calculate this manually. See #23924
  5908. const span = item.spans && item.spans[0];
  5909. if (!span) {
  5910. return null;
  5911. }
  5912. const range = typeConverters.Range.fromTextSpan(span);
  5913. const text = document.getText(range);
  5914. const identifierMatch = new RegExp(`^(.*?(\\b|\\W))${regexp_1.escapeRegExp(item.text || '')}(\\b|\\W)`, 'gm');
  5915. const match = identifierMatch.exec(text);
  5916. const prefixLength = match ? match.index + match[1].length : 0;
  5917. const startOffset = document.offsetAt(range.start) + prefixLength;
  5918. return {
  5919. start: document.positionAt(startOffset),
  5920. end: document.positionAt(startOffset + item.text.length)
  5921. };
  5922. }
  5923. }
  5924. exports.TypeScriptBaseCodeLensProvider = TypeScriptBaseCodeLensProvider;
  5925. /***/ }),
  5926. /* 36 */
  5927. /***/ (function(module, exports, __webpack_require__) {
  5928. "use strict";
  5929. /*---------------------------------------------------------------------------------------------
  5930. * Copyright (c) Microsoft Corporation. All rights reserved.
  5931. * Licensed under the MIT License. See License.txt in the project root for license information.
  5932. *--------------------------------------------------------------------------------------------*/
  5933. Object.defineProperty(exports, "__esModule", { value: true });
  5934. exports.escapeRegExp = void 0;
  5935. function escapeRegExp(text) {
  5936. return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  5937. }
  5938. exports.escapeRegExp = escapeRegExp;
  5939. /***/ }),
  5940. /* 37 */
  5941. /***/ (function(module, exports, __webpack_require__) {
  5942. "use strict";
  5943. Object.defineProperty(exports, "__esModule", { value: true });
  5944. exports.WorkspaceEdit = exports.TextEdit = exports.Location = exports.Position = exports.Range = void 0;
  5945. var Range;
  5946. (function (Range) {
  5947. Range.fromTextSpan = (span) => {
  5948. return {
  5949. start: {
  5950. line: span.start.line - 1,
  5951. character: span.start.offset - 1
  5952. },
  5953. end: {
  5954. line: span.end.line - 1,
  5955. character: span.end.offset - 1
  5956. }
  5957. };
  5958. };
  5959. Range.toFormattingRequestArgs = (file, range) => ({
  5960. file,
  5961. line: range.start.line + 1,
  5962. offset: range.start.character + 1,
  5963. endLine: range.end.line + 1,
  5964. endOffset: range.end.character + 1
  5965. });
  5966. Range.toFileRangeRequestArgs = (file, range) => ({
  5967. file,
  5968. startLine: range.start.line + 1,
  5969. startOffset: range.start.character + 1,
  5970. endLine: range.end.line + 1,
  5971. endOffset: range.end.character + 1
  5972. });
  5973. })(Range = exports.Range || (exports.Range = {}));
  5974. var Position;
  5975. (function (Position) {
  5976. Position.fromLocation = (tslocation) => {
  5977. return {
  5978. line: tslocation.line - 1,
  5979. character: tslocation.offset - 1
  5980. };
  5981. };
  5982. Position.toLocation = (position) => ({
  5983. line: position.line + 1,
  5984. offset: position.character + 1,
  5985. });
  5986. Position.toFileLocationRequestArgs = (file, position) => ({
  5987. file,
  5988. line: position.line + 1,
  5989. offset: position.character + 1
  5990. });
  5991. })(Position = exports.Position || (exports.Position = {}));
  5992. var Location;
  5993. (function (Location) {
  5994. Location.fromTextSpan = (uri, tsTextSpan) => {
  5995. return {
  5996. uri,
  5997. range: Range.fromTextSpan(tsTextSpan)
  5998. };
  5999. };
  6000. })(Location = exports.Location || (exports.Location = {}));
  6001. var TextEdit;
  6002. (function (TextEdit) {
  6003. TextEdit.fromCodeEdit = (edit) => {
  6004. return {
  6005. range: Range.fromTextSpan(edit),
  6006. newText: edit.newText
  6007. };
  6008. };
  6009. })(TextEdit = exports.TextEdit || (exports.TextEdit = {}));
  6010. var WorkspaceEdit;
  6011. (function (WorkspaceEdit) {
  6012. function fromFileCodeEdits(client, edits) {
  6013. let changes = {};
  6014. for (const edit of edits) {
  6015. let uri = client.toResource(edit.fileName);
  6016. changes[uri] = edit.textChanges.map(change => {
  6017. return TextEdit.fromCodeEdit(change);
  6018. });
  6019. }
  6020. return { changes };
  6021. }
  6022. WorkspaceEdit.fromFileCodeEdits = fromFileCodeEdits;
  6023. })(WorkspaceEdit = exports.WorkspaceEdit || (exports.WorkspaceEdit = {}));
  6024. /***/ }),
  6025. /* 38 */
  6026. /***/ (function(module, exports, __webpack_require__) {
  6027. "use strict";
  6028. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  6029. if (k2 === undefined) k2 = k;
  6030. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  6031. }) : (function(o, m, k, k2) {
  6032. if (k2 === undefined) k2 = k;
  6033. o[k2] = m[k];
  6034. }));
  6035. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  6036. Object.defineProperty(o, "default", { enumerable: true, value: v });
  6037. }) : function(o, v) {
  6038. o["default"] = v;
  6039. });
  6040. var __importStar = (this && this.__importStar) || function (mod) {
  6041. if (mod && mod.__esModule) return mod;
  6042. var result = {};
  6043. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  6044. __setModuleDefault(result, mod);
  6045. return result;
  6046. };
  6047. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  6048. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  6049. return new (P || (P = Promise))(function (resolve, reject) {
  6050. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6051. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  6052. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  6053. step((generator = generator.apply(thisArg, _arguments || [])).next());
  6054. });
  6055. };
  6056. var __importDefault = (this && this.__importDefault) || function (mod) {
  6057. return (mod && mod.__esModule) ? mod : { "default": mod };
  6058. };
  6059. Object.defineProperty(exports, "__esModule", { value: true });
  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. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  6065. const coc_nvim_1 = __webpack_require__(1);
  6066. const PConst = __importStar(__webpack_require__(39));
  6067. const api_1 = __importDefault(__webpack_require__(40));
  6068. const codeAction_1 = __webpack_require__(84);
  6069. const completionItem_1 = __webpack_require__(85);
  6070. const Previewer = __importStar(__webpack_require__(86));
  6071. const typeConverters = __importStar(__webpack_require__(37));
  6072. const SnippetString_1 = __importDefault(__webpack_require__(87));
  6073. class ApplyCompletionCodeActionCommand {
  6074. constructor(client) {
  6075. this.client = client;
  6076. this.id = ApplyCompletionCodeActionCommand.ID;
  6077. }
  6078. // apply code action on complete
  6079. execute(codeActions) {
  6080. return __awaiter(this, void 0, void 0, function* () {
  6081. if (codeActions.length === 0) {
  6082. return;
  6083. }
  6084. if (codeActions.length === 1) {
  6085. yield codeAction_1.applyCodeAction(this.client, codeActions[0]);
  6086. return;
  6087. }
  6088. const idx = yield coc_nvim_1.workspace.showQuickpick(codeActions.map(o => o.description), 'Select code action to apply');
  6089. if (idx < 0)
  6090. return;
  6091. const action = codeActions[idx];
  6092. yield codeAction_1.applyCodeAction(this.client, action);
  6093. return;
  6094. });
  6095. }
  6096. }
  6097. ApplyCompletionCodeActionCommand.ID = '_typescript.applyCompletionCodeAction';
  6098. class TypeScriptCompletionItemProvider {
  6099. constructor(client, typingsStatus, fileConfigurationManager, languageId) {
  6100. this.client = client;
  6101. this.typingsStatus = typingsStatus;
  6102. this.fileConfigurationManager = fileConfigurationManager;
  6103. this.setCompleteOption(languageId);
  6104. coc_nvim_1.commands.register(new ApplyCompletionCodeActionCommand(this.client));
  6105. coc_nvim_1.workspace.onDidChangeConfiguration(_e => {
  6106. this.setCompleteOption(languageId);
  6107. });
  6108. }
  6109. setCompleteOption(languageId) {
  6110. this.completeOption = this.fileConfigurationManager.getCompleteOptions(languageId);
  6111. }
  6112. /**
  6113. * Get completionItems
  6114. *
  6115. * @public
  6116. * @param {TextDocument} document
  6117. * @param {Position} position
  6118. * @param {CancellationToken} token
  6119. * @param {string} triggerCharacter
  6120. * @returns {Promise<CompletionItem[]>}
  6121. */
  6122. provideCompletionItems(document, position, token, context) {
  6123. return __awaiter(this, void 0, void 0, function* () {
  6124. if (this.typingsStatus.isAcquiringTypings) {
  6125. return Promise.resolve({
  6126. isIncomplete: true,
  6127. items: [{
  6128. label: 'Acquiring typings...',
  6129. detail: 'Acquiring typings definitions for IntelliSense.'
  6130. }]
  6131. });
  6132. }
  6133. let { uri } = document;
  6134. const file = this.client.toPath(document.uri);
  6135. if (!file)
  6136. return null;
  6137. let preText = document.getText({
  6138. start: { line: position.line, character: 0 },
  6139. end: position
  6140. });
  6141. let { triggerCharacter, option } = context;
  6142. if (!this.shouldTrigger(triggerCharacter, preText, option)) {
  6143. return null;
  6144. }
  6145. const { completeOption } = this;
  6146. const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { includeExternalModuleExports: completeOption.autoImports, includeInsertTextCompletions: true, triggerCharacter: this.getTsTriggerCharacter(context), includeAutomaticOptionalChainCompletions: completeOption.includeAutomaticOptionalChainCompletions });
  6147. let entries;
  6148. let dotAccessorContext;
  6149. let isNewIdentifierLocation = true;
  6150. let isMemberCompletion = false;
  6151. let isIncomplete = false;
  6152. const isInValidCommitCharacterContext = this.isInValidCommitCharacterContext(document, position);
  6153. if (this.client.apiVersion.gte(api_1.default.v300)) {
  6154. try {
  6155. const response = yield this.client.interruptGetErr(() => this.client.execute('completionInfo', args, token));
  6156. if (response.type !== 'response' || !response.body) {
  6157. return null;
  6158. }
  6159. isNewIdentifierLocation = response.body.isNewIdentifierLocation;
  6160. isMemberCompletion = response.body.isMemberCompletion;
  6161. if (isMemberCompletion) {
  6162. const dotMatch = preText.slice(0, position.character).match(/\??\.\s*$/) || undefined;
  6163. if (dotMatch) {
  6164. const range = vscode_languageserver_protocol_1.Range.create({
  6165. line: position.line,
  6166. character: position.character - dotMatch.length
  6167. }, position);
  6168. const text = document.getText(range);
  6169. dotAccessorContext = { range, text };
  6170. }
  6171. }
  6172. isIncomplete = response.metadata && response.metadata.isIncomplete;
  6173. entries = response.body.entries;
  6174. }
  6175. catch (e) {
  6176. if (e.message == 'No content available.') {
  6177. return null;
  6178. }
  6179. throw e;
  6180. }
  6181. }
  6182. else {
  6183. const response = yield this.client.interruptGetErr(() => this.client.execute('completions', args, token));
  6184. if (response.type !== 'response' || !response.body) {
  6185. return null;
  6186. }
  6187. entries = response.body;
  6188. }
  6189. const completionItems = [];
  6190. for (const element of entries) {
  6191. if (shouldExcludeCompletionEntry(element, completeOption)) {
  6192. continue;
  6193. }
  6194. const item = completionItem_1.convertCompletionEntry(element, uri, position, {
  6195. isNewIdentifierLocation,
  6196. isMemberCompletion,
  6197. enableCallCompletions: completeOption.completeFunctionCalls,
  6198. isInValidCommitCharacterContext,
  6199. dotAccessorContext,
  6200. });
  6201. completionItems.push(item);
  6202. }
  6203. return { isIncomplete, items: completionItems };
  6204. });
  6205. }
  6206. getTsTriggerCharacter(context) {
  6207. // return context.triggerCharacter as Proto.CompletionsTriggerCharacter
  6208. switch (context.triggerCharacter) {
  6209. case '@': // Workaround for https://github.com/Microsoft/TypeScript/issues/27321
  6210. return this.client.apiVersion.gte(api_1.default.v310) && this.client.apiVersion.lt(api_1.default.v320) ? undefined : '@';
  6211. case '#': // Workaround for https://github.com/microsoft/TypeScript/issues/36367
  6212. return this.client.apiVersion.lt(api_1.default.v381) ? undefined : '#';
  6213. case '.':
  6214. case '"':
  6215. case '\'':
  6216. case '`':
  6217. case '/':
  6218. case '<':
  6219. return context.triggerCharacter;
  6220. }
  6221. return undefined;
  6222. }
  6223. /**
  6224. * Resolve complete item, could have documentation added
  6225. *
  6226. * @public
  6227. * @param {CompletionItem} item
  6228. * @param {CancellationToken} token
  6229. * @returns {Promise<CompletionItem>}
  6230. */
  6231. resolveCompletionItem(item, token) {
  6232. return __awaiter(this, void 0, void 0, function* () {
  6233. if (item == null)
  6234. return undefined;
  6235. let { uri, position, source } = item.data;
  6236. const filepath = this.client.toPath(uri);
  6237. if (!filepath)
  6238. return undefined;
  6239. let document = coc_nvim_1.workspace.getDocument(uri);
  6240. if (!document)
  6241. return undefined;
  6242. const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(filepath, position)), { entryNames: [
  6243. source
  6244. ? { name: item.label, source }
  6245. : item.label
  6246. ] });
  6247. let response;
  6248. try {
  6249. response = yield this.client.interruptGetErr(() => this.client.execute('completionEntryDetails', args, token));
  6250. }
  6251. catch (_a) {
  6252. return item;
  6253. }
  6254. if (response.type !== 'response' || !response.body) {
  6255. return item;
  6256. }
  6257. const details = response.body;
  6258. if (!details || !details.length || !details[0]) {
  6259. return item;
  6260. }
  6261. const detail = details[0];
  6262. if (!item.detail && detail.displayParts.length) {
  6263. item.detail = Previewer.plain(detail.displayParts);
  6264. }
  6265. item.documentation = this.getDocumentation(detail);
  6266. const { command, additionalTextEdits } = this.getCodeActions(detail, filepath);
  6267. if (command)
  6268. item.command = command;
  6269. item.additionalTextEdits = additionalTextEdits;
  6270. if (detail && item.insertTextFormat == vscode_languageserver_protocol_1.InsertTextFormat.Snippet) {
  6271. const shouldCompleteFunction = yield this.isValidFunctionCompletionContext(filepath, position, token);
  6272. if (shouldCompleteFunction) {
  6273. this.createSnippetOfFunctionCall(item, detail);
  6274. }
  6275. }
  6276. return item;
  6277. });
  6278. }
  6279. getCodeActions(detail, filepath) {
  6280. if (!detail.codeActions || !detail.codeActions.length) {
  6281. return {};
  6282. }
  6283. // Try to extract out the additionalTextEdits for the current file.
  6284. // Also check if we still have to apply other workspace edits
  6285. const additionalTextEdits = [];
  6286. let hasRemainingCommandsOrEdits = false;
  6287. for (const tsAction of detail.codeActions) {
  6288. if (tsAction.commands) {
  6289. hasRemainingCommandsOrEdits = true;
  6290. }
  6291. // Convert all edits in the current file using `additionalTextEdits`
  6292. if (tsAction.changes) {
  6293. for (const change of tsAction.changes) {
  6294. if (change.fileName === filepath) {
  6295. additionalTextEdits.push(...change.textChanges.map(typeConverters.TextEdit.fromCodeEdit));
  6296. }
  6297. else {
  6298. hasRemainingCommandsOrEdits = true;
  6299. }
  6300. }
  6301. }
  6302. }
  6303. let command = null;
  6304. if (hasRemainingCommandsOrEdits) {
  6305. // Create command that applies all edits not in the current file.
  6306. command = {
  6307. title: '',
  6308. command: ApplyCompletionCodeActionCommand.ID,
  6309. arguments: [
  6310. detail.codeActions.map((x) => ({
  6311. commands: x.commands,
  6312. description: x.description,
  6313. changes: x.changes.filter(x => x.fileName !== filepath)
  6314. }))
  6315. ]
  6316. };
  6317. }
  6318. return {
  6319. command,
  6320. additionalTextEdits: additionalTextEdits.length
  6321. ? additionalTextEdits
  6322. : undefined
  6323. };
  6324. }
  6325. shouldTrigger(triggerCharacter, pre, option) {
  6326. if (triggerCharacter && this.client.apiVersion.lt(api_1.default.v290)) {
  6327. if (triggerCharacter === '@') {
  6328. // trigger in string
  6329. if (option.synname && /string/i.test(option.synname)) {
  6330. return true;
  6331. }
  6332. // make sure we are in something that looks like the start of a jsdoc comment
  6333. if (!pre.match(/^\s*\*[ ]?@/) && !pre.match(/\/\*\*+[ ]?@/)) {
  6334. return false;
  6335. }
  6336. }
  6337. else if (triggerCharacter === '<') {
  6338. return false;
  6339. }
  6340. }
  6341. return true;
  6342. }
  6343. // complete item documentation
  6344. getDocumentation(detail) {
  6345. let documentation = '';
  6346. if (detail.source) {
  6347. const importPath = `'${Previewer.plain(detail.source)}'`;
  6348. const autoImportLabel = `Auto import from ${importPath}`;
  6349. documentation += `${autoImportLabel}\n`;
  6350. }
  6351. let parts = [
  6352. Previewer.plain(detail.documentation),
  6353. Previewer.tagsMarkdownPreview(detail.tags)
  6354. ];
  6355. parts = parts.filter(s => s && s.trim() != '');
  6356. documentation += parts.join('\n\n');
  6357. if (documentation.length) {
  6358. return {
  6359. kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
  6360. value: documentation
  6361. };
  6362. }
  6363. return undefined;
  6364. }
  6365. createSnippetOfFunctionCall(item, detail) {
  6366. let { displayParts } = detail;
  6367. const parameterListParts = completionItem_1.getParameterListParts(displayParts);
  6368. const snippet = new SnippetString_1.default();
  6369. snippet.appendText(`${item.insertText || item.label}(`);
  6370. appendJoinedPlaceholders(snippet, parameterListParts.parts, ', ');
  6371. if (parameterListParts.hasOptionalParameters) {
  6372. snippet.appendTabstop();
  6373. }
  6374. snippet.appendText(')');
  6375. snippet.appendTabstop(0);
  6376. item.insertText = snippet.value;
  6377. }
  6378. isValidFunctionCompletionContext(filepath, position, token) {
  6379. return __awaiter(this, void 0, void 0, function* () {
  6380. // Workaround for https://github.com/Microsoft/TypeScript/issues/12677
  6381. // Don't complete function calls inside of destructive assigments or imports
  6382. try {
  6383. const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
  6384. const response = yield this.client.execute('quickinfo', args, token);
  6385. if (response.type !== 'response') {
  6386. return true;
  6387. }
  6388. const { body } = response;
  6389. switch (body && body.kind) {
  6390. case 'var':
  6391. case 'let':
  6392. case 'const':
  6393. case 'alias':
  6394. return false;
  6395. default:
  6396. return true;
  6397. }
  6398. }
  6399. catch (e) {
  6400. return true;
  6401. }
  6402. });
  6403. }
  6404. isInValidCommitCharacterContext(document, position) {
  6405. if (this.client.apiVersion.lt(api_1.default.v320)) {
  6406. // Workaround for https://github.com/Microsoft/TypeScript/issues/27742
  6407. // Only enable dot completions when previous character not a dot preceded by whitespace.
  6408. // Prevents incorrectly completing while typing spread operators.
  6409. if (position.character > 1) {
  6410. const preText = document.getText(vscode_languageserver_protocol_1.Range.create(position.line, 0, position.line, position.character));
  6411. return preText.match(/(\s|^)\.$/ig) === null;
  6412. }
  6413. }
  6414. return true;
  6415. }
  6416. }
  6417. exports.default = TypeScriptCompletionItemProvider;
  6418. TypeScriptCompletionItemProvider.triggerCharacters = ['.', '"', '\'', '`', '/', '@', '<', '#'];
  6419. function shouldExcludeCompletionEntry(element, completionConfiguration) {
  6420. return ((!completionConfiguration.names && element.kind === PConst.Kind.warning)
  6421. || (!completionConfiguration.paths &&
  6422. (element.kind === PConst.Kind.directory || element.kind === PConst.Kind.script || element.kind === PConst.Kind.externalModuleName))
  6423. || (!completionConfiguration.autoImports && element.hasAction));
  6424. }
  6425. function appendJoinedPlaceholders(snippet, parts, joiner) {
  6426. for (let i = 0; i < parts.length; ++i) {
  6427. const paramterPart = parts[i];
  6428. snippet.appendPlaceholder(paramterPart.text);
  6429. if (i !== parts.length - 1) {
  6430. snippet.appendText(joiner);
  6431. }
  6432. }
  6433. }
  6434. /***/ }),
  6435. /* 39 */
  6436. /***/ (function(module, exports, __webpack_require__) {
  6437. "use strict";
  6438. /*---------------------------------------------------------------------------------------------
  6439. * Copyright (c) Microsoft Corporation. All rights reserved.
  6440. * Licensed under the MIT License. See License.txt in the project root for license information.
  6441. *--------------------------------------------------------------------------------------------*/
  6442. Object.defineProperty(exports, "__esModule", { value: true });
  6443. exports.DisplayPartKind = exports.KindModifiers = exports.DiagnosticCategory = exports.Kind = void 0;
  6444. class Kind {
  6445. }
  6446. exports.Kind = Kind;
  6447. Kind.alias = 'alias';
  6448. Kind.callSignature = 'call';
  6449. Kind.class = 'class';
  6450. Kind.const = 'const';
  6451. Kind.constructorImplementation = 'constructor';
  6452. Kind.constructSignature = 'construct';
  6453. Kind.directory = 'directory';
  6454. Kind.enum = 'enum';
  6455. Kind.enumMember = 'enum member';
  6456. Kind.externalModuleName = 'external module name';
  6457. Kind.function = 'function';
  6458. Kind.indexSignature = 'index';
  6459. Kind.interface = 'interface';
  6460. Kind.keyword = 'keyword';
  6461. Kind.let = 'let';
  6462. Kind.localFunction = 'local function';
  6463. Kind.localVariable = 'local var';
  6464. Kind.method = 'method';
  6465. Kind.memberGetAccessor = 'getter';
  6466. Kind.memberSetAccessor = 'setter';
  6467. Kind.memberVariable = 'property';
  6468. Kind.module = 'module';
  6469. Kind.primitiveType = 'primitive type';
  6470. Kind.script = 'script';
  6471. Kind.type = 'type';
  6472. Kind.variable = 'var';
  6473. Kind.warning = 'warning';
  6474. Kind.string = 'string';
  6475. Kind.parameter = 'parameter';
  6476. Kind.typeParameter = 'type parameter';
  6477. class DiagnosticCategory {
  6478. }
  6479. exports.DiagnosticCategory = DiagnosticCategory;
  6480. DiagnosticCategory.error = 'error';
  6481. DiagnosticCategory.warning = 'warning';
  6482. DiagnosticCategory.suggestion = 'suggestion';
  6483. class KindModifiers {
  6484. }
  6485. exports.KindModifiers = KindModifiers;
  6486. KindModifiers.optional = 'optional';
  6487. KindModifiers.color = 'color';
  6488. KindModifiers.dtsFile = '.d.ts';
  6489. KindModifiers.tsFile = '.ts';
  6490. KindModifiers.tsxFile = '.tsx';
  6491. KindModifiers.jsFile = '.js';
  6492. KindModifiers.jsxFile = '.jsx';
  6493. KindModifiers.jsonFile = '.json';
  6494. KindModifiers.fileExtensionKindModifiers = [
  6495. KindModifiers.dtsFile,
  6496. KindModifiers.tsFile,
  6497. KindModifiers.tsxFile,
  6498. KindModifiers.jsFile,
  6499. KindModifiers.jsxFile,
  6500. KindModifiers.jsonFile,
  6501. ];
  6502. class DisplayPartKind {
  6503. }
  6504. exports.DisplayPartKind = DisplayPartKind;
  6505. DisplayPartKind.functionName = 'functionName';
  6506. DisplayPartKind.methodName = 'methodName';
  6507. DisplayPartKind.parameterName = 'parameterName';
  6508. DisplayPartKind.propertyName = 'propertyName';
  6509. DisplayPartKind.punctuation = 'punctuation';
  6510. DisplayPartKind.text = 'text';
  6511. /***/ }),
  6512. /* 40 */
  6513. /***/ (function(module, exports, __webpack_require__) {
  6514. "use strict";
  6515. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  6516. if (k2 === undefined) k2 = k;
  6517. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  6518. }) : (function(o, m, k, k2) {
  6519. if (k2 === undefined) k2 = k;
  6520. o[k2] = m[k];
  6521. }));
  6522. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  6523. Object.defineProperty(o, "default", { enumerable: true, value: v });
  6524. }) : function(o, v) {
  6525. o["default"] = v;
  6526. });
  6527. var __importStar = (this && this.__importStar) || function (mod) {
  6528. if (mod && mod.__esModule) return mod;
  6529. var result = {};
  6530. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  6531. __setModuleDefault(result, mod);
  6532. return result;
  6533. };
  6534. Object.defineProperty(exports, "__esModule", { value: true });
  6535. /*---------------------------------------------------------------------------------------------
  6536. * Copyright (c) Microsoft Corporation. All rights reserved.
  6537. * Licensed under the MIT License. See License.txt in the project root for license information.
  6538. *--------------------------------------------------------------------------------------------*/
  6539. const semver = __importStar(__webpack_require__(41));
  6540. class API {
  6541. constructor(versionString, version) {
  6542. this.versionString = versionString;
  6543. this.version = version;
  6544. }
  6545. static fromSimpleString(value) {
  6546. return new API(value, value);
  6547. }
  6548. static fromVersionString(versionString) {
  6549. let version = semver.valid(versionString);
  6550. if (!version) {
  6551. return new API('invalid version', '1.0.0');
  6552. }
  6553. // Cut off any prerelease tag since we sometimes consume those on purpose.
  6554. const index = versionString.indexOf('-');
  6555. if (index >= 0) {
  6556. version = version.substr(0, index);
  6557. }
  6558. return new API(versionString, version);
  6559. }
  6560. gte(other) {
  6561. return semver.gte(this.version, other.version);
  6562. }
  6563. lt(other) {
  6564. return !this.gte(other);
  6565. }
  6566. }
  6567. exports.default = API;
  6568. API.defaultVersion = API.fromSimpleString('1.0.0');
  6569. API.v203 = API.fromSimpleString('2.0.3');
  6570. API.v206 = API.fromSimpleString('2.0.6');
  6571. API.v208 = API.fromSimpleString('2.0.8');
  6572. API.v213 = API.fromSimpleString('2.1.3');
  6573. API.v220 = API.fromSimpleString('2.2.0');
  6574. API.v222 = API.fromSimpleString('2.2.2');
  6575. API.v230 = API.fromSimpleString('2.3.0');
  6576. API.v234 = API.fromSimpleString('2.3.4');
  6577. API.v240 = API.fromSimpleString('2.4.0');
  6578. API.v250 = API.fromSimpleString('2.5.0');
  6579. API.v260 = API.fromSimpleString('2.6.0');
  6580. API.v270 = API.fromSimpleString('2.7.0');
  6581. API.v280 = API.fromSimpleString('2.8.0');
  6582. API.v290 = API.fromSimpleString('2.9.0');
  6583. API.v291 = API.fromSimpleString('2.9.1');
  6584. API.v292 = API.fromSimpleString('2.9.2');
  6585. API.v300 = API.fromSimpleString('3.0.0');
  6586. API.v310 = API.fromSimpleString('3.1.0');
  6587. API.v314 = API.fromSimpleString('3.1.4');
  6588. API.v320 = API.fromSimpleString('3.2.0');
  6589. API.v330 = API.fromSimpleString('3.3.0');
  6590. API.v333 = API.fromSimpleString('3.3.3');
  6591. API.v340 = API.fromSimpleString('3.4.0');
  6592. API.v345 = API.fromSimpleString('3.4.5');
  6593. API.v350 = API.fromSimpleString('3.5.0');
  6594. API.v380 = API.fromSimpleString('3.8.0');
  6595. API.v381 = API.fromSimpleString('3.8.1');
  6596. API.v390 = API.fromSimpleString('3.9.0');
  6597. /***/ }),
  6598. /* 41 */
  6599. /***/ (function(module, exports, __webpack_require__) {
  6600. // just pre-load all the stuff that index.js lazily exports
  6601. const internalRe = __webpack_require__(42)
  6602. module.exports = {
  6603. re: internalRe.re,
  6604. src: internalRe.src,
  6605. tokens: internalRe.t,
  6606. SEMVER_SPEC_VERSION: __webpack_require__(43).SEMVER_SPEC_VERSION,
  6607. SemVer: __webpack_require__(45),
  6608. compareIdentifiers: __webpack_require__(46).compareIdentifiers,
  6609. rcompareIdentifiers: __webpack_require__(46).rcompareIdentifiers,
  6610. parse: __webpack_require__(47),
  6611. valid: __webpack_require__(48),
  6612. clean: __webpack_require__(49),
  6613. inc: __webpack_require__(50),
  6614. diff: __webpack_require__(51),
  6615. major: __webpack_require__(54),
  6616. minor: __webpack_require__(55),
  6617. patch: __webpack_require__(56),
  6618. prerelease: __webpack_require__(57),
  6619. compare: __webpack_require__(53),
  6620. rcompare: __webpack_require__(58),
  6621. compareLoose: __webpack_require__(59),
  6622. compareBuild: __webpack_require__(60),
  6623. sort: __webpack_require__(61),
  6624. rsort: __webpack_require__(62),
  6625. gt: __webpack_require__(63),
  6626. lt: __webpack_require__(64),
  6627. eq: __webpack_require__(52),
  6628. neq: __webpack_require__(65),
  6629. gte: __webpack_require__(66),
  6630. lte: __webpack_require__(67),
  6631. cmp: __webpack_require__(68),
  6632. coerce: __webpack_require__(69),
  6633. Comparator: __webpack_require__(70),
  6634. Range: __webpack_require__(71),
  6635. satisfies: __webpack_require__(72),
  6636. toComparators: __webpack_require__(73),
  6637. maxSatisfying: __webpack_require__(74),
  6638. minSatisfying: __webpack_require__(75),
  6639. minVersion: __webpack_require__(76),
  6640. validRange: __webpack_require__(77),
  6641. outside: __webpack_require__(78),
  6642. gtr: __webpack_require__(79),
  6643. ltr: __webpack_require__(80),
  6644. intersects: __webpack_require__(81),
  6645. simplifyRange: __webpack_require__(82),
  6646. subset: __webpack_require__(83),
  6647. }
  6648. /***/ }),
  6649. /* 42 */
  6650. /***/ (function(module, exports, __webpack_require__) {
  6651. const { MAX_SAFE_COMPONENT_LENGTH } = __webpack_require__(43)
  6652. const debug = __webpack_require__(44)
  6653. exports = module.exports = {}
  6654. // The actual regexps go on exports.re
  6655. const re = exports.re = []
  6656. const src = exports.src = []
  6657. const t = exports.t = {}
  6658. let R = 0
  6659. const createToken = (name, value, isGlobal) => {
  6660. const index = R++
  6661. debug(index, value)
  6662. t[name] = index
  6663. src[index] = value
  6664. re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
  6665. }
  6666. // The following Regular Expressions can be used for tokenizing,
  6667. // validating, and parsing SemVer version strings.
  6668. // ## Numeric Identifier
  6669. // A single `0`, or a non-zero digit followed by zero or more digits.
  6670. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
  6671. createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+')
  6672. // ## Non-numeric Identifier
  6673. // Zero or more digits, followed by a letter or hyphen, and then zero or
  6674. // more letters, digits, or hyphens.
  6675. createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*')
  6676. // ## Main Version
  6677. // Three dot-separated numeric identifiers.
  6678. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
  6679. `(${src[t.NUMERICIDENTIFIER]})\\.` +
  6680. `(${src[t.NUMERICIDENTIFIER]})`)
  6681. createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
  6682. `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
  6683. `(${src[t.NUMERICIDENTIFIERLOOSE]})`)
  6684. // ## Pre-release Version Identifier
  6685. // A numeric identifier, or a non-numeric identifier.
  6686. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
  6687. }|${src[t.NONNUMERICIDENTIFIER]})`)
  6688. createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
  6689. }|${src[t.NONNUMERICIDENTIFIER]})`)
  6690. // ## Pre-release Version
  6691. // Hyphen, followed by one or more dot-separated pre-release version
  6692. // identifiers.
  6693. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
  6694. }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
  6695. createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
  6696. }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
  6697. // ## Build Metadata Identifier
  6698. // Any combination of digits, letters, or hyphens.
  6699. createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+')
  6700. // ## Build Metadata
  6701. // Plus sign, followed by one or more period-separated build metadata
  6702. // identifiers.
  6703. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
  6704. }(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
  6705. // ## Full Version String
  6706. // A main version, followed optionally by a pre-release version and
  6707. // build metadata.
  6708. // Note that the only major, minor, patch, and pre-release sections of
  6709. // the version string are capturing groups. The build metadata is not a
  6710. // capturing group, because it should not ever be used in version
  6711. // comparison.
  6712. createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
  6713. }${src[t.PRERELEASE]}?${
  6714. src[t.BUILD]}?`)
  6715. createToken('FULL', `^${src[t.FULLPLAIN]}$`)
  6716. // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
  6717. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
  6718. // common in the npm registry.
  6719. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
  6720. }${src[t.PRERELEASELOOSE]}?${
  6721. src[t.BUILD]}?`)
  6722. createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
  6723. createToken('GTLT', '((?:<|>)?=?)')
  6724. // Something like "2.*" or "1.2.x".
  6725. // Note that "x.x" is a valid xRange identifer, meaning "any version"
  6726. // Only the first item is strictly required.
  6727. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
  6728. createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
  6729. createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
  6730. `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
  6731. `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
  6732. `(?:${src[t.PRERELEASE]})?${
  6733. src[t.BUILD]}?` +
  6734. `)?)?`)
  6735. createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
  6736. `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
  6737. `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
  6738. `(?:${src[t.PRERELEASELOOSE]})?${
  6739. src[t.BUILD]}?` +
  6740. `)?)?`)
  6741. createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
  6742. createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
  6743. // Coercion.
  6744. // Extract anything that could conceivably be a part of a valid semver
  6745. createToken('COERCE', `${'(^|[^\\d])' +
  6746. '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
  6747. `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
  6748. `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
  6749. `(?:$|[^\\d])`)
  6750. createToken('COERCERTL', src[t.COERCE], true)
  6751. // Tilde ranges.
  6752. // Meaning is "reasonably at or greater than"
  6753. createToken('LONETILDE', '(?:~>?)')
  6754. createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
  6755. exports.tildeTrimReplace = '$1~'
  6756. createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
  6757. createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
  6758. // Caret ranges.
  6759. // Meaning is "at least and backwards compatible with"
  6760. createToken('LONECARET', '(?:\\^)')
  6761. createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
  6762. exports.caretTrimReplace = '$1^'
  6763. createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
  6764. createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
  6765. // A simple gt/lt/eq thing, or just "" to indicate "any version"
  6766. createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
  6767. createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
  6768. // An expression to strip any whitespace between the gtlt and the thing
  6769. // it modifies, so that `> 1.2.3` ==> `>1.2.3`
  6770. createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
  6771. }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
  6772. exports.comparatorTrimReplace = '$1$2$3'
  6773. // Something like `1.2.3 - 1.2.4`
  6774. // Note that these all use the loose form, because they'll be
  6775. // checked against either the strict or loose comparator form
  6776. // later.
  6777. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
  6778. `\\s+-\\s+` +
  6779. `(${src[t.XRANGEPLAIN]})` +
  6780. `\\s*$`)
  6781. createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
  6782. `\\s+-\\s+` +
  6783. `(${src[t.XRANGEPLAINLOOSE]})` +
  6784. `\\s*$`)
  6785. // Star ranges basically just allow anything at all.
  6786. createToken('STAR', '(<|>)?=?\\s*\\*')
  6787. // >=0.0.0 is like a star
  6788. createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$')
  6789. createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$')
  6790. /***/ }),
  6791. /* 43 */
  6792. /***/ (function(module, exports) {
  6793. // Note: this is the semver.org version of the spec that it implements
  6794. // Not necessarily the package version of this code.
  6795. const SEMVER_SPEC_VERSION = '2.0.0'
  6796. const MAX_LENGTH = 256
  6797. const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
  6798. /* istanbul ignore next */ 9007199254740991
  6799. // Max safe segment length for coercion.
  6800. const MAX_SAFE_COMPONENT_LENGTH = 16
  6801. module.exports = {
  6802. SEMVER_SPEC_VERSION,
  6803. MAX_LENGTH,
  6804. MAX_SAFE_INTEGER,
  6805. MAX_SAFE_COMPONENT_LENGTH
  6806. }
  6807. /***/ }),
  6808. /* 44 */
  6809. /***/ (function(module, exports) {
  6810. const debug = (
  6811. typeof process === 'object' &&
  6812. process.env &&
  6813. process.env.NODE_DEBUG &&
  6814. /\bsemver\b/i.test(process.env.NODE_DEBUG)
  6815. ) ? (...args) => console.error('SEMVER', ...args)
  6816. : () => {}
  6817. module.exports = debug
  6818. /***/ }),
  6819. /* 45 */
  6820. /***/ (function(module, exports, __webpack_require__) {
  6821. const debug = __webpack_require__(44)
  6822. const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(43)
  6823. const { re, t } = __webpack_require__(42)
  6824. const { compareIdentifiers } = __webpack_require__(46)
  6825. class SemVer {
  6826. constructor (version, options) {
  6827. if (!options || typeof options !== 'object') {
  6828. options = {
  6829. loose: !!options,
  6830. includePrerelease: false
  6831. }
  6832. }
  6833. if (version instanceof SemVer) {
  6834. if (version.loose === !!options.loose &&
  6835. version.includePrerelease === !!options.includePrerelease) {
  6836. return version
  6837. } else {
  6838. version = version.version
  6839. }
  6840. } else if (typeof version !== 'string') {
  6841. throw new TypeError(`Invalid Version: ${version}`)
  6842. }
  6843. if (version.length > MAX_LENGTH) {
  6844. throw new TypeError(
  6845. `version is longer than ${MAX_LENGTH} characters`
  6846. )
  6847. }
  6848. debug('SemVer', version, options)
  6849. this.options = options
  6850. this.loose = !!options.loose
  6851. // this isn't actually relevant for versions, but keep it so that we
  6852. // don't run into trouble passing this.options around.
  6853. this.includePrerelease = !!options.includePrerelease
  6854. const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
  6855. if (!m) {
  6856. throw new TypeError(`Invalid Version: ${version}`)
  6857. }
  6858. this.raw = version
  6859. // these are actually numbers
  6860. this.major = +m[1]
  6861. this.minor = +m[2]
  6862. this.patch = +m[3]
  6863. if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
  6864. throw new TypeError('Invalid major version')
  6865. }
  6866. if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
  6867. throw new TypeError('Invalid minor version')
  6868. }
  6869. if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
  6870. throw new TypeError('Invalid patch version')
  6871. }
  6872. // numberify any prerelease numeric ids
  6873. if (!m[4]) {
  6874. this.prerelease = []
  6875. } else {
  6876. this.prerelease = m[4].split('.').map((id) => {
  6877. if (/^[0-9]+$/.test(id)) {
  6878. const num = +id
  6879. if (num >= 0 && num < MAX_SAFE_INTEGER) {
  6880. return num
  6881. }
  6882. }
  6883. return id
  6884. })
  6885. }
  6886. this.build = m[5] ? m[5].split('.') : []
  6887. this.format()
  6888. }
  6889. format () {
  6890. this.version = `${this.major}.${this.minor}.${this.patch}`
  6891. if (this.prerelease.length) {
  6892. this.version += `-${this.prerelease.join('.')}`
  6893. }
  6894. return this.version
  6895. }
  6896. toString () {
  6897. return this.version
  6898. }
  6899. compare (other) {
  6900. debug('SemVer.compare', this.version, this.options, other)
  6901. if (!(other instanceof SemVer)) {
  6902. if (typeof other === 'string' && other === this.version) {
  6903. return 0
  6904. }
  6905. other = new SemVer(other, this.options)
  6906. }
  6907. if (other.version === this.version) {
  6908. return 0
  6909. }
  6910. return this.compareMain(other) || this.comparePre(other)
  6911. }
  6912. compareMain (other) {
  6913. if (!(other instanceof SemVer)) {
  6914. other = new SemVer(other, this.options)
  6915. }
  6916. return (
  6917. compareIdentifiers(this.major, other.major) ||
  6918. compareIdentifiers(this.minor, other.minor) ||
  6919. compareIdentifiers(this.patch, other.patch)
  6920. )
  6921. }
  6922. comparePre (other) {
  6923. if (!(other instanceof SemVer)) {
  6924. other = new SemVer(other, this.options)
  6925. }
  6926. // NOT having a prerelease is > having one
  6927. if (this.prerelease.length && !other.prerelease.length) {
  6928. return -1
  6929. } else if (!this.prerelease.length && other.prerelease.length) {
  6930. return 1
  6931. } else if (!this.prerelease.length && !other.prerelease.length) {
  6932. return 0
  6933. }
  6934. let i = 0
  6935. do {
  6936. const a = this.prerelease[i]
  6937. const b = other.prerelease[i]
  6938. debug('prerelease compare', i, a, b)
  6939. if (a === undefined && b === undefined) {
  6940. return 0
  6941. } else if (b === undefined) {
  6942. return 1
  6943. } else if (a === undefined) {
  6944. return -1
  6945. } else if (a === b) {
  6946. continue
  6947. } else {
  6948. return compareIdentifiers(a, b)
  6949. }
  6950. } while (++i)
  6951. }
  6952. compareBuild (other) {
  6953. if (!(other instanceof SemVer)) {
  6954. other = new SemVer(other, this.options)
  6955. }
  6956. let i = 0
  6957. do {
  6958. const a = this.build[i]
  6959. const b = other.build[i]
  6960. debug('prerelease compare', i, a, b)
  6961. if (a === undefined && b === undefined) {
  6962. return 0
  6963. } else if (b === undefined) {
  6964. return 1
  6965. } else if (a === undefined) {
  6966. return -1
  6967. } else if (a === b) {
  6968. continue
  6969. } else {
  6970. return compareIdentifiers(a, b)
  6971. }
  6972. } while (++i)
  6973. }
  6974. // preminor will bump the version up to the next minor release, and immediately
  6975. // down to pre-release. premajor and prepatch work the same way.
  6976. inc (release, identifier) {
  6977. switch (release) {
  6978. case 'premajor':
  6979. this.prerelease.length = 0
  6980. this.patch = 0
  6981. this.minor = 0
  6982. this.major++
  6983. this.inc('pre', identifier)
  6984. break
  6985. case 'preminor':
  6986. this.prerelease.length = 0
  6987. this.patch = 0
  6988. this.minor++
  6989. this.inc('pre', identifier)
  6990. break
  6991. case 'prepatch':
  6992. // If this is already a prerelease, it will bump to the next version
  6993. // drop any prereleases that might already exist, since they are not
  6994. // relevant at this point.
  6995. this.prerelease.length = 0
  6996. this.inc('patch', identifier)
  6997. this.inc('pre', identifier)
  6998. break
  6999. // If the input is a non-prerelease version, this acts the same as
  7000. // prepatch.
  7001. case 'prerelease':
  7002. if (this.prerelease.length === 0) {
  7003. this.inc('patch', identifier)
  7004. }
  7005. this.inc('pre', identifier)
  7006. break
  7007. case 'major':
  7008. // If this is a pre-major version, bump up to the same major version.
  7009. // Otherwise increment major.
  7010. // 1.0.0-5 bumps to 1.0.0
  7011. // 1.1.0 bumps to 2.0.0
  7012. if (
  7013. this.minor !== 0 ||
  7014. this.patch !== 0 ||
  7015. this.prerelease.length === 0
  7016. ) {
  7017. this.major++
  7018. }
  7019. this.minor = 0
  7020. this.patch = 0
  7021. this.prerelease = []
  7022. break
  7023. case 'minor':
  7024. // If this is a pre-minor version, bump up to the same minor version.
  7025. // Otherwise increment minor.
  7026. // 1.2.0-5 bumps to 1.2.0
  7027. // 1.2.1 bumps to 1.3.0
  7028. if (this.patch !== 0 || this.prerelease.length === 0) {
  7029. this.minor++
  7030. }
  7031. this.patch = 0
  7032. this.prerelease = []
  7033. break
  7034. case 'patch':
  7035. // If this is not a pre-release version, it will increment the patch.
  7036. // If it is a pre-release it will bump up to the same patch version.
  7037. // 1.2.0-5 patches to 1.2.0
  7038. // 1.2.0 patches to 1.2.1
  7039. if (this.prerelease.length === 0) {
  7040. this.patch++
  7041. }
  7042. this.prerelease = []
  7043. break
  7044. // This probably shouldn't be used publicly.
  7045. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
  7046. case 'pre':
  7047. if (this.prerelease.length === 0) {
  7048. this.prerelease = [0]
  7049. } else {
  7050. let i = this.prerelease.length
  7051. while (--i >= 0) {
  7052. if (typeof this.prerelease[i] === 'number') {
  7053. this.prerelease[i]++
  7054. i = -2
  7055. }
  7056. }
  7057. if (i === -1) {
  7058. // didn't increment anything
  7059. this.prerelease.push(0)
  7060. }
  7061. }
  7062. if (identifier) {
  7063. // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
  7064. // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
  7065. if (this.prerelease[0] === identifier) {
  7066. if (isNaN(this.prerelease[1])) {
  7067. this.prerelease = [identifier, 0]
  7068. }
  7069. } else {
  7070. this.prerelease = [identifier, 0]
  7071. }
  7072. }
  7073. break
  7074. default:
  7075. throw new Error(`invalid increment argument: ${release}`)
  7076. }
  7077. this.format()
  7078. this.raw = this.version
  7079. return this
  7080. }
  7081. }
  7082. module.exports = SemVer
  7083. /***/ }),
  7084. /* 46 */
  7085. /***/ (function(module, exports) {
  7086. const numeric = /^[0-9]+$/
  7087. const compareIdentifiers = (a, b) => {
  7088. const anum = numeric.test(a)
  7089. const bnum = numeric.test(b)
  7090. if (anum && bnum) {
  7091. a = +a
  7092. b = +b
  7093. }
  7094. return a === b ? 0
  7095. : (anum && !bnum) ? -1
  7096. : (bnum && !anum) ? 1
  7097. : a < b ? -1
  7098. : 1
  7099. }
  7100. const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
  7101. module.exports = {
  7102. compareIdentifiers,
  7103. rcompareIdentifiers
  7104. }
  7105. /***/ }),
  7106. /* 47 */
  7107. /***/ (function(module, exports, __webpack_require__) {
  7108. const {MAX_LENGTH} = __webpack_require__(43)
  7109. const { re, t } = __webpack_require__(42)
  7110. const SemVer = __webpack_require__(45)
  7111. const parse = (version, options) => {
  7112. if (!options || typeof options !== 'object') {
  7113. options = {
  7114. loose: !!options,
  7115. includePrerelease: false
  7116. }
  7117. }
  7118. if (version instanceof SemVer) {
  7119. return version
  7120. }
  7121. if (typeof version !== 'string') {
  7122. return null
  7123. }
  7124. if (version.length > MAX_LENGTH) {
  7125. return null
  7126. }
  7127. const r = options.loose ? re[t.LOOSE] : re[t.FULL]
  7128. if (!r.test(version)) {
  7129. return null
  7130. }
  7131. try {
  7132. return new SemVer(version, options)
  7133. } catch (er) {
  7134. return null
  7135. }
  7136. }
  7137. module.exports = parse
  7138. /***/ }),
  7139. /* 48 */
  7140. /***/ (function(module, exports, __webpack_require__) {
  7141. const parse = __webpack_require__(47)
  7142. const valid = (version, options) => {
  7143. const v = parse(version, options)
  7144. return v ? v.version : null
  7145. }
  7146. module.exports = valid
  7147. /***/ }),
  7148. /* 49 */
  7149. /***/ (function(module, exports, __webpack_require__) {
  7150. const parse = __webpack_require__(47)
  7151. const clean = (version, options) => {
  7152. const s = parse(version.trim().replace(/^[=v]+/, ''), options)
  7153. return s ? s.version : null
  7154. }
  7155. module.exports = clean
  7156. /***/ }),
  7157. /* 50 */
  7158. /***/ (function(module, exports, __webpack_require__) {
  7159. const SemVer = __webpack_require__(45)
  7160. const inc = (version, release, options, identifier) => {
  7161. if (typeof (options) === 'string') {
  7162. identifier = options
  7163. options = undefined
  7164. }
  7165. try {
  7166. return new SemVer(version, options).inc(release, identifier).version
  7167. } catch (er) {
  7168. return null
  7169. }
  7170. }
  7171. module.exports = inc
  7172. /***/ }),
  7173. /* 51 */
  7174. /***/ (function(module, exports, __webpack_require__) {
  7175. const parse = __webpack_require__(47)
  7176. const eq = __webpack_require__(52)
  7177. const diff = (version1, version2) => {
  7178. if (eq(version1, version2)) {
  7179. return null
  7180. } else {
  7181. const v1 = parse(version1)
  7182. const v2 = parse(version2)
  7183. const hasPre = v1.prerelease.length || v2.prerelease.length
  7184. const prefix = hasPre ? 'pre' : ''
  7185. const defaultResult = hasPre ? 'prerelease' : ''
  7186. for (const key in v1) {
  7187. if (key === 'major' || key === 'minor' || key === 'patch') {
  7188. if (v1[key] !== v2[key]) {
  7189. return prefix + key
  7190. }
  7191. }
  7192. }
  7193. return defaultResult // may be undefined
  7194. }
  7195. }
  7196. module.exports = diff
  7197. /***/ }),
  7198. /* 52 */
  7199. /***/ (function(module, exports, __webpack_require__) {
  7200. const compare = __webpack_require__(53)
  7201. const eq = (a, b, loose) => compare(a, b, loose) === 0
  7202. module.exports = eq
  7203. /***/ }),
  7204. /* 53 */
  7205. /***/ (function(module, exports, __webpack_require__) {
  7206. const SemVer = __webpack_require__(45)
  7207. const compare = (a, b, loose) =>
  7208. new SemVer(a, loose).compare(new SemVer(b, loose))
  7209. module.exports = compare
  7210. /***/ }),
  7211. /* 54 */
  7212. /***/ (function(module, exports, __webpack_require__) {
  7213. const SemVer = __webpack_require__(45)
  7214. const major = (a, loose) => new SemVer(a, loose).major
  7215. module.exports = major
  7216. /***/ }),
  7217. /* 55 */
  7218. /***/ (function(module, exports, __webpack_require__) {
  7219. const SemVer = __webpack_require__(45)
  7220. const minor = (a, loose) => new SemVer(a, loose).minor
  7221. module.exports = minor
  7222. /***/ }),
  7223. /* 56 */
  7224. /***/ (function(module, exports, __webpack_require__) {
  7225. const SemVer = __webpack_require__(45)
  7226. const patch = (a, loose) => new SemVer(a, loose).patch
  7227. module.exports = patch
  7228. /***/ }),
  7229. /* 57 */
  7230. /***/ (function(module, exports, __webpack_require__) {
  7231. const parse = __webpack_require__(47)
  7232. const prerelease = (version, options) => {
  7233. const parsed = parse(version, options)
  7234. return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
  7235. }
  7236. module.exports = prerelease
  7237. /***/ }),
  7238. /* 58 */
  7239. /***/ (function(module, exports, __webpack_require__) {
  7240. const compare = __webpack_require__(53)
  7241. const rcompare = (a, b, loose) => compare(b, a, loose)
  7242. module.exports = rcompare
  7243. /***/ }),
  7244. /* 59 */
  7245. /***/ (function(module, exports, __webpack_require__) {
  7246. const compare = __webpack_require__(53)
  7247. const compareLoose = (a, b) => compare(a, b, true)
  7248. module.exports = compareLoose
  7249. /***/ }),
  7250. /* 60 */
  7251. /***/ (function(module, exports, __webpack_require__) {
  7252. const SemVer = __webpack_require__(45)
  7253. const compareBuild = (a, b, loose) => {
  7254. const versionA = new SemVer(a, loose)
  7255. const versionB = new SemVer(b, loose)
  7256. return versionA.compare(versionB) || versionA.compareBuild(versionB)
  7257. }
  7258. module.exports = compareBuild
  7259. /***/ }),
  7260. /* 61 */
  7261. /***/ (function(module, exports, __webpack_require__) {
  7262. const compareBuild = __webpack_require__(60)
  7263. const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
  7264. module.exports = sort
  7265. /***/ }),
  7266. /* 62 */
  7267. /***/ (function(module, exports, __webpack_require__) {
  7268. const compareBuild = __webpack_require__(60)
  7269. const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
  7270. module.exports = rsort
  7271. /***/ }),
  7272. /* 63 */
  7273. /***/ (function(module, exports, __webpack_require__) {
  7274. const compare = __webpack_require__(53)
  7275. const gt = (a, b, loose) => compare(a, b, loose) > 0
  7276. module.exports = gt
  7277. /***/ }),
  7278. /* 64 */
  7279. /***/ (function(module, exports, __webpack_require__) {
  7280. const compare = __webpack_require__(53)
  7281. const lt = (a, b, loose) => compare(a, b, loose) < 0
  7282. module.exports = lt
  7283. /***/ }),
  7284. /* 65 */
  7285. /***/ (function(module, exports, __webpack_require__) {
  7286. const compare = __webpack_require__(53)
  7287. const neq = (a, b, loose) => compare(a, b, loose) !== 0
  7288. module.exports = neq
  7289. /***/ }),
  7290. /* 66 */
  7291. /***/ (function(module, exports, __webpack_require__) {
  7292. const compare = __webpack_require__(53)
  7293. const gte = (a, b, loose) => compare(a, b, loose) >= 0
  7294. module.exports = gte
  7295. /***/ }),
  7296. /* 67 */
  7297. /***/ (function(module, exports, __webpack_require__) {
  7298. const compare = __webpack_require__(53)
  7299. const lte = (a, b, loose) => compare(a, b, loose) <= 0
  7300. module.exports = lte
  7301. /***/ }),
  7302. /* 68 */
  7303. /***/ (function(module, exports, __webpack_require__) {
  7304. const eq = __webpack_require__(52)
  7305. const neq = __webpack_require__(65)
  7306. const gt = __webpack_require__(63)
  7307. const gte = __webpack_require__(66)
  7308. const lt = __webpack_require__(64)
  7309. const lte = __webpack_require__(67)
  7310. const cmp = (a, op, b, loose) => {
  7311. switch (op) {
  7312. case '===':
  7313. if (typeof a === 'object')
  7314. a = a.version
  7315. if (typeof b === 'object')
  7316. b = b.version
  7317. return a === b
  7318. case '!==':
  7319. if (typeof a === 'object')
  7320. a = a.version
  7321. if (typeof b === 'object')
  7322. b = b.version
  7323. return a !== b
  7324. case '':
  7325. case '=':
  7326. case '==':
  7327. return eq(a, b, loose)
  7328. case '!=':
  7329. return neq(a, b, loose)
  7330. case '>':
  7331. return gt(a, b, loose)
  7332. case '>=':
  7333. return gte(a, b, loose)
  7334. case '<':
  7335. return lt(a, b, loose)
  7336. case '<=':
  7337. return lte(a, b, loose)
  7338. default:
  7339. throw new TypeError(`Invalid operator: ${op}`)
  7340. }
  7341. }
  7342. module.exports = cmp
  7343. /***/ }),
  7344. /* 69 */
  7345. /***/ (function(module, exports, __webpack_require__) {
  7346. const SemVer = __webpack_require__(45)
  7347. const parse = __webpack_require__(47)
  7348. const {re, t} = __webpack_require__(42)
  7349. const coerce = (version, options) => {
  7350. if (version instanceof SemVer) {
  7351. return version
  7352. }
  7353. if (typeof version === 'number') {
  7354. version = String(version)
  7355. }
  7356. if (typeof version !== 'string') {
  7357. return null
  7358. }
  7359. options = options || {}
  7360. let match = null
  7361. if (!options.rtl) {
  7362. match = version.match(re[t.COERCE])
  7363. } else {
  7364. // Find the right-most coercible string that does not share
  7365. // a terminus with a more left-ward coercible string.
  7366. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
  7367. //
  7368. // Walk through the string checking with a /g regexp
  7369. // Manually set the index so as to pick up overlapping matches.
  7370. // Stop when we get a match that ends at the string end, since no
  7371. // coercible string can be more right-ward without the same terminus.
  7372. let next
  7373. while ((next = re[t.COERCERTL].exec(version)) &&
  7374. (!match || match.index + match[0].length !== version.length)
  7375. ) {
  7376. if (!match ||
  7377. next.index + next[0].length !== match.index + match[0].length) {
  7378. match = next
  7379. }
  7380. re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
  7381. }
  7382. // leave it in a clean state
  7383. re[t.COERCERTL].lastIndex = -1
  7384. }
  7385. if (match === null)
  7386. return null
  7387. return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
  7388. }
  7389. module.exports = coerce
  7390. /***/ }),
  7391. /* 70 */
  7392. /***/ (function(module, exports, __webpack_require__) {
  7393. const ANY = Symbol('SemVer ANY')
  7394. // hoisted class for cyclic dependency
  7395. class Comparator {
  7396. static get ANY () {
  7397. return ANY
  7398. }
  7399. constructor (comp, options) {
  7400. if (!options || typeof options !== 'object') {
  7401. options = {
  7402. loose: !!options,
  7403. includePrerelease: false
  7404. }
  7405. }
  7406. if (comp instanceof Comparator) {
  7407. if (comp.loose === !!options.loose) {
  7408. return comp
  7409. } else {
  7410. comp = comp.value
  7411. }
  7412. }
  7413. debug('comparator', comp, options)
  7414. this.options = options
  7415. this.loose = !!options.loose
  7416. this.parse(comp)
  7417. if (this.semver === ANY) {
  7418. this.value = ''
  7419. } else {
  7420. this.value = this.operator + this.semver.version
  7421. }
  7422. debug('comp', this)
  7423. }
  7424. parse (comp) {
  7425. const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
  7426. const m = comp.match(r)
  7427. if (!m) {
  7428. throw new TypeError(`Invalid comparator: ${comp}`)
  7429. }
  7430. this.operator = m[1] !== undefined ? m[1] : ''
  7431. if (this.operator === '=') {
  7432. this.operator = ''
  7433. }
  7434. // if it literally is just '>' or '' then allow anything.
  7435. if (!m[2]) {
  7436. this.semver = ANY
  7437. } else {
  7438. this.semver = new SemVer(m[2], this.options.loose)
  7439. }
  7440. }
  7441. toString () {
  7442. return this.value
  7443. }
  7444. test (version) {
  7445. debug('Comparator.test', version, this.options.loose)
  7446. if (this.semver === ANY || version === ANY) {
  7447. return true
  7448. }
  7449. if (typeof version === 'string') {
  7450. try {
  7451. version = new SemVer(version, this.options)
  7452. } catch (er) {
  7453. return false
  7454. }
  7455. }
  7456. return cmp(version, this.operator, this.semver, this.options)
  7457. }
  7458. intersects (comp, options) {
  7459. if (!(comp instanceof Comparator)) {
  7460. throw new TypeError('a Comparator is required')
  7461. }
  7462. if (!options || typeof options !== 'object') {
  7463. options = {
  7464. loose: !!options,
  7465. includePrerelease: false
  7466. }
  7467. }
  7468. if (this.operator === '') {
  7469. if (this.value === '') {
  7470. return true
  7471. }
  7472. return new Range(comp.value, options).test(this.value)
  7473. } else if (comp.operator === '') {
  7474. if (comp.value === '') {
  7475. return true
  7476. }
  7477. return new Range(this.value, options).test(comp.semver)
  7478. }
  7479. const sameDirectionIncreasing =
  7480. (this.operator === '>=' || this.operator === '>') &&
  7481. (comp.operator === '>=' || comp.operator === '>')
  7482. const sameDirectionDecreasing =
  7483. (this.operator === '<=' || this.operator === '<') &&
  7484. (comp.operator === '<=' || comp.operator === '<')
  7485. const sameSemVer = this.semver.version === comp.semver.version
  7486. const differentDirectionsInclusive =
  7487. (this.operator === '>=' || this.operator === '<=') &&
  7488. (comp.operator === '>=' || comp.operator === '<=')
  7489. const oppositeDirectionsLessThan =
  7490. cmp(this.semver, '<', comp.semver, options) &&
  7491. (this.operator === '>=' || this.operator === '>') &&
  7492. (comp.operator === '<=' || comp.operator === '<')
  7493. const oppositeDirectionsGreaterThan =
  7494. cmp(this.semver, '>', comp.semver, options) &&
  7495. (this.operator === '<=' || this.operator === '<') &&
  7496. (comp.operator === '>=' || comp.operator === '>')
  7497. return (
  7498. sameDirectionIncreasing ||
  7499. sameDirectionDecreasing ||
  7500. (sameSemVer && differentDirectionsInclusive) ||
  7501. oppositeDirectionsLessThan ||
  7502. oppositeDirectionsGreaterThan
  7503. )
  7504. }
  7505. }
  7506. module.exports = Comparator
  7507. const {re, t} = __webpack_require__(42)
  7508. const cmp = __webpack_require__(68)
  7509. const debug = __webpack_require__(44)
  7510. const SemVer = __webpack_require__(45)
  7511. const Range = __webpack_require__(71)
  7512. /***/ }),
  7513. /* 71 */
  7514. /***/ (function(module, exports, __webpack_require__) {
  7515. // hoisted class for cyclic dependency
  7516. class Range {
  7517. constructor (range, options) {
  7518. if (!options || typeof options !== 'object') {
  7519. options = {
  7520. loose: !!options,
  7521. includePrerelease: false
  7522. }
  7523. }
  7524. if (range instanceof Range) {
  7525. if (
  7526. range.loose === !!options.loose &&
  7527. range.includePrerelease === !!options.includePrerelease
  7528. ) {
  7529. return range
  7530. } else {
  7531. return new Range(range.raw, options)
  7532. }
  7533. }
  7534. if (range instanceof Comparator) {
  7535. // just put it in the set and return
  7536. this.raw = range.value
  7537. this.set = [[range]]
  7538. this.format()
  7539. return this
  7540. }
  7541. this.options = options
  7542. this.loose = !!options.loose
  7543. this.includePrerelease = !!options.includePrerelease
  7544. // First, split based on boolean or ||
  7545. this.raw = range
  7546. this.set = range
  7547. .split(/\s*\|\|\s*/)
  7548. // map the range to a 2d array of comparators
  7549. .map(range => this.parseRange(range.trim()))
  7550. // throw out any comparator lists that are empty
  7551. // this generally means that it was not a valid range, which is allowed
  7552. // in loose mode, but will still throw if the WHOLE range is invalid.
  7553. .filter(c => c.length)
  7554. if (!this.set.length) {
  7555. throw new TypeError(`Invalid SemVer Range: ${range}`)
  7556. }
  7557. this.format()
  7558. }
  7559. format () {
  7560. this.range = this.set
  7561. .map((comps) => {
  7562. return comps.join(' ').trim()
  7563. })
  7564. .join('||')
  7565. .trim()
  7566. return this.range
  7567. }
  7568. toString () {
  7569. return this.range
  7570. }
  7571. parseRange (range) {
  7572. const loose = this.options.loose
  7573. range = range.trim()
  7574. // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
  7575. const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
  7576. range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
  7577. debug('hyphen replace', range)
  7578. // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
  7579. range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
  7580. debug('comparator trim', range, re[t.COMPARATORTRIM])
  7581. // `~ 1.2.3` => `~1.2.3`
  7582. range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
  7583. // `^ 1.2.3` => `^1.2.3`
  7584. range = range.replace(re[t.CARETTRIM], caretTrimReplace)
  7585. // normalize spaces
  7586. range = range.split(/\s+/).join(' ')
  7587. // At this point, the range is completely trimmed and
  7588. // ready to be split into comparators.
  7589. const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
  7590. return range
  7591. .split(' ')
  7592. .map(comp => parseComparator(comp, this.options))
  7593. .join(' ')
  7594. .split(/\s+/)
  7595. .map(comp => replaceGTE0(comp, this.options))
  7596. // in loose mode, throw out any that are not valid comparators
  7597. .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true)
  7598. .map(comp => new Comparator(comp, this.options))
  7599. }
  7600. intersects (range, options) {
  7601. if (!(range instanceof Range)) {
  7602. throw new TypeError('a Range is required')
  7603. }
  7604. return this.set.some((thisComparators) => {
  7605. return (
  7606. isSatisfiable(thisComparators, options) &&
  7607. range.set.some((rangeComparators) => {
  7608. return (
  7609. isSatisfiable(rangeComparators, options) &&
  7610. thisComparators.every((thisComparator) => {
  7611. return rangeComparators.every((rangeComparator) => {
  7612. return thisComparator.intersects(rangeComparator, options)
  7613. })
  7614. })
  7615. )
  7616. })
  7617. )
  7618. })
  7619. }
  7620. // if ANY of the sets match ALL of its comparators, then pass
  7621. test (version) {
  7622. if (!version) {
  7623. return false
  7624. }
  7625. if (typeof version === 'string') {
  7626. try {
  7627. version = new SemVer(version, this.options)
  7628. } catch (er) {
  7629. return false
  7630. }
  7631. }
  7632. for (let i = 0; i < this.set.length; i++) {
  7633. if (testSet(this.set[i], version, this.options)) {
  7634. return true
  7635. }
  7636. }
  7637. return false
  7638. }
  7639. }
  7640. module.exports = Range
  7641. const Comparator = __webpack_require__(70)
  7642. const debug = __webpack_require__(44)
  7643. const SemVer = __webpack_require__(45)
  7644. const {
  7645. re,
  7646. t,
  7647. comparatorTrimReplace,
  7648. tildeTrimReplace,
  7649. caretTrimReplace
  7650. } = __webpack_require__(42)
  7651. // take a set of comparators and determine whether there
  7652. // exists a version which can satisfy it
  7653. const isSatisfiable = (comparators, options) => {
  7654. let result = true
  7655. const remainingComparators = comparators.slice()
  7656. let testComparator = remainingComparators.pop()
  7657. while (result && remainingComparators.length) {
  7658. result = remainingComparators.every((otherComparator) => {
  7659. return testComparator.intersects(otherComparator, options)
  7660. })
  7661. testComparator = remainingComparators.pop()
  7662. }
  7663. return result
  7664. }
  7665. // comprised of xranges, tildes, stars, and gtlt's at this point.
  7666. // already replaced the hyphen ranges
  7667. // turn into a set of JUST comparators.
  7668. const parseComparator = (comp, options) => {
  7669. debug('comp', comp, options)
  7670. comp = replaceCarets(comp, options)
  7671. debug('caret', comp)
  7672. comp = replaceTildes(comp, options)
  7673. debug('tildes', comp)
  7674. comp = replaceXRanges(comp, options)
  7675. debug('xrange', comp)
  7676. comp = replaceStars(comp, options)
  7677. debug('stars', comp)
  7678. return comp
  7679. }
  7680. const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
  7681. // ~, ~> --> * (any, kinda silly)
  7682. // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
  7683. // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
  7684. // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
  7685. // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
  7686. // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
  7687. const replaceTildes = (comp, options) =>
  7688. comp.trim().split(/\s+/).map((comp) => {
  7689. return replaceTilde(comp, options)
  7690. }).join(' ')
  7691. const replaceTilde = (comp, options) => {
  7692. const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
  7693. return comp.replace(r, (_, M, m, p, pr) => {
  7694. debug('tilde', comp, _, M, m, p, pr)
  7695. let ret
  7696. if (isX(M)) {
  7697. ret = ''
  7698. } else if (isX(m)) {
  7699. ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
  7700. } else if (isX(p)) {
  7701. // ~1.2 == >=1.2.0 <1.3.0-0
  7702. ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
  7703. } else if (pr) {
  7704. debug('replaceTilde pr', pr)
  7705. ret = `>=${M}.${m}.${p}-${pr
  7706. } <${M}.${+m + 1}.0-0`
  7707. } else {
  7708. // ~1.2.3 == >=1.2.3 <1.3.0-0
  7709. ret = `>=${M}.${m}.${p
  7710. } <${M}.${+m + 1}.0-0`
  7711. }
  7712. debug('tilde return', ret)
  7713. return ret
  7714. })
  7715. }
  7716. // ^ --> * (any, kinda silly)
  7717. // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
  7718. // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
  7719. // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
  7720. // ^1.2.3 --> >=1.2.3 <2.0.0-0
  7721. // ^1.2.0 --> >=1.2.0 <2.0.0-0
  7722. const replaceCarets = (comp, options) =>
  7723. comp.trim().split(/\s+/).map((comp) => {
  7724. return replaceCaret(comp, options)
  7725. }).join(' ')
  7726. const replaceCaret = (comp, options) => {
  7727. debug('caret', comp, options)
  7728. const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
  7729. const z = options.includePrerelease ? '-0' : ''
  7730. return comp.replace(r, (_, M, m, p, pr) => {
  7731. debug('caret', comp, _, M, m, p, pr)
  7732. let ret
  7733. if (isX(M)) {
  7734. ret = ''
  7735. } else if (isX(m)) {
  7736. ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
  7737. } else if (isX(p)) {
  7738. if (M === '0') {
  7739. ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
  7740. } else {
  7741. ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
  7742. }
  7743. } else if (pr) {
  7744. debug('replaceCaret pr', pr)
  7745. if (M === '0') {
  7746. if (m === '0') {
  7747. ret = `>=${M}.${m}.${p}-${pr
  7748. } <${M}.${m}.${+p + 1}-0`
  7749. } else {
  7750. ret = `>=${M}.${m}.${p}-${pr
  7751. } <${M}.${+m + 1}.0-0`
  7752. }
  7753. } else {
  7754. ret = `>=${M}.${m}.${p}-${pr
  7755. } <${+M + 1}.0.0-0`
  7756. }
  7757. } else {
  7758. debug('no pr')
  7759. if (M === '0') {
  7760. if (m === '0') {
  7761. ret = `>=${M}.${m}.${p
  7762. }${z} <${M}.${m}.${+p + 1}-0`
  7763. } else {
  7764. ret = `>=${M}.${m}.${p
  7765. }${z} <${M}.${+m + 1}.0-0`
  7766. }
  7767. } else {
  7768. ret = `>=${M}.${m}.${p
  7769. } <${+M + 1}.0.0-0`
  7770. }
  7771. }
  7772. debug('caret return', ret)
  7773. return ret
  7774. })
  7775. }
  7776. const replaceXRanges = (comp, options) => {
  7777. debug('replaceXRanges', comp, options)
  7778. return comp.split(/\s+/).map((comp) => {
  7779. return replaceXRange(comp, options)
  7780. }).join(' ')
  7781. }
  7782. const replaceXRange = (comp, options) => {
  7783. comp = comp.trim()
  7784. const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
  7785. return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
  7786. debug('xRange', comp, ret, gtlt, M, m, p, pr)
  7787. const xM = isX(M)
  7788. const xm = xM || isX(m)
  7789. const xp = xm || isX(p)
  7790. const anyX = xp
  7791. if (gtlt === '=' && anyX) {
  7792. gtlt = ''
  7793. }
  7794. // if we're including prereleases in the match, then we need
  7795. // to fix this to -0, the lowest possible prerelease value
  7796. pr = options.includePrerelease ? '-0' : ''
  7797. if (xM) {
  7798. if (gtlt === '>' || gtlt === '<') {
  7799. // nothing is allowed
  7800. ret = '<0.0.0-0'
  7801. } else {
  7802. // nothing is forbidden
  7803. ret = '*'
  7804. }
  7805. } else if (gtlt && anyX) {
  7806. // we know patch is an x, because we have any x at all.
  7807. // replace X with 0
  7808. if (xm) {
  7809. m = 0
  7810. }
  7811. p = 0
  7812. if (gtlt === '>') {
  7813. // >1 => >=2.0.0
  7814. // >1.2 => >=1.3.0
  7815. gtlt = '>='
  7816. if (xm) {
  7817. M = +M + 1
  7818. m = 0
  7819. p = 0
  7820. } else {
  7821. m = +m + 1
  7822. p = 0
  7823. }
  7824. } else if (gtlt === '<=') {
  7825. // <=0.7.x is actually <0.8.0, since any 0.7.x should
  7826. // pass. Similarly, <=7.x is actually <8.0.0, etc.
  7827. gtlt = '<'
  7828. if (xm) {
  7829. M = +M + 1
  7830. } else {
  7831. m = +m + 1
  7832. }
  7833. }
  7834. if (gtlt === '<')
  7835. pr = '-0'
  7836. ret = `${gtlt + M}.${m}.${p}${pr}`
  7837. } else if (xm) {
  7838. ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
  7839. } else if (xp) {
  7840. ret = `>=${M}.${m}.0${pr
  7841. } <${M}.${+m + 1}.0-0`
  7842. }
  7843. debug('xRange return', ret)
  7844. return ret
  7845. })
  7846. }
  7847. // Because * is AND-ed with everything else in the comparator,
  7848. // and '' means "any version", just remove the *s entirely.
  7849. const replaceStars = (comp, options) => {
  7850. debug('replaceStars', comp, options)
  7851. // Looseness is ignored here. star is always as loose as it gets!
  7852. return comp.trim().replace(re[t.STAR], '')
  7853. }
  7854. const replaceGTE0 = (comp, options) => {
  7855. debug('replaceGTE0', comp, options)
  7856. return comp.trim()
  7857. .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
  7858. }
  7859. // This function is passed to string.replace(re[t.HYPHENRANGE])
  7860. // M, m, patch, prerelease, build
  7861. // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
  7862. // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
  7863. // 1.2 - 3.4 => >=1.2.0 <3.5.0-0
  7864. const hyphenReplace = incPr => ($0,
  7865. from, fM, fm, fp, fpr, fb,
  7866. to, tM, tm, tp, tpr, tb) => {
  7867. if (isX(fM)) {
  7868. from = ''
  7869. } else if (isX(fm)) {
  7870. from = `>=${fM}.0.0${incPr ? '-0' : ''}`
  7871. } else if (isX(fp)) {
  7872. from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
  7873. } else if (fpr) {
  7874. from = `>=${from}`
  7875. } else {
  7876. from = `>=${from}${incPr ? '-0' : ''}`
  7877. }
  7878. if (isX(tM)) {
  7879. to = ''
  7880. } else if (isX(tm)) {
  7881. to = `<${+tM + 1}.0.0-0`
  7882. } else if (isX(tp)) {
  7883. to = `<${tM}.${+tm + 1}.0-0`
  7884. } else if (tpr) {
  7885. to = `<=${tM}.${tm}.${tp}-${tpr}`
  7886. } else if (incPr) {
  7887. to = `<${tM}.${tm}.${+tp + 1}-0`
  7888. } else {
  7889. to = `<=${to}`
  7890. }
  7891. return (`${from} ${to}`).trim()
  7892. }
  7893. const testSet = (set, version, options) => {
  7894. for (let i = 0; i < set.length; i++) {
  7895. if (!set[i].test(version)) {
  7896. return false
  7897. }
  7898. }
  7899. if (version.prerelease.length && !options.includePrerelease) {
  7900. // Find the set of versions that are allowed to have prereleases
  7901. // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
  7902. // That should allow `1.2.3-pr.2` to pass.
  7903. // However, `1.2.4-alpha.notready` should NOT be allowed,
  7904. // even though it's within the range set by the comparators.
  7905. for (let i = 0; i < set.length; i++) {
  7906. debug(set[i].semver)
  7907. if (set[i].semver === Comparator.ANY) {
  7908. continue
  7909. }
  7910. if (set[i].semver.prerelease.length > 0) {
  7911. const allowed = set[i].semver
  7912. if (allowed.major === version.major &&
  7913. allowed.minor === version.minor &&
  7914. allowed.patch === version.patch) {
  7915. return true
  7916. }
  7917. }
  7918. }
  7919. // Version has a -pre, but it's not one of the ones we like.
  7920. return false
  7921. }
  7922. return true
  7923. }
  7924. /***/ }),
  7925. /* 72 */
  7926. /***/ (function(module, exports, __webpack_require__) {
  7927. const Range = __webpack_require__(71)
  7928. const satisfies = (version, range, options) => {
  7929. try {
  7930. range = new Range(range, options)
  7931. } catch (er) {
  7932. return false
  7933. }
  7934. return range.test(version)
  7935. }
  7936. module.exports = satisfies
  7937. /***/ }),
  7938. /* 73 */
  7939. /***/ (function(module, exports, __webpack_require__) {
  7940. const Range = __webpack_require__(71)
  7941. // Mostly just for testing and legacy API reasons
  7942. const toComparators = (range, options) =>
  7943. new Range(range, options).set
  7944. .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
  7945. module.exports = toComparators
  7946. /***/ }),
  7947. /* 74 */
  7948. /***/ (function(module, exports, __webpack_require__) {
  7949. const SemVer = __webpack_require__(45)
  7950. const Range = __webpack_require__(71)
  7951. const maxSatisfying = (versions, range, options) => {
  7952. let max = null
  7953. let maxSV = null
  7954. let rangeObj = null
  7955. try {
  7956. rangeObj = new Range(range, options)
  7957. } catch (er) {
  7958. return null
  7959. }
  7960. versions.forEach((v) => {
  7961. if (rangeObj.test(v)) {
  7962. // satisfies(v, range, options)
  7963. if (!max || maxSV.compare(v) === -1) {
  7964. // compare(max, v, true)
  7965. max = v
  7966. maxSV = new SemVer(max, options)
  7967. }
  7968. }
  7969. })
  7970. return max
  7971. }
  7972. module.exports = maxSatisfying
  7973. /***/ }),
  7974. /* 75 */
  7975. /***/ (function(module, exports, __webpack_require__) {
  7976. const SemVer = __webpack_require__(45)
  7977. const Range = __webpack_require__(71)
  7978. const minSatisfying = (versions, range, options) => {
  7979. let min = null
  7980. let minSV = null
  7981. let rangeObj = null
  7982. try {
  7983. rangeObj = new Range(range, options)
  7984. } catch (er) {
  7985. return null
  7986. }
  7987. versions.forEach((v) => {
  7988. if (rangeObj.test(v)) {
  7989. // satisfies(v, range, options)
  7990. if (!min || minSV.compare(v) === 1) {
  7991. // compare(min, v, true)
  7992. min = v
  7993. minSV = new SemVer(min, options)
  7994. }
  7995. }
  7996. })
  7997. return min
  7998. }
  7999. module.exports = minSatisfying
  8000. /***/ }),
  8001. /* 76 */
  8002. /***/ (function(module, exports, __webpack_require__) {
  8003. const SemVer = __webpack_require__(45)
  8004. const Range = __webpack_require__(71)
  8005. const gt = __webpack_require__(63)
  8006. const minVersion = (range, loose) => {
  8007. range = new Range(range, loose)
  8008. let minver = new SemVer('0.0.0')
  8009. if (range.test(minver)) {
  8010. return minver
  8011. }
  8012. minver = new SemVer('0.0.0-0')
  8013. if (range.test(minver)) {
  8014. return minver
  8015. }
  8016. minver = null
  8017. for (let i = 0; i < range.set.length; ++i) {
  8018. const comparators = range.set[i]
  8019. comparators.forEach((comparator) => {
  8020. // Clone to avoid manipulating the comparator's semver object.
  8021. const compver = new SemVer(comparator.semver.version)
  8022. switch (comparator.operator) {
  8023. case '>':
  8024. if (compver.prerelease.length === 0) {
  8025. compver.patch++
  8026. } else {
  8027. compver.prerelease.push(0)
  8028. }
  8029. compver.raw = compver.format()
  8030. /* fallthrough */
  8031. case '':
  8032. case '>=':
  8033. if (!minver || gt(minver, compver)) {
  8034. minver = compver
  8035. }
  8036. break
  8037. case '<':
  8038. case '<=':
  8039. /* Ignore maximum versions */
  8040. break
  8041. /* istanbul ignore next */
  8042. default:
  8043. throw new Error(`Unexpected operation: ${comparator.operator}`)
  8044. }
  8045. })
  8046. }
  8047. if (minver && range.test(minver)) {
  8048. return minver
  8049. }
  8050. return null
  8051. }
  8052. module.exports = minVersion
  8053. /***/ }),
  8054. /* 77 */
  8055. /***/ (function(module, exports, __webpack_require__) {
  8056. const Range = __webpack_require__(71)
  8057. const validRange = (range, options) => {
  8058. try {
  8059. // Return '*' instead of '' so that truthiness works.
  8060. // This will throw if it's invalid anyway
  8061. return new Range(range, options).range || '*'
  8062. } catch (er) {
  8063. return null
  8064. }
  8065. }
  8066. module.exports = validRange
  8067. /***/ }),
  8068. /* 78 */
  8069. /***/ (function(module, exports, __webpack_require__) {
  8070. const SemVer = __webpack_require__(45)
  8071. const Comparator = __webpack_require__(70)
  8072. const {ANY} = Comparator
  8073. const Range = __webpack_require__(71)
  8074. const satisfies = __webpack_require__(72)
  8075. const gt = __webpack_require__(63)
  8076. const lt = __webpack_require__(64)
  8077. const lte = __webpack_require__(67)
  8078. const gte = __webpack_require__(66)
  8079. const outside = (version, range, hilo, options) => {
  8080. version = new SemVer(version, options)
  8081. range = new Range(range, options)
  8082. let gtfn, ltefn, ltfn, comp, ecomp
  8083. switch (hilo) {
  8084. case '>':
  8085. gtfn = gt
  8086. ltefn = lte
  8087. ltfn = lt
  8088. comp = '>'
  8089. ecomp = '>='
  8090. break
  8091. case '<':
  8092. gtfn = lt
  8093. ltefn = gte
  8094. ltfn = gt
  8095. comp = '<'
  8096. ecomp = '<='
  8097. break
  8098. default:
  8099. throw new TypeError('Must provide a hilo val of "<" or ">"')
  8100. }
  8101. // If it satisifes the range it is not outside
  8102. if (satisfies(version, range, options)) {
  8103. return false
  8104. }
  8105. // From now on, variable terms are as if we're in "gtr" mode.
  8106. // but note that everything is flipped for the "ltr" function.
  8107. for (let i = 0; i < range.set.length; ++i) {
  8108. const comparators = range.set[i]
  8109. let high = null
  8110. let low = null
  8111. comparators.forEach((comparator) => {
  8112. if (comparator.semver === ANY) {
  8113. comparator = new Comparator('>=0.0.0')
  8114. }
  8115. high = high || comparator
  8116. low = low || comparator
  8117. if (gtfn(comparator.semver, high.semver, options)) {
  8118. high = comparator
  8119. } else if (ltfn(comparator.semver, low.semver, options)) {
  8120. low = comparator
  8121. }
  8122. })
  8123. // If the edge version comparator has a operator then our version
  8124. // isn't outside it
  8125. if (high.operator === comp || high.operator === ecomp) {
  8126. return false
  8127. }
  8128. // If the lowest version comparator has an operator and our version
  8129. // is less than it then it isn't higher than the range
  8130. if ((!low.operator || low.operator === comp) &&
  8131. ltefn(version, low.semver)) {
  8132. return false
  8133. } else if (low.operator === ecomp && ltfn(version, low.semver)) {
  8134. return false
  8135. }
  8136. }
  8137. return true
  8138. }
  8139. module.exports = outside
  8140. /***/ }),
  8141. /* 79 */
  8142. /***/ (function(module, exports, __webpack_require__) {
  8143. // Determine if version is greater than all the versions possible in the range.
  8144. const outside = __webpack_require__(78)
  8145. const gtr = (version, range, options) => outside(version, range, '>', options)
  8146. module.exports = gtr
  8147. /***/ }),
  8148. /* 80 */
  8149. /***/ (function(module, exports, __webpack_require__) {
  8150. const outside = __webpack_require__(78)
  8151. // Determine if version is less than all the versions possible in the range
  8152. const ltr = (version, range, options) => outside(version, range, '<', options)
  8153. module.exports = ltr
  8154. /***/ }),
  8155. /* 81 */
  8156. /***/ (function(module, exports, __webpack_require__) {
  8157. const Range = __webpack_require__(71)
  8158. const intersects = (r1, r2, options) => {
  8159. r1 = new Range(r1, options)
  8160. r2 = new Range(r2, options)
  8161. return r1.intersects(r2)
  8162. }
  8163. module.exports = intersects
  8164. /***/ }),
  8165. /* 82 */
  8166. /***/ (function(module, exports, __webpack_require__) {
  8167. // given a set of versions and a range, create a "simplified" range
  8168. // that includes the same versions that the original range does
  8169. // If the original range is shorter than the simplified one, return that.
  8170. const satisfies = __webpack_require__(72)
  8171. const compare = __webpack_require__(53)
  8172. module.exports = (versions, range, options) => {
  8173. const set = []
  8174. let min = null
  8175. let prev = null
  8176. const v = versions.sort((a, b) => compare(a, b, options))
  8177. for (const version of v) {
  8178. const included = satisfies(version, range, options)
  8179. if (included) {
  8180. prev = version
  8181. if (!min)
  8182. min = version
  8183. } else {
  8184. if (prev) {
  8185. set.push([min, prev])
  8186. }
  8187. prev = null
  8188. min = null
  8189. }
  8190. }
  8191. if (min)
  8192. set.push([min, null])
  8193. const ranges = []
  8194. for (const [min, max] of set) {
  8195. if (min === max)
  8196. ranges.push(min)
  8197. else if (!max && min === v[0])
  8198. ranges.push('*')
  8199. else if (!max)
  8200. ranges.push(`>=${min}`)
  8201. else if (min === v[0])
  8202. ranges.push(`<=${max}`)
  8203. else
  8204. ranges.push(`${min} - ${max}`)
  8205. }
  8206. const simplified = ranges.join(' || ')
  8207. const original = typeof range.raw === 'string' ? range.raw : String(range)
  8208. return simplified.length < original.length ? simplified : range
  8209. }
  8210. /***/ }),
  8211. /* 83 */
  8212. /***/ (function(module, exports, __webpack_require__) {
  8213. const Range = __webpack_require__(71)
  8214. const { ANY } = __webpack_require__(70)
  8215. const satisfies = __webpack_require__(72)
  8216. const compare = __webpack_require__(53)
  8217. // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
  8218. // - Every simple range `r1, r2, ...` is a subset of some `R1, R2, ...`
  8219. //
  8220. // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
  8221. // - If c is only the ANY comparator
  8222. // - If C is only the ANY comparator, return true
  8223. // - Else return false
  8224. // - Let EQ be the set of = comparators in c
  8225. // - If EQ is more than one, return true (null set)
  8226. // - Let GT be the highest > or >= comparator in c
  8227. // - Let LT be the lowest < or <= comparator in c
  8228. // - If GT and LT, and GT.semver > LT.semver, return true (null set)
  8229. // - If EQ
  8230. // - If GT, and EQ does not satisfy GT, return true (null set)
  8231. // - If LT, and EQ does not satisfy LT, return true (null set)
  8232. // - If EQ satisfies every C, return true
  8233. // - Else return false
  8234. // - If GT
  8235. // - If GT is lower than any > or >= comp in C, return false
  8236. // - If GT is >=, and GT.semver does not satisfy every C, return false
  8237. // - If LT
  8238. // - If LT.semver is greater than that of any > comp in C, return false
  8239. // - If LT is <=, and LT.semver does not satisfy every C, return false
  8240. // - If any C is a = range, and GT or LT are set, return false
  8241. // - Else return true
  8242. const subset = (sub, dom, options) => {
  8243. sub = new Range(sub, options)
  8244. dom = new Range(dom, options)
  8245. let sawNonNull = false
  8246. OUTER: for (const simpleSub of sub.set) {
  8247. for (const simpleDom of dom.set) {
  8248. const isSub = simpleSubset(simpleSub, simpleDom, options)
  8249. sawNonNull = sawNonNull || isSub !== null
  8250. if (isSub)
  8251. continue OUTER
  8252. }
  8253. // the null set is a subset of everything, but null simple ranges in
  8254. // a complex range should be ignored. so if we saw a non-null range,
  8255. // then we know this isn't a subset, but if EVERY simple range was null,
  8256. // then it is a subset.
  8257. if (sawNonNull)
  8258. return false
  8259. }
  8260. return true
  8261. }
  8262. const simpleSubset = (sub, dom, options) => {
  8263. if (sub.length === 1 && sub[0].semver === ANY)
  8264. return dom.length === 1 && dom[0].semver === ANY
  8265. const eqSet = new Set()
  8266. let gt, lt
  8267. for (const c of sub) {
  8268. if (c.operator === '>' || c.operator === '>=')
  8269. gt = higherGT(gt, c, options)
  8270. else if (c.operator === '<' || c.operator === '<=')
  8271. lt = lowerLT(lt, c, options)
  8272. else
  8273. eqSet.add(c.semver)
  8274. }
  8275. if (eqSet.size > 1)
  8276. return null
  8277. let gtltComp
  8278. if (gt && lt) {
  8279. gtltComp = compare(gt.semver, lt.semver, options)
  8280. if (gtltComp > 0)
  8281. return null
  8282. else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<='))
  8283. return null
  8284. }
  8285. // will iterate one or zero times
  8286. for (const eq of eqSet) {
  8287. if (gt && !satisfies(eq, String(gt), options))
  8288. return null
  8289. if (lt && !satisfies(eq, String(lt), options))
  8290. return null
  8291. for (const c of dom) {
  8292. if (!satisfies(eq, String(c), options))
  8293. return false
  8294. }
  8295. return true
  8296. }
  8297. let higher, lower
  8298. let hasDomLT, hasDomGT
  8299. for (const c of dom) {
  8300. hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
  8301. hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
  8302. if (gt) {
  8303. if (c.operator === '>' || c.operator === '>=') {
  8304. higher = higherGT(gt, c, options)
  8305. if (higher === c)
  8306. return false
  8307. } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options))
  8308. return false
  8309. }
  8310. if (lt) {
  8311. if (c.operator === '<' || c.operator === '<=') {
  8312. lower = lowerLT(lt, c, options)
  8313. if (lower === c)
  8314. return false
  8315. } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options))
  8316. return false
  8317. }
  8318. if (!c.operator && (lt || gt) && gtltComp !== 0)
  8319. return false
  8320. }
  8321. // if there was a < or >, and nothing in the dom, then must be false
  8322. // UNLESS it was limited by another range in the other direction.
  8323. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
  8324. if (gt && hasDomLT && !lt && gtltComp !== 0)
  8325. return false
  8326. if (lt && hasDomGT && !gt && gtltComp !== 0)
  8327. return false
  8328. return true
  8329. }
  8330. // >=1.2.3 is lower than >1.2.3
  8331. const higherGT = (a, b, options) => {
  8332. if (!a)
  8333. return b
  8334. const comp = compare(a.semver, b.semver, options)
  8335. return comp > 0 ? a
  8336. : comp < 0 ? b
  8337. : b.operator === '>' && a.operator === '>=' ? b
  8338. : a
  8339. }
  8340. // <=1.2.3 is higher than <1.2.3
  8341. const lowerLT = (a, b, options) => {
  8342. if (!a)
  8343. return b
  8344. const comp = compare(a.semver, b.semver, options)
  8345. return comp < 0 ? a
  8346. : comp > 0 ? b
  8347. : b.operator === '<' && a.operator === '<=' ? b
  8348. : a
  8349. }
  8350. module.exports = subset
  8351. /***/ }),
  8352. /* 84 */
  8353. /***/ (function(module, exports, __webpack_require__) {
  8354. "use strict";
  8355. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  8356. if (k2 === undefined) k2 = k;
  8357. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  8358. }) : (function(o, m, k, k2) {
  8359. if (k2 === undefined) k2 = k;
  8360. o[k2] = m[k];
  8361. }));
  8362. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  8363. Object.defineProperty(o, "default", { enumerable: true, value: v });
  8364. }) : function(o, v) {
  8365. o["default"] = v;
  8366. });
  8367. var __importStar = (this && this.__importStar) || function (mod) {
  8368. if (mod && mod.__esModule) return mod;
  8369. var result = {};
  8370. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  8371. __setModuleDefault(result, mod);
  8372. return result;
  8373. };
  8374. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  8375. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  8376. return new (P || (P = Promise))(function (resolve, reject) {
  8377. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  8378. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  8379. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8380. step((generator = generator.apply(thisArg, _arguments || [])).next());
  8381. });
  8382. };
  8383. Object.defineProperty(exports, "__esModule", { value: true });
  8384. exports.applyCodeActionCommands = exports.applyCodeAction = exports.getEditForCodeAction = void 0;
  8385. /*---------------------------------------------------------------------------------------------
  8386. * Copyright (c) Microsoft Corporation. All rights reserved.
  8387. * Licensed under the MIT License. See License.txt in the project root for license information.
  8388. *--------------------------------------------------------------------------------------------*/
  8389. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  8390. const coc_nvim_1 = __webpack_require__(1);
  8391. const typeConverters = __importStar(__webpack_require__(37));
  8392. function getEditForCodeAction(client, action) {
  8393. return action.changes && action.changes.length
  8394. ? typeConverters.WorkspaceEdit.fromFileCodeEdits(client, action.changes)
  8395. : undefined;
  8396. }
  8397. exports.getEditForCodeAction = getEditForCodeAction;
  8398. function applyCodeAction(client, action) {
  8399. return __awaiter(this, void 0, void 0, function* () {
  8400. const workspaceEdit = getEditForCodeAction(client, action);
  8401. if (workspaceEdit) {
  8402. if (!(yield coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
  8403. return false;
  8404. }
  8405. }
  8406. return applyCodeActionCommands(client, action);
  8407. });
  8408. }
  8409. exports.applyCodeAction = applyCodeAction;
  8410. function applyCodeActionCommands(client, action) {
  8411. return __awaiter(this, void 0, void 0, function* () {
  8412. // make sure there is command
  8413. if (action.commands && action.commands.length) {
  8414. for (const command of action.commands) {
  8415. const response = yield client.execute('applyCodeActionCommand', { command }, vscode_languageserver_protocol_1.CancellationToken.None);
  8416. if (!response || response.type != 'response' || !response.body) {
  8417. return false;
  8418. }
  8419. }
  8420. }
  8421. return true;
  8422. });
  8423. }
  8424. exports.applyCodeActionCommands = applyCodeActionCommands;
  8425. /***/ }),
  8426. /* 85 */
  8427. /***/ (function(module, exports, __webpack_require__) {
  8428. "use strict";
  8429. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  8430. if (k2 === undefined) k2 = k;
  8431. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  8432. }) : (function(o, m, k, k2) {
  8433. if (k2 === undefined) k2 = k;
  8434. o[k2] = m[k];
  8435. }));
  8436. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  8437. Object.defineProperty(o, "default", { enumerable: true, value: v });
  8438. }) : function(o, v) {
  8439. o["default"] = v;
  8440. });
  8441. var __importStar = (this && this.__importStar) || function (mod) {
  8442. if (mod && mod.__esModule) return mod;
  8443. var result = {};
  8444. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  8445. __setModuleDefault(result, mod);
  8446. return result;
  8447. };
  8448. Object.defineProperty(exports, "__esModule", { value: true });
  8449. exports.getParameterListParts = exports.convertCompletionEntry = void 0;
  8450. /*---------------------------------------------------------------------------------------------
  8451. * Copyright (c) Microsoft Corporation. All rights reserved.
  8452. * Licensed under the MIT License. See License.txt in the project root for license information.
  8453. *--------------------------------------------------------------------------------------------*/
  8454. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  8455. const PConst = __importStar(__webpack_require__(39));
  8456. function convertCompletionEntry(tsEntry, uri, position, context) {
  8457. let label = tsEntry.name;
  8458. let sortText = tsEntry.sortText;
  8459. let preselect = false;
  8460. let detail;
  8461. if (tsEntry.isRecommended) {
  8462. preselect = true;
  8463. }
  8464. if (tsEntry.source) {
  8465. // De-prioritze auto-imports https://github.com/Microsoft/vscode/issues/40311
  8466. sortText = '\uffff' + sortText;
  8467. }
  8468. else {
  8469. sortText = tsEntry.sortText;
  8470. }
  8471. let kind = convertKind(tsEntry.kind);
  8472. let insertTextFormat = (context.enableCallCompletions &&
  8473. (kind === vscode_languageserver_protocol_1.CompletionItemKind.Function ||
  8474. kind === vscode_languageserver_protocol_1.CompletionItemKind.Method)) ? vscode_languageserver_protocol_1.InsertTextFormat.Snippet : vscode_languageserver_protocol_1.InsertTextFormat.PlainText;
  8475. let insertText = tsEntry.insertText;
  8476. let commitCharacters = getCommitCharacters(tsEntry, context);
  8477. let textEdit = null;
  8478. if (tsEntry.replacementSpan) {
  8479. let { start, end } = tsEntry.replacementSpan;
  8480. if (start.line == end.line) {
  8481. textEdit = {
  8482. range: vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1),
  8483. newText: insertText || label
  8484. };
  8485. }
  8486. }
  8487. if (tsEntry.kindModifiers) {
  8488. const kindModifiers = new Set(tsEntry.kindModifiers.split(/,|\s+/g));
  8489. if (kindModifiers.has(PConst.KindModifiers.optional)) {
  8490. insertText = label;
  8491. label += '?';
  8492. }
  8493. if (kindModifiers.has(PConst.KindModifiers.color)) {
  8494. kind = vscode_languageserver_protocol_1.CompletionItemKind.Color;
  8495. }
  8496. if (tsEntry.kind === PConst.Kind.script) {
  8497. for (const extModifier of PConst.KindModifiers.fileExtensionKindModifiers) {
  8498. if (kindModifiers.has(extModifier)) {
  8499. if (tsEntry.name.toLowerCase().endsWith(extModifier)) {
  8500. detail = tsEntry.name;
  8501. }
  8502. else {
  8503. detail = tsEntry.name + extModifier;
  8504. }
  8505. break;
  8506. }
  8507. }
  8508. }
  8509. }
  8510. return {
  8511. label,
  8512. insertText,
  8513. textEdit,
  8514. kind,
  8515. preselect,
  8516. insertTextFormat,
  8517. sortText,
  8518. commitCharacters,
  8519. detail,
  8520. data: {
  8521. uri,
  8522. position,
  8523. source: tsEntry.source || ''
  8524. }
  8525. };
  8526. }
  8527. exports.convertCompletionEntry = convertCompletionEntry;
  8528. function convertKind(kind) {
  8529. switch (kind) {
  8530. case PConst.Kind.primitiveType:
  8531. case PConst.Kind.keyword:
  8532. return vscode_languageserver_protocol_1.CompletionItemKind.Keyword;
  8533. case PConst.Kind.const:
  8534. return vscode_languageserver_protocol_1.CompletionItemKind.Constant;
  8535. case PConst.Kind.let:
  8536. case PConst.Kind.variable:
  8537. case PConst.Kind.localVariable:
  8538. case PConst.Kind.alias:
  8539. return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
  8540. case PConst.Kind.memberVariable:
  8541. case PConst.Kind.memberGetAccessor:
  8542. case PConst.Kind.memberSetAccessor:
  8543. return vscode_languageserver_protocol_1.CompletionItemKind.Field;
  8544. case PConst.Kind.function:
  8545. return vscode_languageserver_protocol_1.CompletionItemKind.Function;
  8546. case PConst.Kind.method:
  8547. case PConst.Kind.constructSignature:
  8548. case PConst.Kind.callSignature:
  8549. case PConst.Kind.indexSignature:
  8550. return vscode_languageserver_protocol_1.CompletionItemKind.Method;
  8551. case PConst.Kind.enum:
  8552. return vscode_languageserver_protocol_1.CompletionItemKind.Enum;
  8553. case PConst.Kind.module:
  8554. case PConst.Kind.externalModuleName:
  8555. return vscode_languageserver_protocol_1.CompletionItemKind.Module;
  8556. case PConst.Kind.class:
  8557. case PConst.Kind.type:
  8558. return vscode_languageserver_protocol_1.CompletionItemKind.Class;
  8559. case PConst.Kind.interface:
  8560. return vscode_languageserver_protocol_1.CompletionItemKind.Interface;
  8561. case PConst.Kind.warning:
  8562. case PConst.Kind.script:
  8563. return vscode_languageserver_protocol_1.CompletionItemKind.File;
  8564. case PConst.Kind.directory:
  8565. return vscode_languageserver_protocol_1.CompletionItemKind.Folder;
  8566. }
  8567. return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
  8568. }
  8569. function getCommitCharacters(tsEntry, context) {
  8570. if (context.isNewIdentifierLocation || !context.isInValidCommitCharacterContext) {
  8571. return undefined;
  8572. }
  8573. const commitCharacters = [];
  8574. switch (tsEntry.kind) {
  8575. case PConst.Kind.memberGetAccessor:
  8576. case PConst.Kind.memberSetAccessor:
  8577. case PConst.Kind.constructSignature:
  8578. case PConst.Kind.callSignature:
  8579. case PConst.Kind.indexSignature:
  8580. case PConst.Kind.enum:
  8581. case PConst.Kind.interface:
  8582. commitCharacters.push('.', ';');
  8583. break;
  8584. case PConst.Kind.module:
  8585. case PConst.Kind.alias:
  8586. case PConst.Kind.const:
  8587. case PConst.Kind.let:
  8588. case PConst.Kind.variable:
  8589. case PConst.Kind.localVariable:
  8590. case PConst.Kind.memberVariable:
  8591. case PConst.Kind.class:
  8592. case PConst.Kind.function:
  8593. case PConst.Kind.method:
  8594. case PConst.Kind.keyword:
  8595. case PConst.Kind.parameter:
  8596. commitCharacters.push('.', ',', ';');
  8597. if (context.enableCallCompletions) {
  8598. commitCharacters.push('(');
  8599. }
  8600. break;
  8601. }
  8602. return commitCharacters.length === 0 ? undefined : commitCharacters;
  8603. }
  8604. function getParameterListParts(displayParts) {
  8605. const parts = [];
  8606. let isInMethod = false;
  8607. let hasOptionalParameters = false;
  8608. let parenCount = 0;
  8609. let braceCount = 0;
  8610. outer: for (let i = 0; i < displayParts.length; ++i) {
  8611. const part = displayParts[i];
  8612. switch (part.kind) {
  8613. case PConst.DisplayPartKind.methodName:
  8614. case PConst.DisplayPartKind.functionName:
  8615. case PConst.DisplayPartKind.text:
  8616. case PConst.DisplayPartKind.propertyName:
  8617. if (parenCount === 0 && braceCount === 0) {
  8618. isInMethod = true;
  8619. }
  8620. break;
  8621. case PConst.DisplayPartKind.parameterName:
  8622. if (parenCount === 1 && braceCount === 0 && isInMethod) {
  8623. // Only take top level paren names
  8624. const next = displayParts[i + 1];
  8625. // Skip optional parameters
  8626. const nameIsFollowedByOptionalIndicator = next && next.text === '?';
  8627. if (!nameIsFollowedByOptionalIndicator) {
  8628. parts.push(part);
  8629. }
  8630. hasOptionalParameters = hasOptionalParameters || nameIsFollowedByOptionalIndicator;
  8631. }
  8632. break;
  8633. case PConst.DisplayPartKind.punctuation:
  8634. if (part.text === '(') {
  8635. ++parenCount;
  8636. }
  8637. else if (part.text === ')') {
  8638. --parenCount;
  8639. if (parenCount <= 0 && isInMethod) {
  8640. break outer;
  8641. }
  8642. }
  8643. else if (part.text === '...' && parenCount === 1) {
  8644. // Found rest parmeter. Do not fill in any further arguments
  8645. hasOptionalParameters = true;
  8646. break outer;
  8647. }
  8648. else if (part.text === '{') {
  8649. ++braceCount;
  8650. }
  8651. else if (part.text === '}') {
  8652. --braceCount;
  8653. }
  8654. break;
  8655. }
  8656. }
  8657. return { hasOptionalParameters, parts };
  8658. }
  8659. exports.getParameterListParts = getParameterListParts;
  8660. /***/ }),
  8661. /* 86 */
  8662. /***/ (function(module, exports, __webpack_require__) {
  8663. "use strict";
  8664. /*---------------------------------------------------------------------------------------------
  8665. * Copyright (c) Microsoft Corporation. All rights reserved.
  8666. * Licensed under the MIT License. See License.txt in the project root for license information.
  8667. *--------------------------------------------------------------------------------------------*/
  8668. Object.defineProperty(exports, "__esModule", { value: true });
  8669. exports.markdownDocumentation = exports.tagsMarkdownPreview = exports.plain = void 0;
  8670. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  8671. function getTagBodyText(tag) {
  8672. if (!tag.text) {
  8673. return undefined;
  8674. }
  8675. switch (tag.name) {
  8676. case 'example':
  8677. case 'default':
  8678. // Convert to markdown code block if it not already one
  8679. if (tag.text.match(/^\s*[~`]{3}/g)) {
  8680. return tag.text;
  8681. }
  8682. return '```\n' + tag.text + '\n```';
  8683. }
  8684. return tag.text;
  8685. }
  8686. function getTagDocumentation(tag) {
  8687. switch (tag.name) {
  8688. case 'param':
  8689. const body = (tag.text || '').split(/^([\w\.]+)\s*/);
  8690. if (body && body.length === 3) {
  8691. const param = body[1];
  8692. const doc = body[2];
  8693. const label = `*@${tag.name}* \`${param}\``;
  8694. if (!doc) {
  8695. return label;
  8696. }
  8697. return label + (doc.match(/\r\n|\n/g) ? '\n' + doc : ` — ${doc}`);
  8698. }
  8699. }
  8700. // Generic tag
  8701. const label = `*@${tag.name}*`;
  8702. const text = getTagBodyText(tag);
  8703. if (!text) {
  8704. return label;
  8705. }
  8706. return label + (text.match(/\r\n|\n/g) ? '\n' + text : ` — ${text}`);
  8707. }
  8708. function plain(parts) {
  8709. if (!parts || !parts.length)
  8710. return '';
  8711. return parts.map(part => part.text).join('');
  8712. }
  8713. exports.plain = plain;
  8714. function tagsMarkdownPreview(tags) {
  8715. return (tags || []).map(getTagDocumentation).join(' \n\n');
  8716. }
  8717. exports.tagsMarkdownPreview = tagsMarkdownPreview;
  8718. function markdownDocumentation(documentation, tags) {
  8719. let out = plain(documentation);
  8720. const tagsPreview = tagsMarkdownPreview(tags);
  8721. if (tagsPreview) {
  8722. out = out + ('\n\n' + tagsPreview);
  8723. }
  8724. return {
  8725. kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
  8726. value: out
  8727. };
  8728. }
  8729. exports.markdownDocumentation = markdownDocumentation;
  8730. /***/ }),
  8731. /* 87 */
  8732. /***/ (function(module, exports, __webpack_require__) {
  8733. "use strict";
  8734. Object.defineProperty(exports, "__esModule", { value: true });
  8735. class SnippetString {
  8736. constructor(value) {
  8737. this._tabstop = 1;
  8738. this.value = value || '';
  8739. }
  8740. static isSnippetString(thing) {
  8741. if (thing instanceof SnippetString) {
  8742. return true;
  8743. }
  8744. if (!thing) {
  8745. return false;
  8746. }
  8747. return typeof thing.value === 'string';
  8748. }
  8749. static _escape(value) {
  8750. return value.replace(/\$|}|\\/g, '\\$&');
  8751. }
  8752. appendText(str) {
  8753. this.value += SnippetString._escape(str);
  8754. return this;
  8755. }
  8756. appendTabstop(n = this._tabstop++) {
  8757. this.value += '$';
  8758. this.value += n;
  8759. return this;
  8760. }
  8761. appendPlaceholder(value, n = this._tabstop++) {
  8762. if (typeof value === 'function') {
  8763. const nested = new SnippetString();
  8764. nested._tabstop = this._tabstop;
  8765. value(nested);
  8766. this._tabstop = nested._tabstop;
  8767. value = nested.value;
  8768. }
  8769. else {
  8770. value = SnippetString._escape(value);
  8771. }
  8772. this.value += '${';
  8773. this.value += n;
  8774. this.value += ':';
  8775. this.value += value;
  8776. this.value += '}';
  8777. return this;
  8778. }
  8779. appendVariable(name, defaultValue) {
  8780. if (typeof defaultValue === 'function') {
  8781. const nested = new SnippetString();
  8782. nested._tabstop = this._tabstop;
  8783. defaultValue(nested);
  8784. this._tabstop = nested._tabstop;
  8785. defaultValue = nested.value;
  8786. }
  8787. else if (typeof defaultValue === 'string') {
  8788. defaultValue = defaultValue.replace(/\$|}/g, '\\$&');
  8789. }
  8790. this.value += '${';
  8791. this.value += name;
  8792. if (defaultValue) {
  8793. this.value += ':';
  8794. this.value += defaultValue;
  8795. }
  8796. this.value += '}';
  8797. return this;
  8798. }
  8799. }
  8800. exports.default = SnippetString;
  8801. /***/ }),
  8802. /* 88 */
  8803. /***/ (function(module, exports, __webpack_require__) {
  8804. "use strict";
  8805. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  8806. if (k2 === undefined) k2 = k;
  8807. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  8808. }) : (function(o, m, k, k2) {
  8809. if (k2 === undefined) k2 = k;
  8810. o[k2] = m[k];
  8811. }));
  8812. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  8813. Object.defineProperty(o, "default", { enumerable: true, value: v });
  8814. }) : function(o, v) {
  8815. o["default"] = v;
  8816. });
  8817. var __importStar = (this && this.__importStar) || function (mod) {
  8818. if (mod && mod.__esModule) return mod;
  8819. var result = {};
  8820. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  8821. __setModuleDefault(result, mod);
  8822. return result;
  8823. };
  8824. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  8825. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  8826. return new (P || (P = Promise))(function (resolve, reject) {
  8827. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  8828. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  8829. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8830. step((generator = generator.apply(thisArg, _arguments || [])).next());
  8831. });
  8832. };
  8833. Object.defineProperty(exports, "__esModule", { value: true });
  8834. const typeConverters = __importStar(__webpack_require__(37));
  8835. class TypeScriptDefinitionProvider {
  8836. constructor(client) {
  8837. this.client = client;
  8838. }
  8839. getSymbolLocations(definitionType, document, position, token) {
  8840. return __awaiter(this, void 0, void 0, function* () {
  8841. const filepath = this.client.toPath(document.uri);
  8842. if (!filepath) {
  8843. return undefined;
  8844. }
  8845. const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
  8846. try {
  8847. const response = yield this.client.execute(definitionType, args, token);
  8848. const locations = (response.type == 'response' && response.body) || [];
  8849. return locations.map(location => typeConverters.Location.fromTextSpan(this.client.toResource(location.file), location));
  8850. }
  8851. catch (_a) {
  8852. return [];
  8853. }
  8854. });
  8855. }
  8856. provideDefinition(document, position, token) {
  8857. return this.getSymbolLocations('definition', document, position, token);
  8858. }
  8859. provideTypeDefinition(document, position, token) {
  8860. return this.getSymbolLocations('typeDefinition', document, position, token);
  8861. }
  8862. provideImplementation(document, position, token) {
  8863. return this.getSymbolLocations('implementation', document, position, token);
  8864. }
  8865. }
  8866. exports.default = TypeScriptDefinitionProvider;
  8867. /***/ }),
  8868. /* 89 */
  8869. /***/ (function(module, exports, __webpack_require__) {
  8870. "use strict";
  8871. var __importDefault = (this && this.__importDefault) || function (mod) {
  8872. return (mod && mod.__esModule) ? mod : { "default": mod };
  8873. };
  8874. Object.defineProperty(exports, "__esModule", { value: true });
  8875. /*---------------------------------------------------------------------------------------------
  8876. * Copyright (c) Microsoft Corporation. All rights reserved.
  8877. * Licensed under the MIT License. See License.txt in the project root for license information.
  8878. *--------------------------------------------------------------------------------------------*/
  8879. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  8880. const coc_nvim_1 = __webpack_require__(1);
  8881. const api_1 = __importDefault(__webpack_require__(40));
  8882. const tsDirectives = [
  8883. {
  8884. value: '@ts-check',
  8885. description: 'Enables semantic checking in a JavaScript file. Must be at the top of a file.'
  8886. },
  8887. {
  8888. value: '@ts-nocheck',
  8889. description: 'Disables semantic checking in a JavaScript file. Must be at the top of a file.'
  8890. },
  8891. {
  8892. value: '@ts-ignore',
  8893. description: 'Suppresses @ts-check errors on the next line of a file.'
  8894. }
  8895. ];
  8896. const tsDirectives390 = [
  8897. ...tsDirectives,
  8898. {
  8899. value: '@ts-expect-error',
  8900. description: 'Suppresses @ts-check errors on the next line of a file, expecting at least one to exist.'
  8901. }
  8902. ];
  8903. class DirectiveCommentCompletionProvider {
  8904. constructor(client) {
  8905. this.client = client;
  8906. }
  8907. provideCompletionItems(document, position, _token, context) {
  8908. if (context.triggerCharacter != '@') {
  8909. return [];
  8910. }
  8911. const file = this.client.toPath(document.uri);
  8912. if (!file) {
  8913. return [];
  8914. }
  8915. const doc = coc_nvim_1.workspace.getDocument(document.uri);
  8916. const line = doc.getline(position.line);
  8917. const prefix = line.slice(0, position.character);
  8918. const match = prefix.match(/^\s*\/\/+\s?(@[a-zA-Z\-]*)?$/);
  8919. if (match) {
  8920. const directives = this.client.apiVersion.gte(api_1.default.v390)
  8921. ? tsDirectives390
  8922. : tsDirectives;
  8923. let items = directives.map(directive => {
  8924. const item = vscode_languageserver_protocol_1.CompletionItem.create(directive.value);
  8925. item.kind = vscode_languageserver_protocol_1.CompletionItemKind.Snippet;
  8926. item.detail = directive.description;
  8927. item.textEdit = {
  8928. range: vscode_languageserver_protocol_1.Range.create(position.line, Math.max(0, position.character - (match[1] ? match[1].length : 0)), position.line, position.character),
  8929. newText: directive.value
  8930. };
  8931. return item;
  8932. });
  8933. let res = {
  8934. isIncomplete: false,
  8935. items
  8936. };
  8937. res.startcol = doc.fixStartcol(position, ['@']);
  8938. return res;
  8939. }
  8940. return [];
  8941. }
  8942. }
  8943. exports.default = DirectiveCommentCompletionProvider;
  8944. /***/ }),
  8945. /* 90 */
  8946. /***/ (function(module, exports, __webpack_require__) {
  8947. "use strict";
  8948. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  8949. if (k2 === undefined) k2 = k;
  8950. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  8951. }) : (function(o, m, k, k2) {
  8952. if (k2 === undefined) k2 = k;
  8953. o[k2] = m[k];
  8954. }));
  8955. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  8956. Object.defineProperty(o, "default", { enumerable: true, value: v });
  8957. }) : function(o, v) {
  8958. o["default"] = v;
  8959. });
  8960. var __importStar = (this && this.__importStar) || function (mod) {
  8961. if (mod && mod.__esModule) return mod;
  8962. var result = {};
  8963. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  8964. __setModuleDefault(result, mod);
  8965. return result;
  8966. };
  8967. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  8968. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  8969. return new (P || (P = Promise))(function (resolve, reject) {
  8970. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  8971. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  8972. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8973. step((generator = generator.apply(thisArg, _arguments || [])).next());
  8974. });
  8975. };
  8976. Object.defineProperty(exports, "__esModule", { value: true });
  8977. /*---------------------------------------------------------------------------------------------
  8978. * Copyright (c) Microsoft Corporation. All rights reserved.
  8979. * Licensed under the MIT License. See License.txt in the project root for license information.
  8980. *--------------------------------------------------------------------------------------------*/
  8981. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  8982. const typeConverters = __importStar(__webpack_require__(37));
  8983. const arrays_1 = __webpack_require__(91);
  8984. class TypeScriptDocumentHighlightProvider {
  8985. constructor(client) {
  8986. this.client = client;
  8987. }
  8988. provideDocumentHighlights(resource, position, token) {
  8989. return __awaiter(this, void 0, void 0, function* () {
  8990. const file = this.client.toPath(resource.uri);
  8991. if (!file)
  8992. return [];
  8993. const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { filesToSearch: [file] });
  8994. try {
  8995. const response = yield this.client.execute('documentHighlights', args, token);
  8996. if (response.type !== 'response' || !response.body) {
  8997. return [];
  8998. }
  8999. return arrays_1.flatten(response.body
  9000. .filter(highlight => highlight.file === file)
  9001. .map(convertDocumentHighlight));
  9002. }
  9003. catch (_e) {
  9004. return [];
  9005. }
  9006. });
  9007. }
  9008. }
  9009. exports.default = TypeScriptDocumentHighlightProvider;
  9010. function convertDocumentHighlight(highlight) {
  9011. return highlight.highlightSpans.map(span => {
  9012. return {
  9013. range: typeConverters.Range.fromTextSpan(span),
  9014. kind: span.kind === 'writtenReference' ? vscode_languageserver_protocol_1.DocumentHighlightKind.Write : vscode_languageserver_protocol_1.DocumentHighlightKind.Read
  9015. };
  9016. });
  9017. }
  9018. /***/ }),
  9019. /* 91 */
  9020. /***/ (function(module, exports, __webpack_require__) {
  9021. "use strict";
  9022. Object.defineProperty(exports, "__esModule", { value: true });
  9023. exports.flatten = exports.equals = void 0;
  9024. /*---------------------------------------------------------------------------------------------
  9025. * Copyright (c) Microsoft Corporation. All rights reserved.
  9026. * Licensed under the MIT License. See License.txt in the project root for license information.
  9027. *--------------------------------------------------------------------------------------------*/
  9028. function equals(one, other, itemEquals = (a, b) => a === b) {
  9029. if (one.length !== other.length) {
  9030. return false;
  9031. }
  9032. for (let i = 0, len = one.length; i < len; i++) {
  9033. if (!itemEquals(one[i], other[i])) {
  9034. return false;
  9035. }
  9036. }
  9037. return true;
  9038. }
  9039. exports.equals = equals;
  9040. function flatten(arr) {
  9041. return [].concat.apply([], arr);
  9042. }
  9043. exports.flatten = flatten;
  9044. /***/ }),
  9045. /* 92 */
  9046. /***/ (function(module, exports, __webpack_require__) {
  9047. "use strict";
  9048. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  9049. if (k2 === undefined) k2 = k;
  9050. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  9051. }) : (function(o, m, k, k2) {
  9052. if (k2 === undefined) k2 = k;
  9053. o[k2] = m[k];
  9054. }));
  9055. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  9056. Object.defineProperty(o, "default", { enumerable: true, value: v });
  9057. }) : function(o, v) {
  9058. o["default"] = v;
  9059. });
  9060. var __importStar = (this && this.__importStar) || function (mod) {
  9061. if (mod && mod.__esModule) return mod;
  9062. var result = {};
  9063. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  9064. __setModuleDefault(result, mod);
  9065. return result;
  9066. };
  9067. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  9068. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  9069. return new (P || (P = Promise))(function (resolve, reject) {
  9070. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  9071. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  9072. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  9073. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9074. });
  9075. };
  9076. Object.defineProperty(exports, "__esModule", { value: true });
  9077. /*---------------------------------------------------------------------------------------------
  9078. * Copyright (c) Microsoft Corporation. All rights reserved.
  9079. * Licensed under the MIT License. See License.txt in the project root for license information.
  9080. *--------------------------------------------------------------------------------------------*/
  9081. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  9082. const PConst = __importStar(__webpack_require__(39));
  9083. const typeConverters = __importStar(__webpack_require__(37));
  9084. const getSymbolKind = (kind) => {
  9085. switch (kind) {
  9086. case PConst.Kind.module:
  9087. return vscode_languageserver_protocol_1.SymbolKind.Module;
  9088. case PConst.Kind.class:
  9089. return vscode_languageserver_protocol_1.SymbolKind.Class;
  9090. case PConst.Kind.enum:
  9091. return vscode_languageserver_protocol_1.SymbolKind.Enum;
  9092. case PConst.Kind.interface:
  9093. return vscode_languageserver_protocol_1.SymbolKind.Interface;
  9094. case PConst.Kind.method:
  9095. return vscode_languageserver_protocol_1.SymbolKind.Method;
  9096. case PConst.Kind.memberVariable:
  9097. return vscode_languageserver_protocol_1.SymbolKind.Property;
  9098. case PConst.Kind.memberGetAccessor:
  9099. return vscode_languageserver_protocol_1.SymbolKind.Property;
  9100. case PConst.Kind.memberSetAccessor:
  9101. return vscode_languageserver_protocol_1.SymbolKind.Property;
  9102. case PConst.Kind.variable:
  9103. return vscode_languageserver_protocol_1.SymbolKind.Variable;
  9104. case PConst.Kind.const:
  9105. return vscode_languageserver_protocol_1.SymbolKind.Variable;
  9106. case PConst.Kind.localVariable:
  9107. return vscode_languageserver_protocol_1.SymbolKind.Variable;
  9108. case PConst.Kind.variable:
  9109. return vscode_languageserver_protocol_1.SymbolKind.Variable;
  9110. case PConst.Kind.constructSignature:
  9111. case PConst.Kind.constructorImplementation:
  9112. case PConst.Kind.function:
  9113. case PConst.Kind.localFunction:
  9114. return vscode_languageserver_protocol_1.SymbolKind.Function;
  9115. }
  9116. return vscode_languageserver_protocol_1.SymbolKind.Variable;
  9117. };
  9118. class TypeScriptDocumentSymbolProvider {
  9119. constructor(client) {
  9120. this.client = client;
  9121. }
  9122. provideDocumentSymbols(resource, token) {
  9123. return __awaiter(this, void 0, void 0, function* () {
  9124. const filepath = this.client.toPath(resource.uri);
  9125. if (!filepath)
  9126. return [];
  9127. const args = {
  9128. file: filepath
  9129. };
  9130. try {
  9131. const response = yield this.client.execute('navtree', args, token);
  9132. if (response.type == 'response' && response.body) {
  9133. // The root represents the file. Ignore this when showing in the UI
  9134. const tree = response.body;
  9135. if (tree.childItems) {
  9136. const result = new Array();
  9137. tree.childItems.forEach(item => TypeScriptDocumentSymbolProvider.convertNavTree(result, item));
  9138. return result;
  9139. }
  9140. }
  9141. return [];
  9142. }
  9143. catch (e) {
  9144. return [];
  9145. }
  9146. });
  9147. }
  9148. static convertNavTree(bucket, item) {
  9149. let shouldInclude = TypeScriptDocumentSymbolProvider.shouldInclueEntry(item);
  9150. const children = new Set(item.childItems || []);
  9151. for (const span of item.spans) {
  9152. const range = typeConverters.Range.fromTextSpan(span);
  9153. const symbolInfo = vscode_languageserver_protocol_1.DocumentSymbol.create(item.text, '', getSymbolKind(item.kind), range, range);
  9154. symbolInfo.children = children.size > 0 ? [] : null;
  9155. for (const child of children) {
  9156. if (child.spans.some(span => !!containsRange(range, typeConverters.Range.fromTextSpan(span)))) {
  9157. const includedChild = TypeScriptDocumentSymbolProvider.convertNavTree(symbolInfo.children, child);
  9158. shouldInclude = shouldInclude || includedChild;
  9159. children.delete(child);
  9160. }
  9161. }
  9162. if (shouldInclude) {
  9163. bucket.push(symbolInfo);
  9164. }
  9165. }
  9166. return shouldInclude;
  9167. }
  9168. static shouldInclueEntry(item) {
  9169. if (item.kind === PConst.Kind.alias) {
  9170. return false;
  9171. }
  9172. return !!(item.text &&
  9173. item.text !== '<function>' &&
  9174. item.text !== '<class>');
  9175. }
  9176. }
  9177. exports.default = TypeScriptDocumentSymbolProvider;
  9178. function containsRange(range, otherRange) {
  9179. if (otherRange.start.line < range.start.line || otherRange.end.line < range.start.line) {
  9180. return false;
  9181. }
  9182. if (otherRange.start.line > range.end.line || otherRange.end.line > range.end.line) {
  9183. return false;
  9184. }
  9185. if (otherRange.start.line === range.start.line && otherRange.start.character < range.start.character) {
  9186. return false;
  9187. }
  9188. if (otherRange.end.line === range.end.line && otherRange.end.character > range.end.character) {
  9189. return false;
  9190. }
  9191. return true;
  9192. }
  9193. /***/ }),
  9194. /* 93 */
  9195. /***/ (function(module, exports, __webpack_require__) {
  9196. "use strict";
  9197. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  9198. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  9199. return new (P || (P = Promise))(function (resolve, reject) {
  9200. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  9201. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  9202. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  9203. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9204. });
  9205. };
  9206. var __importDefault = (this && this.__importDefault) || function (mod) {
  9207. return (mod && mod.__esModule) ? mod : { "default": mod };
  9208. };
  9209. Object.defineProperty(exports, "__esModule", { value: true });
  9210. /*---------------------------------------------------------------------------------------------
  9211. * Copyright (c) Microsoft Corporation. All rights reserved.
  9212. * Licensed under the MIT License. See License.txt in the project root for license information.
  9213. *--------------------------------------------------------------------------------------------*/
  9214. const coc_nvim_1 = __webpack_require__(1);
  9215. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  9216. const api_1 = __importDefault(__webpack_require__(40));
  9217. function objAreEqual(a, b) {
  9218. let keys = Object.keys(a);
  9219. for (let i = 0; i < keys.length; i++) { // tslint:disable-line
  9220. let key = keys[i];
  9221. if (a[key] !== b[key]) {
  9222. return false;
  9223. }
  9224. }
  9225. return true;
  9226. }
  9227. class FileConfigurationManager {
  9228. constructor(client) {
  9229. this.client = client;
  9230. this.cachedMap = new Map();
  9231. }
  9232. ensureConfigurationOptions(document, insertSpaces, tabSize) {
  9233. return __awaiter(this, void 0, void 0, function* () {
  9234. const file = this.client.toPath(document.uri);
  9235. let options = {
  9236. tabSize,
  9237. insertSpaces
  9238. };
  9239. let cachedOption = this.cachedMap.get(document.uri);
  9240. const currentOptions = this.getFileOptions(options, document);
  9241. if (cachedOption
  9242. && objAreEqual(cachedOption.formatOptions, currentOptions.formatOptions)
  9243. && objAreEqual(cachedOption.preferences, currentOptions.preferences))
  9244. return;
  9245. this.cachedMap.set(document.uri, currentOptions);
  9246. const args = Object.assign({ file }, currentOptions);
  9247. yield this.client.execute('configure', args, vscode_languageserver_protocol_1.CancellationToken.None);
  9248. });
  9249. }
  9250. ensureConfigurationForDocument(document) {
  9251. return __awaiter(this, void 0, void 0, function* () {
  9252. let opts = yield coc_nvim_1.workspace.getFormatOptions(document.uri);
  9253. return this.ensureConfigurationOptions(document, opts.insertSpaces, opts.tabSize);
  9254. });
  9255. }
  9256. reset() {
  9257. this.cachedMap.clear();
  9258. }
  9259. getLanguageConfiguration(languageId) {
  9260. return coc_nvim_1.workspace.getConfiguration(languageId);
  9261. }
  9262. isTypeScriptDocument(languageId) {
  9263. return languageId.startsWith('typescript');
  9264. }
  9265. formatEnabled(document) {
  9266. let { languageId, uri } = document;
  9267. let language = languageId.startsWith('typescript') ? 'typescript' : 'javascript';
  9268. const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
  9269. return config.get('enabled');
  9270. }
  9271. enableJavascript() {
  9272. const config = coc_nvim_1.workspace.getConfiguration('tsserver');
  9273. return !!config.get('enableJavascript');
  9274. }
  9275. getFileOptions(options, document) {
  9276. const lang = this.isTypeScriptDocument(document.languageId) ? 'typescript' : 'javascript';
  9277. return {
  9278. formatOptions: this.getFormatOptions(options, lang, document.uri),
  9279. preferences: this.getPreferences(lang, document.uri)
  9280. };
  9281. }
  9282. getFormatOptions(options, language, uri) {
  9283. const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
  9284. return {
  9285. tabSize: options.tabSize,
  9286. indentSize: options.tabSize,
  9287. convertTabsToSpaces: options.insertSpaces,
  9288. // We can use \n here since the editor normalizes later on to its line endings.
  9289. newLineCharacter: '\n',
  9290. insertSpaceAfterCommaDelimiter: config.get('insertSpaceAfterCommaDelimiter'),
  9291. insertSpaceAfterConstructor: config.get('insertSpaceAfterConstructor'),
  9292. insertSpaceAfterSemicolonInForStatements: config.get('insertSpaceAfterSemicolonInForStatements'),
  9293. insertSpaceBeforeAndAfterBinaryOperators: config.get('insertSpaceBeforeAndAfterBinaryOperators'),
  9294. insertSpaceAfterKeywordsInControlFlowStatements: config.get('insertSpaceAfterKeywordsInControlFlowStatements'),
  9295. insertSpaceAfterFunctionKeywordForAnonymousFunctions: config.get('insertSpaceAfterFunctionKeywordForAnonymousFunctions'),
  9296. insertSpaceBeforeFunctionParenthesis: config.get('insertSpaceBeforeFunctionParenthesis'),
  9297. insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis'),
  9298. insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets'),
  9299. insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces'),
  9300. insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces'),
  9301. insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces'),
  9302. insertSpaceAfterTypeAssertion: config.get('insertSpaceAfterTypeAssertion'),
  9303. placeOpenBraceOnNewLineForFunctions: config.get('placeOpenBraceOnNewLineForFunctions'),
  9304. placeOpenBraceOnNewLineForControlBlocks: config.get('placeOpenBraceOnNewLineForControlBlocks'),
  9305. semicolons: config.get('semicolons', undefined)
  9306. };
  9307. }
  9308. getCompleteOptions(languageId) {
  9309. const lang = this.isTypeScriptDocument(languageId) ? 'typescript' : 'javascript';
  9310. const config = coc_nvim_1.workspace.getConfiguration(`${lang}.suggest`);
  9311. return {
  9312. enabled: config.get('enabled', true),
  9313. names: config.get('names', true),
  9314. paths: config.get('paths', true),
  9315. completeFunctionCalls: config.get('completeFunctionCalls', true),
  9316. autoImports: config.get('autoImports', true),
  9317. includeAutomaticOptionalChainCompletions: config.get('includeAutomaticOptionalChainCompletions', true)
  9318. };
  9319. }
  9320. getPreferences(language, uri) {
  9321. if (this.client.apiVersion.lt(api_1.default.v290)) {
  9322. return {};
  9323. }
  9324. const config = coc_nvim_1.workspace.getConfiguration(`${language}.preferences`, uri);
  9325. // getImportModuleSpecifierEndingPreference available on ts 2.9.0
  9326. const preferences = {
  9327. quotePreference: this.getQuoteStyle(config),
  9328. importModuleSpecifierPreference: getImportModuleSpecifier(config),
  9329. importModuleSpecifierEnding: getImportModuleSpecifierEndingPreference(config),
  9330. allowTextChangesInNewFiles: uri.startsWith('file:'),
  9331. allowRenameOfImportPath: true,
  9332. providePrefixAndSuffixTextForRename: true,
  9333. };
  9334. return preferences;
  9335. }
  9336. getQuoteStyle(config) {
  9337. let quoteStyle = config.get('quoteStyle', 'auto');
  9338. if (this.client.apiVersion.gte(api_1.default.v333) || quoteStyle != 'auto')
  9339. return quoteStyle;
  9340. return 'single';
  9341. }
  9342. }
  9343. exports.default = FileConfigurationManager;
  9344. function getImportModuleSpecifier(config) {
  9345. let val = config.get('importModuleSpecifier');
  9346. switch (val) {
  9347. case 'relative':
  9348. return 'relative';
  9349. case 'non-relative':
  9350. return 'non-relative';
  9351. default:
  9352. return 'auto';
  9353. }
  9354. }
  9355. function getImportModuleSpecifierEndingPreference(config) {
  9356. switch (config.get('importModuleSpecifierEnding')) {
  9357. case 'minimal': return 'minimal';
  9358. case 'index': return 'index';
  9359. case 'js': return 'js';
  9360. default: return 'auto';
  9361. }
  9362. }
  9363. /***/ }),
  9364. /* 94 */
  9365. /***/ (function(module, exports, __webpack_require__) {
  9366. "use strict";
  9367. /*---------------------------------------------------------------------------------------------
  9368. * Copyright (c) Microsoft Corporation. All rights reserved.
  9369. * Licensed under the MIT License. See License.txt in the project root for license information.
  9370. *--------------------------------------------------------------------------------------------*/
  9371. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  9372. if (k2 === undefined) k2 = k;
  9373. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  9374. }) : (function(o, m, k, k2) {
  9375. if (k2 === undefined) k2 = k;
  9376. o[k2] = m[k];
  9377. }));
  9378. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  9379. Object.defineProperty(o, "default", { enumerable: true, value: v });
  9380. }) : function(o, v) {
  9381. o["default"] = v;
  9382. });
  9383. var __importStar = (this && this.__importStar) || function (mod) {
  9384. if (mod && mod.__esModule) return mod;
  9385. var result = {};
  9386. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  9387. __setModuleDefault(result, mod);
  9388. return result;
  9389. };
  9390. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  9391. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  9392. return new (P || (P = Promise))(function (resolve, reject) {
  9393. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  9394. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  9395. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  9396. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9397. });
  9398. };
  9399. Object.defineProperty(exports, "__esModule", { value: true });
  9400. const vscode_languageserver_types_1 = __webpack_require__(18);
  9401. const coc_nvim_1 = __webpack_require__(1);
  9402. const typeConverters = __importStar(__webpack_require__(37));
  9403. class TypeScriptFoldingProvider {
  9404. constructor(client) {
  9405. this.client = client;
  9406. }
  9407. provideFoldingRanges(document, _context, token) {
  9408. return __awaiter(this, void 0, void 0, function* () {
  9409. const file = this.client.toPath(document.uri);
  9410. if (!file) {
  9411. return;
  9412. }
  9413. const args = { file };
  9414. const res = yield this.client.execute('getOutliningSpans', args, token);
  9415. if (res.type != 'response') {
  9416. return;
  9417. }
  9418. const { body } = res;
  9419. if (!body) {
  9420. return;
  9421. }
  9422. return body
  9423. .map(span => this.convertOutliningSpan(span, document))
  9424. .filter(foldingRange => !!foldingRange);
  9425. });
  9426. }
  9427. convertOutliningSpan(span, document) {
  9428. const range = typeConverters.Range.fromTextSpan(span.textSpan);
  9429. const kind = TypeScriptFoldingProvider.getFoldingRangeKind(span);
  9430. // Workaround for #49904
  9431. if (span.kind === 'comment') {
  9432. let doc = coc_nvim_1.workspace.getDocument(document.uri);
  9433. const line = doc.getline(range.start.line);
  9434. if (line.match(/\/\/\s*#endregion/gi)) {
  9435. return undefined;
  9436. }
  9437. }
  9438. let { start, end } = range;
  9439. return vscode_languageserver_types_1.FoldingRange.create(start.line, end.line, start.character, end.character, kind);
  9440. }
  9441. static getFoldingRangeKind(span) {
  9442. switch (span.kind) {
  9443. case 'comment':
  9444. case 'region':
  9445. case 'imports':
  9446. case 'code':
  9447. return span.kind;
  9448. default:
  9449. return undefined;
  9450. }
  9451. }
  9452. }
  9453. exports.default = TypeScriptFoldingProvider;
  9454. /***/ }),
  9455. /* 95 */
  9456. /***/ (function(module, exports, __webpack_require__) {
  9457. "use strict";
  9458. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  9459. if (k2 === undefined) k2 = k;
  9460. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  9461. }) : (function(o, m, k, k2) {
  9462. if (k2 === undefined) k2 = k;
  9463. o[k2] = m[k];
  9464. }));
  9465. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  9466. Object.defineProperty(o, "default", { enumerable: true, value: v });
  9467. }) : function(o, v) {
  9468. o["default"] = v;
  9469. });
  9470. var __importStar = (this && this.__importStar) || function (mod) {
  9471. if (mod && mod.__esModule) return mod;
  9472. var result = {};
  9473. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  9474. __setModuleDefault(result, mod);
  9475. return result;
  9476. };
  9477. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  9478. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  9479. return new (P || (P = Promise))(function (resolve, reject) {
  9480. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  9481. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  9482. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  9483. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9484. });
  9485. };
  9486. Object.defineProperty(exports, "__esModule", { value: true });
  9487. /*---------------------------------------------------------------------------------------------
  9488. * Copyright (c) Microsoft Corporation. All rights reserved.
  9489. * Licensed under the MIT License. See License.txt in the project root for license information.
  9490. *--------------------------------------------------------------------------------------------*/
  9491. const coc_nvim_1 = __webpack_require__(1);
  9492. const typeConverters = __importStar(__webpack_require__(37));
  9493. class TypeScriptFormattingProvider {
  9494. constructor(client, formattingOptionsManager) {
  9495. this.client = client;
  9496. this.formattingOptionsManager = formattingOptionsManager;
  9497. }
  9498. enabled(document) {
  9499. return this.formattingOptionsManager.formatEnabled(document);
  9500. }
  9501. doFormat(document, options, args, token) {
  9502. return __awaiter(this, void 0, void 0, function* () {
  9503. if (!this.enabled(document))
  9504. return [];
  9505. yield this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize);
  9506. try {
  9507. const response = yield this.client.execute('format', args, token);
  9508. if (response.type == 'response' && response.body) {
  9509. let edits = response.body.map(typeConverters.TextEdit.fromCodeEdit);
  9510. return edits;
  9511. }
  9512. }
  9513. catch (_a) {
  9514. // noop
  9515. }
  9516. return [];
  9517. });
  9518. }
  9519. provideDocumentRangeFormattingEdits(document, range, options, token) {
  9520. return __awaiter(this, void 0, void 0, function* () {
  9521. if (!this.enabled(document))
  9522. return [];
  9523. const filepath = this.client.toPath(document.uri);
  9524. if (!filepath)
  9525. return [];
  9526. const args = {
  9527. file: filepath,
  9528. line: range.start.line + 1,
  9529. offset: range.start.character + 1,
  9530. endLine: range.end.line + 1,
  9531. endOffset: range.end.character + 1
  9532. };
  9533. return this.doFormat(document, options, args, token);
  9534. });
  9535. }
  9536. provideDocumentFormattingEdits(document, options, token) {
  9537. return __awaiter(this, void 0, void 0, function* () {
  9538. if (!this.enabled(document))
  9539. return [];
  9540. const filepath = this.client.toPath(document.uri);
  9541. if (!filepath)
  9542. return [];
  9543. const args = {
  9544. file: filepath,
  9545. line: 1,
  9546. offset: 1,
  9547. endLine: document.lineCount + 1,
  9548. endOffset: 1
  9549. };
  9550. return this.doFormat(document, options, args, token);
  9551. });
  9552. }
  9553. provideOnTypeFormattingEdits(document, position, ch, options, token) {
  9554. return __awaiter(this, void 0, void 0, function* () {
  9555. if (!this.enabled(document))
  9556. return [];
  9557. if (!this.client.configuration.formatOnType)
  9558. return [];
  9559. const file = this.client.toPath(document.uri);
  9560. if (!file)
  9561. return [];
  9562. yield this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize);
  9563. const doc = coc_nvim_1.workspace.getDocument(document.uri);
  9564. const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { key: ch });
  9565. try {
  9566. const res = yield this.client.execute('formatonkey', args, token);
  9567. if (res.type != 'response') {
  9568. return [];
  9569. }
  9570. const { body } = res;
  9571. const edits = body;
  9572. const result = [];
  9573. if (!edits) {
  9574. return result;
  9575. }
  9576. for (const edit of edits) {
  9577. const textEdit = typeConverters.TextEdit.fromCodeEdit(edit);
  9578. const range = textEdit.range;
  9579. // Work around for https://github.com/Microsoft/TypeScript/issues/6700.
  9580. // Check if we have an edit at the beginning of the line which only removes white spaces and leaves
  9581. // an empty line. Drop those edits
  9582. if (range.start.character === 0 &&
  9583. range.start.line === range.end.line &&
  9584. textEdit.newText === '') {
  9585. const lText = doc.getline(range.start.line);
  9586. // If the edit leaves something on the line keep the edit (note that the end character is exclusive).
  9587. // Keep it also if it removes something else than whitespace
  9588. if (lText.trim().length > 0 || lText.length > range.end.character) {
  9589. result.push(textEdit);
  9590. }
  9591. }
  9592. else {
  9593. result.push(textEdit);
  9594. }
  9595. }
  9596. return result;
  9597. }
  9598. catch (_a) {
  9599. // noop
  9600. }
  9601. return [];
  9602. });
  9603. }
  9604. }
  9605. exports.default = TypeScriptFormattingProvider;
  9606. /***/ }),
  9607. /* 96 */
  9608. /***/ (function(module, exports, __webpack_require__) {
  9609. "use strict";
  9610. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  9611. if (k2 === undefined) k2 = k;
  9612. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  9613. }) : (function(o, m, k, k2) {
  9614. if (k2 === undefined) k2 = k;
  9615. o[k2] = m[k];
  9616. }));
  9617. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  9618. Object.defineProperty(o, "default", { enumerable: true, value: v });
  9619. }) : function(o, v) {
  9620. o["default"] = v;
  9621. });
  9622. var __importStar = (this && this.__importStar) || function (mod) {
  9623. if (mod && mod.__esModule) return mod;
  9624. var result = {};
  9625. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  9626. __setModuleDefault(result, mod);
  9627. return result;
  9628. };
  9629. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  9630. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  9631. return new (P || (P = Promise))(function (resolve, reject) {
  9632. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  9633. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  9634. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  9635. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9636. });
  9637. };
  9638. Object.defineProperty(exports, "__esModule", { value: true });
  9639. const previewer_1 = __webpack_require__(86);
  9640. const typeConverters = __importStar(__webpack_require__(37));
  9641. class TypeScriptHoverProvider {
  9642. constructor(client) {
  9643. this.client = client;
  9644. }
  9645. provideHover(document, position, token) {
  9646. return __awaiter(this, void 0, void 0, function* () {
  9647. const filepath = this.client.toPath(document.uri);
  9648. if (!filepath) {
  9649. return undefined;
  9650. }
  9651. const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
  9652. try {
  9653. const response = yield this.client.interruptGetErr(() => this.client.execute('quickinfo', args, token));
  9654. if (response && response.type == 'response' && response.body) {
  9655. const data = response.body;
  9656. return {
  9657. contents: TypeScriptHoverProvider.getContents(data),
  9658. range: typeConverters.Range.fromTextSpan(data)
  9659. };
  9660. }
  9661. }
  9662. catch (e) {
  9663. // noop
  9664. }
  9665. return undefined;
  9666. });
  9667. }
  9668. static getContents(data) {
  9669. const parts = [];
  9670. if (data.displayString) {
  9671. parts.push({ language: 'typescript', value: data.displayString });
  9672. }
  9673. const tags = previewer_1.tagsMarkdownPreview(data.tags);
  9674. parts.push(data.documentation + (tags ? '\n\n' + tags : ''));
  9675. return parts;
  9676. }
  9677. }
  9678. exports.default = TypeScriptHoverProvider;
  9679. /***/ }),
  9680. /* 97 */
  9681. /***/ (function(module, exports, __webpack_require__) {
  9682. "use strict";
  9683. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  9684. if (k2 === undefined) k2 = k;
  9685. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  9686. }) : (function(o, m, k, k2) {
  9687. if (k2 === undefined) k2 = k;
  9688. o[k2] = m[k];
  9689. }));
  9690. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  9691. Object.defineProperty(o, "default", { enumerable: true, value: v });
  9692. }) : function(o, v) {
  9693. o["default"] = v;
  9694. });
  9695. var __importStar = (this && this.__importStar) || function (mod) {
  9696. if (mod && mod.__esModule) return mod;
  9697. var result = {};
  9698. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  9699. __setModuleDefault(result, mod);
  9700. return result;
  9701. };
  9702. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  9703. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  9704. return new (P || (P = Promise))(function (resolve, reject) {
  9705. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  9706. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  9707. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  9708. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9709. });
  9710. };
  9711. Object.defineProperty(exports, "__esModule", { value: true });
  9712. const PConst = __importStar(__webpack_require__(39));
  9713. const typeConverters = __importStar(__webpack_require__(37));
  9714. const baseCodeLensProvider_1 = __webpack_require__(35);
  9715. class TypeScriptImplementationsCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
  9716. resolveCodeLens(codeLens, token) {
  9717. return __awaiter(this, void 0, void 0, function* () {
  9718. let { uri } = codeLens.data;
  9719. let filepath = this.client.toPath(uri);
  9720. const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
  9721. try {
  9722. const response = yield this.client.execute('implementation', args, token, true);
  9723. if (response && response.type == 'response' && response.body) {
  9724. const locations = response.body
  9725. .map(reference => {
  9726. return {
  9727. uri: this.client.toResource(reference.file),
  9728. range: {
  9729. start: typeConverters.Position.fromLocation(reference.start),
  9730. end: {
  9731. line: reference.start.line,
  9732. character: 0
  9733. }
  9734. }
  9735. };
  9736. })
  9737. // Exclude original from implementations
  9738. .filter(location => !(location.uri.toString() === uri &&
  9739. location.range.start.line === codeLens.range.start.line &&
  9740. location.range.start.character ===
  9741. codeLens.range.start.character));
  9742. codeLens.command = this.getCommand(locations, codeLens);
  9743. return codeLens;
  9744. }
  9745. }
  9746. catch (_a) {
  9747. // noop
  9748. }
  9749. codeLens.command = {
  9750. title: '0 implementations',
  9751. command: ''
  9752. };
  9753. return codeLens;
  9754. });
  9755. }
  9756. getCommand(locations, codeLens) {
  9757. let { uri } = codeLens.data;
  9758. return {
  9759. title: this.getTitle(locations),
  9760. command: locations.length ? 'editor.action.showReferences' : '',
  9761. arguments: [uri, codeLens.range.start, locations]
  9762. };
  9763. }
  9764. getTitle(locations) {
  9765. return locations.length === 1 ? '1 implementation' : `${locations.length} implementations`;
  9766. }
  9767. extractSymbol(document, item, _parent) {
  9768. switch (item.kind) {
  9769. case PConst.Kind.interface:
  9770. return super.getSymbolRange(document, item);
  9771. case PConst.Kind.class:
  9772. case PConst.Kind.method:
  9773. case PConst.Kind.memberVariable:
  9774. case PConst.Kind.memberGetAccessor:
  9775. case PConst.Kind.memberSetAccessor:
  9776. if (item.kindModifiers.match(/\babstract\b/g)) {
  9777. return super.getSymbolRange(document, item);
  9778. }
  9779. break;
  9780. }
  9781. return null;
  9782. }
  9783. }
  9784. exports.default = TypeScriptImplementationsCodeLensProvider;
  9785. /***/ }),
  9786. /* 98 */
  9787. /***/ (function(module, exports, __webpack_require__) {
  9788. "use strict";
  9789. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  9790. if (k2 === undefined) k2 = k;
  9791. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  9792. }) : (function(o, m, k, k2) {
  9793. if (k2 === undefined) k2 = k;
  9794. o[k2] = m[k];
  9795. }));
  9796. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  9797. Object.defineProperty(o, "default", { enumerable: true, value: v });
  9798. }) : function(o, v) {
  9799. o["default"] = v;
  9800. });
  9801. var __importStar = (this && this.__importStar) || function (mod) {
  9802. if (mod && mod.__esModule) return mod;
  9803. var result = {};
  9804. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  9805. __setModuleDefault(result, mod);
  9806. return result;
  9807. };
  9808. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  9809. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  9810. return new (P || (P = Promise))(function (resolve, reject) {
  9811. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  9812. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  9813. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  9814. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9815. });
  9816. };
  9817. var __importDefault = (this && this.__importDefault) || function (mod) {
  9818. return (mod && mod.__esModule) ? mod : { "default": mod };
  9819. };
  9820. Object.defineProperty(exports, "__esModule", { value: true });
  9821. /*---------------------------------------------------------------------------------------------
  9822. * Copyright (c) Microsoft Corporation. All rights reserved.
  9823. * Licensed under the MIT License. See License.txt in the project root for license information.
  9824. *--------------------------------------------------------------------------------------------*/
  9825. const coc_nvim_1 = __webpack_require__(1);
  9826. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  9827. const api_1 = __importDefault(__webpack_require__(40));
  9828. const codeAction_1 = __webpack_require__(84);
  9829. const typeConverters = __importStar(__webpack_require__(37));
  9830. class ApplyCodeActionCommand {
  9831. constructor(client) {
  9832. this.client = client;
  9833. this.id = ApplyCodeActionCommand.ID;
  9834. }
  9835. execute(action) {
  9836. return __awaiter(this, void 0, void 0, function* () {
  9837. return codeAction_1.applyCodeActionCommands(this.client, action);
  9838. });
  9839. }
  9840. }
  9841. ApplyCodeActionCommand.ID = '_typescript.applyCodeActionCommand';
  9842. class ApplyFixAllCodeAction {
  9843. constructor(client) {
  9844. this.client = client;
  9845. this.id = ApplyFixAllCodeAction.ID;
  9846. }
  9847. execute(file, tsAction) {
  9848. return __awaiter(this, void 0, void 0, function* () {
  9849. if (!tsAction.fixId) {
  9850. return;
  9851. }
  9852. const args = {
  9853. scope: {
  9854. type: 'file',
  9855. args: { file }
  9856. },
  9857. fixId: tsAction.fixId
  9858. };
  9859. try {
  9860. const res = yield this.client.execute('getCombinedCodeFix', args, vscode_languageserver_protocol_1.CancellationToken.None);
  9861. if (res.type != 'response') {
  9862. return;
  9863. }
  9864. let { body } = res;
  9865. const edit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.changes);
  9866. yield coc_nvim_1.workspace.applyEdit(edit);
  9867. const token = vscode_languageserver_protocol_1.CancellationToken.None;
  9868. const { commands } = body;
  9869. if (commands && commands.length) {
  9870. for (const command of commands) {
  9871. yield this.client.execute('applyCodeActionCommand', { command }, token);
  9872. }
  9873. }
  9874. }
  9875. catch (_a) {
  9876. // noop
  9877. }
  9878. });
  9879. }
  9880. }
  9881. ApplyFixAllCodeAction.ID = '_typescript.applyFixAllCodeAction';
  9882. /**
  9883. * Unique set of diagnostics keyed on diagnostic range and error code.
  9884. */
  9885. class DiagnosticsSet {
  9886. constructor(_values) {
  9887. this._values = _values;
  9888. }
  9889. static from(diagnostics) {
  9890. const values = new Map();
  9891. for (const diagnostic of diagnostics) {
  9892. values.set(DiagnosticsSet.key(diagnostic), diagnostic);
  9893. }
  9894. return new DiagnosticsSet(values);
  9895. }
  9896. static key(diagnostic) {
  9897. const { start, end } = diagnostic.range;
  9898. return `${diagnostic.code}-${start.line},${start.character}-${end.line},${end.character}`;
  9899. }
  9900. get values() {
  9901. return this._values.values();
  9902. }
  9903. }
  9904. class SupportedCodeActionProvider {
  9905. constructor(client) {
  9906. this.client = client;
  9907. }
  9908. getFixableDiagnosticsForContext(context) {
  9909. return __awaiter(this, void 0, void 0, function* () {
  9910. const supportedActions = yield this.supportedCodeActions;
  9911. const fixableDiagnostics = DiagnosticsSet.from(context.diagnostics.filter(diagnostic => supportedActions.has(+diagnostic.code)));
  9912. return Array.from(fixableDiagnostics.values);
  9913. });
  9914. }
  9915. get supportedCodeActions() {
  9916. if (!this._supportedCodeActions) {
  9917. return new Promise((resolve, reject) => {
  9918. this.client.execute('getSupportedCodeFixes', null, vscode_languageserver_protocol_1.CancellationToken.None).then(res => {
  9919. if (res.type !== 'response') {
  9920. resolve(new Set());
  9921. return;
  9922. }
  9923. let codes = res.body.map(code => +code).filter(code => !isNaN(code));
  9924. resolve(new Set(codes));
  9925. }, reject);
  9926. });
  9927. }
  9928. return Promise.resolve(this._supportedCodeActions);
  9929. }
  9930. }
  9931. class TypeScriptQuickFixProvider {
  9932. constructor(client) {
  9933. this.client = client;
  9934. coc_nvim_1.commands.register(new ApplyCodeActionCommand(client));
  9935. coc_nvim_1.commands.register(new ApplyFixAllCodeAction(client));
  9936. this.supportedCodeActionProvider = new SupportedCodeActionProvider(client);
  9937. }
  9938. provideCodeActions(document, _range, context, token) {
  9939. return __awaiter(this, void 0, void 0, function* () {
  9940. if (!this.client.apiVersion.gte(api_1.default.v213)) {
  9941. return [];
  9942. }
  9943. const file = this.client.toPath(document.uri);
  9944. if (!file) {
  9945. return [];
  9946. }
  9947. const fixableDiagnostics = yield this.supportedCodeActionProvider.getFixableDiagnosticsForContext(context);
  9948. if (!fixableDiagnostics.length) {
  9949. return [];
  9950. }
  9951. if (this.client.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
  9952. return [];
  9953. }
  9954. const results = [];
  9955. for (const diagnostic of fixableDiagnostics) {
  9956. results.push(...(yield this.getFixesForDiagnostic(document, file, diagnostic, token)));
  9957. }
  9958. return results;
  9959. });
  9960. }
  9961. getFixesForDiagnostic(document, file, diagnostic, token) {
  9962. return __awaiter(this, void 0, void 0, function* () {
  9963. const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+diagnostic.code] });
  9964. const codeFixesResponse = yield this.client.execute('getCodeFixes', args, token);
  9965. if (codeFixesResponse.type != 'response') {
  9966. return [];
  9967. }
  9968. if (codeFixesResponse.body) {
  9969. const results = [];
  9970. for (const tsCodeFix of codeFixesResponse.body) {
  9971. results.push(...(yield this.getAllFixesForTsCodeAction(document, file, diagnostic, tsCodeFix)));
  9972. }
  9973. return results;
  9974. }
  9975. return [];
  9976. });
  9977. }
  9978. getAllFixesForTsCodeAction(document, file, diagnostic, tsAction) {
  9979. return __awaiter(this, void 0, void 0, function* () {
  9980. const singleFix = this.getSingleFixForTsCodeAction(diagnostic, tsAction);
  9981. const fixAll = yield this.getFixAllForTsCodeAction(document, file, diagnostic, tsAction);
  9982. return fixAll ? [singleFix, fixAll] : [singleFix];
  9983. });
  9984. }
  9985. getSingleFixForTsCodeAction(diagnostic, tsAction) {
  9986. const codeAction = {
  9987. title: tsAction.description,
  9988. kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
  9989. };
  9990. codeAction.edit = codeAction_1.getEditForCodeAction(this.client, tsAction);
  9991. codeAction.diagnostics = [diagnostic];
  9992. codeAction.isPrefered = true;
  9993. if (tsAction.commands) {
  9994. codeAction.command = {
  9995. command: ApplyCodeActionCommand.ID,
  9996. arguments: [tsAction],
  9997. title: tsAction.description
  9998. };
  9999. }
  10000. return codeAction;
  10001. }
  10002. getFixAllForTsCodeAction(document, file, diagnostic, tsAction) {
  10003. return __awaiter(this, void 0, void 0, function* () {
  10004. if (!tsAction.fixId || !this.client.apiVersion.gte(api_1.default.v270)) {
  10005. return undefined;
  10006. }
  10007. // Make sure there are multiple diagnostics of the same type in the file
  10008. if (!this.client.diagnosticsManager
  10009. .getDiagnostics(document.uri)
  10010. .some(x => x.code === diagnostic.code && x !== diagnostic)) {
  10011. return;
  10012. }
  10013. const action = {
  10014. title: tsAction.fixAllDescription || 'Fix all in file',
  10015. kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
  10016. };
  10017. action.diagnostics = [diagnostic];
  10018. action.command = {
  10019. command: ApplyFixAllCodeAction.ID,
  10020. arguments: [file, tsAction],
  10021. title: ''
  10022. };
  10023. return action;
  10024. });
  10025. }
  10026. }
  10027. exports.default = TypeScriptQuickFixProvider;
  10028. /***/ }),
  10029. /* 99 */
  10030. /***/ (function(module, exports, __webpack_require__) {
  10031. "use strict";
  10032. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  10033. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  10034. return new (P || (P = Promise))(function (resolve, reject) {
  10035. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  10036. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  10037. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  10038. step((generator = generator.apply(thisArg, _arguments || [])).next());
  10039. });
  10040. };
  10041. Object.defineProperty(exports, "__esModule", { value: true });
  10042. const coc_nvim_1 = __webpack_require__(1);
  10043. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  10044. const helper_1 = __webpack_require__(100);
  10045. class ImportFixProvider {
  10046. constructor(bufferSyncSupport) {
  10047. this.bufferSyncSupport = bufferSyncSupport;
  10048. }
  10049. provideCodeActions(document, _range, context, _token) {
  10050. return __awaiter(this, void 0, void 0, function* () {
  10051. if (this.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
  10052. return [];
  10053. }
  10054. let diagnostics = context.diagnostics.filter(d => d.code == 2304);
  10055. if (!diagnostics.length)
  10056. return [];
  10057. let edits = [];
  10058. let names = [];
  10059. let doc = coc_nvim_1.workspace.getDocument(document.uri);
  10060. let command;
  10061. for (const diagnostic of diagnostics) {
  10062. let { range } = diagnostic;
  10063. let line = doc.getline(range.start.line);
  10064. let name = line.slice(range.start.character, range.end.character);
  10065. if (names.indexOf(name) !== -1)
  10066. continue;
  10067. if (helper_1.nodeModules.indexOf(name) !== -1) {
  10068. names.push(name);
  10069. edits.push({
  10070. range: vscode_languageserver_protocol_1.Range.create(0, 0, 0, 0),
  10071. newText: `import ${name} from '${name}'\n`
  10072. });
  10073. command = 'tsserver.organizeImports';
  10074. }
  10075. }
  10076. let edit = {
  10077. changes: {
  10078. [document.uri]: edits
  10079. }
  10080. };
  10081. let cmd = null;
  10082. if (command)
  10083. cmd = {
  10084. title: `fix import`,
  10085. command: 'tsserver.organizeImports'
  10086. };
  10087. return [{
  10088. title: `Add import ${names.join(', ')}`,
  10089. edit,
  10090. command: cmd
  10091. }];
  10092. });
  10093. }
  10094. }
  10095. exports.default = ImportFixProvider;
  10096. /***/ }),
  10097. /* 100 */
  10098. /***/ (function(module, exports, __webpack_require__) {
  10099. "use strict";
  10100. Object.defineProperty(exports, "__esModule", { value: true });
  10101. exports.nodeModules = void 0;
  10102. exports.nodeModules = [
  10103. 'assert',
  10104. 'cluster',
  10105. 'crypto',
  10106. 'dns',
  10107. 'domain',
  10108. 'events',
  10109. 'fs',
  10110. 'http',
  10111. 'http2',
  10112. 'https',
  10113. 'inspector',
  10114. 'net',
  10115. 'os',
  10116. 'path',
  10117. 'punycode',
  10118. 'querystring',
  10119. 'readline',
  10120. 'repl',
  10121. 'stream',
  10122. 'string_decoder',
  10123. 'tls',
  10124. 'tty',
  10125. 'url',
  10126. 'util',
  10127. 'v8',
  10128. 'vm',
  10129. 'zlib',
  10130. 'perf_hooks'
  10131. ];
  10132. /***/ }),
  10133. /* 101 */
  10134. /***/ (function(module, exports, __webpack_require__) {
  10135. "use strict";
  10136. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  10137. if (k2 === undefined) k2 = k;
  10138. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  10139. }) : (function(o, m, k, k2) {
  10140. if (k2 === undefined) k2 = k;
  10141. o[k2] = m[k];
  10142. }));
  10143. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  10144. Object.defineProperty(o, "default", { enumerable: true, value: v });
  10145. }) : function(o, v) {
  10146. o["default"] = v;
  10147. });
  10148. var __importStar = (this && this.__importStar) || function (mod) {
  10149. if (mod && mod.__esModule) return mod;
  10150. var result = {};
  10151. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  10152. __setModuleDefault(result, mod);
  10153. return result;
  10154. };
  10155. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  10156. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  10157. return new (P || (P = Promise))(function (resolve, reject) {
  10158. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  10159. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  10160. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  10161. step((generator = generator.apply(thisArg, _arguments || [])).next());
  10162. });
  10163. };
  10164. Object.defineProperty(exports, "__esModule", { value: true });
  10165. /*---------------------------------------------------------------------------------------------
  10166. * Copyright (c) Microsoft Corporation. All rights reserved.
  10167. * Licensed under the MIT License. See License.txt in the project root for license information.
  10168. *--------------------------------------------------------------------------------------------*/
  10169. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  10170. const coc_nvim_1 = __webpack_require__(1);
  10171. const typeConverters = __importStar(__webpack_require__(37));
  10172. class ApplyRefactoringCommand {
  10173. constructor(client) {
  10174. this.client = client;
  10175. this.id = ApplyRefactoringCommand.ID;
  10176. }
  10177. execute(document, file, refactor, action, range) {
  10178. return __awaiter(this, void 0, void 0, function* () {
  10179. const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, range)), { refactor,
  10180. action });
  10181. const response = yield this.client.execute('getEditsForRefactor', args, vscode_languageserver_protocol_1.CancellationToken.None);
  10182. const body = response && response.body;
  10183. if (!body || !body.edits.length) {
  10184. return false;
  10185. }
  10186. const workspaceEdit = yield this.toWorkspaceEdit(body);
  10187. if (!(yield coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
  10188. return false;
  10189. }
  10190. const renameLocation = body.renameLocation;
  10191. if (renameLocation) {
  10192. coc_nvim_1.commands.executeCommand('editor.action.rename', document.uri, typeConverters.Position.fromLocation(renameLocation));
  10193. }
  10194. return true;
  10195. });
  10196. }
  10197. toWorkspaceEdit(body) {
  10198. return __awaiter(this, void 0, void 0, function* () {
  10199. for (const edit of body.edits) {
  10200. yield coc_nvim_1.workspace.createFile(edit.fileName, { ignoreIfExists: true });
  10201. }
  10202. let workspaceEdit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.edits);
  10203. return workspaceEdit;
  10204. });
  10205. }
  10206. }
  10207. ApplyRefactoringCommand.ID = '_typescript.applyRefactoring';
  10208. class SelectRefactorCommand {
  10209. constructor(doRefactoring) {
  10210. this.doRefactoring = doRefactoring;
  10211. this.id = SelectRefactorCommand.ID;
  10212. }
  10213. execute(document, file, info, range) {
  10214. return __awaiter(this, void 0, void 0, function* () {
  10215. let { actions } = info;
  10216. const idx = actions.length == 1 ? 0 : yield coc_nvim_1.workspace.showQuickpick(actions.map(action => action.description || action.name));
  10217. if (idx == -1)
  10218. return false;
  10219. let label = info.actions[idx].name;
  10220. if (!label)
  10221. return false;
  10222. return this.doRefactoring.execute(document, file, info.name, label, range);
  10223. });
  10224. }
  10225. }
  10226. SelectRefactorCommand.ID = '_typescript.selectRefactoring';
  10227. class TypeScriptRefactorProvider {
  10228. constructor(client, formattingOptionsManager) {
  10229. this.client = client;
  10230. this.formattingOptionsManager = formattingOptionsManager;
  10231. const doRefactoringCommand = coc_nvim_1.commands.register(new ApplyRefactoringCommand(this.client));
  10232. coc_nvim_1.commands.register(new SelectRefactorCommand(doRefactoringCommand));
  10233. }
  10234. provideCodeActions(document, range, context, token) {
  10235. return __awaiter(this, void 0, void 0, function* () {
  10236. if (!this.shouldTrigger(context)) {
  10237. return undefined;
  10238. }
  10239. const file = this.client.toPath(document.uri);
  10240. if (!file)
  10241. return undefined;
  10242. yield this.formattingOptionsManager.ensureConfigurationForDocument(document);
  10243. const args = typeConverters.Range.toFileRangeRequestArgs(file, range);
  10244. let response;
  10245. try {
  10246. response = yield this.client.interruptGetErr(() => {
  10247. return this.client.execute('getApplicableRefactors', args, token);
  10248. });
  10249. if (!response || !response.body) {
  10250. return undefined;
  10251. }
  10252. }
  10253. catch (_a) {
  10254. return undefined;
  10255. }
  10256. return this.convertApplicableRefactors(response.body, document, file, range);
  10257. });
  10258. }
  10259. convertApplicableRefactors(body, document, file, rangeOrSelection) {
  10260. const actions = [];
  10261. for (const info of body) {
  10262. if (!info.inlineable) {
  10263. const codeAction = {
  10264. title: info.description,
  10265. kind: vscode_languageserver_protocol_1.CodeActionKind.Refactor
  10266. };
  10267. codeAction.command = {
  10268. title: info.description,
  10269. command: SelectRefactorCommand.ID,
  10270. arguments: [document, file, info, rangeOrSelection]
  10271. };
  10272. actions.push(codeAction);
  10273. }
  10274. else {
  10275. for (const action of info.actions) {
  10276. actions.push(this.refactorActionToCodeAction(action, document, file, info, rangeOrSelection));
  10277. }
  10278. }
  10279. }
  10280. return actions;
  10281. }
  10282. refactorActionToCodeAction(action, document, file, info, rangeOrSelection) {
  10283. const codeAction = {
  10284. title: action.description,
  10285. kind: TypeScriptRefactorProvider.getKind(action)
  10286. };
  10287. codeAction.command = {
  10288. title: action.description,
  10289. command: ApplyRefactoringCommand.ID,
  10290. arguments: [document, file, info.name, action.name, rangeOrSelection]
  10291. };
  10292. return codeAction;
  10293. }
  10294. shouldTrigger(context) {
  10295. if (context.only &&
  10296. context.only.indexOf(vscode_languageserver_protocol_1.CodeActionKind.Refactor) == -1) {
  10297. return false;
  10298. }
  10299. return true;
  10300. }
  10301. static getKind(refactor) {
  10302. if (refactor.name.startsWith('function_')) {
  10303. return TypeScriptRefactorProvider.extractFunctionKind;
  10304. }
  10305. else if (refactor.name.startsWith('constant_')) {
  10306. return TypeScriptRefactorProvider.extractConstantKind;
  10307. }
  10308. else if (refactor.name.startsWith('Move')) {
  10309. return TypeScriptRefactorProvider.moveKind;
  10310. }
  10311. return vscode_languageserver_protocol_1.CodeActionKind.Refactor;
  10312. }
  10313. }
  10314. exports.default = TypeScriptRefactorProvider;
  10315. TypeScriptRefactorProvider.extractFunctionKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.function';
  10316. TypeScriptRefactorProvider.extractConstantKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.constant';
  10317. TypeScriptRefactorProvider.moveKind = vscode_languageserver_protocol_1.CodeActionKind.Refactor + '.move';
  10318. TypeScriptRefactorProvider.metadata = {
  10319. providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.Refactor]
  10320. };
  10321. /***/ }),
  10322. /* 102 */
  10323. /***/ (function(module, exports, __webpack_require__) {
  10324. "use strict";
  10325. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  10326. if (k2 === undefined) k2 = k;
  10327. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  10328. }) : (function(o, m, k, k2) {
  10329. if (k2 === undefined) k2 = k;
  10330. o[k2] = m[k];
  10331. }));
  10332. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  10333. Object.defineProperty(o, "default", { enumerable: true, value: v });
  10334. }) : function(o, v) {
  10335. o["default"] = v;
  10336. });
  10337. var __importStar = (this && this.__importStar) || function (mod) {
  10338. if (mod && mod.__esModule) return mod;
  10339. var result = {};
  10340. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  10341. __setModuleDefault(result, mod);
  10342. return result;
  10343. };
  10344. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  10345. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  10346. return new (P || (P = Promise))(function (resolve, reject) {
  10347. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  10348. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  10349. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  10350. step((generator = generator.apply(thisArg, _arguments || [])).next());
  10351. });
  10352. };
  10353. Object.defineProperty(exports, "__esModule", { value: true });
  10354. const typeConverters = __importStar(__webpack_require__(37));
  10355. class TypeScriptReferences {
  10356. constructor(client) {
  10357. this.client = client;
  10358. }
  10359. provideReferences(document, position, context, token) {
  10360. return __awaiter(this, void 0, void 0, function* () {
  10361. const filepath = this.client.toPath(document.uri);
  10362. if (!filepath)
  10363. return [];
  10364. const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
  10365. try {
  10366. const msg = yield this.client.execute('references', args, token);
  10367. if (!msg || msg.type != 'response' || !msg.body) {
  10368. return [];
  10369. }
  10370. const result = [];
  10371. for (const ref of msg.body.refs) {
  10372. if (!context.includeDeclaration && ref.isDefinition) {
  10373. continue;
  10374. }
  10375. const url = this.client.toResource(ref.file);
  10376. const location = typeConverters.Location.fromTextSpan(url, ref);
  10377. result.push(location);
  10378. }
  10379. return result;
  10380. }
  10381. catch (_a) {
  10382. return [];
  10383. }
  10384. });
  10385. }
  10386. }
  10387. exports.default = TypeScriptReferences;
  10388. /***/ }),
  10389. /* 103 */
  10390. /***/ (function(module, exports, __webpack_require__) {
  10391. "use strict";
  10392. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  10393. if (k2 === undefined) k2 = k;
  10394. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  10395. }) : (function(o, m, k, k2) {
  10396. if (k2 === undefined) k2 = k;
  10397. o[k2] = m[k];
  10398. }));
  10399. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  10400. Object.defineProperty(o, "default", { enumerable: true, value: v });
  10401. }) : function(o, v) {
  10402. o["default"] = v;
  10403. });
  10404. var __importStar = (this && this.__importStar) || function (mod) {
  10405. if (mod && mod.__esModule) return mod;
  10406. var result = {};
  10407. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  10408. __setModuleDefault(result, mod);
  10409. return result;
  10410. };
  10411. Object.defineProperty(exports, "__esModule", { value: true });
  10412. const PConst = __importStar(__webpack_require__(39));
  10413. const typeConverters = __importStar(__webpack_require__(37));
  10414. const baseCodeLensProvider_1 = __webpack_require__(35);
  10415. class TypeScriptReferencesCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
  10416. resolveCodeLens(codeLens, token) {
  10417. let { uri } = codeLens.data;
  10418. let filepath = this.client.toPath(uri);
  10419. const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
  10420. return this.client
  10421. .execute('references', args, token, true)
  10422. .then(response => {
  10423. if (!response || response.type != 'response' || !response.body) {
  10424. throw codeLens;
  10425. }
  10426. const locations = response.body.refs
  10427. .map(reference => typeConverters.Location.fromTextSpan(this.client.toResource(reference.file), reference))
  10428. .filter(location =>
  10429. // Exclude original definition from references
  10430. !(location.uri.toString() === uri &&
  10431. location.range.start.line === codeLens.range.start.line &&
  10432. location.range.start.character ===
  10433. codeLens.range.start.character));
  10434. codeLens.command = {
  10435. title: locations.length === 1 ? '1 reference' : `${locations.length} references`,
  10436. command: locations.length ? 'editor.action.showReferences' : '',
  10437. arguments: [uri, codeLens.range.start, locations]
  10438. };
  10439. return codeLens;
  10440. })
  10441. .catch(() => {
  10442. codeLens.command = {
  10443. title: '0 references',
  10444. command: ''
  10445. };
  10446. return codeLens;
  10447. });
  10448. }
  10449. extractSymbol(document, item, parent) {
  10450. if (parent && parent.kind === PConst.Kind.enum) {
  10451. return super.getSymbolRange(document, item);
  10452. }
  10453. switch (item.kind) {
  10454. case PConst.Kind.const:
  10455. case PConst.Kind.let:
  10456. case PConst.Kind.variable:
  10457. case PConst.Kind.function:
  10458. // Only show references for exported variables
  10459. if (!item.kindModifiers.match(/\bexport\b/)) {
  10460. break;
  10461. }
  10462. // fallthrough
  10463. case PConst.Kind.class:
  10464. if (item.text === '<class>') {
  10465. break;
  10466. }
  10467. // fallthrough
  10468. case PConst.Kind.method:
  10469. case PConst.Kind.memberVariable:
  10470. case PConst.Kind.memberGetAccessor:
  10471. case PConst.Kind.memberSetAccessor:
  10472. case PConst.Kind.constructorImplementation:
  10473. case PConst.Kind.interface:
  10474. case PConst.Kind.type:
  10475. case PConst.Kind.enum:
  10476. return super.getSymbolRange(document, item);
  10477. }
  10478. return null;
  10479. }
  10480. }
  10481. exports.default = TypeScriptReferencesCodeLensProvider;
  10482. /***/ }),
  10483. /* 104 */
  10484. /***/ (function(module, exports, __webpack_require__) {
  10485. "use strict";
  10486. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  10487. if (k2 === undefined) k2 = k;
  10488. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  10489. }) : (function(o, m, k, k2) {
  10490. if (k2 === undefined) k2 = k;
  10491. o[k2] = m[k];
  10492. }));
  10493. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  10494. Object.defineProperty(o, "default", { enumerable: true, value: v });
  10495. }) : function(o, v) {
  10496. o["default"] = v;
  10497. });
  10498. var __importStar = (this && this.__importStar) || function (mod) {
  10499. if (mod && mod.__esModule) return mod;
  10500. var result = {};
  10501. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  10502. __setModuleDefault(result, mod);
  10503. return result;
  10504. };
  10505. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  10506. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  10507. return new (P || (P = Promise))(function (resolve, reject) {
  10508. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  10509. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  10510. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  10511. step((generator = generator.apply(thisArg, _arguments || [])).next());
  10512. });
  10513. };
  10514. var __importDefault = (this && this.__importDefault) || function (mod) {
  10515. return (mod && mod.__esModule) ? mod : { "default": mod };
  10516. };
  10517. Object.defineProperty(exports, "__esModule", { value: true });
  10518. /*---------------------------------------------------------------------------------------------
  10519. * Copyright (c) Microsoft Corporation. All rights reserved.
  10520. * Licensed under the MIT License. See License.txt in the project root for license information.
  10521. *--------------------------------------------------------------------------------------------*/
  10522. const coc_nvim_1 = __webpack_require__(1);
  10523. const path_1 = __importDefault(__webpack_require__(13));
  10524. const api_1 = __importDefault(__webpack_require__(40));
  10525. const typeConverters = __importStar(__webpack_require__(37));
  10526. class TypeScriptRenameProvider {
  10527. constructor(client) {
  10528. this.client = client;
  10529. }
  10530. prepareRename(document, position, token) {
  10531. return __awaiter(this, void 0, void 0, function* () {
  10532. const response = yield this.execRename(document, position, token);
  10533. if (!response || response.type !== 'response' || !response.body) {
  10534. return null;
  10535. }
  10536. const renameInfo = response.body.info;
  10537. if (!renameInfo.canRename) {
  10538. return Promise.reject(new Error('Invalid location for rename.'));
  10539. }
  10540. if (this.client.apiVersion.gte(api_1.default.v310)) {
  10541. const triggerSpan = renameInfo.triggerSpan;
  10542. if (triggerSpan) {
  10543. const range = typeConverters.Range.fromTextSpan(triggerSpan);
  10544. return range;
  10545. }
  10546. }
  10547. return null;
  10548. });
  10549. }
  10550. provideRenameEdits(document, position, newName, token) {
  10551. return __awaiter(this, void 0, void 0, function* () {
  10552. const response = yield this.execRename(document, position, token);
  10553. if (!response || response.type !== 'response' || !response.body) {
  10554. return null;
  10555. }
  10556. const renameInfo = response.body.info;
  10557. if (!renameInfo.canRename) {
  10558. return Promise.reject(new Error('Invalid location for rename.'));
  10559. }
  10560. if (this.client.apiVersion.gte(api_1.default.v310)) {
  10561. if (renameInfo.fileToRename) {
  10562. const edits = yield this.renameFile(renameInfo.fileToRename, newName, token);
  10563. if (edits) {
  10564. return edits;
  10565. }
  10566. else {
  10567. return Promise.reject(new Error('An error occurred while renaming file'));
  10568. }
  10569. }
  10570. }
  10571. return this.toWorkspaceEdit(response.body.locs, newName);
  10572. });
  10573. }
  10574. execRename(document, position, token) {
  10575. return __awaiter(this, void 0, void 0, function* () {
  10576. const file = this.client.toPath(document.uri);
  10577. if (!file)
  10578. return undefined;
  10579. const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { findInStrings: false, findInComments: false });
  10580. return this.client.interruptGetErr(() => {
  10581. return this.client.execute('rename', args, token);
  10582. });
  10583. });
  10584. }
  10585. toWorkspaceEdit(locations, newName) {
  10586. let changes = {};
  10587. for (const spanGroup of locations) {
  10588. const uri = this.client.toResource(spanGroup.file);
  10589. if (uri) {
  10590. changes[uri] = [];
  10591. for (const textSpan of spanGroup.locs) {
  10592. changes[uri].push({
  10593. range: typeConverters.Range.fromTextSpan(textSpan),
  10594. newText: (textSpan.prefixText || '') + newName + (textSpan.suffixText || '')
  10595. });
  10596. }
  10597. }
  10598. }
  10599. return { changes };
  10600. }
  10601. renameFile(fileToRename, newName, token) {
  10602. return __awaiter(this, void 0, void 0, function* () {
  10603. // Make sure we preserve file exension if none provided
  10604. if (!path_1.default.extname(newName)) {
  10605. newName += path_1.default.extname(fileToRename);
  10606. }
  10607. const dirname = path_1.default.dirname(fileToRename);
  10608. const newFilePath = path_1.default.join(dirname, newName);
  10609. const args = {
  10610. file: fileToRename,
  10611. oldFilePath: fileToRename,
  10612. newFilePath
  10613. };
  10614. const response = yield this.client.execute('getEditsForFileRename', args, token);
  10615. if (response.type !== 'response' || !response.body) {
  10616. return undefined;
  10617. }
  10618. const edits = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, response.body);
  10619. edits.documentChanges = edits.documentChanges || [];
  10620. edits.documentChanges.push({
  10621. kind: 'rename',
  10622. oldUri: coc_nvim_1.Uri.file(fileToRename).toString(),
  10623. newUri: coc_nvim_1.Uri.file(newFilePath).toString(),
  10624. options: {
  10625. overwrite: false,
  10626. ignoreIfExists: true
  10627. }
  10628. });
  10629. return edits;
  10630. });
  10631. }
  10632. }
  10633. exports.default = TypeScriptRenameProvider;
  10634. /***/ }),
  10635. /* 105 */
  10636. /***/ (function(module, exports, __webpack_require__) {
  10637. "use strict";
  10638. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  10639. if (k2 === undefined) k2 = k;
  10640. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  10641. }) : (function(o, m, k, k2) {
  10642. if (k2 === undefined) k2 = k;
  10643. o[k2] = m[k];
  10644. }));
  10645. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  10646. Object.defineProperty(o, "default", { enumerable: true, value: v });
  10647. }) : function(o, v) {
  10648. o["default"] = v;
  10649. });
  10650. var __importStar = (this && this.__importStar) || function (mod) {
  10651. if (mod && mod.__esModule) return mod;
  10652. var result = {};
  10653. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  10654. __setModuleDefault(result, mod);
  10655. return result;
  10656. };
  10657. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  10658. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  10659. return new (P || (P = Promise))(function (resolve, reject) {
  10660. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  10661. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  10662. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  10663. step((generator = generator.apply(thisArg, _arguments || [])).next());
  10664. });
  10665. };
  10666. Object.defineProperty(exports, "__esModule", { value: true });
  10667. const Previewer = __importStar(__webpack_require__(86));
  10668. const typeConverters = __importStar(__webpack_require__(37));
  10669. class TypeScriptSignatureHelpProvider {
  10670. constructor(client) {
  10671. this.client = client;
  10672. }
  10673. provideSignatureHelp(document, position, token) {
  10674. return __awaiter(this, void 0, void 0, function* () {
  10675. const filepath = this.client.toPath(document.uri);
  10676. if (!filepath) {
  10677. return undefined;
  10678. }
  10679. const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
  10680. let response;
  10681. try {
  10682. response = yield this.client.interruptGetErr(() => this.client.execute('signatureHelp', args, token));
  10683. }
  10684. catch (e) {
  10685. return undefined;
  10686. }
  10687. if (response.type !== 'response' || !response.body) {
  10688. return undefined;
  10689. }
  10690. let info = response.body;
  10691. const result = {
  10692. activeSignature: info.selectedItemIndex,
  10693. activeParameter: this.getActiveParmeter(info),
  10694. signatures: info.items.map(signature => {
  10695. return this.convertSignature(signature);
  10696. })
  10697. };
  10698. return result;
  10699. });
  10700. }
  10701. getActiveParmeter(info) {
  10702. const activeSignature = info.items[info.selectedItemIndex];
  10703. if (activeSignature && activeSignature.isVariadic) {
  10704. return Math.min(info.argumentIndex, activeSignature.parameters.length - 1);
  10705. }
  10706. return info.argumentIndex;
  10707. }
  10708. convertSignature(item) {
  10709. let parameters = item.parameters.map(p => {
  10710. return {
  10711. label: Previewer.plain(p.displayParts),
  10712. documentation: Previewer.markdownDocumentation(p.documentation, [])
  10713. };
  10714. });
  10715. let label = Previewer.plain(item.prefixDisplayParts);
  10716. label += parameters.map(parameter => parameter.label).join(Previewer.plain(item.separatorDisplayParts));
  10717. label += Previewer.plain(item.suffixDisplayParts);
  10718. return {
  10719. label,
  10720. documentation: Previewer.markdownDocumentation(item.documentation, item.tags.filter(x => x.name !== 'param')),
  10721. parameters
  10722. };
  10723. }
  10724. }
  10725. exports.default = TypeScriptSignatureHelpProvider;
  10726. TypeScriptSignatureHelpProvider.triggerCharacters = ['(', ',', '<'];
  10727. /***/ }),
  10728. /* 106 */
  10729. /***/ (function(module, exports, __webpack_require__) {
  10730. "use strict";
  10731. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  10732. if (k2 === undefined) k2 = k;
  10733. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  10734. }) : (function(o, m, k, k2) {
  10735. if (k2 === undefined) k2 = k;
  10736. o[k2] = m[k];
  10737. }));
  10738. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  10739. Object.defineProperty(o, "default", { enumerable: true, value: v });
  10740. }) : function(o, v) {
  10741. o["default"] = v;
  10742. });
  10743. var __importStar = (this && this.__importStar) || function (mod) {
  10744. if (mod && mod.__esModule) return mod;
  10745. var result = {};
  10746. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  10747. __setModuleDefault(result, mod);
  10748. return result;
  10749. };
  10750. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  10751. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  10752. return new (P || (P = Promise))(function (resolve, reject) {
  10753. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  10754. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  10755. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  10756. step((generator = generator.apply(thisArg, _arguments || [])).next());
  10757. });
  10758. };
  10759. Object.defineProperty(exports, "__esModule", { value: true });
  10760. /*---------------------------------------------------------------------------------------------
  10761. * Copyright (c) Microsoft Corporation. All rights reserved.
  10762. * Licensed under the MIT License. See License.txt in the project root for license information.
  10763. *--------------------------------------------------------------------------------------------*/
  10764. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  10765. const coc_nvim_1 = __webpack_require__(1);
  10766. const typeConverters = __importStar(__webpack_require__(37));
  10767. const mutex_1 = __webpack_require__(107);
  10768. function wait(ms) {
  10769. return new Promise(resolve => {
  10770. setTimeout(() => {
  10771. resolve();
  10772. }, ms);
  10773. });
  10774. }
  10775. class UpdateImportsOnFileRenameHandler {
  10776. constructor(client, fileConfigurationManager, languageId) {
  10777. this.client = client;
  10778. this.fileConfigurationManager = fileConfigurationManager;
  10779. this.disposables = [];
  10780. let glob = languageId == 'typescript' ? '**/*.{ts,tsx}' : '**/*.{js,jsx}';
  10781. const watcher = coc_nvim_1.workspace.createFileSystemWatcher(glob);
  10782. this.disposables.push(watcher);
  10783. let mutex = new mutex_1.Mutex();
  10784. watcher.onDidRename((e) => __awaiter(this, void 0, void 0, function* () {
  10785. let release = yield mutex.acquire();
  10786. try {
  10787. yield this.doRename(e.oldUri, e.newUri);
  10788. release();
  10789. }
  10790. catch (e) {
  10791. this.client.logger.error('Error on rename:', e);
  10792. release();
  10793. }
  10794. }), null, this.disposables);
  10795. }
  10796. dispose() {
  10797. coc_nvim_1.disposeAll(this.disposables);
  10798. }
  10799. doRename(oldResource, newResource) {
  10800. return __awaiter(this, void 0, void 0, function* () {
  10801. if (oldResource.scheme !== 'file' || newResource.scheme !== 'file') {
  10802. return;
  10803. }
  10804. const targetFile = newResource.fsPath;
  10805. const oldFile = oldResource.fsPath;
  10806. const newUri = newResource.toString();
  10807. let oldDocument = coc_nvim_1.workspace.getDocument(oldResource.toString());
  10808. if (oldDocument) {
  10809. yield coc_nvim_1.workspace.nvim.command(`silent ${oldDocument.bufnr}bwipeout!`);
  10810. }
  10811. let document = coc_nvim_1.workspace.getDocument(newUri);
  10812. if (document) {
  10813. yield coc_nvim_1.workspace.nvim.command(`silent ${document.bufnr}bwipeout!`);
  10814. yield wait(30);
  10815. }
  10816. document = yield coc_nvim_1.workspace.loadFile(newUri);
  10817. if (!document)
  10818. return;
  10819. yield wait(50);
  10820. const edits = yield this.getEditsForFileRename(document.textDocument, oldFile, targetFile);
  10821. if (!edits)
  10822. return;
  10823. if (yield this.promptUser(newResource)) {
  10824. yield coc_nvim_1.workspace.applyEdit(edits);
  10825. }
  10826. });
  10827. }
  10828. promptUser(newResource) {
  10829. return __awaiter(this, void 0, void 0, function* () {
  10830. return yield coc_nvim_1.workspace.showPrompt(`Update imports for moved file: ${newResource.fsPath}?`);
  10831. });
  10832. }
  10833. getEditsForFileRename(document, oldFile, newFile) {
  10834. return __awaiter(this, void 0, void 0, function* () {
  10835. yield this.fileConfigurationManager.ensureConfigurationForDocument(document);
  10836. const response = yield this.client.interruptGetErr(() => {
  10837. const args = {
  10838. oldFilePath: oldFile,
  10839. newFilePath: newFile,
  10840. };
  10841. return this.client.execute('getEditsForFileRename', args, vscode_languageserver_protocol_1.CancellationToken.None);
  10842. });
  10843. if (!response || response.type != 'response' || !response.body) {
  10844. return;
  10845. }
  10846. const edits = [];
  10847. for (const edit of response.body) {
  10848. // Workaround for https://github.com/Microsoft/vscode/issues/52675
  10849. if (edit.fileName.match(/[\/\\]node_modules[\/\\]/gi)) {
  10850. continue;
  10851. }
  10852. for (const change of edit.textChanges) {
  10853. if (change.newText.match(/\/node_modules\//gi)) {
  10854. continue;
  10855. }
  10856. }
  10857. edits.push(edit);
  10858. }
  10859. return typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, edits);
  10860. });
  10861. }
  10862. }
  10863. exports.default = UpdateImportsOnFileRenameHandler;
  10864. /***/ }),
  10865. /* 107 */
  10866. /***/ (function(module, exports, __webpack_require__) {
  10867. "use strict";
  10868. Object.defineProperty(exports, "__esModule", { value: true });
  10869. exports.Mutex = void 0;
  10870. class Mutex {
  10871. constructor() {
  10872. this.tasks = [];
  10873. this.count = 1;
  10874. }
  10875. sched() {
  10876. if (this.count > 0 && this.tasks.length > 0) {
  10877. this.count--;
  10878. let next = this.tasks.shift();
  10879. next();
  10880. }
  10881. }
  10882. get busy() {
  10883. return this.count == 0;
  10884. }
  10885. // tslint:disable-next-line: typedef
  10886. acquire() {
  10887. return new Promise(res => {
  10888. let task = () => {
  10889. let released = false;
  10890. res(() => {
  10891. if (!released) {
  10892. released = true;
  10893. this.count++;
  10894. this.sched();
  10895. }
  10896. });
  10897. };
  10898. this.tasks.push(task);
  10899. process.nextTick(this.sched.bind(this));
  10900. });
  10901. }
  10902. use(f) {
  10903. return this.acquire()
  10904. .then(release => {
  10905. return f()
  10906. .then(res => {
  10907. release();
  10908. return res;
  10909. })
  10910. .catch(err => {
  10911. release();
  10912. throw err;
  10913. });
  10914. });
  10915. }
  10916. }
  10917. exports.Mutex = Mutex;
  10918. /***/ }),
  10919. /* 108 */
  10920. /***/ (function(module, exports, __webpack_require__) {
  10921. "use strict";
  10922. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  10923. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  10924. return new (P || (P = Promise))(function (resolve, reject) {
  10925. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  10926. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  10927. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  10928. step((generator = generator.apply(thisArg, _arguments || [])).next());
  10929. });
  10930. };
  10931. var __importDefault = (this && this.__importDefault) || function (mod) {
  10932. return (mod && mod.__esModule) ? mod : { "default": mod };
  10933. };
  10934. Object.defineProperty(exports, "__esModule", { value: true });
  10935. const coc_nvim_1 = __webpack_require__(1);
  10936. const path_1 = __importDefault(__webpack_require__(13));
  10937. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  10938. const countRegex = /Found\s+(\d+)\s+error/;
  10939. const errorRegex = /^(.+)\((\d+),(\d+)\):\s(\w+)\sTS(\d+):\s*(.+)$/;
  10940. var TscStatus;
  10941. (function (TscStatus) {
  10942. TscStatus[TscStatus["INIT"] = 0] = "INIT";
  10943. TscStatus[TscStatus["COMPILING"] = 1] = "COMPILING";
  10944. TscStatus[TscStatus["RUNNING"] = 2] = "RUNNING";
  10945. TscStatus[TscStatus["ERROR"] = 3] = "ERROR";
  10946. })(TscStatus || (TscStatus = {}));
  10947. class WatchProject {
  10948. constructor(commandManager, client) {
  10949. this.client = client;
  10950. this.disposables = [];
  10951. this.statusItem = coc_nvim_1.workspace.createStatusBarItem(1, { progress: true });
  10952. let task = this.task = coc_nvim_1.workspace.createTask('TSC');
  10953. this.disposables.push(commandManager.registerCommand(WatchProject.id, () => __awaiter(this, void 0, void 0, function* () {
  10954. let opts = this.options = yield this.getOptions();
  10955. yield this.start(opts);
  10956. })));
  10957. task.onExit(code => {
  10958. if (code != 0) {
  10959. coc_nvim_1.workspace.showMessage(`TSC exit with code ${code}`, 'warning');
  10960. }
  10961. this.onStop();
  10962. });
  10963. task.onStdout(lines => {
  10964. for (let line of lines) {
  10965. this.onLine(line);
  10966. }
  10967. });
  10968. task.onStderr(lines => {
  10969. coc_nvim_1.workspace.showMessage(`TSC error: ` + lines.join('\n'), 'error');
  10970. });
  10971. this.disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => {
  10972. task.dispose();
  10973. }));
  10974. this.check().catch(_e => {
  10975. // noop
  10976. });
  10977. }
  10978. check() {
  10979. return __awaiter(this, void 0, void 0, function* () {
  10980. let running = yield this.task.running;
  10981. if (running) {
  10982. this.options = yield this.getOptions();
  10983. this.statusItem.isProgress = false;
  10984. this.statusItem.text = '?';
  10985. this.statusItem.show();
  10986. }
  10987. else {
  10988. this.onStop();
  10989. }
  10990. });
  10991. }
  10992. start(options) {
  10993. return __awaiter(this, void 0, void 0, function* () {
  10994. yield this.task.start(options);
  10995. });
  10996. }
  10997. onStop() {
  10998. this.statusItem.hide();
  10999. }
  11000. onStart() {
  11001. this.statusItem.text = 'compiling';
  11002. this.statusItem.isProgress = true;
  11003. this.statusItem.show();
  11004. coc_nvim_1.workspace.nvim.call('setqflist', [[]], true);
  11005. }
  11006. onLine(line) {
  11007. if (countRegex.test(line)) {
  11008. let ms = line.match(countRegex);
  11009. this.statusItem.text = ms[1] == '0' ? '✓' : '✗';
  11010. this.statusItem.isProgress = false;
  11011. }
  11012. else if (WatchProject.startTexts.findIndex(s => line.indexOf(s) !== -1) != -1) {
  11013. this.onStart();
  11014. }
  11015. else {
  11016. let ms = line.match(errorRegex);
  11017. if (!ms)
  11018. return;
  11019. let fullpath = path_1.default.join(this.options.cwd, ms[1]);
  11020. let uri = coc_nvim_1.Uri.file(fullpath).toString();
  11021. let doc = coc_nvim_1.workspace.getDocument(uri);
  11022. let bufnr = doc ? doc.bufnr : null;
  11023. let item = {
  11024. filename: fullpath,
  11025. lnum: Number(ms[2]),
  11026. col: Number(ms[3]),
  11027. text: `[tsc ${ms[5]}] ${ms[6]}`,
  11028. type: /error/i.test(ms[4]) ? 'E' : 'W'
  11029. };
  11030. if (bufnr)
  11031. item.bufnr = bufnr;
  11032. coc_nvim_1.workspace.nvim.call('setqflist', [[item], 'a']);
  11033. }
  11034. }
  11035. getOptions() {
  11036. return __awaiter(this, void 0, void 0, function* () {
  11037. let { tscPath } = this.client;
  11038. if (!tscPath) {
  11039. coc_nvim_1.workspace.showMessage(`Local & global tsc not found`, 'error');
  11040. return;
  11041. }
  11042. let find = yield coc_nvim_1.workspace.findUp(['tsconfig.json']);
  11043. if (!find) {
  11044. coc_nvim_1.workspace.showMessage('tsconfig.json not found!', 'error');
  11045. return;
  11046. }
  11047. let root = path_1.default.dirname(find);
  11048. return {
  11049. cmd: tscPath,
  11050. args: ['-p', 'tsconfig.json', '--watch', 'true', '--pretty', 'false'],
  11051. cwd: root
  11052. };
  11053. });
  11054. }
  11055. dispose() {
  11056. coc_nvim_1.disposeAll(this.disposables);
  11057. }
  11058. }
  11059. exports.default = WatchProject;
  11060. WatchProject.id = 'tsserver.watchBuild';
  11061. WatchProject.startTexts = ['Starting compilation in watch mode', 'Starting incremental compilation'];
  11062. /***/ }),
  11063. /* 109 */
  11064. /***/ (function(module, exports, __webpack_require__) {
  11065. "use strict";
  11066. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  11067. if (k2 === undefined) k2 = k;
  11068. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  11069. }) : (function(o, m, k, k2) {
  11070. if (k2 === undefined) k2 = k;
  11071. o[k2] = m[k];
  11072. }));
  11073. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  11074. Object.defineProperty(o, "default", { enumerable: true, value: v });
  11075. }) : function(o, v) {
  11076. o["default"] = v;
  11077. });
  11078. var __importStar = (this && this.__importStar) || function (mod) {
  11079. if (mod && mod.__esModule) return mod;
  11080. var result = {};
  11081. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  11082. __setModuleDefault(result, mod);
  11083. return result;
  11084. };
  11085. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  11086. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  11087. return new (P || (P = Promise))(function (resolve, reject) {
  11088. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  11089. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  11090. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  11091. step((generator = generator.apply(thisArg, _arguments || [])).next());
  11092. });
  11093. };
  11094. var __importDefault = (this && this.__importDefault) || function (mod) {
  11095. return (mod && mod.__esModule) ? mod : { "default": mod };
  11096. };
  11097. Object.defineProperty(exports, "__esModule", { value: true });
  11098. /*---------------------------------------------------------------------------------------------
  11099. * Copyright (c) Microsoft Corporation. All rights reserved.
  11100. * Licensed under the MIT License. See License.txt in the project root for license information.
  11101. *--------------------------------------------------------------------------------------------*/
  11102. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  11103. const coc_nvim_1 = __webpack_require__(1);
  11104. const typeConverters = __importStar(__webpack_require__(37));
  11105. const api_1 = __importDefault(__webpack_require__(40));
  11106. function getSymbolKind(item) {
  11107. switch (item.kind) {
  11108. case 'method':
  11109. return vscode_languageserver_protocol_1.SymbolKind.Method;
  11110. case 'enum':
  11111. return vscode_languageserver_protocol_1.SymbolKind.Enum;
  11112. case 'function':
  11113. return vscode_languageserver_protocol_1.SymbolKind.Function;
  11114. case 'class':
  11115. return vscode_languageserver_protocol_1.SymbolKind.Class;
  11116. case 'interface':
  11117. return vscode_languageserver_protocol_1.SymbolKind.Interface;
  11118. case 'var':
  11119. return vscode_languageserver_protocol_1.SymbolKind.Variable;
  11120. default:
  11121. return vscode_languageserver_protocol_1.SymbolKind.Variable;
  11122. }
  11123. }
  11124. class TypeScriptWorkspaceSymbolProvider {
  11125. constructor(client, languageIds) {
  11126. this.client = client;
  11127. this.languageIds = languageIds;
  11128. }
  11129. provideWorkspaceSymbols(search, token) {
  11130. return __awaiter(this, void 0, void 0, function* () {
  11131. let filepath;
  11132. if (this.searchAllOpenProjects) {
  11133. filepath = undefined;
  11134. }
  11135. else {
  11136. let uri = this.getUri();
  11137. filepath = uri ? this.client.toPath(uri) : undefined;
  11138. if (!filepath && this.client.apiVersion.lt(api_1.default.v390)) {
  11139. return [];
  11140. }
  11141. }
  11142. const args = {
  11143. file: filepath,
  11144. searchValue: search,
  11145. maxResultCount: 256,
  11146. };
  11147. const response = yield this.client.execute('navto', args, token);
  11148. if (response.type !== 'response' || response.body == null)
  11149. return [];
  11150. const result = [];
  11151. for (const item of response.body) {
  11152. if (!item.containerName && item.kind === 'alias') {
  11153. continue;
  11154. }
  11155. const label = TypeScriptWorkspaceSymbolProvider.getLabel(item);
  11156. const range = {
  11157. start: typeConverters.Position.fromLocation(item.start),
  11158. end: typeConverters.Position.fromLocation(item.end),
  11159. };
  11160. const symbolInfo = vscode_languageserver_protocol_1.SymbolInformation.create(label, getSymbolKind(item), range, this.client.toResource(item.file));
  11161. result.push(symbolInfo);
  11162. }
  11163. return result;
  11164. });
  11165. }
  11166. static getLabel(item) {
  11167. let label = item.name;
  11168. if (item.kind === 'method' || item.kind === 'function') {
  11169. label += '()';
  11170. }
  11171. return label;
  11172. }
  11173. getUri() {
  11174. // typescript wants to have a resource even when asking
  11175. // general questions so we check the active editor. If this
  11176. // doesn't match we take the first TS document.
  11177. const documents = coc_nvim_1.workspace.textDocuments;
  11178. for (const document of documents) {
  11179. if (this.languageIds.indexOf(document.languageId) >= 0) {
  11180. return document.uri;
  11181. }
  11182. }
  11183. return undefined;
  11184. }
  11185. get searchAllOpenProjects() {
  11186. return this.client.apiVersion.gte(api_1.default.v390)
  11187. && coc_nvim_1.workspace.getConfiguration('typescript').get('workspaceSymbols.scope', 'allOpenProjects') === 'allOpenProjects';
  11188. }
  11189. }
  11190. exports.default = TypeScriptWorkspaceSymbolProvider;
  11191. /***/ }),
  11192. /* 110 */
  11193. /***/ (function(module, exports, __webpack_require__) {
  11194. "use strict";
  11195. /*---------------------------------------------------------------------------------------------
  11196. * Copyright (c) Microsoft Corporation. All rights reserved.
  11197. * Licensed under the MIT License. See License.txt in the project root for license information.
  11198. *--------------------------------------------------------------------------------------------*/
  11199. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  11200. if (k2 === undefined) k2 = k;
  11201. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  11202. }) : (function(o, m, k, k2) {
  11203. if (k2 === undefined) k2 = k;
  11204. o[k2] = m[k];
  11205. }));
  11206. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  11207. Object.defineProperty(o, "default", { enumerable: true, value: v });
  11208. }) : function(o, v) {
  11209. o["default"] = v;
  11210. });
  11211. var __importStar = (this && this.__importStar) || function (mod) {
  11212. if (mod && mod.__esModule) return mod;
  11213. var result = {};
  11214. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  11215. __setModuleDefault(result, mod);
  11216. return result;
  11217. };
  11218. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  11219. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  11220. return new (P || (P = Promise))(function (resolve, reject) {
  11221. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  11222. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  11223. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  11224. step((generator = generator.apply(thisArg, _arguments || [])).next());
  11225. });
  11226. };
  11227. Object.defineProperty(exports, "__esModule", { value: true });
  11228. const typeConverters = __importStar(__webpack_require__(37));
  11229. class SmartSelection {
  11230. constructor(client) {
  11231. this.client = client;
  11232. }
  11233. provideSelectionRanges(document, positions, token) {
  11234. return __awaiter(this, void 0, void 0, function* () {
  11235. const file = this.client.toPath(document.uri);
  11236. if (!file) {
  11237. return undefined;
  11238. }
  11239. const args = {
  11240. file,
  11241. locations: positions.map(typeConverters.Position.toLocation)
  11242. };
  11243. const response = yield this.client.execute('selectionRange', args, token);
  11244. if (response.type !== 'response' || !response.body) {
  11245. return undefined;
  11246. }
  11247. return response.body.map(SmartSelection.convertSelectionRange);
  11248. });
  11249. }
  11250. static convertSelectionRange(selectionRange) {
  11251. return {
  11252. range: typeConverters.Range.fromTextSpan(selectionRange.textSpan),
  11253. parent: selectionRange.parent ? SmartSelection.convertSelectionRange(selectionRange.parent) : undefined,
  11254. };
  11255. }
  11256. }
  11257. exports.default = SmartSelection;
  11258. /***/ }),
  11259. /* 111 */
  11260. /***/ (function(module, exports, __webpack_require__) {
  11261. "use strict";
  11262. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  11263. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  11264. return new (P || (P = Promise))(function (resolve, reject) {
  11265. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  11266. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  11267. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  11268. step((generator = generator.apply(thisArg, _arguments || [])).next());
  11269. });
  11270. };
  11271. Object.defineProperty(exports, "__esModule", { value: true });
  11272. const coc_nvim_1 = __webpack_require__(1);
  11273. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  11274. const modules_1 = __webpack_require__(112);
  11275. class InstallModuleCommand {
  11276. constructor() {
  11277. this.id = InstallModuleCommand.ID;
  11278. }
  11279. execute(uri, name) {
  11280. return __awaiter(this, void 0, void 0, function* () {
  11281. yield modules_1.installModules(uri, [name]);
  11282. });
  11283. }
  11284. }
  11285. InstallModuleCommand.ID = '_tsserver.installModule';
  11286. class InstallModuleProvider {
  11287. constructor(client) {
  11288. this.client = client;
  11289. coc_nvim_1.commands.register(new InstallModuleCommand(), true);
  11290. }
  11291. provideCodeActions(document, _range, context, _token) {
  11292. return __awaiter(this, void 0, void 0, function* () {
  11293. const uri = coc_nvim_1.Uri.parse(document.uri);
  11294. if (uri.scheme != 'file')
  11295. return null;
  11296. let { diagnostics } = context;
  11297. let diags = diagnostics.filter(s => s.code == 2307);
  11298. let names = diags.map(o => {
  11299. let ms = o.message.match(/module\s'(.+)'\./);
  11300. return ms ? ms[1] : null;
  11301. });
  11302. names = names.filter(s => s != null);
  11303. if (!names.length)
  11304. return null;
  11305. let actions = [];
  11306. for (let name of names) {
  11307. let title = `install ${name}`;
  11308. let command = {
  11309. title: `install ${name}`,
  11310. command: InstallModuleCommand.ID,
  11311. arguments: [document.uri, name]
  11312. };
  11313. let codeAction = vscode_languageserver_protocol_1.CodeAction.create(title, command);
  11314. actions.push(codeAction);
  11315. }
  11316. return actions;
  11317. });
  11318. }
  11319. }
  11320. exports.default = InstallModuleProvider;
  11321. /***/ }),
  11322. /* 112 */
  11323. /***/ (function(module, exports, __webpack_require__) {
  11324. "use strict";
  11325. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  11326. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  11327. return new (P || (P = Promise))(function (resolve, reject) {
  11328. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  11329. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  11330. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  11331. step((generator = generator.apply(thisArg, _arguments || [])).next());
  11332. });
  11333. };
  11334. var __importDefault = (this && this.__importDefault) || function (mod) {
  11335. return (mod && mod.__esModule) ? mod : { "default": mod };
  11336. };
  11337. Object.defineProperty(exports, "__esModule", { value: true });
  11338. exports.installModules = exports.distinct = exports.moduleExists = exports.runCommand = void 0;
  11339. const child_process_1 = __webpack_require__(113);
  11340. const path_1 = __importDefault(__webpack_require__(13));
  11341. const coc_nvim_1 = __webpack_require__(1);
  11342. function runCommand(cmd, cwd, timeout) {
  11343. return new Promise((resolve, reject) => {
  11344. let timer;
  11345. if (timeout) {
  11346. timer = setTimeout(() => {
  11347. reject(new Error(`timeout after ${timeout}s`));
  11348. }, timeout * 1000);
  11349. }
  11350. child_process_1.exec(cmd, { cwd }, (err, stdout) => {
  11351. if (timer)
  11352. clearTimeout(timer);
  11353. if (err) {
  11354. reject(new Error(`exited with ${err.code}`));
  11355. return;
  11356. }
  11357. resolve(stdout);
  11358. });
  11359. });
  11360. }
  11361. exports.runCommand = runCommand;
  11362. function getManager() {
  11363. return __awaiter(this, void 0, void 0, function* () {
  11364. let res = yield coc_nvim_1.workspace.findUp(['yarn.lock', 'package-lock.json']);
  11365. if (!res)
  11366. return 'yarn';
  11367. return res.endsWith('yarn.lock') ? 'yarn' : 'npm';
  11368. });
  11369. }
  11370. function getRoot() {
  11371. return __awaiter(this, void 0, void 0, function* () {
  11372. let res = yield coc_nvim_1.workspace.findUp(['package.json']);
  11373. if (!res)
  11374. return null;
  11375. return path_1.default.dirname(res);
  11376. });
  11377. }
  11378. function moduleExists(name) {
  11379. return __awaiter(this, void 0, void 0, function* () {
  11380. try {
  11381. let content = yield runCommand(`npm info ${name} --json`, process.cwd());
  11382. if (!content)
  11383. return false;
  11384. let obj = JSON.parse(content);
  11385. if (obj.error != null)
  11386. return false;
  11387. return true;
  11388. }
  11389. catch (e) {
  11390. return false;
  11391. }
  11392. return false;
  11393. });
  11394. }
  11395. exports.moduleExists = moduleExists;
  11396. /**
  11397. * Removes duplicates from the given array. The optional keyFn allows to specify
  11398. * how elements are checked for equalness by returning a unique string for each.
  11399. */
  11400. function distinct(array, keyFn) {
  11401. if (!keyFn) {
  11402. return array.filter((element, position) => {
  11403. return array.indexOf(element) === position;
  11404. });
  11405. }
  11406. const seen = Object.create(null);
  11407. return array.filter(elem => {
  11408. const key = keyFn(elem);
  11409. if (seen[key]) {
  11410. return false;
  11411. }
  11412. seen[key] = true;
  11413. return true;
  11414. });
  11415. }
  11416. exports.distinct = distinct;
  11417. function installModules(uri, names) {
  11418. return __awaiter(this, void 0, void 0, function* () {
  11419. names = distinct(names);
  11420. let root = yield getRoot();
  11421. if (!root) {
  11422. coc_nvim_1.workspace.showMessage(`package.json not found from cwd: ${coc_nvim_1.workspace.cwd}`, 'error');
  11423. return;
  11424. }
  11425. let arr = names.concat(names.map(s => `@types/${s}`));
  11426. let statusItem = coc_nvim_1.workspace.createStatusBarItem(99, { progress: true });
  11427. statusItem.text = `Checking module ${arr.join(' ')}`;
  11428. statusItem.show();
  11429. let exists = yield Promise.all(arr.map(name => {
  11430. return moduleExists(name).then(exists => {
  11431. return exists ? name : null;
  11432. });
  11433. }));
  11434. let manager = yield getManager();
  11435. exists = exists.filter(s => s != null);
  11436. if (!exists.length)
  11437. return;
  11438. let devs = exists.filter(s => s.startsWith('@types'));
  11439. let deps = exists.filter(s => devs.indexOf(s) == -1);
  11440. statusItem.text = `Installing ${exists.join(' ')}`;
  11441. try {
  11442. yield Promise.all([deps, devs].map((names, i) => {
  11443. let cmd = manager == 'npm' ? `npm i ${names.join(' ')}` : `yarn add ${names.join(' ')} --ignore-scripts --no-default-rc`;
  11444. if (i == 1)
  11445. cmd = cmd + ' --dev';
  11446. return runCommand(cmd, root);
  11447. }));
  11448. }
  11449. catch (e) {
  11450. statusItem.dispose();
  11451. coc_nvim_1.workspace.showMessage(`Install error ${e.message}`, 'error');
  11452. return;
  11453. }
  11454. statusItem.dispose();
  11455. coc_nvim_1.workspace.showMessage(`Installed: ${exists.join(' ')}`, 'more');
  11456. });
  11457. }
  11458. exports.installModules = installModules;
  11459. /***/ }),
  11460. /* 113 */
  11461. /***/ (function(module, exports) {
  11462. module.exports = require("child_process");
  11463. /***/ }),
  11464. /* 114 */
  11465. /***/ (function(module, exports, __webpack_require__) {
  11466. "use strict";
  11467. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  11468. if (k2 === undefined) k2 = k;
  11469. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  11470. }) : (function(o, m, k, k2) {
  11471. if (k2 === undefined) k2 = k;
  11472. o[k2] = m[k];
  11473. }));
  11474. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  11475. Object.defineProperty(o, "default", { enumerable: true, value: v });
  11476. }) : function(o, v) {
  11477. o["default"] = v;
  11478. });
  11479. var __importStar = (this && this.__importStar) || function (mod) {
  11480. if (mod && mod.__esModule) return mod;
  11481. var result = {};
  11482. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  11483. __setModuleDefault(result, mod);
  11484. return result;
  11485. };
  11486. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  11487. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  11488. return new (P || (P = Promise))(function (resolve, reject) {
  11489. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  11490. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  11491. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  11492. step((generator = generator.apply(thisArg, _arguments || [])).next());
  11493. });
  11494. };
  11495. Object.defineProperty(exports, "__esModule", { value: true });
  11496. exports.OrganizeImportsCodeActionProvider = exports.OrganizeImportsCommand = void 0;
  11497. /*---------------------------------------------------------------------------------------------
  11498. * Copyright (c) Microsoft Corporation. All rights reserved.
  11499. * Licensed under the MIT License. See License.txt in the project root for license information.
  11500. *--------------------------------------------------------------------------------------------*/
  11501. const coc_nvim_1 = __webpack_require__(1);
  11502. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  11503. const languageDescription_1 = __webpack_require__(115);
  11504. const languageModeIds_1 = __webpack_require__(116);
  11505. const typeconverts = __importStar(__webpack_require__(37));
  11506. class OrganizeImportsCommand {
  11507. constructor(client) {
  11508. this.client = client;
  11509. this.id = 'tsserver.organizeImports';
  11510. }
  11511. getTextEdits(document) {
  11512. return __awaiter(this, void 0, void 0, function* () {
  11513. let client = this.client;
  11514. let file = client.toPath(document.uri);
  11515. const args = {
  11516. scope: {
  11517. type: 'file',
  11518. args: {
  11519. file
  11520. }
  11521. }
  11522. };
  11523. const response = yield this.client.interruptGetErr(() => this.client.execute('organizeImports', args, vscode_languageserver_protocol_1.CancellationToken.None));
  11524. if (!response || response.type != 'response' || !response.success) {
  11525. return;
  11526. }
  11527. const edit = typeconverts.WorkspaceEdit.fromFileCodeEdits(client, response.body);
  11528. let desc = languageDescription_1.standardLanguageDescriptions.find(o => o.modeIds.indexOf(document.languageId) !== -1);
  11529. if (!desc)
  11530. return null;
  11531. return edit;
  11532. });
  11533. }
  11534. execute(document) {
  11535. return __awaiter(this, void 0, void 0, function* () {
  11536. if (!document) {
  11537. let doc = yield coc_nvim_1.workspace.document;
  11538. if (languageModeIds_1.languageIds.indexOf(doc.filetype) == -1)
  11539. return;
  11540. document = doc.textDocument;
  11541. }
  11542. let edit = yield this.getTextEdits(document);
  11543. if (edit)
  11544. yield coc_nvim_1.workspace.applyEdit(edit);
  11545. return;
  11546. });
  11547. }
  11548. }
  11549. exports.OrganizeImportsCommand = OrganizeImportsCommand;
  11550. class OrganizeImportsCodeActionProvider {
  11551. // public static readonly minVersion = API.v280
  11552. constructor(client, fileConfigManager) {
  11553. this.client = client;
  11554. this.fileConfigManager = fileConfigManager;
  11555. this.metadata = {
  11556. providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]
  11557. };
  11558. }
  11559. provideCodeActions(document, _range, context, _token) {
  11560. if (languageModeIds_1.languageIds.indexOf(document.languageId) == -1)
  11561. return;
  11562. if (!context.only || !context.only.includes(vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports)) {
  11563. return [];
  11564. }
  11565. const action = vscode_languageserver_protocol_1.CodeAction.create('Organize Imports', {
  11566. title: '',
  11567. command: 'tsserver.organizeImports',
  11568. arguments: [document]
  11569. }, vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports);
  11570. return [action];
  11571. }
  11572. }
  11573. exports.OrganizeImportsCodeActionProvider = OrganizeImportsCodeActionProvider;
  11574. /***/ }),
  11575. /* 115 */
  11576. /***/ (function(module, exports, __webpack_require__) {
  11577. "use strict";
  11578. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  11579. if (k2 === undefined) k2 = k;
  11580. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  11581. }) : (function(o, m, k, k2) {
  11582. if (k2 === undefined) k2 = k;
  11583. o[k2] = m[k];
  11584. }));
  11585. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  11586. Object.defineProperty(o, "default", { enumerable: true, value: v });
  11587. }) : function(o, v) {
  11588. o["default"] = v;
  11589. });
  11590. var __importStar = (this && this.__importStar) || function (mod) {
  11591. if (mod && mod.__esModule) return mod;
  11592. var result = {};
  11593. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  11594. __setModuleDefault(result, mod);
  11595. return result;
  11596. };
  11597. Object.defineProperty(exports, "__esModule", { value: true });
  11598. exports.standardLanguageDescriptions = void 0;
  11599. /*---------------------------------------------------------------------------------------------
  11600. * Copyright (c) Microsoft Corporation. All rights reserved.
  11601. * Licensed under the MIT License. See License.txt in the project root for license information.
  11602. *--------------------------------------------------------------------------------------------*/
  11603. const languageModeIds = __importStar(__webpack_require__(116));
  11604. exports.standardLanguageDescriptions = [
  11605. {
  11606. id: 'typescript',
  11607. diagnosticSource: 'ts',
  11608. diagnosticOwner: 'typescript',
  11609. modeIds: [languageModeIds.typescript, languageModeIds.typescriptreact,
  11610. languageModeIds.typescripttsx, languageModeIds.typescriptjsx],
  11611. diagnosticLanguage: 1 /* TypeScript */,
  11612. configFile: 'tsconfig.json'
  11613. },
  11614. {
  11615. id: 'javascript',
  11616. diagnosticSource: 'ts',
  11617. diagnosticOwner: 'typescript',
  11618. modeIds: [languageModeIds.javascript, languageModeIds.javascriptreact],
  11619. diagnosticLanguage: 0 /* JavaScript */,
  11620. configFile: 'jsconfig.json'
  11621. }
  11622. ];
  11623. /***/ }),
  11624. /* 116 */
  11625. /***/ (function(module, exports, __webpack_require__) {
  11626. "use strict";
  11627. /*---------------------------------------------------------------------------------------------
  11628. * Copyright (c) Microsoft Corporation. All rights reserved.
  11629. * Licensed under the MIT License. See License.txt in the project root for license information.
  11630. *--------------------------------------------------------------------------------------------*/
  11631. Object.defineProperty(exports, "__esModule", { value: true });
  11632. exports.languageIds = exports.jsxTags = exports.javascriptjsx = exports.javascriptreact = exports.javascript = exports.typescriptjsx = exports.typescripttsx = exports.typescriptreact = exports.typescript = void 0;
  11633. exports.typescript = 'typescript';
  11634. exports.typescriptreact = 'typescriptreact';
  11635. exports.typescripttsx = 'typescript.tsx';
  11636. exports.typescriptjsx = 'typescript.jsx';
  11637. exports.javascript = 'javascript';
  11638. exports.javascriptreact = 'javascriptreact';
  11639. exports.javascriptjsx = 'javascript.jsx';
  11640. exports.jsxTags = 'jsx-tags';
  11641. exports.languageIds = [exports.typescript, exports.typescriptreact, exports.javascript, exports.javascriptreact, exports.javascriptjsx, exports.typescripttsx, exports.jsxTags];
  11642. /***/ }),
  11643. /* 117 */
  11644. /***/ (function(module, exports, __webpack_require__) {
  11645. "use strict";
  11646. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  11647. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  11648. return new (P || (P = Promise))(function (resolve, reject) {
  11649. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  11650. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  11651. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  11652. step((generator = generator.apply(thisArg, _arguments || [])).next());
  11653. });
  11654. };
  11655. var __importDefault = (this && this.__importDefault) || function (mod) {
  11656. return (mod && mod.__esModule) ? mod : { "default": mod };
  11657. };
  11658. Object.defineProperty(exports, "__esModule", { value: true });
  11659. const fs_1 = __importDefault(__webpack_require__(118));
  11660. const os_1 = __importDefault(__webpack_require__(14));
  11661. const path_1 = __importDefault(__webpack_require__(13));
  11662. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  11663. const which_1 = __importDefault(__webpack_require__(119));
  11664. const coc_nvim_1 = __webpack_require__(1);
  11665. const fileConfigurationManager_1 = __importDefault(__webpack_require__(93));
  11666. const typescriptService_1 = __webpack_require__(123);
  11667. const api_1 = __importDefault(__webpack_require__(40));
  11668. const configuration_1 = __webpack_require__(124);
  11669. const logger_1 = __importDefault(__webpack_require__(125));
  11670. const process_1 = __webpack_require__(127);
  11671. const tracer_1 = __importDefault(__webpack_require__(128));
  11672. const tsconfig_1 = __webpack_require__(129);
  11673. const versionProvider_1 = __webpack_require__(130);
  11674. const versionStatus_1 = __importDefault(__webpack_require__(131));
  11675. const wireProtocol_1 = __webpack_require__(132);
  11676. const callbackMap_1 = __webpack_require__(133);
  11677. const requestQueue_1 = __webpack_require__(134);
  11678. const bufferSyncSupport_1 = __importDefault(__webpack_require__(135));
  11679. const diagnostics_1 = __webpack_require__(137);
  11680. class ForkedTsServerProcess {
  11681. constructor(childProcess) {
  11682. this.childProcess = childProcess;
  11683. }
  11684. onError(cb) {
  11685. this.childProcess.on('error', cb);
  11686. }
  11687. onExit(cb) {
  11688. this.childProcess.on('exit', cb);
  11689. }
  11690. write(serverRequest) {
  11691. this.childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8');
  11692. }
  11693. createReader(callback, onError) {
  11694. // tslint:disable-next-line:no-unused-expression
  11695. new wireProtocol_1.Reader(this.childProcess.stdout, callback, onError);
  11696. }
  11697. kill() {
  11698. this.childProcess.kill();
  11699. }
  11700. }
  11701. class TypeScriptServiceClient {
  11702. constructor(pluginManager) {
  11703. this.pluginManager = pluginManager;
  11704. this.state = coc_nvim_1.ServiceStat.Initial;
  11705. this.logger = new logger_1.default();
  11706. this.tsServerLogFile = null;
  11707. this.cancellationPipeName = null;
  11708. this._callbacks = new callbackMap_1.CallbackMap();
  11709. this._requestQueue = new requestQueue_1.RequestQueue();
  11710. this._pendingResponses = new Set();
  11711. this._onTsServerStarted = new vscode_languageserver_protocol_1.Emitter();
  11712. this._onProjectLanguageServiceStateChanged = new vscode_languageserver_protocol_1.Emitter();
  11713. this._onDidBeginInstallTypings = new vscode_languageserver_protocol_1.Emitter();
  11714. this._onDidEndInstallTypings = new vscode_languageserver_protocol_1.Emitter();
  11715. this._onTypesInstallerInitializationFailed = new vscode_languageserver_protocol_1.Emitter();
  11716. this.disposables = [];
  11717. this.isRestarting = false;
  11718. this._onDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
  11719. this._onConfigDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
  11720. this._onResendModelsRequested = new vscode_languageserver_protocol_1.Emitter();
  11721. this.pathSeparator = path_1.default.sep;
  11722. this.lastStart = Date.now();
  11723. this.servicePromise = null;
  11724. this.lastError = null;
  11725. this.numberRestarts = 0;
  11726. this.fileConfigurationManager = new fileConfigurationManager_1.default(this);
  11727. this._configuration = configuration_1.TypeScriptServiceConfiguration.loadFromWorkspace();
  11728. this.versionProvider = new versionProvider_1.TypeScriptVersionProvider(this._configuration);
  11729. this._apiVersion = api_1.default.defaultVersion;
  11730. this.tracer = new tracer_1.default(this.logger);
  11731. this.versionStatus = new versionStatus_1.default(this.normalizePath.bind(this), this.fileConfigurationManager.enableJavascript());
  11732. pluginManager.onDidUpdateConfig(update => {
  11733. this.configurePlugin(update.pluginId, update.config);
  11734. }, null, this.disposables);
  11735. pluginManager.onDidChangePlugins(() => {
  11736. this.restartTsServer();
  11737. }, null, this.disposables);
  11738. this.bufferSyncSupport = new bufferSyncSupport_1.default(this);
  11739. this.onTsServerStarted(() => {
  11740. this.bufferSyncSupport.listen();
  11741. });
  11742. this.diagnosticsManager = new diagnostics_1.DiagnosticsManager();
  11743. this.bufferSyncSupport.onDelete(resource => {
  11744. this.diagnosticsManager.delete(resource);
  11745. }, null, this.disposables);
  11746. }
  11747. get onDiagnosticsReceived() {
  11748. return this._onDiagnosticsReceived.event;
  11749. }
  11750. get onConfigDiagnosticsReceived() {
  11751. return this._onConfigDiagnosticsReceived.event;
  11752. }
  11753. get onResendModelsRequested() {
  11754. return this._onResendModelsRequested.event;
  11755. }
  11756. get configuration() {
  11757. return this._configuration;
  11758. }
  11759. dispose() {
  11760. if (this.servicePromise) {
  11761. this.servicePromise
  11762. .then(childProcess => {
  11763. childProcess.kill();
  11764. })
  11765. .then(undefined, () => void 0);
  11766. }
  11767. this.bufferSyncSupport.dispose();
  11768. coc_nvim_1.disposeAll(this.disposables);
  11769. this.logger.dispose();
  11770. this._onTsServerStarted.dispose();
  11771. this._onResendModelsRequested.dispose();
  11772. this.versionStatus.dispose();
  11773. }
  11774. info(message, data) {
  11775. this.logger.info(message, data);
  11776. }
  11777. error(message, data) {
  11778. this.logger.error(message, data);
  11779. }
  11780. restartTsServer() {
  11781. const start = () => {
  11782. this.servicePromise = this.startService(true);
  11783. return this.servicePromise;
  11784. };
  11785. if (this.servicePromise) {
  11786. return Promise.resolve(this.servicePromise.then(childProcess => {
  11787. this.state = coc_nvim_1.ServiceStat.Stopping;
  11788. this.info('Killing TS Server');
  11789. this.isRestarting = true;
  11790. childProcess.kill();
  11791. this.servicePromise = null;
  11792. }).then(start));
  11793. }
  11794. else {
  11795. return Promise.resolve(start());
  11796. }
  11797. }
  11798. stop() {
  11799. if (!this.servicePromise)
  11800. return;
  11801. return new Promise((resolve, reject) => {
  11802. this.servicePromise.then(childProcess => {
  11803. if (this.state == coc_nvim_1.ServiceStat.Running) {
  11804. this.info('Killing TS Server');
  11805. childProcess.onExit(() => {
  11806. resolve();
  11807. });
  11808. childProcess.kill();
  11809. this.servicePromise = null;
  11810. }
  11811. else {
  11812. resolve();
  11813. }
  11814. }, reject);
  11815. });
  11816. }
  11817. get onTsServerStarted() {
  11818. return this._onTsServerStarted.event;
  11819. }
  11820. get onProjectLanguageServiceStateChanged() {
  11821. return this._onProjectLanguageServiceStateChanged.event;
  11822. }
  11823. get onDidBeginInstallTypings() {
  11824. return this._onDidBeginInstallTypings.event;
  11825. }
  11826. get onDidEndInstallTypings() {
  11827. return this._onDidEndInstallTypings.event;
  11828. }
  11829. get onTypesInstallerInitializationFailed() {
  11830. return this._onTypesInstallerInitializationFailed.event;
  11831. }
  11832. get apiVersion() {
  11833. return this._apiVersion;
  11834. }
  11835. get tscPath() {
  11836. return this._tscPath;
  11837. }
  11838. service() {
  11839. if (this.servicePromise) {
  11840. return this.servicePromise;
  11841. }
  11842. if (this.lastError) {
  11843. return Promise.reject(this.lastError);
  11844. }
  11845. return this.startService().then(() => {
  11846. if (this.servicePromise) {
  11847. return this.servicePromise;
  11848. }
  11849. });
  11850. }
  11851. ensureServiceStarted() {
  11852. if (!this.servicePromise) {
  11853. this.startService().catch(err => {
  11854. coc_nvim_1.workspace.showMessage(`TSServer start failed: ${err.message}`, 'error');
  11855. this.error(`Service start failed: ${err.stack}`);
  11856. });
  11857. }
  11858. }
  11859. startService(resendModels = false) {
  11860. return __awaiter(this, void 0, void 0, function* () {
  11861. const { ignoreLocalTsserver } = this.configuration;
  11862. let currentVersion;
  11863. if (!ignoreLocalTsserver)
  11864. currentVersion = this.versionProvider.getLocalVersion();
  11865. if (!currentVersion || !fs_1.default.existsSync(currentVersion.tsServerPath)) {
  11866. currentVersion = this.versionProvider.getDefaultVersion();
  11867. }
  11868. if (!currentVersion || !currentVersion.isValid) {
  11869. if (this.configuration.globalTsdk) {
  11870. coc_nvim_1.workspace.showMessage(`Can not find typescript module, in 'tsserver.tsdk': ${this.configuration.globalTsdk}`, 'error');
  11871. }
  11872. else {
  11873. coc_nvim_1.workspace.showMessage(`Can not find typescript module, run ':CocInstall coc-tsserver' to fix it!`, 'error');
  11874. }
  11875. return;
  11876. }
  11877. this._apiVersion = currentVersion.version;
  11878. this._tscPath = currentVersion.tscPath;
  11879. this.versionStatus.onDidChangeTypeScriptVersion(currentVersion);
  11880. this.lastError = null;
  11881. const tsServerForkArgs = yield this.getTsServerArgs();
  11882. const debugPort = this._configuration.debugPort;
  11883. const maxTsServerMemory = this._configuration.maxTsServerMemory;
  11884. const options = {
  11885. execArgv: [
  11886. ...(debugPort ? [`--inspect=${debugPort}`] : []),
  11887. ...(maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : []),
  11888. ],
  11889. cwd: coc_nvim_1.workspace.root
  11890. };
  11891. this.servicePromise = this.startProcess(currentVersion, tsServerForkArgs, options, resendModels);
  11892. return this.servicePromise;
  11893. });
  11894. }
  11895. startProcess(currentVersion, args, options, resendModels) {
  11896. this.state = coc_nvim_1.ServiceStat.Starting;
  11897. return new Promise((resolve, reject) => {
  11898. try {
  11899. process_1.fork(currentVersion.tsServerPath, args, options, this.logger, (err, childProcess) => {
  11900. if (err || !childProcess) {
  11901. this.state = coc_nvim_1.ServiceStat.StartFailed;
  11902. this.lastError = err;
  11903. this.error('Starting TSServer failed with error.', err.stack);
  11904. return;
  11905. }
  11906. this.state = coc_nvim_1.ServiceStat.Running;
  11907. this.info('Started TSServer', JSON.stringify(currentVersion, null, 2));
  11908. const handle = new ForkedTsServerProcess(childProcess);
  11909. this.lastStart = Date.now();
  11910. handle.onError((err) => {
  11911. this.lastError = err;
  11912. this.error('TSServer errored with error.', err);
  11913. this.error(`TSServer log file: ${this.tsServerLogFile || ''}`);
  11914. coc_nvim_1.workspace.showMessage(`TSServer errored with error. ${err.message}`, 'error');
  11915. this.serviceExited(false);
  11916. });
  11917. handle.onExit((code) => {
  11918. if (code == null) {
  11919. this.info('TSServer normal exit');
  11920. }
  11921. else {
  11922. this.error(`TSServer exited with code: ${code}`);
  11923. }
  11924. this.info(`TSServer log file: ${this.tsServerLogFile || ''}`);
  11925. this.serviceExited(!this.isRestarting);
  11926. this.isRestarting = false;
  11927. });
  11928. handle.createReader(msg => {
  11929. this.dispatchMessage(msg);
  11930. }, error => {
  11931. this.error('ReaderError', error);
  11932. });
  11933. resolve(handle);
  11934. this.serviceStarted(resendModels);
  11935. this._onTsServerStarted.fire(currentVersion.version);
  11936. });
  11937. }
  11938. catch (e) {
  11939. reject(e);
  11940. }
  11941. });
  11942. }
  11943. openTsServerLogFile() {
  11944. return __awaiter(this, void 0, void 0, function* () {
  11945. const isRoot = process.getuid && process.getuid() == 0;
  11946. let echoErr = (msg) => {
  11947. coc_nvim_1.workspace.showMessage(msg, 'error');
  11948. };
  11949. if (isRoot) {
  11950. echoErr('Log disabled for root user.');
  11951. return false;
  11952. }
  11953. if (!this.apiVersion.gte(api_1.default.v222)) {
  11954. echoErr('TS Server logging requires TS 2.2.2+');
  11955. return false;
  11956. }
  11957. if (this._configuration.tsServerLogLevel === configuration_1.TsServerLogLevel.Off) {
  11958. echoErr(`TS Server logging is off. Change 'tsserver.log' in 'coc-settings.json' to enable`);
  11959. return false;
  11960. }
  11961. if (!this.tsServerLogFile) {
  11962. echoErr('TS Server has not started logging.');
  11963. return false;
  11964. }
  11965. try {
  11966. yield coc_nvim_1.workspace.nvim.command(`edit ${this.tsServerLogFile}`);
  11967. return true;
  11968. }
  11969. catch (_a) {
  11970. echoErr('Could not open TS Server log file');
  11971. return false;
  11972. }
  11973. });
  11974. }
  11975. serviceStarted(resendModels) {
  11976. const watchOptions = this.apiVersion.gte(api_1.default.v380)
  11977. ? this.configuration.watchOptions
  11978. : undefined;
  11979. const configureOptions = {
  11980. hostInfo: 'coc-nvim',
  11981. preferences: {
  11982. providePrefixAndSuffixTextForRename: true,
  11983. allowRenameOfImportPath: true,
  11984. },
  11985. watchOptions
  11986. };
  11987. this.executeWithoutWaitingForResponse('configure', configureOptions); // tslint:disable-line
  11988. this.setCompilerOptionsForInferredProjects(this._configuration);
  11989. if (resendModels) {
  11990. this._onResendModelsRequested.fire(void 0);
  11991. this.diagnosticsManager.reInitialize();
  11992. this.bufferSyncSupport.reinitialize();
  11993. }
  11994. // Reconfigure any plugins
  11995. for (const [config, pluginName] of this.pluginManager.configurations()) {
  11996. this.configurePlugin(config, pluginName);
  11997. }
  11998. }
  11999. setCompilerOptionsForInferredProjects(configuration) {
  12000. if (!this.apiVersion.gte(api_1.default.v206))
  12001. return;
  12002. const args = {
  12003. options: this.getCompilerOptionsForInferredProjects(configuration)
  12004. };
  12005. this.executeWithoutWaitingForResponse('compilerOptionsForInferredProjects', args); // tslint:disable-line
  12006. }
  12007. getCompilerOptionsForInferredProjects(configuration) {
  12008. return Object.assign(Object.assign({}, tsconfig_1.inferredProjectConfig(configuration)), { allowJs: true, allowSyntheticDefaultImports: true, allowNonTsExtensions: true });
  12009. }
  12010. serviceExited(restart) {
  12011. this.state = coc_nvim_1.ServiceStat.Stopped;
  12012. this.servicePromise = null;
  12013. this.tsServerLogFile = null;
  12014. this._callbacks.destroy('Service died.');
  12015. this._callbacks = new callbackMap_1.CallbackMap();
  12016. this._requestQueue = new requestQueue_1.RequestQueue();
  12017. this._pendingResponses = new Set();
  12018. if (restart) {
  12019. const diff = Date.now() - this.lastStart;
  12020. this.numberRestarts++;
  12021. let startService = true;
  12022. if (this.numberRestarts > 5) {
  12023. this.numberRestarts = 0;
  12024. if (diff < 10 * 1000 /* 10 seconds */) {
  12025. this.lastStart = Date.now();
  12026. startService = false;
  12027. coc_nvim_1.workspace.showMessage('The TypeScript language service died 5 times right after it got started.', 'error'); // tslint:disable-line
  12028. }
  12029. else if (diff < 60 * 1000 /* 1 Minutes */) {
  12030. this.lastStart = Date.now();
  12031. coc_nvim_1.workspace.showMessage('The TypeScript language service died unexpectedly 5 times in the last 5 Minutes.', 'error'); // tslint:disable-line
  12032. }
  12033. }
  12034. if (startService) {
  12035. this.startService(true); // tslint:disable-line
  12036. }
  12037. }
  12038. }
  12039. toPath(uri) {
  12040. return this.normalizePath(coc_nvim_1.Uri.parse(uri));
  12041. }
  12042. toResource(filepath) {
  12043. if (this._apiVersion.gte(api_1.default.v213)) {
  12044. if (filepath.startsWith('untitled:')) {
  12045. let resource = coc_nvim_1.Uri.parse(filepath);
  12046. if (this.inMemoryResourcePrefix) {
  12047. const dirName = path_1.default.dirname(resource.path);
  12048. const fileName = path_1.default.basename(resource.path);
  12049. if (fileName.startsWith(this.inMemoryResourcePrefix)) {
  12050. resource = resource.with({ path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length)) });
  12051. }
  12052. }
  12053. return resource.toString();
  12054. }
  12055. }
  12056. return coc_nvim_1.Uri.file(filepath).toString();
  12057. }
  12058. normalizePath(resource) {
  12059. if (this._apiVersion.gte(api_1.default.v213)) {
  12060. if (resource.scheme == 'untitled') {
  12061. const dirName = path_1.default.dirname(resource.path);
  12062. const fileName = this.inMemoryResourcePrefix + path_1.default.basename(resource.path);
  12063. return resource
  12064. .with({ path: path_1.default.posix.join(dirName, fileName) })
  12065. .toString(true);
  12066. }
  12067. }
  12068. const result = resource.fsPath;
  12069. if (!result)
  12070. return null;
  12071. // Both \ and / must be escaped in regular expressions
  12072. return result.replace(new RegExp('\\' + this.pathSeparator, 'g'), '/');
  12073. }
  12074. get inMemoryResourcePrefix() {
  12075. return this._apiVersion.gte(api_1.default.v270) ? '^' : '';
  12076. }
  12077. asUrl(filepath) {
  12078. if (this._apiVersion.gte(api_1.default.v213)) {
  12079. if (filepath.startsWith('untitled:')) {
  12080. let resource = coc_nvim_1.Uri.parse(filepath);
  12081. if (this.inMemoryResourcePrefix) {
  12082. const dirName = path_1.default.dirname(resource.path);
  12083. const fileName = path_1.default.basename(resource.path);
  12084. if (fileName.startsWith(this.inMemoryResourcePrefix)) {
  12085. resource = resource.with({
  12086. path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length))
  12087. });
  12088. }
  12089. }
  12090. return resource;
  12091. }
  12092. }
  12093. return coc_nvim_1.Uri.file(filepath);
  12094. }
  12095. execute(command, args, token, lowPriority) {
  12096. return this.executeImpl(command, args, {
  12097. isAsync: false,
  12098. token,
  12099. expectsResult: true,
  12100. lowPriority
  12101. });
  12102. }
  12103. executeAsync(command, args, token) {
  12104. return this.executeImpl(command, args, {
  12105. isAsync: true,
  12106. token,
  12107. expectsResult: true
  12108. });
  12109. }
  12110. executeWithoutWaitingForResponse(command, args) {
  12111. this.executeImpl(command, args, {
  12112. isAsync: false,
  12113. token: undefined,
  12114. expectsResult: false
  12115. });
  12116. }
  12117. executeImpl(command, args, executeInfo) {
  12118. if (this.servicePromise == null) {
  12119. return Promise.resolve(undefined);
  12120. }
  12121. this.bufferSyncSupport.beforeCommand(command);
  12122. const request = this._requestQueue.createRequest(command, args);
  12123. const requestInfo = {
  12124. request,
  12125. expectsResponse: executeInfo.expectsResult,
  12126. isAsync: executeInfo.isAsync,
  12127. queueingType: getQueueingType(command, executeInfo.lowPriority)
  12128. };
  12129. let result;
  12130. if (executeInfo.expectsResult) {
  12131. result = new Promise((resolve, reject) => {
  12132. this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync);
  12133. if (executeInfo.token) {
  12134. executeInfo.token.onCancellationRequested(() => {
  12135. this.tryCancelRequest(request.seq, command);
  12136. });
  12137. }
  12138. }).catch((err) => {
  12139. throw err;
  12140. });
  12141. }
  12142. this._requestQueue.enqueue(requestInfo);
  12143. this.sendNextRequests();
  12144. return result;
  12145. }
  12146. sendNextRequests() {
  12147. while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
  12148. const item = this._requestQueue.dequeue();
  12149. if (item) {
  12150. this.sendRequest(item);
  12151. }
  12152. }
  12153. }
  12154. sendRequest(requestItem) {
  12155. const serverRequest = requestItem.request;
  12156. this.tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length);
  12157. if (requestItem.expectsResponse && !requestItem.isAsync) {
  12158. this._pendingResponses.add(requestItem.request.seq);
  12159. }
  12160. this.service().then(childProcess => {
  12161. try {
  12162. childProcess.write(serverRequest);
  12163. }
  12164. catch (err) {
  12165. const callback = this.fetchCallback(serverRequest.seq);
  12166. if (callback) {
  12167. callback.onError(err);
  12168. }
  12169. }
  12170. });
  12171. }
  12172. tryCancelRequest(seq, command) {
  12173. try {
  12174. if (this._requestQueue.tryDeletePendingRequest(seq)) {
  12175. this.tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
  12176. return true;
  12177. }
  12178. if (this.cancellationPipeName) {
  12179. this.tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
  12180. try {
  12181. fs_1.default.writeFileSync(this.cancellationPipeName + seq, '');
  12182. }
  12183. catch (_a) {
  12184. // noop
  12185. }
  12186. return true;
  12187. }
  12188. this.tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
  12189. return false;
  12190. }
  12191. finally {
  12192. const callback = this.fetchCallback(seq);
  12193. if (callback) {
  12194. callback.onSuccess(new typescriptService_1.ServerResponse.Cancelled(`Cancelled request ${seq} - ${command}`));
  12195. }
  12196. }
  12197. }
  12198. fetchCallback(seq) {
  12199. const callback = this._callbacks.fetch(seq);
  12200. if (!callback) {
  12201. return undefined;
  12202. }
  12203. this._pendingResponses.delete(seq);
  12204. return callback;
  12205. }
  12206. dispatchMessage(message) {
  12207. try {
  12208. switch (message.type) {
  12209. case 'response':
  12210. this.dispatchResponse(message);
  12211. break;
  12212. case 'event':
  12213. const event = message;
  12214. if (event.event === 'requestCompleted') {
  12215. const seq = event.body.request_seq;
  12216. const p = this._callbacks.fetch(seq);
  12217. if (p) {
  12218. this.tracer.traceRequestCompleted('requestCompleted', seq, p.startTime);
  12219. p.onSuccess(undefined);
  12220. }
  12221. }
  12222. else {
  12223. this.tracer.traceEvent(event);
  12224. this.dispatchEvent(event);
  12225. }
  12226. break;
  12227. default:
  12228. throw new Error(`Unknown message type ${message.type} received`);
  12229. }
  12230. }
  12231. finally {
  12232. this.sendNextRequests();
  12233. }
  12234. }
  12235. dispatchResponse(response) {
  12236. const callback = this.fetchCallback(response.request_seq);
  12237. if (!callback) {
  12238. return;
  12239. }
  12240. this.tracer.traceResponse(response, callback.startTime);
  12241. if (response.success) {
  12242. callback.onSuccess(response);
  12243. }
  12244. else if (response.message === 'No content available.') {
  12245. // Special case where response itself is successful but there is not any data to return.
  12246. callback.onSuccess(typescriptService_1.ServerResponse.NoContent);
  12247. }
  12248. else {
  12249. callback.onError(new Error(response.message));
  12250. }
  12251. }
  12252. dispatchEvent(event) {
  12253. switch (event.event) {
  12254. case 'syntaxDiag':
  12255. case 'semanticDiag':
  12256. case 'suggestionDiag':
  12257. const diagnosticEvent = event;
  12258. if (diagnosticEvent.body && diagnosticEvent.body.diagnostics) {
  12259. this._onDiagnosticsReceived.fire({
  12260. kind: getDiagnosticsKind(event),
  12261. resource: this.asUrl(diagnosticEvent.body.file),
  12262. diagnostics: diagnosticEvent.body.diagnostics
  12263. });
  12264. }
  12265. break;
  12266. case 'configFileDiag':
  12267. this._onConfigDiagnosticsReceived.fire(event);
  12268. break;
  12269. case 'projectLanguageServiceState':
  12270. if (event.body) {
  12271. this._onProjectLanguageServiceStateChanged.fire(event.body);
  12272. }
  12273. break;
  12274. case 'beginInstallTypes':
  12275. if (event.body) {
  12276. this._onDidBeginInstallTypings.fire(event.body);
  12277. }
  12278. break;
  12279. case 'endInstallTypes':
  12280. if (event.body) {
  12281. this._onDidEndInstallTypings.fire(event.body);
  12282. }
  12283. break;
  12284. case 'projectsUpdatedInBackground':
  12285. const body = event.body;
  12286. const resources = body.openFiles.map(coc_nvim_1.Uri.file);
  12287. this.bufferSyncSupport.getErr(resources);
  12288. break;
  12289. case 'typesInstallerInitializationFailed':
  12290. if (event.body) {
  12291. this._onTypesInstallerInitializationFailed.fire(event.body);
  12292. }
  12293. break;
  12294. case 'projectLoadingStart':
  12295. this.versionStatus.loading = true;
  12296. break;
  12297. case 'projectLoadingFinish':
  12298. this.versionStatus.loading = false;
  12299. break;
  12300. }
  12301. }
  12302. getTsServerArgs() {
  12303. return __awaiter(this, void 0, void 0, function* () {
  12304. const args = [];
  12305. args.push('--allowLocalPluginLoads');
  12306. if (this.apiVersion.gte(api_1.default.v250)) {
  12307. args.push('--useInferredProjectPerProjectRoot');
  12308. }
  12309. else {
  12310. args.push('--useSingleInferredProject');
  12311. }
  12312. if (this.apiVersion.gte(api_1.default.v206) && this._configuration.disableAutomaticTypeAcquisition) {
  12313. args.push('--disableAutomaticTypingAcquisition');
  12314. }
  12315. if (this.apiVersion.gte(api_1.default.v222)) {
  12316. this.cancellationPipeName = process_1.getTempFile(`tscancellation-${process_1.makeRandomHexString(20)}`);
  12317. args.push('--cancellationPipeName', this.cancellationPipeName + '*');
  12318. }
  12319. if (this.apiVersion.gte(api_1.default.v222)) {
  12320. const isRoot = process.getuid && process.getuid() == 0;
  12321. if (this._configuration.tsServerLogLevel !== configuration_1.TsServerLogLevel.Off && !isRoot) {
  12322. const logDir = process_1.getTempDirectory();
  12323. if (logDir) {
  12324. this.tsServerLogFile = path_1.default.join(logDir, `tsserver.log`);
  12325. this.info('TSServer log file :', this.tsServerLogFile);
  12326. }
  12327. else {
  12328. this.tsServerLogFile = null;
  12329. this.error('Could not create TSServer log directory');
  12330. }
  12331. if (this.tsServerLogFile) {
  12332. args.push('--logVerbosity', configuration_1.TsServerLogLevel.toString(this._configuration.tsServerLogLevel));
  12333. args.push('--logFile', this.tsServerLogFile);
  12334. }
  12335. }
  12336. }
  12337. if (this.apiVersion.gte(api_1.default.v230)) {
  12338. const pluginNames = this.pluginManager.plugins.map(x => x.name);
  12339. const pluginRoot = this._configuration.tsServerPluginRoot;
  12340. const pluginPaths = pluginRoot ? [pluginRoot] : [];
  12341. if (pluginNames.length) {
  12342. args.push('--globalPlugins', pluginNames.join(','));
  12343. for (const plugin of this.pluginManager.plugins) {
  12344. pluginPaths.push(plugin.path);
  12345. }
  12346. }
  12347. if (pluginPaths.length) {
  12348. args.push('--pluginProbeLocations', pluginPaths.join(','));
  12349. }
  12350. }
  12351. if (this._configuration.typingsCacheLocation) {
  12352. args.push('--globalTypingsCacheLocation', `"${this._configuration.typingsCacheLocation}"`);
  12353. }
  12354. if (this.apiVersion.gte(api_1.default.v234)) {
  12355. if (this._configuration.npmLocation) {
  12356. args.push('--npmLocation', `"${this._configuration.npmLocation}"`);
  12357. }
  12358. else {
  12359. try {
  12360. args.push('--npmLocation', `"${which_1.default.sync('npm')}"`);
  12361. }
  12362. catch (e) { } // tslint:disable-line
  12363. }
  12364. }
  12365. if (this.apiVersion.gte(api_1.default.v291)) {
  12366. args.push('--noGetErrOnBackgroundUpdate');
  12367. }
  12368. if (this.apiVersion.gte(api_1.default.v345)) {
  12369. args.push('--validateDefaultNpmLocation');
  12370. }
  12371. return args;
  12372. });
  12373. }
  12374. getProjectRootPath(uri) {
  12375. let root = coc_nvim_1.workspace.cwd;
  12376. let u = coc_nvim_1.Uri.parse(uri);
  12377. if (u.scheme == 'file') {
  12378. let folder = coc_nvim_1.workspace.getWorkspaceFolder(uri);
  12379. if (folder) {
  12380. root = coc_nvim_1.Uri.parse(folder.uri).fsPath;
  12381. }
  12382. else {
  12383. let filepath = coc_nvim_1.Uri.parse(uri).fsPath;
  12384. if (!filepath.startsWith(root)) {
  12385. root = path_1.default.dirname(filepath);
  12386. }
  12387. }
  12388. }
  12389. if (root == os_1.default.homedir())
  12390. return null;
  12391. return root;
  12392. }
  12393. configurePlugin(pluginName, configuration) {
  12394. if (this.apiVersion.gte(api_1.default.v314)) {
  12395. if (!this.servicePromise)
  12396. return;
  12397. this.servicePromise.then(() => {
  12398. // tslint:disable-next-line: no-floating-promises
  12399. this.executeWithoutWaitingForResponse('configurePlugin', { pluginName, configuration });
  12400. });
  12401. }
  12402. }
  12403. interruptGetErr(f) {
  12404. return this.bufferSyncSupport.interuptGetErr(f);
  12405. }
  12406. }
  12407. exports.default = TypeScriptServiceClient;
  12408. function getDiagnosticsKind(event) {
  12409. switch (event.event) {
  12410. case 'syntaxDiag':
  12411. return diagnostics_1.DiagnosticKind.Syntax;
  12412. case 'semanticDiag':
  12413. return diagnostics_1.DiagnosticKind.Semantic;
  12414. case 'suggestionDiag':
  12415. return diagnostics_1.DiagnosticKind.Suggestion;
  12416. }
  12417. throw new Error('Unknown dignostics kind');
  12418. }
  12419. const fenceCommands = new Set(['change', 'close', 'open']);
  12420. function getQueueingType(command, lowPriority) {
  12421. if (fenceCommands.has(command)) {
  12422. return requestQueue_1.RequestQueueingType.Fence;
  12423. }
  12424. return lowPriority ? requestQueue_1.RequestQueueingType.LowPriority : requestQueue_1.RequestQueueingType.Normal;
  12425. }
  12426. /***/ }),
  12427. /* 118 */
  12428. /***/ (function(module, exports) {
  12429. module.exports = require("fs");
  12430. /***/ }),
  12431. /* 119 */
  12432. /***/ (function(module, exports, __webpack_require__) {
  12433. const isWindows = process.platform === 'win32' ||
  12434. process.env.OSTYPE === 'cygwin' ||
  12435. process.env.OSTYPE === 'msys'
  12436. const path = __webpack_require__(13)
  12437. const COLON = isWindows ? ';' : ':'
  12438. const isexe = __webpack_require__(120)
  12439. const getNotFoundError = (cmd) =>
  12440. Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })
  12441. const getPathInfo = (cmd, opt) => {
  12442. const colon = opt.colon || COLON
  12443. // If it has a slash, then we don't bother searching the pathenv.
  12444. // just check the file itself, and that's it.
  12445. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
  12446. : (
  12447. [
  12448. // windows always checks the cwd first
  12449. ...(isWindows ? [process.cwd()] : []),
  12450. ...(opt.path || process.env.PATH ||
  12451. /* istanbul ignore next: very unusual */ '').split(colon),
  12452. ]
  12453. )
  12454. const pathExtExe = isWindows
  12455. ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
  12456. : ''
  12457. const pathExt = isWindows ? pathExtExe.split(colon) : ['']
  12458. if (isWindows) {
  12459. if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
  12460. pathExt.unshift('')
  12461. }
  12462. return {
  12463. pathEnv,
  12464. pathExt,
  12465. pathExtExe,
  12466. }
  12467. }
  12468. const which = (cmd, opt, cb) => {
  12469. if (typeof opt === 'function') {
  12470. cb = opt
  12471. opt = {}
  12472. }
  12473. if (!opt)
  12474. opt = {}
  12475. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
  12476. const found = []
  12477. const step = i => new Promise((resolve, reject) => {
  12478. if (i === pathEnv.length)
  12479. return opt.all && found.length ? resolve(found)
  12480. : reject(getNotFoundError(cmd))
  12481. const ppRaw = pathEnv[i]
  12482. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
  12483. const pCmd = path.join(pathPart, cmd)
  12484. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  12485. : pCmd
  12486. resolve(subStep(p, i, 0))
  12487. })
  12488. const subStep = (p, i, ii) => new Promise((resolve, reject) => {
  12489. if (ii === pathExt.length)
  12490. return resolve(step(i + 1))
  12491. const ext = pathExt[ii]
  12492. isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
  12493. if (!er && is) {
  12494. if (opt.all)
  12495. found.push(p + ext)
  12496. else
  12497. return resolve(p + ext)
  12498. }
  12499. return resolve(subStep(p, i, ii + 1))
  12500. })
  12501. })
  12502. return cb ? step(0).then(res => cb(null, res), cb) : step(0)
  12503. }
  12504. const whichSync = (cmd, opt) => {
  12505. opt = opt || {}
  12506. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
  12507. const found = []
  12508. for (let i = 0; i < pathEnv.length; i ++) {
  12509. const ppRaw = pathEnv[i]
  12510. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
  12511. const pCmd = path.join(pathPart, cmd)
  12512. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  12513. : pCmd
  12514. for (let j = 0; j < pathExt.length; j ++) {
  12515. const cur = p + pathExt[j]
  12516. try {
  12517. const is = isexe.sync(cur, { pathExt: pathExtExe })
  12518. if (is) {
  12519. if (opt.all)
  12520. found.push(cur)
  12521. else
  12522. return cur
  12523. }
  12524. } catch (ex) {}
  12525. }
  12526. }
  12527. if (opt.all && found.length)
  12528. return found
  12529. if (opt.nothrow)
  12530. return null
  12531. throw getNotFoundError(cmd)
  12532. }
  12533. module.exports = which
  12534. which.sync = whichSync
  12535. /***/ }),
  12536. /* 120 */
  12537. /***/ (function(module, exports, __webpack_require__) {
  12538. var fs = __webpack_require__(118)
  12539. var core
  12540. if (process.platform === 'win32' || global.TESTING_WINDOWS) {
  12541. core = __webpack_require__(121)
  12542. } else {
  12543. core = __webpack_require__(122)
  12544. }
  12545. module.exports = isexe
  12546. isexe.sync = sync
  12547. function isexe (path, options, cb) {
  12548. if (typeof options === 'function') {
  12549. cb = options
  12550. options = {}
  12551. }
  12552. if (!cb) {
  12553. if (typeof Promise !== 'function') {
  12554. throw new TypeError('callback not provided')
  12555. }
  12556. return new Promise(function (resolve, reject) {
  12557. isexe(path, options || {}, function (er, is) {
  12558. if (er) {
  12559. reject(er)
  12560. } else {
  12561. resolve(is)
  12562. }
  12563. })
  12564. })
  12565. }
  12566. core(path, options || {}, function (er, is) {
  12567. // ignore EACCES because that just means we aren't allowed to run it
  12568. if (er) {
  12569. if (er.code === 'EACCES' || options && options.ignoreErrors) {
  12570. er = null
  12571. is = false
  12572. }
  12573. }
  12574. cb(er, is)
  12575. })
  12576. }
  12577. function sync (path, options) {
  12578. // my kingdom for a filtered catch
  12579. try {
  12580. return core.sync(path, options || {})
  12581. } catch (er) {
  12582. if (options && options.ignoreErrors || er.code === 'EACCES') {
  12583. return false
  12584. } else {
  12585. throw er
  12586. }
  12587. }
  12588. }
  12589. /***/ }),
  12590. /* 121 */
  12591. /***/ (function(module, exports, __webpack_require__) {
  12592. module.exports = isexe
  12593. isexe.sync = sync
  12594. var fs = __webpack_require__(118)
  12595. function checkPathExt (path, options) {
  12596. var pathext = options.pathExt !== undefined ?
  12597. options.pathExt : process.env.PATHEXT
  12598. if (!pathext) {
  12599. return true
  12600. }
  12601. pathext = pathext.split(';')
  12602. if (pathext.indexOf('') !== -1) {
  12603. return true
  12604. }
  12605. for (var i = 0; i < pathext.length; i++) {
  12606. var p = pathext[i].toLowerCase()
  12607. if (p && path.substr(-p.length).toLowerCase() === p) {
  12608. return true
  12609. }
  12610. }
  12611. return false
  12612. }
  12613. function checkStat (stat, path, options) {
  12614. if (!stat.isSymbolicLink() && !stat.isFile()) {
  12615. return false
  12616. }
  12617. return checkPathExt(path, options)
  12618. }
  12619. function isexe (path, options, cb) {
  12620. fs.stat(path, function (er, stat) {
  12621. cb(er, er ? false : checkStat(stat, path, options))
  12622. })
  12623. }
  12624. function sync (path, options) {
  12625. return checkStat(fs.statSync(path), path, options)
  12626. }
  12627. /***/ }),
  12628. /* 122 */
  12629. /***/ (function(module, exports, __webpack_require__) {
  12630. module.exports = isexe
  12631. isexe.sync = sync
  12632. var fs = __webpack_require__(118)
  12633. function isexe (path, options, cb) {
  12634. fs.stat(path, function (er, stat) {
  12635. cb(er, er ? false : checkStat(stat, options))
  12636. })
  12637. }
  12638. function sync (path, options) {
  12639. return checkStat(fs.statSync(path), options)
  12640. }
  12641. function checkStat (stat, options) {
  12642. return stat.isFile() && checkMode(stat, options)
  12643. }
  12644. function checkMode (stat, options) {
  12645. var mod = stat.mode
  12646. var uid = stat.uid
  12647. var gid = stat.gid
  12648. var myUid = options.uid !== undefined ?
  12649. options.uid : process.getuid && process.getuid()
  12650. var myGid = options.gid !== undefined ?
  12651. options.gid : process.getgid && process.getgid()
  12652. var u = parseInt('100', 8)
  12653. var g = parseInt('010', 8)
  12654. var o = parseInt('001', 8)
  12655. var ug = u | g
  12656. var ret = (mod & o) ||
  12657. (mod & g) && gid === myGid ||
  12658. (mod & u) && uid === myUid ||
  12659. (mod & ug) && myUid === 0
  12660. return ret
  12661. }
  12662. /***/ }),
  12663. /* 123 */
  12664. /***/ (function(module, exports, __webpack_require__) {
  12665. "use strict";
  12666. Object.defineProperty(exports, "__esModule", { value: true });
  12667. exports.ServerResponse = void 0;
  12668. var ServerResponse;
  12669. (function (ServerResponse) {
  12670. class Cancelled {
  12671. constructor(reason) {
  12672. this.reason = reason;
  12673. this.type = 'cancelled';
  12674. }
  12675. }
  12676. ServerResponse.Cancelled = Cancelled;
  12677. // tslint:disable-next-line: new-parens
  12678. ServerResponse.NoContent = new class {
  12679. constructor() {
  12680. this.type = 'noContent';
  12681. }
  12682. };
  12683. })(ServerResponse = exports.ServerResponse || (exports.ServerResponse = {}));
  12684. /***/ }),
  12685. /* 124 */
  12686. /***/ (function(module, exports, __webpack_require__) {
  12687. "use strict";
  12688. var __importDefault = (this && this.__importDefault) || function (mod) {
  12689. return (mod && mod.__esModule) ? mod : { "default": mod };
  12690. };
  12691. Object.defineProperty(exports, "__esModule", { value: true });
  12692. exports.TypeScriptServiceConfiguration = exports.TsServerLogLevel = void 0;
  12693. const coc_nvim_1 = __webpack_require__(1);
  12694. const which_1 = __importDefault(__webpack_require__(119));
  12695. var TsServerLogLevel;
  12696. (function (TsServerLogLevel) {
  12697. TsServerLogLevel[TsServerLogLevel["Off"] = 0] = "Off";
  12698. TsServerLogLevel[TsServerLogLevel["Normal"] = 1] = "Normal";
  12699. TsServerLogLevel[TsServerLogLevel["Terse"] = 2] = "Terse";
  12700. TsServerLogLevel[TsServerLogLevel["Verbose"] = 3] = "Verbose";
  12701. })(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
  12702. (function (TsServerLogLevel) {
  12703. function fromString(value) {
  12704. switch (value && value.toLowerCase()) {
  12705. case 'normal':
  12706. return TsServerLogLevel.Normal;
  12707. case 'terse':
  12708. return TsServerLogLevel.Terse;
  12709. case 'verbose':
  12710. return TsServerLogLevel.Verbose;
  12711. case 'off':
  12712. default:
  12713. return TsServerLogLevel.Off;
  12714. }
  12715. }
  12716. TsServerLogLevel.fromString = fromString;
  12717. function toString(value) {
  12718. switch (value) {
  12719. case TsServerLogLevel.Normal:
  12720. return 'normal';
  12721. case TsServerLogLevel.Terse:
  12722. return 'terse';
  12723. case TsServerLogLevel.Verbose:
  12724. return 'verbose';
  12725. case TsServerLogLevel.Off:
  12726. default:
  12727. return 'off';
  12728. }
  12729. }
  12730. TsServerLogLevel.toString = toString;
  12731. })(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
  12732. class TypeScriptServiceConfiguration {
  12733. constructor() {
  12734. this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
  12735. coc_nvim_1.workspace.onDidChangeConfiguration(() => {
  12736. this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
  12737. });
  12738. }
  12739. get locale() {
  12740. return this._configuration.get('locale', null);
  12741. }
  12742. get globalTsdk() {
  12743. return this._configuration.get('tsdk', null);
  12744. }
  12745. get ignoreLocalTsserver() {
  12746. return this._configuration.get('ignoreLocalTsserver', false);
  12747. }
  12748. get tsServerLogLevel() {
  12749. return TsServerLogLevel.fromString(this._configuration.get('log', null));
  12750. }
  12751. // public readonly watchOptions: protocol.WatchOptions | undefined;
  12752. get watchOptions() {
  12753. return this._configuration.get('watchOptions');
  12754. }
  12755. get typingsCacheLocation() {
  12756. return this._configuration.get('typingsCacheLocation', '');
  12757. }
  12758. get tsServerPluginRoot() {
  12759. return this._configuration.get('tsServerPluginRoot', null);
  12760. }
  12761. get checkJs() {
  12762. return this._configuration.get('implicitProjectConfig.checkJs', false);
  12763. }
  12764. get experimentalDecorators() {
  12765. return this._configuration.get('implicitProjectConfig.experimentalDecorators', false);
  12766. }
  12767. get disableAutomaticTypeAcquisition() {
  12768. return this._configuration.get('disableAutomaticTypeAcquisition', false);
  12769. }
  12770. get formatOnType() {
  12771. return this._configuration.get('formatOnType', false);
  12772. }
  12773. get maxTsServerMemory() {
  12774. return this._configuration.get('maxTsServerMemory', 0);
  12775. }
  12776. get debugPort() {
  12777. return this._configuration.get('debugPort', parseInt(process.env['TSS_DEBUG'], 10));
  12778. }
  12779. get npmLocation() {
  12780. let path = this._configuration.get('npm', '');
  12781. if (path)
  12782. return path;
  12783. try {
  12784. path = which_1.default.sync('npm');
  12785. }
  12786. catch (e) {
  12787. return null;
  12788. }
  12789. return path;
  12790. }
  12791. static loadFromWorkspace() {
  12792. return new TypeScriptServiceConfiguration();
  12793. }
  12794. }
  12795. exports.TypeScriptServiceConfiguration = TypeScriptServiceConfiguration;
  12796. /***/ }),
  12797. /* 125 */
  12798. /***/ (function(module, exports, __webpack_require__) {
  12799. "use strict";
  12800. /*---------------------------------------------------------------------------------------------
  12801. * Copyright (c) Microsoft Corporation. All rights reserved.
  12802. * Licensed under the MIT License. See License.txt in the project root for license information.
  12803. *--------------------------------------------------------------------------------------------*/
  12804. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  12805. if (k2 === undefined) k2 = k;
  12806. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  12807. }) : (function(o, m, k, k2) {
  12808. if (k2 === undefined) k2 = k;
  12809. o[k2] = m[k];
  12810. }));
  12811. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  12812. Object.defineProperty(o, "default", { enumerable: true, value: v });
  12813. }) : function(o, v) {
  12814. o["default"] = v;
  12815. });
  12816. var __importStar = (this && this.__importStar) || function (mod) {
  12817. if (mod && mod.__esModule) return mod;
  12818. var result = {};
  12819. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  12820. __setModuleDefault(result, mod);
  12821. return result;
  12822. };
  12823. Object.defineProperty(exports, "__esModule", { value: true });
  12824. const coc_nvim_1 = __webpack_require__(1);
  12825. const is = __importStar(__webpack_require__(126));
  12826. class Logger {
  12827. get output() {
  12828. if (this._channel) {
  12829. return this._channel;
  12830. }
  12831. this._channel = coc_nvim_1.workspace.createOutputChannel('tsserver');
  12832. return this._channel;
  12833. }
  12834. dispose() {
  12835. if (this._channel) {
  12836. this._channel.dispose();
  12837. }
  12838. }
  12839. data2String(data) {
  12840. if (data instanceof Error) {
  12841. if (is.string(data.stack)) {
  12842. return data.stack;
  12843. }
  12844. return data.message;
  12845. }
  12846. if (is.boolean(data.success) && !data.success && is.string(data.message)) {
  12847. return data.message;
  12848. }
  12849. if (is.string(data)) {
  12850. return data;
  12851. }
  12852. return data.toString();
  12853. }
  12854. info(message, data) {
  12855. this.logLevel('Info', message, data);
  12856. }
  12857. warn(message, data) {
  12858. this.logLevel('Warn', message, data);
  12859. }
  12860. error(message, data) {
  12861. // See https://github.com/Microsoft/TypeScript/issues/10496
  12862. if (data && data.message === 'No content available.') {
  12863. return;
  12864. }
  12865. this.logLevel('Error', message, data);
  12866. }
  12867. logLevel(level, message, data) {
  12868. this.output.appendLine(`[${level} - ${new Date().toLocaleTimeString()}] ${message}`);
  12869. if (data) {
  12870. this.output.appendLine(this.data2String(data));
  12871. }
  12872. }
  12873. }
  12874. exports.default = Logger;
  12875. /***/ }),
  12876. /* 126 */
  12877. /***/ (function(module, exports, __webpack_require__) {
  12878. "use strict";
  12879. /*---------------------------------------------------------------------------------------------
  12880. * Copyright (c) Microsoft Corporation. All rights reserved.
  12881. * Licensed under the MIT License. See License.txt in the project root for license information.
  12882. *--------------------------------------------------------------------------------------------*/
  12883. Object.defineProperty(exports, "__esModule", { value: true });
  12884. exports.string = exports.boolean = exports.defined = void 0;
  12885. const toString = Object.prototype.toString;
  12886. function defined(value) {
  12887. return typeof value !== 'undefined';
  12888. }
  12889. exports.defined = defined;
  12890. function boolean(value) {
  12891. return value === true || value === false;
  12892. }
  12893. exports.boolean = boolean;
  12894. function string(value) {
  12895. return toString.call(value) === '[object String]';
  12896. }
  12897. exports.string = string;
  12898. /***/ }),
  12899. /* 127 */
  12900. /***/ (function(module, exports, __webpack_require__) {
  12901. "use strict";
  12902. var __importDefault = (this && this.__importDefault) || function (mod) {
  12903. return (mod && mod.__esModule) ? mod : { "default": mod };
  12904. };
  12905. Object.defineProperty(exports, "__esModule", { value: true });
  12906. exports.fork = exports.getTempFile = exports.getTempDirectory = exports.makeRandomHexString = void 0;
  12907. /*---------------------------------------------------------------------------------------------
  12908. * Copyright (c) Microsoft Corporation. All rights reserved.
  12909. * Licensed under the MIT License. See License.txt in the project root for license information.
  12910. *--------------------------------------------------------------------------------------------*/
  12911. const child_process_1 = __importDefault(__webpack_require__(113));
  12912. const net_1 = __importDefault(__webpack_require__(16));
  12913. const os_1 = __importDefault(__webpack_require__(14));
  12914. const path_1 = __importDefault(__webpack_require__(13));
  12915. const fs_1 = __importDefault(__webpack_require__(118));
  12916. function makeRandomHexString(length) {
  12917. let chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
  12918. let result = '';
  12919. for (let i = 0; i < length; i++) {
  12920. const idx = Math.floor(chars.length * Math.random());
  12921. result += chars[idx];
  12922. }
  12923. return result;
  12924. }
  12925. exports.makeRandomHexString = makeRandomHexString;
  12926. function getTempDirectory() {
  12927. let dir = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`);
  12928. if (!fs_1.default.existsSync(dir)) {
  12929. fs_1.default.mkdirSync(dir);
  12930. }
  12931. return dir;
  12932. }
  12933. exports.getTempDirectory = getTempDirectory;
  12934. function generatePipeName() {
  12935. return getPipeName(makeRandomHexString(40));
  12936. }
  12937. function getPipeName(name) {
  12938. const fullName = 'coc-tsc-' + name;
  12939. if (process.platform === 'win32') {
  12940. return '\\\\.\\pipe\\' + fullName + '-sock';
  12941. }
  12942. const tmpdir = getTempDirectory();
  12943. // Mac/Unix: use socket file
  12944. return path_1.default.join(tmpdir, fullName + '.sock');
  12945. }
  12946. function getTempFile(name) {
  12947. const fullName = 'coc-nvim-' + name;
  12948. return path_1.default.join(getTempDirectory(), fullName + '.sock');
  12949. }
  12950. exports.getTempFile = getTempFile;
  12951. function generatePatchedEnv(env, stdInPipeName, stdOutPipeName, stdErrPipeName) {
  12952. const newEnv = Object.assign({}, env);
  12953. // Set the two unique pipe names and the electron flag as process env
  12954. newEnv['STDIN_PIPE_NAME'] = stdInPipeName; // tslint:disable-line
  12955. newEnv['STDOUT_PIPE_NAME'] = stdOutPipeName; // tslint:disable-line
  12956. newEnv['STDERR_PIPE_NAME'] = stdErrPipeName; // tslint:disable-line
  12957. newEnv['TSS_LOG'] = `-level verbose -file ${path_1.default.join(os_1.default.tmpdir(), 'coc-nvim-tsc.log')}`; // tslint:disable-line
  12958. // Ensure we always have a PATH set
  12959. newEnv['PATH'] = newEnv['PATH'] || process.env.PATH; // tslint:disable-line
  12960. return newEnv;
  12961. }
  12962. function fork(modulePath, args, options, logger, callback) {
  12963. let callbackCalled = false;
  12964. const resolve = (result) => {
  12965. if (callbackCalled) {
  12966. return;
  12967. }
  12968. callbackCalled = true;
  12969. callback(null, result);
  12970. };
  12971. const reject = (err) => {
  12972. if (callbackCalled) {
  12973. return;
  12974. }
  12975. callbackCalled = true;
  12976. callback(err, null);
  12977. };
  12978. // Generate three unique pipe names
  12979. const stdInPipeName = generatePipeName();
  12980. const stdOutPipeName = generatePipeName();
  12981. const stdErrPipeName = generatePipeName();
  12982. const newEnv = generatePatchedEnv(process.env, stdInPipeName, stdOutPipeName, stdErrPipeName);
  12983. newEnv['NODE_PATH'] = path_1.default.join(modulePath, '..', '..', '..'); // tslint:disable-line
  12984. let childProcess;
  12985. // Begin listening to stderr pipe
  12986. let stdErrServer = net_1.default.createServer(stdErrStream => {
  12987. // From now on the childProcess.stderr is available for reading
  12988. childProcess.stderr = stdErrStream;
  12989. });
  12990. stdErrServer.listen(stdErrPipeName);
  12991. // Begin listening to stdout pipe
  12992. let stdOutServer = net_1.default.createServer(stdOutStream => {
  12993. // The child process will write exactly one chunk with content `ready` when it has installed a listener to the stdin pipe
  12994. stdOutStream.once('data', (_chunk) => {
  12995. // The child process is sending me the `ready` chunk, time to connect to the stdin pipe
  12996. childProcess.stdin = net_1.default.connect(stdInPipeName);
  12997. // From now on the childProcess.stdout is available for reading
  12998. childProcess.stdout = stdOutStream;
  12999. resolve(childProcess);
  13000. });
  13001. });
  13002. stdOutServer.listen(stdOutPipeName);
  13003. let serverClosed = false;
  13004. const closeServer = () => {
  13005. if (serverClosed) {
  13006. return;
  13007. }
  13008. serverClosed = true;
  13009. stdOutServer.close();
  13010. stdErrServer.close();
  13011. };
  13012. // Create the process
  13013. logger.info('Forking TSServer', `PATH: ${newEnv['PATH']} `);
  13014. const bootstrapperPath = path_1.default.resolve(__dirname, '../bin/tsserverForkStart');
  13015. childProcess = child_process_1.default.fork(bootstrapperPath, [modulePath].concat(args), {
  13016. silent: true,
  13017. env: newEnv,
  13018. execArgv: options.execArgv
  13019. });
  13020. childProcess.once('error', (err) => {
  13021. closeServer();
  13022. reject(err);
  13023. });
  13024. childProcess.once('exit', (err) => {
  13025. closeServer();
  13026. reject(err);
  13027. });
  13028. }
  13029. exports.fork = fork;
  13030. /***/ }),
  13031. /* 128 */
  13032. /***/ (function(module, exports, __webpack_require__) {
  13033. "use strict";
  13034. Object.defineProperty(exports, "__esModule", { value: true });
  13035. /*---------------------------------------------------------------------------------------------
  13036. * Copyright (c) Microsoft Corporation. All rights reserved.
  13037. * Licensed under the MIT License. See License.txt in the project root for license information.
  13038. *--------------------------------------------------------------------------------------------*/
  13039. const coc_nvim_1 = __webpack_require__(1);
  13040. var Trace;
  13041. (function (Trace) {
  13042. Trace[Trace["Off"] = 0] = "Off";
  13043. Trace[Trace["Messages"] = 1] = "Messages";
  13044. Trace[Trace["Verbose"] = 2] = "Verbose";
  13045. })(Trace || (Trace = {}));
  13046. (function (Trace) {
  13047. function fromString(value) {
  13048. value = value || '';
  13049. value = value.toLowerCase();
  13050. switch (value) {
  13051. case 'off':
  13052. return Trace.Off;
  13053. case 'messages':
  13054. return Trace.Messages;
  13055. case 'verbose':
  13056. return Trace.Verbose;
  13057. default:
  13058. return Trace.Off;
  13059. }
  13060. }
  13061. Trace.fromString = fromString;
  13062. })(Trace || (Trace = {}));
  13063. class Tracer {
  13064. constructor(logger) {
  13065. this.logger = logger;
  13066. this.trace = Tracer.readTrace();
  13067. }
  13068. static readTrace() {
  13069. let result = Trace.fromString(coc_nvim_1.workspace.getConfiguration('tsserver').get('trace.server', 'off'));
  13070. if (result === Trace.Off && !!process.env.TSS_TRACE) {
  13071. result = Trace.Messages;
  13072. }
  13073. return result;
  13074. }
  13075. traceRequest(request, responseExpected, queueLength) {
  13076. if (this.trace === Trace.Off)
  13077. return;
  13078. let data;
  13079. if (this.trace === Trace.Verbose && request.arguments) {
  13080. data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`;
  13081. }
  13082. this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? 'yes' : 'no'}. Current queue length: ${queueLength}`, data);
  13083. }
  13084. traceResponse(response, startTime) {
  13085. if (this.trace === Trace.Off) {
  13086. return;
  13087. }
  13088. let data;
  13089. if (this.trace === Trace.Verbose && response.body) {
  13090. data = `Result: ${JSON.stringify(response.body, null, 4)}`;
  13091. }
  13092. this.logTrace(`Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? '. Message: ' + response.message : ''}`, data);
  13093. }
  13094. traceEvent(event) {
  13095. if (this.trace === Trace.Off) {
  13096. return;
  13097. }
  13098. let data;
  13099. if (this.trace === Trace.Verbose && event.body) {
  13100. data = `Data: ${JSON.stringify(event.body, null, 4)}`;
  13101. }
  13102. this.logTrace(`Event received: ${event.event} (${event.seq}).`, data);
  13103. }
  13104. logTrace(message, data) {
  13105. if (this.trace !== Trace.Off) {
  13106. this.logger.logLevel('Trace', message, data);
  13107. }
  13108. }
  13109. traceRequestCompleted(command, request_seq, startTime) {
  13110. if (this.trace === Trace.Off) {
  13111. return;
  13112. }
  13113. this.logTrace(`Async response received: ${command} (${request_seq}). Request took ${Date.now() - startTime} ms.`);
  13114. }
  13115. }
  13116. exports.default = Tracer;
  13117. /***/ }),
  13118. /* 129 */
  13119. /***/ (function(module, exports, __webpack_require__) {
  13120. "use strict";
  13121. Object.defineProperty(exports, "__esModule", { value: true });
  13122. exports.inferredProjectConfig = void 0;
  13123. function inferredProjectConfig(config) {
  13124. const base = {
  13125. module: 'commonjs',
  13126. target: 'es2016',
  13127. jsx: 'preserve'
  13128. };
  13129. if (config.checkJs) {
  13130. base.checkJs = true;
  13131. }
  13132. if (config.experimentalDecorators) {
  13133. base.experimentalDecorators = true;
  13134. }
  13135. return base;
  13136. }
  13137. exports.inferredProjectConfig = inferredProjectConfig;
  13138. /***/ }),
  13139. /* 130 */
  13140. /***/ (function(module, exports, __webpack_require__) {
  13141. "use strict";
  13142. var __importDefault = (this && this.__importDefault) || function (mod) {
  13143. return (mod && mod.__esModule) ? mod : { "default": mod };
  13144. };
  13145. Object.defineProperty(exports, "__esModule", { value: true });
  13146. exports.TypeScriptVersionProvider = exports.TypeScriptVersion = void 0;
  13147. /*---------------------------------------------------------------------------------------------
  13148. * Copyright (c) Microsoft Corporation. All rights reserved.
  13149. * Licensed under the MIT License. See License.txt in the project root for license information.
  13150. *--------------------------------------------------------------------------------------------*/
  13151. const fs_1 = __importDefault(__webpack_require__(118));
  13152. const path_1 = __importDefault(__webpack_require__(13));
  13153. const coc_nvim_1 = __webpack_require__(1);
  13154. const api_1 = __importDefault(__webpack_require__(40));
  13155. const requireFunc = true ? require : undefined;
  13156. class TypeScriptVersion {
  13157. constructor(path, _pathLabel) {
  13158. this.path = path;
  13159. this._pathLabel = _pathLabel;
  13160. this._api = null;
  13161. }
  13162. get tscPath() {
  13163. return path_1.default.resolve(this.path, '../bin/tsc');
  13164. }
  13165. get tsServerPath() {
  13166. return path_1.default.resolve(this.path, 'tsserver.js');
  13167. }
  13168. get pathLabel() {
  13169. return typeof this._pathLabel === 'undefined' ? this.path : this._pathLabel;
  13170. }
  13171. get isValid() {
  13172. return this.version != null;
  13173. }
  13174. get version() {
  13175. if (this._api)
  13176. return this._api;
  13177. let api = this._api = this.getTypeScriptVersion(this.tsServerPath);
  13178. return api;
  13179. }
  13180. get versionString() {
  13181. const version = this.version;
  13182. return version ? version.versionString : null;
  13183. }
  13184. getTypeScriptVersion(serverPath) {
  13185. if (!fs_1.default.existsSync(serverPath)) {
  13186. return undefined;
  13187. }
  13188. const p = serverPath.split(path_1.default.sep);
  13189. if (p.length <= 2) {
  13190. return undefined;
  13191. }
  13192. const p2 = p.slice(0, -2);
  13193. const modulePath = p2.join(path_1.default.sep);
  13194. let fileName = path_1.default.join(modulePath, 'package.json');
  13195. if (!fs_1.default.existsSync(fileName)) {
  13196. // Special case for ts dev versions
  13197. if (path_1.default.basename(modulePath) === 'built') {
  13198. fileName = path_1.default.join(modulePath, '..', 'package.json');
  13199. }
  13200. }
  13201. if (!fs_1.default.existsSync(fileName)) {
  13202. return undefined;
  13203. }
  13204. const contents = fs_1.default.readFileSync(fileName).toString();
  13205. let desc = null;
  13206. try {
  13207. desc = JSON.parse(contents);
  13208. }
  13209. catch (err) {
  13210. return undefined;
  13211. }
  13212. if (!desc || !desc.version) {
  13213. return undefined;
  13214. }
  13215. return desc.version ? api_1.default.fromVersionString(desc.version) : undefined;
  13216. }
  13217. }
  13218. exports.TypeScriptVersion = TypeScriptVersion;
  13219. const MODULE_FOLDERS = ['node_modules/typescript/lib', '.vscode/pnpify/typescript/lib'];
  13220. class TypeScriptVersionProvider {
  13221. constructor(configuration) {
  13222. this.configuration = configuration;
  13223. }
  13224. updateConfiguration(configuration) {
  13225. this.configuration = configuration;
  13226. }
  13227. getDefaultVersion() {
  13228. // tsdk from configuration
  13229. let { globalTsdk } = this.configuration;
  13230. if (globalTsdk)
  13231. return new TypeScriptVersion(globalTsdk);
  13232. return this.bundledVersion;
  13233. }
  13234. get globalVersion() {
  13235. let { globalTsdk } = this.configuration;
  13236. if (globalTsdk)
  13237. return new TypeScriptVersion(globalTsdk);
  13238. return undefined;
  13239. }
  13240. getLocalVersion() {
  13241. let folders = coc_nvim_1.workspace.workspaceFolders.map(f => coc_nvim_1.Uri.parse(f.uri).fsPath);
  13242. for (let p of folders) {
  13243. for (let folder of MODULE_FOLDERS) {
  13244. let libFolder = path_1.default.join(p, folder);
  13245. if (fs_1.default.existsSync(libFolder)) {
  13246. let version = new TypeScriptVersion(libFolder);
  13247. if (version.isValid)
  13248. return version;
  13249. }
  13250. }
  13251. }
  13252. return null;
  13253. }
  13254. get bundledVersion() {
  13255. try {
  13256. const file = requireFunc.resolve('typescript');
  13257. const bundledVersion = new TypeScriptVersion(path_1.default.dirname(file), '');
  13258. return bundledVersion;
  13259. }
  13260. catch (e) {
  13261. coc_nvim_1.workspace.showMessage('Bundled typescript module not found', 'error');
  13262. return null;
  13263. }
  13264. }
  13265. }
  13266. exports.TypeScriptVersionProvider = TypeScriptVersionProvider;
  13267. /***/ }),
  13268. /* 131 */
  13269. /***/ (function(module, exports, __webpack_require__) {
  13270. "use strict";
  13271. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  13272. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  13273. return new (P || (P = Promise))(function (resolve, reject) {
  13274. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  13275. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  13276. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  13277. step((generator = generator.apply(thisArg, _arguments || [])).next());
  13278. });
  13279. };
  13280. Object.defineProperty(exports, "__esModule", { value: true });
  13281. const coc_nvim_1 = __webpack_require__(1);
  13282. class VersionStatus {
  13283. constructor(_normalizePath, enableJavascript) {
  13284. this._normalizePath = _normalizePath;
  13285. this.enableJavascript = enableJavascript;
  13286. this._versionBarEntry = coc_nvim_1.workspace.createStatusBarItem(99);
  13287. this._onChangeEditorSub = coc_nvim_1.events.on('BufEnter', this.onBufEnter, this);
  13288. this._versionBarEntry.show();
  13289. }
  13290. dispose() {
  13291. this._versionBarEntry.dispose();
  13292. this._onChangeEditorSub.dispose();
  13293. }
  13294. onDidChangeTypeScriptVersion(_version) {
  13295. this._versionBarEntry.text = `TSC`;
  13296. }
  13297. set loading(isLoading) {
  13298. this._versionBarEntry.isProgress = isLoading;
  13299. }
  13300. checkFiletype(filetype) {
  13301. if (filetype.startsWith('javascript') && this.enableJavascript) {
  13302. return true;
  13303. }
  13304. return filetype.startsWith('typescript');
  13305. }
  13306. onBufEnter(bufnr) {
  13307. return __awaiter(this, void 0, void 0, function* () {
  13308. let filetype = yield coc_nvim_1.workspace.nvim.call('getbufvar', [bufnr, '&filetype', '']);
  13309. if (this.checkFiletype(filetype)) {
  13310. this._versionBarEntry.show();
  13311. }
  13312. else {
  13313. this._versionBarEntry.hide();
  13314. }
  13315. });
  13316. }
  13317. }
  13318. exports.default = VersionStatus;
  13319. /***/ }),
  13320. /* 132 */
  13321. /***/ (function(module, exports, __webpack_require__) {
  13322. "use strict";
  13323. Object.defineProperty(exports, "__esModule", { value: true });
  13324. exports.Reader = void 0;
  13325. const DefaultSize = 8192;
  13326. const ContentLength = 'Content-Length: ';
  13327. const ContentLengthSize = Buffer.byteLength(ContentLength, 'utf8');
  13328. const Blank = Buffer.from(' ', 'utf8')[0];
  13329. const BackslashR = Buffer.from('\r', 'utf8')[0];
  13330. const BackslashN = Buffer.from('\n', 'utf8')[0];
  13331. class ProtocolBuffer {
  13332. constructor() {
  13333. this.index = 0;
  13334. this.buffer = Buffer.allocUnsafe(DefaultSize);
  13335. }
  13336. append(data) {
  13337. let toAppend = null;
  13338. if (Buffer.isBuffer(data)) {
  13339. toAppend = data;
  13340. }
  13341. else {
  13342. toAppend = Buffer.from(data, 'utf8');
  13343. }
  13344. if (this.buffer.length - this.index >= toAppend.length) {
  13345. toAppend.copy(this.buffer, this.index, 0, toAppend.length);
  13346. }
  13347. else {
  13348. let newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) *
  13349. DefaultSize;
  13350. if (this.index === 0) {
  13351. this.buffer = Buffer.allocUnsafe(newSize);
  13352. toAppend.copy(this.buffer, 0, 0, toAppend.length);
  13353. }
  13354. else {
  13355. this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
  13356. }
  13357. }
  13358. this.index += toAppend.length;
  13359. }
  13360. tryReadContentLength() {
  13361. let result = -1;
  13362. let current = 0;
  13363. // we are utf8 encoding...
  13364. while (current < this.index &&
  13365. (this.buffer[current] === Blank ||
  13366. this.buffer[current] === BackslashR ||
  13367. this.buffer[current] === BackslashN)) {
  13368. current++;
  13369. }
  13370. if (this.index < current + ContentLengthSize) {
  13371. return result;
  13372. }
  13373. current += ContentLengthSize;
  13374. let start = current;
  13375. while (current < this.index && this.buffer[current] !== BackslashR) {
  13376. current++;
  13377. }
  13378. if (current + 3 >= this.index ||
  13379. this.buffer[current + 1] !== BackslashN ||
  13380. this.buffer[current + 2] !== BackslashR ||
  13381. this.buffer[current + 3] !== BackslashN) {
  13382. return result;
  13383. }
  13384. let data = this.buffer.toString('utf8', start, current);
  13385. result = parseInt(data, 10);
  13386. this.buffer = this.buffer.slice(current + 4);
  13387. this.index = this.index - (current + 4);
  13388. return result;
  13389. }
  13390. tryReadContent(length) {
  13391. if (this.index < length) {
  13392. return null;
  13393. }
  13394. let result = this.buffer.toString('utf8', 0, length);
  13395. let sourceStart = length;
  13396. while (sourceStart < this.index &&
  13397. (this.buffer[sourceStart] === BackslashR ||
  13398. this.buffer[sourceStart] === BackslashN)) {
  13399. sourceStart++;
  13400. }
  13401. this.buffer.copy(this.buffer, 0, sourceStart);
  13402. this.index = this.index - sourceStart;
  13403. return result;
  13404. }
  13405. }
  13406. class Reader {
  13407. constructor(readable, callback, onError) {
  13408. this.readable = readable;
  13409. this.callback = callback;
  13410. this.onError = onError;
  13411. this.buffer = new ProtocolBuffer();
  13412. this.nextMessageLength = -1;
  13413. this.readable.on('data', (data) => {
  13414. this.onLengthData(data);
  13415. });
  13416. }
  13417. onLengthData(data) {
  13418. try {
  13419. this.buffer.append(data);
  13420. while (true) {
  13421. if (this.nextMessageLength === -1) {
  13422. this.nextMessageLength = this.buffer.tryReadContentLength();
  13423. if (this.nextMessageLength === -1) {
  13424. return;
  13425. }
  13426. }
  13427. const msg = this.buffer.tryReadContent(this.nextMessageLength);
  13428. if (msg === null) {
  13429. return;
  13430. }
  13431. this.nextMessageLength = -1;
  13432. const json = JSON.parse(msg);
  13433. this.callback(json);
  13434. }
  13435. }
  13436. catch (e) {
  13437. this.onError(e);
  13438. }
  13439. }
  13440. }
  13441. exports.Reader = Reader;
  13442. /***/ }),
  13443. /* 133 */
  13444. /***/ (function(module, exports, __webpack_require__) {
  13445. "use strict";
  13446. /*---------------------------------------------------------------------------------------------
  13447. * Copyright (c) Microsoft Corporation. All rights reserved.
  13448. * Licensed under the MIT License. See License.txt in the project root for license information.
  13449. *--------------------------------------------------------------------------------------------*/
  13450. Object.defineProperty(exports, "__esModule", { value: true });
  13451. exports.CallbackMap = void 0;
  13452. const typescriptService_1 = __webpack_require__(123);
  13453. class CallbackMap {
  13454. constructor() {
  13455. this._callbacks = new Map();
  13456. this._asyncCallbacks = new Map();
  13457. }
  13458. destroy(cause) {
  13459. const cancellation = new typescriptService_1.ServerResponse.Cancelled(cause);
  13460. for (const callback of this._callbacks.values()) {
  13461. callback.onSuccess(cancellation);
  13462. }
  13463. this._callbacks.clear();
  13464. for (const callback of this._asyncCallbacks.values()) {
  13465. callback.onSuccess(cancellation);
  13466. }
  13467. this._asyncCallbacks.clear();
  13468. }
  13469. add(seq, callback, isAsync) {
  13470. if (isAsync) {
  13471. this._asyncCallbacks.set(seq, callback);
  13472. }
  13473. else {
  13474. this._callbacks.set(seq, callback);
  13475. }
  13476. }
  13477. fetch(seq) {
  13478. const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
  13479. this.delete(seq);
  13480. return callback;
  13481. }
  13482. delete(seq) {
  13483. if (!this._callbacks.delete(seq)) {
  13484. this._asyncCallbacks.delete(seq);
  13485. }
  13486. }
  13487. }
  13488. exports.CallbackMap = CallbackMap;
  13489. /***/ }),
  13490. /* 134 */
  13491. /***/ (function(module, exports, __webpack_require__) {
  13492. "use strict";
  13493. /*---------------------------------------------------------------------------------------------
  13494. * Copyright (c) Microsoft Corporation. All rights reserved.
  13495. * Licensed under the MIT License. See License.txt in the project root for license information.
  13496. *--------------------------------------------------------------------------------------------*/
  13497. Object.defineProperty(exports, "__esModule", { value: true });
  13498. exports.RequestQueue = exports.RequestQueueingType = void 0;
  13499. var RequestQueueingType;
  13500. (function (RequestQueueingType) {
  13501. /**
  13502. * Normal request that is executed in order.
  13503. */
  13504. RequestQueueingType[RequestQueueingType["Normal"] = 1] = "Normal";
  13505. /**
  13506. * Request that normal requests jump in front of in the queue.
  13507. */
  13508. RequestQueueingType[RequestQueueingType["LowPriority"] = 2] = "LowPriority";
  13509. /**
  13510. * A fence that blocks request reordering.
  13511. *
  13512. * Fences are not reordered. Unlike a normal request, a fence will never jump in front of a low priority request
  13513. * in the request queue.
  13514. */
  13515. RequestQueueingType[RequestQueueingType["Fence"] = 3] = "Fence";
  13516. })(RequestQueueingType = exports.RequestQueueingType || (exports.RequestQueueingType = {}));
  13517. class RequestQueue {
  13518. constructor() {
  13519. this.queue = [];
  13520. this.sequenceNumber = 0;
  13521. }
  13522. get length() {
  13523. return this.queue.length;
  13524. }
  13525. enqueue(item) {
  13526. if (item.queueingType === RequestQueueingType.Normal) {
  13527. let index = this.queue.length - 1;
  13528. while (index >= 0) {
  13529. if (this.queue[index].queueingType !== RequestQueueingType.LowPriority) {
  13530. break;
  13531. }
  13532. --index;
  13533. }
  13534. this.queue.splice(index + 1, 0, item);
  13535. }
  13536. else {
  13537. // Only normal priority requests can be reordered. All other requests just go to the end.
  13538. this.queue.push(item);
  13539. }
  13540. }
  13541. dequeue() {
  13542. return this.queue.shift();
  13543. }
  13544. tryDeletePendingRequest(seq) {
  13545. for (let i = 0; i < this.queue.length; i++) {
  13546. if (this.queue[i].request.seq === seq) {
  13547. this.queue.splice(i, 1);
  13548. return true;
  13549. }
  13550. }
  13551. return false;
  13552. }
  13553. createRequest(command, args) {
  13554. return {
  13555. seq: this.sequenceNumber++,
  13556. type: 'request',
  13557. command,
  13558. arguments: args
  13559. };
  13560. }
  13561. }
  13562. exports.RequestQueue = RequestQueue;
  13563. /***/ }),
  13564. /* 135 */
  13565. /***/ (function(module, exports, __webpack_require__) {
  13566. "use strict";
  13567. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  13568. if (k2 === undefined) k2 = k;
  13569. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  13570. }) : (function(o, m, k, k2) {
  13571. if (k2 === undefined) k2 = k;
  13572. o[k2] = m[k];
  13573. }));
  13574. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  13575. Object.defineProperty(o, "default", { enumerable: true, value: v });
  13576. }) : function(o, v) {
  13577. o["default"] = v;
  13578. });
  13579. var __importStar = (this && this.__importStar) || function (mod) {
  13580. if (mod && mod.__esModule) return mod;
  13581. var result = {};
  13582. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  13583. __setModuleDefault(result, mod);
  13584. return result;
  13585. };
  13586. var __importDefault = (this && this.__importDefault) || function (mod) {
  13587. return (mod && mod.__esModule) ? mod : { "default": mod };
  13588. };
  13589. Object.defineProperty(exports, "__esModule", { value: true });
  13590. /*---------------------------------------------------------------------------------------------
  13591. * Copyright (c) Microsoft Corporation. All rights reserved.
  13592. * Licensed under the MIT License. See License.txt in the project root for license information.
  13593. *--------------------------------------------------------------------------------------------*/
  13594. const coc_nvim_1 = __webpack_require__(1);
  13595. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  13596. const api_1 = __importDefault(__webpack_require__(40));
  13597. const async_1 = __webpack_require__(136);
  13598. const typeConverters = __importStar(__webpack_require__(37));
  13599. const languageModeIds = __importStar(__webpack_require__(116));
  13600. function mode2ScriptKind(mode) {
  13601. switch (mode) {
  13602. case languageModeIds.typescript:
  13603. return 'TS';
  13604. case languageModeIds.typescripttsx:
  13605. return 'TSX';
  13606. case languageModeIds.typescriptjsx:
  13607. return 'TSX';
  13608. case languageModeIds.typescriptreact:
  13609. return 'TSX';
  13610. case languageModeIds.javascript:
  13611. return 'JS';
  13612. case languageModeIds.javascriptreact:
  13613. return 'JSX';
  13614. }
  13615. return undefined;
  13616. }
  13617. /**
  13618. * Manages synchronization of buffers with the TS server.
  13619. *
  13620. * If supported, batches together file changes. This allows the TS server to more efficiently process changes.
  13621. */
  13622. class BufferSynchronizer {
  13623. constructor(client) {
  13624. this.client = client;
  13625. this._pending = {};
  13626. this._pendingFiles = new Set();
  13627. }
  13628. open(args) {
  13629. this.client.executeWithoutWaitingForResponse('open', args);
  13630. }
  13631. close(filepath) {
  13632. const args = { file: filepath };
  13633. this.client.executeWithoutWaitingForResponse('close', args);
  13634. }
  13635. change(filepath, events) {
  13636. if (!events.length) {
  13637. return;
  13638. }
  13639. if (this.supportsBatching) {
  13640. this.updatePending(filepath, pending => {
  13641. if (!pending.changedFiles) {
  13642. pending.changedFiles = [];
  13643. }
  13644. pending.changedFiles.push({
  13645. fileName: filepath,
  13646. textChanges: events.map((change) => ({
  13647. newText: change.text,
  13648. start: typeConverters.Position.toLocation(change.range.start),
  13649. end: typeConverters.Position.toLocation(change.range.end),
  13650. })).reverse(),
  13651. });
  13652. });
  13653. }
  13654. else {
  13655. for (const event of events) {
  13656. const args = Object.assign({ insertString: event.text }, typeConverters.Range.toFormattingRequestArgs(filepath, event.range));
  13657. this.client.executeWithoutWaitingForResponse('change', args);
  13658. }
  13659. }
  13660. }
  13661. beforeCommand(command) {
  13662. if (command === 'updateOpen') {
  13663. return;
  13664. }
  13665. this.flush();
  13666. }
  13667. flush() {
  13668. if (!this.supportsBatching) {
  13669. // We've already eagerly synchronized
  13670. return;
  13671. }
  13672. if (this._pending.changedFiles) {
  13673. this.client.executeWithoutWaitingForResponse('updateOpen', this._pending);
  13674. this._pending = {};
  13675. this._pendingFiles.clear();
  13676. }
  13677. }
  13678. get supportsBatching() {
  13679. return this.client.apiVersion.gte(api_1.default.v340) && coc_nvim_1.workspace.getConfiguration('tsserver').get('useBatchedBufferSync', true);
  13680. }
  13681. updatePending(filepath, f) {
  13682. if (this.supportsBatching && this._pendingFiles.has(filepath)) {
  13683. this.flush();
  13684. this._pendingFiles.clear();
  13685. f(this._pending);
  13686. this._pendingFiles.add(filepath);
  13687. }
  13688. else {
  13689. f(this._pending);
  13690. }
  13691. }
  13692. reset() {
  13693. this._pending = {};
  13694. this._pendingFiles.clear();
  13695. }
  13696. }
  13697. class BufferSyncSupport {
  13698. constructor(client) {
  13699. this.uris = new Set();
  13700. this.disposables = [];
  13701. this.pendingDiagnostics = new Map();
  13702. this._validateJavaScript = true;
  13703. this._validateTypeScript = true;
  13704. this.listening = false;
  13705. this._onDelete = new vscode_languageserver_protocol_1.Emitter();
  13706. this.onDelete = this._onDelete.event;
  13707. this.client = client;
  13708. this.synchronizer = new BufferSynchronizer(client);
  13709. this.modeIds = new Set(languageModeIds.languageIds);
  13710. this.diagnosticDelayer = new async_1.Delayer(300);
  13711. }
  13712. listen() {
  13713. if (this.listening) {
  13714. return;
  13715. }
  13716. this.listening = true;
  13717. coc_nvim_1.workspace.onDidOpenTextDocument(this.onDidOpenTextDocument, this, this.disposables);
  13718. coc_nvim_1.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, this.disposables);
  13719. coc_nvim_1.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, this.disposables);
  13720. coc_nvim_1.workspace.textDocuments.forEach(this.onDidOpenTextDocument, this);
  13721. this.updateConfiguration();
  13722. coc_nvim_1.workspace.onDidChangeConfiguration(this.updateConfiguration, this, this.disposables);
  13723. }
  13724. dispose() {
  13725. this.pendingDiagnostics.clear();
  13726. coc_nvim_1.disposeAll(this.disposables);
  13727. }
  13728. onDidOpenTextDocument(document) {
  13729. if (!this.modeIds.has(document.languageId))
  13730. return;
  13731. let { uri } = document;
  13732. let filepath = this.client.toPath(uri);
  13733. this.uris.add(uri);
  13734. const args = {
  13735. file: filepath,
  13736. fileContent: document.getText()
  13737. };
  13738. if (this.client.apiVersion.gte(api_1.default.v203)) {
  13739. const scriptKind = mode2ScriptKind(document.languageId);
  13740. if (scriptKind) {
  13741. args.scriptKindName = scriptKind;
  13742. }
  13743. }
  13744. if (this.client.apiVersion.gte(api_1.default.v230)) {
  13745. let root = this.client.getProjectRootPath(document.uri);
  13746. if (root)
  13747. args.projectRootPath = root;
  13748. }
  13749. this.synchronizer.open(args);
  13750. // this.client.executeWithoutWaitingForResponse('open', args)
  13751. this.requestDiagnostic(uri);
  13752. }
  13753. onDidCloseTextDocument(document) {
  13754. let { uri } = document;
  13755. if (!this.uris.has(uri))
  13756. return;
  13757. let filepath = this.client.toPath(uri);
  13758. this.uris.delete(uri);
  13759. this.pendingDiagnostics.delete(uri);
  13760. this.synchronizer.close(filepath);
  13761. this._onDelete.fire(uri);
  13762. this.requestAllDiagnostics();
  13763. // this.client.executeWithoutWaitingForResponse('close', args)
  13764. }
  13765. onDidChangeTextDocument(e) {
  13766. let { textDocument, contentChanges } = e;
  13767. let { uri } = textDocument;
  13768. if (!this.uris.has(uri))
  13769. return;
  13770. let filepath = this.client.toPath(uri);
  13771. this.synchronizer.change(filepath, contentChanges);
  13772. const didTrigger = this.requestDiagnostic(uri);
  13773. if (!didTrigger && this.pendingGetErr) {
  13774. // In this case we always want to re-trigger all diagnostics
  13775. this.pendingGetErr.cancel();
  13776. this.pendingGetErr = undefined;
  13777. this.triggerDiagnostics();
  13778. }
  13779. }
  13780. beforeCommand(command) {
  13781. this.synchronizer.beforeCommand(command);
  13782. }
  13783. interuptGetErr(f) {
  13784. if (!this.pendingGetErr) {
  13785. return f();
  13786. }
  13787. this.pendingGetErr.cancel();
  13788. this.pendingGetErr = undefined;
  13789. const result = f();
  13790. this.triggerDiagnostics();
  13791. return result;
  13792. }
  13793. getErr(resources) {
  13794. const handledResources = resources.filter(resource => this.uris.has(resource.toString()));
  13795. if (!handledResources.length) {
  13796. return;
  13797. }
  13798. for (const resource of handledResources) {
  13799. let uri = resource.toString();
  13800. if (this.shouldValidate(uri)) {
  13801. this.pendingDiagnostics.set(uri, Date.now());
  13802. }
  13803. }
  13804. this.triggerDiagnostics();
  13805. }
  13806. has(uri) {
  13807. return this.uris.has(uri);
  13808. }
  13809. triggerDiagnostics(delay = 200) {
  13810. this.diagnosticDelayer.trigger(() => {
  13811. this.sendPendingDiagnostics();
  13812. }, delay);
  13813. }
  13814. requestAllDiagnostics() {
  13815. for (const uri of this.uris) {
  13816. if (this.shouldValidate(uri)) {
  13817. this.pendingDiagnostics.set(uri, Date.now());
  13818. }
  13819. }
  13820. this.diagnosticDelayer.trigger(() => {
  13821. this.sendPendingDiagnostics();
  13822. }, 200);
  13823. }
  13824. requestDiagnostic(uri) {
  13825. let document = coc_nvim_1.workspace.getDocument(uri);
  13826. if (!document || !this.shouldValidate(uri))
  13827. return false;
  13828. this.pendingDiagnostics.set(uri, Date.now());
  13829. const lineCount = document.lineCount;
  13830. const delay = Math.min(Math.max(Math.ceil(lineCount / 20), 300), 800);
  13831. this.triggerDiagnostics(delay);
  13832. return true;
  13833. }
  13834. hasPendingDiagnostics(uri) {
  13835. return this.pendingDiagnostics.has(uri);
  13836. }
  13837. sendPendingDiagnostics() {
  13838. const uris = Array.from(this.pendingDiagnostics.entries())
  13839. .sort((a, b) => a[1] - b[1])
  13840. .map(entry => entry[0]);
  13841. // Add all open TS buffers to the geterr request. They might be visible
  13842. for (const uri of this.uris) {
  13843. if (uris.indexOf(uri) == -1) {
  13844. uris.push(uri);
  13845. }
  13846. }
  13847. let files = uris.map(uri => this.client.toPath(uri));
  13848. if (files.length) {
  13849. if (this.pendingGetErr)
  13850. this.pendingGetErr.cancel();
  13851. const getErr = this.pendingGetErr = GetErrRequest.executeGetErrRequest(this.client, files, () => {
  13852. if (this.pendingGetErr === getErr) {
  13853. this.pendingGetErr = undefined;
  13854. }
  13855. });
  13856. }
  13857. this.pendingDiagnostics.clear();
  13858. }
  13859. updateConfiguration() {
  13860. const jsConfig = coc_nvim_1.workspace.getConfiguration('javascript', null);
  13861. const tsConfig = coc_nvim_1.workspace.getConfiguration('typescript', null);
  13862. this._validateJavaScript = jsConfig.get('validate.enable', true);
  13863. this._validateTypeScript = tsConfig.get('validate.enable', true);
  13864. }
  13865. shouldValidate(uri) {
  13866. let doc = coc_nvim_1.workspace.getDocument(uri);
  13867. if (!doc)
  13868. return false;
  13869. if (languageModeIds.languageIds.indexOf(doc.filetype) == -1) {
  13870. return false;
  13871. }
  13872. if (doc.filetype.startsWith('javascript')) {
  13873. return this._validateJavaScript;
  13874. }
  13875. return this._validateTypeScript;
  13876. }
  13877. reinitialize() {
  13878. var _a;
  13879. this.pendingDiagnostics.clear();
  13880. (_a = this.pendingGetErr) === null || _a === void 0 ? void 0 : _a.cancel();
  13881. this.synchronizer.reset();
  13882. for (let doc of coc_nvim_1.workspace.documents) {
  13883. this.onDidOpenTextDocument(doc.textDocument);
  13884. }
  13885. }
  13886. }
  13887. exports.default = BufferSyncSupport;
  13888. class GetErrRequest {
  13889. constructor(client, files, _token, onDone) {
  13890. this.files = files;
  13891. this._token = _token;
  13892. this._done = false;
  13893. const args = {
  13894. delay: 0,
  13895. files: this.files
  13896. };
  13897. const done = () => {
  13898. if (this._done) {
  13899. return;
  13900. }
  13901. this._done = true;
  13902. onDone();
  13903. };
  13904. client.executeAsync('geterr', args, _token.token).then(done, done);
  13905. }
  13906. static executeGetErrRequest(client, files, onDone) {
  13907. const token = new vscode_languageserver_protocol_1.CancellationTokenSource();
  13908. return new GetErrRequest(client, files, token, onDone);
  13909. }
  13910. cancel() {
  13911. if (!this._done) {
  13912. this._token.cancel();
  13913. }
  13914. this._token.dispose();
  13915. }
  13916. }
  13917. /***/ }),
  13918. /* 136 */
  13919. /***/ (function(module, exports, __webpack_require__) {
  13920. "use strict";
  13921. Object.defineProperty(exports, "__esModule", { value: true });
  13922. exports.Delayer = void 0;
  13923. class Delayer {
  13924. constructor(defaultDelay) {
  13925. this.defaultDelay = defaultDelay;
  13926. this.timeout = null;
  13927. this.completionPromise = null;
  13928. this.onSuccess = null;
  13929. this.task = null;
  13930. }
  13931. trigger(task, delay = this.defaultDelay) {
  13932. this.task = task;
  13933. if (delay >= 0) {
  13934. this.cancelTimeout();
  13935. }
  13936. if (!this.completionPromise) {
  13937. this.completionPromise = new Promise(resolve => {
  13938. this.onSuccess = resolve;
  13939. }).then(() => {
  13940. this.completionPromise = null;
  13941. this.onSuccess = null;
  13942. let result = this.task && this.task();
  13943. this.task = null;
  13944. return result;
  13945. });
  13946. }
  13947. if (delay >= 0 || this.timeout === null) {
  13948. this.timeout = setTimeout(() => {
  13949. this.timeout = null;
  13950. if (this.onSuccess) {
  13951. this.onSuccess(undefined);
  13952. }
  13953. }, delay >= 0 ? delay : this.defaultDelay);
  13954. }
  13955. return this.completionPromise;
  13956. }
  13957. cancelTimeout() {
  13958. if (this.timeout !== null) {
  13959. clearTimeout(this.timeout);
  13960. this.timeout = null;
  13961. }
  13962. }
  13963. }
  13964. exports.Delayer = Delayer;
  13965. /***/ }),
  13966. /* 137 */
  13967. /***/ (function(module, exports, __webpack_require__) {
  13968. "use strict";
  13969. Object.defineProperty(exports, "__esModule", { value: true });
  13970. exports.DiagnosticsManager = exports.DiagnosticKind = exports.DiagnosticSet = void 0;
  13971. const coc_nvim_1 = __webpack_require__(1);
  13972. const resourceMap_1 = __webpack_require__(138);
  13973. class DiagnosticSet {
  13974. constructor() {
  13975. this._map = new resourceMap_1.ResourceMap();
  13976. }
  13977. set(uri, diagnostics) {
  13978. this._map.set(uri, diagnostics);
  13979. }
  13980. get(uri) {
  13981. return this._map.get(uri) || [];
  13982. }
  13983. clear() {
  13984. this._map = new resourceMap_1.ResourceMap();
  13985. }
  13986. }
  13987. exports.DiagnosticSet = DiagnosticSet;
  13988. var DiagnosticKind;
  13989. (function (DiagnosticKind) {
  13990. DiagnosticKind[DiagnosticKind["Syntax"] = 0] = "Syntax";
  13991. DiagnosticKind[DiagnosticKind["Semantic"] = 1] = "Semantic";
  13992. DiagnosticKind[DiagnosticKind["Suggestion"] = 2] = "Suggestion";
  13993. })(DiagnosticKind = exports.DiagnosticKind || (exports.DiagnosticKind = {}));
  13994. const allDiagnosticKinds = [
  13995. DiagnosticKind.Syntax,
  13996. DiagnosticKind.Semantic,
  13997. DiagnosticKind.Suggestion
  13998. ];
  13999. class DiagnosticsManager {
  14000. constructor() {
  14001. this._diagnostics = new Map();
  14002. this._pendingUpdates = new resourceMap_1.ResourceMap();
  14003. this._enableJavascriptSuggestions = true;
  14004. this._enableTypescriptSuggestions = true;
  14005. this.updateDelay = 200;
  14006. for (const kind of allDiagnosticKinds) {
  14007. this._diagnostics.set(kind, new DiagnosticSet());
  14008. }
  14009. this._currentDiagnostics = coc_nvim_1.languages.createDiagnosticCollection('tsserver');
  14010. }
  14011. dispose() {
  14012. this._currentDiagnostics.dispose();
  14013. for (const value of this._pendingUpdates.values) {
  14014. clearTimeout(value);
  14015. }
  14016. this._pendingUpdates = new resourceMap_1.ResourceMap();
  14017. }
  14018. reInitialize() {
  14019. this._currentDiagnostics.clear();
  14020. for (const diagnosticSet of this._diagnostics.values()) {
  14021. diagnosticSet.clear();
  14022. }
  14023. }
  14024. setEnableSuggestions(languageId, value) {
  14025. let curr = languageId == 'javascript' ? this._enableJavascriptSuggestions : this._enableTypescriptSuggestions;
  14026. if (curr == value) {
  14027. return;
  14028. }
  14029. if (languageId == 'javascript') {
  14030. this._enableJavascriptSuggestions = value;
  14031. }
  14032. else {
  14033. this._enableTypescriptSuggestions = value;
  14034. }
  14035. }
  14036. diagnosticsReceived(kind, uri, diagnostics) {
  14037. const collection = this._diagnostics.get(kind);
  14038. if (!collection)
  14039. return;
  14040. if (diagnostics.length === 0) {
  14041. const existing = collection.get(uri);
  14042. if (existing.length === 0) {
  14043. // No need to update
  14044. return;
  14045. }
  14046. }
  14047. collection.set(uri, diagnostics);
  14048. this.scheduleDiagnosticsUpdate(uri);
  14049. }
  14050. configFileDiagnosticsReceived(uri, diagnostics) {
  14051. this._currentDiagnostics.set(uri, diagnostics);
  14052. }
  14053. delete(uri) {
  14054. this._currentDiagnostics.delete(uri);
  14055. }
  14056. getDiagnostics(uri) {
  14057. return this._currentDiagnostics.get(uri) || [];
  14058. return [];
  14059. }
  14060. scheduleDiagnosticsUpdate(uri) {
  14061. if (!this._pendingUpdates.has(uri)) {
  14062. this._pendingUpdates.set(uri, setTimeout(() => this.updateCurrentDiagnostics(uri), this.updateDelay));
  14063. }
  14064. }
  14065. updateCurrentDiagnostics(uri) {
  14066. if (this._pendingUpdates.has(uri)) {
  14067. clearTimeout(this._pendingUpdates.get(uri));
  14068. this._pendingUpdates.delete(uri);
  14069. }
  14070. const allDiagnostics = [
  14071. ...this._diagnostics.get(DiagnosticKind.Syntax).get(uri),
  14072. ...this._diagnostics.get(DiagnosticKind.Semantic).get(uri),
  14073. ...this.getSuggestionDiagnostics(uri)
  14074. ];
  14075. this._currentDiagnostics.set(uri, allDiagnostics);
  14076. }
  14077. getSuggestionDiagnostics(uri) {
  14078. const enabled = this.suggestionsEnabled(uri);
  14079. return this._diagnostics
  14080. .get(DiagnosticKind.Suggestion)
  14081. .get(uri)
  14082. .filter(x => {
  14083. if (!enabled) {
  14084. // Still show unused
  14085. return x.code == 6133;
  14086. }
  14087. return enabled;
  14088. });
  14089. }
  14090. suggestionsEnabled(uri) {
  14091. let doc = coc_nvim_1.workspace.getDocument(uri);
  14092. if (!doc)
  14093. return false;
  14094. if (doc.filetype.startsWith('javascript')) {
  14095. return this._enableJavascriptSuggestions;
  14096. }
  14097. if (doc.filetype.startsWith('typescript')) {
  14098. return this._enableTypescriptSuggestions;
  14099. }
  14100. return true;
  14101. }
  14102. }
  14103. exports.DiagnosticsManager = DiagnosticsManager;
  14104. /***/ }),
  14105. /* 138 */
  14106. /***/ (function(module, exports, __webpack_require__) {
  14107. "use strict";
  14108. /*---------------------------------------------------------------------------------------------
  14109. * Copyright (c) Microsoft Corporation. All rights reserved.
  14110. * Licensed under the MIT License. See License.txt in the project root for license information.
  14111. *--------------------------------------------------------------------------------------------*/
  14112. Object.defineProperty(exports, "__esModule", { value: true });
  14113. exports.isWindowsPath = exports.ResourceMap = void 0;
  14114. /**
  14115. * Maps of file resources
  14116. *
  14117. * Attempts to handle correct mapping on both case sensitive and case in-sensitive
  14118. * file systems.
  14119. */
  14120. class ResourceMap {
  14121. constructor(_normalizePath) {
  14122. this._normalizePath = _normalizePath;
  14123. this._map = new Map();
  14124. }
  14125. has(resource) {
  14126. const file = this.toKey(resource);
  14127. return !!file && this._map.has(file);
  14128. }
  14129. get(resource) {
  14130. const file = this.toKey(resource);
  14131. return file ? this._map.get(file) : undefined;
  14132. }
  14133. set(resource, value) {
  14134. const file = this.toKey(resource);
  14135. if (file) {
  14136. this._map.set(file, value);
  14137. }
  14138. }
  14139. delete(resource) {
  14140. const file = this.toKey(resource);
  14141. if (file) {
  14142. this._map.delete(file);
  14143. }
  14144. }
  14145. get values() {
  14146. return this._map.values();
  14147. }
  14148. get keys() {
  14149. return this._map.keys();
  14150. }
  14151. toKey(resource) {
  14152. const key = this._normalizePath
  14153. ? this._normalizePath(resource)
  14154. : resource;
  14155. if (!key) {
  14156. return key;
  14157. }
  14158. return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
  14159. }
  14160. isCaseInsensitivePath(path) {
  14161. if (isWindowsPath(path)) {
  14162. return true;
  14163. }
  14164. return path[0] === '/' && this.onIsCaseInsenitiveFileSystem;
  14165. }
  14166. get onIsCaseInsenitiveFileSystem() {
  14167. if (process.platform === 'win32') {
  14168. return true;
  14169. }
  14170. if (process.platform === 'darwin') {
  14171. return true;
  14172. }
  14173. return false;
  14174. }
  14175. }
  14176. exports.ResourceMap = ResourceMap;
  14177. function isWindowsPath(path) {
  14178. return /^[a-zA-Z]:\\/.test(path);
  14179. }
  14180. exports.isWindowsPath = isWindowsPath;
  14181. /***/ }),
  14182. /* 139 */
  14183. /***/ (function(module, exports, __webpack_require__) {
  14184. "use strict";
  14185. Object.defineProperty(exports, "__esModule", { value: true });
  14186. exports.AtaProgressReporter = void 0;
  14187. /*---------------------------------------------------------------------------------------------
  14188. * Copyright (c) Microsoft Corporation. All rights reserved.
  14189. * Licensed under the MIT License. See License.txt in the project root for license information.
  14190. *--------------------------------------------------------------------------------------------*/
  14191. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  14192. const coc_nvim_1 = __webpack_require__(1);
  14193. const typingsInstallTimeout = 30 * 1000;
  14194. class TypingsStatus {
  14195. constructor(client) {
  14196. this._acquiringTypings = Object.create({});
  14197. this._subscriptions = [];
  14198. this._client = client;
  14199. this._subscriptions.push(this._client.onDidBeginInstallTypings(event => this.onBeginInstallTypings(event.eventId)));
  14200. this._subscriptions.push(this._client.onDidEndInstallTypings(event => this.onEndInstallTypings(event.eventId)));
  14201. }
  14202. dispose() {
  14203. this._subscriptions.forEach(x => x.dispose());
  14204. for (const eventId of Object.keys(this._acquiringTypings)) {
  14205. clearTimeout(this._acquiringTypings[eventId]);
  14206. }
  14207. }
  14208. get isAcquiringTypings() {
  14209. return Object.keys(this._acquiringTypings).length > 0;
  14210. }
  14211. onBeginInstallTypings(eventId) {
  14212. if (this._acquiringTypings[eventId]) {
  14213. return;
  14214. }
  14215. this._acquiringTypings[eventId] = setTimeout(() => {
  14216. this.onEndInstallTypings(eventId);
  14217. }, typingsInstallTimeout);
  14218. }
  14219. onEndInstallTypings(eventId) {
  14220. const timer = this._acquiringTypings[eventId];
  14221. if (timer) {
  14222. clearTimeout(timer);
  14223. }
  14224. delete this._acquiringTypings[eventId];
  14225. }
  14226. }
  14227. exports.default = TypingsStatus;
  14228. class AtaProgressReporter {
  14229. constructor(client) {
  14230. this._promises = new Map();
  14231. this._invalid = false;
  14232. this.statusItem = coc_nvim_1.workspace.createStatusBarItem(10, { progress: true });
  14233. const disposables = [];
  14234. disposables.push(client.onDidBeginInstallTypings(e => this._onBegin(e.eventId)));
  14235. disposables.push(client.onDidEndInstallTypings(e => this._onEndOrTimeout(e.eventId)));
  14236. disposables.push(client.onTypesInstallerInitializationFailed(_ => this.onTypesInstallerInitializationFailed()));
  14237. this._disposable = vscode_languageserver_protocol_1.Disposable.create(() => {
  14238. disposables.forEach(disposable => {
  14239. disposable.dispose();
  14240. });
  14241. });
  14242. }
  14243. dispose() {
  14244. this._disposable.dispose();
  14245. this._promises.forEach(value => value());
  14246. }
  14247. _onBegin(eventId) {
  14248. const handle = setTimeout(() => this._onEndOrTimeout(eventId), typingsInstallTimeout);
  14249. new Promise(resolve => {
  14250. this._promises.set(eventId, () => {
  14251. clearTimeout(handle);
  14252. resolve();
  14253. });
  14254. });
  14255. this.statusItem.text = 'Fetching data for better TypeScript IntelliSense';
  14256. this.statusItem.show();
  14257. }
  14258. _onEndOrTimeout(eventId) {
  14259. this.statusItem.hide();
  14260. const resolve = this._promises.get(eventId);
  14261. if (resolve) {
  14262. this._promises.delete(eventId);
  14263. resolve();
  14264. }
  14265. }
  14266. onTypesInstallerInitializationFailed() {
  14267. this.statusItem.hide();
  14268. if (!this._invalid) {
  14269. coc_nvim_1.workspace.showMessage('Could not install typings files for JavaScript language features. Please ensure that NPM is installed', 'error');
  14270. }
  14271. this._invalid = true;
  14272. }
  14273. }
  14274. exports.AtaProgressReporter = AtaProgressReporter;
  14275. /***/ }),
  14276. /* 140 */
  14277. /***/ (function(module, exports, __webpack_require__) {
  14278. "use strict";
  14279. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  14280. if (k2 === undefined) k2 = k;
  14281. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  14282. }) : (function(o, m, k, k2) {
  14283. if (k2 === undefined) k2 = k;
  14284. o[k2] = m[k];
  14285. }));
  14286. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  14287. Object.defineProperty(o, "default", { enumerable: true, value: v });
  14288. }) : function(o, v) {
  14289. o["default"] = v;
  14290. });
  14291. var __importStar = (this && this.__importStar) || function (mod) {
  14292. if (mod && mod.__esModule) return mod;
  14293. var result = {};
  14294. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  14295. __setModuleDefault(result, mod);
  14296. return result;
  14297. };
  14298. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  14299. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  14300. return new (P || (P = Promise))(function (resolve, reject) {
  14301. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  14302. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  14303. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  14304. step((generator = generator.apply(thisArg, _arguments || [])).next());
  14305. });
  14306. };
  14307. Object.defineProperty(exports, "__esModule", { value: true });
  14308. exports.ConfigurePluginCommand = exports.AutoFixCommand = exports.TypeScriptGoToProjectConfigCommand = exports.OpenTsServerLogCommand = exports.ReloadProjectsCommand = void 0;
  14309. const coc_nvim_1 = __webpack_require__(1);
  14310. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  14311. const typeConverters = __importStar(__webpack_require__(37));
  14312. const vscode_languageserver_types_1 = __webpack_require__(18);
  14313. const modules_1 = __webpack_require__(112);
  14314. const helper_1 = __webpack_require__(100);
  14315. const languageModeIds_1 = __webpack_require__(116);
  14316. class ReloadProjectsCommand {
  14317. constructor(client) {
  14318. this.client = client;
  14319. this.id = 'tsserver.reloadProjects';
  14320. }
  14321. execute() {
  14322. this.client.reloadProjects();
  14323. coc_nvim_1.workspace.showMessage('projects reloaded');
  14324. }
  14325. }
  14326. exports.ReloadProjectsCommand = ReloadProjectsCommand;
  14327. class OpenTsServerLogCommand {
  14328. constructor(client) {
  14329. this.client = client;
  14330. this.id = 'tsserver.openTsServerLog';
  14331. }
  14332. execute() {
  14333. this.client.serviceClient.openTsServerLogFile(); // tslint:disable-line
  14334. }
  14335. }
  14336. exports.OpenTsServerLogCommand = OpenTsServerLogCommand;
  14337. class TypeScriptGoToProjectConfigCommand {
  14338. constructor(client) {
  14339. this.client = client;
  14340. this.id = 'tsserver.goToProjectConfig';
  14341. }
  14342. execute() {
  14343. return __awaiter(this, void 0, void 0, function* () {
  14344. let doc = yield coc_nvim_1.workspace.document;
  14345. let { filetype } = doc;
  14346. if (languageModeIds_1.languageIds.indexOf(filetype) == -1) {
  14347. coc_nvim_1.workspace.showMessage(`Could not determine TypeScript or JavaScript project. Unsupported file type: ${filetype}`, 'warning');
  14348. return;
  14349. }
  14350. // doc.filetype
  14351. yield goToProjectConfig(this.client, doc.uri);
  14352. });
  14353. }
  14354. }
  14355. exports.TypeScriptGoToProjectConfigCommand = TypeScriptGoToProjectConfigCommand;
  14356. function goToProjectConfig(clientHost, uri) {
  14357. return __awaiter(this, void 0, void 0, function* () {
  14358. const client = clientHost.serviceClient;
  14359. const file = client.toPath(uri);
  14360. let res;
  14361. try {
  14362. res = yield client.execute('projectInfo', { file, needFileNameList: false }, vscode_languageserver_protocol_1.CancellationToken.None);
  14363. }
  14364. catch (_a) {
  14365. // noop
  14366. }
  14367. if (!res || !res.body) {
  14368. coc_nvim_1.workspace.showMessage('Could not determine TypeScript or JavaScript project.', 'warning');
  14369. return;
  14370. }
  14371. const { configFileName } = res.body;
  14372. if (configFileName && !isImplicitProjectConfigFile(configFileName)) {
  14373. yield coc_nvim_1.workspace.openResource(coc_nvim_1.Uri.file(configFileName).toString());
  14374. return;
  14375. }
  14376. coc_nvim_1.workspace.showMessage('Config file not found', 'warning');
  14377. });
  14378. }
  14379. function isImplicitProjectConfigFile(configFileName) {
  14380. return configFileName.indexOf('/dev/null/') === 0;
  14381. }
  14382. const autoFixableDiagnosticCodes = new Set([
  14383. 2420,
  14384. 2552,
  14385. 2304,
  14386. ]);
  14387. class AutoFixCommand {
  14388. constructor(client) {
  14389. this.client = client;
  14390. this.id = 'tsserver.executeAutofix';
  14391. }
  14392. execute() {
  14393. return __awaiter(this, void 0, void 0, function* () {
  14394. let document = yield coc_nvim_1.workspace.document;
  14395. let { uri } = document;
  14396. if (!this.client.handles(uri)) {
  14397. coc_nvim_1.workspace.showMessage(`Document ${uri} is not handled by tsserver.`, 'warning');
  14398. return;
  14399. }
  14400. let file = this.client.serviceClient.toPath(document.uri);
  14401. let diagnostics = coc_nvim_1.diagnosticManager.getDiagnostics(document.uri);
  14402. let missingDiagnostics = diagnostics.filter(o => o.code == 2307);
  14403. if (missingDiagnostics.length) {
  14404. let names = missingDiagnostics.map(o => {
  14405. let ms = o.message.match(/module\s'(.+)'\./);
  14406. return ms ? ms[1] : null;
  14407. });
  14408. names = names.filter(s => s != null);
  14409. if (names.length) {
  14410. modules_1.installModules(document.uri, names).catch(e => {
  14411. console.error(e.message); // tslint:disable-line
  14412. });
  14413. }
  14414. }
  14415. diagnostics = diagnostics.filter(x => autoFixableDiagnosticCodes.has(x.code));
  14416. if (diagnostics.length == 0)
  14417. return;
  14418. diagnostics = diagnostics.reduce((arr, curr) => {
  14419. if (curr.code == 2304 && arr.findIndex(o => o.message == curr.message) != -1)
  14420. return arr;
  14421. arr.push(curr);
  14422. return arr;
  14423. }, []);
  14424. let client = this.client.serviceClient;
  14425. let edits = [];
  14426. let command;
  14427. let names = [];
  14428. for (let diagnostic of diagnostics) {
  14429. const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+(diagnostic.code)] });
  14430. const response = yield client.execute('getCodeFixes', args, vscode_languageserver_protocol_1.CancellationToken.None);
  14431. if (response.type !== 'response' || !response.body || response.body.length < 1) {
  14432. if (diagnostic.code == 2304) {
  14433. let { range } = diagnostic;
  14434. let line = document.getline(range.start.line);
  14435. let name = line.slice(range.start.character, range.end.character);
  14436. if (helper_1.nodeModules.indexOf(name) !== -1 && names.indexOf(name) == -1) {
  14437. names.push(name);
  14438. edits.push({
  14439. range: vscode_languageserver_types_1.Range.create(0, 0, 0, 0),
  14440. newText: `import ${name} from '${name}'\n`
  14441. });
  14442. command = 'tsserver.organizeImports';
  14443. }
  14444. }
  14445. continue;
  14446. }
  14447. const fix = response.body[0];
  14448. for (let change of fix.changes) {
  14449. if (change.fileName != file)
  14450. continue;
  14451. // change.fileName
  14452. for (let ch of change.textChanges) {
  14453. edits.push({
  14454. range: typeConverters.Range.fromTextSpan(ch),
  14455. newText: ch.newText
  14456. });
  14457. }
  14458. }
  14459. }
  14460. if (edits.length)
  14461. yield document.applyEdits(coc_nvim_1.workspace.nvim, edits);
  14462. if (command)
  14463. coc_nvim_1.commands.executeCommand(command);
  14464. });
  14465. }
  14466. }
  14467. exports.AutoFixCommand = AutoFixCommand;
  14468. class ConfigurePluginCommand {
  14469. constructor(pluginManager) {
  14470. this.pluginManager = pluginManager;
  14471. this.id = '_typescript.configurePlugin';
  14472. }
  14473. execute(pluginId, configuration) {
  14474. this.pluginManager.setConfiguration(pluginId, configuration);
  14475. }
  14476. }
  14477. exports.ConfigurePluginCommand = ConfigurePluginCommand;
  14478. /***/ }),
  14479. /* 141 */
  14480. /***/ (function(module, exports, __webpack_require__) {
  14481. "use strict";
  14482. /*---------------------------------------------------------------------------------------------
  14483. * Copyright (c) Microsoft Corporation. All rights reserved.
  14484. * Licensed under the MIT License. See License.txt in the project root for license information.
  14485. *--------------------------------------------------------------------------------------------*/
  14486. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  14487. if (k2 === undefined) k2 = k;
  14488. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  14489. }) : (function(o, m, k, k2) {
  14490. if (k2 === undefined) k2 = k;
  14491. o[k2] = m[k];
  14492. }));
  14493. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  14494. Object.defineProperty(o, "default", { enumerable: true, value: v });
  14495. }) : function(o, v) {
  14496. o["default"] = v;
  14497. });
  14498. var __importStar = (this && this.__importStar) || function (mod) {
  14499. if (mod && mod.__esModule) return mod;
  14500. var result = {};
  14501. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  14502. __setModuleDefault(result, mod);
  14503. return result;
  14504. };
  14505. Object.defineProperty(exports, "__esModule", { value: true });
  14506. exports.PluginManager = void 0;
  14507. const coc_nvim_1 = __webpack_require__(1);
  14508. const arrays = __importStar(__webpack_require__(91));
  14509. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  14510. var TypeScriptServerPlugin;
  14511. (function (TypeScriptServerPlugin) {
  14512. function equals(a, b) {
  14513. return a.path === b.path
  14514. && a.name === b.name
  14515. && a.enableForWorkspaceTypeScriptVersions === b.enableForWorkspaceTypeScriptVersions
  14516. && arrays.equals(a.languages, b.languages);
  14517. }
  14518. TypeScriptServerPlugin.equals = equals;
  14519. })(TypeScriptServerPlugin || (TypeScriptServerPlugin = {}));
  14520. class PluginManager {
  14521. constructor() {
  14522. this._pluginConfigurations = new Map();
  14523. this._disposables = [];
  14524. this._onDidUpdatePlugins = this._register(new vscode_languageserver_protocol_1.Emitter());
  14525. this.onDidChangePlugins = this._onDidUpdatePlugins.event;
  14526. this._onDidUpdateConfig = this._register(new vscode_languageserver_protocol_1.Emitter());
  14527. this.onDidUpdateConfig = this._onDidUpdateConfig.event;
  14528. let loadPlugins = () => {
  14529. if (!this._plugins) {
  14530. return;
  14531. }
  14532. const newPlugins = this.readPlugins();
  14533. if (!arrays.equals(arrays.flatten(Array.from(this._plugins.values())), arrays.flatten(Array.from(newPlugins.values())), TypeScriptServerPlugin.equals)) {
  14534. this._plugins = newPlugins;
  14535. this._onDidUpdatePlugins.fire(this);
  14536. }
  14537. };
  14538. coc_nvim_1.extensions.onDidActiveExtension(loadPlugins, undefined, this._disposables);
  14539. coc_nvim_1.extensions.onDidUnloadExtension(loadPlugins, undefined, this._disposables);
  14540. }
  14541. dispose() {
  14542. coc_nvim_1.disposeAll(this._disposables);
  14543. }
  14544. get plugins() {
  14545. if (!this._plugins) {
  14546. this._plugins = this.readPlugins();
  14547. }
  14548. return arrays.flatten(Array.from(this._plugins.values()));
  14549. }
  14550. _register(value) {
  14551. this._disposables.push(value);
  14552. return value;
  14553. }
  14554. setConfiguration(pluginId, config) {
  14555. this._pluginConfigurations.set(pluginId, config);
  14556. this._onDidUpdateConfig.fire({ pluginId, config });
  14557. }
  14558. configurations() {
  14559. return this._pluginConfigurations.entries();
  14560. }
  14561. readPlugins() {
  14562. const pluginMap = new Map();
  14563. for (const extension of coc_nvim_1.extensions.all) {
  14564. const pack = extension.packageJSON;
  14565. if (pack.contributes && Array.isArray(pack.contributes.typescriptServerPlugins)) {
  14566. const plugins = [];
  14567. for (const plugin of pack.contributes.typescriptServerPlugins) {
  14568. plugins.push({
  14569. name: plugin.name,
  14570. enableForWorkspaceTypeScriptVersions: !!plugin.enableForWorkspaceTypeScriptVersions,
  14571. path: extension.extensionPath,
  14572. languages: Array.isArray(plugin.languages) ? plugin.languages : [],
  14573. });
  14574. }
  14575. if (plugins.length) {
  14576. pluginMap.set(extension.id, plugins);
  14577. }
  14578. }
  14579. }
  14580. return pluginMap;
  14581. }
  14582. }
  14583. exports.PluginManager = PluginManager;
  14584. /***/ })
  14585. /******/ ])));