My dotfiles
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 

8626 linhas
294 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. Object.defineProperty(exports, "__esModule", { value: true });
  92. const coc_nvim_1 = __webpack_require__(1);
  93. const defaultCompletionProvider_1 = __webpack_require__(2);
  94. const util_1 = __webpack_require__(32);
  95. function activate(context) {
  96. registerCompletionProviders(context);
  97. context.subscriptions.push(coc_nvim_1.workspace.onDidChangeConfiguration(e => {
  98. if (e.affectsConfiguration('emmet.includeLanguages')) {
  99. registerCompletionProviders(context);
  100. }
  101. }));
  102. coc_nvim_1.workspace.onDidOpenTextDocument(() => {
  103. registerCompletionProviders(context);
  104. }, null, context.subscriptions);
  105. }
  106. exports.activate = activate;
  107. /**
  108. * Holds any registered completion providers by their language strings
  109. */
  110. const registeredModes = new Set();
  111. function registerCompletionProviders(context) {
  112. let includedLanguages = util_1.getMappingForIncludedLanguages();
  113. let current_languages = coc_nvim_1.workspace.filetypes;
  114. const emmetConfig = coc_nvim_1.workspace.getConfiguration('emmet');
  115. for (let language of current_languages) {
  116. let emmetMode = Object.keys(util_1.LANGUAGE_MODES).find(s => s == language) || includedLanguages[language];
  117. if (!emmetMode || registeredModes.has(emmetMode))
  118. continue;
  119. registeredModes.add(emmetMode);
  120. let filetypes = [emmetMode];
  121. if (emmetMode != language) {
  122. filetypes.push(language);
  123. }
  124. for (let key of Object.keys(includedLanguages)) {
  125. let val = includedLanguages[key];
  126. if (val == emmetMode && filetypes.indexOf(val) == -1) {
  127. filetypes.push(val);
  128. }
  129. }
  130. let completionProvider = new defaultCompletionProvider_1.DefaultCompletionItemProvider();
  131. const provider = coc_nvim_1.languages.registerCompletionItemProvider(`emmet-${emmetMode}`, 'EM', filetypes, completionProvider, util_1.LANGUAGE_MODES[emmetMode], emmetConfig.get('priority', 3));
  132. context.subscriptions.push(provider);
  133. }
  134. }
  135. /***/ }),
  136. /* 1 */
  137. /***/ (function(module, exports) {
  138. module.exports = require("coc.nvim");
  139. /***/ }),
  140. /* 2 */
  141. /***/ (function(module, exports, __webpack_require__) {
  142. "use strict";
  143. Object.defineProperty(exports, "__esModule", { value: true });
  144. /*---------------------------------------------------------------------------------------------
  145. * Copyright (c) Microsoft Corporation. All rights reserved.
  146. * Licensed under the MIT License. See License.txt in the project root for license information.
  147. *--------------------------------------------------------------------------------------------*/
  148. const coc_nvim_1 = __webpack_require__(1);
  149. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  150. const abbreviationActions_1 = __webpack_require__(31);
  151. const util_1 = __webpack_require__(32);
  152. class DefaultCompletionItemProvider {
  153. provideCompletionItems(document, position, _, context) {
  154. const completionResult = this.provideCompletionItemsInternal(document, position, context);
  155. if (!completionResult) {
  156. this.lastCompletionType = undefined;
  157. return;
  158. }
  159. return completionResult.then(completionList => {
  160. if (!completionList || !completionList.items.length) {
  161. this.lastCompletionType = undefined;
  162. return null;
  163. }
  164. const item = completionList.items[0];
  165. const expandedText = item.documentation ? item.documentation.toString() : '';
  166. if (expandedText.startsWith('<')) {
  167. this.lastCompletionType = 'html';
  168. }
  169. else if (expandedText.indexOf(':') > 0 && expandedText.endsWith(';')) {
  170. this.lastCompletionType = 'css';
  171. }
  172. else {
  173. this.lastCompletionType = undefined;
  174. }
  175. return completionList;
  176. });
  177. }
  178. provideCompletionItemsInternal(document, position, context) {
  179. const emmetConfig = coc_nvim_1.workspace.getConfiguration('emmet');
  180. const excludedLanguages = emmetConfig['excludeLanguages'] ? emmetConfig['excludeLanguages'] : [];
  181. if (excludedLanguages.indexOf(document.languageId) > -1) {
  182. return;
  183. }
  184. const mappedLanguages = util_1.getMappingForIncludedLanguages();
  185. const isSyntaxMapped = mappedLanguages[document.languageId] ? true : false;
  186. let syntax = util_1.getEmmetMode((isSyntaxMapped ? mappedLanguages[document.languageId] : document.languageId), excludedLanguages);
  187. if (!syntax || emmetConfig['showExpandedAbbreviation'] === 'never') {
  188. return;
  189. }
  190. const helper = util_1.getEmmetHelper();
  191. let validateLocation = syntax === 'html' || syntax === 'jsx' || syntax === 'xml';
  192. let rootNode;
  193. let currentNode = null;
  194. if (document.languageId === 'html') {
  195. if (context.triggerKind === vscode_languageserver_protocol_1.CompletionTriggerKind.TriggerForIncompleteCompletions) {
  196. switch (this.lastCompletionType) {
  197. case 'html':
  198. validateLocation = false;
  199. break;
  200. case 'css':
  201. validateLocation = false;
  202. syntax = 'css';
  203. break;
  204. default:
  205. break;
  206. }
  207. }
  208. if (validateLocation) {
  209. rootNode = util_1.parseDocument(document, false);
  210. currentNode = util_1.getNode(rootNode, position, true);
  211. if (util_1.isStyleAttribute(currentNode, position)) {
  212. syntax = 'css';
  213. validateLocation = false;
  214. }
  215. else {
  216. const embeddedCssNode = util_1.getEmbeddedCssNodeIfAny(document, currentNode, position);
  217. if (embeddedCssNode) {
  218. currentNode = util_1.getNode(embeddedCssNode, position, true);
  219. syntax = 'css';
  220. }
  221. }
  222. }
  223. }
  224. const extractAbbreviationResults = helper.extractAbbreviation(document, position, !util_1.isStyleSheet(syntax));
  225. if (!extractAbbreviationResults || !helper.isAbbreviationValid(syntax, extractAbbreviationResults.abbreviation)) {
  226. return;
  227. }
  228. if (util_1.isStyleSheet(document.languageId) && context.triggerKind !== vscode_languageserver_protocol_1.CompletionTriggerKind.TriggerForIncompleteCompletions) {
  229. validateLocation = true;
  230. let usePartialParsing = coc_nvim_1.workspace.getConfiguration('emmet')['optimizeStylesheetParsing'] === true;
  231. rootNode = usePartialParsing && document.lineCount > 1000 ? util_1.parsePartialStylesheet(document, position) : util_1.parseDocument(document, false);
  232. if (!rootNode) {
  233. return;
  234. }
  235. currentNode = util_1.getNode(rootNode, position, true);
  236. }
  237. if (validateLocation && !abbreviationActions_1.isValidLocationForEmmetAbbreviation(document, rootNode, currentNode, syntax, position, extractAbbreviationResults.abbreviationRange)) {
  238. return;
  239. }
  240. let noiseCheckPromise = Promise.resolve();
  241. // Fix for https://github.com/Microsoft/issues/32647
  242. // Check for document symbols in js/ts/jsx/tsx and avoid triggering emmet for abbreviations of the form symbolName.sometext
  243. // Presence of > or * or + in the abbreviation denotes valid abbreviation that should trigger emmet
  244. if (!util_1.isStyleSheet(syntax) && (document.languageId === 'javascript' || document.languageId === 'javascriptreact' || document.languageId === 'typescript' || document.languageId === 'typescriptreact')) {
  245. let abbreviation = extractAbbreviationResults.abbreviation;
  246. if (abbreviation.startsWith('this.')) {
  247. noiseCheckPromise = Promise.resolve(true);
  248. }
  249. }
  250. return noiseCheckPromise.then((noise) => {
  251. if (noise) {
  252. return;
  253. }
  254. let result = helper.doComplete(document, position, syntax, util_1.getEmmetConfiguration(syntax));
  255. let newItems = [];
  256. let { option } = context;
  257. if (result && result.items) {
  258. result.items.forEach((item) => {
  259. let newItem = { label: item.label };
  260. newItem.documentation = item.documentation;
  261. newItem.detail = item.detail;
  262. newItem.insertTextFormat = vscode_languageserver_protocol_1.InsertTextFormat.Snippet;
  263. let oldrange = item.textEdit.range;
  264. newItem.textEdit = {
  265. range: vscode_languageserver_protocol_1.Range.create(oldrange.start.line, oldrange.start.character, oldrange.end.line, oldrange.end.character),
  266. newText: item.textEdit.newText
  267. };
  268. if (emmetConfig['showSuggestionsAsSnippets'] === true) {
  269. newItem.kind = vscode_languageserver_protocol_1.CompletionItemKind.Snippet;
  270. }
  271. newItem.filterText = option ? option.input : item.word;
  272. newItem.data = { word: newItem.filterText };
  273. newItem.sortText = item.sortText;
  274. newItems.push(newItem);
  275. });
  276. }
  277. return {
  278. items: newItems,
  279. isIncomplete: true
  280. };
  281. });
  282. }
  283. }
  284. exports.DefaultCompletionItemProvider = DefaultCompletionItemProvider;
  285. /***/ }),
  286. /* 3 */
  287. /***/ (function(module, exports, __webpack_require__) {
  288. "use strict";
  289. /* --------------------------------------------------------------------------------------------
  290. * Copyright (c) Microsoft Corporation. All rights reserved.
  291. * Licensed under the MIT License. See License.txt in the project root for license information.
  292. * ------------------------------------------------------------------------------------------ */
  293. function __export(m) {
  294. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  295. }
  296. Object.defineProperty(exports, "__esModule", { value: true });
  297. const vscode_jsonrpc_1 = __webpack_require__(4);
  298. exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
  299. exports.ResponseError = vscode_jsonrpc_1.ResponseError;
  300. exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;
  301. exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
  302. exports.Disposable = vscode_jsonrpc_1.Disposable;
  303. exports.Event = vscode_jsonrpc_1.Event;
  304. exports.Emitter = vscode_jsonrpc_1.Emitter;
  305. exports.Trace = vscode_jsonrpc_1.Trace;
  306. exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;
  307. exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
  308. exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
  309. exports.RequestType = vscode_jsonrpc_1.RequestType;
  310. exports.RequestType0 = vscode_jsonrpc_1.RequestType0;
  311. exports.NotificationType = vscode_jsonrpc_1.NotificationType;
  312. exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
  313. exports.MessageReader = vscode_jsonrpc_1.MessageReader;
  314. exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;
  315. exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
  316. exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
  317. exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
  318. exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
  319. exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
  320. exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
  321. exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
  322. exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
  323. exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
  324. exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
  325. __export(__webpack_require__(18));
  326. __export(__webpack_require__(19));
  327. const callHierarchy = __webpack_require__(28);
  328. const progress = __webpack_require__(29);
  329. const sr = __webpack_require__(30);
  330. var Proposed;
  331. (function (Proposed) {
  332. let SelectionRangeRequest;
  333. (function (SelectionRangeRequest) {
  334. SelectionRangeRequest.type = sr.SelectionRangeRequest.type;
  335. })(SelectionRangeRequest = Proposed.SelectionRangeRequest || (Proposed.SelectionRangeRequest = {}));
  336. let CallHierarchyRequest;
  337. (function (CallHierarchyRequest) {
  338. CallHierarchyRequest.type = callHierarchy.CallHierarchyRequest.type;
  339. })(CallHierarchyRequest = Proposed.CallHierarchyRequest || (Proposed.CallHierarchyRequest = {}));
  340. let CallHierarchyDirection;
  341. (function (CallHierarchyDirection) {
  342. CallHierarchyDirection.CallsFrom = callHierarchy.CallHierarchyDirection.CallsFrom;
  343. CallHierarchyDirection.CallsTo = callHierarchy.CallHierarchyDirection.CallsTo;
  344. })(CallHierarchyDirection = Proposed.CallHierarchyDirection || (Proposed.CallHierarchyDirection = {}));
  345. let ProgressStartNotification;
  346. (function (ProgressStartNotification) {
  347. ProgressStartNotification.type = progress.ProgressStartNotification.type;
  348. })(ProgressStartNotification = Proposed.ProgressStartNotification || (Proposed.ProgressStartNotification = {}));
  349. let ProgressReportNotification;
  350. (function (ProgressReportNotification) {
  351. ProgressReportNotification.type = progress.ProgressReportNotification.type;
  352. })(ProgressReportNotification = Proposed.ProgressReportNotification || (Proposed.ProgressReportNotification = {}));
  353. let ProgressDoneNotification;
  354. (function (ProgressDoneNotification) {
  355. ProgressDoneNotification.type = progress.ProgressDoneNotification.type;
  356. })(ProgressDoneNotification = Proposed.ProgressDoneNotification || (Proposed.ProgressDoneNotification = {}));
  357. let ProgressCancelNotification;
  358. (function (ProgressCancelNotification) {
  359. ProgressCancelNotification.type = progress.ProgressCancelNotification.type;
  360. })(ProgressCancelNotification = Proposed.ProgressCancelNotification || (Proposed.ProgressCancelNotification = {}));
  361. })(Proposed = exports.Proposed || (exports.Proposed = {}));
  362. function createProtocolConnection(reader, writer, logger, strategy) {
  363. return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
  364. }
  365. exports.createProtocolConnection = createProtocolConnection;
  366. /***/ }),
  367. /* 4 */
  368. /***/ (function(module, exports, __webpack_require__) {
  369. "use strict";
  370. /* --------------------------------------------------------------------------------------------
  371. * Copyright (c) Microsoft Corporation. All rights reserved.
  372. * Licensed under the MIT License. See License.txt in the project root for license information.
  373. * ------------------------------------------------------------------------------------------ */
  374. /// <reference path="./thenable.ts" />
  375. function __export(m) {
  376. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  377. }
  378. Object.defineProperty(exports, "__esModule", { value: true });
  379. const Is = __webpack_require__(5);
  380. const messages_1 = __webpack_require__(6);
  381. exports.RequestType = messages_1.RequestType;
  382. exports.RequestType0 = messages_1.RequestType0;
  383. exports.RequestType1 = messages_1.RequestType1;
  384. exports.RequestType2 = messages_1.RequestType2;
  385. exports.RequestType3 = messages_1.RequestType3;
  386. exports.RequestType4 = messages_1.RequestType4;
  387. exports.RequestType5 = messages_1.RequestType5;
  388. exports.RequestType6 = messages_1.RequestType6;
  389. exports.RequestType7 = messages_1.RequestType7;
  390. exports.RequestType8 = messages_1.RequestType8;
  391. exports.RequestType9 = messages_1.RequestType9;
  392. exports.ResponseError = messages_1.ResponseError;
  393. exports.ErrorCodes = messages_1.ErrorCodes;
  394. exports.NotificationType = messages_1.NotificationType;
  395. exports.NotificationType0 = messages_1.NotificationType0;
  396. exports.NotificationType1 = messages_1.NotificationType1;
  397. exports.NotificationType2 = messages_1.NotificationType2;
  398. exports.NotificationType3 = messages_1.NotificationType3;
  399. exports.NotificationType4 = messages_1.NotificationType4;
  400. exports.NotificationType5 = messages_1.NotificationType5;
  401. exports.NotificationType6 = messages_1.NotificationType6;
  402. exports.NotificationType7 = messages_1.NotificationType7;
  403. exports.NotificationType8 = messages_1.NotificationType8;
  404. exports.NotificationType9 = messages_1.NotificationType9;
  405. const messageReader_1 = __webpack_require__(7);
  406. exports.MessageReader = messageReader_1.MessageReader;
  407. exports.StreamMessageReader = messageReader_1.StreamMessageReader;
  408. exports.IPCMessageReader = messageReader_1.IPCMessageReader;
  409. exports.SocketMessageReader = messageReader_1.SocketMessageReader;
  410. const messageWriter_1 = __webpack_require__(9);
  411. exports.MessageWriter = messageWriter_1.MessageWriter;
  412. exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
  413. exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
  414. exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
  415. const events_1 = __webpack_require__(8);
  416. exports.Disposable = events_1.Disposable;
  417. exports.Event = events_1.Event;
  418. exports.Emitter = events_1.Emitter;
  419. const cancellation_1 = __webpack_require__(10);
  420. exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
  421. exports.CancellationToken = cancellation_1.CancellationToken;
  422. const linkedMap_1 = __webpack_require__(11);
  423. __export(__webpack_require__(12));
  424. __export(__webpack_require__(17));
  425. var CancelNotification;
  426. (function (CancelNotification) {
  427. CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
  428. })(CancelNotification || (CancelNotification = {}));
  429. exports.NullLogger = Object.freeze({
  430. error: () => { },
  431. warn: () => { },
  432. info: () => { },
  433. log: () => { }
  434. });
  435. var Trace;
  436. (function (Trace) {
  437. Trace[Trace["Off"] = 0] = "Off";
  438. Trace[Trace["Messages"] = 1] = "Messages";
  439. Trace[Trace["Verbose"] = 2] = "Verbose";
  440. })(Trace = exports.Trace || (exports.Trace = {}));
  441. (function (Trace) {
  442. function fromString(value) {
  443. value = value.toLowerCase();
  444. switch (value) {
  445. case 'off':
  446. return Trace.Off;
  447. case 'messages':
  448. return Trace.Messages;
  449. case 'verbose':
  450. return Trace.Verbose;
  451. default:
  452. return Trace.Off;
  453. }
  454. }
  455. Trace.fromString = fromString;
  456. function toString(value) {
  457. switch (value) {
  458. case Trace.Off:
  459. return 'off';
  460. case Trace.Messages:
  461. return 'messages';
  462. case Trace.Verbose:
  463. return 'verbose';
  464. default:
  465. return 'off';
  466. }
  467. }
  468. Trace.toString = toString;
  469. })(Trace = exports.Trace || (exports.Trace = {}));
  470. var TraceFormat;
  471. (function (TraceFormat) {
  472. TraceFormat["Text"] = "text";
  473. TraceFormat["JSON"] = "json";
  474. })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
  475. (function (TraceFormat) {
  476. function fromString(value) {
  477. value = value.toLowerCase();
  478. if (value === 'json') {
  479. return TraceFormat.JSON;
  480. }
  481. else {
  482. return TraceFormat.Text;
  483. }
  484. }
  485. TraceFormat.fromString = fromString;
  486. })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
  487. var SetTraceNotification;
  488. (function (SetTraceNotification) {
  489. SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');
  490. })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
  491. var LogTraceNotification;
  492. (function (LogTraceNotification) {
  493. LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');
  494. })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
  495. var ConnectionErrors;
  496. (function (ConnectionErrors) {
  497. /**
  498. * The connection is closed.
  499. */
  500. ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
  501. /**
  502. * The connection got disposed.
  503. */
  504. ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
  505. /**
  506. * The connection is already in listening mode.
  507. */
  508. ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
  509. })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
  510. class ConnectionError extends Error {
  511. constructor(code, message) {
  512. super(message);
  513. this.code = code;
  514. Object.setPrototypeOf(this, ConnectionError.prototype);
  515. }
  516. }
  517. exports.ConnectionError = ConnectionError;
  518. var ConnectionStrategy;
  519. (function (ConnectionStrategy) {
  520. function is(value) {
  521. let candidate = value;
  522. return candidate && Is.func(candidate.cancelUndispatched);
  523. }
  524. ConnectionStrategy.is = is;
  525. })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
  526. var ConnectionState;
  527. (function (ConnectionState) {
  528. ConnectionState[ConnectionState["New"] = 1] = "New";
  529. ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
  530. ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
  531. ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
  532. })(ConnectionState || (ConnectionState = {}));
  533. function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
  534. let sequenceNumber = 0;
  535. let notificationSquenceNumber = 0;
  536. let unknownResponseSquenceNumber = 0;
  537. const version = '2.0';
  538. let starRequestHandler = undefined;
  539. let requestHandlers = Object.create(null);
  540. let starNotificationHandler = undefined;
  541. let notificationHandlers = Object.create(null);
  542. let timer;
  543. let messageQueue = new linkedMap_1.LinkedMap();
  544. let responsePromises = Object.create(null);
  545. let requestTokens = Object.create(null);
  546. let trace = Trace.Off;
  547. let traceFormat = TraceFormat.Text;
  548. let tracer;
  549. let state = ConnectionState.New;
  550. let errorEmitter = new events_1.Emitter();
  551. let closeEmitter = new events_1.Emitter();
  552. let unhandledNotificationEmitter = new events_1.Emitter();
  553. let disposeEmitter = new events_1.Emitter();
  554. function createRequestQueueKey(id) {
  555. return 'req-' + id.toString();
  556. }
  557. function createResponseQueueKey(id) {
  558. if (id === null) {
  559. return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
  560. }
  561. else {
  562. return 'res-' + id.toString();
  563. }
  564. }
  565. function createNotificationQueueKey() {
  566. return 'not-' + (++notificationSquenceNumber).toString();
  567. }
  568. function addMessageToQueue(queue, message) {
  569. if (messages_1.isRequestMessage(message)) {
  570. queue.set(createRequestQueueKey(message.id), message);
  571. }
  572. else if (messages_1.isResponseMessage(message)) {
  573. queue.set(createResponseQueueKey(message.id), message);
  574. }
  575. else {
  576. queue.set(createNotificationQueueKey(), message);
  577. }
  578. }
  579. function cancelUndispatched(_message) {
  580. return undefined;
  581. }
  582. function isListening() {
  583. return state === ConnectionState.Listening;
  584. }
  585. function isClosed() {
  586. return state === ConnectionState.Closed;
  587. }
  588. function isDisposed() {
  589. return state === ConnectionState.Disposed;
  590. }
  591. function closeHandler() {
  592. if (state === ConnectionState.New || state === ConnectionState.Listening) {
  593. state = ConnectionState.Closed;
  594. closeEmitter.fire(undefined);
  595. }
  596. // If the connection is disposed don't sent close events.
  597. }
  598. ;
  599. function readErrorHandler(error) {
  600. errorEmitter.fire([error, undefined, undefined]);
  601. }
  602. function writeErrorHandler(data) {
  603. errorEmitter.fire(data);
  604. }
  605. messageReader.onClose(closeHandler);
  606. messageReader.onError(readErrorHandler);
  607. messageWriter.onClose(closeHandler);
  608. messageWriter.onError(writeErrorHandler);
  609. function triggerMessageQueue() {
  610. if (timer || messageQueue.size === 0) {
  611. return;
  612. }
  613. timer = setImmediate(() => {
  614. timer = undefined;
  615. processMessageQueue();
  616. });
  617. }
  618. function processMessageQueue() {
  619. if (messageQueue.size === 0) {
  620. return;
  621. }
  622. let message = messageQueue.shift();
  623. try {
  624. if (messages_1.isRequestMessage(message)) {
  625. handleRequest(message);
  626. }
  627. else if (messages_1.isNotificationMessage(message)) {
  628. handleNotification(message);
  629. }
  630. else if (messages_1.isResponseMessage(message)) {
  631. handleResponse(message);
  632. }
  633. else {
  634. handleInvalidMessage(message);
  635. }
  636. }
  637. finally {
  638. triggerMessageQueue();
  639. }
  640. }
  641. let callback = (message) => {
  642. try {
  643. // We have received a cancellation message. Check if the message is still in the queue
  644. // and cancel it if allowed to do so.
  645. if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
  646. let key = createRequestQueueKey(message.params.id);
  647. let toCancel = messageQueue.get(key);
  648. if (messages_1.isRequestMessage(toCancel)) {
  649. let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
  650. if (response && (response.error !== void 0 || response.result !== void 0)) {
  651. messageQueue.delete(key);
  652. response.id = toCancel.id;
  653. traceSendingResponse(response, message.method, Date.now());
  654. messageWriter.write(response);
  655. return;
  656. }
  657. }
  658. }
  659. addMessageToQueue(messageQueue, message);
  660. }
  661. finally {
  662. triggerMessageQueue();
  663. }
  664. };
  665. function handleRequest(requestMessage) {
  666. if (isDisposed()) {
  667. // we return here silently since we fired an event when the
  668. // connection got disposed.
  669. return;
  670. }
  671. function reply(resultOrError, method, startTime) {
  672. let message = {
  673. jsonrpc: version,
  674. id: requestMessage.id
  675. };
  676. if (resultOrError instanceof messages_1.ResponseError) {
  677. message.error = resultOrError.toJson();
  678. }
  679. else {
  680. message.result = resultOrError === void 0 ? null : resultOrError;
  681. }
  682. traceSendingResponse(message, method, startTime);
  683. messageWriter.write(message);
  684. }
  685. function replyError(error, method, startTime) {
  686. let message = {
  687. jsonrpc: version,
  688. id: requestMessage.id,
  689. error: error.toJson()
  690. };
  691. traceSendingResponse(message, method, startTime);
  692. messageWriter.write(message);
  693. }
  694. function replySuccess(result, method, startTime) {
  695. // The JSON RPC defines that a response must either have a result or an error
  696. // So we can't treat undefined as a valid response result.
  697. if (result === void 0) {
  698. result = null;
  699. }
  700. let message = {
  701. jsonrpc: version,
  702. id: requestMessage.id,
  703. result: result
  704. };
  705. traceSendingResponse(message, method, startTime);
  706. messageWriter.write(message);
  707. }
  708. traceReceivedRequest(requestMessage);
  709. let element = requestHandlers[requestMessage.method];
  710. let type;
  711. let requestHandler;
  712. if (element) {
  713. type = element.type;
  714. requestHandler = element.handler;
  715. }
  716. let startTime = Date.now();
  717. if (requestHandler || starRequestHandler) {
  718. let cancellationSource = new cancellation_1.CancellationTokenSource();
  719. let tokenKey = String(requestMessage.id);
  720. requestTokens[tokenKey] = cancellationSource;
  721. try {
  722. let handlerResult;
  723. if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
  724. handlerResult = requestHandler
  725. ? requestHandler(cancellationSource.token)
  726. : starRequestHandler(requestMessage.method, cancellationSource.token);
  727. }
  728. else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
  729. handlerResult = requestHandler
  730. ? requestHandler(...requestMessage.params, cancellationSource.token)
  731. : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
  732. }
  733. else {
  734. handlerResult = requestHandler
  735. ? requestHandler(requestMessage.params, cancellationSource.token)
  736. : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
  737. }
  738. let promise = handlerResult;
  739. if (!handlerResult) {
  740. delete requestTokens[tokenKey];
  741. replySuccess(handlerResult, requestMessage.method, startTime);
  742. }
  743. else if (promise.then) {
  744. promise.then((resultOrError) => {
  745. delete requestTokens[tokenKey];
  746. reply(resultOrError, requestMessage.method, startTime);
  747. }, error => {
  748. delete requestTokens[tokenKey];
  749. if (error instanceof messages_1.ResponseError) {
  750. replyError(error, requestMessage.method, startTime);
  751. }
  752. else if (error && Is.string(error.message)) {
  753. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
  754. }
  755. else {
  756. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
  757. }
  758. });
  759. }
  760. else {
  761. delete requestTokens[tokenKey];
  762. reply(handlerResult, requestMessage.method, startTime);
  763. }
  764. }
  765. catch (error) {
  766. delete requestTokens[tokenKey];
  767. if (error instanceof messages_1.ResponseError) {
  768. reply(error, requestMessage.method, startTime);
  769. }
  770. else if (error && Is.string(error.message)) {
  771. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
  772. }
  773. else {
  774. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
  775. }
  776. }
  777. }
  778. else {
  779. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
  780. }
  781. }
  782. function handleResponse(responseMessage) {
  783. if (isDisposed()) {
  784. // See handle request.
  785. return;
  786. }
  787. if (responseMessage.id === null) {
  788. if (responseMessage.error) {
  789. logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
  790. }
  791. else {
  792. logger.error(`Received response message without id. No further error information provided.`);
  793. }
  794. }
  795. else {
  796. let key = String(responseMessage.id);
  797. let responsePromise = responsePromises[key];
  798. traceReceivedResponse(responseMessage, responsePromise);
  799. if (responsePromise) {
  800. delete responsePromises[key];
  801. try {
  802. if (responseMessage.error) {
  803. let error = responseMessage.error;
  804. responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
  805. }
  806. else if (responseMessage.result !== void 0) {
  807. responsePromise.resolve(responseMessage.result);
  808. }
  809. else {
  810. throw new Error('Should never happen.');
  811. }
  812. }
  813. catch (error) {
  814. if (error.message) {
  815. logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
  816. }
  817. else {
  818. logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
  819. }
  820. }
  821. }
  822. }
  823. }
  824. function handleNotification(message) {
  825. if (isDisposed()) {
  826. // See handle request.
  827. return;
  828. }
  829. let type = undefined;
  830. let notificationHandler;
  831. if (message.method === CancelNotification.type.method) {
  832. notificationHandler = (params) => {
  833. let id = params.id;
  834. let source = requestTokens[String(id)];
  835. if (source) {
  836. source.cancel();
  837. }
  838. };
  839. }
  840. else {
  841. let element = notificationHandlers[message.method];
  842. if (element) {
  843. notificationHandler = element.handler;
  844. type = element.type;
  845. }
  846. }
  847. if (notificationHandler || starNotificationHandler) {
  848. try {
  849. traceReceivedNotification(message);
  850. if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
  851. notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
  852. }
  853. else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
  854. notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
  855. }
  856. else {
  857. notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
  858. }
  859. }
  860. catch (error) {
  861. if (error.message) {
  862. logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
  863. }
  864. else {
  865. logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
  866. }
  867. }
  868. }
  869. else {
  870. unhandledNotificationEmitter.fire(message);
  871. }
  872. }
  873. function handleInvalidMessage(message) {
  874. if (!message) {
  875. logger.error('Received empty message.');
  876. return;
  877. }
  878. logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
  879. // Test whether we find an id to reject the promise
  880. let responseMessage = message;
  881. if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
  882. let key = String(responseMessage.id);
  883. let responseHandler = responsePromises[key];
  884. if (responseHandler) {
  885. responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
  886. }
  887. }
  888. }
  889. function traceSendingRequest(message) {
  890. if (trace === Trace.Off || !tracer) {
  891. return;
  892. }
  893. if (traceFormat === TraceFormat.Text) {
  894. let data = undefined;
  895. if (trace === Trace.Verbose && message.params) {
  896. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  897. }
  898. tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
  899. }
  900. else {
  901. logLSPMessage('send-request', message);
  902. }
  903. }
  904. function traceSendingNotification(message) {
  905. if (trace === Trace.Off || !tracer) {
  906. return;
  907. }
  908. if (traceFormat === TraceFormat.Text) {
  909. let data = undefined;
  910. if (trace === Trace.Verbose) {
  911. if (message.params) {
  912. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  913. }
  914. else {
  915. data = 'No parameters provided.\n\n';
  916. }
  917. }
  918. tracer.log(`Sending notification '${message.method}'.`, data);
  919. }
  920. else {
  921. logLSPMessage('send-notification', message);
  922. }
  923. }
  924. function traceSendingResponse(message, method, startTime) {
  925. if (trace === Trace.Off || !tracer) {
  926. return;
  927. }
  928. if (traceFormat === TraceFormat.Text) {
  929. let data = undefined;
  930. if (trace === Trace.Verbose) {
  931. if (message.error && message.error.data) {
  932. data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
  933. }
  934. else {
  935. if (message.result) {
  936. data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
  937. }
  938. else if (message.error === void 0) {
  939. data = 'No result returned.\n\n';
  940. }
  941. }
  942. }
  943. tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
  944. }
  945. else {
  946. logLSPMessage('send-response', message);
  947. }
  948. }
  949. function traceReceivedRequest(message) {
  950. if (trace === Trace.Off || !tracer) {
  951. return;
  952. }
  953. if (traceFormat === TraceFormat.Text) {
  954. let data = undefined;
  955. if (trace === Trace.Verbose && message.params) {
  956. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  957. }
  958. tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
  959. }
  960. else {
  961. logLSPMessage('receive-request', message);
  962. }
  963. }
  964. function traceReceivedNotification(message) {
  965. if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
  966. return;
  967. }
  968. if (traceFormat === TraceFormat.Text) {
  969. let data = undefined;
  970. if (trace === Trace.Verbose) {
  971. if (message.params) {
  972. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  973. }
  974. else {
  975. data = 'No parameters provided.\n\n';
  976. }
  977. }
  978. tracer.log(`Received notification '${message.method}'.`, data);
  979. }
  980. else {
  981. logLSPMessage('receive-notification', message);
  982. }
  983. }
  984. function traceReceivedResponse(message, responsePromise) {
  985. if (trace === Trace.Off || !tracer) {
  986. return;
  987. }
  988. if (traceFormat === TraceFormat.Text) {
  989. let data = undefined;
  990. if (trace === Trace.Verbose) {
  991. if (message.error && message.error.data) {
  992. data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
  993. }
  994. else {
  995. if (message.result) {
  996. data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
  997. }
  998. else if (message.error === void 0) {
  999. data = 'No result returned.\n\n';
  1000. }
  1001. }
  1002. }
  1003. if (responsePromise) {
  1004. let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
  1005. tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
  1006. }
  1007. else {
  1008. tracer.log(`Received response ${message.id} without active response promise.`, data);
  1009. }
  1010. }
  1011. else {
  1012. logLSPMessage('receive-response', message);
  1013. }
  1014. }
  1015. function logLSPMessage(type, message) {
  1016. if (!tracer || trace === Trace.Off) {
  1017. return;
  1018. }
  1019. const lspMessage = {
  1020. isLSPMessage: true,
  1021. type,
  1022. message,
  1023. timestamp: Date.now()
  1024. };
  1025. tracer.log(lspMessage);
  1026. }
  1027. function throwIfClosedOrDisposed() {
  1028. if (isClosed()) {
  1029. throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
  1030. }
  1031. if (isDisposed()) {
  1032. throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
  1033. }
  1034. }
  1035. function throwIfListening() {
  1036. if (isListening()) {
  1037. throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
  1038. }
  1039. }
  1040. function throwIfNotListening() {
  1041. if (!isListening()) {
  1042. throw new Error('Call listen() first.');
  1043. }
  1044. }
  1045. function undefinedToNull(param) {
  1046. if (param === void 0) {
  1047. return null;
  1048. }
  1049. else {
  1050. return param;
  1051. }
  1052. }
  1053. function computeMessageParams(type, params) {
  1054. let result;
  1055. let numberOfParams = type.numberOfParams;
  1056. switch (numberOfParams) {
  1057. case 0:
  1058. result = null;
  1059. break;
  1060. case 1:
  1061. result = undefinedToNull(params[0]);
  1062. break;
  1063. default:
  1064. result = [];
  1065. for (let i = 0; i < params.length && i < numberOfParams; i++) {
  1066. result.push(undefinedToNull(params[i]));
  1067. }
  1068. if (params.length < numberOfParams) {
  1069. for (let i = params.length; i < numberOfParams; i++) {
  1070. result.push(null);
  1071. }
  1072. }
  1073. break;
  1074. }
  1075. return result;
  1076. }
  1077. let connection = {
  1078. sendNotification: (type, ...params) => {
  1079. throwIfClosedOrDisposed();
  1080. let method;
  1081. let messageParams;
  1082. if (Is.string(type)) {
  1083. method = type;
  1084. switch (params.length) {
  1085. case 0:
  1086. messageParams = null;
  1087. break;
  1088. case 1:
  1089. messageParams = params[0];
  1090. break;
  1091. default:
  1092. messageParams = params;
  1093. break;
  1094. }
  1095. }
  1096. else {
  1097. method = type.method;
  1098. messageParams = computeMessageParams(type, params);
  1099. }
  1100. let notificationMessage = {
  1101. jsonrpc: version,
  1102. method: method,
  1103. params: messageParams
  1104. };
  1105. traceSendingNotification(notificationMessage);
  1106. messageWriter.write(notificationMessage);
  1107. },
  1108. onNotification: (type, handler) => {
  1109. throwIfClosedOrDisposed();
  1110. if (Is.func(type)) {
  1111. starNotificationHandler = type;
  1112. }
  1113. else if (handler) {
  1114. if (Is.string(type)) {
  1115. notificationHandlers[type] = { type: undefined, handler };
  1116. }
  1117. else {
  1118. notificationHandlers[type.method] = { type, handler };
  1119. }
  1120. }
  1121. },
  1122. sendRequest: (type, ...params) => {
  1123. throwIfClosedOrDisposed();
  1124. throwIfNotListening();
  1125. let method;
  1126. let messageParams;
  1127. let token = undefined;
  1128. if (Is.string(type)) {
  1129. method = type;
  1130. switch (params.length) {
  1131. case 0:
  1132. messageParams = null;
  1133. break;
  1134. case 1:
  1135. // The cancellation token is optional so it can also be undefined.
  1136. if (cancellation_1.CancellationToken.is(params[0])) {
  1137. messageParams = null;
  1138. token = params[0];
  1139. }
  1140. else {
  1141. messageParams = undefinedToNull(params[0]);
  1142. }
  1143. break;
  1144. default:
  1145. const last = params.length - 1;
  1146. if (cancellation_1.CancellationToken.is(params[last])) {
  1147. token = params[last];
  1148. if (params.length === 2) {
  1149. messageParams = undefinedToNull(params[0]);
  1150. }
  1151. else {
  1152. messageParams = params.slice(0, last).map(value => undefinedToNull(value));
  1153. }
  1154. }
  1155. else {
  1156. messageParams = params.map(value => undefinedToNull(value));
  1157. }
  1158. break;
  1159. }
  1160. }
  1161. else {
  1162. method = type.method;
  1163. messageParams = computeMessageParams(type, params);
  1164. let numberOfParams = type.numberOfParams;
  1165. token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
  1166. }
  1167. let id = sequenceNumber++;
  1168. let result = new Promise((resolve, reject) => {
  1169. let requestMessage = {
  1170. jsonrpc: version,
  1171. id: id,
  1172. method: method,
  1173. params: messageParams
  1174. };
  1175. let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };
  1176. traceSendingRequest(requestMessage);
  1177. try {
  1178. messageWriter.write(requestMessage);
  1179. }
  1180. catch (e) {
  1181. // Writing the message failed. So we need to reject the promise.
  1182. responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
  1183. responsePromise = null;
  1184. }
  1185. if (responsePromise) {
  1186. responsePromises[String(id)] = responsePromise;
  1187. }
  1188. });
  1189. if (token) {
  1190. token.onCancellationRequested(() => {
  1191. connection.sendNotification(CancelNotification.type, { id });
  1192. });
  1193. }
  1194. return result;
  1195. },
  1196. onRequest: (type, handler) => {
  1197. throwIfClosedOrDisposed();
  1198. if (Is.func(type)) {
  1199. starRequestHandler = type;
  1200. }
  1201. else if (handler) {
  1202. if (Is.string(type)) {
  1203. requestHandlers[type] = { type: undefined, handler };
  1204. }
  1205. else {
  1206. requestHandlers[type.method] = { type, handler };
  1207. }
  1208. }
  1209. },
  1210. trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
  1211. let _sendNotification = false;
  1212. let _traceFormat = TraceFormat.Text;
  1213. if (sendNotificationOrTraceOptions !== void 0) {
  1214. if (Is.boolean(sendNotificationOrTraceOptions)) {
  1215. _sendNotification = sendNotificationOrTraceOptions;
  1216. }
  1217. else {
  1218. _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
  1219. _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
  1220. }
  1221. }
  1222. trace = _value;
  1223. traceFormat = _traceFormat;
  1224. if (trace === Trace.Off) {
  1225. tracer = undefined;
  1226. }
  1227. else {
  1228. tracer = _tracer;
  1229. }
  1230. if (_sendNotification && !isClosed() && !isDisposed()) {
  1231. connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
  1232. }
  1233. },
  1234. onError: errorEmitter.event,
  1235. onClose: closeEmitter.event,
  1236. onUnhandledNotification: unhandledNotificationEmitter.event,
  1237. onDispose: disposeEmitter.event,
  1238. dispose: () => {
  1239. if (isDisposed()) {
  1240. return;
  1241. }
  1242. state = ConnectionState.Disposed;
  1243. disposeEmitter.fire(undefined);
  1244. let error = new Error('Connection got disposed.');
  1245. Object.keys(responsePromises).forEach((key) => {
  1246. responsePromises[key].reject(error);
  1247. });
  1248. responsePromises = Object.create(null);
  1249. requestTokens = Object.create(null);
  1250. messageQueue = new linkedMap_1.LinkedMap();
  1251. // Test for backwards compatibility
  1252. if (Is.func(messageWriter.dispose)) {
  1253. messageWriter.dispose();
  1254. }
  1255. if (Is.func(messageReader.dispose)) {
  1256. messageReader.dispose();
  1257. }
  1258. },
  1259. listen: () => {
  1260. throwIfClosedOrDisposed();
  1261. throwIfListening();
  1262. state = ConnectionState.Listening;
  1263. messageReader.listen(callback);
  1264. },
  1265. inspect: () => {
  1266. console.log("inspect");
  1267. }
  1268. };
  1269. connection.onNotification(LogTraceNotification.type, (params) => {
  1270. if (trace === Trace.Off || !tracer) {
  1271. return;
  1272. }
  1273. tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
  1274. });
  1275. return connection;
  1276. }
  1277. function isMessageReader(value) {
  1278. return value.listen !== void 0 && value.read === void 0;
  1279. }
  1280. function isMessageWriter(value) {
  1281. return value.write !== void 0 && value.end === void 0;
  1282. }
  1283. function createMessageConnection(input, output, logger, strategy) {
  1284. if (!logger) {
  1285. logger = exports.NullLogger;
  1286. }
  1287. let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
  1288. let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
  1289. return _createMessageConnection(reader, writer, logger, strategy);
  1290. }
  1291. exports.createMessageConnection = createMessageConnection;
  1292. /***/ }),
  1293. /* 5 */
  1294. /***/ (function(module, exports, __webpack_require__) {
  1295. "use strict";
  1296. /* --------------------------------------------------------------------------------------------
  1297. * Copyright (c) Microsoft Corporation. All rights reserved.
  1298. * Licensed under the MIT License. See License.txt in the project root for license information.
  1299. * ------------------------------------------------------------------------------------------ */
  1300. Object.defineProperty(exports, "__esModule", { value: true });
  1301. function boolean(value) {
  1302. return value === true || value === false;
  1303. }
  1304. exports.boolean = boolean;
  1305. function string(value) {
  1306. return typeof value === 'string' || value instanceof String;
  1307. }
  1308. exports.string = string;
  1309. function number(value) {
  1310. return typeof value === 'number' || value instanceof Number;
  1311. }
  1312. exports.number = number;
  1313. function error(value) {
  1314. return value instanceof Error;
  1315. }
  1316. exports.error = error;
  1317. function func(value) {
  1318. return typeof value === 'function';
  1319. }
  1320. exports.func = func;
  1321. function array(value) {
  1322. return Array.isArray(value);
  1323. }
  1324. exports.array = array;
  1325. function stringArray(value) {
  1326. return array(value) && value.every(elem => string(elem));
  1327. }
  1328. exports.stringArray = stringArray;
  1329. /***/ }),
  1330. /* 6 */
  1331. /***/ (function(module, exports, __webpack_require__) {
  1332. "use strict";
  1333. /* --------------------------------------------------------------------------------------------
  1334. * Copyright (c) Microsoft Corporation. All rights reserved.
  1335. * Licensed under the MIT License. See License.txt in the project root for license information.
  1336. * ------------------------------------------------------------------------------------------ */
  1337. Object.defineProperty(exports, "__esModule", { value: true });
  1338. const is = __webpack_require__(5);
  1339. /**
  1340. * Predefined error codes.
  1341. */
  1342. var ErrorCodes;
  1343. (function (ErrorCodes) {
  1344. // Defined by JSON RPC
  1345. ErrorCodes.ParseError = -32700;
  1346. ErrorCodes.InvalidRequest = -32600;
  1347. ErrorCodes.MethodNotFound = -32601;
  1348. ErrorCodes.InvalidParams = -32602;
  1349. ErrorCodes.InternalError = -32603;
  1350. ErrorCodes.serverErrorStart = -32099;
  1351. ErrorCodes.serverErrorEnd = -32000;
  1352. ErrorCodes.ServerNotInitialized = -32002;
  1353. ErrorCodes.UnknownErrorCode = -32001;
  1354. // Defined by the protocol.
  1355. ErrorCodes.RequestCancelled = -32800;
  1356. ErrorCodes.ContentModified = -32801;
  1357. // Defined by VSCode library.
  1358. ErrorCodes.MessageWriteError = 1;
  1359. ErrorCodes.MessageReadError = 2;
  1360. })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
  1361. /**
  1362. * An error object return in a response in case a request
  1363. * has failed.
  1364. */
  1365. class ResponseError extends Error {
  1366. constructor(code, message, data) {
  1367. super(message);
  1368. this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
  1369. this.data = data;
  1370. Object.setPrototypeOf(this, ResponseError.prototype);
  1371. }
  1372. toJson() {
  1373. return {
  1374. code: this.code,
  1375. message: this.message,
  1376. data: this.data,
  1377. };
  1378. }
  1379. }
  1380. exports.ResponseError = ResponseError;
  1381. /**
  1382. * An abstract implementation of a MessageType.
  1383. */
  1384. class AbstractMessageType {
  1385. constructor(_method, _numberOfParams) {
  1386. this._method = _method;
  1387. this._numberOfParams = _numberOfParams;
  1388. }
  1389. get method() {
  1390. return this._method;
  1391. }
  1392. get numberOfParams() {
  1393. return this._numberOfParams;
  1394. }
  1395. }
  1396. exports.AbstractMessageType = AbstractMessageType;
  1397. /**
  1398. * Classes to type request response pairs
  1399. */
  1400. class RequestType0 extends AbstractMessageType {
  1401. constructor(method) {
  1402. super(method, 0);
  1403. this._ = undefined;
  1404. }
  1405. }
  1406. exports.RequestType0 = RequestType0;
  1407. class RequestType extends AbstractMessageType {
  1408. constructor(method) {
  1409. super(method, 1);
  1410. this._ = undefined;
  1411. }
  1412. }
  1413. exports.RequestType = RequestType;
  1414. class RequestType1 extends AbstractMessageType {
  1415. constructor(method) {
  1416. super(method, 1);
  1417. this._ = undefined;
  1418. }
  1419. }
  1420. exports.RequestType1 = RequestType1;
  1421. class RequestType2 extends AbstractMessageType {
  1422. constructor(method) {
  1423. super(method, 2);
  1424. this._ = undefined;
  1425. }
  1426. }
  1427. exports.RequestType2 = RequestType2;
  1428. class RequestType3 extends AbstractMessageType {
  1429. constructor(method) {
  1430. super(method, 3);
  1431. this._ = undefined;
  1432. }
  1433. }
  1434. exports.RequestType3 = RequestType3;
  1435. class RequestType4 extends AbstractMessageType {
  1436. constructor(method) {
  1437. super(method, 4);
  1438. this._ = undefined;
  1439. }
  1440. }
  1441. exports.RequestType4 = RequestType4;
  1442. class RequestType5 extends AbstractMessageType {
  1443. constructor(method) {
  1444. super(method, 5);
  1445. this._ = undefined;
  1446. }
  1447. }
  1448. exports.RequestType5 = RequestType5;
  1449. class RequestType6 extends AbstractMessageType {
  1450. constructor(method) {
  1451. super(method, 6);
  1452. this._ = undefined;
  1453. }
  1454. }
  1455. exports.RequestType6 = RequestType6;
  1456. class RequestType7 extends AbstractMessageType {
  1457. constructor(method) {
  1458. super(method, 7);
  1459. this._ = undefined;
  1460. }
  1461. }
  1462. exports.RequestType7 = RequestType7;
  1463. class RequestType8 extends AbstractMessageType {
  1464. constructor(method) {
  1465. super(method, 8);
  1466. this._ = undefined;
  1467. }
  1468. }
  1469. exports.RequestType8 = RequestType8;
  1470. class RequestType9 extends AbstractMessageType {
  1471. constructor(method) {
  1472. super(method, 9);
  1473. this._ = undefined;
  1474. }
  1475. }
  1476. exports.RequestType9 = RequestType9;
  1477. class NotificationType extends AbstractMessageType {
  1478. constructor(method) {
  1479. super(method, 1);
  1480. this._ = undefined;
  1481. }
  1482. }
  1483. exports.NotificationType = NotificationType;
  1484. class NotificationType0 extends AbstractMessageType {
  1485. constructor(method) {
  1486. super(method, 0);
  1487. this._ = undefined;
  1488. }
  1489. }
  1490. exports.NotificationType0 = NotificationType0;
  1491. class NotificationType1 extends AbstractMessageType {
  1492. constructor(method) {
  1493. super(method, 1);
  1494. this._ = undefined;
  1495. }
  1496. }
  1497. exports.NotificationType1 = NotificationType1;
  1498. class NotificationType2 extends AbstractMessageType {
  1499. constructor(method) {
  1500. super(method, 2);
  1501. this._ = undefined;
  1502. }
  1503. }
  1504. exports.NotificationType2 = NotificationType2;
  1505. class NotificationType3 extends AbstractMessageType {
  1506. constructor(method) {
  1507. super(method, 3);
  1508. this._ = undefined;
  1509. }
  1510. }
  1511. exports.NotificationType3 = NotificationType3;
  1512. class NotificationType4 extends AbstractMessageType {
  1513. constructor(method) {
  1514. super(method, 4);
  1515. this._ = undefined;
  1516. }
  1517. }
  1518. exports.NotificationType4 = NotificationType4;
  1519. class NotificationType5 extends AbstractMessageType {
  1520. constructor(method) {
  1521. super(method, 5);
  1522. this._ = undefined;
  1523. }
  1524. }
  1525. exports.NotificationType5 = NotificationType5;
  1526. class NotificationType6 extends AbstractMessageType {
  1527. constructor(method) {
  1528. super(method, 6);
  1529. this._ = undefined;
  1530. }
  1531. }
  1532. exports.NotificationType6 = NotificationType6;
  1533. class NotificationType7 extends AbstractMessageType {
  1534. constructor(method) {
  1535. super(method, 7);
  1536. this._ = undefined;
  1537. }
  1538. }
  1539. exports.NotificationType7 = NotificationType7;
  1540. class NotificationType8 extends AbstractMessageType {
  1541. constructor(method) {
  1542. super(method, 8);
  1543. this._ = undefined;
  1544. }
  1545. }
  1546. exports.NotificationType8 = NotificationType8;
  1547. class NotificationType9 extends AbstractMessageType {
  1548. constructor(method) {
  1549. super(method, 9);
  1550. this._ = undefined;
  1551. }
  1552. }
  1553. exports.NotificationType9 = NotificationType9;
  1554. /**
  1555. * Tests if the given message is a request message
  1556. */
  1557. function isRequestMessage(message) {
  1558. let candidate = message;
  1559. return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
  1560. }
  1561. exports.isRequestMessage = isRequestMessage;
  1562. /**
  1563. * Tests if the given message is a notification message
  1564. */
  1565. function isNotificationMessage(message) {
  1566. let candidate = message;
  1567. return candidate && is.string(candidate.method) && message.id === void 0;
  1568. }
  1569. exports.isNotificationMessage = isNotificationMessage;
  1570. /**
  1571. * Tests if the given message is a response message
  1572. */
  1573. function isResponseMessage(message) {
  1574. let candidate = message;
  1575. return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
  1576. }
  1577. exports.isResponseMessage = isResponseMessage;
  1578. /***/ }),
  1579. /* 7 */
  1580. /***/ (function(module, exports, __webpack_require__) {
  1581. "use strict";
  1582. /* --------------------------------------------------------------------------------------------
  1583. * Copyright (c) Microsoft Corporation. All rights reserved.
  1584. * Licensed under the MIT License. See License.txt in the project root for license information.
  1585. * ------------------------------------------------------------------------------------------ */
  1586. Object.defineProperty(exports, "__esModule", { value: true });
  1587. const events_1 = __webpack_require__(8);
  1588. const Is = __webpack_require__(5);
  1589. let DefaultSize = 8192;
  1590. let CR = Buffer.from('\r', 'ascii')[0];
  1591. let LF = Buffer.from('\n', 'ascii')[0];
  1592. let CRLF = '\r\n';
  1593. class MessageBuffer {
  1594. constructor(encoding = 'utf8') {
  1595. this.encoding = encoding;
  1596. this.index = 0;
  1597. this.buffer = Buffer.allocUnsafe(DefaultSize);
  1598. }
  1599. append(chunk) {
  1600. var toAppend = chunk;
  1601. if (typeof (chunk) === 'string') {
  1602. var str = chunk;
  1603. var bufferLen = Buffer.byteLength(str, this.encoding);
  1604. toAppend = Buffer.allocUnsafe(bufferLen);
  1605. toAppend.write(str, 0, bufferLen, this.encoding);
  1606. }
  1607. if (this.buffer.length - this.index >= toAppend.length) {
  1608. toAppend.copy(this.buffer, this.index, 0, toAppend.length);
  1609. }
  1610. else {
  1611. var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
  1612. if (this.index === 0) {
  1613. this.buffer = Buffer.allocUnsafe(newSize);
  1614. toAppend.copy(this.buffer, 0, 0, toAppend.length);
  1615. }
  1616. else {
  1617. this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
  1618. }
  1619. }
  1620. this.index += toAppend.length;
  1621. }
  1622. tryReadHeaders() {
  1623. let result = undefined;
  1624. let current = 0;
  1625. while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {
  1626. current++;
  1627. }
  1628. // No header / body separator found (e.g CRLFCRLF)
  1629. if (current + 3 >= this.index) {
  1630. return result;
  1631. }
  1632. result = Object.create(null);
  1633. let headers = this.buffer.toString('ascii', 0, current).split(CRLF);
  1634. headers.forEach((header) => {
  1635. let index = header.indexOf(':');
  1636. if (index === -1) {
  1637. throw new Error('Message header must separate key and value using :');
  1638. }
  1639. let key = header.substr(0, index);
  1640. let value = header.substr(index + 1).trim();
  1641. result[key] = value;
  1642. });
  1643. let nextStart = current + 4;
  1644. this.buffer = this.buffer.slice(nextStart);
  1645. this.index = this.index - nextStart;
  1646. return result;
  1647. }
  1648. tryReadContent(length) {
  1649. if (this.index < length) {
  1650. return null;
  1651. }
  1652. let result = this.buffer.toString(this.encoding, 0, length);
  1653. let nextStart = length;
  1654. this.buffer.copy(this.buffer, 0, nextStart);
  1655. this.index = this.index - nextStart;
  1656. return result;
  1657. }
  1658. get numberOfBytes() {
  1659. return this.index;
  1660. }
  1661. }
  1662. var MessageReader;
  1663. (function (MessageReader) {
  1664. function is(value) {
  1665. let candidate = value;
  1666. return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
  1667. Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
  1668. }
  1669. MessageReader.is = is;
  1670. })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
  1671. class AbstractMessageReader {
  1672. constructor() {
  1673. this.errorEmitter = new events_1.Emitter();
  1674. this.closeEmitter = new events_1.Emitter();
  1675. this.partialMessageEmitter = new events_1.Emitter();
  1676. }
  1677. dispose() {
  1678. this.errorEmitter.dispose();
  1679. this.closeEmitter.dispose();
  1680. }
  1681. get onError() {
  1682. return this.errorEmitter.event;
  1683. }
  1684. fireError(error) {
  1685. this.errorEmitter.fire(this.asError(error));
  1686. }
  1687. get onClose() {
  1688. return this.closeEmitter.event;
  1689. }
  1690. fireClose() {
  1691. this.closeEmitter.fire(undefined);
  1692. }
  1693. get onPartialMessage() {
  1694. return this.partialMessageEmitter.event;
  1695. }
  1696. firePartialMessage(info) {
  1697. this.partialMessageEmitter.fire(info);
  1698. }
  1699. asError(error) {
  1700. if (error instanceof Error) {
  1701. return error;
  1702. }
  1703. else {
  1704. return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
  1705. }
  1706. }
  1707. }
  1708. exports.AbstractMessageReader = AbstractMessageReader;
  1709. class StreamMessageReader extends AbstractMessageReader {
  1710. constructor(readable, encoding = 'utf8') {
  1711. super();
  1712. this.readable = readable;
  1713. this.buffer = new MessageBuffer(encoding);
  1714. this._partialMessageTimeout = 10000;
  1715. }
  1716. set partialMessageTimeout(timeout) {
  1717. this._partialMessageTimeout = timeout;
  1718. }
  1719. get partialMessageTimeout() {
  1720. return this._partialMessageTimeout;
  1721. }
  1722. listen(callback) {
  1723. this.nextMessageLength = -1;
  1724. this.messageToken = 0;
  1725. this.partialMessageTimer = undefined;
  1726. this.callback = callback;
  1727. this.readable.on('data', (data) => {
  1728. this.onData(data);
  1729. });
  1730. this.readable.on('error', (error) => this.fireError(error));
  1731. this.readable.on('close', () => this.fireClose());
  1732. }
  1733. onData(data) {
  1734. this.buffer.append(data);
  1735. while (true) {
  1736. if (this.nextMessageLength === -1) {
  1737. let headers = this.buffer.tryReadHeaders();
  1738. if (!headers) {
  1739. return;
  1740. }
  1741. let contentLength = headers['Content-Length'];
  1742. if (!contentLength) {
  1743. throw new Error('Header must provide a Content-Length property.');
  1744. }
  1745. let length = parseInt(contentLength);
  1746. if (isNaN(length)) {
  1747. throw new Error('Content-Length value must be a number.');
  1748. }
  1749. this.nextMessageLength = length;
  1750. // Take the encoding form the header. For compatibility
  1751. // treat both utf-8 and utf8 as node utf8
  1752. }
  1753. var msg = this.buffer.tryReadContent(this.nextMessageLength);
  1754. if (msg === null) {
  1755. /** We haven't received the full message yet. */
  1756. this.setPartialMessageTimer();
  1757. return;
  1758. }
  1759. this.clearPartialMessageTimer();
  1760. this.nextMessageLength = -1;
  1761. this.messageToken++;
  1762. var json = JSON.parse(msg);
  1763. this.callback(json);
  1764. }
  1765. }
  1766. clearPartialMessageTimer() {
  1767. if (this.partialMessageTimer) {
  1768. clearTimeout(this.partialMessageTimer);
  1769. this.partialMessageTimer = undefined;
  1770. }
  1771. }
  1772. setPartialMessageTimer() {
  1773. this.clearPartialMessageTimer();
  1774. if (this._partialMessageTimeout <= 0) {
  1775. return;
  1776. }
  1777. this.partialMessageTimer = setTimeout((token, timeout) => {
  1778. this.partialMessageTimer = undefined;
  1779. if (token === this.messageToken) {
  1780. this.firePartialMessage({ messageToken: token, waitingTime: timeout });
  1781. this.setPartialMessageTimer();
  1782. }
  1783. }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
  1784. }
  1785. }
  1786. exports.StreamMessageReader = StreamMessageReader;
  1787. class IPCMessageReader extends AbstractMessageReader {
  1788. constructor(process) {
  1789. super();
  1790. this.process = process;
  1791. let eventEmitter = this.process;
  1792. eventEmitter.on('error', (error) => this.fireError(error));
  1793. eventEmitter.on('close', () => this.fireClose());
  1794. }
  1795. listen(callback) {
  1796. this.process.on('message', callback);
  1797. }
  1798. }
  1799. exports.IPCMessageReader = IPCMessageReader;
  1800. class SocketMessageReader extends StreamMessageReader {
  1801. constructor(socket, encoding = 'utf-8') {
  1802. super(socket, encoding);
  1803. }
  1804. }
  1805. exports.SocketMessageReader = SocketMessageReader;
  1806. /***/ }),
  1807. /* 8 */
  1808. /***/ (function(module, exports, __webpack_require__) {
  1809. "use strict";
  1810. /* --------------------------------------------------------------------------------------------
  1811. * Copyright (c) Microsoft Corporation. All rights reserved.
  1812. * Licensed under the MIT License. See License.txt in the project root for license information.
  1813. * ------------------------------------------------------------------------------------------ */
  1814. Object.defineProperty(exports, "__esModule", { value: true });
  1815. var Disposable;
  1816. (function (Disposable) {
  1817. function create(func) {
  1818. return {
  1819. dispose: func
  1820. };
  1821. }
  1822. Disposable.create = create;
  1823. })(Disposable = exports.Disposable || (exports.Disposable = {}));
  1824. var Event;
  1825. (function (Event) {
  1826. const _disposable = { dispose() { } };
  1827. Event.None = function () { return _disposable; };
  1828. })(Event = exports.Event || (exports.Event = {}));
  1829. class CallbackList {
  1830. add(callback, context = null, bucket) {
  1831. if (!this._callbacks) {
  1832. this._callbacks = [];
  1833. this._contexts = [];
  1834. }
  1835. this._callbacks.push(callback);
  1836. this._contexts.push(context);
  1837. if (Array.isArray(bucket)) {
  1838. bucket.push({ dispose: () => this.remove(callback, context) });
  1839. }
  1840. }
  1841. remove(callback, context = null) {
  1842. if (!this._callbacks) {
  1843. return;
  1844. }
  1845. var foundCallbackWithDifferentContext = false;
  1846. for (var i = 0, len = this._callbacks.length; i < len; i++) {
  1847. if (this._callbacks[i] === callback) {
  1848. if (this._contexts[i] === context) {
  1849. // callback & context match => remove it
  1850. this._callbacks.splice(i, 1);
  1851. this._contexts.splice(i, 1);
  1852. return;
  1853. }
  1854. else {
  1855. foundCallbackWithDifferentContext = true;
  1856. }
  1857. }
  1858. }
  1859. if (foundCallbackWithDifferentContext) {
  1860. throw new Error('When adding a listener with a context, you should remove it with the same context');
  1861. }
  1862. }
  1863. invoke(...args) {
  1864. if (!this._callbacks) {
  1865. return [];
  1866. }
  1867. var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
  1868. for (var i = 0, len = callbacks.length; i < len; i++) {
  1869. try {
  1870. ret.push(callbacks[i].apply(contexts[i], args));
  1871. }
  1872. catch (e) {
  1873. console.error(e);
  1874. }
  1875. }
  1876. return ret;
  1877. }
  1878. isEmpty() {
  1879. return !this._callbacks || this._callbacks.length === 0;
  1880. }
  1881. dispose() {
  1882. this._callbacks = undefined;
  1883. this._contexts = undefined;
  1884. }
  1885. }
  1886. class Emitter {
  1887. constructor(_options) {
  1888. this._options = _options;
  1889. }
  1890. /**
  1891. * For the public to allow to subscribe
  1892. * to events from this Emitter
  1893. */
  1894. get event() {
  1895. if (!this._event) {
  1896. this._event = (listener, thisArgs, disposables) => {
  1897. if (!this._callbacks) {
  1898. this._callbacks = new CallbackList();
  1899. }
  1900. if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
  1901. this._options.onFirstListenerAdd(this);
  1902. }
  1903. this._callbacks.add(listener, thisArgs);
  1904. let result;
  1905. result = {
  1906. dispose: () => {
  1907. this._callbacks.remove(listener, thisArgs);
  1908. result.dispose = Emitter._noop;
  1909. if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
  1910. this._options.onLastListenerRemove(this);
  1911. }
  1912. }
  1913. };
  1914. if (Array.isArray(disposables)) {
  1915. disposables.push(result);
  1916. }
  1917. return result;
  1918. };
  1919. }
  1920. return this._event;
  1921. }
  1922. /**
  1923. * To be kept private to fire an event to
  1924. * subscribers
  1925. */
  1926. fire(event) {
  1927. if (this._callbacks) {
  1928. this._callbacks.invoke.call(this._callbacks, event);
  1929. }
  1930. }
  1931. dispose() {
  1932. if (this._callbacks) {
  1933. this._callbacks.dispose();
  1934. this._callbacks = undefined;
  1935. }
  1936. }
  1937. }
  1938. Emitter._noop = function () { };
  1939. exports.Emitter = Emitter;
  1940. /***/ }),
  1941. /* 9 */
  1942. /***/ (function(module, exports, __webpack_require__) {
  1943. "use strict";
  1944. /* --------------------------------------------------------------------------------------------
  1945. * Copyright (c) Microsoft Corporation. All rights reserved.
  1946. * Licensed under the MIT License. See License.txt in the project root for license information.
  1947. * ------------------------------------------------------------------------------------------ */
  1948. Object.defineProperty(exports, "__esModule", { value: true });
  1949. const events_1 = __webpack_require__(8);
  1950. const Is = __webpack_require__(5);
  1951. let ContentLength = 'Content-Length: ';
  1952. let CRLF = '\r\n';
  1953. var MessageWriter;
  1954. (function (MessageWriter) {
  1955. function is(value) {
  1956. let candidate = value;
  1957. return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
  1958. Is.func(candidate.onError) && Is.func(candidate.write);
  1959. }
  1960. MessageWriter.is = is;
  1961. })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
  1962. class AbstractMessageWriter {
  1963. constructor() {
  1964. this.errorEmitter = new events_1.Emitter();
  1965. this.closeEmitter = new events_1.Emitter();
  1966. }
  1967. dispose() {
  1968. this.errorEmitter.dispose();
  1969. this.closeEmitter.dispose();
  1970. }
  1971. get onError() {
  1972. return this.errorEmitter.event;
  1973. }
  1974. fireError(error, message, count) {
  1975. this.errorEmitter.fire([this.asError(error), message, count]);
  1976. }
  1977. get onClose() {
  1978. return this.closeEmitter.event;
  1979. }
  1980. fireClose() {
  1981. this.closeEmitter.fire(undefined);
  1982. }
  1983. asError(error) {
  1984. if (error instanceof Error) {
  1985. return error;
  1986. }
  1987. else {
  1988. return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
  1989. }
  1990. }
  1991. }
  1992. exports.AbstractMessageWriter = AbstractMessageWriter;
  1993. class StreamMessageWriter extends AbstractMessageWriter {
  1994. constructor(writable, encoding = 'utf8') {
  1995. super();
  1996. this.writable = writable;
  1997. this.encoding = encoding;
  1998. this.errorCount = 0;
  1999. this.writable.on('error', (error) => this.fireError(error));
  2000. this.writable.on('close', () => this.fireClose());
  2001. }
  2002. write(msg) {
  2003. let json = JSON.stringify(msg);
  2004. let contentLength = Buffer.byteLength(json, this.encoding);
  2005. let headers = [
  2006. ContentLength, contentLength.toString(), CRLF,
  2007. CRLF
  2008. ];
  2009. try {
  2010. // Header must be written in ASCII encoding
  2011. this.writable.write(headers.join(''), 'ascii');
  2012. // Now write the content. This can be written in any encoding
  2013. this.writable.write(json, this.encoding);
  2014. this.errorCount = 0;
  2015. }
  2016. catch (error) {
  2017. this.errorCount++;
  2018. this.fireError(error, msg, this.errorCount);
  2019. }
  2020. }
  2021. }
  2022. exports.StreamMessageWriter = StreamMessageWriter;
  2023. class IPCMessageWriter extends AbstractMessageWriter {
  2024. constructor(process) {
  2025. super();
  2026. this.process = process;
  2027. this.errorCount = 0;
  2028. this.queue = [];
  2029. this.sending = false;
  2030. let eventEmitter = this.process;
  2031. eventEmitter.on('error', (error) => this.fireError(error));
  2032. eventEmitter.on('close', () => this.fireClose);
  2033. }
  2034. write(msg) {
  2035. if (!this.sending && this.queue.length === 0) {
  2036. // See https://github.com/nodejs/node/issues/7657
  2037. this.doWriteMessage(msg);
  2038. }
  2039. else {
  2040. this.queue.push(msg);
  2041. }
  2042. }
  2043. doWriteMessage(msg) {
  2044. try {
  2045. if (this.process.send) {
  2046. this.sending = true;
  2047. this.process.send(msg, undefined, undefined, (error) => {
  2048. this.sending = false;
  2049. if (error) {
  2050. this.errorCount++;
  2051. this.fireError(error, msg, this.errorCount);
  2052. }
  2053. else {
  2054. this.errorCount = 0;
  2055. }
  2056. if (this.queue.length > 0) {
  2057. this.doWriteMessage(this.queue.shift());
  2058. }
  2059. });
  2060. }
  2061. }
  2062. catch (error) {
  2063. this.errorCount++;
  2064. this.fireError(error, msg, this.errorCount);
  2065. }
  2066. }
  2067. }
  2068. exports.IPCMessageWriter = IPCMessageWriter;
  2069. class SocketMessageWriter extends AbstractMessageWriter {
  2070. constructor(socket, encoding = 'utf8') {
  2071. super();
  2072. this.socket = socket;
  2073. this.queue = [];
  2074. this.sending = false;
  2075. this.encoding = encoding;
  2076. this.errorCount = 0;
  2077. this.socket.on('error', (error) => this.fireError(error));
  2078. this.socket.on('close', () => this.fireClose());
  2079. }
  2080. dispose() {
  2081. super.dispose();
  2082. this.socket.destroy();
  2083. }
  2084. write(msg) {
  2085. if (!this.sending && this.queue.length === 0) {
  2086. // See https://github.com/nodejs/node/issues/7657
  2087. this.doWriteMessage(msg);
  2088. }
  2089. else {
  2090. this.queue.push(msg);
  2091. }
  2092. }
  2093. doWriteMessage(msg) {
  2094. let json = JSON.stringify(msg);
  2095. let contentLength = Buffer.byteLength(json, this.encoding);
  2096. let headers = [
  2097. ContentLength, contentLength.toString(), CRLF,
  2098. CRLF
  2099. ];
  2100. try {
  2101. // Header must be written in ASCII encoding
  2102. this.sending = true;
  2103. this.socket.write(headers.join(''), 'ascii', (error) => {
  2104. if (error) {
  2105. this.handleError(error, msg);
  2106. }
  2107. try {
  2108. // Now write the content. This can be written in any encoding
  2109. this.socket.write(json, this.encoding, (error) => {
  2110. this.sending = false;
  2111. if (error) {
  2112. this.handleError(error, msg);
  2113. }
  2114. else {
  2115. this.errorCount = 0;
  2116. }
  2117. if (this.queue.length > 0) {
  2118. this.doWriteMessage(this.queue.shift());
  2119. }
  2120. });
  2121. }
  2122. catch (error) {
  2123. this.handleError(error, msg);
  2124. }
  2125. });
  2126. }
  2127. catch (error) {
  2128. this.handleError(error, msg);
  2129. }
  2130. }
  2131. handleError(error, msg) {
  2132. this.errorCount++;
  2133. this.fireError(error, msg, this.errorCount);
  2134. }
  2135. }
  2136. exports.SocketMessageWriter = SocketMessageWriter;
  2137. /***/ }),
  2138. /* 10 */
  2139. /***/ (function(module, exports, __webpack_require__) {
  2140. "use strict";
  2141. /*---------------------------------------------------------------------------------------------
  2142. * Copyright (c) Microsoft Corporation. All rights reserved.
  2143. * Licensed under the MIT License. See License.txt in the project root for license information.
  2144. *--------------------------------------------------------------------------------------------*/
  2145. Object.defineProperty(exports, "__esModule", { value: true });
  2146. const events_1 = __webpack_require__(8);
  2147. const Is = __webpack_require__(5);
  2148. var CancellationToken;
  2149. (function (CancellationToken) {
  2150. CancellationToken.None = Object.freeze({
  2151. isCancellationRequested: false,
  2152. onCancellationRequested: events_1.Event.None
  2153. });
  2154. CancellationToken.Cancelled = Object.freeze({
  2155. isCancellationRequested: true,
  2156. onCancellationRequested: events_1.Event.None
  2157. });
  2158. function is(value) {
  2159. let candidate = value;
  2160. return candidate && (candidate === CancellationToken.None
  2161. || candidate === CancellationToken.Cancelled
  2162. || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
  2163. }
  2164. CancellationToken.is = is;
  2165. })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
  2166. const shortcutEvent = Object.freeze(function (callback, context) {
  2167. let handle = setTimeout(callback.bind(context), 0);
  2168. return { dispose() { clearTimeout(handle); } };
  2169. });
  2170. class MutableToken {
  2171. constructor() {
  2172. this._isCancelled = false;
  2173. }
  2174. cancel() {
  2175. if (!this._isCancelled) {
  2176. this._isCancelled = true;
  2177. if (this._emitter) {
  2178. this._emitter.fire(undefined);
  2179. this.dispose();
  2180. }
  2181. }
  2182. }
  2183. get isCancellationRequested() {
  2184. return this._isCancelled;
  2185. }
  2186. get onCancellationRequested() {
  2187. if (this._isCancelled) {
  2188. return shortcutEvent;
  2189. }
  2190. if (!this._emitter) {
  2191. this._emitter = new events_1.Emitter();
  2192. }
  2193. return this._emitter.event;
  2194. }
  2195. dispose() {
  2196. if (this._emitter) {
  2197. this._emitter.dispose();
  2198. this._emitter = undefined;
  2199. }
  2200. }
  2201. }
  2202. class CancellationTokenSource {
  2203. get token() {
  2204. if (!this._token) {
  2205. // be lazy and create the token only when
  2206. // actually needed
  2207. this._token = new MutableToken();
  2208. }
  2209. return this._token;
  2210. }
  2211. cancel() {
  2212. if (!this._token) {
  2213. // save an object by returning the default
  2214. // cancelled token when cancellation happens
  2215. // before someone asks for the token
  2216. this._token = CancellationToken.Cancelled;
  2217. }
  2218. else {
  2219. this._token.cancel();
  2220. }
  2221. }
  2222. dispose() {
  2223. if (!this._token) {
  2224. // ensure to initialize with an empty token if we had none
  2225. this._token = CancellationToken.None;
  2226. }
  2227. else if (this._token instanceof MutableToken) {
  2228. // actually dispose
  2229. this._token.dispose();
  2230. }
  2231. }
  2232. }
  2233. exports.CancellationTokenSource = CancellationTokenSource;
  2234. /***/ }),
  2235. /* 11 */
  2236. /***/ (function(module, exports, __webpack_require__) {
  2237. "use strict";
  2238. /*---------------------------------------------------------------------------------------------
  2239. * Copyright (c) Microsoft Corporation. All rights reserved.
  2240. * Licensed under the MIT License. See License.txt in the project root for license information.
  2241. *--------------------------------------------------------------------------------------------*/
  2242. Object.defineProperty(exports, "__esModule", { value: true });
  2243. var Touch;
  2244. (function (Touch) {
  2245. Touch.None = 0;
  2246. Touch.First = 1;
  2247. Touch.Last = 2;
  2248. })(Touch = exports.Touch || (exports.Touch = {}));
  2249. class LinkedMap {
  2250. constructor() {
  2251. this._map = new Map();
  2252. this._head = undefined;
  2253. this._tail = undefined;
  2254. this._size = 0;
  2255. }
  2256. clear() {
  2257. this._map.clear();
  2258. this._head = undefined;
  2259. this._tail = undefined;
  2260. this._size = 0;
  2261. }
  2262. isEmpty() {
  2263. return !this._head && !this._tail;
  2264. }
  2265. get size() {
  2266. return this._size;
  2267. }
  2268. has(key) {
  2269. return this._map.has(key);
  2270. }
  2271. get(key) {
  2272. const item = this._map.get(key);
  2273. if (!item) {
  2274. return undefined;
  2275. }
  2276. return item.value;
  2277. }
  2278. set(key, value, touch = Touch.None) {
  2279. let item = this._map.get(key);
  2280. if (item) {
  2281. item.value = value;
  2282. if (touch !== Touch.None) {
  2283. this.touch(item, touch);
  2284. }
  2285. }
  2286. else {
  2287. item = { key, value, next: undefined, previous: undefined };
  2288. switch (touch) {
  2289. case Touch.None:
  2290. this.addItemLast(item);
  2291. break;
  2292. case Touch.First:
  2293. this.addItemFirst(item);
  2294. break;
  2295. case Touch.Last:
  2296. this.addItemLast(item);
  2297. break;
  2298. default:
  2299. this.addItemLast(item);
  2300. break;
  2301. }
  2302. this._map.set(key, item);
  2303. this._size++;
  2304. }
  2305. }
  2306. delete(key) {
  2307. const item = this._map.get(key);
  2308. if (!item) {
  2309. return false;
  2310. }
  2311. this._map.delete(key);
  2312. this.removeItem(item);
  2313. this._size--;
  2314. return true;
  2315. }
  2316. shift() {
  2317. if (!this._head && !this._tail) {
  2318. return undefined;
  2319. }
  2320. if (!this._head || !this._tail) {
  2321. throw new Error('Invalid list');
  2322. }
  2323. const item = this._head;
  2324. this._map.delete(item.key);
  2325. this.removeItem(item);
  2326. this._size--;
  2327. return item.value;
  2328. }
  2329. forEach(callbackfn, thisArg) {
  2330. let current = this._head;
  2331. while (current) {
  2332. if (thisArg) {
  2333. callbackfn.bind(thisArg)(current.value, current.key, this);
  2334. }
  2335. else {
  2336. callbackfn(current.value, current.key, this);
  2337. }
  2338. current = current.next;
  2339. }
  2340. }
  2341. forEachReverse(callbackfn, thisArg) {
  2342. let current = this._tail;
  2343. while (current) {
  2344. if (thisArg) {
  2345. callbackfn.bind(thisArg)(current.value, current.key, this);
  2346. }
  2347. else {
  2348. callbackfn(current.value, current.key, this);
  2349. }
  2350. current = current.previous;
  2351. }
  2352. }
  2353. values() {
  2354. let result = [];
  2355. let current = this._head;
  2356. while (current) {
  2357. result.push(current.value);
  2358. current = current.next;
  2359. }
  2360. return result;
  2361. }
  2362. keys() {
  2363. let result = [];
  2364. let current = this._head;
  2365. while (current) {
  2366. result.push(current.key);
  2367. current = current.next;
  2368. }
  2369. return result;
  2370. }
  2371. /* JSON RPC run on es5 which has no Symbol.iterator
  2372. public keys(): IterableIterator<K> {
  2373. let current = this._head;
  2374. let iterator: IterableIterator<K> = {
  2375. [Symbol.iterator]() {
  2376. return iterator;
  2377. },
  2378. next():IteratorResult<K> {
  2379. if (current) {
  2380. let result = { value: current.key, done: false };
  2381. current = current.next;
  2382. return result;
  2383. } else {
  2384. return { value: undefined, done: true };
  2385. }
  2386. }
  2387. };
  2388. return iterator;
  2389. }
  2390. public values(): IterableIterator<V> {
  2391. let current = this._head;
  2392. let iterator: IterableIterator<V> = {
  2393. [Symbol.iterator]() {
  2394. return iterator;
  2395. },
  2396. next():IteratorResult<V> {
  2397. if (current) {
  2398. let result = { value: current.value, done: false };
  2399. current = current.next;
  2400. return result;
  2401. } else {
  2402. return { value: undefined, done: true };
  2403. }
  2404. }
  2405. };
  2406. return iterator;
  2407. }
  2408. */
  2409. addItemFirst(item) {
  2410. // First time Insert
  2411. if (!this._head && !this._tail) {
  2412. this._tail = item;
  2413. }
  2414. else if (!this._head) {
  2415. throw new Error('Invalid list');
  2416. }
  2417. else {
  2418. item.next = this._head;
  2419. this._head.previous = item;
  2420. }
  2421. this._head = item;
  2422. }
  2423. addItemLast(item) {
  2424. // First time Insert
  2425. if (!this._head && !this._tail) {
  2426. this._head = item;
  2427. }
  2428. else if (!this._tail) {
  2429. throw new Error('Invalid list');
  2430. }
  2431. else {
  2432. item.previous = this._tail;
  2433. this._tail.next = item;
  2434. }
  2435. this._tail = item;
  2436. }
  2437. removeItem(item) {
  2438. if (item === this._head && item === this._tail) {
  2439. this._head = undefined;
  2440. this._tail = undefined;
  2441. }
  2442. else if (item === this._head) {
  2443. this._head = item.next;
  2444. }
  2445. else if (item === this._tail) {
  2446. this._tail = item.previous;
  2447. }
  2448. else {
  2449. const next = item.next;
  2450. const previous = item.previous;
  2451. if (!next || !previous) {
  2452. throw new Error('Invalid list');
  2453. }
  2454. next.previous = previous;
  2455. previous.next = next;
  2456. }
  2457. }
  2458. touch(item, touch) {
  2459. if (!this._head || !this._tail) {
  2460. throw new Error('Invalid list');
  2461. }
  2462. if ((touch !== Touch.First && touch !== Touch.Last)) {
  2463. return;
  2464. }
  2465. if (touch === Touch.First) {
  2466. if (item === this._head) {
  2467. return;
  2468. }
  2469. const next = item.next;
  2470. const previous = item.previous;
  2471. // Unlink the item
  2472. if (item === this._tail) {
  2473. // previous must be defined since item was not head but is tail
  2474. // So there are more than on item in the map
  2475. previous.next = undefined;
  2476. this._tail = previous;
  2477. }
  2478. else {
  2479. // Both next and previous are not undefined since item was neither head nor tail.
  2480. next.previous = previous;
  2481. previous.next = next;
  2482. }
  2483. // Insert the node at head
  2484. item.previous = undefined;
  2485. item.next = this._head;
  2486. this._head.previous = item;
  2487. this._head = item;
  2488. }
  2489. else if (touch === Touch.Last) {
  2490. if (item === this._tail) {
  2491. return;
  2492. }
  2493. const next = item.next;
  2494. const previous = item.previous;
  2495. // Unlink the item.
  2496. if (item === this._head) {
  2497. // next must be defined since item was not tail but is head
  2498. // So there are more than on item in the map
  2499. next.previous = undefined;
  2500. this._head = next;
  2501. }
  2502. else {
  2503. // Both next and previous are not undefined since item was neither head nor tail.
  2504. next.previous = previous;
  2505. previous.next = next;
  2506. }
  2507. item.next = undefined;
  2508. item.previous = this._tail;
  2509. this._tail.next = item;
  2510. this._tail = item;
  2511. }
  2512. }
  2513. }
  2514. exports.LinkedMap = LinkedMap;
  2515. /***/ }),
  2516. /* 12 */
  2517. /***/ (function(module, exports, __webpack_require__) {
  2518. "use strict";
  2519. /* --------------------------------------------------------------------------------------------
  2520. * Copyright (c) Microsoft Corporation. All rights reserved.
  2521. * Licensed under the MIT License. See License.txt in the project root for license information.
  2522. * ------------------------------------------------------------------------------------------ */
  2523. Object.defineProperty(exports, "__esModule", { value: true });
  2524. const path_1 = __webpack_require__(13);
  2525. const os_1 = __webpack_require__(14);
  2526. const crypto_1 = __webpack_require__(15);
  2527. const net_1 = __webpack_require__(16);
  2528. const messageReader_1 = __webpack_require__(7);
  2529. const messageWriter_1 = __webpack_require__(9);
  2530. function generateRandomPipeName() {
  2531. const randomSuffix = crypto_1.randomBytes(21).toString('hex');
  2532. if (process.platform === 'win32') {
  2533. return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
  2534. }
  2535. else {
  2536. // Mac/Unix: use socket file
  2537. return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
  2538. }
  2539. }
  2540. exports.generateRandomPipeName = generateRandomPipeName;
  2541. function createClientPipeTransport(pipeName, encoding = 'utf-8') {
  2542. let connectResolve;
  2543. let connected = new Promise((resolve, _reject) => {
  2544. connectResolve = resolve;
  2545. });
  2546. return new Promise((resolve, reject) => {
  2547. let server = net_1.createServer((socket) => {
  2548. server.close();
  2549. connectResolve([
  2550. new messageReader_1.SocketMessageReader(socket, encoding),
  2551. new messageWriter_1.SocketMessageWriter(socket, encoding)
  2552. ]);
  2553. });
  2554. server.on('error', reject);
  2555. server.listen(pipeName, () => {
  2556. server.removeListener('error', reject);
  2557. resolve({
  2558. onConnected: () => { return connected; }
  2559. });
  2560. });
  2561. });
  2562. }
  2563. exports.createClientPipeTransport = createClientPipeTransport;
  2564. function createServerPipeTransport(pipeName, encoding = 'utf-8') {
  2565. const socket = net_1.createConnection(pipeName);
  2566. return [
  2567. new messageReader_1.SocketMessageReader(socket, encoding),
  2568. new messageWriter_1.SocketMessageWriter(socket, encoding)
  2569. ];
  2570. }
  2571. exports.createServerPipeTransport = createServerPipeTransport;
  2572. /***/ }),
  2573. /* 13 */
  2574. /***/ (function(module, exports) {
  2575. module.exports = require("path");
  2576. /***/ }),
  2577. /* 14 */
  2578. /***/ (function(module, exports) {
  2579. module.exports = require("os");
  2580. /***/ }),
  2581. /* 15 */
  2582. /***/ (function(module, exports) {
  2583. module.exports = require("crypto");
  2584. /***/ }),
  2585. /* 16 */
  2586. /***/ (function(module, exports) {
  2587. module.exports = require("net");
  2588. /***/ }),
  2589. /* 17 */
  2590. /***/ (function(module, exports, __webpack_require__) {
  2591. "use strict";
  2592. /* --------------------------------------------------------------------------------------------
  2593. * Copyright (c) Microsoft Corporation. All rights reserved.
  2594. * Licensed under the MIT License. See License.txt in the project root for license information.
  2595. * ------------------------------------------------------------------------------------------ */
  2596. Object.defineProperty(exports, "__esModule", { value: true });
  2597. const net_1 = __webpack_require__(16);
  2598. const messageReader_1 = __webpack_require__(7);
  2599. const messageWriter_1 = __webpack_require__(9);
  2600. function createClientSocketTransport(port, encoding = 'utf-8') {
  2601. let connectResolve;
  2602. let connected = new Promise((resolve, _reject) => {
  2603. connectResolve = resolve;
  2604. });
  2605. return new Promise((resolve, reject) => {
  2606. let server = net_1.createServer((socket) => {
  2607. server.close();
  2608. connectResolve([
  2609. new messageReader_1.SocketMessageReader(socket, encoding),
  2610. new messageWriter_1.SocketMessageWriter(socket, encoding)
  2611. ]);
  2612. });
  2613. server.on('error', reject);
  2614. server.listen(port, '127.0.0.1', () => {
  2615. server.removeListener('error', reject);
  2616. resolve({
  2617. onConnected: () => { return connected; }
  2618. });
  2619. });
  2620. });
  2621. }
  2622. exports.createClientSocketTransport = createClientSocketTransport;
  2623. function createServerSocketTransport(port, encoding = 'utf-8') {
  2624. const socket = net_1.createConnection(port, '127.0.0.1');
  2625. return [
  2626. new messageReader_1.SocketMessageReader(socket, encoding),
  2627. new messageWriter_1.SocketMessageWriter(socket, encoding)
  2628. ];
  2629. }
  2630. exports.createServerSocketTransport = createServerSocketTransport;
  2631. /***/ }),
  2632. /* 18 */
  2633. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  2634. "use strict";
  2635. __webpack_require__.r(__webpack_exports__);
  2636. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
  2637. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
  2638. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
  2639. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
  2640. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
  2641. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
  2642. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
  2643. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
  2644. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
  2645. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
  2646. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
  2647. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
  2648. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
  2649. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
  2650. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
  2651. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
  2652. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
  2653. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
  2654. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
  2655. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
  2656. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
  2657. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
  2658. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
  2659. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
  2660. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
  2661. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
  2662. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
  2663. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
  2664. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
  2665. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
  2666. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
  2667. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
  2668. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
  2669. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
  2670. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
  2671. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
  2672. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
  2673. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
  2674. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
  2675. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
  2676. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
  2677. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
  2678. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
  2679. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
  2680. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
  2681. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
  2682. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
  2683. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentSaveReason", function() { return TextDocumentSaveReason; });
  2684. /* --------------------------------------------------------------------------------------------
  2685. * Copyright (c) Microsoft Corporation. All rights reserved.
  2686. * Licensed under the MIT License. See License.txt in the project root for license information.
  2687. * ------------------------------------------------------------------------------------------ */
  2688. /**
  2689. * The Position namespace provides helper functions to work with
  2690. * [Position](#Position) literals.
  2691. */
  2692. var Position;
  2693. (function (Position) {
  2694. /**
  2695. * Creates a new Position literal from the given line and character.
  2696. * @param line The position's line.
  2697. * @param character The position's character.
  2698. */
  2699. function create(line, character) {
  2700. return { line: line, character: character };
  2701. }
  2702. Position.create = create;
  2703. /**
  2704. * Checks whether the given liternal conforms to the [Position](#Position) interface.
  2705. */
  2706. function is(value) {
  2707. var candidate = value;
  2708. return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
  2709. }
  2710. Position.is = is;
  2711. })(Position || (Position = {}));
  2712. /**
  2713. * The Range namespace provides helper functions to work with
  2714. * [Range](#Range) literals.
  2715. */
  2716. var Range;
  2717. (function (Range) {
  2718. function create(one, two, three, four) {
  2719. if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
  2720. return { start: Position.create(one, two), end: Position.create(three, four) };
  2721. }
  2722. else if (Position.is(one) && Position.is(two)) {
  2723. return { start: one, end: two };
  2724. }
  2725. else {
  2726. throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
  2727. }
  2728. }
  2729. Range.create = create;
  2730. /**
  2731. * Checks whether the given literal conforms to the [Range](#Range) interface.
  2732. */
  2733. function is(value) {
  2734. var candidate = value;
  2735. return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
  2736. }
  2737. Range.is = is;
  2738. })(Range || (Range = {}));
  2739. /**
  2740. * The Location namespace provides helper functions to work with
  2741. * [Location](#Location) literals.
  2742. */
  2743. var Location;
  2744. (function (Location) {
  2745. /**
  2746. * Creates a Location literal.
  2747. * @param uri The location's uri.
  2748. * @param range The location's range.
  2749. */
  2750. function create(uri, range) {
  2751. return { uri: uri, range: range };
  2752. }
  2753. Location.create = create;
  2754. /**
  2755. * Checks whether the given literal conforms to the [Location](#Location) interface.
  2756. */
  2757. function is(value) {
  2758. var candidate = value;
  2759. return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
  2760. }
  2761. Location.is = is;
  2762. })(Location || (Location = {}));
  2763. /**
  2764. * The LocationLink namespace provides helper functions to work with
  2765. * [LocationLink](#LocationLink) literals.
  2766. */
  2767. var LocationLink;
  2768. (function (LocationLink) {
  2769. /**
  2770. * Creates a LocationLink literal.
  2771. * @param targetUri The definition's uri.
  2772. * @param targetRange The full range of the definition.
  2773. * @param targetSelectionRange The span of the symbol definition at the target.
  2774. * @param originSelectionRange The span of the symbol being defined in the originating source file.
  2775. */
  2776. function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
  2777. return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
  2778. }
  2779. LocationLink.create = create;
  2780. /**
  2781. * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
  2782. */
  2783. function is(value) {
  2784. var candidate = value;
  2785. return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
  2786. && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
  2787. && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
  2788. }
  2789. LocationLink.is = is;
  2790. })(LocationLink || (LocationLink = {}));
  2791. /**
  2792. * The Color namespace provides helper functions to work with
  2793. * [Color](#Color) literals.
  2794. */
  2795. var Color;
  2796. (function (Color) {
  2797. /**
  2798. * Creates a new Color literal.
  2799. */
  2800. function create(red, green, blue, alpha) {
  2801. return {
  2802. red: red,
  2803. green: green,
  2804. blue: blue,
  2805. alpha: alpha,
  2806. };
  2807. }
  2808. Color.create = create;
  2809. /**
  2810. * Checks whether the given literal conforms to the [Color](#Color) interface.
  2811. */
  2812. function is(value) {
  2813. var candidate = value;
  2814. return Is.number(candidate.red)
  2815. && Is.number(candidate.green)
  2816. && Is.number(candidate.blue)
  2817. && Is.number(candidate.alpha);
  2818. }
  2819. Color.is = is;
  2820. })(Color || (Color = {}));
  2821. /**
  2822. * The ColorInformation namespace provides helper functions to work with
  2823. * [ColorInformation](#ColorInformation) literals.
  2824. */
  2825. var ColorInformation;
  2826. (function (ColorInformation) {
  2827. /**
  2828. * Creates a new ColorInformation literal.
  2829. */
  2830. function create(range, color) {
  2831. return {
  2832. range: range,
  2833. color: color,
  2834. };
  2835. }
  2836. ColorInformation.create = create;
  2837. /**
  2838. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  2839. */
  2840. function is(value) {
  2841. var candidate = value;
  2842. return Range.is(candidate.range) && Color.is(candidate.color);
  2843. }
  2844. ColorInformation.is = is;
  2845. })(ColorInformation || (ColorInformation = {}));
  2846. /**
  2847. * The Color namespace provides helper functions to work with
  2848. * [ColorPresentation](#ColorPresentation) literals.
  2849. */
  2850. var ColorPresentation;
  2851. (function (ColorPresentation) {
  2852. /**
  2853. * Creates a new ColorInformation literal.
  2854. */
  2855. function create(label, textEdit, additionalTextEdits) {
  2856. return {
  2857. label: label,
  2858. textEdit: textEdit,
  2859. additionalTextEdits: additionalTextEdits,
  2860. };
  2861. }
  2862. ColorPresentation.create = create;
  2863. /**
  2864. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  2865. */
  2866. function is(value) {
  2867. var candidate = value;
  2868. return Is.string(candidate.label)
  2869. && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
  2870. && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
  2871. }
  2872. ColorPresentation.is = is;
  2873. })(ColorPresentation || (ColorPresentation = {}));
  2874. /**
  2875. * Enum of known range kinds
  2876. */
  2877. var FoldingRangeKind;
  2878. (function (FoldingRangeKind) {
  2879. /**
  2880. * Folding range for a comment
  2881. */
  2882. FoldingRangeKind["Comment"] = "comment";
  2883. /**
  2884. * Folding range for a imports or includes
  2885. */
  2886. FoldingRangeKind["Imports"] = "imports";
  2887. /**
  2888. * Folding range for a region (e.g. `#region`)
  2889. */
  2890. FoldingRangeKind["Region"] = "region";
  2891. })(FoldingRangeKind || (FoldingRangeKind = {}));
  2892. /**
  2893. * The folding range namespace provides helper functions to work with
  2894. * [FoldingRange](#FoldingRange) literals.
  2895. */
  2896. var FoldingRange;
  2897. (function (FoldingRange) {
  2898. /**
  2899. * Creates a new FoldingRange literal.
  2900. */
  2901. function create(startLine, endLine, startCharacter, endCharacter, kind) {
  2902. var result = {
  2903. startLine: startLine,
  2904. endLine: endLine
  2905. };
  2906. if (Is.defined(startCharacter)) {
  2907. result.startCharacter = startCharacter;
  2908. }
  2909. if (Is.defined(endCharacter)) {
  2910. result.endCharacter = endCharacter;
  2911. }
  2912. if (Is.defined(kind)) {
  2913. result.kind = kind;
  2914. }
  2915. return result;
  2916. }
  2917. FoldingRange.create = create;
  2918. /**
  2919. * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
  2920. */
  2921. function is(value) {
  2922. var candidate = value;
  2923. return Is.number(candidate.startLine) && Is.number(candidate.startLine)
  2924. && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
  2925. && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
  2926. && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
  2927. }
  2928. FoldingRange.is = is;
  2929. })(FoldingRange || (FoldingRange = {}));
  2930. /**
  2931. * The DiagnosticRelatedInformation namespace provides helper functions to work with
  2932. * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
  2933. */
  2934. var DiagnosticRelatedInformation;
  2935. (function (DiagnosticRelatedInformation) {
  2936. /**
  2937. * Creates a new DiagnosticRelatedInformation literal.
  2938. */
  2939. function create(location, message) {
  2940. return {
  2941. location: location,
  2942. message: message
  2943. };
  2944. }
  2945. DiagnosticRelatedInformation.create = create;
  2946. /**
  2947. * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
  2948. */
  2949. function is(value) {
  2950. var candidate = value;
  2951. return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
  2952. }
  2953. DiagnosticRelatedInformation.is = is;
  2954. })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
  2955. /**
  2956. * The diagnostic's severity.
  2957. */
  2958. var DiagnosticSeverity;
  2959. (function (DiagnosticSeverity) {
  2960. /**
  2961. * Reports an error.
  2962. */
  2963. DiagnosticSeverity.Error = 1;
  2964. /**
  2965. * Reports a warning.
  2966. */
  2967. DiagnosticSeverity.Warning = 2;
  2968. /**
  2969. * Reports an information.
  2970. */
  2971. DiagnosticSeverity.Information = 3;
  2972. /**
  2973. * Reports a hint.
  2974. */
  2975. DiagnosticSeverity.Hint = 4;
  2976. })(DiagnosticSeverity || (DiagnosticSeverity = {}));
  2977. var DiagnosticTag;
  2978. (function (DiagnosticTag) {
  2979. /**
  2980. * Unused or unnecessary code.
  2981. *
  2982. * Clients are allowed to render diagnostics with this tag faded out instead of having
  2983. * an error squiggle.
  2984. */
  2985. DiagnosticTag.Unnecessary = 1;
  2986. })(DiagnosticTag || (DiagnosticTag = {}));
  2987. /**
  2988. * The Diagnostic namespace provides helper functions to work with
  2989. * [Diagnostic](#Diagnostic) literals.
  2990. */
  2991. var Diagnostic;
  2992. (function (Diagnostic) {
  2993. /**
  2994. * Creates a new Diagnostic literal.
  2995. */
  2996. function create(range, message, severity, code, source, relatedInformation) {
  2997. var result = { range: range, message: message };
  2998. if (Is.defined(severity)) {
  2999. result.severity = severity;
  3000. }
  3001. if (Is.defined(code)) {
  3002. result.code = code;
  3003. }
  3004. if (Is.defined(source)) {
  3005. result.source = source;
  3006. }
  3007. if (Is.defined(relatedInformation)) {
  3008. result.relatedInformation = relatedInformation;
  3009. }
  3010. return result;
  3011. }
  3012. Diagnostic.create = create;
  3013. /**
  3014. * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
  3015. */
  3016. function is(value) {
  3017. var candidate = value;
  3018. return Is.defined(candidate)
  3019. && Range.is(candidate.range)
  3020. && Is.string(candidate.message)
  3021. && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
  3022. && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
  3023. && (Is.string(candidate.source) || Is.undefined(candidate.source))
  3024. && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
  3025. }
  3026. Diagnostic.is = is;
  3027. })(Diagnostic || (Diagnostic = {}));
  3028. /**
  3029. * The Command namespace provides helper functions to work with
  3030. * [Command](#Command) literals.
  3031. */
  3032. var Command;
  3033. (function (Command) {
  3034. /**
  3035. * Creates a new Command literal.
  3036. */
  3037. function create(title, command) {
  3038. var args = [];
  3039. for (var _i = 2; _i < arguments.length; _i++) {
  3040. args[_i - 2] = arguments[_i];
  3041. }
  3042. var result = { title: title, command: command };
  3043. if (Is.defined(args) && args.length > 0) {
  3044. result.arguments = args;
  3045. }
  3046. return result;
  3047. }
  3048. Command.create = create;
  3049. /**
  3050. * Checks whether the given literal conforms to the [Command](#Command) interface.
  3051. */
  3052. function is(value) {
  3053. var candidate = value;
  3054. return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
  3055. }
  3056. Command.is = is;
  3057. })(Command || (Command = {}));
  3058. /**
  3059. * The TextEdit namespace provides helper function to create replace,
  3060. * insert and delete edits more easily.
  3061. */
  3062. var TextEdit;
  3063. (function (TextEdit) {
  3064. /**
  3065. * Creates a replace text edit.
  3066. * @param range The range of text to be replaced.
  3067. * @param newText The new text.
  3068. */
  3069. function replace(range, newText) {
  3070. return { range: range, newText: newText };
  3071. }
  3072. TextEdit.replace = replace;
  3073. /**
  3074. * Creates a insert text edit.
  3075. * @param position The position to insert the text at.
  3076. * @param newText The text to be inserted.
  3077. */
  3078. function insert(position, newText) {
  3079. return { range: { start: position, end: position }, newText: newText };
  3080. }
  3081. TextEdit.insert = insert;
  3082. /**
  3083. * Creates a delete text edit.
  3084. * @param range The range of text to be deleted.
  3085. */
  3086. function del(range) {
  3087. return { range: range, newText: '' };
  3088. }
  3089. TextEdit.del = del;
  3090. function is(value) {
  3091. var candidate = value;
  3092. return Is.objectLiteral(candidate)
  3093. && Is.string(candidate.newText)
  3094. && Range.is(candidate.range);
  3095. }
  3096. TextEdit.is = is;
  3097. })(TextEdit || (TextEdit = {}));
  3098. /**
  3099. * The TextDocumentEdit namespace provides helper function to create
  3100. * an edit that manipulates a text document.
  3101. */
  3102. var TextDocumentEdit;
  3103. (function (TextDocumentEdit) {
  3104. /**
  3105. * Creates a new `TextDocumentEdit`
  3106. */
  3107. function create(textDocument, edits) {
  3108. return { textDocument: textDocument, edits: edits };
  3109. }
  3110. TextDocumentEdit.create = create;
  3111. function is(value) {
  3112. var candidate = value;
  3113. return Is.defined(candidate)
  3114. && VersionedTextDocumentIdentifier.is(candidate.textDocument)
  3115. && Array.isArray(candidate.edits);
  3116. }
  3117. TextDocumentEdit.is = is;
  3118. })(TextDocumentEdit || (TextDocumentEdit = {}));
  3119. var CreateFile;
  3120. (function (CreateFile) {
  3121. function create(uri, options) {
  3122. var result = {
  3123. kind: 'create',
  3124. uri: uri
  3125. };
  3126. if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
  3127. result.options = options;
  3128. }
  3129. return result;
  3130. }
  3131. CreateFile.create = create;
  3132. function is(value) {
  3133. var candidate = value;
  3134. return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
  3135. (candidate.options === void 0 ||
  3136. ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
  3137. }
  3138. CreateFile.is = is;
  3139. })(CreateFile || (CreateFile = {}));
  3140. var RenameFile;
  3141. (function (RenameFile) {
  3142. function create(oldUri, newUri, options) {
  3143. var result = {
  3144. kind: 'rename',
  3145. oldUri: oldUri,
  3146. newUri: newUri
  3147. };
  3148. if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
  3149. result.options = options;
  3150. }
  3151. return result;
  3152. }
  3153. RenameFile.create = create;
  3154. function is(value) {
  3155. var candidate = value;
  3156. return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
  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. RenameFile.is = is;
  3161. })(RenameFile || (RenameFile = {}));
  3162. var DeleteFile;
  3163. (function (DeleteFile) {
  3164. function create(uri, options) {
  3165. var result = {
  3166. kind: 'delete',
  3167. uri: uri
  3168. };
  3169. if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
  3170. result.options = options;
  3171. }
  3172. return result;
  3173. }
  3174. DeleteFile.create = create;
  3175. function is(value) {
  3176. var candidate = value;
  3177. return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
  3178. (candidate.options === void 0 ||
  3179. ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
  3180. }
  3181. DeleteFile.is = is;
  3182. })(DeleteFile || (DeleteFile = {}));
  3183. var WorkspaceEdit;
  3184. (function (WorkspaceEdit) {
  3185. function is(value) {
  3186. var candidate = value;
  3187. return candidate &&
  3188. (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
  3189. (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
  3190. if (Is.string(change.kind)) {
  3191. return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
  3192. }
  3193. else {
  3194. return TextDocumentEdit.is(change);
  3195. }
  3196. }));
  3197. }
  3198. WorkspaceEdit.is = is;
  3199. })(WorkspaceEdit || (WorkspaceEdit = {}));
  3200. var TextEditChangeImpl = /** @class */ (function () {
  3201. function TextEditChangeImpl(edits) {
  3202. this.edits = edits;
  3203. }
  3204. TextEditChangeImpl.prototype.insert = function (position, newText) {
  3205. this.edits.push(TextEdit.insert(position, newText));
  3206. };
  3207. TextEditChangeImpl.prototype.replace = function (range, newText) {
  3208. this.edits.push(TextEdit.replace(range, newText));
  3209. };
  3210. TextEditChangeImpl.prototype.delete = function (range) {
  3211. this.edits.push(TextEdit.del(range));
  3212. };
  3213. TextEditChangeImpl.prototype.add = function (edit) {
  3214. this.edits.push(edit);
  3215. };
  3216. TextEditChangeImpl.prototype.all = function () {
  3217. return this.edits;
  3218. };
  3219. TextEditChangeImpl.prototype.clear = function () {
  3220. this.edits.splice(0, this.edits.length);
  3221. };
  3222. return TextEditChangeImpl;
  3223. }());
  3224. /**
  3225. * A workspace change helps constructing changes to a workspace.
  3226. */
  3227. var WorkspaceChange = /** @class */ (function () {
  3228. function WorkspaceChange(workspaceEdit) {
  3229. var _this = this;
  3230. this._textEditChanges = Object.create(null);
  3231. if (workspaceEdit) {
  3232. this._workspaceEdit = workspaceEdit;
  3233. if (workspaceEdit.documentChanges) {
  3234. workspaceEdit.documentChanges.forEach(function (change) {
  3235. if (TextDocumentEdit.is(change)) {
  3236. var textEditChange = new TextEditChangeImpl(change.edits);
  3237. _this._textEditChanges[change.textDocument.uri] = textEditChange;
  3238. }
  3239. });
  3240. }
  3241. else if (workspaceEdit.changes) {
  3242. Object.keys(workspaceEdit.changes).forEach(function (key) {
  3243. var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
  3244. _this._textEditChanges[key] = textEditChange;
  3245. });
  3246. }
  3247. }
  3248. }
  3249. Object.defineProperty(WorkspaceChange.prototype, "edit", {
  3250. /**
  3251. * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
  3252. * use to be returned from a workspace edit operation like rename.
  3253. */
  3254. get: function () {
  3255. return this._workspaceEdit;
  3256. },
  3257. enumerable: true,
  3258. configurable: true
  3259. });
  3260. WorkspaceChange.prototype.getTextEditChange = function (key) {
  3261. if (VersionedTextDocumentIdentifier.is(key)) {
  3262. if (!this._workspaceEdit) {
  3263. this._workspaceEdit = {
  3264. documentChanges: []
  3265. };
  3266. }
  3267. if (!this._workspaceEdit.documentChanges) {
  3268. throw new Error('Workspace edit is not configured for document changes.');
  3269. }
  3270. var textDocument = key;
  3271. var result = this._textEditChanges[textDocument.uri];
  3272. if (!result) {
  3273. var edits = [];
  3274. var textDocumentEdit = {
  3275. textDocument: textDocument,
  3276. edits: edits
  3277. };
  3278. this._workspaceEdit.documentChanges.push(textDocumentEdit);
  3279. result = new TextEditChangeImpl(edits);
  3280. this._textEditChanges[textDocument.uri] = result;
  3281. }
  3282. return result;
  3283. }
  3284. else {
  3285. if (!this._workspaceEdit) {
  3286. this._workspaceEdit = {
  3287. changes: Object.create(null)
  3288. };
  3289. }
  3290. if (!this._workspaceEdit.changes) {
  3291. throw new Error('Workspace edit is not configured for normal text edit changes.');
  3292. }
  3293. var result = this._textEditChanges[key];
  3294. if (!result) {
  3295. var edits = [];
  3296. this._workspaceEdit.changes[key] = edits;
  3297. result = new TextEditChangeImpl(edits);
  3298. this._textEditChanges[key] = result;
  3299. }
  3300. return result;
  3301. }
  3302. };
  3303. WorkspaceChange.prototype.createFile = function (uri, options) {
  3304. this.checkDocumentChanges();
  3305. this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
  3306. };
  3307. WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
  3308. this.checkDocumentChanges();
  3309. this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
  3310. };
  3311. WorkspaceChange.prototype.deleteFile = function (uri, options) {
  3312. this.checkDocumentChanges();
  3313. this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
  3314. };
  3315. WorkspaceChange.prototype.checkDocumentChanges = function () {
  3316. if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
  3317. throw new Error('Workspace edit is not configured for document changes.');
  3318. }
  3319. };
  3320. return WorkspaceChange;
  3321. }());
  3322. /**
  3323. * The TextDocumentIdentifier namespace provides helper functions to work with
  3324. * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
  3325. */
  3326. var TextDocumentIdentifier;
  3327. (function (TextDocumentIdentifier) {
  3328. /**
  3329. * Creates a new TextDocumentIdentifier literal.
  3330. * @param uri The document's uri.
  3331. */
  3332. function create(uri) {
  3333. return { uri: uri };
  3334. }
  3335. TextDocumentIdentifier.create = create;
  3336. /**
  3337. * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
  3338. */
  3339. function is(value) {
  3340. var candidate = value;
  3341. return Is.defined(candidate) && Is.string(candidate.uri);
  3342. }
  3343. TextDocumentIdentifier.is = is;
  3344. })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
  3345. /**
  3346. * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
  3347. * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
  3348. */
  3349. var VersionedTextDocumentIdentifier;
  3350. (function (VersionedTextDocumentIdentifier) {
  3351. /**
  3352. * Creates a new VersionedTextDocumentIdentifier literal.
  3353. * @param uri The document's uri.
  3354. * @param uri The document's text.
  3355. */
  3356. function create(uri, version) {
  3357. return { uri: uri, version: version };
  3358. }
  3359. VersionedTextDocumentIdentifier.create = create;
  3360. /**
  3361. * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
  3362. */
  3363. function is(value) {
  3364. var candidate = value;
  3365. return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
  3366. }
  3367. VersionedTextDocumentIdentifier.is = is;
  3368. })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
  3369. /**
  3370. * The TextDocumentItem namespace provides helper functions to work with
  3371. * [TextDocumentItem](#TextDocumentItem) literals.
  3372. */
  3373. var TextDocumentItem;
  3374. (function (TextDocumentItem) {
  3375. /**
  3376. * Creates a new TextDocumentItem literal.
  3377. * @param uri The document's uri.
  3378. * @param languageId The document's language identifier.
  3379. * @param version The document's version number.
  3380. * @param text The document's text.
  3381. */
  3382. function create(uri, languageId, version, text) {
  3383. return { uri: uri, languageId: languageId, version: version, text: text };
  3384. }
  3385. TextDocumentItem.create = create;
  3386. /**
  3387. * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
  3388. */
  3389. function is(value) {
  3390. var candidate = value;
  3391. return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
  3392. }
  3393. TextDocumentItem.is = is;
  3394. })(TextDocumentItem || (TextDocumentItem = {}));
  3395. /**
  3396. * Describes the content type that a client supports in various
  3397. * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
  3398. *
  3399. * Please note that `MarkupKinds` must not start with a `$`. This kinds
  3400. * are reserved for internal usage.
  3401. */
  3402. var MarkupKind;
  3403. (function (MarkupKind) {
  3404. /**
  3405. * Plain text is supported as a content format
  3406. */
  3407. MarkupKind.PlainText = 'plaintext';
  3408. /**
  3409. * Markdown is supported as a content format
  3410. */
  3411. MarkupKind.Markdown = 'markdown';
  3412. })(MarkupKind || (MarkupKind = {}));
  3413. (function (MarkupKind) {
  3414. /**
  3415. * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
  3416. */
  3417. function is(value) {
  3418. var candidate = value;
  3419. return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
  3420. }
  3421. MarkupKind.is = is;
  3422. })(MarkupKind || (MarkupKind = {}));
  3423. var MarkupContent;
  3424. (function (MarkupContent) {
  3425. /**
  3426. * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
  3427. */
  3428. function is(value) {
  3429. var candidate = value;
  3430. return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
  3431. }
  3432. MarkupContent.is = is;
  3433. })(MarkupContent || (MarkupContent = {}));
  3434. /**
  3435. * The kind of a completion entry.
  3436. */
  3437. var CompletionItemKind;
  3438. (function (CompletionItemKind) {
  3439. CompletionItemKind.Text = 1;
  3440. CompletionItemKind.Method = 2;
  3441. CompletionItemKind.Function = 3;
  3442. CompletionItemKind.Constructor = 4;
  3443. CompletionItemKind.Field = 5;
  3444. CompletionItemKind.Variable = 6;
  3445. CompletionItemKind.Class = 7;
  3446. CompletionItemKind.Interface = 8;
  3447. CompletionItemKind.Module = 9;
  3448. CompletionItemKind.Property = 10;
  3449. CompletionItemKind.Unit = 11;
  3450. CompletionItemKind.Value = 12;
  3451. CompletionItemKind.Enum = 13;
  3452. CompletionItemKind.Keyword = 14;
  3453. CompletionItemKind.Snippet = 15;
  3454. CompletionItemKind.Color = 16;
  3455. CompletionItemKind.File = 17;
  3456. CompletionItemKind.Reference = 18;
  3457. CompletionItemKind.Folder = 19;
  3458. CompletionItemKind.EnumMember = 20;
  3459. CompletionItemKind.Constant = 21;
  3460. CompletionItemKind.Struct = 22;
  3461. CompletionItemKind.Event = 23;
  3462. CompletionItemKind.Operator = 24;
  3463. CompletionItemKind.TypeParameter = 25;
  3464. })(CompletionItemKind || (CompletionItemKind = {}));
  3465. /**
  3466. * Defines whether the insert text in a completion item should be interpreted as
  3467. * plain text or a snippet.
  3468. */
  3469. var InsertTextFormat;
  3470. (function (InsertTextFormat) {
  3471. /**
  3472. * The primary text to be inserted is treated as a plain string.
  3473. */
  3474. InsertTextFormat.PlainText = 1;
  3475. /**
  3476. * The primary text to be inserted is treated as a snippet.
  3477. *
  3478. * A snippet can define tab stops and placeholders with `$1`, `$2`
  3479. * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
  3480. * the end of the snippet. Placeholders with equal identifiers are linked,
  3481. * that is typing in one will update others too.
  3482. *
  3483. * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
  3484. */
  3485. InsertTextFormat.Snippet = 2;
  3486. })(InsertTextFormat || (InsertTextFormat = {}));
  3487. /**
  3488. * The CompletionItem namespace provides functions to deal with
  3489. * completion items.
  3490. */
  3491. var CompletionItem;
  3492. (function (CompletionItem) {
  3493. /**
  3494. * Create a completion item and seed it with a label.
  3495. * @param label The completion item's label
  3496. */
  3497. function create(label) {
  3498. return { label: label };
  3499. }
  3500. CompletionItem.create = create;
  3501. })(CompletionItem || (CompletionItem = {}));
  3502. /**
  3503. * The CompletionList namespace provides functions to deal with
  3504. * completion lists.
  3505. */
  3506. var CompletionList;
  3507. (function (CompletionList) {
  3508. /**
  3509. * Creates a new completion list.
  3510. *
  3511. * @param items The completion items.
  3512. * @param isIncomplete The list is not complete.
  3513. */
  3514. function create(items, isIncomplete) {
  3515. return { items: items ? items : [], isIncomplete: !!isIncomplete };
  3516. }
  3517. CompletionList.create = create;
  3518. })(CompletionList || (CompletionList = {}));
  3519. var MarkedString;
  3520. (function (MarkedString) {
  3521. /**
  3522. * Creates a marked string from plain text.
  3523. *
  3524. * @param plainText The plain text.
  3525. */
  3526. function fromPlainText(plainText) {
  3527. return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
  3528. }
  3529. MarkedString.fromPlainText = fromPlainText;
  3530. /**
  3531. * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
  3532. */
  3533. function is(value) {
  3534. var candidate = value;
  3535. return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
  3536. }
  3537. MarkedString.is = is;
  3538. })(MarkedString || (MarkedString = {}));
  3539. var Hover;
  3540. (function (Hover) {
  3541. /**
  3542. * Checks whether the given value conforms to the [Hover](#Hover) interface.
  3543. */
  3544. function is(value) {
  3545. var candidate = value;
  3546. return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
  3547. MarkedString.is(candidate.contents) ||
  3548. Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
  3549. }
  3550. Hover.is = is;
  3551. })(Hover || (Hover = {}));
  3552. /**
  3553. * The ParameterInformation namespace provides helper functions to work with
  3554. * [ParameterInformation](#ParameterInformation) literals.
  3555. */
  3556. var ParameterInformation;
  3557. (function (ParameterInformation) {
  3558. /**
  3559. * Creates a new parameter information literal.
  3560. *
  3561. * @param label A label string.
  3562. * @param documentation A doc string.
  3563. */
  3564. function create(label, documentation) {
  3565. return documentation ? { label: label, documentation: documentation } : { label: label };
  3566. }
  3567. ParameterInformation.create = create;
  3568. ;
  3569. })(ParameterInformation || (ParameterInformation = {}));
  3570. /**
  3571. * The SignatureInformation namespace provides helper functions to work with
  3572. * [SignatureInformation](#SignatureInformation) literals.
  3573. */
  3574. var SignatureInformation;
  3575. (function (SignatureInformation) {
  3576. function create(label, documentation) {
  3577. var parameters = [];
  3578. for (var _i = 2; _i < arguments.length; _i++) {
  3579. parameters[_i - 2] = arguments[_i];
  3580. }
  3581. var result = { label: label };
  3582. if (Is.defined(documentation)) {
  3583. result.documentation = documentation;
  3584. }
  3585. if (Is.defined(parameters)) {
  3586. result.parameters = parameters;
  3587. }
  3588. else {
  3589. result.parameters = [];
  3590. }
  3591. return result;
  3592. }
  3593. SignatureInformation.create = create;
  3594. })(SignatureInformation || (SignatureInformation = {}));
  3595. /**
  3596. * A document highlight kind.
  3597. */
  3598. var DocumentHighlightKind;
  3599. (function (DocumentHighlightKind) {
  3600. /**
  3601. * A textual occurrence.
  3602. */
  3603. DocumentHighlightKind.Text = 1;
  3604. /**
  3605. * Read-access of a symbol, like reading a variable.
  3606. */
  3607. DocumentHighlightKind.Read = 2;
  3608. /**
  3609. * Write-access of a symbol, like writing to a variable.
  3610. */
  3611. DocumentHighlightKind.Write = 3;
  3612. })(DocumentHighlightKind || (DocumentHighlightKind = {}));
  3613. /**
  3614. * DocumentHighlight namespace to provide helper functions to work with
  3615. * [DocumentHighlight](#DocumentHighlight) literals.
  3616. */
  3617. var DocumentHighlight;
  3618. (function (DocumentHighlight) {
  3619. /**
  3620. * Create a DocumentHighlight object.
  3621. * @param range The range the highlight applies to.
  3622. */
  3623. function create(range, kind) {
  3624. var result = { range: range };
  3625. if (Is.number(kind)) {
  3626. result.kind = kind;
  3627. }
  3628. return result;
  3629. }
  3630. DocumentHighlight.create = create;
  3631. })(DocumentHighlight || (DocumentHighlight = {}));
  3632. /**
  3633. * A symbol kind.
  3634. */
  3635. var SymbolKind;
  3636. (function (SymbolKind) {
  3637. SymbolKind.File = 1;
  3638. SymbolKind.Module = 2;
  3639. SymbolKind.Namespace = 3;
  3640. SymbolKind.Package = 4;
  3641. SymbolKind.Class = 5;
  3642. SymbolKind.Method = 6;
  3643. SymbolKind.Property = 7;
  3644. SymbolKind.Field = 8;
  3645. SymbolKind.Constructor = 9;
  3646. SymbolKind.Enum = 10;
  3647. SymbolKind.Interface = 11;
  3648. SymbolKind.Function = 12;
  3649. SymbolKind.Variable = 13;
  3650. SymbolKind.Constant = 14;
  3651. SymbolKind.String = 15;
  3652. SymbolKind.Number = 16;
  3653. SymbolKind.Boolean = 17;
  3654. SymbolKind.Array = 18;
  3655. SymbolKind.Object = 19;
  3656. SymbolKind.Key = 20;
  3657. SymbolKind.Null = 21;
  3658. SymbolKind.EnumMember = 22;
  3659. SymbolKind.Struct = 23;
  3660. SymbolKind.Event = 24;
  3661. SymbolKind.Operator = 25;
  3662. SymbolKind.TypeParameter = 26;
  3663. })(SymbolKind || (SymbolKind = {}));
  3664. var SymbolInformation;
  3665. (function (SymbolInformation) {
  3666. /**
  3667. * Creates a new symbol information literal.
  3668. *
  3669. * @param name The name of the symbol.
  3670. * @param kind The kind of the symbol.
  3671. * @param range The range of the location of the symbol.
  3672. * @param uri The resource of the location of symbol, defaults to the current document.
  3673. * @param containerName The name of the symbol containing the symbol.
  3674. */
  3675. function create(name, kind, range, uri, containerName) {
  3676. var result = {
  3677. name: name,
  3678. kind: kind,
  3679. location: { uri: uri, range: range }
  3680. };
  3681. if (containerName) {
  3682. result.containerName = containerName;
  3683. }
  3684. return result;
  3685. }
  3686. SymbolInformation.create = create;
  3687. })(SymbolInformation || (SymbolInformation = {}));
  3688. /**
  3689. * Represents programming constructs like variables, classes, interfaces etc.
  3690. * that appear in a document. Document symbols can be hierarchical and they
  3691. * have two ranges: one that encloses its definition and one that points to
  3692. * its most interesting range, e.g. the range of an identifier.
  3693. */
  3694. var DocumentSymbol = /** @class */ (function () {
  3695. function DocumentSymbol() {
  3696. }
  3697. return DocumentSymbol;
  3698. }());
  3699. (function (DocumentSymbol) {
  3700. /**
  3701. * Creates a new symbol information literal.
  3702. *
  3703. * @param name The name of the symbol.
  3704. * @param detail The detail of the symbol.
  3705. * @param kind The kind of the symbol.
  3706. * @param range The range of the symbol.
  3707. * @param selectionRange The selectionRange of the symbol.
  3708. * @param children Children of the symbol.
  3709. */
  3710. function create(name, detail, kind, range, selectionRange, children) {
  3711. var result = {
  3712. name: name,
  3713. detail: detail,
  3714. kind: kind,
  3715. range: range,
  3716. selectionRange: selectionRange
  3717. };
  3718. if (children !== void 0) {
  3719. result.children = children;
  3720. }
  3721. return result;
  3722. }
  3723. DocumentSymbol.create = create;
  3724. /**
  3725. * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
  3726. */
  3727. function is(value) {
  3728. var candidate = value;
  3729. return candidate &&
  3730. Is.string(candidate.name) && Is.number(candidate.kind) &&
  3731. Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
  3732. (candidate.detail === void 0 || Is.string(candidate.detail)) &&
  3733. (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
  3734. (candidate.children === void 0 || Array.isArray(candidate.children));
  3735. }
  3736. DocumentSymbol.is = is;
  3737. })(DocumentSymbol || (DocumentSymbol = {}));
  3738. /**
  3739. * A set of predefined code action kinds
  3740. */
  3741. var CodeActionKind;
  3742. (function (CodeActionKind) {
  3743. /**
  3744. * Base kind for quickfix actions: 'quickfix'
  3745. */
  3746. CodeActionKind.QuickFix = 'quickfix';
  3747. /**
  3748. * Base kind for refactoring actions: 'refactor'
  3749. */
  3750. CodeActionKind.Refactor = 'refactor';
  3751. /**
  3752. * Base kind for refactoring extraction actions: 'refactor.extract'
  3753. *
  3754. * Example extract actions:
  3755. *
  3756. * - Extract method
  3757. * - Extract function
  3758. * - Extract variable
  3759. * - Extract interface from class
  3760. * - ...
  3761. */
  3762. CodeActionKind.RefactorExtract = 'refactor.extract';
  3763. /**
  3764. * Base kind for refactoring inline actions: 'refactor.inline'
  3765. *
  3766. * Example inline actions:
  3767. *
  3768. * - Inline function
  3769. * - Inline variable
  3770. * - Inline constant
  3771. * - ...
  3772. */
  3773. CodeActionKind.RefactorInline = 'refactor.inline';
  3774. /**
  3775. * Base kind for refactoring rewrite actions: 'refactor.rewrite'
  3776. *
  3777. * Example rewrite actions:
  3778. *
  3779. * - Convert JavaScript function to class
  3780. * - Add or remove parameter
  3781. * - Encapsulate field
  3782. * - Make method static
  3783. * - Move method to base class
  3784. * - ...
  3785. */
  3786. CodeActionKind.RefactorRewrite = 'refactor.rewrite';
  3787. /**
  3788. * Base kind for source actions: `source`
  3789. *
  3790. * Source code actions apply to the entire file.
  3791. */
  3792. CodeActionKind.Source = 'source';
  3793. /**
  3794. * Base kind for an organize imports source action: `source.organizeImports`
  3795. */
  3796. CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
  3797. })(CodeActionKind || (CodeActionKind = {}));
  3798. /**
  3799. * The CodeActionContext namespace provides helper functions to work with
  3800. * [CodeActionContext](#CodeActionContext) literals.
  3801. */
  3802. var CodeActionContext;
  3803. (function (CodeActionContext) {
  3804. /**
  3805. * Creates a new CodeActionContext literal.
  3806. */
  3807. function create(diagnostics, only) {
  3808. var result = { diagnostics: diagnostics };
  3809. if (only !== void 0 && only !== null) {
  3810. result.only = only;
  3811. }
  3812. return result;
  3813. }
  3814. CodeActionContext.create = create;
  3815. /**
  3816. * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
  3817. */
  3818. function is(value) {
  3819. var candidate = value;
  3820. return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
  3821. }
  3822. CodeActionContext.is = is;
  3823. })(CodeActionContext || (CodeActionContext = {}));
  3824. var CodeAction;
  3825. (function (CodeAction) {
  3826. function create(title, commandOrEdit, kind) {
  3827. var result = { title: title };
  3828. if (Command.is(commandOrEdit)) {
  3829. result.command = commandOrEdit;
  3830. }
  3831. else {
  3832. result.edit = commandOrEdit;
  3833. }
  3834. if (kind !== void null) {
  3835. result.kind = kind;
  3836. }
  3837. return result;
  3838. }
  3839. CodeAction.create = create;
  3840. function is(value) {
  3841. var candidate = value;
  3842. return candidate && Is.string(candidate.title) &&
  3843. (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
  3844. (candidate.kind === void 0 || Is.string(candidate.kind)) &&
  3845. (candidate.edit !== void 0 || candidate.command !== void 0) &&
  3846. (candidate.command === void 0 || Command.is(candidate.command)) &&
  3847. (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
  3848. }
  3849. CodeAction.is = is;
  3850. })(CodeAction || (CodeAction = {}));
  3851. /**
  3852. * The CodeLens namespace provides helper functions to work with
  3853. * [CodeLens](#CodeLens) literals.
  3854. */
  3855. var CodeLens;
  3856. (function (CodeLens) {
  3857. /**
  3858. * Creates a new CodeLens literal.
  3859. */
  3860. function create(range, data) {
  3861. var result = { range: range };
  3862. if (Is.defined(data))
  3863. result.data = data;
  3864. return result;
  3865. }
  3866. CodeLens.create = create;
  3867. /**
  3868. * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
  3869. */
  3870. function is(value) {
  3871. var candidate = value;
  3872. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
  3873. }
  3874. CodeLens.is = is;
  3875. })(CodeLens || (CodeLens = {}));
  3876. /**
  3877. * The FormattingOptions namespace provides helper functions to work with
  3878. * [FormattingOptions](#FormattingOptions) literals.
  3879. */
  3880. var FormattingOptions;
  3881. (function (FormattingOptions) {
  3882. /**
  3883. * Creates a new FormattingOptions literal.
  3884. */
  3885. function create(tabSize, insertSpaces) {
  3886. return { tabSize: tabSize, insertSpaces: insertSpaces };
  3887. }
  3888. FormattingOptions.create = create;
  3889. /**
  3890. * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
  3891. */
  3892. function is(value) {
  3893. var candidate = value;
  3894. return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
  3895. }
  3896. FormattingOptions.is = is;
  3897. })(FormattingOptions || (FormattingOptions = {}));
  3898. /**
  3899. * A document link is a range in a text document that links to an internal or external resource, like another
  3900. * text document or a web site.
  3901. */
  3902. var DocumentLink = /** @class */ (function () {
  3903. function DocumentLink() {
  3904. }
  3905. return DocumentLink;
  3906. }());
  3907. /**
  3908. * The DocumentLink namespace provides helper functions to work with
  3909. * [DocumentLink](#DocumentLink) literals.
  3910. */
  3911. (function (DocumentLink) {
  3912. /**
  3913. * Creates a new DocumentLink literal.
  3914. */
  3915. function create(range, target, data) {
  3916. return { range: range, target: target, data: data };
  3917. }
  3918. DocumentLink.create = create;
  3919. /**
  3920. * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
  3921. */
  3922. function is(value) {
  3923. var candidate = value;
  3924. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
  3925. }
  3926. DocumentLink.is = is;
  3927. })(DocumentLink || (DocumentLink = {}));
  3928. var EOL = ['\n', '\r\n', '\r'];
  3929. var TextDocument;
  3930. (function (TextDocument) {
  3931. /**
  3932. * Creates a new ITextDocument literal from the given uri and content.
  3933. * @param uri The document's uri.
  3934. * @param languageId The document's language Id.
  3935. * @param content The document's content.
  3936. */
  3937. function create(uri, languageId, version, content) {
  3938. return new FullTextDocument(uri, languageId, version, content);
  3939. }
  3940. TextDocument.create = create;
  3941. /**
  3942. * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
  3943. */
  3944. function is(value) {
  3945. var candidate = value;
  3946. return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
  3947. && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
  3948. }
  3949. TextDocument.is = is;
  3950. function applyEdits(document, edits) {
  3951. var text = document.getText();
  3952. var sortedEdits = mergeSort(edits, function (a, b) {
  3953. var diff = a.range.start.line - b.range.start.line;
  3954. if (diff === 0) {
  3955. return a.range.start.character - b.range.start.character;
  3956. }
  3957. return diff;
  3958. });
  3959. var lastModifiedOffset = text.length;
  3960. for (var i = sortedEdits.length - 1; i >= 0; i--) {
  3961. var e = sortedEdits[i];
  3962. var startOffset = document.offsetAt(e.range.start);
  3963. var endOffset = document.offsetAt(e.range.end);
  3964. if (endOffset <= lastModifiedOffset) {
  3965. text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
  3966. }
  3967. else {
  3968. throw new Error('Overlapping edit');
  3969. }
  3970. lastModifiedOffset = startOffset;
  3971. }
  3972. return text;
  3973. }
  3974. TextDocument.applyEdits = applyEdits;
  3975. function mergeSort(data, compare) {
  3976. if (data.length <= 1) {
  3977. // sorted
  3978. return data;
  3979. }
  3980. var p = (data.length / 2) | 0;
  3981. var left = data.slice(0, p);
  3982. var right = data.slice(p);
  3983. mergeSort(left, compare);
  3984. mergeSort(right, compare);
  3985. var leftIdx = 0;
  3986. var rightIdx = 0;
  3987. var i = 0;
  3988. while (leftIdx < left.length && rightIdx < right.length) {
  3989. var ret = compare(left[leftIdx], right[rightIdx]);
  3990. if (ret <= 0) {
  3991. // smaller_equal -> take left to preserve order
  3992. data[i++] = left[leftIdx++];
  3993. }
  3994. else {
  3995. // greater -> take right
  3996. data[i++] = right[rightIdx++];
  3997. }
  3998. }
  3999. while (leftIdx < left.length) {
  4000. data[i++] = left[leftIdx++];
  4001. }
  4002. while (rightIdx < right.length) {
  4003. data[i++] = right[rightIdx++];
  4004. }
  4005. return data;
  4006. }
  4007. })(TextDocument || (TextDocument = {}));
  4008. /**
  4009. * Represents reasons why a text document is saved.
  4010. */
  4011. var TextDocumentSaveReason;
  4012. (function (TextDocumentSaveReason) {
  4013. /**
  4014. * Manually triggered, e.g. by the user pressing save, by starting debugging,
  4015. * or by an API call.
  4016. */
  4017. TextDocumentSaveReason.Manual = 1;
  4018. /**
  4019. * Automatic after a delay.
  4020. */
  4021. TextDocumentSaveReason.AfterDelay = 2;
  4022. /**
  4023. * When the editor lost focus.
  4024. */
  4025. TextDocumentSaveReason.FocusOut = 3;
  4026. })(TextDocumentSaveReason || (TextDocumentSaveReason = {}));
  4027. var FullTextDocument = /** @class */ (function () {
  4028. function FullTextDocument(uri, languageId, version, content) {
  4029. this._uri = uri;
  4030. this._languageId = languageId;
  4031. this._version = version;
  4032. this._content = content;
  4033. this._lineOffsets = null;
  4034. }
  4035. Object.defineProperty(FullTextDocument.prototype, "uri", {
  4036. get: function () {
  4037. return this._uri;
  4038. },
  4039. enumerable: true,
  4040. configurable: true
  4041. });
  4042. Object.defineProperty(FullTextDocument.prototype, "languageId", {
  4043. get: function () {
  4044. return this._languageId;
  4045. },
  4046. enumerable: true,
  4047. configurable: true
  4048. });
  4049. Object.defineProperty(FullTextDocument.prototype, "version", {
  4050. get: function () {
  4051. return this._version;
  4052. },
  4053. enumerable: true,
  4054. configurable: true
  4055. });
  4056. FullTextDocument.prototype.getText = function (range) {
  4057. if (range) {
  4058. var start = this.offsetAt(range.start);
  4059. var end = this.offsetAt(range.end);
  4060. return this._content.substring(start, end);
  4061. }
  4062. return this._content;
  4063. };
  4064. FullTextDocument.prototype.update = function (event, version) {
  4065. this._content = event.text;
  4066. this._version = version;
  4067. this._lineOffsets = null;
  4068. };
  4069. FullTextDocument.prototype.getLineOffsets = function () {
  4070. if (this._lineOffsets === null) {
  4071. var lineOffsets = [];
  4072. var text = this._content;
  4073. var isLineStart = true;
  4074. for (var i = 0; i < text.length; i++) {
  4075. if (isLineStart) {
  4076. lineOffsets.push(i);
  4077. isLineStart = false;
  4078. }
  4079. var ch = text.charAt(i);
  4080. isLineStart = (ch === '\r' || ch === '\n');
  4081. if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
  4082. i++;
  4083. }
  4084. }
  4085. if (isLineStart && text.length > 0) {
  4086. lineOffsets.push(text.length);
  4087. }
  4088. this._lineOffsets = lineOffsets;
  4089. }
  4090. return this._lineOffsets;
  4091. };
  4092. FullTextDocument.prototype.positionAt = function (offset) {
  4093. offset = Math.max(Math.min(offset, this._content.length), 0);
  4094. var lineOffsets = this.getLineOffsets();
  4095. var low = 0, high = lineOffsets.length;
  4096. if (high === 0) {
  4097. return Position.create(0, offset);
  4098. }
  4099. while (low < high) {
  4100. var mid = Math.floor((low + high) / 2);
  4101. if (lineOffsets[mid] > offset) {
  4102. high = mid;
  4103. }
  4104. else {
  4105. low = mid + 1;
  4106. }
  4107. }
  4108. // low is the least x for which the line offset is larger than the current offset
  4109. // or array.length if no line offset is larger than the current offset
  4110. var line = low - 1;
  4111. return Position.create(line, offset - lineOffsets[line]);
  4112. };
  4113. FullTextDocument.prototype.offsetAt = function (position) {
  4114. var lineOffsets = this.getLineOffsets();
  4115. if (position.line >= lineOffsets.length) {
  4116. return this._content.length;
  4117. }
  4118. else if (position.line < 0) {
  4119. return 0;
  4120. }
  4121. var lineOffset = lineOffsets[position.line];
  4122. var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
  4123. return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
  4124. };
  4125. Object.defineProperty(FullTextDocument.prototype, "lineCount", {
  4126. get: function () {
  4127. return this.getLineOffsets().length;
  4128. },
  4129. enumerable: true,
  4130. configurable: true
  4131. });
  4132. return FullTextDocument;
  4133. }());
  4134. var Is;
  4135. (function (Is) {
  4136. var toString = Object.prototype.toString;
  4137. function defined(value) {
  4138. return typeof value !== 'undefined';
  4139. }
  4140. Is.defined = defined;
  4141. function undefined(value) {
  4142. return typeof value === 'undefined';
  4143. }
  4144. Is.undefined = undefined;
  4145. function boolean(value) {
  4146. return value === true || value === false;
  4147. }
  4148. Is.boolean = boolean;
  4149. function string(value) {
  4150. return toString.call(value) === '[object String]';
  4151. }
  4152. Is.string = string;
  4153. function number(value) {
  4154. return toString.call(value) === '[object Number]';
  4155. }
  4156. Is.number = number;
  4157. function func(value) {
  4158. return toString.call(value) === '[object Function]';
  4159. }
  4160. Is.func = func;
  4161. function objectLiteral(value) {
  4162. // Strictly speaking class instances pass this check as well. Since the LSP
  4163. // doesn't use classes we ignore this for now. If we do we need to add something
  4164. // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
  4165. return value !== null && typeof value === 'object';
  4166. }
  4167. Is.objectLiteral = objectLiteral;
  4168. function typedArray(value, check) {
  4169. return Array.isArray(value) && value.every(check);
  4170. }
  4171. Is.typedArray = typedArray;
  4172. })(Is || (Is = {}));
  4173. /***/ }),
  4174. /* 19 */
  4175. /***/ (function(module, exports, __webpack_require__) {
  4176. "use strict";
  4177. /* --------------------------------------------------------------------------------------------
  4178. * Copyright (c) Microsoft Corporation. All rights reserved.
  4179. * Licensed under the MIT License. See License.txt in the project root for license information.
  4180. * ------------------------------------------------------------------------------------------ */
  4181. Object.defineProperty(exports, "__esModule", { value: true });
  4182. const Is = __webpack_require__(20);
  4183. const vscode_jsonrpc_1 = __webpack_require__(4);
  4184. const protocol_implementation_1 = __webpack_require__(21);
  4185. exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
  4186. const protocol_typeDefinition_1 = __webpack_require__(22);
  4187. exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
  4188. const protocol_workspaceFolders_1 = __webpack_require__(23);
  4189. exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
  4190. exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
  4191. const protocol_configuration_1 = __webpack_require__(24);
  4192. exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
  4193. const protocol_colorProvider_1 = __webpack_require__(25);
  4194. exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
  4195. exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
  4196. const protocol_foldingRange_1 = __webpack_require__(26);
  4197. exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
  4198. const protocol_declaration_1 = __webpack_require__(27);
  4199. exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
  4200. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  4201. let __noDynamicImport;
  4202. var DocumentFilter;
  4203. (function (DocumentFilter) {
  4204. function is(value) {
  4205. let candidate = value;
  4206. return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
  4207. }
  4208. DocumentFilter.is = is;
  4209. })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));
  4210. /**
  4211. * The `client/registerCapability` request is sent from the server to the client to register a new capability
  4212. * handler on the client side.
  4213. */
  4214. var RegistrationRequest;
  4215. (function (RegistrationRequest) {
  4216. RegistrationRequest.type = new vscode_jsonrpc_1.RequestType('client/registerCapability');
  4217. })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
  4218. /**
  4219. * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
  4220. * handler on the client side.
  4221. */
  4222. var UnregistrationRequest;
  4223. (function (UnregistrationRequest) {
  4224. UnregistrationRequest.type = new vscode_jsonrpc_1.RequestType('client/unregisterCapability');
  4225. })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
  4226. var ResourceOperationKind;
  4227. (function (ResourceOperationKind) {
  4228. /**
  4229. * Supports creating new files and folders.
  4230. */
  4231. ResourceOperationKind.Create = 'create';
  4232. /**
  4233. * Supports renaming existing files and folders.
  4234. */
  4235. ResourceOperationKind.Rename = 'rename';
  4236. /**
  4237. * Supports deleting existing files and folders.
  4238. */
  4239. ResourceOperationKind.Delete = 'delete';
  4240. })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
  4241. var FailureHandlingKind;
  4242. (function (FailureHandlingKind) {
  4243. /**
  4244. * Applying the workspace change is simply aborted if one of the changes provided
  4245. * fails. All operations executed before the failing operation stay executed.
  4246. */
  4247. FailureHandlingKind.Abort = 'abort';
  4248. /**
  4249. * All operations are executed transactional. That means they either all
  4250. * succeed or no changes at all are applied to the workspace.
  4251. */
  4252. FailureHandlingKind.Transactional = 'transactional';
  4253. /**
  4254. * If the workspace edit contains only textual file changes they are executed transactional.
  4255. * If resource changes (create, rename or delete file) are part of the change the failure
  4256. * handling startegy is abort.
  4257. */
  4258. FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
  4259. /**
  4260. * The client tries to undo the operations already executed. But there is no
  4261. * guaruntee that this is succeeding.
  4262. */
  4263. FailureHandlingKind.Undo = 'undo';
  4264. })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
  4265. /**
  4266. * Defines how the host (editor) should sync
  4267. * document changes to the language server.
  4268. */
  4269. var TextDocumentSyncKind;
  4270. (function (TextDocumentSyncKind) {
  4271. /**
  4272. * Documents should not be synced at all.
  4273. */
  4274. TextDocumentSyncKind.None = 0;
  4275. /**
  4276. * Documents are synced by always sending the full content
  4277. * of the document.
  4278. */
  4279. TextDocumentSyncKind.Full = 1;
  4280. /**
  4281. * Documents are synced by sending the full content on open.
  4282. * After that only incremental updates to the document are
  4283. * send.
  4284. */
  4285. TextDocumentSyncKind.Incremental = 2;
  4286. })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
  4287. /**
  4288. * The initialize request is sent from the client to the server.
  4289. * It is sent once as the request after starting up the server.
  4290. * The requests parameter is of type [InitializeParams](#InitializeParams)
  4291. * the response if of type [InitializeResult](#InitializeResult) of a Thenable that
  4292. * resolves to such.
  4293. */
  4294. var InitializeRequest;
  4295. (function (InitializeRequest) {
  4296. InitializeRequest.type = new vscode_jsonrpc_1.RequestType('initialize');
  4297. })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
  4298. /**
  4299. * Known error codes for an `InitializeError`;
  4300. */
  4301. var InitializeError;
  4302. (function (InitializeError) {
  4303. /**
  4304. * If the protocol version provided by the client can't be handled by the server.
  4305. * @deprecated This initialize error got replaced by client capabilities. There is
  4306. * no version handshake in version 3.0x
  4307. */
  4308. InitializeError.unknownProtocolVersion = 1;
  4309. })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));
  4310. /**
  4311. * The intialized notification is sent from the client to the
  4312. * server after the client is fully initialized and the server
  4313. * is allowed to send requests from the server to the client.
  4314. */
  4315. var InitializedNotification;
  4316. (function (InitializedNotification) {
  4317. InitializedNotification.type = new vscode_jsonrpc_1.NotificationType('initialized');
  4318. })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
  4319. //---- Shutdown Method ----
  4320. /**
  4321. * A shutdown request is sent from the client to the server.
  4322. * It is sent once when the client decides to shutdown the
  4323. * server. The only notification that is sent after a shutdown request
  4324. * is the exit event.
  4325. */
  4326. var ShutdownRequest;
  4327. (function (ShutdownRequest) {
  4328. ShutdownRequest.type = new vscode_jsonrpc_1.RequestType0('shutdown');
  4329. })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
  4330. //---- Exit Notification ----
  4331. /**
  4332. * The exit event is sent from the client to the server to
  4333. * ask the server to exit its process.
  4334. */
  4335. var ExitNotification;
  4336. (function (ExitNotification) {
  4337. ExitNotification.type = new vscode_jsonrpc_1.NotificationType0('exit');
  4338. })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
  4339. //---- Configuration notification ----
  4340. /**
  4341. * The configuration change notification is sent from the client to the server
  4342. * when the client's configuration has changed. The notification contains
  4343. * the changed configuration as defined by the language client.
  4344. */
  4345. var DidChangeConfigurationNotification;
  4346. (function (DidChangeConfigurationNotification) {
  4347. DidChangeConfigurationNotification.type = new vscode_jsonrpc_1.NotificationType('workspace/didChangeConfiguration');
  4348. })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
  4349. //---- Message show and log notifications ----
  4350. /**
  4351. * The message type
  4352. */
  4353. var MessageType;
  4354. (function (MessageType) {
  4355. /**
  4356. * An error message.
  4357. */
  4358. MessageType.Error = 1;
  4359. /**
  4360. * A warning message.
  4361. */
  4362. MessageType.Warning = 2;
  4363. /**
  4364. * An information message.
  4365. */
  4366. MessageType.Info = 3;
  4367. /**
  4368. * A log message.
  4369. */
  4370. MessageType.Log = 4;
  4371. })(MessageType = exports.MessageType || (exports.MessageType = {}));
  4372. /**
  4373. * The show message notification is sent from a server to a client to ask
  4374. * the client to display a particular message in the user interface.
  4375. */
  4376. var ShowMessageNotification;
  4377. (function (ShowMessageNotification) {
  4378. ShowMessageNotification.type = new vscode_jsonrpc_1.NotificationType('window/showMessage');
  4379. })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
  4380. /**
  4381. * The show message request is sent from the server to the client to show a message
  4382. * and a set of options actions to the user.
  4383. */
  4384. var ShowMessageRequest;
  4385. (function (ShowMessageRequest) {
  4386. ShowMessageRequest.type = new vscode_jsonrpc_1.RequestType('window/showMessageRequest');
  4387. })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
  4388. /**
  4389. * The log message notification is sent from the server to the client to ask
  4390. * the client to log a particular message.
  4391. */
  4392. var LogMessageNotification;
  4393. (function (LogMessageNotification) {
  4394. LogMessageNotification.type = new vscode_jsonrpc_1.NotificationType('window/logMessage');
  4395. })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
  4396. //---- Telemetry notification
  4397. /**
  4398. * The telemetry event notification is sent from the server to the client to ask
  4399. * the client to log telemetry data.
  4400. */
  4401. var TelemetryEventNotification;
  4402. (function (TelemetryEventNotification) {
  4403. TelemetryEventNotification.type = new vscode_jsonrpc_1.NotificationType('telemetry/event');
  4404. })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
  4405. /**
  4406. * The document open notification is sent from the client to the server to signal
  4407. * newly opened text documents. The document's truth is now managed by the client
  4408. * and the server must not try to read the document's truth using the document's
  4409. * uri. Open in this sense means it is managed by the client. It doesn't necessarily
  4410. * mean that its content is presented in an editor. An open notification must not
  4411. * be sent more than once without a corresponding close notification send before.
  4412. * This means open and close notification must be balanced and the max open count
  4413. * is one.
  4414. */
  4415. var DidOpenTextDocumentNotification;
  4416. (function (DidOpenTextDocumentNotification) {
  4417. DidOpenTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/didOpen');
  4418. })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
  4419. /**
  4420. * The document change notification is sent from the client to the server to signal
  4421. * changes to a text document.
  4422. */
  4423. var DidChangeTextDocumentNotification;
  4424. (function (DidChangeTextDocumentNotification) {
  4425. DidChangeTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/didChange');
  4426. })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
  4427. /**
  4428. * The document close notification is sent from the client to the server when
  4429. * the document got closed in the client. The document's truth now exists where
  4430. * the document's uri points to (e.g. if the document's uri is a file uri the
  4431. * truth now exists on disk). As with the open notification the close notification
  4432. * is about managing the document's content. Receiving a close notification
  4433. * doesn't mean that the document was open in an editor before. A close
  4434. * notification requires a previous open notification to be sent.
  4435. */
  4436. var DidCloseTextDocumentNotification;
  4437. (function (DidCloseTextDocumentNotification) {
  4438. DidCloseTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/didClose');
  4439. })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
  4440. /**
  4441. * The document save notification is sent from the client to the server when
  4442. * the document got saved in the client.
  4443. */
  4444. var DidSaveTextDocumentNotification;
  4445. (function (DidSaveTextDocumentNotification) {
  4446. DidSaveTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/didSave');
  4447. })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
  4448. /**
  4449. * A document will save notification is sent from the client to the server before
  4450. * the document is actually saved.
  4451. */
  4452. var WillSaveTextDocumentNotification;
  4453. (function (WillSaveTextDocumentNotification) {
  4454. WillSaveTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/willSave');
  4455. })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
  4456. /**
  4457. * A document will save request is sent from the client to the server before
  4458. * the document is actually saved. The request can return an array of TextEdits
  4459. * which will be applied to the text document before it is saved. Please note that
  4460. * clients might drop results if computing the text edits took too long or if a
  4461. * server constantly fails on this request. This is done to keep the save fast and
  4462. * reliable.
  4463. */
  4464. var WillSaveTextDocumentWaitUntilRequest;
  4465. (function (WillSaveTextDocumentWaitUntilRequest) {
  4466. WillSaveTextDocumentWaitUntilRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/willSaveWaitUntil');
  4467. })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
  4468. //---- File eventing ----
  4469. /**
  4470. * The watched files notification is sent from the client to the server when
  4471. * the client detects changes to file watched by the language client.
  4472. */
  4473. var DidChangeWatchedFilesNotification;
  4474. (function (DidChangeWatchedFilesNotification) {
  4475. DidChangeWatchedFilesNotification.type = new vscode_jsonrpc_1.NotificationType('workspace/didChangeWatchedFiles');
  4476. })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
  4477. /**
  4478. * The file event type
  4479. */
  4480. var FileChangeType;
  4481. (function (FileChangeType) {
  4482. /**
  4483. * The file got created.
  4484. */
  4485. FileChangeType.Created = 1;
  4486. /**
  4487. * The file got changed.
  4488. */
  4489. FileChangeType.Changed = 2;
  4490. /**
  4491. * The file got deleted.
  4492. */
  4493. FileChangeType.Deleted = 3;
  4494. })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
  4495. var WatchKind;
  4496. (function (WatchKind) {
  4497. /**
  4498. * Interested in create events.
  4499. */
  4500. WatchKind.Create = 1;
  4501. /**
  4502. * Interested in change events
  4503. */
  4504. WatchKind.Change = 2;
  4505. /**
  4506. * Interested in delete events
  4507. */
  4508. WatchKind.Delete = 4;
  4509. })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
  4510. //---- Diagnostic notification ----
  4511. /**
  4512. * Diagnostics notification are sent from the server to the client to signal
  4513. * results of validation runs.
  4514. */
  4515. var PublishDiagnosticsNotification;
  4516. (function (PublishDiagnosticsNotification) {
  4517. PublishDiagnosticsNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/publishDiagnostics');
  4518. })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
  4519. /**
  4520. * How a completion was triggered
  4521. */
  4522. var CompletionTriggerKind;
  4523. (function (CompletionTriggerKind) {
  4524. /**
  4525. * Completion was triggered by typing an identifier (24x7 code
  4526. * complete), manual invocation (e.g Ctrl+Space) or via API.
  4527. */
  4528. CompletionTriggerKind.Invoked = 1;
  4529. /**
  4530. * Completion was triggered by a trigger character specified by
  4531. * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
  4532. */
  4533. CompletionTriggerKind.TriggerCharacter = 2;
  4534. /**
  4535. * Completion was re-triggered as current completion list is incomplete
  4536. */
  4537. CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
  4538. })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
  4539. /**
  4540. * Request to request completion at a given text document position. The request's
  4541. * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response
  4542. * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)
  4543. * or a Thenable that resolves to such.
  4544. *
  4545. * The request can delay the computation of the [`detail`](#CompletionItem.detail)
  4546. * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`
  4547. * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
  4548. * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
  4549. */
  4550. var CompletionRequest;
  4551. (function (CompletionRequest) {
  4552. CompletionRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/completion');
  4553. })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
  4554. /**
  4555. * Request to resolve additional information for a given completion item.The request's
  4556. * parameter is of type [CompletionItem](#CompletionItem) the response
  4557. * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.
  4558. */
  4559. var CompletionResolveRequest;
  4560. (function (CompletionResolveRequest) {
  4561. CompletionResolveRequest.type = new vscode_jsonrpc_1.RequestType('completionItem/resolve');
  4562. })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
  4563. //---- Hover Support -------------------------------
  4564. /**
  4565. * Request to request hover information at a given text document position. The request's
  4566. * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of
  4567. * type [Hover](#Hover) or a Thenable that resolves to such.
  4568. */
  4569. var HoverRequest;
  4570. (function (HoverRequest) {
  4571. HoverRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/hover');
  4572. })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
  4573. var SignatureHelpRequest;
  4574. (function (SignatureHelpRequest) {
  4575. SignatureHelpRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/signatureHelp');
  4576. })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
  4577. //---- Goto Definition -------------------------------------
  4578. /**
  4579. * A request to resolve the definition location of a symbol at a given text
  4580. * document position. The request's parameter is of type [TextDocumentPosition]
  4581. * (#TextDocumentPosition) the response is of either type [Definition](#Definition)
  4582. * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves
  4583. * to such.
  4584. */
  4585. var DefinitionRequest;
  4586. (function (DefinitionRequest) {
  4587. DefinitionRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/definition');
  4588. })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
  4589. /**
  4590. * A request to resolve project-wide references for the symbol denoted
  4591. * by the given text document position. The request's parameter is of
  4592. * type [ReferenceParams](#ReferenceParams) the response is of type
  4593. * [Location[]](#Location) or a Thenable that resolves to such.
  4594. */
  4595. var ReferencesRequest;
  4596. (function (ReferencesRequest) {
  4597. ReferencesRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/references');
  4598. })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
  4599. //---- Document Highlight ----------------------------------
  4600. /**
  4601. * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given
  4602. * text document position. The request's parameter is of type [TextDocumentPosition]
  4603. * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
  4604. * (#DocumentHighlight) or a Thenable that resolves to such.
  4605. */
  4606. var DocumentHighlightRequest;
  4607. (function (DocumentHighlightRequest) {
  4608. DocumentHighlightRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/documentHighlight');
  4609. })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
  4610. //---- Document Symbol Provider ---------------------------
  4611. /**
  4612. * A request to list all symbols found in a given text document. The request's
  4613. * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the
  4614. * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable
  4615. * that resolves to such.
  4616. */
  4617. var DocumentSymbolRequest;
  4618. (function (DocumentSymbolRequest) {
  4619. DocumentSymbolRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/documentSymbol');
  4620. })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
  4621. //---- Workspace Symbol Provider ---------------------------
  4622. /**
  4623. * A request to list project-wide symbols matching the query string given
  4624. * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is
  4625. * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that
  4626. * resolves to such.
  4627. */
  4628. var WorkspaceSymbolRequest;
  4629. (function (WorkspaceSymbolRequest) {
  4630. WorkspaceSymbolRequest.type = new vscode_jsonrpc_1.RequestType('workspace/symbol');
  4631. })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
  4632. /**
  4633. * A request to provide commands for the given text document and range.
  4634. */
  4635. var CodeActionRequest;
  4636. (function (CodeActionRequest) {
  4637. CodeActionRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/codeAction');
  4638. })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
  4639. /**
  4640. * A request to provide code lens for the given text document.
  4641. */
  4642. var CodeLensRequest;
  4643. (function (CodeLensRequest) {
  4644. CodeLensRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/codeLens');
  4645. })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
  4646. /**
  4647. * A request to resolve a command for a given code lens.
  4648. */
  4649. var CodeLensResolveRequest;
  4650. (function (CodeLensResolveRequest) {
  4651. CodeLensResolveRequest.type = new vscode_jsonrpc_1.RequestType('codeLens/resolve');
  4652. })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
  4653. /**
  4654. * A request to to format a whole document.
  4655. */
  4656. var DocumentFormattingRequest;
  4657. (function (DocumentFormattingRequest) {
  4658. DocumentFormattingRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/formatting');
  4659. })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
  4660. /**
  4661. * A request to to format a range in a document.
  4662. */
  4663. var DocumentRangeFormattingRequest;
  4664. (function (DocumentRangeFormattingRequest) {
  4665. DocumentRangeFormattingRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/rangeFormatting');
  4666. })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
  4667. /**
  4668. * A request to format a document on type.
  4669. */
  4670. var DocumentOnTypeFormattingRequest;
  4671. (function (DocumentOnTypeFormattingRequest) {
  4672. DocumentOnTypeFormattingRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/onTypeFormatting');
  4673. })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
  4674. /**
  4675. * A request to rename a symbol.
  4676. */
  4677. var RenameRequest;
  4678. (function (RenameRequest) {
  4679. RenameRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/rename');
  4680. })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
  4681. /**
  4682. * A request to test and perform the setup necessary for a rename.
  4683. */
  4684. var PrepareRenameRequest;
  4685. (function (PrepareRenameRequest) {
  4686. PrepareRenameRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/prepareRename');
  4687. })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
  4688. /**
  4689. * A request to provide document links
  4690. */
  4691. var DocumentLinkRequest;
  4692. (function (DocumentLinkRequest) {
  4693. DocumentLinkRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/documentLink');
  4694. })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
  4695. /**
  4696. * Request to resolve additional information for a given document link. The request's
  4697. * parameter is of type [DocumentLink](#DocumentLink) the response
  4698. * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.
  4699. */
  4700. var DocumentLinkResolveRequest;
  4701. (function (DocumentLinkResolveRequest) {
  4702. DocumentLinkResolveRequest.type = new vscode_jsonrpc_1.RequestType('documentLink/resolve');
  4703. })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
  4704. /**
  4705. * A request send from the client to the server to execute a command. The request might return
  4706. * a workspace edit which the client will apply to the workspace.
  4707. */
  4708. var ExecuteCommandRequest;
  4709. (function (ExecuteCommandRequest) {
  4710. ExecuteCommandRequest.type = new vscode_jsonrpc_1.RequestType('workspace/executeCommand');
  4711. })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
  4712. /**
  4713. * A request sent from the server to the client to modified certain resources.
  4714. */
  4715. var ApplyWorkspaceEditRequest;
  4716. (function (ApplyWorkspaceEditRequest) {
  4717. ApplyWorkspaceEditRequest.type = new vscode_jsonrpc_1.RequestType('workspace/applyEdit');
  4718. })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
  4719. /***/ }),
  4720. /* 20 */
  4721. /***/ (function(module, exports, __webpack_require__) {
  4722. "use strict";
  4723. /* --------------------------------------------------------------------------------------------
  4724. * Copyright (c) Microsoft Corporation. All rights reserved.
  4725. * Licensed under the MIT License. See License.txt in the project root for license information.
  4726. * ------------------------------------------------------------------------------------------ */
  4727. Object.defineProperty(exports, "__esModule", { value: true });
  4728. function boolean(value) {
  4729. return value === true || value === false;
  4730. }
  4731. exports.boolean = boolean;
  4732. function string(value) {
  4733. return typeof value === 'string' || value instanceof String;
  4734. }
  4735. exports.string = string;
  4736. function number(value) {
  4737. return typeof value === 'number' || value instanceof Number;
  4738. }
  4739. exports.number = number;
  4740. function error(value) {
  4741. return value instanceof Error;
  4742. }
  4743. exports.error = error;
  4744. function func(value) {
  4745. return typeof value === 'function';
  4746. }
  4747. exports.func = func;
  4748. function array(value) {
  4749. return Array.isArray(value);
  4750. }
  4751. exports.array = array;
  4752. function stringArray(value) {
  4753. return array(value) && value.every(elem => string(elem));
  4754. }
  4755. exports.stringArray = stringArray;
  4756. function typedArray(value, check) {
  4757. return Array.isArray(value) && value.every(check);
  4758. }
  4759. exports.typedArray = typedArray;
  4760. function thenable(value) {
  4761. return value && func(value.then);
  4762. }
  4763. exports.thenable = thenable;
  4764. /***/ }),
  4765. /* 21 */
  4766. /***/ (function(module, exports, __webpack_require__) {
  4767. "use strict";
  4768. /* --------------------------------------------------------------------------------------------
  4769. * Copyright (c) Microsoft Corporation. All rights reserved.
  4770. * Licensed under the MIT License. See License.txt in the project root for license information.
  4771. * ------------------------------------------------------------------------------------------ */
  4772. Object.defineProperty(exports, "__esModule", { value: true });
  4773. const vscode_jsonrpc_1 = __webpack_require__(4);
  4774. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  4775. let __noDynamicImport;
  4776. /**
  4777. * A request to resolve the implementation locations of a symbol at a given text
  4778. * document position. The request's parameter is of type [TextDocumentPositioParams]
  4779. * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
  4780. * Thenable that resolves to such.
  4781. */
  4782. var ImplementationRequest;
  4783. (function (ImplementationRequest) {
  4784. ImplementationRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/implementation');
  4785. })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
  4786. /***/ }),
  4787. /* 22 */
  4788. /***/ (function(module, exports, __webpack_require__) {
  4789. "use strict";
  4790. /* --------------------------------------------------------------------------------------------
  4791. * Copyright (c) Microsoft Corporation. All rights reserved.
  4792. * Licensed under the MIT License. See License.txt in the project root for license information.
  4793. * ------------------------------------------------------------------------------------------ */
  4794. Object.defineProperty(exports, "__esModule", { value: true });
  4795. const vscode_jsonrpc_1 = __webpack_require__(4);
  4796. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  4797. let __noDynamicImport;
  4798. /**
  4799. * A request to resolve the type definition locations of a symbol at a given text
  4800. * document position. The request's parameter is of type [TextDocumentPositioParams]
  4801. * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
  4802. * Thenable that resolves to such.
  4803. */
  4804. var TypeDefinitionRequest;
  4805. (function (TypeDefinitionRequest) {
  4806. TypeDefinitionRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/typeDefinition');
  4807. })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
  4808. /***/ }),
  4809. /* 23 */
  4810. /***/ (function(module, exports, __webpack_require__) {
  4811. "use strict";
  4812. /* --------------------------------------------------------------------------------------------
  4813. * Copyright (c) Microsoft Corporation. All rights reserved.
  4814. * Licensed under the MIT License. See License.txt in the project root for license information.
  4815. * ------------------------------------------------------------------------------------------ */
  4816. Object.defineProperty(exports, "__esModule", { value: true });
  4817. const vscode_jsonrpc_1 = __webpack_require__(4);
  4818. /**
  4819. * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
  4820. */
  4821. var WorkspaceFoldersRequest;
  4822. (function (WorkspaceFoldersRequest) {
  4823. WorkspaceFoldersRequest.type = new vscode_jsonrpc_1.RequestType0('workspace/workspaceFolders');
  4824. })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
  4825. /**
  4826. * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
  4827. * folder configuration changes.
  4828. */
  4829. var DidChangeWorkspaceFoldersNotification;
  4830. (function (DidChangeWorkspaceFoldersNotification) {
  4831. DidChangeWorkspaceFoldersNotification.type = new vscode_jsonrpc_1.NotificationType('workspace/didChangeWorkspaceFolders');
  4832. })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
  4833. /***/ }),
  4834. /* 24 */
  4835. /***/ (function(module, exports, __webpack_require__) {
  4836. "use strict";
  4837. /* --------------------------------------------------------------------------------------------
  4838. * Copyright (c) Microsoft Corporation. All rights reserved.
  4839. * Licensed under the MIT License. See License.txt in the project root for license information.
  4840. * ------------------------------------------------------------------------------------------ */
  4841. Object.defineProperty(exports, "__esModule", { value: true });
  4842. const vscode_jsonrpc_1 = __webpack_require__(4);
  4843. /**
  4844. * The 'workspace/configuration' request is sent from the server to the client to fetch a certain
  4845. * configuration setting.
  4846. *
  4847. * This pull model replaces the old push model were the client signaled configuration change via an
  4848. * event. If the server still needs to react to configuration changes (since the server caches the
  4849. * result of `workspace/configuration` requests) the server should register for an empty configuration
  4850. * change event and empty the cache if such an event is received.
  4851. */
  4852. var ConfigurationRequest;
  4853. (function (ConfigurationRequest) {
  4854. ConfigurationRequest.type = new vscode_jsonrpc_1.RequestType('workspace/configuration');
  4855. })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
  4856. /***/ }),
  4857. /* 25 */
  4858. /***/ (function(module, exports, __webpack_require__) {
  4859. "use strict";
  4860. /* --------------------------------------------------------------------------------------------
  4861. * Copyright (c) Microsoft Corporation. All rights reserved.
  4862. * Licensed under the MIT License. See License.txt in the project root for license information.
  4863. * ------------------------------------------------------------------------------------------ */
  4864. Object.defineProperty(exports, "__esModule", { value: true });
  4865. const vscode_jsonrpc_1 = __webpack_require__(4);
  4866. /**
  4867. * A request to list all color symbols found in a given text document. The request's
  4868. * parameter is of type [DocumentColorParams](#DocumentColorParams) the
  4869. * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
  4870. * that resolves to such.
  4871. */
  4872. var DocumentColorRequest;
  4873. (function (DocumentColorRequest) {
  4874. DocumentColorRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/documentColor');
  4875. })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
  4876. /**
  4877. * A request to list all presentation for a color. The request's
  4878. * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the
  4879. * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
  4880. * that resolves to such.
  4881. */
  4882. var ColorPresentationRequest;
  4883. (function (ColorPresentationRequest) {
  4884. ColorPresentationRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/colorPresentation');
  4885. })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
  4886. /***/ }),
  4887. /* 26 */
  4888. /***/ (function(module, exports, __webpack_require__) {
  4889. "use strict";
  4890. /*---------------------------------------------------------------------------------------------
  4891. * Copyright (c) Microsoft Corporation. All rights reserved.
  4892. * Licensed under the MIT License. See License.txt in the project root for license information.
  4893. *--------------------------------------------------------------------------------------------*/
  4894. Object.defineProperty(exports, "__esModule", { value: true });
  4895. const vscode_jsonrpc_1 = __webpack_require__(4);
  4896. /**
  4897. * Enum of known range kinds
  4898. */
  4899. var FoldingRangeKind;
  4900. (function (FoldingRangeKind) {
  4901. /**
  4902. * Folding range for a comment
  4903. */
  4904. FoldingRangeKind["Comment"] = "comment";
  4905. /**
  4906. * Folding range for a imports or includes
  4907. */
  4908. FoldingRangeKind["Imports"] = "imports";
  4909. /**
  4910. * Folding range for a region (e.g. `#region`)
  4911. */
  4912. FoldingRangeKind["Region"] = "region";
  4913. })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
  4914. /**
  4915. * A request to provide folding ranges in a document. The request's
  4916. * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the
  4917. * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable
  4918. * that resolves to such.
  4919. */
  4920. var FoldingRangeRequest;
  4921. (function (FoldingRangeRequest) {
  4922. FoldingRangeRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/foldingRange');
  4923. })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
  4924. /***/ }),
  4925. /* 27 */
  4926. /***/ (function(module, exports, __webpack_require__) {
  4927. "use strict";
  4928. /* --------------------------------------------------------------------------------------------
  4929. * Copyright (c) Microsoft Corporation. All rights reserved.
  4930. * Licensed under the MIT License. See License.txt in the project root for license information.
  4931. * ------------------------------------------------------------------------------------------ */
  4932. Object.defineProperty(exports, "__esModule", { value: true });
  4933. const vscode_jsonrpc_1 = __webpack_require__(4);
  4934. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  4935. let __noDynamicImport;
  4936. /**
  4937. * A request to resolve the type definition locations of a symbol at a given text
  4938. * document position. The request's parameter is of type [TextDocumentPositioParams]
  4939. * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)
  4940. * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves
  4941. * to such.
  4942. */
  4943. var DeclarationRequest;
  4944. (function (DeclarationRequest) {
  4945. DeclarationRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/declaration');
  4946. })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
  4947. /***/ }),
  4948. /* 28 */
  4949. /***/ (function(module, exports, __webpack_require__) {
  4950. "use strict";
  4951. /* --------------------------------------------------------------------------------------------
  4952. * Copyright (c) TypeFox and others. All rights reserved.
  4953. * Licensed under the MIT License. See License.txt in the project root for license information.
  4954. * ------------------------------------------------------------------------------------------ */
  4955. Object.defineProperty(exports, "__esModule", { value: true });
  4956. const vscode_jsonrpc_1 = __webpack_require__(4);
  4957. /**
  4958. * The direction of a call hierarchy request.
  4959. */
  4960. var CallHierarchyDirection;
  4961. (function (CallHierarchyDirection) {
  4962. /**
  4963. * The callers
  4964. */
  4965. CallHierarchyDirection.CallsFrom = 1;
  4966. /**
  4967. * The callees
  4968. */
  4969. CallHierarchyDirection.CallsTo = 2;
  4970. })(CallHierarchyDirection = exports.CallHierarchyDirection || (exports.CallHierarchyDirection = {}));
  4971. /**
  4972. * Request to provide the call hierarchy at a given text document position.
  4973. *
  4974. * The request's parameter is of type [CallHierarchyParams](#CallHierarchyParams). The response
  4975. * is of type [CallHierarchyCall[]](#CallHierarchyCall) or a Thenable that resolves to such.
  4976. *
  4977. * Evaluates the symbol defined (or referenced) at the given position, and returns all incoming or outgoing calls to the symbol(s).
  4978. */
  4979. var CallHierarchyRequest;
  4980. (function (CallHierarchyRequest) {
  4981. CallHierarchyRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/callHierarchy');
  4982. })(CallHierarchyRequest = exports.CallHierarchyRequest || (exports.CallHierarchyRequest = {}));
  4983. /***/ }),
  4984. /* 29 */
  4985. /***/ (function(module, exports, __webpack_require__) {
  4986. "use strict";
  4987. /* --------------------------------------------------------------------------------------------
  4988. * Copyright (c) Microsoft Corporation. All rights reserved.
  4989. * Licensed under the MIT License. See License.txt in the project root for license information.
  4990. * ------------------------------------------------------------------------------------------ */
  4991. Object.defineProperty(exports, "__esModule", { value: true });
  4992. const vscode_jsonrpc_1 = __webpack_require__(4);
  4993. /**
  4994. * The `window/progress/start` notification is sent from the server to the client
  4995. * to initiate a progress.
  4996. */
  4997. var ProgressStartNotification;
  4998. (function (ProgressStartNotification) {
  4999. ProgressStartNotification.type = new vscode_jsonrpc_1.NotificationType('window/progress/start');
  5000. })(ProgressStartNotification = exports.ProgressStartNotification || (exports.ProgressStartNotification = {}));
  5001. /**
  5002. * The `window/progress/report` notification is sent from the server to the client
  5003. * to initiate a progress.
  5004. */
  5005. var ProgressReportNotification;
  5006. (function (ProgressReportNotification) {
  5007. ProgressReportNotification.type = new vscode_jsonrpc_1.NotificationType('window/progress/report');
  5008. })(ProgressReportNotification = exports.ProgressReportNotification || (exports.ProgressReportNotification = {}));
  5009. /**
  5010. * The `window/progress/done` notification is sent from the server to the client
  5011. * to initiate a progress.
  5012. */
  5013. var ProgressDoneNotification;
  5014. (function (ProgressDoneNotification) {
  5015. ProgressDoneNotification.type = new vscode_jsonrpc_1.NotificationType('window/progress/done');
  5016. })(ProgressDoneNotification = exports.ProgressDoneNotification || (exports.ProgressDoneNotification = {}));
  5017. /**
  5018. * The `window/progress/cancel` notification is sent client to the server to cancel a progress
  5019. * initiated on the server side.
  5020. */
  5021. var ProgressCancelNotification;
  5022. (function (ProgressCancelNotification) {
  5023. ProgressCancelNotification.type = new vscode_jsonrpc_1.NotificationType('window/progress/cancel');
  5024. })(ProgressCancelNotification = exports.ProgressCancelNotification || (exports.ProgressCancelNotification = {}));
  5025. /***/ }),
  5026. /* 30 */
  5027. /***/ (function(module, exports, __webpack_require__) {
  5028. "use strict";
  5029. /*---------------------------------------------------------------------------------------------
  5030. * Copyright (c) Microsoft Corporation. All rights reserved.
  5031. * Licensed under the MIT License. See License.txt in the project root for license information.
  5032. *--------------------------------------------------------------------------------------------*/
  5033. Object.defineProperty(exports, "__esModule", { value: true });
  5034. const vscode_jsonrpc_1 = __webpack_require__(4);
  5035. const vscode_languageserver_types_1 = __webpack_require__(18);
  5036. /**
  5037. * The SelectionRange namespace provides helper function to work with
  5038. * SelectionRange literals.
  5039. */
  5040. var SelectionRange;
  5041. (function (SelectionRange) {
  5042. /**
  5043. * Creates a new SelectionRange
  5044. * @param range the range.
  5045. * @param parent an optional parent.
  5046. */
  5047. function create(range, parent) {
  5048. return { range, parent };
  5049. }
  5050. SelectionRange.create = create;
  5051. function is(value) {
  5052. let candidate = value;
  5053. return candidate !== undefined && vscode_languageserver_types_1.Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
  5054. }
  5055. SelectionRange.is = is;
  5056. })(SelectionRange = exports.SelectionRange || (exports.SelectionRange = {}));
  5057. /**
  5058. * A request to provide selection ranges in a document. The request's
  5059. * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the
  5060. * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable
  5061. * that resolves to such.
  5062. */
  5063. var SelectionRangeRequest;
  5064. (function (SelectionRangeRequest) {
  5065. SelectionRangeRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/selectionRange');
  5066. })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
  5067. /***/ }),
  5068. /* 31 */
  5069. /***/ (function(module, exports, __webpack_require__) {
  5070. "use strict";
  5071. Object.defineProperty(exports, "__esModule", { value: true });
  5072. const coc_nvim_1 = __webpack_require__(1);
  5073. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  5074. const util_1 = __webpack_require__(32);
  5075. const hexColorRegex = /^#[\d,a-f,A-F]{0,6}$/;
  5076. /**
  5077. * Checks if given position is a valid location to expand emmet abbreviation.
  5078. * Works only on html and css/less/scss syntax
  5079. * @param document current Text Document
  5080. * @param rootNode parsed document
  5081. * @param currentNode current node in the parsed document
  5082. * @param syntax syntax of the abbreviation
  5083. * @param position position to validate
  5084. * @param abbreviationRange The range of the abbreviation for which given position is being validated
  5085. */
  5086. function isValidLocationForEmmetAbbreviation(document, rootNode, currentNode, syntax, position, abbreviationRange) {
  5087. if (util_1.isStyleSheet(syntax)) {
  5088. const stylesheet = rootNode;
  5089. if (stylesheet &&
  5090. (stylesheet.comments || []).some(x => util_1.comparePosition(position, x.start) >= 0 && util_1.comparePosition(position, x.end) <= 0)) {
  5091. return false;
  5092. }
  5093. // Continue validation only if the file was parse-able and the currentNode has been found
  5094. if (!currentNode) {
  5095. return true;
  5096. }
  5097. // Fix for https://github.com/Microsoft/issues/34162
  5098. // Other than sass, stylus, we can make use of the terminator tokens to validate position
  5099. if (syntax !== 'sass' && syntax !== 'stylus' && currentNode.type === 'property') {
  5100. // Fix for upstream issue https://github.com/emmetio/css-parser/issues/3
  5101. if (currentNode.parent
  5102. && currentNode.parent.type !== 'rule'
  5103. && currentNode.parent.type !== 'at-rule') {
  5104. return false;
  5105. }
  5106. const abbreviation = document.getText(vscode_languageserver_protocol_1.Range.create(abbreviationRange.start.line, abbreviationRange.start.character, abbreviationRange.end.line, abbreviationRange.end.character));
  5107. const propertyNode = currentNode;
  5108. if (propertyNode.terminatorToken
  5109. && propertyNode.separator
  5110. && util_1.comparePosition(position, propertyNode.separatorToken.end) >= 0
  5111. && util_1.comparePosition(position, propertyNode.terminatorToken.start) <= 0
  5112. && abbreviation.indexOf(':') === -1) {
  5113. return hexColorRegex.test(abbreviation) || abbreviation === '!';
  5114. }
  5115. if (!propertyNode.terminatorToken
  5116. && propertyNode.separator
  5117. && util_1.comparePosition(position, propertyNode.separatorToken.end) >= 0
  5118. && abbreviation.indexOf(':') === -1) {
  5119. return hexColorRegex.test(abbreviation) || abbreviation === '!';
  5120. }
  5121. if (hexColorRegex.test(abbreviation) || abbreviation === '!') {
  5122. return false;
  5123. }
  5124. }
  5125. // If current node is a rule or at-rule, then perform additional checks to ensure
  5126. // emmet suggestions are not provided in the rule selector
  5127. if (currentNode.type !== 'rule' && currentNode.type !== 'at-rule') {
  5128. return true;
  5129. }
  5130. const currentCssNode = currentNode;
  5131. // Position is valid if it occurs after the `{` that marks beginning of rule contents
  5132. if (util_1.comparePosition(position, currentCssNode.contentStartToken.end) > 0) {
  5133. return true;
  5134. }
  5135. // Workaround for https://github.com/Microsoft/30188
  5136. // The line above the rule selector is considered as part of the selector by the css-parser
  5137. // But we should assume it is a valid location for css properties under the parent rule
  5138. if (currentCssNode.parent
  5139. && (currentCssNode.parent.type === 'rule' || currentCssNode.parent.type === 'at-rule')
  5140. && currentCssNode.selectorToken
  5141. && position.line !== currentCssNode.selectorToken.end.line
  5142. && currentCssNode.selectorToken.start.character === abbreviationRange.start.character
  5143. && currentCssNode.selectorToken.start.line === abbreviationRange.start.line) {
  5144. return true;
  5145. }
  5146. return false;
  5147. }
  5148. const startAngle = '<';
  5149. const endAngle = '>';
  5150. const escape = '\\';
  5151. const question = '?';
  5152. const currentHtmlNode = currentNode;
  5153. let start = vscode_languageserver_protocol_1.Position.create(0, 0);
  5154. if (currentHtmlNode) {
  5155. if (currentHtmlNode.name === 'script') {
  5156. const typeAttribute = (currentHtmlNode.attributes || []).filter(x => x.name.toString() === 'type')[0];
  5157. const typeValue = typeAttribute ? typeAttribute.value.toString() : '';
  5158. if (util_1.allowedMimeTypesInScriptTag.indexOf(typeValue) > -1) {
  5159. return true;
  5160. }
  5161. const isScriptJavascriptType = !typeValue || typeValue === 'application/javascript' || typeValue === 'text/javascript';
  5162. if (isScriptJavascriptType) {
  5163. return !!getSyntaxFromArgs({ language: 'javascript' });
  5164. }
  5165. return false;
  5166. }
  5167. const innerRange = util_1.getInnerRange(currentHtmlNode);
  5168. // Fix for https://github.com/Microsoft/issues/28829
  5169. if (!innerRange || !util_1.positionInRange(position, innerRange)) {
  5170. return false;
  5171. }
  5172. // Fix for https://github.com/Microsoft/issues/35128
  5173. // Find the position up till where we will backtrack looking for unescaped < or >
  5174. // to decide if current position is valid for emmet expansion
  5175. start = innerRange.start;
  5176. let lastChildBeforePosition = currentHtmlNode.firstChild;
  5177. while (lastChildBeforePosition) {
  5178. if (util_1.comparePosition(lastChildBeforePosition.end, position) > 0) {
  5179. break;
  5180. }
  5181. start = lastChildBeforePosition.end;
  5182. lastChildBeforePosition = lastChildBeforePosition.nextSibling;
  5183. }
  5184. }
  5185. let textToBackTrack = document.getText(vscode_languageserver_protocol_1.Range.create(start.line, start.character, abbreviationRange.start.line, abbreviationRange.start.character));
  5186. // Worse case scenario is when cursor is inside a big chunk of text which needs to backtracked
  5187. // Backtrack only 500 offsets to ensure we dont waste time doing this
  5188. if (textToBackTrack.length > 500) {
  5189. textToBackTrack = textToBackTrack.substr(textToBackTrack.length - 500);
  5190. }
  5191. if (!textToBackTrack.trim()) {
  5192. return true;
  5193. }
  5194. let valid = true;
  5195. let foundSpace = false; // If < is found before finding whitespace, then its valid abbreviation. Eg: <div|
  5196. let i = textToBackTrack.length - 1;
  5197. if (textToBackTrack[i] === startAngle) {
  5198. return false;
  5199. }
  5200. while (i >= 0) {
  5201. const char = textToBackTrack[i];
  5202. i--;
  5203. if (!foundSpace && /\s/.test(char)) {
  5204. foundSpace = true;
  5205. continue;
  5206. }
  5207. if (char === question && textToBackTrack[i] === startAngle) {
  5208. i--;
  5209. continue;
  5210. }
  5211. // Fix for https://github.com/Microsoft/issues/55411
  5212. // A space is not a valid character right after < in a tag name.
  5213. if (/\s/.test(char) && textToBackTrack[i] === startAngle) {
  5214. i--;
  5215. continue;
  5216. }
  5217. if (char !== startAngle && char !== endAngle) {
  5218. continue;
  5219. }
  5220. if (i >= 0 && textToBackTrack[i] === escape) {
  5221. i--;
  5222. continue;
  5223. }
  5224. if (char === endAngle) {
  5225. if (i >= 0 && textToBackTrack[i] === '=') {
  5226. continue; // False alarm of cases like =>
  5227. }
  5228. else {
  5229. break;
  5230. }
  5231. }
  5232. if (char === startAngle) {
  5233. valid = !foundSpace;
  5234. break;
  5235. }
  5236. }
  5237. return valid;
  5238. }
  5239. exports.isValidLocationForEmmetAbbreviation = isValidLocationForEmmetAbbreviation;
  5240. function getSyntaxFromArgs(args) {
  5241. const mappedModes = util_1.getMappingForIncludedLanguages();
  5242. const language = args['language'];
  5243. const parentMode = args['parentMode'];
  5244. const excludedLanguages = coc_nvim_1.workspace.getConfiguration('emmet')['excludeLanguages'] ? coc_nvim_1.workspace.getConfiguration('emmet')['excludeLanguages'] : [];
  5245. if (excludedLanguages.indexOf(language) > -1) {
  5246. return;
  5247. }
  5248. let syntax = util_1.getEmmetMode((mappedModes[language] ? mappedModes[language] : language), excludedLanguages);
  5249. if (!syntax) {
  5250. syntax = util_1.getEmmetMode((mappedModes[parentMode] ? mappedModes[parentMode] : parentMode), excludedLanguages);
  5251. }
  5252. return syntax;
  5253. }
  5254. /***/ }),
  5255. /* 32 */
  5256. /***/ (function(module, exports, __webpack_require__) {
  5257. "use strict";
  5258. var __importDefault = (this && this.__importDefault) || function (mod) {
  5259. return (mod && mod.__esModule) ? mod : { "default": mod };
  5260. };
  5261. Object.defineProperty(exports, "__esModule", { value: true });
  5262. /*---------------------------------------------------------------------------------------------
  5263. * Copyright (c) Microsoft Corporation. All rights reserved.
  5264. * Licensed under the MIT License. See License.txt in the project root for license information.
  5265. *--------------------------------------------------------------------------------------------*/
  5266. const coc_nvim_1 = __webpack_require__(1);
  5267. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  5268. const html_matcher_1 = __importDefault(__webpack_require__(33));
  5269. const css_parser_1 = __importDefault(__webpack_require__(36));
  5270. const bufferStream_1 = __webpack_require__(37);
  5271. exports.comparePosition = bufferStream_1.comparePosition;
  5272. let _emmetHelper;
  5273. let _currentExtensionsPath;
  5274. function positionInRange(position, range) {
  5275. let { start, end } = range;
  5276. if (bufferStream_1.comparePosition(position, start) < 0)
  5277. return -1;
  5278. if (bufferStream_1.comparePosition(position, end) > 0)
  5279. return 1;
  5280. return 0;
  5281. }
  5282. exports.positionInRange = positionInRange;
  5283. function getEmmetHelper() {
  5284. // Lazy load emmet-helper instead of importing it
  5285. // directly to reduce the start-up time of the extension
  5286. if (!_emmetHelper) {
  5287. _emmetHelper = __webpack_require__(38);
  5288. }
  5289. updateEmmetExtensionsPath();
  5290. return _emmetHelper;
  5291. }
  5292. exports.getEmmetHelper = getEmmetHelper;
  5293. /**
  5294. * Update Emmet Helper to use user snippets from the extensionsPath setting
  5295. */
  5296. function updateEmmetExtensionsPath() {
  5297. if (!_emmetHelper) {
  5298. return;
  5299. }
  5300. let extensionsPath = coc_nvim_1.workspace.getConfiguration('emmet')['extensionsPath'];
  5301. if (_currentExtensionsPath !== extensionsPath) {
  5302. _currentExtensionsPath = extensionsPath;
  5303. _emmetHelper.updateExtensionsPath(extensionsPath, coc_nvim_1.workspace.rootPath).then(null, (err) => coc_nvim_1.workspace.showMessage(err, 'error'));
  5304. }
  5305. }
  5306. exports.updateEmmetExtensionsPath = updateEmmetExtensionsPath;
  5307. /**
  5308. * Mapping between languages that support Emmet and completion trigger characters
  5309. */
  5310. exports.LANGUAGE_MODES = {
  5311. 'html': ['!', '.', '}', ':', '*', '$', ']', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  5312. 'jade': ['!', '.', '}', ':', '*', '$', ']', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  5313. 'slim': ['!', '.', '}', ':', '*', '$', ']', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  5314. 'haml': ['!', '.', '}', ':', '*', '$', ']', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  5315. 'xml': ['.', '}', '*', '$', ']', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  5316. 'xsl': ['!', '.', '}', '*', '$', ']', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  5317. 'css': [':', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  5318. 'scss': [':', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  5319. 'sass': [':', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  5320. 'less': [':', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  5321. 'stylus': [':', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  5322. 'javascriptreact': ['!', '.', '}', '*', '$', ']', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  5323. 'typescriptreact': ['!', '.', '}', '*', '$', ']', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
  5324. };
  5325. function isStyleSheet(syntax) {
  5326. let stylesheetSyntaxes = ['css', 'scss', 'sass', 'less', 'stylus', 'wxss'];
  5327. return (stylesheetSyntaxes.indexOf(syntax) > -1);
  5328. }
  5329. exports.isStyleSheet = isStyleSheet;
  5330. function validate(allowStylesheet = true) {
  5331. let doc = coc_nvim_1.workspace.getDocument(coc_nvim_1.workspace.bufnr);
  5332. if (!doc)
  5333. return false;
  5334. if (!allowStylesheet && isStyleSheet(doc.filetype)) {
  5335. return false;
  5336. }
  5337. return true;
  5338. }
  5339. exports.validate = validate;
  5340. function getMappingForIncludedLanguages() {
  5341. // Explicitly map languages that have built-in grammar in VS Code to their parent language
  5342. // to get emmet completion support
  5343. // For other languages, users will have to use `emmet.includeLanguages` or
  5344. // language specific extensions can provide emmet completion support
  5345. const MAPPED_MODES = {
  5346. 'handlebars': 'html',
  5347. 'php': 'html'
  5348. };
  5349. const finalMappedModes = Object.create(null);
  5350. let includeLanguagesConfig = coc_nvim_1.workspace.getConfiguration('emmet')['includeLanguages'];
  5351. let includeLanguages = Object.assign({}, MAPPED_MODES, includeLanguagesConfig ? includeLanguagesConfig : {});
  5352. Object.keys(includeLanguages).forEach(syntax => {
  5353. if (typeof includeLanguages[syntax] === 'string' && exports.LANGUAGE_MODES[includeLanguages[syntax]]) {
  5354. finalMappedModes[syntax] = includeLanguages[syntax];
  5355. }
  5356. });
  5357. return finalMappedModes;
  5358. }
  5359. exports.getMappingForIncludedLanguages = getMappingForIncludedLanguages;
  5360. /**
  5361. * Get the corresponding emmet mode for given language mode
  5362. * Eg: jsx for typescriptreact/javascriptreact or pug for jade
  5363. * If the language is not supported by emmet or has been exlcuded via `exlcudeLanguages` setting,
  5364. * then nothing is returned
  5365. *
  5366. * @param language
  5367. * @param exlcudedLanguages Array of language ids that user has chosen to exlcude for emmet
  5368. */
  5369. function getEmmetMode(language, excludedLanguages) {
  5370. if (!language || excludedLanguages.indexOf(language) > -1) {
  5371. return;
  5372. }
  5373. if (/\b(typescriptreact|javascriptreact|jsx-tags)\b/.test(language)) { // treat tsx like jsx
  5374. return 'jsx';
  5375. }
  5376. if (language === 'sass-indented') { // map sass-indented to sass
  5377. return 'sass';
  5378. }
  5379. if (language === 'jade') {
  5380. return 'pug';
  5381. }
  5382. const emmetModes = ['html', 'pug', 'slim', 'haml', 'xml', 'xsl', 'jsx', 'css', 'scss', 'sass', 'less', 'stylus'];
  5383. if (emmetModes.indexOf(language) > -1) {
  5384. return language;
  5385. }
  5386. return;
  5387. }
  5388. exports.getEmmetMode = getEmmetMode;
  5389. /**
  5390. * Parses the given document using emmet parsing modules
  5391. */
  5392. function parseDocument(document, showError = true) {
  5393. let parseContent = isStyleSheet(document.languageId) ? css_parser_1.default : html_matcher_1.default;
  5394. try {
  5395. return parseContent(new bufferStream_1.DocumentStreamReader(document));
  5396. }
  5397. catch (e) {
  5398. if (showError) {
  5399. console.error('Emmet: Failed to parse the file');
  5400. }
  5401. }
  5402. return undefined;
  5403. }
  5404. exports.parseDocument = parseDocument;
  5405. const closeBrace = 125;
  5406. const openBrace = 123;
  5407. const slash = 47;
  5408. const star = 42;
  5409. /**
  5410. * Traverse the given document backward & forward from given position
  5411. * to find a complete ruleset, then parse just that to return a Stylesheet
  5412. * @param document TextDocument
  5413. * @param position Position
  5414. */
  5415. function parsePartialStylesheet(document, position) {
  5416. const isCSS = document.languageId === 'css';
  5417. let startPosition = vscode_languageserver_protocol_1.Position.create(0, 0);
  5418. let lastLine = document.getText(vscode_languageserver_protocol_1.Range.create(document.lineCount - 1, 0, document.lineCount, 0)).replace(/\n$/, '');
  5419. let endPosition = vscode_languageserver_protocol_1.Position.create(document.lineCount - 1, lastLine.length);
  5420. const limitCharacter = document.offsetAt(position) - 5000;
  5421. const limitPosition = limitCharacter > 0 ? document.positionAt(limitCharacter) : startPosition;
  5422. const stream = new bufferStream_1.DocumentStreamReader(document, position);
  5423. function findOpeningCommentBeforePosition(pos) {
  5424. let text = document.getText(vscode_languageserver_protocol_1.Range.create(0, 0, pos.line, pos.character));
  5425. let offset = text.lastIndexOf('/*');
  5426. if (offset === -1) {
  5427. return;
  5428. }
  5429. return document.positionAt(offset);
  5430. }
  5431. function findClosingCommentAfterPosition(pos) {
  5432. let text = document.getText(vscode_languageserver_protocol_1.Range.create(pos.line, pos.character, document.lineCount - 1, lastLine.length));
  5433. let offset = text.indexOf('*/');
  5434. if (offset === -1) {
  5435. return;
  5436. }
  5437. offset += 2 + document.offsetAt(pos);
  5438. return document.positionAt(offset);
  5439. }
  5440. function consumeLineCommentBackwards() {
  5441. if (!isCSS && currentLine !== stream.pos.line) {
  5442. currentLine = stream.pos.line;
  5443. let line = document.getText(vscode_languageserver_protocol_1.Range.create(currentLine, 0, currentLine + 1, 0));
  5444. let startLineComment = line.indexOf('//');
  5445. if (startLineComment > -1) {
  5446. stream.pos = vscode_languageserver_protocol_1.Position.create(currentLine, startLineComment);
  5447. }
  5448. }
  5449. }
  5450. function consumeBlockCommentBackwards() {
  5451. if (stream.peek() === slash) {
  5452. if (stream.backUp(1) === star) {
  5453. stream.pos = findOpeningCommentBeforePosition(stream.pos) || startPosition;
  5454. }
  5455. else {
  5456. stream.next();
  5457. }
  5458. }
  5459. }
  5460. function consumeCommentForwards() {
  5461. if (stream.eat(slash)) {
  5462. if (stream.eat(slash) && !isCSS) {
  5463. stream.pos = vscode_languageserver_protocol_1.Position.create(stream.pos.line + 1, 0);
  5464. }
  5465. else if (stream.eat(star)) {
  5466. stream.pos = findClosingCommentAfterPosition(stream.pos) || endPosition;
  5467. }
  5468. }
  5469. }
  5470. // Go forward until we find a closing brace.
  5471. while (!stream.eof() && !stream.eat(closeBrace)) {
  5472. if (stream.peek() === slash) {
  5473. consumeCommentForwards();
  5474. }
  5475. else {
  5476. stream.next();
  5477. }
  5478. }
  5479. if (!stream.eof()) {
  5480. endPosition = stream.pos;
  5481. }
  5482. stream.pos = position;
  5483. let openBracesToFind = 1;
  5484. let currentLine = position.line;
  5485. let exit = false;
  5486. // Go back until we found an opening brace. If we find a closing one, consume its pair and continue.
  5487. while (!exit && openBracesToFind > 0 && !stream.sof()) {
  5488. consumeLineCommentBackwards();
  5489. switch (stream.backUp(1)) {
  5490. case openBrace:
  5491. openBracesToFind--;
  5492. break;
  5493. case closeBrace:
  5494. if (isCSS) {
  5495. stream.next();
  5496. startPosition = stream.pos;
  5497. exit = true;
  5498. }
  5499. else {
  5500. openBracesToFind++;
  5501. }
  5502. break;
  5503. case slash:
  5504. consumeBlockCommentBackwards();
  5505. break;
  5506. default:
  5507. break;
  5508. }
  5509. if (position.line - stream.pos.line > 100 || bufferStream_1.comparePosition(stream.pos, limitPosition) <= 0) {
  5510. exit = true;
  5511. }
  5512. }
  5513. // We are at an opening brace. We need to include its selector.
  5514. currentLine = stream.pos.line;
  5515. openBracesToFind = 0;
  5516. let foundSelector = false;
  5517. while (!exit && !stream.sof() && !foundSelector && openBracesToFind >= 0) {
  5518. consumeLineCommentBackwards();
  5519. const ch = stream.backUp(1);
  5520. if (/\s/.test(String.fromCharCode(ch))) {
  5521. continue;
  5522. }
  5523. switch (ch) {
  5524. case slash:
  5525. consumeBlockCommentBackwards();
  5526. break;
  5527. case closeBrace:
  5528. openBracesToFind++;
  5529. break;
  5530. case openBrace:
  5531. openBracesToFind--;
  5532. break;
  5533. default:
  5534. if (!openBracesToFind) {
  5535. foundSelector = true;
  5536. }
  5537. break;
  5538. }
  5539. if (!stream.sof() && foundSelector) {
  5540. startPosition = stream.pos;
  5541. }
  5542. }
  5543. try {
  5544. return css_parser_1.default(new bufferStream_1.DocumentStreamReader(document, startPosition, vscode_languageserver_protocol_1.Range.create(startPosition, endPosition)));
  5545. }
  5546. catch (e) {
  5547. return;
  5548. }
  5549. }
  5550. exports.parsePartialStylesheet = parsePartialStylesheet;
  5551. /**
  5552. * Returns node corresponding to given position in the given root node
  5553. */
  5554. function getNode(root, position, includeNodeBoundary) {
  5555. if (!root) {
  5556. return null;
  5557. }
  5558. let currentNode = root.firstChild;
  5559. let foundNode = null;
  5560. while (currentNode) {
  5561. const nodeStart = currentNode.start;
  5562. const nodeEnd = currentNode.end;
  5563. if ((bufferStream_1.comparePosition(nodeStart, position) < 0 && bufferStream_1.comparePosition(nodeEnd, position) > 0)
  5564. || (includeNodeBoundary && (bufferStream_1.comparePosition(nodeStart, position) <= 0 && bufferStream_1.comparePosition(nodeEnd, position) >= 0))) {
  5565. foundNode = currentNode;
  5566. // Dig deeper
  5567. currentNode = currentNode.firstChild;
  5568. }
  5569. else {
  5570. currentNode = currentNode.nextSibling;
  5571. }
  5572. }
  5573. return foundNode;
  5574. }
  5575. exports.getNode = getNode;
  5576. exports.allowedMimeTypesInScriptTag = ['text/html', 'text/plain', 'text/x-template', 'text/template', 'text/ng-template'];
  5577. /**
  5578. * Returns inner range of an html node.
  5579. * @param currentNode
  5580. */
  5581. function getInnerRange(currentNode) {
  5582. if (!currentNode.close) {
  5583. return undefined;
  5584. }
  5585. return vscode_languageserver_protocol_1.Range.create(currentNode.open.end, currentNode.close.start);
  5586. }
  5587. exports.getInnerRange = getInnerRange;
  5588. /**
  5589. * Returns the deepest non comment node under given node
  5590. * @param node
  5591. */
  5592. function getDeepestNode(node) {
  5593. if (!node || !node.children || node.children.length === 0 || !node.children.find(x => x.type !== 'comment')) {
  5594. return node;
  5595. }
  5596. for (let i = node.children.length - 1; i >= 0; i--) {
  5597. if (node.children[i].type !== 'comment') {
  5598. return getDeepestNode(node.children[i]);
  5599. }
  5600. }
  5601. return undefined;
  5602. }
  5603. exports.getDeepestNode = getDeepestNode;
  5604. function findNextWord(propertyValue, pos) {
  5605. let foundSpace = pos === -1;
  5606. let foundStart = false;
  5607. let foundEnd = false;
  5608. let newSelectionStart;
  5609. let newSelectionEnd;
  5610. while (pos < propertyValue.length - 1) {
  5611. pos++;
  5612. if (!foundSpace) {
  5613. if (propertyValue[pos] === ' ') {
  5614. foundSpace = true;
  5615. }
  5616. continue;
  5617. }
  5618. if (foundSpace && !foundStart && propertyValue[pos] === ' ') {
  5619. continue;
  5620. }
  5621. if (!foundStart) {
  5622. newSelectionStart = pos;
  5623. foundStart = true;
  5624. continue;
  5625. }
  5626. if (propertyValue[pos] === ' ') {
  5627. newSelectionEnd = pos;
  5628. foundEnd = true;
  5629. break;
  5630. }
  5631. }
  5632. if (foundStart && !foundEnd) {
  5633. newSelectionEnd = propertyValue.length;
  5634. }
  5635. return [newSelectionStart, newSelectionEnd];
  5636. }
  5637. exports.findNextWord = findNextWord;
  5638. function findPrevWord(propertyValue, pos) {
  5639. let foundSpace = pos === propertyValue.length;
  5640. let foundStart = false;
  5641. let foundEnd = false;
  5642. let newSelectionStart;
  5643. let newSelectionEnd;
  5644. while (pos > -1) {
  5645. pos--;
  5646. if (!foundSpace) {
  5647. if (propertyValue[pos] === ' ') {
  5648. foundSpace = true;
  5649. }
  5650. continue;
  5651. }
  5652. if (foundSpace && !foundEnd && propertyValue[pos] === ' ') {
  5653. continue;
  5654. }
  5655. if (!foundEnd) {
  5656. newSelectionEnd = pos + 1;
  5657. foundEnd = true;
  5658. continue;
  5659. }
  5660. if (propertyValue[pos] === ' ') {
  5661. newSelectionStart = pos + 1;
  5662. foundStart = true;
  5663. break;
  5664. }
  5665. }
  5666. if (foundEnd && !foundStart) {
  5667. newSelectionStart = 0;
  5668. }
  5669. return [newSelectionStart, newSelectionEnd];
  5670. }
  5671. exports.findPrevWord = findPrevWord;
  5672. function getEmmetConfiguration(syntax) {
  5673. const emmetConfig = coc_nvim_1.workspace.getConfiguration('emmet');
  5674. const syntaxProfiles = Object.assign({}, emmetConfig['syntaxProfiles'] || {});
  5675. const preferences = Object.assign({}, emmetConfig['preferences'] || {});
  5676. // jsx, xml and xsl syntaxes need to have self closing tags unless otherwise configured by user
  5677. if (syntax === 'jsx' || syntax === 'xml' || syntax === 'xsl') {
  5678. syntaxProfiles[syntax] = syntaxProfiles[syntax] || {};
  5679. if (typeof syntaxProfiles[syntax] === 'object'
  5680. && !syntaxProfiles[syntax].hasOwnProperty('self_closing_tag') // Old Emmet format
  5681. && !syntaxProfiles[syntax].hasOwnProperty('selfClosingStyle') // Emmet 2.0 format
  5682. ) {
  5683. syntaxProfiles[syntax] = Object.assign({}, syntaxProfiles[syntax], { selfClosingStyle: 'xml' });
  5684. }
  5685. }
  5686. return {
  5687. preferences,
  5688. showExpandedAbbreviation: emmetConfig['showExpandedAbbreviation'],
  5689. showAbbreviationSuggestions: emmetConfig['showAbbreviationSuggestions'],
  5690. syntaxProfiles,
  5691. variables: emmetConfig['variables'],
  5692. excludeLanguages: emmetConfig['excludeLanguages'],
  5693. showSuggestionsAsSnippets: emmetConfig['showSuggestionsAsSnippets']
  5694. };
  5695. }
  5696. exports.getEmmetConfiguration = getEmmetConfiguration;
  5697. /**
  5698. * Itereates by each child, as well as nested child's children, in their order
  5699. * and invokes `fn` for each. If `fn` function returns `false`, iteration stops
  5700. */
  5701. function iterateCSSToken(token, fn) {
  5702. for (let i = 0, il = token.size; i < il; i++) {
  5703. if (fn(token.item(i)) === false || iterateCSSToken(token.item(i), fn) === false) {
  5704. return false;
  5705. }
  5706. }
  5707. return true;
  5708. }
  5709. exports.iterateCSSToken = iterateCSSToken;
  5710. /**
  5711. * Returns `name` CSS property from given `rule`
  5712. */
  5713. function getCssPropertyFromRule(rule, name) {
  5714. return rule.children.find(node => node.type === 'property' && node.name === name);
  5715. }
  5716. exports.getCssPropertyFromRule = getCssPropertyFromRule;
  5717. function getEmbeddedCssNodeIfAny(document, currentNode, position) {
  5718. if (!currentNode) {
  5719. return;
  5720. }
  5721. const currentHtmlNode = currentNode;
  5722. if (currentHtmlNode && currentHtmlNode.close) {
  5723. const innerRange = getInnerRange(currentHtmlNode);
  5724. if (innerRange && positionInRange(position, innerRange)) {
  5725. if (currentHtmlNode.name === 'style'
  5726. && bufferStream_1.comparePosition(currentHtmlNode.open.end, position) < 0
  5727. && bufferStream_1.comparePosition(currentHtmlNode.close.start, position) > 0) {
  5728. let buffer = new bufferStream_1.DocumentStreamReader(document, currentHtmlNode.open.end, vscode_languageserver_protocol_1.Range.create(currentHtmlNode.open.end, currentHtmlNode.close.start));
  5729. return css_parser_1.default(buffer);
  5730. }
  5731. }
  5732. }
  5733. return;
  5734. }
  5735. exports.getEmbeddedCssNodeIfAny = getEmbeddedCssNodeIfAny;
  5736. function isStyleAttribute(currentNode, position) {
  5737. if (!currentNode) {
  5738. return false;
  5739. }
  5740. const currentHtmlNode = currentNode;
  5741. const index = (currentHtmlNode.attributes || []).findIndex(x => x.name.toString() === 'style');
  5742. if (index === -1) {
  5743. return false;
  5744. }
  5745. const styleAttribute = currentHtmlNode.attributes[index];
  5746. return bufferStream_1.comparePosition(position, styleAttribute.value.start) >= 0 && bufferStream_1.comparePosition(position, styleAttribute.value.end) <= 0;
  5747. }
  5748. exports.isStyleAttribute = isStyleAttribute;
  5749. /***/ }),
  5750. /* 33 */
  5751. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  5752. "use strict";
  5753. __webpack_require__.r(__webpack_exports__);
  5754. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultOptions", function() { return defaultOptions; });
  5755. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "match", function() { return match; });
  5756. /* harmony import */ var _emmetio_stream_reader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(34);
  5757. /* harmony import */ var _emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35);
  5758. class Node {
  5759. constructor(stream, type, open, close) {
  5760. this.stream = stream;
  5761. this.type = type;
  5762. this.open = open;
  5763. this.close = close;
  5764. this.children = [];
  5765. this.parent = null;
  5766. }
  5767. /**
  5768. * Returns node name
  5769. * @return {String}
  5770. */
  5771. get name() {
  5772. if (this.type === 'tag' && this.open) {
  5773. return this.open && this.open.name && this.open.name.value;
  5774. }
  5775. return '#' + this.type;
  5776. }
  5777. /**
  5778. * Returns attributes of current node
  5779. * @return {Array}
  5780. */
  5781. get attributes() {
  5782. return this.open && this.open.attributes;
  5783. }
  5784. /**
  5785. * Returns node’s start position in stream
  5786. * @return {*}
  5787. */
  5788. get start() {
  5789. return this.open && this.open.start;
  5790. }
  5791. /**
  5792. * Returns node’s start position in stream
  5793. * @return {*}
  5794. */
  5795. get end() {
  5796. return this.close ? this.close.end : this.open && this.open.end;
  5797. }
  5798. get firstChild() {
  5799. return this.children[0];
  5800. }
  5801. get nextSibling() {
  5802. const ix = this.getIndex();
  5803. return ix !== -1 ? this.parent.children[ix + 1] : null;
  5804. }
  5805. get previousSibling() {
  5806. const ix = this.getIndex();
  5807. return ix !== -1 ? this.parent.children[ix - 1] : null;
  5808. }
  5809. /**
  5810. * Returns current element’s index in parent list of child nodes
  5811. * @return {Number}
  5812. */
  5813. getIndex() {
  5814. return this.parent ? this.parent.children.indexOf(this) : -1;
  5815. }
  5816. /**
  5817. * Adds given node as a child
  5818. * @param {Node} node
  5819. * @return {Node} Current node
  5820. */
  5821. addChild(node) {
  5822. this.removeChild(node);
  5823. this.children.push(node);
  5824. node.parent = this;
  5825. return this;
  5826. }
  5827. /**
  5828. * Removes given node from current node’s child list
  5829. * @param {Node} node
  5830. * @return {Node} Current node
  5831. */
  5832. removeChild(node) {
  5833. const ix = this.children.indexOf(node);
  5834. if (ix !== -1) {
  5835. this.children.splice(ix, 1);
  5836. node.parent = null;
  5837. }
  5838. return this;
  5839. }
  5840. }
  5841. /**
  5842. * A token factory method
  5843. * @param {StreamReader} stream
  5844. * @param {Point|Function} start Tokens’ start location or stream consumer
  5845. * @param {Point} [end] Tokens’ end location
  5846. * @return {Token}
  5847. */
  5848. var token = function(stream, start, end) {
  5849. return typeof start === 'function'
  5850. ? eatToken(stream, start)
  5851. : new Token(stream, start, end);
  5852. };
  5853. /**
  5854. * Consumes characters from given stream that matches `fn` call and returns it
  5855. * as token, if consumed
  5856. * @param {StreamReader} stream
  5857. * @param {Function} test
  5858. * @return {Token}
  5859. */
  5860. function eatToken(stream, test) {
  5861. const start = stream.pos;
  5862. if (stream.eatWhile(test)) {
  5863. return new Token(stream, start, stream.pos);
  5864. }
  5865. stream.pos = start;
  5866. }
  5867. /**
  5868. * A structure describing text fragment in content stream
  5869. */
  5870. class Token {
  5871. /**
  5872. * @param {ContentStreamReader} stream
  5873. * @param {Point} start Tokens’ start location in content stream
  5874. * @param {Point} end Tokens’ end location in content stream
  5875. */
  5876. constructor(stream, start, end) {
  5877. this.stream = stream;
  5878. this.start = start != null ? start : stream.start;
  5879. this.end = end != null ? end : stream.pos;
  5880. this._value = null;
  5881. }
  5882. /**
  5883. * Returns token textual value
  5884. * NB implemented as getter to reduce unnecessary memory allocations for
  5885. * strings that not required
  5886. * @return {String}
  5887. */
  5888. get value() {
  5889. if (this._value === null) {
  5890. const start = this.stream.start;
  5891. const end = this.stream.pos;
  5892. this.stream.start = this.start;
  5893. this.stream.pos = this.end;
  5894. this._value = this.stream.current();
  5895. this.stream.start = start;
  5896. this.stream.pos = end;
  5897. }
  5898. return this._value;
  5899. }
  5900. toString() {
  5901. return this.value;
  5902. }
  5903. valueOf() {
  5904. return `${this.value} [${this.start}; ${this.end}]`;
  5905. }
  5906. }
  5907. const LANGLE = 60;
  5908. const RANGLE = 62; // < and >
  5909. const LSQUARE = 91;
  5910. const RSQUARE = 93; // [ and ]
  5911. const LROUND = 40;
  5912. const RROUND = 41; // ( and )
  5913. const LCURLY = 123;
  5914. const RCURLY = 125; // { and }
  5915. const opt = { throws: true };
  5916. /**
  5917. * Consumes paired tokens (like `[` and `]`) with respect of nesting and embedded
  5918. * quoted values
  5919. * @param {StreamReader} stream
  5920. * @return {Token} A token with consumed paired character
  5921. */
  5922. var eatPaired = function(stream) {
  5923. const start = stream.pos;
  5924. const consumed = Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["eatPair"])(stream, LANGLE, RANGLE, opt)
  5925. || Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["eatPair"])(stream, LSQUARE, RSQUARE, opt)
  5926. || Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["eatPair"])(stream, LROUND, RROUND, opt)
  5927. || Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["eatPair"])(stream, LCURLY, RCURLY, opt);
  5928. if (consumed) {
  5929. return token(stream, start);
  5930. }
  5931. };
  5932. const SLASH$1 = 47; // /
  5933. const EQUALS = 61; // =
  5934. const RIGHT_ANGLE$1 = 62; // >
  5935. /**
  5936. * Consumes attributes from given stream
  5937. * @param {StreamReader} stream
  5938. * @return {Array} Array of consumed attributes
  5939. */
  5940. var eatAttributes = function(stream) {
  5941. const result = [];
  5942. let name, value, attr;
  5943. while (!stream.eof()) {
  5944. stream.eatWhile(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isSpace"]);
  5945. attr = { start: stream.pos };
  5946. // A name could be a regular name or expression:
  5947. // React-style – <div {...props}>
  5948. // Angular-style – <div [ng-for]>
  5949. if (attr.name = eatAttributeName(stream)) {
  5950. // Consumed attribute name. Can be an attribute with name
  5951. // or boolean attribute. The value can be React-like expression
  5952. if (stream.eat(EQUALS)) {
  5953. attr.value = eatAttributeValue(stream);
  5954. } else {
  5955. attr.boolean = true;
  5956. }
  5957. attr.end = stream.pos;
  5958. result.push(attr);
  5959. } else if (isTerminator(stream.peek())) {
  5960. // look for tag terminator in order to skip any other possible characters
  5961. // (maybe junk)
  5962. break;
  5963. } else {
  5964. stream.next();
  5965. }
  5966. }
  5967. return result;
  5968. };
  5969. /**
  5970. * Consumes attribute name from current location
  5971. * @param {StreamReader} stream
  5972. * @return {Token}
  5973. */
  5974. function eatAttributeName(stream) {
  5975. return eatPaired(stream) || token(stream, isAttributeName);
  5976. }
  5977. /**
  5978. * Consumes attribute value from given location
  5979. * @param {StreamReader} stream
  5980. * @return {Token}
  5981. */
  5982. function eatAttributeValue(stream) {
  5983. const start = stream.pos;
  5984. if (Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["eatQuoted"])(stream)) {
  5985. // Should return token that points to unquoted value.
  5986. // Use stream readers’ public API to traverse instead of direct
  5987. // manipulation
  5988. const current = stream.pos;
  5989. let valueStart, valueEnd;
  5990. stream.pos = start;
  5991. stream.next();
  5992. valueStart = stream.start = stream.pos;
  5993. stream.pos = current;
  5994. stream.backUp(1);
  5995. valueEnd = stream.pos;
  5996. const result = token(stream, valueStart, valueEnd);
  5997. stream.pos = current;
  5998. return result;
  5999. }
  6000. return eatPaired(stream) || eatUnquoted(stream);
  6001. }
  6002. /**
  6003. * Check if given code belongs to attribute name.
  6004. * NB some custom HTML variations allow non-default values in name, like `*ngFor`
  6005. * @param {Number} code
  6006. * @return {Boolean}
  6007. */
  6008. function isAttributeName(code) {
  6009. return code !== EQUALS && !isTerminator(code) && !Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isSpace"])(code);
  6010. }
  6011. /**
  6012. * Check if given code is tag terminator
  6013. * @param {Number} code
  6014. * @return {Boolean}
  6015. */
  6016. function isTerminator(code) {
  6017. return code === RIGHT_ANGLE$1 || code === SLASH$1;
  6018. }
  6019. /**
  6020. * Eats unquoted value from stream
  6021. * @param {StreamReader} stream
  6022. * @return {Token}
  6023. */
  6024. function eatUnquoted(stream) {
  6025. return token(stream, isUnquoted);
  6026. }
  6027. /**
  6028. * Check if given character code is valid unquoted value
  6029. * @param {Number} code
  6030. * @return {Boolean}
  6031. */
  6032. function isUnquoted(code) {
  6033. return !isNaN(code) && !Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isQuote"])(code) && !Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isSpace"])(code) && !isTerminator(code);
  6034. }
  6035. const DASH = 45; // -
  6036. const DOT = 46; // .
  6037. const SLASH = 47; // /
  6038. const COLON = 58; // :
  6039. const LEFT_ANGLE = 60; // <
  6040. const RIGHT_ANGLE = 62; // >
  6041. const UNDERSCORE = 95; // _
  6042. /**
  6043. * Parses tag definition (open or close tag) from given stream state
  6044. * @param {StreamReader} stream Content stream reader
  6045. * @return {Object}
  6046. */
  6047. var tag = function(stream) {
  6048. const start = stream.pos;
  6049. if (stream.eat(LEFT_ANGLE)) {
  6050. const model = { type: stream.eat(SLASH) ? 'close' : 'open' };
  6051. if (model.name = eatTagName(stream)) {
  6052. if (model.type !== 'close') {
  6053. model.attributes = eatAttributes(stream);
  6054. stream.eatWhile(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isSpace"]);
  6055. model.selfClosing = stream.eat(SLASH);
  6056. }
  6057. if (stream.eat(RIGHT_ANGLE)) {
  6058. // tag properly closed
  6059. return Object.assign(token(stream, start), model);
  6060. }
  6061. }
  6062. }
  6063. // invalid tag, revert to original position
  6064. stream.pos = start;
  6065. return null;
  6066. };
  6067. /**
  6068. * Eats HTML identifier (tag or attribute name) from given stream
  6069. * @param {StreamReader} stream
  6070. * @return {Token}
  6071. */
  6072. function eatTagName(stream) {
  6073. return token(stream, isTagName);
  6074. }
  6075. /**
  6076. * Check if given character code can be used as HTML/XML tag name
  6077. * @param {Number} code
  6078. * @return {Boolean}
  6079. */
  6080. function isTagName(code) {
  6081. return Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isAlphaNumeric"])(code)
  6082. || code === COLON // colon is used for namespaces
  6083. || code === DOT // in rare cases declarative tag names may have dots in names
  6084. || code === DASH
  6085. || code === UNDERSCORE;
  6086. }
  6087. /**
  6088. * Eats array of character codes from given stream
  6089. * @param {StreamReader} stream
  6090. * @param {Number[]} codes Array of character codes
  6091. * @return {Boolean}
  6092. */
  6093. function eatArray(stream, codes) {
  6094. const start = stream.pos;
  6095. for (let i = 0; i < codes.length; i++) {
  6096. if (!stream.eat(codes[i])) {
  6097. stream.pos = start;
  6098. return false;
  6099. }
  6100. }
  6101. stream.start = start;
  6102. return true;
  6103. }
  6104. /**
  6105. * Consumes section from given string which starts with `open` character codes
  6106. * and ends with `close` character codes
  6107. * @param {StreamReader} stream
  6108. * @param {Number[]} open
  6109. * @param {Number[]} close
  6110. * @return {Boolean} Returns `true` if section was consumed
  6111. */
  6112. function eatSection(stream, open, close, allowUnclosed) {
  6113. const start = stream.pos;
  6114. if (eatArray(stream, open)) {
  6115. // consumed `<!--`, read next until we find ending part or reach the end of input
  6116. while (!stream.eof()) {
  6117. if (eatArray(stream, close)) {
  6118. return true;
  6119. }
  6120. stream.next();
  6121. }
  6122. // unclosed section is allowed
  6123. if (allowUnclosed) {
  6124. return true;
  6125. }
  6126. stream.pos = start;
  6127. return false;
  6128. }
  6129. // unable to find section, revert to initial position
  6130. stream.pos = start;
  6131. return null;
  6132. }
  6133. /**
  6134. * Converts given string into array of character codes
  6135. * @param {String} str
  6136. * @return {Number[]}
  6137. */
  6138. function toCharCodes(str) {
  6139. return str.split('').map(ch => ch.charCodeAt(0));
  6140. }
  6141. const open = toCharCodes('<!--');
  6142. const close = toCharCodes('-->');
  6143. /**
  6144. * Consumes HTML comment from given stream
  6145. * @param {StreamReader} stream
  6146. * @return {Token}
  6147. */
  6148. var comment = function(stream) {
  6149. const start = stream.pos;
  6150. if (eatSection(stream, open, close, true)) {
  6151. const result = token(stream, start);
  6152. result.type = 'comment';
  6153. return result;
  6154. }
  6155. return null;
  6156. };
  6157. const open$1 = toCharCodes('<![CDATA[');
  6158. const close$1 = toCharCodes(']]>');
  6159. /**
  6160. * Consumes CDATA from given stream
  6161. * @param {StreamReader} stream
  6162. * @return {Token}
  6163. */
  6164. var cdata = function(stream) {
  6165. const start = stream.pos;
  6166. if (eatSection(stream, open$1, close$1, true)) {
  6167. const result = token(stream, start);
  6168. result.type = 'cdata';
  6169. return result;
  6170. }
  6171. return null;
  6172. };
  6173. const defaultOptions = {
  6174. /**
  6175. * Expect XML content in searching content. It alters how should-be-empty
  6176. * elements are treated: for example, in XML mode parser will try to locate
  6177. * closing pair for `<br>` tag
  6178. * @type {Boolean}
  6179. */
  6180. xml: false,
  6181. special: ['script', 'style'],
  6182. /**
  6183. * List of elements that should be treated as empty (e.g. without closing tag)
  6184. * in non-XML syntax
  6185. * @type {Array}
  6186. */
  6187. empty: ['img', 'meta', 'link', 'br', 'base', 'hr', 'area', 'wbr','col', 'embed', 'input', 'param', 'source', 'track']
  6188. };
  6189. /**
  6190. * Parses given content into a DOM-like structure
  6191. * @param {String|StreamReader} content
  6192. * @param {Object} options
  6193. * @return {Node}
  6194. */
  6195. function parse(content, options) {
  6196. options = Object.assign({}, defaultOptions, options);
  6197. const stream = typeof content === 'string'
  6198. ? new _emmetio_stream_reader__WEBPACK_IMPORTED_MODULE_0__["default"](content)
  6199. : content;
  6200. const root = new Node(stream, 'root');
  6201. const empty = new Set(options.empty);
  6202. const special = options.special.reduce(
  6203. (map, name) => map.set(name, toCharCodes(`</${name}>`)), new Map());
  6204. const isEmpty = (token, name) =>
  6205. token.selfClosing || (!options.xml && empty.has(name));
  6206. let m, node, name, stack = [root];
  6207. while (!stream.eof()) {
  6208. if (m = match(stream)) {
  6209. name = getName(m);
  6210. if (m.type === 'open') {
  6211. // opening tag
  6212. node = new Node(stream, 'tag', m);
  6213. last(stack).addChild(node);
  6214. if (special.has(name)) {
  6215. node.close = consumeSpecial(stream, special.get(name));
  6216. } else if (!isEmpty(m, name)) {
  6217. stack.push(node);
  6218. }
  6219. } else if (m.type === 'close') {
  6220. // closing tag, find it’s matching opening tag
  6221. for (let i = stack.length - 1; i > 0; i--) {
  6222. if (stack[i].name.toLowerCase() === name) {
  6223. stack[i].close = m;
  6224. stack = stack.slice(0, i);
  6225. break;
  6226. }
  6227. }
  6228. } else {
  6229. last(stack).addChild(new Node(stream, m.type, m));
  6230. }
  6231. } else {
  6232. stream.next();
  6233. }
  6234. }
  6235. return root;
  6236. }
  6237. /**
  6238. * Matches known token in current state of given stream
  6239. * @param {ContentStreamReader} stream
  6240. * @return {Token}
  6241. */
  6242. function match(stream) {
  6243. // fast-path optimization: check for `<` code
  6244. if (stream.peek() === 60 /* < */) {
  6245. return comment(stream) || cdata(stream) || tag(stream);
  6246. }
  6247. }
  6248. /**
  6249. * @param {StreamReader} stream
  6250. * @param {Number[]} codes
  6251. * @return {Token}
  6252. */
  6253. function consumeSpecial(stream, codes) {
  6254. const start = stream.pos;
  6255. let m;
  6256. while (!stream.eof()) {
  6257. if (eatArray(stream, codes)) {
  6258. stream.pos = stream.start;
  6259. return tag(stream);
  6260. }
  6261. stream.next();
  6262. }
  6263. stream.pos = start;
  6264. return null;
  6265. }
  6266. /**
  6267. * Returns name of given matched token
  6268. * @param {Token} tag
  6269. * @return {String}
  6270. */
  6271. function getName(tag$$1) {
  6272. return tag$$1.name ? tag$$1.name.value.toLowerCase() : `#${tag$$1.type}`;
  6273. }
  6274. function last(arr) {
  6275. return arr[arr.length - 1];
  6276. }
  6277. /* harmony default export */ __webpack_exports__["default"] = (parse);
  6278. /***/ }),
  6279. /* 34 */
  6280. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  6281. "use strict";
  6282. __webpack_require__.r(__webpack_exports__);
  6283. /**
  6284. * A streaming, character code-based string reader
  6285. */
  6286. class StreamReader {
  6287. constructor(string, start, end) {
  6288. if (end == null && typeof string === 'string') {
  6289. end = string.length;
  6290. }
  6291. this.string = string;
  6292. this.pos = this.start = start || 0;
  6293. this.end = end;
  6294. }
  6295. /**
  6296. * Returns true only if the stream is at the end of the file.
  6297. * @returns {Boolean}
  6298. */
  6299. eof() {
  6300. return this.pos >= this.end;
  6301. }
  6302. /**
  6303. * Creates a new stream instance which is limited to given `start` and `end`
  6304. * range. E.g. its `eof()` method will look at `end` property, not actual
  6305. * stream end
  6306. * @param {Point} start
  6307. * @param {Point} end
  6308. * @return {StreamReader}
  6309. */
  6310. limit(start, end) {
  6311. return new this.constructor(this.string, start, end);
  6312. }
  6313. /**
  6314. * Returns the next character code in the stream without advancing it.
  6315. * Will return NaN at the end of the file.
  6316. * @returns {Number}
  6317. */
  6318. peek() {
  6319. return this.string.charCodeAt(this.pos);
  6320. }
  6321. /**
  6322. * Returns the next character in the stream and advances it.
  6323. * Also returns <code>undefined</code> when no more characters are available.
  6324. * @returns {Number}
  6325. */
  6326. next() {
  6327. if (this.pos < this.string.length) {
  6328. return this.string.charCodeAt(this.pos++);
  6329. }
  6330. }
  6331. /**
  6332. * `match` can be a character code or a function that takes a character code
  6333. * and returns a boolean. If the next character in the stream 'matches'
  6334. * the given argument, it is consumed and returned.
  6335. * Otherwise, `false` is returned.
  6336. * @param {Number|Function} match
  6337. * @returns {Boolean}
  6338. */
  6339. eat(match) {
  6340. const ch = this.peek();
  6341. const ok = typeof match === 'function' ? match(ch) : ch === match;
  6342. if (ok) {
  6343. this.next();
  6344. }
  6345. return ok;
  6346. }
  6347. /**
  6348. * Repeatedly calls <code>eat</code> with the given argument, until it
  6349. * fails. Returns <code>true</code> if any characters were eaten.
  6350. * @param {Object} match
  6351. * @returns {Boolean}
  6352. */
  6353. eatWhile(match) {
  6354. const start = this.pos;
  6355. while (!this.eof() && this.eat(match)) {}
  6356. return this.pos !== start;
  6357. }
  6358. /**
  6359. * Backs up the stream n characters. Backing it up further than the
  6360. * start of the current token will cause things to break, so be careful.
  6361. * @param {Number} n
  6362. */
  6363. backUp(n) {
  6364. this.pos -= (n || 1);
  6365. }
  6366. /**
  6367. * Get the string between the start of the current token and the
  6368. * current stream position.
  6369. * @returns {String}
  6370. */
  6371. current() {
  6372. return this.substring(this.start, this.pos);
  6373. }
  6374. /**
  6375. * Returns substring for given range
  6376. * @param {Number} start
  6377. * @param {Number} [end]
  6378. * @return {String}
  6379. */
  6380. substring(start, end) {
  6381. return this.string.slice(start, end);
  6382. }
  6383. /**
  6384. * Creates error object with current stream state
  6385. * @param {String} message
  6386. * @return {Error}
  6387. */
  6388. error(message) {
  6389. const err = new Error(`${message} at char ${this.pos + 1}`);
  6390. err.originalMessage = message;
  6391. err.pos = this.pos;
  6392. err.string = this.string;
  6393. return err;
  6394. }
  6395. }
  6396. /* harmony default export */ __webpack_exports__["default"] = (StreamReader);
  6397. /***/ }),
  6398. /* 35 */
  6399. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  6400. "use strict";
  6401. __webpack_require__.r(__webpack_exports__);
  6402. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "eatQuoted", function() { return eatQuoted; });
  6403. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isQuote", function() { return isQuote; });
  6404. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isAlpha", function() { return isAlpha; });
  6405. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNumber", function() { return isNumber; });
  6406. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isAlphaNumeric", function() { return isAlphaNumeric; });
  6407. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSpace", function() { return isSpace; });
  6408. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isWhiteSpace", function() { return isWhiteSpace; });
  6409. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "eatPair", function() { return eatPair; });
  6410. /**
  6411. * Methods for consuming quoted values
  6412. */
  6413. const SINGLE_QUOTE = 39; // '
  6414. const DOUBLE_QUOTE = 34; // "
  6415. const defaultOptions = {
  6416. escape: 92, // \ character
  6417. throws: false
  6418. };
  6419. /**
  6420. * Consumes 'single' or "double"-quoted string from given string, if possible
  6421. * @param {StreamReader} stream
  6422. * @param {Number} options.escape A character code of quote-escape symbol
  6423. * @param {Boolean} options.throws Throw error if quotes string can’t be properly consumed
  6424. * @return {Boolean} `true` if quoted string was consumed. The contents
  6425. * of quoted string will be availabe as `stream.current()`
  6426. */
  6427. var eatQuoted = function(stream, options) {
  6428. options = options ? Object.assign({}, defaultOptions, options) : defaultOptions;
  6429. const start = stream.pos;
  6430. const quote = stream.peek();
  6431. if (stream.eat(isQuote)) {
  6432. while (!stream.eof()) {
  6433. switch (stream.next()) {
  6434. case quote:
  6435. stream.start = start;
  6436. return true;
  6437. case options.escape:
  6438. stream.next();
  6439. break;
  6440. }
  6441. }
  6442. // If we’re here then stream wasn’t properly consumed.
  6443. // Revert stream and decide what to do
  6444. stream.pos = start;
  6445. if (options.throws) {
  6446. throw stream.error('Unable to consume quoted string');
  6447. }
  6448. }
  6449. return false;
  6450. };
  6451. function isQuote(code) {
  6452. return code === SINGLE_QUOTE || code === DOUBLE_QUOTE;
  6453. }
  6454. /**
  6455. * Check if given code is a number
  6456. * @param {Number} code
  6457. * @return {Boolean}
  6458. */
  6459. function isNumber(code) {
  6460. return code > 47 && code < 58;
  6461. }
  6462. /**
  6463. * Check if given character code is alpha code (letter through A to Z)
  6464. * @param {Number} code
  6465. * @param {Number} [from]
  6466. * @param {Number} [to]
  6467. * @return {Boolean}
  6468. */
  6469. function isAlpha(code, from, to) {
  6470. from = from || 65; // A
  6471. to = to || 90; // Z
  6472. code &= ~32; // quick hack to convert any char code to uppercase char code
  6473. return code >= from && code <= to;
  6474. }
  6475. /**
  6476. * Check if given character code is alpha-numeric (letter through A to Z or number)
  6477. * @param {Number} code
  6478. * @return {Boolean}
  6479. */
  6480. function isAlphaNumeric(code) {
  6481. return isNumber(code) || isAlpha(code);
  6482. }
  6483. function isWhiteSpace(code) {
  6484. return code === 32 /* space */
  6485. || code === 9 /* tab */
  6486. || code === 160; /* non-breaking space */
  6487. }
  6488. /**
  6489. * Check if given character code is a space
  6490. * @param {Number} code
  6491. * @return {Boolean}
  6492. */
  6493. function isSpace(code) {
  6494. return isWhiteSpace(code)
  6495. || code === 10 /* LF */
  6496. || code === 13; /* CR */
  6497. }
  6498. const defaultOptions$1 = {
  6499. escape: 92, // \ character
  6500. throws: false
  6501. };
  6502. /**
  6503. * Eats paired characters substring, for example `(foo)` or `[bar]`
  6504. * @param {StreamReader} stream
  6505. * @param {Number} open Character code of pair openinig
  6506. * @param {Number} close Character code of pair closing
  6507. * @param {Object} [options]
  6508. * @return {Boolean} Returns `true` if chacarter pair was successfully
  6509. * consumed, it’s content will be available as `stream.current()`
  6510. */
  6511. function eatPair(stream, open, close, options) {
  6512. options = options ? Object.assign({}, defaultOptions$1, options) : defaultOptions$1;
  6513. const start = stream.pos;
  6514. if (stream.eat(open)) {
  6515. let stack = 1, ch;
  6516. while (!stream.eof()) {
  6517. if (eatQuoted(stream, options)) {
  6518. continue;
  6519. }
  6520. ch = stream.next();
  6521. if (ch === open) {
  6522. stack++;
  6523. } else if (ch === close) {
  6524. stack--;
  6525. if (!stack) {
  6526. stream.start = start;
  6527. return true;
  6528. }
  6529. } else if (ch === options.escape) {
  6530. stream.next();
  6531. }
  6532. }
  6533. // If we’re here then paired character can’t be consumed
  6534. stream.pos = start;
  6535. if (options.throws) {
  6536. throw stream.error(`Unable to find matching pair for ${String.fromCharCode(open)}`);
  6537. }
  6538. }
  6539. return false;
  6540. }
  6541. /***/ }),
  6542. /* 36 */
  6543. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  6544. "use strict";
  6545. __webpack_require__.r(__webpack_exports__);
  6546. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lexer", function() { return lexer; });
  6547. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Token", function() { return Token; });
  6548. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "any", function() { return any; });
  6549. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selector", function() { return selector; });
  6550. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "value", function() { return value; });
  6551. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "keyword", function() { return keyword; });
  6552. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "variable", function() { return variable; });
  6553. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "formatting", function() { return formatting; });
  6554. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "comment", function() { return comment; });
  6555. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "whitespace", function() { return whitespace; });
  6556. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ident", function() { return ident; });
  6557. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "string", function() { return string; });
  6558. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "url", function() { return url; });
  6559. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "interpolation", function() { return interpolation; });
  6560. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "backtick", function() { return backtick; });
  6561. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseMediaExpression", function() { return parseMediaExpression; });
  6562. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parsePropertyName", function() { return parsePropertyName; });
  6563. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parsePropertyValue", function() { return parsePropertyValue; });
  6564. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseSelector", function() { return parseSelector; });
  6565. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createProperty", function() { return createProperty; });
  6566. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createRule", function() { return createRule; });
  6567. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createAtRule", function() { return createAtRule; });
  6568. /* harmony import */ var _emmetio_stream_reader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(34);
  6569. /* harmony import */ var _emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35);
  6570. /**
  6571. * Abstract container that contains nested nodes or other containers
  6572. */
  6573. class Node {
  6574. constructor(type) {
  6575. this.type = type;
  6576. this.children = [];
  6577. this.parent = null;
  6578. }
  6579. get firstChild() {
  6580. return this.children[0];
  6581. }
  6582. get nextSibling() {
  6583. const ix = this.index();
  6584. return ix !== -1 ? this.parent.children[ix + 1] : null;
  6585. }
  6586. get previousSibling() {
  6587. const ix = this.index();
  6588. return ix !== -1 ? this.parent.children[ix - 1] : null;
  6589. }
  6590. /**
  6591. * Returns current element’s index in parent list of child nodes
  6592. * @return {Number}
  6593. */
  6594. index() {
  6595. return this.parent ? this.parent.children.indexOf(this) : -1;
  6596. }
  6597. /**
  6598. * Adds given node as a child
  6599. * @param {Node} node
  6600. * @return {Node} Current node
  6601. */
  6602. add(node) {
  6603. if (node) {
  6604. node.remove();
  6605. this.children.push(node);
  6606. node.parent = this;
  6607. }
  6608. return this;
  6609. }
  6610. /**
  6611. * Removes current node from its parent
  6612. * @return {Node} Current node
  6613. */
  6614. remove() {
  6615. if (this.parent) {
  6616. const ix = this.index();
  6617. if (ix !== -1) {
  6618. this.parent.children.splice(ix, 1);
  6619. this.parent = null;
  6620. }
  6621. }
  6622. return this;
  6623. }
  6624. }
  6625. class Stylesheet extends Node {
  6626. constructor() {
  6627. super('stylesheet');
  6628. this.comments = [];
  6629. }
  6630. /**
  6631. * Returns node’s start position in stream
  6632. * @return {*}
  6633. */
  6634. get start() {
  6635. const node = this.firstChild;
  6636. return node && node.start;
  6637. }
  6638. /**
  6639. * Returns node’s end position in stream
  6640. * @return {*}
  6641. */
  6642. get end() {
  6643. const node = this.children[this.children.length - 1];
  6644. return node && node.end;
  6645. }
  6646. /**
  6647. * Adds comment token into a list.
  6648. * This somewhat awkward feature is required to properly detect comment
  6649. * ranges. Specifically, in Atom: it’s API provides scopes limited to current
  6650. * line only
  6651. * @param {Token} token
  6652. */
  6653. addComment(token) {
  6654. this.comments.push(token);
  6655. }
  6656. }
  6657. /**
  6658. * Removes tokens that matches given criteria from start and end of given list
  6659. * @param {Token[]} tokens
  6660. * @return {Token[]}
  6661. */
  6662. function trimTokens(tokens) {
  6663. tokens = tokens.slice();
  6664. let len;
  6665. while (len !== tokens.length) {
  6666. len = tokens.length;
  6667. if (isFormattingToken(tokens[0])) {
  6668. tokens.shift();
  6669. }
  6670. if (isFormattingToken(last(tokens))) {
  6671. tokens.pop();
  6672. }
  6673. }
  6674. return tokens;
  6675. }
  6676. /**
  6677. * Trims formatting tokens (whitespace and comments) from the beginning and end
  6678. * of given token list
  6679. * @param {Token[]} tokens
  6680. * @return {Token[]}
  6681. */
  6682. function trimFormatting(tokens) {
  6683. return trimTokens(tokens, isFormattingToken);
  6684. }
  6685. /**
  6686. * Check if given token is a formatting one (whitespace or comment)
  6687. * @param {Token} token
  6688. * @return {Boolean}
  6689. */
  6690. function isFormattingToken(token) {
  6691. const type = token && token.type;
  6692. return type === 'whitespace' || type === 'comment';
  6693. }
  6694. /**
  6695. * Consumes string char-by-char from given stream
  6696. * @param {StreamReader} stream
  6697. * @param {String} string
  6698. * @return {Boolean} Returns `true` if string was completely consumed
  6699. */
  6700. function eatString(stream, string) {
  6701. const start = stream.pos;
  6702. for (let i = 0, il = string.length; i < il; i++) {
  6703. if (!stream.eat(string.charCodeAt(i))) {
  6704. stream.pos = start;
  6705. return false;
  6706. }
  6707. }
  6708. return true;
  6709. }
  6710. function consume(stream, match) {
  6711. const start = stream.pos;
  6712. if (stream.eat(match)) {
  6713. stream.start = start;
  6714. return true;
  6715. }
  6716. return false;
  6717. }
  6718. function consumeWhile(stream, match) {
  6719. const start = stream.pos;
  6720. if (stream.eatWhile(match)) {
  6721. stream.start = start;
  6722. return true;
  6723. }
  6724. return false;
  6725. }
  6726. function last(arr) {
  6727. return arr[arr.length - 1];
  6728. }
  6729. function valueOf(token) {
  6730. return token && token.valueOf();
  6731. }
  6732. /**
  6733. * A structure describing text fragment in content stream. It may contain
  6734. * other sub-fragments (also tokens) that represent current fragments’ logical
  6735. * parts
  6736. */
  6737. class Token {
  6738. /**
  6739. * @param {StreamReader} stream
  6740. * @param {String} type Token type
  6741. * @param {Object} [start] Tokens’ start position in `stream`
  6742. * @param {Object} [end] Tokens’ end position in `stream`
  6743. */
  6744. constructor(stream, type, start, end) {
  6745. this.stream = stream;
  6746. this.start = start != null ? start : stream.start;
  6747. this.end = end != null ? end : stream.pos;
  6748. this.type = type;
  6749. this._props = null;
  6750. this._value = null;
  6751. this._items = null;
  6752. }
  6753. get size() {
  6754. return this._items ? this._items.length : 0;
  6755. }
  6756. get items() {
  6757. return this._items;
  6758. }
  6759. clone(start, end) {
  6760. return new this.constructor(this.stream, this.type,
  6761. start != null ? start : this.start,
  6762. end != null ? end : this.end);
  6763. }
  6764. add(item) {
  6765. if (Array.isArray(item)) {
  6766. for (let i = 0, il = item.length; i < il; i++) {
  6767. this.add(item[i]);
  6768. }
  6769. } else if (item) {
  6770. if (!this._items) {
  6771. this._items = [item];
  6772. } else {
  6773. this._items.push(item);
  6774. }
  6775. }
  6776. return this;
  6777. }
  6778. remove(item) {
  6779. if (this._items) {
  6780. const ix = this._items.indexOf(item);
  6781. if (ix !== -1 ) {
  6782. this._items.splice(ix, 1);
  6783. }
  6784. }
  6785. return this;
  6786. }
  6787. item(i) {
  6788. const size = this.size;
  6789. return this._items && this._items[(size + i) % size];
  6790. }
  6791. limit() {
  6792. return this.stream.limit(this.start, this.end);
  6793. }
  6794. slice(from, to) {
  6795. const token = this.clone();
  6796. const items = this._items && this._items.slice(from, to);
  6797. if (items && items.length) {
  6798. token.start = items[0].start;
  6799. token.end = items[items.length - 1].end;
  6800. token.add(items);
  6801. } else if (items) {
  6802. // Empty token
  6803. token.start = token.end;
  6804. }
  6805. return token;
  6806. }
  6807. property(name, value) {
  6808. if (typeof value !== 'undefined') {
  6809. // set property value
  6810. if (!this._props) {
  6811. this._props = {};
  6812. }
  6813. this._props[name] = value;
  6814. }
  6815. return this._props && this._props[name];
  6816. }
  6817. /**
  6818. * Returns token textual representation
  6819. * @return {String}
  6820. */
  6821. toString() {
  6822. return `${this.valueOf()} [${this.start}, ${this.end}] (${this.type})`;
  6823. }
  6824. valueOf() {
  6825. if (this._value === null) {
  6826. this._value = this.stream.substring(this.start, this.end);
  6827. }
  6828. return this._value;
  6829. }
  6830. }
  6831. const COMMA = 44; // ,
  6832. const PROP_DELIMITER$1 = 58; // :
  6833. const PROP_TERMINATOR$1 = 59; // ;
  6834. const RULE_START$1 = 123; // {
  6835. const RULE_END$1 = 125; // }
  6836. const types = new Map()
  6837. .set(COMMA, 'comma')
  6838. .set(PROP_DELIMITER$1, 'propertyDelimiter')
  6839. .set(PROP_TERMINATOR$1, 'propertyTerminator')
  6840. .set(RULE_START$1, 'ruleStart')
  6841. .set(RULE_END$1, 'ruleEnd');
  6842. /**
  6843. * Consumes separator token from given string
  6844. */
  6845. function separator(stream) {
  6846. if (isSeparator(stream.peek())) {
  6847. const start = stream.pos;
  6848. const type = types.get(stream.next());
  6849. const token = new Token(stream, 'separator', start);
  6850. token.property('type', type);
  6851. return token;
  6852. }
  6853. }
  6854. function isSeparator(code) {
  6855. return code === COMMA
  6856. || code === PROP_DELIMITER$1 || code === PROP_TERMINATOR$1
  6857. || code === RULE_START$1 || code === RULE_END$1;
  6858. }
  6859. const ARGUMENTS_START = 40; // (
  6860. const ARGUMENTS_END = 41; // )
  6861. var args = function(stream, tokenConsumer) {
  6862. if (stream.peek() === ARGUMENTS_START) {
  6863. const start = stream.pos;
  6864. stream.next();
  6865. const tokens = [];
  6866. let t;
  6867. // in LESS, it’s possible to separate arguments list either by `;` or `,`.
  6868. // In first case, we should keep comma-separated item as a single argument
  6869. let usePropTerminator = false;
  6870. while (!stream.eof()) {
  6871. if (isUnexpectedTerminator(stream.peek()) || stream.eat(ARGUMENTS_END)) {
  6872. break;
  6873. }
  6874. t = tokenConsumer(stream);
  6875. if (!t) {
  6876. break;
  6877. }
  6878. if (isSemicolonSeparator(t)) {
  6879. usePropTerminator = true;
  6880. }
  6881. tokens.push(t);
  6882. }
  6883. stream.start = start;
  6884. return createArgumentList(stream, tokens, usePropTerminator);
  6885. }
  6886. };
  6887. function isUnexpectedTerminator(code) {
  6888. return code === RULE_START$1 || code === RULE_END$1;
  6889. }
  6890. function createArgumentList(stream, tokens, usePropTerminator) {
  6891. const argsToken = new Token(stream, 'arguments');
  6892. const isSeparator = usePropTerminator ? isSemicolonSeparator : isCommaSeparator;
  6893. let arg = [];
  6894. for (let i = 0, il = tokens.length, token; i < il; i++) {
  6895. token = tokens[i];
  6896. if (isSeparator(token)) {
  6897. argsToken.add(createArgument(stream, arg) || createEmptyArgument(stream, token.start));
  6898. arg.length = 0;
  6899. } else {
  6900. arg.push(token);
  6901. }
  6902. }
  6903. if (arg.length) {
  6904. argsToken.add(createArgument(stream, arg));
  6905. }
  6906. return argsToken;
  6907. }
  6908. function createArgument(stream, tokens) {
  6909. tokens = trimFormatting(tokens);
  6910. if (tokens.length) {
  6911. const arg = new Token(stream, 'argument', tokens[0].start, last(tokens).end);
  6912. for (let i = 0; i < tokens.length; i++) {
  6913. arg.add(tokens[i]);
  6914. }
  6915. return arg;
  6916. }
  6917. }
  6918. function createEmptyArgument(stream, pos) {
  6919. const token = new Token(stream, 'argument', pos, pos);
  6920. token.property('empty', true);
  6921. return token;
  6922. }
  6923. function isCommaSeparator(token) {
  6924. return token.property('type') === 'comma';
  6925. }
  6926. function isSemicolonSeparator(token) {
  6927. return token.property('type') === 'propertyTerminator';
  6928. }
  6929. const HYPHEN = 45;
  6930. const UNDERSCORE = 95;
  6931. function ident(stream) {
  6932. return eatIdent(stream) && new Token(stream, 'ident');
  6933. }
  6934. function eatIdent(stream) {
  6935. const start = stream.pos;
  6936. stream.eat(HYPHEN);
  6937. if (stream.eat(isIdentStart)) {
  6938. stream.eatWhile(isIdent);
  6939. stream.start = start;
  6940. return true;
  6941. }
  6942. stream.pos = start;
  6943. return false;
  6944. }
  6945. function isIdentStart(code) {
  6946. return code === UNDERSCORE || code === HYPHEN || Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isAlpha"])(code) || code >= 128;
  6947. }
  6948. function isIdent(code) {
  6949. return Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(code) || isIdentStart(code);
  6950. }
  6951. function prefixed(stream, tokenType, prefix, body, allowEmptyBody) {
  6952. const start = stream.pos;
  6953. if (stream.eat(prefix)) {
  6954. const bodyToken = body(stream, start);
  6955. if (bodyToken || allowEmptyBody) {
  6956. stream.start = start;
  6957. return new Token(stream, tokenType, start).add(bodyToken);
  6958. }
  6959. }
  6960. stream.pos = start;
  6961. }
  6962. const AT = 64; // @
  6963. /**
  6964. * Consumes at-keyword from given stream
  6965. */
  6966. function atKeyword(stream) {
  6967. return prefixed(stream, 'at-keyword', AT, ident);
  6968. }
  6969. const HASH = 35; // #
  6970. const AT$1 = 64; // @
  6971. /**
  6972. * Consumes interpolation token, e.g. `#{expression}`
  6973. * @param {StreamReader} stream
  6974. * @param {Function} tokenConsumer
  6975. * @return {Token}
  6976. */
  6977. function interpolation(stream, tokenConsumer) {
  6978. const start = stream.pos;
  6979. tokenConsumer = tokenConsumer || defaultTokenConsumer;
  6980. if ((stream.eat(HASH) || stream.eat(AT$1)) && stream.eat(RULE_START$1)) {
  6981. const container = new Token(stream, 'interpolation', start);
  6982. let stack = 1, token;
  6983. while (!stream.eof()) {
  6984. if (stream.eat(RULE_START$1)) {
  6985. stack++;
  6986. } else if (stream.eat(RULE_END$1)) {
  6987. stack--;
  6988. if (!stack) {
  6989. container.end = stream.pos;
  6990. return container;
  6991. }
  6992. } else if (token = tokenConsumer(stream)) {
  6993. container.add(token);
  6994. } else {
  6995. break;
  6996. }
  6997. }
  6998. }
  6999. stream.pos = start;
  7000. }
  7001. function eatInterpolation(stream) {
  7002. const start = stream.pos;
  7003. if ((stream.eat(HASH) || stream.eat(AT$1)) && Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["eatPair"])(stream, RULE_START$1, RULE_END$1)) {
  7004. stream.start = start;
  7005. return true;
  7006. }
  7007. stream.pos = start;
  7008. return false;
  7009. }
  7010. function defaultTokenConsumer(stream) {
  7011. const start = stream.pos;
  7012. while (!stream.eof()) {
  7013. if (stream.peek() === RULE_END$1) {
  7014. break;
  7015. }
  7016. eatString$1(stream) || stream.next();
  7017. }
  7018. if (start !== stream.pos) {
  7019. return new Token(stream, 'expression', start);
  7020. }
  7021. }
  7022. /**
  7023. * Consumes quoted string from current string and returns token with consumed
  7024. * data or `null`, if string wasn’t consumed
  7025. * @param {StreamReader} stream
  7026. * @return {StringToken}
  7027. */
  7028. function string(stream) {
  7029. return eatString$1(stream, true);
  7030. }
  7031. function eatString$1(stream, asToken) {
  7032. let ch = stream.peek(), pos, tokens, token;
  7033. if (Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isQuote"])(ch)) {
  7034. stream.start = stream.pos;
  7035. stream.next();
  7036. const quote = ch;
  7037. const valueStart = stream.pos;
  7038. while (!stream.eof()) {
  7039. pos = stream.pos;
  7040. if (stream.eat(quote) || stream.eat(isNewline)) {
  7041. // found end of string or newline without preceding '\',
  7042. // which is not allowed (don’t throw error, for now)
  7043. break;
  7044. } else if (stream.eat(92 /* \ */)) {
  7045. // backslash allows newline in string
  7046. stream.eat(isNewline);
  7047. } else if (asToken && (token = interpolation(stream))) {
  7048. if (!tokens) {
  7049. tokens = [token];
  7050. } else {
  7051. tokens.push(token);
  7052. }
  7053. }
  7054. stream.next();
  7055. }
  7056. // Either reached EOF or explicitly stopped at string end
  7057. // NB use extra `asToken` param to return boolean instead of token to reduce
  7058. // memory allocations and improve performance
  7059. if (asToken) {
  7060. const token = new Token(stream, 'string');
  7061. const inner = new Token(stream, 'unquoted', valueStart, pos);
  7062. inner.add(tokens);
  7063. token.add(inner);
  7064. token.property('quote', quote);
  7065. return token;
  7066. }
  7067. return true;
  7068. }
  7069. return false;
  7070. }
  7071. function isNewline(code) {
  7072. return code === 10 /* LF */ || code === 13 /* CR */;
  7073. }
  7074. const ASTERISK = 42;
  7075. const SLASH = 47;
  7076. /**
  7077. * Consumes comment from given stream: either multi-line or single-line
  7078. * @param {StreamReader} stream
  7079. * @return {CommentToken}
  7080. */
  7081. var comment = function(stream) {
  7082. return singleLineComment(stream) || multiLineComment(stream);
  7083. };
  7084. function singleLineComment(stream) {
  7085. if (eatSingleLineComment(stream)) {
  7086. const token = new Token(stream, 'comment');
  7087. token.property('type', 'single-line');
  7088. return token;
  7089. }
  7090. }
  7091. function multiLineComment(stream) {
  7092. if (eatMultiLineComment(stream)) {
  7093. const token = new Token(stream, 'comment');
  7094. token.property('type', 'multiline');
  7095. return token;
  7096. }
  7097. }
  7098. function eatComment(stream) {
  7099. return eatSingleLineComment(stream) || eatMultiLineComment(stream);
  7100. }
  7101. function eatSingleLineComment(stream) {
  7102. const start = stream.pos;
  7103. if (stream.eat(SLASH) && stream.eat(SLASH)) {
  7104. // single-line comment, consume till the end of line
  7105. stream.start = start;
  7106. while (!stream.eof()) {
  7107. if (isLineBreak(stream.next())) {
  7108. break;
  7109. }
  7110. }
  7111. return true;
  7112. }
  7113. stream.pos = start;
  7114. return false;
  7115. }
  7116. function eatMultiLineComment(stream) {
  7117. const start = stream.pos;
  7118. if (stream.eat(SLASH) && stream.eat(ASTERISK)) {
  7119. while (!stream.eof()) {
  7120. if (stream.next() === ASTERISK && stream.eat(SLASH)) {
  7121. break;
  7122. }
  7123. }
  7124. stream.start = start;
  7125. return true;
  7126. }
  7127. stream.pos = start;
  7128. return false;
  7129. }
  7130. function isLineBreak(code) {
  7131. return code === 10 /* LF */ || code === 13 /* CR */;
  7132. }
  7133. /**
  7134. * Consumes white-space tokens from given stream
  7135. */
  7136. function whitespace(stream) {
  7137. return eatWhitespace(stream) && new Token(stream, 'whitespace');
  7138. }
  7139. function eatWhitespace(stream) {
  7140. return consumeWhile(stream, _emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isSpace"]);
  7141. }
  7142. const ATTR_START = 91; // [
  7143. const ATTR_END = 93; // ]
  7144. /**
  7145. * Consumes attribute from given string, e.g. value between [ and ]
  7146. * @param {StreamReader} stream
  7147. * @return {AttributeToken}
  7148. */
  7149. function eatAttribuite(stream) {
  7150. const start = stream.pos;
  7151. if (stream.eat(ATTR_START)) {
  7152. skip(stream);
  7153. const name = ident(stream);
  7154. skip(stream);
  7155. const op = operator(stream);
  7156. skip(stream);
  7157. const value = string(stream) || ident(stream);
  7158. skip(stream);
  7159. stream.eat(ATTR_END);
  7160. return new Token(stream, 'attribute', start).add(name).add(op).add(value);
  7161. }
  7162. }
  7163. function skip(stream) {
  7164. while (!stream.eof()) {
  7165. if (!eatWhitespace(stream) && !eatComment(stream)) {
  7166. return true;
  7167. }
  7168. }
  7169. }
  7170. function operator(stream) {
  7171. return consumeWhile(stream, isOperator) && new Token(stream, 'operator');
  7172. }
  7173. function isOperator(code) {
  7174. return code === 126 /* ~ */
  7175. || code === 124 /* | */
  7176. || code === 94 /* ^ */
  7177. || code === 36 /* $ */
  7178. || code === 42 /* * */
  7179. || code === 61; /* = */
  7180. }
  7181. const BACKTICK = 96; // `
  7182. /**
  7183. * Consumes backtick token, e.g. `...`
  7184. * @param {StreamReader} stream
  7185. * @param {Function} tokenConsumer
  7186. * @return {Token}
  7187. */
  7188. function backtick(stream) {
  7189. if (eatBacktick(stream)) {
  7190. return new Token(stream, 'backtick');
  7191. }
  7192. }
  7193. function eatBacktick(stream) {
  7194. const start = stream.pos;
  7195. if (Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["eatPair"])(stream, BACKTICK, BACKTICK)) {
  7196. stream.start = start;
  7197. return true;
  7198. }
  7199. return false;
  7200. }
  7201. const CLASS = 46; // .
  7202. /**
  7203. * Consumes class fragment from given stream, e.g. `.foo`
  7204. * @param {StreamReader} stream
  7205. * @return {ClassToken}
  7206. */
  7207. function className(stream) {
  7208. return prefixed(stream, 'class', CLASS, ident);
  7209. }
  7210. const ADJACENT_SIBLING = 43; // +
  7211. const GENERAL_SIBLING = 126; // ~
  7212. const CHILD = 62; // >
  7213. const NESTING = 38; // &
  7214. const types$1 = {
  7215. [ADJACENT_SIBLING]: 'adjacentSibling',
  7216. [GENERAL_SIBLING]: 'generalSibling',
  7217. [CHILD]: 'child',
  7218. [NESTING]: 'nesting'
  7219. };
  7220. /**
  7221. * Consumes combinator token from given string
  7222. */
  7223. var combinator = function(stream) {
  7224. if (isCombinator(stream.peek())) {
  7225. const start = stream.pos;
  7226. const type = types$1[stream.next()];
  7227. const token = new Token(stream, 'combinator', start);
  7228. token.property('type', type);
  7229. return token;
  7230. }
  7231. };
  7232. function isCombinator(code) {
  7233. return code === ADJACENT_SIBLING || code === GENERAL_SIBLING
  7234. || code === NESTING || code === CHILD;
  7235. }
  7236. const HASH$1 = 35;
  7237. function hash(stream) {
  7238. return prefixed(stream, 'hash', HASH$1, hashValue, true);
  7239. }
  7240. function hashValue(stream) {
  7241. if (eatHashValue(stream)) {
  7242. return new Token(stream, 'hash-value');
  7243. }
  7244. }
  7245. function eatHashValue(stream) {
  7246. return consumeWhile(stream, isHashValue);
  7247. }
  7248. function isHashValue(code) {
  7249. return Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(code) || Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isAlpha"])(code, 65 /* A */, 70 /* F */)
  7250. || code === 95 /* _ */ || code === 45 /* - */
  7251. || code > 128; /* non-ASCII */
  7252. }
  7253. const ID = 35; // #
  7254. /**
  7255. * Consumes id fragment from given stream, e.g. `#foo`
  7256. * @param {StreamReader} stream
  7257. * @return {Token}
  7258. */
  7259. function id(stream) {
  7260. return prefixed(stream, 'id', ID, ident);
  7261. }
  7262. const IMPORTANT = 33; // !
  7263. /**
  7264. * Consumes !important token
  7265. * @param {StreamReader} stream
  7266. * @return {Token}
  7267. */
  7268. function important(stream) {
  7269. return prefixed(stream, 'important', IMPORTANT, ident);
  7270. }
  7271. const DOT = 46; // .
  7272. /**
  7273. * Consumes number from given string, e.g. `10px`
  7274. * @param {StreamReader} stream
  7275. * @return {NumberToken}
  7276. */
  7277. function number(stream) {
  7278. if (eatNumericPart(stream)) {
  7279. const start = stream.start;
  7280. const num = new Token(stream, 'value');
  7281. const unit = eatUnitPart(stream) ? new Token(stream, 'unit') : null;
  7282. return new Token(stream, 'number', start).add(num).add(unit);
  7283. }
  7284. }
  7285. function eatNumericPart(stream) {
  7286. const start = stream.pos;
  7287. stream.eat(isOperator$1);
  7288. if (stream.eatWhile(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isNumber"])) {
  7289. stream.start = start;
  7290. const decimalEnd = stream.pos;
  7291. if (!(stream.eat(DOT) && stream.eatWhile(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isNumber"]))) {
  7292. stream.pos = decimalEnd;
  7293. }
  7294. return true;
  7295. } else if (stream.eat(DOT) && stream.eatWhile(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isNumber"])) {
  7296. stream.start = start;
  7297. return true;
  7298. }
  7299. // TODO eat exponent part
  7300. stream.pos = start;
  7301. return false;
  7302. }
  7303. function eatUnitPart(stream) {
  7304. return eatIdent(stream) || eatPercent(stream);
  7305. }
  7306. function eatPercent(stream) {
  7307. return consume(stream, 37 /* % */);
  7308. }
  7309. function isOperator$1(code) {
  7310. return code === 45 /* - */ || code === 43 /* + */;
  7311. }
  7312. const NOT = 33; // !
  7313. const MULTIPLY = 42; // *
  7314. const PLUS = 43; // +
  7315. const MINUS = 45; // -
  7316. const DIVIDE = 47; // /
  7317. const LESS_THAN = 60; // <
  7318. const EQUALS = 61; // =
  7319. const GREATER_THAN = 62; // <
  7320. function operator$1(stream) {
  7321. return eatOperator(stream) && new Token(stream, 'operator');
  7322. }
  7323. function eatOperator(stream) {
  7324. if (consume(stream, isEquality)) {
  7325. stream.eatWhile(EQUALS);
  7326. return true;
  7327. } else if (consume(stream, isOperator$2)) {
  7328. return true;
  7329. }
  7330. return false;
  7331. }
  7332. function isEquality(code) {
  7333. return code === NOT || code === LESS_THAN || code === EQUALS || code === GREATER_THAN;
  7334. }
  7335. function isOperator$2(code) {
  7336. return code === MULTIPLY || code === PLUS || code === MINUS || code === DIVIDE
  7337. || isEquality(code);
  7338. }
  7339. const PSEUDO = 58; // :
  7340. /**
  7341. * Consumes pseudo-selector from given stream
  7342. */
  7343. var pseudo = function(stream) {
  7344. const start = stream.pos;
  7345. if (stream.eatWhile(PSEUDO)) {
  7346. const name = ident(stream);
  7347. if (name) {
  7348. return new Token(stream, 'pseudo', start).add(name);
  7349. }
  7350. }
  7351. stream.pos = start;
  7352. };
  7353. /**
  7354. * Consumes unquoted value from given stream
  7355. * @param {StreamReader} stream
  7356. * @return {UnquotedToken}
  7357. */
  7358. var unquoted = function(stream) {
  7359. return eatUnquoted(stream) && new Token(stream, 'unquoted');
  7360. };
  7361. function eatUnquoted(stream) {
  7362. return consumeWhile(stream, isUnquoted);
  7363. }
  7364. function isUnquoted(code) {
  7365. return !isNaN(code) && !Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isQuote"])(code) && !Object(_emmetio_stream_reader_utils__WEBPACK_IMPORTED_MODULE_1__["isSpace"])(code)
  7366. && code !== 40 /* ( */ && code !== 41 /* ) */ && code !== 92 /* \ */
  7367. && !isNonPrintable(code);
  7368. }
  7369. function isNonPrintable(code) {
  7370. return (code >= 0 && code <= 8) || code === 11
  7371. || (code >= 14 && code <= 31) || code === 127;
  7372. }
  7373. /**
  7374. * Consumes URL token from given stream
  7375. * @param {StreamReader} stream
  7376. * @return {Token}
  7377. */
  7378. function url(stream) {
  7379. const start = stream.pos;
  7380. if (eatString(stream, 'url(')) {
  7381. eatWhitespace(stream);
  7382. const value = string(stream) || unquoted(stream);
  7383. eatWhitespace(stream);
  7384. stream.eat(41); // )
  7385. return new Token(stream, 'url', start).add(value);
  7386. }
  7387. stream.pos = start;
  7388. }
  7389. function eatUrl(stream) {
  7390. const start = stream.pos;
  7391. if (eatString(stream, 'url(')) {
  7392. eatWhitespace(stream);
  7393. eatString$1(stream) || eatUnquoted(stream);
  7394. eatWhitespace(stream);
  7395. stream.eat(41); // )
  7396. stream.start = start;
  7397. return true;
  7398. }
  7399. stream.pos = start;
  7400. return false;
  7401. }
  7402. const VARIABLE = 36; // $
  7403. /**
  7404. * Consumes SCSS variable from given stream
  7405. */
  7406. function variable(stream) {
  7407. return prefixed(stream, 'variable', VARIABLE, variableName);
  7408. }
  7409. function variableName(stream) {
  7410. if (eatVariableName(stream)) {
  7411. return new Token(stream, 'name');
  7412. }
  7413. }
  7414. function eatVariableName(stream) {
  7415. return consumeWhile(stream, isVariableName);
  7416. }
  7417. function isVariableName(code) {
  7418. return code === VARIABLE || isIdent(code);
  7419. }
  7420. /**
  7421. * Group tokens by commonly used context
  7422. */
  7423. function consumeToken(stream) {
  7424. const _token = any(stream) || args(stream, consumeToken);
  7425. if (_token && _token.type === 'ident') {
  7426. const _args = args(stream, consumeToken);
  7427. if (_args) {
  7428. // An identifier followed by arguments – function call
  7429. return new Token(stream, 'function', _token.start, _args.end).add(_token).add(_args);
  7430. }
  7431. }
  7432. return _token || unknown(stream);
  7433. }
  7434. function any(stream) {
  7435. return formatting(stream) || url(stream) || selector(stream) || value(stream)
  7436. || separator(stream);
  7437. }
  7438. function selector(stream) {
  7439. return interpolation(stream) || backtick(stream) || ident(stream) || atKeyword(stream)
  7440. || className(stream) || id(stream) || pseudo(stream) || eatAttribuite(stream)
  7441. || combinator(stream);
  7442. }
  7443. function value(stream) {
  7444. return url(stream) || string(stream) || interpolation(stream) || backtick(stream)
  7445. || number(stream) || hash(stream) || keyword(stream) || important(stream)
  7446. || operator$1(stream);
  7447. }
  7448. function keyword(stream) {
  7449. return backtick(stream) || variable(stream) || atKeyword(stream) || ident(stream);
  7450. }
  7451. function formatting(stream) {
  7452. return comment(stream) || whitespace(stream);
  7453. }
  7454. function unknown(stream) {
  7455. stream.start = stream.pos;
  7456. const ch = stream.next();
  7457. if (ch != null) {
  7458. return new Token(stream, 'unknown');
  7459. }
  7460. }
  7461. /**
  7462. * Parses CSS rule selector
  7463. * @param {String|StreamReader} source
  7464. * @return {Token[]}
  7465. */
  7466. function parseSelector(source) {
  7467. return parseList(source, 'selector');
  7468. }
  7469. /**
  7470. * Parses CSS property name. Mostly used for LESS where
  7471. * property-like entry might be used as a mixin call
  7472. * @param {String|StreamReader} source
  7473. * @return {Token}
  7474. */
  7475. function parsePropertyName(source) {
  7476. const stream = typeof source === 'string' ? new _emmetio_stream_reader__WEBPACK_IMPORTED_MODULE_0__["default"](source) : source;
  7477. const items = [];
  7478. while (!stream.eof()) {
  7479. items.push(consumeToken(stream));
  7480. }
  7481. let token;
  7482. if (items.length === 1) {
  7483. token = items[0];
  7484. } else {
  7485. token = new Token(stream, 'property-name', stream.start, stream.end);
  7486. for (let i = 0, il = items.length; i < il; i++) {
  7487. token.add(items[i]);
  7488. }
  7489. }
  7490. return token;
  7491. }
  7492. /**
  7493. * Parses CSS property value
  7494. * @param {String|StreamReader} source
  7495. * @return {Token[]}
  7496. */
  7497. function parsePropertyValue(source) {
  7498. return parseList(source);
  7499. }
  7500. /**
  7501. * Parses @media CSS rule expression
  7502. * @param {String|StreamReader} source
  7503. * @return {Token[]}
  7504. */
  7505. function parseMediaExpression(source) {
  7506. return parseList(source);
  7507. }
  7508. /**
  7509. * Parses given source into a set of tokens, separated by comma. Each token contains
  7510. * parsed sub-items as independent tokens and so on. Mostly used to parse
  7511. * selectors and property values
  7512. * @param {String|StreamReader} source Source to parse
  7513. * @param {String} [tokenType] Type of first-level tokens.
  7514. * Default is `item`
  7515. * @return {Token[]}
  7516. */
  7517. function parseList(source, tokenType) {
  7518. tokenType = tokenType || 'item';
  7519. const stream = typeof source === 'string' ? new _emmetio_stream_reader__WEBPACK_IMPORTED_MODULE_0__["default"](source) : source;
  7520. const items = [];
  7521. const fragments = [];
  7522. const flush = () => {
  7523. const clean = trimFormatting(fragments);
  7524. if (clean.length) {
  7525. const item = new Token(stream, tokenType, clean[0].start, last(clean).end);
  7526. for (let i = 0; i < clean.length; i++) {
  7527. item.add(clean[i]);
  7528. }
  7529. items.push(item);
  7530. }
  7531. fragments.length = 0;
  7532. };
  7533. let token;
  7534. while (!stream.eof()) {
  7535. if (stream.eat(44 /* , */)) {
  7536. flush();
  7537. } else if (token = consumeToken(stream)) {
  7538. if (token.type !== 'comment') {
  7539. fragments.push(token);
  7540. }
  7541. } else {
  7542. throw stream.error('Unexpected character');
  7543. }
  7544. }
  7545. flush();
  7546. return items;
  7547. }
  7548. /**
  7549. * Creates CSS rule from given tokens
  7550. * @param {StreamReader} stream
  7551. * @param {Token[]} tokens
  7552. * @param {Token} [content]
  7553. * @return {Rule}
  7554. */
  7555. function createRule(stream, tokens, contentStart, contentEnd) {
  7556. if (!tokens.length) {
  7557. return null;
  7558. }
  7559. const name = tokens[0];
  7560. name.end = last(tokens).end;
  7561. return new Rule(stream, name, contentStart, contentEnd);
  7562. }
  7563. /**
  7564. * Represents CSS rule
  7565. * @type {Node}
  7566. */
  7567. class Rule extends Node {
  7568. /**
  7569. * @param {StreamReader} stream
  7570. * @param {Token} name Rule’s name token
  7571. * @param {Token} contentStart Rule’s content start token
  7572. * @param {Token} [contentEnd] Rule’s content end token
  7573. */
  7574. constructor(stream, name, contentStart, contentEnd) {
  7575. super('rule');
  7576. this.stream = stream;
  7577. this.selectorToken = name;
  7578. this.contentStartToken = contentStart;
  7579. this.contentEndToken = contentEnd || contentStart;
  7580. this._parsedSelector = null;
  7581. }
  7582. /**
  7583. * Returns rule selector
  7584. * @return {String}
  7585. */
  7586. get selector() {
  7587. return valueOf(this.selectorToken);
  7588. }
  7589. get parsedSelector() {
  7590. if (!this._parsedSelector) {
  7591. this._parsedSelector = parseSelector(this.selectorToken.limit());
  7592. }
  7593. return this._parsedSelector;
  7594. }
  7595. /**
  7596. * Returns node’s start position in stream
  7597. * @return {*}
  7598. */
  7599. get start() {
  7600. return this.selectorToken && this.selectorToken.start;
  7601. }
  7602. /**
  7603. * Returns node’s end position in stream
  7604. * @return {*}
  7605. */
  7606. get end() {
  7607. const token = this.contentEndToken || this.contentStartToken || this.nameToken;
  7608. return token && token.end;
  7609. }
  7610. }
  7611. /**
  7612. * Creates CSS rule from given tokens
  7613. * @param {StreamReader} stream
  7614. * @param {Token[]} tokens
  7615. * @param {Token} [content]
  7616. * @return {Rule}
  7617. */
  7618. function createAtRule(stream, tokens, contentStart, contentEnd) {
  7619. if (!tokens.length) {
  7620. return null;
  7621. }
  7622. let ix = 0, expression;
  7623. const name = tokens[ix++];
  7624. if (ix < tokens.length) {
  7625. expression = tokens[ix++];
  7626. expression.type = 'expression';
  7627. expression.end = last(tokens).end;
  7628. } else {
  7629. expression = new Token(stream, 'expression', name.end, name.end);
  7630. }
  7631. return new AtRule(stream, name, expression, contentStart, contentEnd);
  7632. }
  7633. class AtRule extends Node {
  7634. constructor(stream, name, expression, contentStart, contentEnd) {
  7635. super('at-rule');
  7636. this.stream = stream;
  7637. this.nameToken = name;
  7638. this.expressionToken = expression;
  7639. this.contentStartToken = contentStart;
  7640. this.contentEndToken = contentEnd || contentStart;
  7641. this._parsedExpression = null;
  7642. }
  7643. /**
  7644. * Returns at-rule name
  7645. * @return {String}
  7646. */
  7647. get name() {
  7648. return valueOf(this.nameToken && this.nameToken.item(0));
  7649. }
  7650. get expression() {
  7651. return valueOf(this.expressionToken);
  7652. }
  7653. get parsedExpression() {
  7654. if (!this._parsedExpression) {
  7655. this._parsedExpression = parseMediaExpression(this.expressionToken.limit());
  7656. }
  7657. return this._parsedExpression;
  7658. }
  7659. /**
  7660. * Returns node’s start position in stream
  7661. * @return {*}
  7662. */
  7663. get start() {
  7664. return this.nameToken && this.nameToken.start;
  7665. }
  7666. /**
  7667. * Returns node’s end position in stream
  7668. * @return {*}
  7669. */
  7670. get end() {
  7671. const token = this.contentEndToken || this.contentStartToken || this.nameToken;
  7672. return token && token.end;
  7673. }
  7674. }
  7675. /**
  7676. * Factory method that creates property node from given tokens
  7677. * @param {StreamReader} stream
  7678. * @param {Token[]} tokens
  7679. * @param {Token} terminator
  7680. * @return {Property}
  7681. */
  7682. function createProperty(stream, tokens, terminator) {
  7683. // NB in LESS, fragmented properties without value like `.foo.bar;` must be
  7684. // treated like mixin call
  7685. if (!tokens.length) {
  7686. return null;
  7687. }
  7688. let separator, value, ix = 0;
  7689. const name = tokens[ix++];
  7690. if (ix < tokens.length) {
  7691. value = tokens[ix++];
  7692. value.type = 'value';
  7693. value.end = last(tokens).end;
  7694. }
  7695. if (name && value) {
  7696. separator = new Token(stream, 'separator', name.end, value.start);
  7697. }
  7698. return new Property(
  7699. stream,
  7700. name,
  7701. value,
  7702. separator,
  7703. terminator
  7704. );
  7705. }
  7706. class Property extends Node {
  7707. constructor(stream, name, value, separator, terminator) {
  7708. super('property');
  7709. this.stream = stream;
  7710. this.nameToken = name;
  7711. this.valueToken = value;
  7712. this._parsedName = null;
  7713. this._parsedValue = null;
  7714. this.separatorToken = separator;
  7715. this.terminatorToken = terminator;
  7716. }
  7717. /**
  7718. * Property name
  7719. * @return {String}
  7720. */
  7721. get name() {
  7722. return valueOf(this.nameToken);
  7723. }
  7724. /**
  7725. * Returns parsed sub-tokens of current property name
  7726. * @return {Token[]}
  7727. */
  7728. get parsedName() {
  7729. if (!this._parsedName) {
  7730. this._parsedName = parsePropertyName(this.nameToken.limit());
  7731. }
  7732. return this._parsedName;
  7733. }
  7734. /**
  7735. * Property value
  7736. * @return {String}
  7737. */
  7738. get value() {
  7739. return valueOf(this.valueToken);
  7740. }
  7741. /**
  7742. * Parsed value parts: a list of tokens, separated by comma. Each token may
  7743. * contains parsed sub-tokens and so on
  7744. * @return {Token[]}
  7745. */
  7746. get parsedValue() {
  7747. if (!this._parsedValue) {
  7748. this._parsedValue = parsePropertyValue(this.valueToken.limit());
  7749. }
  7750. return this._parsedValue;
  7751. }
  7752. get separator() {
  7753. return valueOf(this.separatorToken);
  7754. }
  7755. get terminator() {
  7756. return valueOf(this.terminatorToken);
  7757. }
  7758. get start() {
  7759. const token = this.nameToken || this.separatorToken || this.valueToken
  7760. || this.terminatorToken;
  7761. return token && token.start;
  7762. }
  7763. get end() {
  7764. const token = this.terminatorToken || this.valueToken
  7765. || this.separatorToken || this.nameToken;
  7766. return token && token.end;
  7767. }
  7768. }
  7769. const LBRACE = 40; // (
  7770. const RBRACE = 41; // )
  7771. const PROP_DELIMITER = 58; // :
  7772. const PROP_TERMINATOR = 59; // ;
  7773. const RULE_START = 123; // {
  7774. const RULE_END = 125; // }
  7775. function parseStylesheet(source) {
  7776. const stream = typeof source === 'string' ? new _emmetio_stream_reader__WEBPACK_IMPORTED_MODULE_0__["default"](source) : source;
  7777. const root = new Stylesheet();
  7778. let ctx = root, child, accum, token;
  7779. let tokens = [];
  7780. const flush = () => {
  7781. if (accum) {
  7782. tokens.push(accum);
  7783. accum = null;
  7784. }
  7785. };
  7786. while (!stream.eof()) {
  7787. if (eatWhitespace(stream)) {
  7788. continue;
  7789. }
  7790. if (token = comment(stream)) {
  7791. root.addComment(token);
  7792. continue;
  7793. }
  7794. stream.start = stream.pos;
  7795. if (stream.eatWhile(PROP_DELIMITER)) {
  7796. // Property delimiter can be either a real property delimiter or a
  7797. // part of pseudo-selector.
  7798. if (!tokens.length) {
  7799. if (accum) {
  7800. // No consumed tokens yet but pending token: most likely it’s
  7801. // a CSS property
  7802. flush();
  7803. } else {
  7804. // No consumend or accumulated token, seems like a start of
  7805. // pseudo-selector, e.g. `::slotted`
  7806. accum = new Token(stream, 'preparse');
  7807. }
  7808. }
  7809. // Skip delimiter if there are already consumend tokens: most likely
  7810. // it’s a part of pseudo-selector
  7811. } else if (stream.eat(PROP_TERMINATOR)) {
  7812. flush();
  7813. ctx.add(createProperty(stream, tokens, new Token(stream, 'termintator')));
  7814. tokens.length = 0;
  7815. } else if (stream.eat(RULE_START)) {
  7816. flush();
  7817. if (tokens.length > 0) {
  7818. child = tokens[0].type === 'at-keyword'
  7819. ? createAtRule(stream, tokens, new Token(stream, 'body-start'))
  7820. : createRule(stream, tokens, new Token(stream, 'body-start'));
  7821. ctx.add(child);
  7822. ctx = child;
  7823. tokens.length = 0;
  7824. }
  7825. } else if (stream.eat(RULE_END)) {
  7826. flush();
  7827. // Finalize context section
  7828. ctx.add(createProperty(stream, tokens));
  7829. if (ctx.type !== 'stylesheet') {
  7830. // In case of invalid stylesheet with redundant `}`,
  7831. // don’t modify root section.
  7832. ctx.contentEndToken = new Token(stream, 'body-end');
  7833. ctx = ctx.parent;
  7834. }
  7835. tokens.length = 0;
  7836. } else if (token = atKeyword(stream)) {
  7837. // Explictly consume @-tokens since it defines how rule or property
  7838. // should be pre-parsed
  7839. flush();
  7840. tokens.push(token);
  7841. } else if (eatUrl(stream) || eatInterpolation(stream) || eatBacktick(stream)
  7842. || eatBraces(stream, root) || eatString$1(stream) || stream.next()) {
  7843. // NB explicitly consume `url()` token since it may contain
  7844. // an unquoted url like `http://example.com` which interferes
  7845. // with single-line comment
  7846. accum = accum || new Token(stream, 'preparse');
  7847. accum.end = stream.pos;
  7848. } else {
  7849. throw new Error(`Unexpected end-of-stream at ${stream.pos}`);
  7850. }
  7851. }
  7852. if (accum) {
  7853. tokens.push(accum);
  7854. }
  7855. // Finalize all the rest properties
  7856. ctx.add(createProperty(stream, tokens));
  7857. // Finalize unterminated rules
  7858. stream.start = stream.pos;
  7859. while (ctx && ctx !== root) {
  7860. ctx.contentEndToken = new Token(stream, 'body-end');
  7861. ctx = ctx.parent;
  7862. }
  7863. return root;
  7864. }
  7865. /**
  7866. * Parses given source into tokens
  7867. * @param {String|StreamReader} source
  7868. * @param {Function} [consumer] Token consumer function, for example, `selector`,
  7869. * `value` etc. from `lib/tokens` module. Default is generic `consumeToken`
  7870. * @return {Token[]}
  7871. */
  7872. function lexer(source, consumer) {
  7873. consumer = consumer || consumeToken;
  7874. const stream = typeof source === 'string' ? new _emmetio_stream_reader__WEBPACK_IMPORTED_MODULE_0__["default"](source) : source;
  7875. const result = [];
  7876. let token;
  7877. while (!stream.eof() && (token = consumer(stream))) {
  7878. result.push(token);
  7879. }
  7880. return result;
  7881. }
  7882. /**
  7883. * Consumes content inside round braces. Mostly used to skip `;` token inside
  7884. * expressions since in LESS it is also used to separate function arguments
  7885. * @param {StringReader} stream
  7886. * @param {Stylesheet} root A stylesheet root. Used to accumulate comments
  7887. * @return {Boolean}
  7888. */
  7889. function eatBraces(stream, root) {
  7890. if (stream.eat(LBRACE)) {
  7891. let stack = 1, token;
  7892. while (!stream.eof()) {
  7893. if (stream.eat(RBRACE)) {
  7894. stack--;
  7895. if (!stack) {
  7896. break;
  7897. }
  7898. } else if (stream.eat(LBRACE)) {
  7899. stack++;
  7900. } else if (eatUrl(stream) || eatString$1(stream)) {
  7901. continue;
  7902. } else if (token = comment(stream)) {
  7903. root.addComment(token);
  7904. continue;
  7905. } else {
  7906. stream.next();
  7907. }
  7908. }
  7909. return true;
  7910. }
  7911. return false;
  7912. }
  7913. /* harmony default export */ __webpack_exports__["default"] = (parseStylesheet);
  7914. /***/ }),
  7915. /* 37 */
  7916. /***/ (function(module, exports, __webpack_require__) {
  7917. "use strict";
  7918. /*---------------------------------------------------------------------------------------------
  7919. * Copyright (c) Microsoft Corporation. All rights reserved.
  7920. * Licensed under the MIT License. See License.txt in the project root for license information.
  7921. *--------------------------------------------------------------------------------------------*/
  7922. Object.defineProperty(exports, "__esModule", { value: true });
  7923. /* Based on @sergeche's work in his emmet plugin */
  7924. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  7925. function comparePosition(position, other) {
  7926. if (position.line > other.line)
  7927. return 1;
  7928. if (other.line == position.line && position.character > other.character)
  7929. return 1;
  7930. if (other.line == position.line && position.character == other.character)
  7931. return 0;
  7932. return -1;
  7933. }
  7934. exports.comparePosition = comparePosition;
  7935. /**
  7936. * A stream reader for VSCode's `TextDocument`
  7937. * Based on @emmetio/stream-reader and @emmetio/atom-plugin
  7938. */
  7939. class DocumentStreamReader {
  7940. constructor(document, pos, limit) {
  7941. this.document = document;
  7942. this.start = this.pos = pos ? pos : vscode_languageserver_protocol_1.Position.create(0, 0);
  7943. this._sof = limit ? limit.start : vscode_languageserver_protocol_1.Position.create(0, 0);
  7944. this._eof = limit ? limit.end : vscode_languageserver_protocol_1.Position.create(document.lineCount - 1, this._lineLength(this.document.lineCount - 1));
  7945. this._eol = `\n`;
  7946. }
  7947. /**
  7948. * Returns true only if the stream is at the start of the file.
  7949. */
  7950. sof() {
  7951. return comparePosition(this.pos, this._sof) <= 0;
  7952. }
  7953. /**
  7954. * Returns true only if the stream is at the end of the file.
  7955. */
  7956. eof() {
  7957. return comparePosition(this.pos, this._eof) >= 0;
  7958. }
  7959. /**
  7960. * Creates a new stream instance which is limited to given range for given document
  7961. */
  7962. limit(start, end) {
  7963. return new DocumentStreamReader(this.document, start, vscode_languageserver_protocol_1.Range.create(start, end));
  7964. }
  7965. /**
  7966. * Returns the next character code in the stream without advancing it.
  7967. * Will return NaN at the end of the file.
  7968. */
  7969. peek() {
  7970. if (this.eof()) {
  7971. return NaN;
  7972. }
  7973. const line = this.getline(this.pos.line);
  7974. return this.pos.character < line.length ? line.charCodeAt(this.pos.character) : this._eol.charCodeAt(0);
  7975. }
  7976. getline(line) {
  7977. let content = this.document.getText();
  7978. let lines = content.split('\n');
  7979. return lines[line] || '';
  7980. }
  7981. /**
  7982. * Returns the next character in the stream and advances it.
  7983. * Also returns NaN when no more characters are available.
  7984. */
  7985. next() {
  7986. if (this.eof()) {
  7987. return NaN;
  7988. }
  7989. const line = this.getline(this.pos.line);
  7990. let code;
  7991. if (this.pos.character < line.length) {
  7992. code = line.charCodeAt(this.pos.character);
  7993. this.pos = vscode_languageserver_protocol_1.Position.create(this.pos.line, this.pos.character + 1);
  7994. }
  7995. else {
  7996. code = this._eol.charCodeAt(this.pos.character - line.length);
  7997. this.pos = vscode_languageserver_protocol_1.Position.create(this.pos.line + 1, this.pos.character);
  7998. }
  7999. if (this.eof()) {
  8000. // restrict pos to eof, if in case it got moved beyond eof
  8001. this.pos = vscode_languageserver_protocol_1.Position.create(this._eof.line, this._eof.character);
  8002. }
  8003. return code;
  8004. }
  8005. /**
  8006. * Backs up the stream n characters. Backing it up further than the
  8007. * start of the current token will cause things to break, so be careful.
  8008. */
  8009. backUp(n) {
  8010. let row = this.pos.line;
  8011. let column = this.pos.character;
  8012. column -= (n || 1);
  8013. while (row >= 0 && column < 0) {
  8014. row--;
  8015. column += this._lineLength(row);
  8016. }
  8017. this.pos = row < 0 || column < 0
  8018. ? vscode_languageserver_protocol_1.Position.create(0, 0)
  8019. : vscode_languageserver_protocol_1.Position.create(row, column);
  8020. return this.peek();
  8021. }
  8022. /**
  8023. * Get the string between the start of the current token and the
  8024. * current stream position.
  8025. */
  8026. current() {
  8027. return this.substring(this.start, this.pos);
  8028. }
  8029. /**
  8030. * Returns contents for given range
  8031. */
  8032. substring(from, to) {
  8033. return this.document.getText(vscode_languageserver_protocol_1.Range.create(from, to));
  8034. }
  8035. /**
  8036. * Creates error object with current stream state
  8037. */
  8038. error(message) {
  8039. const err = new Error(`${message} at row ${this.pos.line}, column ${this.pos.character}`);
  8040. return err;
  8041. }
  8042. /**
  8043. * Returns line length of given row, including line ending
  8044. */
  8045. _lineLength(row) {
  8046. const line = this.getline(row);
  8047. return line.length;
  8048. }
  8049. /**
  8050. * `match` can be a character code or a function that takes a character code
  8051. * and returns a boolean. If the next character in the stream 'matches'
  8052. * the given argument, it is consumed and returned.
  8053. * Otherwise, `false` is returned.
  8054. */
  8055. eat(match) {
  8056. const ch = this.peek();
  8057. const ok = typeof match === 'function' ? match(ch) : ch === match;
  8058. if (ok) {
  8059. this.next();
  8060. }
  8061. return ok;
  8062. }
  8063. /**
  8064. * Repeatedly calls <code>eat</code> with the given argument, until it
  8065. * fails. Returns <code>true</code> if any characters were eaten.
  8066. */
  8067. eatWhile(match) {
  8068. const start = this.pos;
  8069. while (!this.eof() && this.eat(match)) { }
  8070. return comparePosition(this.pos, start) != 0;
  8071. }
  8072. }
  8073. exports.DocumentStreamReader = DocumentStreamReader;
  8074. /***/ }),
  8075. /* 38 */
  8076. /***/ (function(module, exports) {
  8077. module.exports = require("vscode-emmet-helper");
  8078. /***/ })
  8079. /******/ ])));