My dotfiles
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

22609 wiersze
852 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 = 33);
  85. /******/ })
  86. /************************************************************************/
  87. /******/ ([
  88. /* 0 */,
  89. /* 1 */
  90. /***/ (function(module, exports) {
  91. module.exports = require("path");
  92. /***/ }),
  93. /* 2 */
  94. /***/ (function(module, exports) {
  95. module.exports = require("fs");
  96. /***/ }),
  97. /* 3 */
  98. /***/ (function(module, exports, __webpack_require__) {
  99. "use strict";
  100. /* --------------------------------------------------------------------------------------------
  101. * Copyright (c) Microsoft Corporation. All rights reserved.
  102. * Licensed under the MIT License. See License.txt in the project root for license information.
  103. * ------------------------------------------------------------------------------------------ */
  104. function __export(m) {
  105. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  106. }
  107. Object.defineProperty(exports, "__esModule", { value: true });
  108. const vscode_jsonrpc_1 = __webpack_require__(4);
  109. exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
  110. exports.ResponseError = vscode_jsonrpc_1.ResponseError;
  111. exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;
  112. exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
  113. exports.Disposable = vscode_jsonrpc_1.Disposable;
  114. exports.Event = vscode_jsonrpc_1.Event;
  115. exports.Emitter = vscode_jsonrpc_1.Emitter;
  116. exports.Trace = vscode_jsonrpc_1.Trace;
  117. exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;
  118. exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
  119. exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
  120. exports.RequestType = vscode_jsonrpc_1.RequestType;
  121. exports.RequestType0 = vscode_jsonrpc_1.RequestType0;
  122. exports.NotificationType = vscode_jsonrpc_1.NotificationType;
  123. exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
  124. exports.MessageReader = vscode_jsonrpc_1.MessageReader;
  125. exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;
  126. exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
  127. exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
  128. exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
  129. exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
  130. exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
  131. exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
  132. exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
  133. exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
  134. exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
  135. exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
  136. __export(__webpack_require__(17));
  137. __export(__webpack_require__(18));
  138. const callHierarchy = __webpack_require__(27);
  139. const progress = __webpack_require__(28);
  140. const sr = __webpack_require__(29);
  141. var Proposed;
  142. (function (Proposed) {
  143. let SelectionRangeRequest;
  144. (function (SelectionRangeRequest) {
  145. SelectionRangeRequest.type = sr.SelectionRangeRequest.type;
  146. })(SelectionRangeRequest = Proposed.SelectionRangeRequest || (Proposed.SelectionRangeRequest = {}));
  147. let CallHierarchyRequest;
  148. (function (CallHierarchyRequest) {
  149. CallHierarchyRequest.type = callHierarchy.CallHierarchyRequest.type;
  150. })(CallHierarchyRequest = Proposed.CallHierarchyRequest || (Proposed.CallHierarchyRequest = {}));
  151. let CallHierarchyDirection;
  152. (function (CallHierarchyDirection) {
  153. CallHierarchyDirection.CallsFrom = callHierarchy.CallHierarchyDirection.CallsFrom;
  154. CallHierarchyDirection.CallsTo = callHierarchy.CallHierarchyDirection.CallsTo;
  155. })(CallHierarchyDirection = Proposed.CallHierarchyDirection || (Proposed.CallHierarchyDirection = {}));
  156. let ProgressStartNotification;
  157. (function (ProgressStartNotification) {
  158. ProgressStartNotification.type = progress.ProgressStartNotification.type;
  159. })(ProgressStartNotification = Proposed.ProgressStartNotification || (Proposed.ProgressStartNotification = {}));
  160. let ProgressReportNotification;
  161. (function (ProgressReportNotification) {
  162. ProgressReportNotification.type = progress.ProgressReportNotification.type;
  163. })(ProgressReportNotification = Proposed.ProgressReportNotification || (Proposed.ProgressReportNotification = {}));
  164. let ProgressDoneNotification;
  165. (function (ProgressDoneNotification) {
  166. ProgressDoneNotification.type = progress.ProgressDoneNotification.type;
  167. })(ProgressDoneNotification = Proposed.ProgressDoneNotification || (Proposed.ProgressDoneNotification = {}));
  168. let ProgressCancelNotification;
  169. (function (ProgressCancelNotification) {
  170. ProgressCancelNotification.type = progress.ProgressCancelNotification.type;
  171. })(ProgressCancelNotification = Proposed.ProgressCancelNotification || (Proposed.ProgressCancelNotification = {}));
  172. })(Proposed = exports.Proposed || (exports.Proposed = {}));
  173. function createProtocolConnection(reader, writer, logger, strategy) {
  174. return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
  175. }
  176. exports.createProtocolConnection = createProtocolConnection;
  177. /***/ }),
  178. /* 4 */
  179. /***/ (function(module, exports, __webpack_require__) {
  180. "use strict";
  181. /* --------------------------------------------------------------------------------------------
  182. * Copyright (c) Microsoft Corporation. All rights reserved.
  183. * Licensed under the MIT License. See License.txt in the project root for license information.
  184. * ------------------------------------------------------------------------------------------ */
  185. /// <reference path="./thenable.ts" />
  186. function __export(m) {
  187. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  188. }
  189. Object.defineProperty(exports, "__esModule", { value: true });
  190. const Is = __webpack_require__(5);
  191. const messages_1 = __webpack_require__(6);
  192. exports.RequestType = messages_1.RequestType;
  193. exports.RequestType0 = messages_1.RequestType0;
  194. exports.RequestType1 = messages_1.RequestType1;
  195. exports.RequestType2 = messages_1.RequestType2;
  196. exports.RequestType3 = messages_1.RequestType3;
  197. exports.RequestType4 = messages_1.RequestType4;
  198. exports.RequestType5 = messages_1.RequestType5;
  199. exports.RequestType6 = messages_1.RequestType6;
  200. exports.RequestType7 = messages_1.RequestType7;
  201. exports.RequestType8 = messages_1.RequestType8;
  202. exports.RequestType9 = messages_1.RequestType9;
  203. exports.ResponseError = messages_1.ResponseError;
  204. exports.ErrorCodes = messages_1.ErrorCodes;
  205. exports.NotificationType = messages_1.NotificationType;
  206. exports.NotificationType0 = messages_1.NotificationType0;
  207. exports.NotificationType1 = messages_1.NotificationType1;
  208. exports.NotificationType2 = messages_1.NotificationType2;
  209. exports.NotificationType3 = messages_1.NotificationType3;
  210. exports.NotificationType4 = messages_1.NotificationType4;
  211. exports.NotificationType5 = messages_1.NotificationType5;
  212. exports.NotificationType6 = messages_1.NotificationType6;
  213. exports.NotificationType7 = messages_1.NotificationType7;
  214. exports.NotificationType8 = messages_1.NotificationType8;
  215. exports.NotificationType9 = messages_1.NotificationType9;
  216. const messageReader_1 = __webpack_require__(7);
  217. exports.MessageReader = messageReader_1.MessageReader;
  218. exports.StreamMessageReader = messageReader_1.StreamMessageReader;
  219. exports.IPCMessageReader = messageReader_1.IPCMessageReader;
  220. exports.SocketMessageReader = messageReader_1.SocketMessageReader;
  221. const messageWriter_1 = __webpack_require__(9);
  222. exports.MessageWriter = messageWriter_1.MessageWriter;
  223. exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
  224. exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
  225. exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
  226. const events_1 = __webpack_require__(8);
  227. exports.Disposable = events_1.Disposable;
  228. exports.Event = events_1.Event;
  229. exports.Emitter = events_1.Emitter;
  230. const cancellation_1 = __webpack_require__(10);
  231. exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
  232. exports.CancellationToken = cancellation_1.CancellationToken;
  233. const linkedMap_1 = __webpack_require__(11);
  234. __export(__webpack_require__(12));
  235. __export(__webpack_require__(16));
  236. var CancelNotification;
  237. (function (CancelNotification) {
  238. CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
  239. })(CancelNotification || (CancelNotification = {}));
  240. exports.NullLogger = Object.freeze({
  241. error: () => { },
  242. warn: () => { },
  243. info: () => { },
  244. log: () => { }
  245. });
  246. var Trace;
  247. (function (Trace) {
  248. Trace[Trace["Off"] = 0] = "Off";
  249. Trace[Trace["Messages"] = 1] = "Messages";
  250. Trace[Trace["Verbose"] = 2] = "Verbose";
  251. })(Trace = exports.Trace || (exports.Trace = {}));
  252. (function (Trace) {
  253. function fromString(value) {
  254. value = value.toLowerCase();
  255. switch (value) {
  256. case 'off':
  257. return Trace.Off;
  258. case 'messages':
  259. return Trace.Messages;
  260. case 'verbose':
  261. return Trace.Verbose;
  262. default:
  263. return Trace.Off;
  264. }
  265. }
  266. Trace.fromString = fromString;
  267. function toString(value) {
  268. switch (value) {
  269. case Trace.Off:
  270. return 'off';
  271. case Trace.Messages:
  272. return 'messages';
  273. case Trace.Verbose:
  274. return 'verbose';
  275. default:
  276. return 'off';
  277. }
  278. }
  279. Trace.toString = toString;
  280. })(Trace = exports.Trace || (exports.Trace = {}));
  281. var TraceFormat;
  282. (function (TraceFormat) {
  283. TraceFormat["Text"] = "text";
  284. TraceFormat["JSON"] = "json";
  285. })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
  286. (function (TraceFormat) {
  287. function fromString(value) {
  288. value = value.toLowerCase();
  289. if (value === 'json') {
  290. return TraceFormat.JSON;
  291. }
  292. else {
  293. return TraceFormat.Text;
  294. }
  295. }
  296. TraceFormat.fromString = fromString;
  297. })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
  298. var SetTraceNotification;
  299. (function (SetTraceNotification) {
  300. SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');
  301. })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
  302. var LogTraceNotification;
  303. (function (LogTraceNotification) {
  304. LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');
  305. })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
  306. var ConnectionErrors;
  307. (function (ConnectionErrors) {
  308. /**
  309. * The connection is closed.
  310. */
  311. ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
  312. /**
  313. * The connection got disposed.
  314. */
  315. ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
  316. /**
  317. * The connection is already in listening mode.
  318. */
  319. ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
  320. })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
  321. class ConnectionError extends Error {
  322. constructor(code, message) {
  323. super(message);
  324. this.code = code;
  325. Object.setPrototypeOf(this, ConnectionError.prototype);
  326. }
  327. }
  328. exports.ConnectionError = ConnectionError;
  329. var ConnectionStrategy;
  330. (function (ConnectionStrategy) {
  331. function is(value) {
  332. let candidate = value;
  333. return candidate && Is.func(candidate.cancelUndispatched);
  334. }
  335. ConnectionStrategy.is = is;
  336. })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
  337. var ConnectionState;
  338. (function (ConnectionState) {
  339. ConnectionState[ConnectionState["New"] = 1] = "New";
  340. ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
  341. ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
  342. ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
  343. })(ConnectionState || (ConnectionState = {}));
  344. function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
  345. let sequenceNumber = 0;
  346. let notificationSquenceNumber = 0;
  347. let unknownResponseSquenceNumber = 0;
  348. const version = '2.0';
  349. let starRequestHandler = undefined;
  350. let requestHandlers = Object.create(null);
  351. let starNotificationHandler = undefined;
  352. let notificationHandlers = Object.create(null);
  353. let timer;
  354. let messageQueue = new linkedMap_1.LinkedMap();
  355. let responsePromises = Object.create(null);
  356. let requestTokens = Object.create(null);
  357. let trace = Trace.Off;
  358. let traceFormat = TraceFormat.Text;
  359. let tracer;
  360. let state = ConnectionState.New;
  361. let errorEmitter = new events_1.Emitter();
  362. let closeEmitter = new events_1.Emitter();
  363. let unhandledNotificationEmitter = new events_1.Emitter();
  364. let disposeEmitter = new events_1.Emitter();
  365. function createRequestQueueKey(id) {
  366. return 'req-' + id.toString();
  367. }
  368. function createResponseQueueKey(id) {
  369. if (id === null) {
  370. return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
  371. }
  372. else {
  373. return 'res-' + id.toString();
  374. }
  375. }
  376. function createNotificationQueueKey() {
  377. return 'not-' + (++notificationSquenceNumber).toString();
  378. }
  379. function addMessageToQueue(queue, message) {
  380. if (messages_1.isRequestMessage(message)) {
  381. queue.set(createRequestQueueKey(message.id), message);
  382. }
  383. else if (messages_1.isResponseMessage(message)) {
  384. queue.set(createResponseQueueKey(message.id), message);
  385. }
  386. else {
  387. queue.set(createNotificationQueueKey(), message);
  388. }
  389. }
  390. function cancelUndispatched(_message) {
  391. return undefined;
  392. }
  393. function isListening() {
  394. return state === ConnectionState.Listening;
  395. }
  396. function isClosed() {
  397. return state === ConnectionState.Closed;
  398. }
  399. function isDisposed() {
  400. return state === ConnectionState.Disposed;
  401. }
  402. function closeHandler() {
  403. if (state === ConnectionState.New || state === ConnectionState.Listening) {
  404. state = ConnectionState.Closed;
  405. closeEmitter.fire(undefined);
  406. }
  407. // If the connection is disposed don't sent close events.
  408. }
  409. ;
  410. function readErrorHandler(error) {
  411. errorEmitter.fire([error, undefined, undefined]);
  412. }
  413. function writeErrorHandler(data) {
  414. errorEmitter.fire(data);
  415. }
  416. messageReader.onClose(closeHandler);
  417. messageReader.onError(readErrorHandler);
  418. messageWriter.onClose(closeHandler);
  419. messageWriter.onError(writeErrorHandler);
  420. function triggerMessageQueue() {
  421. if (timer || messageQueue.size === 0) {
  422. return;
  423. }
  424. timer = setImmediate(() => {
  425. timer = undefined;
  426. processMessageQueue();
  427. });
  428. }
  429. function processMessageQueue() {
  430. if (messageQueue.size === 0) {
  431. return;
  432. }
  433. let message = messageQueue.shift();
  434. try {
  435. if (messages_1.isRequestMessage(message)) {
  436. handleRequest(message);
  437. }
  438. else if (messages_1.isNotificationMessage(message)) {
  439. handleNotification(message);
  440. }
  441. else if (messages_1.isResponseMessage(message)) {
  442. handleResponse(message);
  443. }
  444. else {
  445. handleInvalidMessage(message);
  446. }
  447. }
  448. finally {
  449. triggerMessageQueue();
  450. }
  451. }
  452. let callback = (message) => {
  453. try {
  454. // We have received a cancellation message. Check if the message is still in the queue
  455. // and cancel it if allowed to do so.
  456. if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
  457. let key = createRequestQueueKey(message.params.id);
  458. let toCancel = messageQueue.get(key);
  459. if (messages_1.isRequestMessage(toCancel)) {
  460. let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
  461. if (response && (response.error !== void 0 || response.result !== void 0)) {
  462. messageQueue.delete(key);
  463. response.id = toCancel.id;
  464. traceSendingResponse(response, message.method, Date.now());
  465. messageWriter.write(response);
  466. return;
  467. }
  468. }
  469. }
  470. addMessageToQueue(messageQueue, message);
  471. }
  472. finally {
  473. triggerMessageQueue();
  474. }
  475. };
  476. function handleRequest(requestMessage) {
  477. if (isDisposed()) {
  478. // we return here silently since we fired an event when the
  479. // connection got disposed.
  480. return;
  481. }
  482. function reply(resultOrError, method, startTime) {
  483. let message = {
  484. jsonrpc: version,
  485. id: requestMessage.id
  486. };
  487. if (resultOrError instanceof messages_1.ResponseError) {
  488. message.error = resultOrError.toJson();
  489. }
  490. else {
  491. message.result = resultOrError === void 0 ? null : resultOrError;
  492. }
  493. traceSendingResponse(message, method, startTime);
  494. messageWriter.write(message);
  495. }
  496. function replyError(error, method, startTime) {
  497. let message = {
  498. jsonrpc: version,
  499. id: requestMessage.id,
  500. error: error.toJson()
  501. };
  502. traceSendingResponse(message, method, startTime);
  503. messageWriter.write(message);
  504. }
  505. function replySuccess(result, method, startTime) {
  506. // The JSON RPC defines that a response must either have a result or an error
  507. // So we can't treat undefined as a valid response result.
  508. if (result === void 0) {
  509. result = null;
  510. }
  511. let message = {
  512. jsonrpc: version,
  513. id: requestMessage.id,
  514. result: result
  515. };
  516. traceSendingResponse(message, method, startTime);
  517. messageWriter.write(message);
  518. }
  519. traceReceivedRequest(requestMessage);
  520. let element = requestHandlers[requestMessage.method];
  521. let type;
  522. let requestHandler;
  523. if (element) {
  524. type = element.type;
  525. requestHandler = element.handler;
  526. }
  527. let startTime = Date.now();
  528. if (requestHandler || starRequestHandler) {
  529. let cancellationSource = new cancellation_1.CancellationTokenSource();
  530. let tokenKey = String(requestMessage.id);
  531. requestTokens[tokenKey] = cancellationSource;
  532. try {
  533. let handlerResult;
  534. if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
  535. handlerResult = requestHandler
  536. ? requestHandler(cancellationSource.token)
  537. : starRequestHandler(requestMessage.method, cancellationSource.token);
  538. }
  539. else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
  540. handlerResult = requestHandler
  541. ? requestHandler(...requestMessage.params, cancellationSource.token)
  542. : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
  543. }
  544. else {
  545. handlerResult = requestHandler
  546. ? requestHandler(requestMessage.params, cancellationSource.token)
  547. : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
  548. }
  549. let promise = handlerResult;
  550. if (!handlerResult) {
  551. delete requestTokens[tokenKey];
  552. replySuccess(handlerResult, requestMessage.method, startTime);
  553. }
  554. else if (promise.then) {
  555. promise.then((resultOrError) => {
  556. delete requestTokens[tokenKey];
  557. reply(resultOrError, requestMessage.method, startTime);
  558. }, error => {
  559. delete requestTokens[tokenKey];
  560. if (error instanceof messages_1.ResponseError) {
  561. replyError(error, requestMessage.method, startTime);
  562. }
  563. else if (error && Is.string(error.message)) {
  564. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
  565. }
  566. else {
  567. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
  568. }
  569. });
  570. }
  571. else {
  572. delete requestTokens[tokenKey];
  573. reply(handlerResult, requestMessage.method, startTime);
  574. }
  575. }
  576. catch (error) {
  577. delete requestTokens[tokenKey];
  578. if (error instanceof messages_1.ResponseError) {
  579. reply(error, requestMessage.method, startTime);
  580. }
  581. else if (error && Is.string(error.message)) {
  582. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
  583. }
  584. else {
  585. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
  586. }
  587. }
  588. }
  589. else {
  590. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
  591. }
  592. }
  593. function handleResponse(responseMessage) {
  594. if (isDisposed()) {
  595. // See handle request.
  596. return;
  597. }
  598. if (responseMessage.id === null) {
  599. if (responseMessage.error) {
  600. logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
  601. }
  602. else {
  603. logger.error(`Received response message without id. No further error information provided.`);
  604. }
  605. }
  606. else {
  607. let key = String(responseMessage.id);
  608. let responsePromise = responsePromises[key];
  609. traceReceivedResponse(responseMessage, responsePromise);
  610. if (responsePromise) {
  611. delete responsePromises[key];
  612. try {
  613. if (responseMessage.error) {
  614. let error = responseMessage.error;
  615. responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
  616. }
  617. else if (responseMessage.result !== void 0) {
  618. responsePromise.resolve(responseMessage.result);
  619. }
  620. else {
  621. throw new Error('Should never happen.');
  622. }
  623. }
  624. catch (error) {
  625. if (error.message) {
  626. logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
  627. }
  628. else {
  629. logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
  630. }
  631. }
  632. }
  633. }
  634. }
  635. function handleNotification(message) {
  636. if (isDisposed()) {
  637. // See handle request.
  638. return;
  639. }
  640. let type = undefined;
  641. let notificationHandler;
  642. if (message.method === CancelNotification.type.method) {
  643. notificationHandler = (params) => {
  644. let id = params.id;
  645. let source = requestTokens[String(id)];
  646. if (source) {
  647. source.cancel();
  648. }
  649. };
  650. }
  651. else {
  652. let element = notificationHandlers[message.method];
  653. if (element) {
  654. notificationHandler = element.handler;
  655. type = element.type;
  656. }
  657. }
  658. if (notificationHandler || starNotificationHandler) {
  659. try {
  660. traceReceivedNotification(message);
  661. if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
  662. notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
  663. }
  664. else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
  665. notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
  666. }
  667. else {
  668. notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
  669. }
  670. }
  671. catch (error) {
  672. if (error.message) {
  673. logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
  674. }
  675. else {
  676. logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
  677. }
  678. }
  679. }
  680. else {
  681. unhandledNotificationEmitter.fire(message);
  682. }
  683. }
  684. function handleInvalidMessage(message) {
  685. if (!message) {
  686. logger.error('Received empty message.');
  687. return;
  688. }
  689. logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
  690. // Test whether we find an id to reject the promise
  691. let responseMessage = message;
  692. if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
  693. let key = String(responseMessage.id);
  694. let responseHandler = responsePromises[key];
  695. if (responseHandler) {
  696. responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
  697. }
  698. }
  699. }
  700. function traceSendingRequest(message) {
  701. if (trace === Trace.Off || !tracer) {
  702. return;
  703. }
  704. if (traceFormat === TraceFormat.Text) {
  705. let data = undefined;
  706. if (trace === Trace.Verbose && message.params) {
  707. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  708. }
  709. tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
  710. }
  711. else {
  712. logLSPMessage('send-request', message);
  713. }
  714. }
  715. function traceSendingNotification(message) {
  716. if (trace === Trace.Off || !tracer) {
  717. return;
  718. }
  719. if (traceFormat === TraceFormat.Text) {
  720. let data = undefined;
  721. if (trace === Trace.Verbose) {
  722. if (message.params) {
  723. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  724. }
  725. else {
  726. data = 'No parameters provided.\n\n';
  727. }
  728. }
  729. tracer.log(`Sending notification '${message.method}'.`, data);
  730. }
  731. else {
  732. logLSPMessage('send-notification', message);
  733. }
  734. }
  735. function traceSendingResponse(message, method, startTime) {
  736. if (trace === Trace.Off || !tracer) {
  737. return;
  738. }
  739. if (traceFormat === TraceFormat.Text) {
  740. let data = undefined;
  741. if (trace === Trace.Verbose) {
  742. if (message.error && message.error.data) {
  743. data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
  744. }
  745. else {
  746. if (message.result) {
  747. data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
  748. }
  749. else if (message.error === void 0) {
  750. data = 'No result returned.\n\n';
  751. }
  752. }
  753. }
  754. tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
  755. }
  756. else {
  757. logLSPMessage('send-response', message);
  758. }
  759. }
  760. function traceReceivedRequest(message) {
  761. if (trace === Trace.Off || !tracer) {
  762. return;
  763. }
  764. if (traceFormat === TraceFormat.Text) {
  765. let data = undefined;
  766. if (trace === Trace.Verbose && message.params) {
  767. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  768. }
  769. tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
  770. }
  771. else {
  772. logLSPMessage('receive-request', message);
  773. }
  774. }
  775. function traceReceivedNotification(message) {
  776. if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
  777. return;
  778. }
  779. if (traceFormat === TraceFormat.Text) {
  780. let data = undefined;
  781. if (trace === Trace.Verbose) {
  782. if (message.params) {
  783. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  784. }
  785. else {
  786. data = 'No parameters provided.\n\n';
  787. }
  788. }
  789. tracer.log(`Received notification '${message.method}'.`, data);
  790. }
  791. else {
  792. logLSPMessage('receive-notification', message);
  793. }
  794. }
  795. function traceReceivedResponse(message, responsePromise) {
  796. if (trace === Trace.Off || !tracer) {
  797. return;
  798. }
  799. if (traceFormat === TraceFormat.Text) {
  800. let data = undefined;
  801. if (trace === Trace.Verbose) {
  802. if (message.error && message.error.data) {
  803. data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
  804. }
  805. else {
  806. if (message.result) {
  807. data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
  808. }
  809. else if (message.error === void 0) {
  810. data = 'No result returned.\n\n';
  811. }
  812. }
  813. }
  814. if (responsePromise) {
  815. let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
  816. tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
  817. }
  818. else {
  819. tracer.log(`Received response ${message.id} without active response promise.`, data);
  820. }
  821. }
  822. else {
  823. logLSPMessage('receive-response', message);
  824. }
  825. }
  826. function logLSPMessage(type, message) {
  827. if (!tracer || trace === Trace.Off) {
  828. return;
  829. }
  830. const lspMessage = {
  831. isLSPMessage: true,
  832. type,
  833. message,
  834. timestamp: Date.now()
  835. };
  836. tracer.log(lspMessage);
  837. }
  838. function throwIfClosedOrDisposed() {
  839. if (isClosed()) {
  840. throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
  841. }
  842. if (isDisposed()) {
  843. throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
  844. }
  845. }
  846. function throwIfListening() {
  847. if (isListening()) {
  848. throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
  849. }
  850. }
  851. function throwIfNotListening() {
  852. if (!isListening()) {
  853. throw new Error('Call listen() first.');
  854. }
  855. }
  856. function undefinedToNull(param) {
  857. if (param === void 0) {
  858. return null;
  859. }
  860. else {
  861. return param;
  862. }
  863. }
  864. function computeMessageParams(type, params) {
  865. let result;
  866. let numberOfParams = type.numberOfParams;
  867. switch (numberOfParams) {
  868. case 0:
  869. result = null;
  870. break;
  871. case 1:
  872. result = undefinedToNull(params[0]);
  873. break;
  874. default:
  875. result = [];
  876. for (let i = 0; i < params.length && i < numberOfParams; i++) {
  877. result.push(undefinedToNull(params[i]));
  878. }
  879. if (params.length < numberOfParams) {
  880. for (let i = params.length; i < numberOfParams; i++) {
  881. result.push(null);
  882. }
  883. }
  884. break;
  885. }
  886. return result;
  887. }
  888. let connection = {
  889. sendNotification: (type, ...params) => {
  890. throwIfClosedOrDisposed();
  891. let method;
  892. let messageParams;
  893. if (Is.string(type)) {
  894. method = type;
  895. switch (params.length) {
  896. case 0:
  897. messageParams = null;
  898. break;
  899. case 1:
  900. messageParams = params[0];
  901. break;
  902. default:
  903. messageParams = params;
  904. break;
  905. }
  906. }
  907. else {
  908. method = type.method;
  909. messageParams = computeMessageParams(type, params);
  910. }
  911. let notificationMessage = {
  912. jsonrpc: version,
  913. method: method,
  914. params: messageParams
  915. };
  916. traceSendingNotification(notificationMessage);
  917. messageWriter.write(notificationMessage);
  918. },
  919. onNotification: (type, handler) => {
  920. throwIfClosedOrDisposed();
  921. if (Is.func(type)) {
  922. starNotificationHandler = type;
  923. }
  924. else if (handler) {
  925. if (Is.string(type)) {
  926. notificationHandlers[type] = { type: undefined, handler };
  927. }
  928. else {
  929. notificationHandlers[type.method] = { type, handler };
  930. }
  931. }
  932. },
  933. sendRequest: (type, ...params) => {
  934. throwIfClosedOrDisposed();
  935. throwIfNotListening();
  936. let method;
  937. let messageParams;
  938. let token = undefined;
  939. if (Is.string(type)) {
  940. method = type;
  941. switch (params.length) {
  942. case 0:
  943. messageParams = null;
  944. break;
  945. case 1:
  946. // The cancellation token is optional so it can also be undefined.
  947. if (cancellation_1.CancellationToken.is(params[0])) {
  948. messageParams = null;
  949. token = params[0];
  950. }
  951. else {
  952. messageParams = undefinedToNull(params[0]);
  953. }
  954. break;
  955. default:
  956. const last = params.length - 1;
  957. if (cancellation_1.CancellationToken.is(params[last])) {
  958. token = params[last];
  959. if (params.length === 2) {
  960. messageParams = undefinedToNull(params[0]);
  961. }
  962. else {
  963. messageParams = params.slice(0, last).map(value => undefinedToNull(value));
  964. }
  965. }
  966. else {
  967. messageParams = params.map(value => undefinedToNull(value));
  968. }
  969. break;
  970. }
  971. }
  972. else {
  973. method = type.method;
  974. messageParams = computeMessageParams(type, params);
  975. let numberOfParams = type.numberOfParams;
  976. token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
  977. }
  978. let id = sequenceNumber++;
  979. let result = new Promise((resolve, reject) => {
  980. let requestMessage = {
  981. jsonrpc: version,
  982. id: id,
  983. method: method,
  984. params: messageParams
  985. };
  986. let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };
  987. traceSendingRequest(requestMessage);
  988. try {
  989. messageWriter.write(requestMessage);
  990. }
  991. catch (e) {
  992. // Writing the message failed. So we need to reject the promise.
  993. responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
  994. responsePromise = null;
  995. }
  996. if (responsePromise) {
  997. responsePromises[String(id)] = responsePromise;
  998. }
  999. });
  1000. if (token) {
  1001. token.onCancellationRequested(() => {
  1002. connection.sendNotification(CancelNotification.type, { id });
  1003. });
  1004. }
  1005. return result;
  1006. },
  1007. onRequest: (type, handler) => {
  1008. throwIfClosedOrDisposed();
  1009. if (Is.func(type)) {
  1010. starRequestHandler = type;
  1011. }
  1012. else if (handler) {
  1013. if (Is.string(type)) {
  1014. requestHandlers[type] = { type: undefined, handler };
  1015. }
  1016. else {
  1017. requestHandlers[type.method] = { type, handler };
  1018. }
  1019. }
  1020. },
  1021. trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
  1022. let _sendNotification = false;
  1023. let _traceFormat = TraceFormat.Text;
  1024. if (sendNotificationOrTraceOptions !== void 0) {
  1025. if (Is.boolean(sendNotificationOrTraceOptions)) {
  1026. _sendNotification = sendNotificationOrTraceOptions;
  1027. }
  1028. else {
  1029. _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
  1030. _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
  1031. }
  1032. }
  1033. trace = _value;
  1034. traceFormat = _traceFormat;
  1035. if (trace === Trace.Off) {
  1036. tracer = undefined;
  1037. }
  1038. else {
  1039. tracer = _tracer;
  1040. }
  1041. if (_sendNotification && !isClosed() && !isDisposed()) {
  1042. connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
  1043. }
  1044. },
  1045. onError: errorEmitter.event,
  1046. onClose: closeEmitter.event,
  1047. onUnhandledNotification: unhandledNotificationEmitter.event,
  1048. onDispose: disposeEmitter.event,
  1049. dispose: () => {
  1050. if (isDisposed()) {
  1051. return;
  1052. }
  1053. state = ConnectionState.Disposed;
  1054. disposeEmitter.fire(undefined);
  1055. let error = new Error('Connection got disposed.');
  1056. Object.keys(responsePromises).forEach((key) => {
  1057. responsePromises[key].reject(error);
  1058. });
  1059. responsePromises = Object.create(null);
  1060. requestTokens = Object.create(null);
  1061. messageQueue = new linkedMap_1.LinkedMap();
  1062. // Test for backwards compatibility
  1063. if (Is.func(messageWriter.dispose)) {
  1064. messageWriter.dispose();
  1065. }
  1066. if (Is.func(messageReader.dispose)) {
  1067. messageReader.dispose();
  1068. }
  1069. },
  1070. listen: () => {
  1071. throwIfClosedOrDisposed();
  1072. throwIfListening();
  1073. state = ConnectionState.Listening;
  1074. messageReader.listen(callback);
  1075. },
  1076. inspect: () => {
  1077. console.log("inspect");
  1078. }
  1079. };
  1080. connection.onNotification(LogTraceNotification.type, (params) => {
  1081. if (trace === Trace.Off || !tracer) {
  1082. return;
  1083. }
  1084. tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
  1085. });
  1086. return connection;
  1087. }
  1088. function isMessageReader(value) {
  1089. return value.listen !== void 0 && value.read === void 0;
  1090. }
  1091. function isMessageWriter(value) {
  1092. return value.write !== void 0 && value.end === void 0;
  1093. }
  1094. function createMessageConnection(input, output, logger, strategy) {
  1095. if (!logger) {
  1096. logger = exports.NullLogger;
  1097. }
  1098. let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
  1099. let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
  1100. return _createMessageConnection(reader, writer, logger, strategy);
  1101. }
  1102. exports.createMessageConnection = createMessageConnection;
  1103. /***/ }),
  1104. /* 5 */
  1105. /***/ (function(module, exports, __webpack_require__) {
  1106. "use strict";
  1107. /* --------------------------------------------------------------------------------------------
  1108. * Copyright (c) Microsoft Corporation. All rights reserved.
  1109. * Licensed under the MIT License. See License.txt in the project root for license information.
  1110. * ------------------------------------------------------------------------------------------ */
  1111. Object.defineProperty(exports, "__esModule", { value: true });
  1112. function boolean(value) {
  1113. return value === true || value === false;
  1114. }
  1115. exports.boolean = boolean;
  1116. function string(value) {
  1117. return typeof value === 'string' || value instanceof String;
  1118. }
  1119. exports.string = string;
  1120. function number(value) {
  1121. return typeof value === 'number' || value instanceof Number;
  1122. }
  1123. exports.number = number;
  1124. function error(value) {
  1125. return value instanceof Error;
  1126. }
  1127. exports.error = error;
  1128. function func(value) {
  1129. return typeof value === 'function';
  1130. }
  1131. exports.func = func;
  1132. function array(value) {
  1133. return Array.isArray(value);
  1134. }
  1135. exports.array = array;
  1136. function stringArray(value) {
  1137. return array(value) && value.every(elem => string(elem));
  1138. }
  1139. exports.stringArray = stringArray;
  1140. /***/ }),
  1141. /* 6 */
  1142. /***/ (function(module, exports, __webpack_require__) {
  1143. "use strict";
  1144. /* --------------------------------------------------------------------------------------------
  1145. * Copyright (c) Microsoft Corporation. All rights reserved.
  1146. * Licensed under the MIT License. See License.txt in the project root for license information.
  1147. * ------------------------------------------------------------------------------------------ */
  1148. Object.defineProperty(exports, "__esModule", { value: true });
  1149. const is = __webpack_require__(5);
  1150. /**
  1151. * Predefined error codes.
  1152. */
  1153. var ErrorCodes;
  1154. (function (ErrorCodes) {
  1155. // Defined by JSON RPC
  1156. ErrorCodes.ParseError = -32700;
  1157. ErrorCodes.InvalidRequest = -32600;
  1158. ErrorCodes.MethodNotFound = -32601;
  1159. ErrorCodes.InvalidParams = -32602;
  1160. ErrorCodes.InternalError = -32603;
  1161. ErrorCodes.serverErrorStart = -32099;
  1162. ErrorCodes.serverErrorEnd = -32000;
  1163. ErrorCodes.ServerNotInitialized = -32002;
  1164. ErrorCodes.UnknownErrorCode = -32001;
  1165. // Defined by the protocol.
  1166. ErrorCodes.RequestCancelled = -32800;
  1167. ErrorCodes.ContentModified = -32801;
  1168. // Defined by VSCode library.
  1169. ErrorCodes.MessageWriteError = 1;
  1170. ErrorCodes.MessageReadError = 2;
  1171. })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
  1172. /**
  1173. * An error object return in a response in case a request
  1174. * has failed.
  1175. */
  1176. class ResponseError extends Error {
  1177. constructor(code, message, data) {
  1178. super(message);
  1179. this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
  1180. this.data = data;
  1181. Object.setPrototypeOf(this, ResponseError.prototype);
  1182. }
  1183. toJson() {
  1184. return {
  1185. code: this.code,
  1186. message: this.message,
  1187. data: this.data,
  1188. };
  1189. }
  1190. }
  1191. exports.ResponseError = ResponseError;
  1192. /**
  1193. * An abstract implementation of a MessageType.
  1194. */
  1195. class AbstractMessageType {
  1196. constructor(_method, _numberOfParams) {
  1197. this._method = _method;
  1198. this._numberOfParams = _numberOfParams;
  1199. }
  1200. get method() {
  1201. return this._method;
  1202. }
  1203. get numberOfParams() {
  1204. return this._numberOfParams;
  1205. }
  1206. }
  1207. exports.AbstractMessageType = AbstractMessageType;
  1208. /**
  1209. * Classes to type request response pairs
  1210. */
  1211. class RequestType0 extends AbstractMessageType {
  1212. constructor(method) {
  1213. super(method, 0);
  1214. this._ = undefined;
  1215. }
  1216. }
  1217. exports.RequestType0 = RequestType0;
  1218. class RequestType extends AbstractMessageType {
  1219. constructor(method) {
  1220. super(method, 1);
  1221. this._ = undefined;
  1222. }
  1223. }
  1224. exports.RequestType = RequestType;
  1225. class RequestType1 extends AbstractMessageType {
  1226. constructor(method) {
  1227. super(method, 1);
  1228. this._ = undefined;
  1229. }
  1230. }
  1231. exports.RequestType1 = RequestType1;
  1232. class RequestType2 extends AbstractMessageType {
  1233. constructor(method) {
  1234. super(method, 2);
  1235. this._ = undefined;
  1236. }
  1237. }
  1238. exports.RequestType2 = RequestType2;
  1239. class RequestType3 extends AbstractMessageType {
  1240. constructor(method) {
  1241. super(method, 3);
  1242. this._ = undefined;
  1243. }
  1244. }
  1245. exports.RequestType3 = RequestType3;
  1246. class RequestType4 extends AbstractMessageType {
  1247. constructor(method) {
  1248. super(method, 4);
  1249. this._ = undefined;
  1250. }
  1251. }
  1252. exports.RequestType4 = RequestType4;
  1253. class RequestType5 extends AbstractMessageType {
  1254. constructor(method) {
  1255. super(method, 5);
  1256. this._ = undefined;
  1257. }
  1258. }
  1259. exports.RequestType5 = RequestType5;
  1260. class RequestType6 extends AbstractMessageType {
  1261. constructor(method) {
  1262. super(method, 6);
  1263. this._ = undefined;
  1264. }
  1265. }
  1266. exports.RequestType6 = RequestType6;
  1267. class RequestType7 extends AbstractMessageType {
  1268. constructor(method) {
  1269. super(method, 7);
  1270. this._ = undefined;
  1271. }
  1272. }
  1273. exports.RequestType7 = RequestType7;
  1274. class RequestType8 extends AbstractMessageType {
  1275. constructor(method) {
  1276. super(method, 8);
  1277. this._ = undefined;
  1278. }
  1279. }
  1280. exports.RequestType8 = RequestType8;
  1281. class RequestType9 extends AbstractMessageType {
  1282. constructor(method) {
  1283. super(method, 9);
  1284. this._ = undefined;
  1285. }
  1286. }
  1287. exports.RequestType9 = RequestType9;
  1288. class NotificationType extends AbstractMessageType {
  1289. constructor(method) {
  1290. super(method, 1);
  1291. this._ = undefined;
  1292. }
  1293. }
  1294. exports.NotificationType = NotificationType;
  1295. class NotificationType0 extends AbstractMessageType {
  1296. constructor(method) {
  1297. super(method, 0);
  1298. this._ = undefined;
  1299. }
  1300. }
  1301. exports.NotificationType0 = NotificationType0;
  1302. class NotificationType1 extends AbstractMessageType {
  1303. constructor(method) {
  1304. super(method, 1);
  1305. this._ = undefined;
  1306. }
  1307. }
  1308. exports.NotificationType1 = NotificationType1;
  1309. class NotificationType2 extends AbstractMessageType {
  1310. constructor(method) {
  1311. super(method, 2);
  1312. this._ = undefined;
  1313. }
  1314. }
  1315. exports.NotificationType2 = NotificationType2;
  1316. class NotificationType3 extends AbstractMessageType {
  1317. constructor(method) {
  1318. super(method, 3);
  1319. this._ = undefined;
  1320. }
  1321. }
  1322. exports.NotificationType3 = NotificationType3;
  1323. class NotificationType4 extends AbstractMessageType {
  1324. constructor(method) {
  1325. super(method, 4);
  1326. this._ = undefined;
  1327. }
  1328. }
  1329. exports.NotificationType4 = NotificationType4;
  1330. class NotificationType5 extends AbstractMessageType {
  1331. constructor(method) {
  1332. super(method, 5);
  1333. this._ = undefined;
  1334. }
  1335. }
  1336. exports.NotificationType5 = NotificationType5;
  1337. class NotificationType6 extends AbstractMessageType {
  1338. constructor(method) {
  1339. super(method, 6);
  1340. this._ = undefined;
  1341. }
  1342. }
  1343. exports.NotificationType6 = NotificationType6;
  1344. class NotificationType7 extends AbstractMessageType {
  1345. constructor(method) {
  1346. super(method, 7);
  1347. this._ = undefined;
  1348. }
  1349. }
  1350. exports.NotificationType7 = NotificationType7;
  1351. class NotificationType8 extends AbstractMessageType {
  1352. constructor(method) {
  1353. super(method, 8);
  1354. this._ = undefined;
  1355. }
  1356. }
  1357. exports.NotificationType8 = NotificationType8;
  1358. class NotificationType9 extends AbstractMessageType {
  1359. constructor(method) {
  1360. super(method, 9);
  1361. this._ = undefined;
  1362. }
  1363. }
  1364. exports.NotificationType9 = NotificationType9;
  1365. /**
  1366. * Tests if the given message is a request message
  1367. */
  1368. function isRequestMessage(message) {
  1369. let candidate = message;
  1370. return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
  1371. }
  1372. exports.isRequestMessage = isRequestMessage;
  1373. /**
  1374. * Tests if the given message is a notification message
  1375. */
  1376. function isNotificationMessage(message) {
  1377. let candidate = message;
  1378. return candidate && is.string(candidate.method) && message.id === void 0;
  1379. }
  1380. exports.isNotificationMessage = isNotificationMessage;
  1381. /**
  1382. * Tests if the given message is a response message
  1383. */
  1384. function isResponseMessage(message) {
  1385. let candidate = message;
  1386. return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
  1387. }
  1388. exports.isResponseMessage = isResponseMessage;
  1389. /***/ }),
  1390. /* 7 */
  1391. /***/ (function(module, exports, __webpack_require__) {
  1392. "use strict";
  1393. /* --------------------------------------------------------------------------------------------
  1394. * Copyright (c) Microsoft Corporation. All rights reserved.
  1395. * Licensed under the MIT License. See License.txt in the project root for license information.
  1396. * ------------------------------------------------------------------------------------------ */
  1397. Object.defineProperty(exports, "__esModule", { value: true });
  1398. const events_1 = __webpack_require__(8);
  1399. const Is = __webpack_require__(5);
  1400. let DefaultSize = 8192;
  1401. let CR = Buffer.from('\r', 'ascii')[0];
  1402. let LF = Buffer.from('\n', 'ascii')[0];
  1403. let CRLF = '\r\n';
  1404. class MessageBuffer {
  1405. constructor(encoding = 'utf8') {
  1406. this.encoding = encoding;
  1407. this.index = 0;
  1408. this.buffer = Buffer.allocUnsafe(DefaultSize);
  1409. }
  1410. append(chunk) {
  1411. var toAppend = chunk;
  1412. if (typeof (chunk) === 'string') {
  1413. var str = chunk;
  1414. var bufferLen = Buffer.byteLength(str, this.encoding);
  1415. toAppend = Buffer.allocUnsafe(bufferLen);
  1416. toAppend.write(str, 0, bufferLen, this.encoding);
  1417. }
  1418. if (this.buffer.length - this.index >= toAppend.length) {
  1419. toAppend.copy(this.buffer, this.index, 0, toAppend.length);
  1420. }
  1421. else {
  1422. var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
  1423. if (this.index === 0) {
  1424. this.buffer = Buffer.allocUnsafe(newSize);
  1425. toAppend.copy(this.buffer, 0, 0, toAppend.length);
  1426. }
  1427. else {
  1428. this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
  1429. }
  1430. }
  1431. this.index += toAppend.length;
  1432. }
  1433. tryReadHeaders() {
  1434. let result = undefined;
  1435. let current = 0;
  1436. while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {
  1437. current++;
  1438. }
  1439. // No header / body separator found (e.g CRLFCRLF)
  1440. if (current + 3 >= this.index) {
  1441. return result;
  1442. }
  1443. result = Object.create(null);
  1444. let headers = this.buffer.toString('ascii', 0, current).split(CRLF);
  1445. headers.forEach((header) => {
  1446. let index = header.indexOf(':');
  1447. if (index === -1) {
  1448. throw new Error('Message header must separate key and value using :');
  1449. }
  1450. let key = header.substr(0, index);
  1451. let value = header.substr(index + 1).trim();
  1452. result[key] = value;
  1453. });
  1454. let nextStart = current + 4;
  1455. this.buffer = this.buffer.slice(nextStart);
  1456. this.index = this.index - nextStart;
  1457. return result;
  1458. }
  1459. tryReadContent(length) {
  1460. if (this.index < length) {
  1461. return null;
  1462. }
  1463. let result = this.buffer.toString(this.encoding, 0, length);
  1464. let nextStart = length;
  1465. this.buffer.copy(this.buffer, 0, nextStart);
  1466. this.index = this.index - nextStart;
  1467. return result;
  1468. }
  1469. get numberOfBytes() {
  1470. return this.index;
  1471. }
  1472. }
  1473. var MessageReader;
  1474. (function (MessageReader) {
  1475. function is(value) {
  1476. let candidate = value;
  1477. return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
  1478. Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
  1479. }
  1480. MessageReader.is = is;
  1481. })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
  1482. class AbstractMessageReader {
  1483. constructor() {
  1484. this.errorEmitter = new events_1.Emitter();
  1485. this.closeEmitter = new events_1.Emitter();
  1486. this.partialMessageEmitter = new events_1.Emitter();
  1487. }
  1488. dispose() {
  1489. this.errorEmitter.dispose();
  1490. this.closeEmitter.dispose();
  1491. }
  1492. get onError() {
  1493. return this.errorEmitter.event;
  1494. }
  1495. fireError(error) {
  1496. this.errorEmitter.fire(this.asError(error));
  1497. }
  1498. get onClose() {
  1499. return this.closeEmitter.event;
  1500. }
  1501. fireClose() {
  1502. this.closeEmitter.fire(undefined);
  1503. }
  1504. get onPartialMessage() {
  1505. return this.partialMessageEmitter.event;
  1506. }
  1507. firePartialMessage(info) {
  1508. this.partialMessageEmitter.fire(info);
  1509. }
  1510. asError(error) {
  1511. if (error instanceof Error) {
  1512. return error;
  1513. }
  1514. else {
  1515. return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
  1516. }
  1517. }
  1518. }
  1519. exports.AbstractMessageReader = AbstractMessageReader;
  1520. class StreamMessageReader extends AbstractMessageReader {
  1521. constructor(readable, encoding = 'utf8') {
  1522. super();
  1523. this.readable = readable;
  1524. this.buffer = new MessageBuffer(encoding);
  1525. this._partialMessageTimeout = 10000;
  1526. }
  1527. set partialMessageTimeout(timeout) {
  1528. this._partialMessageTimeout = timeout;
  1529. }
  1530. get partialMessageTimeout() {
  1531. return this._partialMessageTimeout;
  1532. }
  1533. listen(callback) {
  1534. this.nextMessageLength = -1;
  1535. this.messageToken = 0;
  1536. this.partialMessageTimer = undefined;
  1537. this.callback = callback;
  1538. this.readable.on('data', (data) => {
  1539. this.onData(data);
  1540. });
  1541. this.readable.on('error', (error) => this.fireError(error));
  1542. this.readable.on('close', () => this.fireClose());
  1543. }
  1544. onData(data) {
  1545. this.buffer.append(data);
  1546. while (true) {
  1547. if (this.nextMessageLength === -1) {
  1548. let headers = this.buffer.tryReadHeaders();
  1549. if (!headers) {
  1550. return;
  1551. }
  1552. let contentLength = headers['Content-Length'];
  1553. if (!contentLength) {
  1554. throw new Error('Header must provide a Content-Length property.');
  1555. }
  1556. let length = parseInt(contentLength);
  1557. if (isNaN(length)) {
  1558. throw new Error('Content-Length value must be a number.');
  1559. }
  1560. this.nextMessageLength = length;
  1561. // Take the encoding form the header. For compatibility
  1562. // treat both utf-8 and utf8 as node utf8
  1563. }
  1564. var msg = this.buffer.tryReadContent(this.nextMessageLength);
  1565. if (msg === null) {
  1566. /** We haven't received the full message yet. */
  1567. this.setPartialMessageTimer();
  1568. return;
  1569. }
  1570. this.clearPartialMessageTimer();
  1571. this.nextMessageLength = -1;
  1572. this.messageToken++;
  1573. var json = JSON.parse(msg);
  1574. this.callback(json);
  1575. }
  1576. }
  1577. clearPartialMessageTimer() {
  1578. if (this.partialMessageTimer) {
  1579. clearTimeout(this.partialMessageTimer);
  1580. this.partialMessageTimer = undefined;
  1581. }
  1582. }
  1583. setPartialMessageTimer() {
  1584. this.clearPartialMessageTimer();
  1585. if (this._partialMessageTimeout <= 0) {
  1586. return;
  1587. }
  1588. this.partialMessageTimer = setTimeout((token, timeout) => {
  1589. this.partialMessageTimer = undefined;
  1590. if (token === this.messageToken) {
  1591. this.firePartialMessage({ messageToken: token, waitingTime: timeout });
  1592. this.setPartialMessageTimer();
  1593. }
  1594. }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
  1595. }
  1596. }
  1597. exports.StreamMessageReader = StreamMessageReader;
  1598. class IPCMessageReader extends AbstractMessageReader {
  1599. constructor(process) {
  1600. super();
  1601. this.process = process;
  1602. let eventEmitter = this.process;
  1603. eventEmitter.on('error', (error) => this.fireError(error));
  1604. eventEmitter.on('close', () => this.fireClose());
  1605. }
  1606. listen(callback) {
  1607. this.process.on('message', callback);
  1608. }
  1609. }
  1610. exports.IPCMessageReader = IPCMessageReader;
  1611. class SocketMessageReader extends StreamMessageReader {
  1612. constructor(socket, encoding = 'utf-8') {
  1613. super(socket, encoding);
  1614. }
  1615. }
  1616. exports.SocketMessageReader = SocketMessageReader;
  1617. /***/ }),
  1618. /* 8 */
  1619. /***/ (function(module, exports, __webpack_require__) {
  1620. "use strict";
  1621. /* --------------------------------------------------------------------------------------------
  1622. * Copyright (c) Microsoft Corporation. All rights reserved.
  1623. * Licensed under the MIT License. See License.txt in the project root for license information.
  1624. * ------------------------------------------------------------------------------------------ */
  1625. Object.defineProperty(exports, "__esModule", { value: true });
  1626. var Disposable;
  1627. (function (Disposable) {
  1628. function create(func) {
  1629. return {
  1630. dispose: func
  1631. };
  1632. }
  1633. Disposable.create = create;
  1634. })(Disposable = exports.Disposable || (exports.Disposable = {}));
  1635. var Event;
  1636. (function (Event) {
  1637. const _disposable = { dispose() { } };
  1638. Event.None = function () { return _disposable; };
  1639. })(Event = exports.Event || (exports.Event = {}));
  1640. class CallbackList {
  1641. add(callback, context = null, bucket) {
  1642. if (!this._callbacks) {
  1643. this._callbacks = [];
  1644. this._contexts = [];
  1645. }
  1646. this._callbacks.push(callback);
  1647. this._contexts.push(context);
  1648. if (Array.isArray(bucket)) {
  1649. bucket.push({ dispose: () => this.remove(callback, context) });
  1650. }
  1651. }
  1652. remove(callback, context = null) {
  1653. if (!this._callbacks) {
  1654. return;
  1655. }
  1656. var foundCallbackWithDifferentContext = false;
  1657. for (var i = 0, len = this._callbacks.length; i < len; i++) {
  1658. if (this._callbacks[i] === callback) {
  1659. if (this._contexts[i] === context) {
  1660. // callback & context match => remove it
  1661. this._callbacks.splice(i, 1);
  1662. this._contexts.splice(i, 1);
  1663. return;
  1664. }
  1665. else {
  1666. foundCallbackWithDifferentContext = true;
  1667. }
  1668. }
  1669. }
  1670. if (foundCallbackWithDifferentContext) {
  1671. throw new Error('When adding a listener with a context, you should remove it with the same context');
  1672. }
  1673. }
  1674. invoke(...args) {
  1675. if (!this._callbacks) {
  1676. return [];
  1677. }
  1678. var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
  1679. for (var i = 0, len = callbacks.length; i < len; i++) {
  1680. try {
  1681. ret.push(callbacks[i].apply(contexts[i], args));
  1682. }
  1683. catch (e) {
  1684. console.error(e);
  1685. }
  1686. }
  1687. return ret;
  1688. }
  1689. isEmpty() {
  1690. return !this._callbacks || this._callbacks.length === 0;
  1691. }
  1692. dispose() {
  1693. this._callbacks = undefined;
  1694. this._contexts = undefined;
  1695. }
  1696. }
  1697. class Emitter {
  1698. constructor(_options) {
  1699. this._options = _options;
  1700. }
  1701. /**
  1702. * For the public to allow to subscribe
  1703. * to events from this Emitter
  1704. */
  1705. get event() {
  1706. if (!this._event) {
  1707. this._event = (listener, thisArgs, disposables) => {
  1708. if (!this._callbacks) {
  1709. this._callbacks = new CallbackList();
  1710. }
  1711. if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
  1712. this._options.onFirstListenerAdd(this);
  1713. }
  1714. this._callbacks.add(listener, thisArgs);
  1715. let result;
  1716. result = {
  1717. dispose: () => {
  1718. this._callbacks.remove(listener, thisArgs);
  1719. result.dispose = Emitter._noop;
  1720. if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
  1721. this._options.onLastListenerRemove(this);
  1722. }
  1723. }
  1724. };
  1725. if (Array.isArray(disposables)) {
  1726. disposables.push(result);
  1727. }
  1728. return result;
  1729. };
  1730. }
  1731. return this._event;
  1732. }
  1733. /**
  1734. * To be kept private to fire an event to
  1735. * subscribers
  1736. */
  1737. fire(event) {
  1738. if (this._callbacks) {
  1739. this._callbacks.invoke.call(this._callbacks, event);
  1740. }
  1741. }
  1742. dispose() {
  1743. if (this._callbacks) {
  1744. this._callbacks.dispose();
  1745. this._callbacks = undefined;
  1746. }
  1747. }
  1748. }
  1749. Emitter._noop = function () { };
  1750. exports.Emitter = Emitter;
  1751. /***/ }),
  1752. /* 9 */
  1753. /***/ (function(module, exports, __webpack_require__) {
  1754. "use strict";
  1755. /* --------------------------------------------------------------------------------------------
  1756. * Copyright (c) Microsoft Corporation. All rights reserved.
  1757. * Licensed under the MIT License. See License.txt in the project root for license information.
  1758. * ------------------------------------------------------------------------------------------ */
  1759. Object.defineProperty(exports, "__esModule", { value: true });
  1760. const events_1 = __webpack_require__(8);
  1761. const Is = __webpack_require__(5);
  1762. let ContentLength = 'Content-Length: ';
  1763. let CRLF = '\r\n';
  1764. var MessageWriter;
  1765. (function (MessageWriter) {
  1766. function is(value) {
  1767. let candidate = value;
  1768. return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
  1769. Is.func(candidate.onError) && Is.func(candidate.write);
  1770. }
  1771. MessageWriter.is = is;
  1772. })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
  1773. class AbstractMessageWriter {
  1774. constructor() {
  1775. this.errorEmitter = new events_1.Emitter();
  1776. this.closeEmitter = new events_1.Emitter();
  1777. }
  1778. dispose() {
  1779. this.errorEmitter.dispose();
  1780. this.closeEmitter.dispose();
  1781. }
  1782. get onError() {
  1783. return this.errorEmitter.event;
  1784. }
  1785. fireError(error, message, count) {
  1786. this.errorEmitter.fire([this.asError(error), message, count]);
  1787. }
  1788. get onClose() {
  1789. return this.closeEmitter.event;
  1790. }
  1791. fireClose() {
  1792. this.closeEmitter.fire(undefined);
  1793. }
  1794. asError(error) {
  1795. if (error instanceof Error) {
  1796. return error;
  1797. }
  1798. else {
  1799. return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
  1800. }
  1801. }
  1802. }
  1803. exports.AbstractMessageWriter = AbstractMessageWriter;
  1804. class StreamMessageWriter extends AbstractMessageWriter {
  1805. constructor(writable, encoding = 'utf8') {
  1806. super();
  1807. this.writable = writable;
  1808. this.encoding = encoding;
  1809. this.errorCount = 0;
  1810. this.writable.on('error', (error) => this.fireError(error));
  1811. this.writable.on('close', () => this.fireClose());
  1812. }
  1813. write(msg) {
  1814. let json = JSON.stringify(msg);
  1815. let contentLength = Buffer.byteLength(json, this.encoding);
  1816. let headers = [
  1817. ContentLength, contentLength.toString(), CRLF,
  1818. CRLF
  1819. ];
  1820. try {
  1821. // Header must be written in ASCII encoding
  1822. this.writable.write(headers.join(''), 'ascii');
  1823. // Now write the content. This can be written in any encoding
  1824. this.writable.write(json, this.encoding);
  1825. this.errorCount = 0;
  1826. }
  1827. catch (error) {
  1828. this.errorCount++;
  1829. this.fireError(error, msg, this.errorCount);
  1830. }
  1831. }
  1832. }
  1833. exports.StreamMessageWriter = StreamMessageWriter;
  1834. class IPCMessageWriter extends AbstractMessageWriter {
  1835. constructor(process) {
  1836. super();
  1837. this.process = process;
  1838. this.errorCount = 0;
  1839. this.queue = [];
  1840. this.sending = false;
  1841. let eventEmitter = this.process;
  1842. eventEmitter.on('error', (error) => this.fireError(error));
  1843. eventEmitter.on('close', () => this.fireClose);
  1844. }
  1845. write(msg) {
  1846. if (!this.sending && this.queue.length === 0) {
  1847. // See https://github.com/nodejs/node/issues/7657
  1848. this.doWriteMessage(msg);
  1849. }
  1850. else {
  1851. this.queue.push(msg);
  1852. }
  1853. }
  1854. doWriteMessage(msg) {
  1855. try {
  1856. if (this.process.send) {
  1857. this.sending = true;
  1858. this.process.send(msg, undefined, undefined, (error) => {
  1859. this.sending = false;
  1860. if (error) {
  1861. this.errorCount++;
  1862. this.fireError(error, msg, this.errorCount);
  1863. }
  1864. else {
  1865. this.errorCount = 0;
  1866. }
  1867. if (this.queue.length > 0) {
  1868. this.doWriteMessage(this.queue.shift());
  1869. }
  1870. });
  1871. }
  1872. }
  1873. catch (error) {
  1874. this.errorCount++;
  1875. this.fireError(error, msg, this.errorCount);
  1876. }
  1877. }
  1878. }
  1879. exports.IPCMessageWriter = IPCMessageWriter;
  1880. class SocketMessageWriter extends AbstractMessageWriter {
  1881. constructor(socket, encoding = 'utf8') {
  1882. super();
  1883. this.socket = socket;
  1884. this.queue = [];
  1885. this.sending = false;
  1886. this.encoding = encoding;
  1887. this.errorCount = 0;
  1888. this.socket.on('error', (error) => this.fireError(error));
  1889. this.socket.on('close', () => this.fireClose());
  1890. }
  1891. dispose() {
  1892. super.dispose();
  1893. this.socket.destroy();
  1894. }
  1895. write(msg) {
  1896. if (!this.sending && this.queue.length === 0) {
  1897. // See https://github.com/nodejs/node/issues/7657
  1898. this.doWriteMessage(msg);
  1899. }
  1900. else {
  1901. this.queue.push(msg);
  1902. }
  1903. }
  1904. doWriteMessage(msg) {
  1905. let json = JSON.stringify(msg);
  1906. let contentLength = Buffer.byteLength(json, this.encoding);
  1907. let headers = [
  1908. ContentLength, contentLength.toString(), CRLF,
  1909. CRLF
  1910. ];
  1911. try {
  1912. // Header must be written in ASCII encoding
  1913. this.sending = true;
  1914. this.socket.write(headers.join(''), 'ascii', (error) => {
  1915. if (error) {
  1916. this.handleError(error, msg);
  1917. }
  1918. try {
  1919. // Now write the content. This can be written in any encoding
  1920. this.socket.write(json, this.encoding, (error) => {
  1921. this.sending = false;
  1922. if (error) {
  1923. this.handleError(error, msg);
  1924. }
  1925. else {
  1926. this.errorCount = 0;
  1927. }
  1928. if (this.queue.length > 0) {
  1929. this.doWriteMessage(this.queue.shift());
  1930. }
  1931. });
  1932. }
  1933. catch (error) {
  1934. this.handleError(error, msg);
  1935. }
  1936. });
  1937. }
  1938. catch (error) {
  1939. this.handleError(error, msg);
  1940. }
  1941. }
  1942. handleError(error, msg) {
  1943. this.errorCount++;
  1944. this.fireError(error, msg, this.errorCount);
  1945. }
  1946. }
  1947. exports.SocketMessageWriter = SocketMessageWriter;
  1948. /***/ }),
  1949. /* 10 */
  1950. /***/ (function(module, exports, __webpack_require__) {
  1951. "use strict";
  1952. /*---------------------------------------------------------------------------------------------
  1953. * Copyright (c) Microsoft Corporation. All rights reserved.
  1954. * Licensed under the MIT License. See License.txt in the project root for license information.
  1955. *--------------------------------------------------------------------------------------------*/
  1956. Object.defineProperty(exports, "__esModule", { value: true });
  1957. const events_1 = __webpack_require__(8);
  1958. const Is = __webpack_require__(5);
  1959. var CancellationToken;
  1960. (function (CancellationToken) {
  1961. CancellationToken.None = Object.freeze({
  1962. isCancellationRequested: false,
  1963. onCancellationRequested: events_1.Event.None
  1964. });
  1965. CancellationToken.Cancelled = Object.freeze({
  1966. isCancellationRequested: true,
  1967. onCancellationRequested: events_1.Event.None
  1968. });
  1969. function is(value) {
  1970. let candidate = value;
  1971. return candidate && (candidate === CancellationToken.None
  1972. || candidate === CancellationToken.Cancelled
  1973. || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
  1974. }
  1975. CancellationToken.is = is;
  1976. })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
  1977. const shortcutEvent = Object.freeze(function (callback, context) {
  1978. let handle = setTimeout(callback.bind(context), 0);
  1979. return { dispose() { clearTimeout(handle); } };
  1980. });
  1981. class MutableToken {
  1982. constructor() {
  1983. this._isCancelled = false;
  1984. }
  1985. cancel() {
  1986. if (!this._isCancelled) {
  1987. this._isCancelled = true;
  1988. if (this._emitter) {
  1989. this._emitter.fire(undefined);
  1990. this.dispose();
  1991. }
  1992. }
  1993. }
  1994. get isCancellationRequested() {
  1995. return this._isCancelled;
  1996. }
  1997. get onCancellationRequested() {
  1998. if (this._isCancelled) {
  1999. return shortcutEvent;
  2000. }
  2001. if (!this._emitter) {
  2002. this._emitter = new events_1.Emitter();
  2003. }
  2004. return this._emitter.event;
  2005. }
  2006. dispose() {
  2007. if (this._emitter) {
  2008. this._emitter.dispose();
  2009. this._emitter = undefined;
  2010. }
  2011. }
  2012. }
  2013. class CancellationTokenSource {
  2014. get token() {
  2015. if (!this._token) {
  2016. // be lazy and create the token only when
  2017. // actually needed
  2018. this._token = new MutableToken();
  2019. }
  2020. return this._token;
  2021. }
  2022. cancel() {
  2023. if (!this._token) {
  2024. // save an object by returning the default
  2025. // cancelled token when cancellation happens
  2026. // before someone asks for the token
  2027. this._token = CancellationToken.Cancelled;
  2028. }
  2029. else {
  2030. this._token.cancel();
  2031. }
  2032. }
  2033. dispose() {
  2034. if (!this._token) {
  2035. // ensure to initialize with an empty token if we had none
  2036. this._token = CancellationToken.None;
  2037. }
  2038. else if (this._token instanceof MutableToken) {
  2039. // actually dispose
  2040. this._token.dispose();
  2041. }
  2042. }
  2043. }
  2044. exports.CancellationTokenSource = CancellationTokenSource;
  2045. /***/ }),
  2046. /* 11 */
  2047. /***/ (function(module, exports, __webpack_require__) {
  2048. "use strict";
  2049. /*---------------------------------------------------------------------------------------------
  2050. * Copyright (c) Microsoft Corporation. All rights reserved.
  2051. * Licensed under the MIT License. See License.txt in the project root for license information.
  2052. *--------------------------------------------------------------------------------------------*/
  2053. Object.defineProperty(exports, "__esModule", { value: true });
  2054. var Touch;
  2055. (function (Touch) {
  2056. Touch.None = 0;
  2057. Touch.First = 1;
  2058. Touch.Last = 2;
  2059. })(Touch = exports.Touch || (exports.Touch = {}));
  2060. class LinkedMap {
  2061. constructor() {
  2062. this._map = new Map();
  2063. this._head = undefined;
  2064. this._tail = undefined;
  2065. this._size = 0;
  2066. }
  2067. clear() {
  2068. this._map.clear();
  2069. this._head = undefined;
  2070. this._tail = undefined;
  2071. this._size = 0;
  2072. }
  2073. isEmpty() {
  2074. return !this._head && !this._tail;
  2075. }
  2076. get size() {
  2077. return this._size;
  2078. }
  2079. has(key) {
  2080. return this._map.has(key);
  2081. }
  2082. get(key) {
  2083. const item = this._map.get(key);
  2084. if (!item) {
  2085. return undefined;
  2086. }
  2087. return item.value;
  2088. }
  2089. set(key, value, touch = Touch.None) {
  2090. let item = this._map.get(key);
  2091. if (item) {
  2092. item.value = value;
  2093. if (touch !== Touch.None) {
  2094. this.touch(item, touch);
  2095. }
  2096. }
  2097. else {
  2098. item = { key, value, next: undefined, previous: undefined };
  2099. switch (touch) {
  2100. case Touch.None:
  2101. this.addItemLast(item);
  2102. break;
  2103. case Touch.First:
  2104. this.addItemFirst(item);
  2105. break;
  2106. case Touch.Last:
  2107. this.addItemLast(item);
  2108. break;
  2109. default:
  2110. this.addItemLast(item);
  2111. break;
  2112. }
  2113. this._map.set(key, item);
  2114. this._size++;
  2115. }
  2116. }
  2117. delete(key) {
  2118. const item = this._map.get(key);
  2119. if (!item) {
  2120. return false;
  2121. }
  2122. this._map.delete(key);
  2123. this.removeItem(item);
  2124. this._size--;
  2125. return true;
  2126. }
  2127. shift() {
  2128. if (!this._head && !this._tail) {
  2129. return undefined;
  2130. }
  2131. if (!this._head || !this._tail) {
  2132. throw new Error('Invalid list');
  2133. }
  2134. const item = this._head;
  2135. this._map.delete(item.key);
  2136. this.removeItem(item);
  2137. this._size--;
  2138. return item.value;
  2139. }
  2140. forEach(callbackfn, thisArg) {
  2141. let current = this._head;
  2142. while (current) {
  2143. if (thisArg) {
  2144. callbackfn.bind(thisArg)(current.value, current.key, this);
  2145. }
  2146. else {
  2147. callbackfn(current.value, current.key, this);
  2148. }
  2149. current = current.next;
  2150. }
  2151. }
  2152. forEachReverse(callbackfn, thisArg) {
  2153. let current = this._tail;
  2154. while (current) {
  2155. if (thisArg) {
  2156. callbackfn.bind(thisArg)(current.value, current.key, this);
  2157. }
  2158. else {
  2159. callbackfn(current.value, current.key, this);
  2160. }
  2161. current = current.previous;
  2162. }
  2163. }
  2164. values() {
  2165. let result = [];
  2166. let current = this._head;
  2167. while (current) {
  2168. result.push(current.value);
  2169. current = current.next;
  2170. }
  2171. return result;
  2172. }
  2173. keys() {
  2174. let result = [];
  2175. let current = this._head;
  2176. while (current) {
  2177. result.push(current.key);
  2178. current = current.next;
  2179. }
  2180. return result;
  2181. }
  2182. /* JSON RPC run on es5 which has no Symbol.iterator
  2183. public keys(): IterableIterator<K> {
  2184. let current = this._head;
  2185. let iterator: IterableIterator<K> = {
  2186. [Symbol.iterator]() {
  2187. return iterator;
  2188. },
  2189. next():IteratorResult<K> {
  2190. if (current) {
  2191. let result = { value: current.key, done: false };
  2192. current = current.next;
  2193. return result;
  2194. } else {
  2195. return { value: undefined, done: true };
  2196. }
  2197. }
  2198. };
  2199. return iterator;
  2200. }
  2201. public values(): IterableIterator<V> {
  2202. let current = this._head;
  2203. let iterator: IterableIterator<V> = {
  2204. [Symbol.iterator]() {
  2205. return iterator;
  2206. },
  2207. next():IteratorResult<V> {
  2208. if (current) {
  2209. let result = { value: current.value, done: false };
  2210. current = current.next;
  2211. return result;
  2212. } else {
  2213. return { value: undefined, done: true };
  2214. }
  2215. }
  2216. };
  2217. return iterator;
  2218. }
  2219. */
  2220. addItemFirst(item) {
  2221. // First time Insert
  2222. if (!this._head && !this._tail) {
  2223. this._tail = item;
  2224. }
  2225. else if (!this._head) {
  2226. throw new Error('Invalid list');
  2227. }
  2228. else {
  2229. item.next = this._head;
  2230. this._head.previous = item;
  2231. }
  2232. this._head = item;
  2233. }
  2234. addItemLast(item) {
  2235. // First time Insert
  2236. if (!this._head && !this._tail) {
  2237. this._head = item;
  2238. }
  2239. else if (!this._tail) {
  2240. throw new Error('Invalid list');
  2241. }
  2242. else {
  2243. item.previous = this._tail;
  2244. this._tail.next = item;
  2245. }
  2246. this._tail = item;
  2247. }
  2248. removeItem(item) {
  2249. if (item === this._head && item === this._tail) {
  2250. this._head = undefined;
  2251. this._tail = undefined;
  2252. }
  2253. else if (item === this._head) {
  2254. this._head = item.next;
  2255. }
  2256. else if (item === this._tail) {
  2257. this._tail = item.previous;
  2258. }
  2259. else {
  2260. const next = item.next;
  2261. const previous = item.previous;
  2262. if (!next || !previous) {
  2263. throw new Error('Invalid list');
  2264. }
  2265. next.previous = previous;
  2266. previous.next = next;
  2267. }
  2268. }
  2269. touch(item, touch) {
  2270. if (!this._head || !this._tail) {
  2271. throw new Error('Invalid list');
  2272. }
  2273. if ((touch !== Touch.First && touch !== Touch.Last)) {
  2274. return;
  2275. }
  2276. if (touch === Touch.First) {
  2277. if (item === this._head) {
  2278. return;
  2279. }
  2280. const next = item.next;
  2281. const previous = item.previous;
  2282. // Unlink the item
  2283. if (item === this._tail) {
  2284. // previous must be defined since item was not head but is tail
  2285. // So there are more than on item in the map
  2286. previous.next = undefined;
  2287. this._tail = previous;
  2288. }
  2289. else {
  2290. // Both next and previous are not undefined since item was neither head nor tail.
  2291. next.previous = previous;
  2292. previous.next = next;
  2293. }
  2294. // Insert the node at head
  2295. item.previous = undefined;
  2296. item.next = this._head;
  2297. this._head.previous = item;
  2298. this._head = item;
  2299. }
  2300. else if (touch === Touch.Last) {
  2301. if (item === this._tail) {
  2302. return;
  2303. }
  2304. const next = item.next;
  2305. const previous = item.previous;
  2306. // Unlink the item.
  2307. if (item === this._head) {
  2308. // next must be defined since item was not tail but is head
  2309. // So there are more than on item in the map
  2310. next.previous = undefined;
  2311. this._head = next;
  2312. }
  2313. else {
  2314. // Both next and previous are not undefined since item was neither head nor tail.
  2315. next.previous = previous;
  2316. previous.next = next;
  2317. }
  2318. item.next = undefined;
  2319. item.previous = this._tail;
  2320. this._tail.next = item;
  2321. this._tail = item;
  2322. }
  2323. }
  2324. }
  2325. exports.LinkedMap = LinkedMap;
  2326. /***/ }),
  2327. /* 12 */
  2328. /***/ (function(module, exports, __webpack_require__) {
  2329. "use strict";
  2330. /* --------------------------------------------------------------------------------------------
  2331. * Copyright (c) Microsoft Corporation. All rights reserved.
  2332. * Licensed under the MIT License. See License.txt in the project root for license information.
  2333. * ------------------------------------------------------------------------------------------ */
  2334. Object.defineProperty(exports, "__esModule", { value: true });
  2335. const path_1 = __webpack_require__(1);
  2336. const os_1 = __webpack_require__(13);
  2337. const crypto_1 = __webpack_require__(14);
  2338. const net_1 = __webpack_require__(15);
  2339. const messageReader_1 = __webpack_require__(7);
  2340. const messageWriter_1 = __webpack_require__(9);
  2341. function generateRandomPipeName() {
  2342. const randomSuffix = crypto_1.randomBytes(21).toString('hex');
  2343. if (process.platform === 'win32') {
  2344. return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
  2345. }
  2346. else {
  2347. // Mac/Unix: use socket file
  2348. return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
  2349. }
  2350. }
  2351. exports.generateRandomPipeName = generateRandomPipeName;
  2352. function createClientPipeTransport(pipeName, encoding = 'utf-8') {
  2353. let connectResolve;
  2354. let connected = new Promise((resolve, _reject) => {
  2355. connectResolve = resolve;
  2356. });
  2357. return new Promise((resolve, reject) => {
  2358. let server = net_1.createServer((socket) => {
  2359. server.close();
  2360. connectResolve([
  2361. new messageReader_1.SocketMessageReader(socket, encoding),
  2362. new messageWriter_1.SocketMessageWriter(socket, encoding)
  2363. ]);
  2364. });
  2365. server.on('error', reject);
  2366. server.listen(pipeName, () => {
  2367. server.removeListener('error', reject);
  2368. resolve({
  2369. onConnected: () => { return connected; }
  2370. });
  2371. });
  2372. });
  2373. }
  2374. exports.createClientPipeTransport = createClientPipeTransport;
  2375. function createServerPipeTransport(pipeName, encoding = 'utf-8') {
  2376. const socket = net_1.createConnection(pipeName);
  2377. return [
  2378. new messageReader_1.SocketMessageReader(socket, encoding),
  2379. new messageWriter_1.SocketMessageWriter(socket, encoding)
  2380. ];
  2381. }
  2382. exports.createServerPipeTransport = createServerPipeTransport;
  2383. /***/ }),
  2384. /* 13 */
  2385. /***/ (function(module, exports) {
  2386. module.exports = require("os");
  2387. /***/ }),
  2388. /* 14 */
  2389. /***/ (function(module, exports) {
  2390. module.exports = require("crypto");
  2391. /***/ }),
  2392. /* 15 */
  2393. /***/ (function(module, exports) {
  2394. module.exports = require("net");
  2395. /***/ }),
  2396. /* 16 */
  2397. /***/ (function(module, exports, __webpack_require__) {
  2398. "use strict";
  2399. /* --------------------------------------------------------------------------------------------
  2400. * Copyright (c) Microsoft Corporation. All rights reserved.
  2401. * Licensed under the MIT License. See License.txt in the project root for license information.
  2402. * ------------------------------------------------------------------------------------------ */
  2403. Object.defineProperty(exports, "__esModule", { value: true });
  2404. const net_1 = __webpack_require__(15);
  2405. const messageReader_1 = __webpack_require__(7);
  2406. const messageWriter_1 = __webpack_require__(9);
  2407. function createClientSocketTransport(port, encoding = 'utf-8') {
  2408. let connectResolve;
  2409. let connected = new Promise((resolve, _reject) => {
  2410. connectResolve = resolve;
  2411. });
  2412. return new Promise((resolve, reject) => {
  2413. let server = net_1.createServer((socket) => {
  2414. server.close();
  2415. connectResolve([
  2416. new messageReader_1.SocketMessageReader(socket, encoding),
  2417. new messageWriter_1.SocketMessageWriter(socket, encoding)
  2418. ]);
  2419. });
  2420. server.on('error', reject);
  2421. server.listen(port, '127.0.0.1', () => {
  2422. server.removeListener('error', reject);
  2423. resolve({
  2424. onConnected: () => { return connected; }
  2425. });
  2426. });
  2427. });
  2428. }
  2429. exports.createClientSocketTransport = createClientSocketTransport;
  2430. function createServerSocketTransport(port, encoding = 'utf-8') {
  2431. const socket = net_1.createConnection(port, '127.0.0.1');
  2432. return [
  2433. new messageReader_1.SocketMessageReader(socket, encoding),
  2434. new messageWriter_1.SocketMessageWriter(socket, encoding)
  2435. ];
  2436. }
  2437. exports.createServerSocketTransport = createServerSocketTransport;
  2438. /***/ }),
  2439. /* 17 */
  2440. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  2441. "use strict";
  2442. __webpack_require__.r(__webpack_exports__);
  2443. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
  2444. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
  2445. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
  2446. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
  2447. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
  2448. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
  2449. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
  2450. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
  2451. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
  2452. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
  2453. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
  2454. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
  2455. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
  2456. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
  2457. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
  2458. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
  2459. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
  2460. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
  2461. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
  2462. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
  2463. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
  2464. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
  2465. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
  2466. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
  2467. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
  2468. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
  2469. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
  2470. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
  2471. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
  2472. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
  2473. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
  2474. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
  2475. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
  2476. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
  2477. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
  2478. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
  2479. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
  2480. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
  2481. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
  2482. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
  2483. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
  2484. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
  2485. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
  2486. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
  2487. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
  2488. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
  2489. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
  2490. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentSaveReason", function() { return TextDocumentSaveReason; });
  2491. /* --------------------------------------------------------------------------------------------
  2492. * Copyright (c) Microsoft Corporation. All rights reserved.
  2493. * Licensed under the MIT License. See License.txt in the project root for license information.
  2494. * ------------------------------------------------------------------------------------------ */
  2495. /**
  2496. * The Position namespace provides helper functions to work with
  2497. * [Position](#Position) literals.
  2498. */
  2499. var Position;
  2500. (function (Position) {
  2501. /**
  2502. * Creates a new Position literal from the given line and character.
  2503. * @param line The position's line.
  2504. * @param character The position's character.
  2505. */
  2506. function create(line, character) {
  2507. return { line: line, character: character };
  2508. }
  2509. Position.create = create;
  2510. /**
  2511. * Checks whether the given liternal conforms to the [Position](#Position) interface.
  2512. */
  2513. function is(value) {
  2514. var candidate = value;
  2515. return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
  2516. }
  2517. Position.is = is;
  2518. })(Position || (Position = {}));
  2519. /**
  2520. * The Range namespace provides helper functions to work with
  2521. * [Range](#Range) literals.
  2522. */
  2523. var Range;
  2524. (function (Range) {
  2525. function create(one, two, three, four) {
  2526. if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
  2527. return { start: Position.create(one, two), end: Position.create(three, four) };
  2528. }
  2529. else if (Position.is(one) && Position.is(two)) {
  2530. return { start: one, end: two };
  2531. }
  2532. else {
  2533. throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
  2534. }
  2535. }
  2536. Range.create = create;
  2537. /**
  2538. * Checks whether the given literal conforms to the [Range](#Range) interface.
  2539. */
  2540. function is(value) {
  2541. var candidate = value;
  2542. return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
  2543. }
  2544. Range.is = is;
  2545. })(Range || (Range = {}));
  2546. /**
  2547. * The Location namespace provides helper functions to work with
  2548. * [Location](#Location) literals.
  2549. */
  2550. var Location;
  2551. (function (Location) {
  2552. /**
  2553. * Creates a Location literal.
  2554. * @param uri The location's uri.
  2555. * @param range The location's range.
  2556. */
  2557. function create(uri, range) {
  2558. return { uri: uri, range: range };
  2559. }
  2560. Location.create = create;
  2561. /**
  2562. * Checks whether the given literal conforms to the [Location](#Location) interface.
  2563. */
  2564. function is(value) {
  2565. var candidate = value;
  2566. return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
  2567. }
  2568. Location.is = is;
  2569. })(Location || (Location = {}));
  2570. /**
  2571. * The LocationLink namespace provides helper functions to work with
  2572. * [LocationLink](#LocationLink) literals.
  2573. */
  2574. var LocationLink;
  2575. (function (LocationLink) {
  2576. /**
  2577. * Creates a LocationLink literal.
  2578. * @param targetUri The definition's uri.
  2579. * @param targetRange The full range of the definition.
  2580. * @param targetSelectionRange The span of the symbol definition at the target.
  2581. * @param originSelectionRange The span of the symbol being defined in the originating source file.
  2582. */
  2583. function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
  2584. return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
  2585. }
  2586. LocationLink.create = create;
  2587. /**
  2588. * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
  2589. */
  2590. function is(value) {
  2591. var candidate = value;
  2592. return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
  2593. && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
  2594. && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
  2595. }
  2596. LocationLink.is = is;
  2597. })(LocationLink || (LocationLink = {}));
  2598. /**
  2599. * The Color namespace provides helper functions to work with
  2600. * [Color](#Color) literals.
  2601. */
  2602. var Color;
  2603. (function (Color) {
  2604. /**
  2605. * Creates a new Color literal.
  2606. */
  2607. function create(red, green, blue, alpha) {
  2608. return {
  2609. red: red,
  2610. green: green,
  2611. blue: blue,
  2612. alpha: alpha,
  2613. };
  2614. }
  2615. Color.create = create;
  2616. /**
  2617. * Checks whether the given literal conforms to the [Color](#Color) interface.
  2618. */
  2619. function is(value) {
  2620. var candidate = value;
  2621. return Is.number(candidate.red)
  2622. && Is.number(candidate.green)
  2623. && Is.number(candidate.blue)
  2624. && Is.number(candidate.alpha);
  2625. }
  2626. Color.is = is;
  2627. })(Color || (Color = {}));
  2628. /**
  2629. * The ColorInformation namespace provides helper functions to work with
  2630. * [ColorInformation](#ColorInformation) literals.
  2631. */
  2632. var ColorInformation;
  2633. (function (ColorInformation) {
  2634. /**
  2635. * Creates a new ColorInformation literal.
  2636. */
  2637. function create(range, color) {
  2638. return {
  2639. range: range,
  2640. color: color,
  2641. };
  2642. }
  2643. ColorInformation.create = create;
  2644. /**
  2645. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  2646. */
  2647. function is(value) {
  2648. var candidate = value;
  2649. return Range.is(candidate.range) && Color.is(candidate.color);
  2650. }
  2651. ColorInformation.is = is;
  2652. })(ColorInformation || (ColorInformation = {}));
  2653. /**
  2654. * The Color namespace provides helper functions to work with
  2655. * [ColorPresentation](#ColorPresentation) literals.
  2656. */
  2657. var ColorPresentation;
  2658. (function (ColorPresentation) {
  2659. /**
  2660. * Creates a new ColorInformation literal.
  2661. */
  2662. function create(label, textEdit, additionalTextEdits) {
  2663. return {
  2664. label: label,
  2665. textEdit: textEdit,
  2666. additionalTextEdits: additionalTextEdits,
  2667. };
  2668. }
  2669. ColorPresentation.create = create;
  2670. /**
  2671. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  2672. */
  2673. function is(value) {
  2674. var candidate = value;
  2675. return Is.string(candidate.label)
  2676. && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
  2677. && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
  2678. }
  2679. ColorPresentation.is = is;
  2680. })(ColorPresentation || (ColorPresentation = {}));
  2681. /**
  2682. * Enum of known range kinds
  2683. */
  2684. var FoldingRangeKind;
  2685. (function (FoldingRangeKind) {
  2686. /**
  2687. * Folding range for a comment
  2688. */
  2689. FoldingRangeKind["Comment"] = "comment";
  2690. /**
  2691. * Folding range for a imports or includes
  2692. */
  2693. FoldingRangeKind["Imports"] = "imports";
  2694. /**
  2695. * Folding range for a region (e.g. `#region`)
  2696. */
  2697. FoldingRangeKind["Region"] = "region";
  2698. })(FoldingRangeKind || (FoldingRangeKind = {}));
  2699. /**
  2700. * The folding range namespace provides helper functions to work with
  2701. * [FoldingRange](#FoldingRange) literals.
  2702. */
  2703. var FoldingRange;
  2704. (function (FoldingRange) {
  2705. /**
  2706. * Creates a new FoldingRange literal.
  2707. */
  2708. function create(startLine, endLine, startCharacter, endCharacter, kind) {
  2709. var result = {
  2710. startLine: startLine,
  2711. endLine: endLine
  2712. };
  2713. if (Is.defined(startCharacter)) {
  2714. result.startCharacter = startCharacter;
  2715. }
  2716. if (Is.defined(endCharacter)) {
  2717. result.endCharacter = endCharacter;
  2718. }
  2719. if (Is.defined(kind)) {
  2720. result.kind = kind;
  2721. }
  2722. return result;
  2723. }
  2724. FoldingRange.create = create;
  2725. /**
  2726. * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
  2727. */
  2728. function is(value) {
  2729. var candidate = value;
  2730. return Is.number(candidate.startLine) && Is.number(candidate.startLine)
  2731. && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
  2732. && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
  2733. && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
  2734. }
  2735. FoldingRange.is = is;
  2736. })(FoldingRange || (FoldingRange = {}));
  2737. /**
  2738. * The DiagnosticRelatedInformation namespace provides helper functions to work with
  2739. * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
  2740. */
  2741. var DiagnosticRelatedInformation;
  2742. (function (DiagnosticRelatedInformation) {
  2743. /**
  2744. * Creates a new DiagnosticRelatedInformation literal.
  2745. */
  2746. function create(location, message) {
  2747. return {
  2748. location: location,
  2749. message: message
  2750. };
  2751. }
  2752. DiagnosticRelatedInformation.create = create;
  2753. /**
  2754. * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
  2755. */
  2756. function is(value) {
  2757. var candidate = value;
  2758. return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
  2759. }
  2760. DiagnosticRelatedInformation.is = is;
  2761. })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
  2762. /**
  2763. * The diagnostic's severity.
  2764. */
  2765. var DiagnosticSeverity;
  2766. (function (DiagnosticSeverity) {
  2767. /**
  2768. * Reports an error.
  2769. */
  2770. DiagnosticSeverity.Error = 1;
  2771. /**
  2772. * Reports a warning.
  2773. */
  2774. DiagnosticSeverity.Warning = 2;
  2775. /**
  2776. * Reports an information.
  2777. */
  2778. DiagnosticSeverity.Information = 3;
  2779. /**
  2780. * Reports a hint.
  2781. */
  2782. DiagnosticSeverity.Hint = 4;
  2783. })(DiagnosticSeverity || (DiagnosticSeverity = {}));
  2784. var DiagnosticTag;
  2785. (function (DiagnosticTag) {
  2786. /**
  2787. * Unused or unnecessary code.
  2788. *
  2789. * Clients are allowed to render diagnostics with this tag faded out instead of having
  2790. * an error squiggle.
  2791. */
  2792. DiagnosticTag.Unnecessary = 1;
  2793. })(DiagnosticTag || (DiagnosticTag = {}));
  2794. /**
  2795. * The Diagnostic namespace provides helper functions to work with
  2796. * [Diagnostic](#Diagnostic) literals.
  2797. */
  2798. var Diagnostic;
  2799. (function (Diagnostic) {
  2800. /**
  2801. * Creates a new Diagnostic literal.
  2802. */
  2803. function create(range, message, severity, code, source, relatedInformation) {
  2804. var result = { range: range, message: message };
  2805. if (Is.defined(severity)) {
  2806. result.severity = severity;
  2807. }
  2808. if (Is.defined(code)) {
  2809. result.code = code;
  2810. }
  2811. if (Is.defined(source)) {
  2812. result.source = source;
  2813. }
  2814. if (Is.defined(relatedInformation)) {
  2815. result.relatedInformation = relatedInformation;
  2816. }
  2817. return result;
  2818. }
  2819. Diagnostic.create = create;
  2820. /**
  2821. * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
  2822. */
  2823. function is(value) {
  2824. var candidate = value;
  2825. return Is.defined(candidate)
  2826. && Range.is(candidate.range)
  2827. && Is.string(candidate.message)
  2828. && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
  2829. && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
  2830. && (Is.string(candidate.source) || Is.undefined(candidate.source))
  2831. && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
  2832. }
  2833. Diagnostic.is = is;
  2834. })(Diagnostic || (Diagnostic = {}));
  2835. /**
  2836. * The Command namespace provides helper functions to work with
  2837. * [Command](#Command) literals.
  2838. */
  2839. var Command;
  2840. (function (Command) {
  2841. /**
  2842. * Creates a new Command literal.
  2843. */
  2844. function create(title, command) {
  2845. var args = [];
  2846. for (var _i = 2; _i < arguments.length; _i++) {
  2847. args[_i - 2] = arguments[_i];
  2848. }
  2849. var result = { title: title, command: command };
  2850. if (Is.defined(args) && args.length > 0) {
  2851. result.arguments = args;
  2852. }
  2853. return result;
  2854. }
  2855. Command.create = create;
  2856. /**
  2857. * Checks whether the given literal conforms to the [Command](#Command) interface.
  2858. */
  2859. function is(value) {
  2860. var candidate = value;
  2861. return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
  2862. }
  2863. Command.is = is;
  2864. })(Command || (Command = {}));
  2865. /**
  2866. * The TextEdit namespace provides helper function to create replace,
  2867. * insert and delete edits more easily.
  2868. */
  2869. var TextEdit;
  2870. (function (TextEdit) {
  2871. /**
  2872. * Creates a replace text edit.
  2873. * @param range The range of text to be replaced.
  2874. * @param newText The new text.
  2875. */
  2876. function replace(range, newText) {
  2877. return { range: range, newText: newText };
  2878. }
  2879. TextEdit.replace = replace;
  2880. /**
  2881. * Creates a insert text edit.
  2882. * @param position The position to insert the text at.
  2883. * @param newText The text to be inserted.
  2884. */
  2885. function insert(position, newText) {
  2886. return { range: { start: position, end: position }, newText: newText };
  2887. }
  2888. TextEdit.insert = insert;
  2889. /**
  2890. * Creates a delete text edit.
  2891. * @param range The range of text to be deleted.
  2892. */
  2893. function del(range) {
  2894. return { range: range, newText: '' };
  2895. }
  2896. TextEdit.del = del;
  2897. function is(value) {
  2898. var candidate = value;
  2899. return Is.objectLiteral(candidate)
  2900. && Is.string(candidate.newText)
  2901. && Range.is(candidate.range);
  2902. }
  2903. TextEdit.is = is;
  2904. })(TextEdit || (TextEdit = {}));
  2905. /**
  2906. * The TextDocumentEdit namespace provides helper function to create
  2907. * an edit that manipulates a text document.
  2908. */
  2909. var TextDocumentEdit;
  2910. (function (TextDocumentEdit) {
  2911. /**
  2912. * Creates a new `TextDocumentEdit`
  2913. */
  2914. function create(textDocument, edits) {
  2915. return { textDocument: textDocument, edits: edits };
  2916. }
  2917. TextDocumentEdit.create = create;
  2918. function is(value) {
  2919. var candidate = value;
  2920. return Is.defined(candidate)
  2921. && VersionedTextDocumentIdentifier.is(candidate.textDocument)
  2922. && Array.isArray(candidate.edits);
  2923. }
  2924. TextDocumentEdit.is = is;
  2925. })(TextDocumentEdit || (TextDocumentEdit = {}));
  2926. var CreateFile;
  2927. (function (CreateFile) {
  2928. function create(uri, options) {
  2929. var result = {
  2930. kind: 'create',
  2931. uri: uri
  2932. };
  2933. if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
  2934. result.options = options;
  2935. }
  2936. return result;
  2937. }
  2938. CreateFile.create = create;
  2939. function is(value) {
  2940. var candidate = value;
  2941. return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
  2942. (candidate.options === void 0 ||
  2943. ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
  2944. }
  2945. CreateFile.is = is;
  2946. })(CreateFile || (CreateFile = {}));
  2947. var RenameFile;
  2948. (function (RenameFile) {
  2949. function create(oldUri, newUri, options) {
  2950. var result = {
  2951. kind: 'rename',
  2952. oldUri: oldUri,
  2953. newUri: newUri
  2954. };
  2955. if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
  2956. result.options = options;
  2957. }
  2958. return result;
  2959. }
  2960. RenameFile.create = create;
  2961. function is(value) {
  2962. var candidate = value;
  2963. return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
  2964. (candidate.options === void 0 ||
  2965. ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
  2966. }
  2967. RenameFile.is = is;
  2968. })(RenameFile || (RenameFile = {}));
  2969. var DeleteFile;
  2970. (function (DeleteFile) {
  2971. function create(uri, options) {
  2972. var result = {
  2973. kind: 'delete',
  2974. uri: uri
  2975. };
  2976. if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
  2977. result.options = options;
  2978. }
  2979. return result;
  2980. }
  2981. DeleteFile.create = create;
  2982. function is(value) {
  2983. var candidate = value;
  2984. return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
  2985. (candidate.options === void 0 ||
  2986. ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
  2987. }
  2988. DeleteFile.is = is;
  2989. })(DeleteFile || (DeleteFile = {}));
  2990. var WorkspaceEdit;
  2991. (function (WorkspaceEdit) {
  2992. function is(value) {
  2993. var candidate = value;
  2994. return candidate &&
  2995. (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
  2996. (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
  2997. if (Is.string(change.kind)) {
  2998. return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
  2999. }
  3000. else {
  3001. return TextDocumentEdit.is(change);
  3002. }
  3003. }));
  3004. }
  3005. WorkspaceEdit.is = is;
  3006. })(WorkspaceEdit || (WorkspaceEdit = {}));
  3007. var TextEditChangeImpl = /** @class */ (function () {
  3008. function TextEditChangeImpl(edits) {
  3009. this.edits = edits;
  3010. }
  3011. TextEditChangeImpl.prototype.insert = function (position, newText) {
  3012. this.edits.push(TextEdit.insert(position, newText));
  3013. };
  3014. TextEditChangeImpl.prototype.replace = function (range, newText) {
  3015. this.edits.push(TextEdit.replace(range, newText));
  3016. };
  3017. TextEditChangeImpl.prototype.delete = function (range) {
  3018. this.edits.push(TextEdit.del(range));
  3019. };
  3020. TextEditChangeImpl.prototype.add = function (edit) {
  3021. this.edits.push(edit);
  3022. };
  3023. TextEditChangeImpl.prototype.all = function () {
  3024. return this.edits;
  3025. };
  3026. TextEditChangeImpl.prototype.clear = function () {
  3027. this.edits.splice(0, this.edits.length);
  3028. };
  3029. return TextEditChangeImpl;
  3030. }());
  3031. /**
  3032. * A workspace change helps constructing changes to a workspace.
  3033. */
  3034. var WorkspaceChange = /** @class */ (function () {
  3035. function WorkspaceChange(workspaceEdit) {
  3036. var _this = this;
  3037. this._textEditChanges = Object.create(null);
  3038. if (workspaceEdit) {
  3039. this._workspaceEdit = workspaceEdit;
  3040. if (workspaceEdit.documentChanges) {
  3041. workspaceEdit.documentChanges.forEach(function (change) {
  3042. if (TextDocumentEdit.is(change)) {
  3043. var textEditChange = new TextEditChangeImpl(change.edits);
  3044. _this._textEditChanges[change.textDocument.uri] = textEditChange;
  3045. }
  3046. });
  3047. }
  3048. else if (workspaceEdit.changes) {
  3049. Object.keys(workspaceEdit.changes).forEach(function (key) {
  3050. var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
  3051. _this._textEditChanges[key] = textEditChange;
  3052. });
  3053. }
  3054. }
  3055. }
  3056. Object.defineProperty(WorkspaceChange.prototype, "edit", {
  3057. /**
  3058. * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
  3059. * use to be returned from a workspace edit operation like rename.
  3060. */
  3061. get: function () {
  3062. return this._workspaceEdit;
  3063. },
  3064. enumerable: true,
  3065. configurable: true
  3066. });
  3067. WorkspaceChange.prototype.getTextEditChange = function (key) {
  3068. if (VersionedTextDocumentIdentifier.is(key)) {
  3069. if (!this._workspaceEdit) {
  3070. this._workspaceEdit = {
  3071. documentChanges: []
  3072. };
  3073. }
  3074. if (!this._workspaceEdit.documentChanges) {
  3075. throw new Error('Workspace edit is not configured for document changes.');
  3076. }
  3077. var textDocument = key;
  3078. var result = this._textEditChanges[textDocument.uri];
  3079. if (!result) {
  3080. var edits = [];
  3081. var textDocumentEdit = {
  3082. textDocument: textDocument,
  3083. edits: edits
  3084. };
  3085. this._workspaceEdit.documentChanges.push(textDocumentEdit);
  3086. result = new TextEditChangeImpl(edits);
  3087. this._textEditChanges[textDocument.uri] = result;
  3088. }
  3089. return result;
  3090. }
  3091. else {
  3092. if (!this._workspaceEdit) {
  3093. this._workspaceEdit = {
  3094. changes: Object.create(null)
  3095. };
  3096. }
  3097. if (!this._workspaceEdit.changes) {
  3098. throw new Error('Workspace edit is not configured for normal text edit changes.');
  3099. }
  3100. var result = this._textEditChanges[key];
  3101. if (!result) {
  3102. var edits = [];
  3103. this._workspaceEdit.changes[key] = edits;
  3104. result = new TextEditChangeImpl(edits);
  3105. this._textEditChanges[key] = result;
  3106. }
  3107. return result;
  3108. }
  3109. };
  3110. WorkspaceChange.prototype.createFile = function (uri, options) {
  3111. this.checkDocumentChanges();
  3112. this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
  3113. };
  3114. WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
  3115. this.checkDocumentChanges();
  3116. this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
  3117. };
  3118. WorkspaceChange.prototype.deleteFile = function (uri, options) {
  3119. this.checkDocumentChanges();
  3120. this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
  3121. };
  3122. WorkspaceChange.prototype.checkDocumentChanges = function () {
  3123. if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
  3124. throw new Error('Workspace edit is not configured for document changes.');
  3125. }
  3126. };
  3127. return WorkspaceChange;
  3128. }());
  3129. /**
  3130. * The TextDocumentIdentifier namespace provides helper functions to work with
  3131. * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
  3132. */
  3133. var TextDocumentIdentifier;
  3134. (function (TextDocumentIdentifier) {
  3135. /**
  3136. * Creates a new TextDocumentIdentifier literal.
  3137. * @param uri The document's uri.
  3138. */
  3139. function create(uri) {
  3140. return { uri: uri };
  3141. }
  3142. TextDocumentIdentifier.create = create;
  3143. /**
  3144. * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
  3145. */
  3146. function is(value) {
  3147. var candidate = value;
  3148. return Is.defined(candidate) && Is.string(candidate.uri);
  3149. }
  3150. TextDocumentIdentifier.is = is;
  3151. })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
  3152. /**
  3153. * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
  3154. * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
  3155. */
  3156. var VersionedTextDocumentIdentifier;
  3157. (function (VersionedTextDocumentIdentifier) {
  3158. /**
  3159. * Creates a new VersionedTextDocumentIdentifier literal.
  3160. * @param uri The document's uri.
  3161. * @param uri The document's text.
  3162. */
  3163. function create(uri, version) {
  3164. return { uri: uri, version: version };
  3165. }
  3166. VersionedTextDocumentIdentifier.create = create;
  3167. /**
  3168. * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
  3169. */
  3170. function is(value) {
  3171. var candidate = value;
  3172. return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
  3173. }
  3174. VersionedTextDocumentIdentifier.is = is;
  3175. })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
  3176. /**
  3177. * The TextDocumentItem namespace provides helper functions to work with
  3178. * [TextDocumentItem](#TextDocumentItem) literals.
  3179. */
  3180. var TextDocumentItem;
  3181. (function (TextDocumentItem) {
  3182. /**
  3183. * Creates a new TextDocumentItem literal.
  3184. * @param uri The document's uri.
  3185. * @param languageId The document's language identifier.
  3186. * @param version The document's version number.
  3187. * @param text The document's text.
  3188. */
  3189. function create(uri, languageId, version, text) {
  3190. return { uri: uri, languageId: languageId, version: version, text: text };
  3191. }
  3192. TextDocumentItem.create = create;
  3193. /**
  3194. * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
  3195. */
  3196. function is(value) {
  3197. var candidate = value;
  3198. return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
  3199. }
  3200. TextDocumentItem.is = is;
  3201. })(TextDocumentItem || (TextDocumentItem = {}));
  3202. /**
  3203. * Describes the content type that a client supports in various
  3204. * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
  3205. *
  3206. * Please note that `MarkupKinds` must not start with a `$`. This kinds
  3207. * are reserved for internal usage.
  3208. */
  3209. var MarkupKind;
  3210. (function (MarkupKind) {
  3211. /**
  3212. * Plain text is supported as a content format
  3213. */
  3214. MarkupKind.PlainText = 'plaintext';
  3215. /**
  3216. * Markdown is supported as a content format
  3217. */
  3218. MarkupKind.Markdown = 'markdown';
  3219. })(MarkupKind || (MarkupKind = {}));
  3220. (function (MarkupKind) {
  3221. /**
  3222. * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
  3223. */
  3224. function is(value) {
  3225. var candidate = value;
  3226. return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
  3227. }
  3228. MarkupKind.is = is;
  3229. })(MarkupKind || (MarkupKind = {}));
  3230. var MarkupContent;
  3231. (function (MarkupContent) {
  3232. /**
  3233. * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
  3234. */
  3235. function is(value) {
  3236. var candidate = value;
  3237. return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
  3238. }
  3239. MarkupContent.is = is;
  3240. })(MarkupContent || (MarkupContent = {}));
  3241. /**
  3242. * The kind of a completion entry.
  3243. */
  3244. var CompletionItemKind;
  3245. (function (CompletionItemKind) {
  3246. CompletionItemKind.Text = 1;
  3247. CompletionItemKind.Method = 2;
  3248. CompletionItemKind.Function = 3;
  3249. CompletionItemKind.Constructor = 4;
  3250. CompletionItemKind.Field = 5;
  3251. CompletionItemKind.Variable = 6;
  3252. CompletionItemKind.Class = 7;
  3253. CompletionItemKind.Interface = 8;
  3254. CompletionItemKind.Module = 9;
  3255. CompletionItemKind.Property = 10;
  3256. CompletionItemKind.Unit = 11;
  3257. CompletionItemKind.Value = 12;
  3258. CompletionItemKind.Enum = 13;
  3259. CompletionItemKind.Keyword = 14;
  3260. CompletionItemKind.Snippet = 15;
  3261. CompletionItemKind.Color = 16;
  3262. CompletionItemKind.File = 17;
  3263. CompletionItemKind.Reference = 18;
  3264. CompletionItemKind.Folder = 19;
  3265. CompletionItemKind.EnumMember = 20;
  3266. CompletionItemKind.Constant = 21;
  3267. CompletionItemKind.Struct = 22;
  3268. CompletionItemKind.Event = 23;
  3269. CompletionItemKind.Operator = 24;
  3270. CompletionItemKind.TypeParameter = 25;
  3271. })(CompletionItemKind || (CompletionItemKind = {}));
  3272. /**
  3273. * Defines whether the insert text in a completion item should be interpreted as
  3274. * plain text or a snippet.
  3275. */
  3276. var InsertTextFormat;
  3277. (function (InsertTextFormat) {
  3278. /**
  3279. * The primary text to be inserted is treated as a plain string.
  3280. */
  3281. InsertTextFormat.PlainText = 1;
  3282. /**
  3283. * The primary text to be inserted is treated as a snippet.
  3284. *
  3285. * A snippet can define tab stops and placeholders with `$1`, `$2`
  3286. * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
  3287. * the end of the snippet. Placeholders with equal identifiers are linked,
  3288. * that is typing in one will update others too.
  3289. *
  3290. * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
  3291. */
  3292. InsertTextFormat.Snippet = 2;
  3293. })(InsertTextFormat || (InsertTextFormat = {}));
  3294. /**
  3295. * The CompletionItem namespace provides functions to deal with
  3296. * completion items.
  3297. */
  3298. var CompletionItem;
  3299. (function (CompletionItem) {
  3300. /**
  3301. * Create a completion item and seed it with a label.
  3302. * @param label The completion item's label
  3303. */
  3304. function create(label) {
  3305. return { label: label };
  3306. }
  3307. CompletionItem.create = create;
  3308. })(CompletionItem || (CompletionItem = {}));
  3309. /**
  3310. * The CompletionList namespace provides functions to deal with
  3311. * completion lists.
  3312. */
  3313. var CompletionList;
  3314. (function (CompletionList) {
  3315. /**
  3316. * Creates a new completion list.
  3317. *
  3318. * @param items The completion items.
  3319. * @param isIncomplete The list is not complete.
  3320. */
  3321. function create(items, isIncomplete) {
  3322. return { items: items ? items : [], isIncomplete: !!isIncomplete };
  3323. }
  3324. CompletionList.create = create;
  3325. })(CompletionList || (CompletionList = {}));
  3326. var MarkedString;
  3327. (function (MarkedString) {
  3328. /**
  3329. * Creates a marked string from plain text.
  3330. *
  3331. * @param plainText The plain text.
  3332. */
  3333. function fromPlainText(plainText) {
  3334. return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
  3335. }
  3336. MarkedString.fromPlainText = fromPlainText;
  3337. /**
  3338. * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
  3339. */
  3340. function is(value) {
  3341. var candidate = value;
  3342. return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
  3343. }
  3344. MarkedString.is = is;
  3345. })(MarkedString || (MarkedString = {}));
  3346. var Hover;
  3347. (function (Hover) {
  3348. /**
  3349. * Checks whether the given value conforms to the [Hover](#Hover) interface.
  3350. */
  3351. function is(value) {
  3352. var candidate = value;
  3353. return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
  3354. MarkedString.is(candidate.contents) ||
  3355. Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
  3356. }
  3357. Hover.is = is;
  3358. })(Hover || (Hover = {}));
  3359. /**
  3360. * The ParameterInformation namespace provides helper functions to work with
  3361. * [ParameterInformation](#ParameterInformation) literals.
  3362. */
  3363. var ParameterInformation;
  3364. (function (ParameterInformation) {
  3365. /**
  3366. * Creates a new parameter information literal.
  3367. *
  3368. * @param label A label string.
  3369. * @param documentation A doc string.
  3370. */
  3371. function create(label, documentation) {
  3372. return documentation ? { label: label, documentation: documentation } : { label: label };
  3373. }
  3374. ParameterInformation.create = create;
  3375. ;
  3376. })(ParameterInformation || (ParameterInformation = {}));
  3377. /**
  3378. * The SignatureInformation namespace provides helper functions to work with
  3379. * [SignatureInformation](#SignatureInformation) literals.
  3380. */
  3381. var SignatureInformation;
  3382. (function (SignatureInformation) {
  3383. function create(label, documentation) {
  3384. var parameters = [];
  3385. for (var _i = 2; _i < arguments.length; _i++) {
  3386. parameters[_i - 2] = arguments[_i];
  3387. }
  3388. var result = { label: label };
  3389. if (Is.defined(documentation)) {
  3390. result.documentation = documentation;
  3391. }
  3392. if (Is.defined(parameters)) {
  3393. result.parameters = parameters;
  3394. }
  3395. else {
  3396. result.parameters = [];
  3397. }
  3398. return result;
  3399. }
  3400. SignatureInformation.create = create;
  3401. })(SignatureInformation || (SignatureInformation = {}));
  3402. /**
  3403. * A document highlight kind.
  3404. */
  3405. var DocumentHighlightKind;
  3406. (function (DocumentHighlightKind) {
  3407. /**
  3408. * A textual occurrence.
  3409. */
  3410. DocumentHighlightKind.Text = 1;
  3411. /**
  3412. * Read-access of a symbol, like reading a variable.
  3413. */
  3414. DocumentHighlightKind.Read = 2;
  3415. /**
  3416. * Write-access of a symbol, like writing to a variable.
  3417. */
  3418. DocumentHighlightKind.Write = 3;
  3419. })(DocumentHighlightKind || (DocumentHighlightKind = {}));
  3420. /**
  3421. * DocumentHighlight namespace to provide helper functions to work with
  3422. * [DocumentHighlight](#DocumentHighlight) literals.
  3423. */
  3424. var DocumentHighlight;
  3425. (function (DocumentHighlight) {
  3426. /**
  3427. * Create a DocumentHighlight object.
  3428. * @param range The range the highlight applies to.
  3429. */
  3430. function create(range, kind) {
  3431. var result = { range: range };
  3432. if (Is.number(kind)) {
  3433. result.kind = kind;
  3434. }
  3435. return result;
  3436. }
  3437. DocumentHighlight.create = create;
  3438. })(DocumentHighlight || (DocumentHighlight = {}));
  3439. /**
  3440. * A symbol kind.
  3441. */
  3442. var SymbolKind;
  3443. (function (SymbolKind) {
  3444. SymbolKind.File = 1;
  3445. SymbolKind.Module = 2;
  3446. SymbolKind.Namespace = 3;
  3447. SymbolKind.Package = 4;
  3448. SymbolKind.Class = 5;
  3449. SymbolKind.Method = 6;
  3450. SymbolKind.Property = 7;
  3451. SymbolKind.Field = 8;
  3452. SymbolKind.Constructor = 9;
  3453. SymbolKind.Enum = 10;
  3454. SymbolKind.Interface = 11;
  3455. SymbolKind.Function = 12;
  3456. SymbolKind.Variable = 13;
  3457. SymbolKind.Constant = 14;
  3458. SymbolKind.String = 15;
  3459. SymbolKind.Number = 16;
  3460. SymbolKind.Boolean = 17;
  3461. SymbolKind.Array = 18;
  3462. SymbolKind.Object = 19;
  3463. SymbolKind.Key = 20;
  3464. SymbolKind.Null = 21;
  3465. SymbolKind.EnumMember = 22;
  3466. SymbolKind.Struct = 23;
  3467. SymbolKind.Event = 24;
  3468. SymbolKind.Operator = 25;
  3469. SymbolKind.TypeParameter = 26;
  3470. })(SymbolKind || (SymbolKind = {}));
  3471. var SymbolInformation;
  3472. (function (SymbolInformation) {
  3473. /**
  3474. * Creates a new symbol information literal.
  3475. *
  3476. * @param name The name of the symbol.
  3477. * @param kind The kind of the symbol.
  3478. * @param range The range of the location of the symbol.
  3479. * @param uri The resource of the location of symbol, defaults to the current document.
  3480. * @param containerName The name of the symbol containing the symbol.
  3481. */
  3482. function create(name, kind, range, uri, containerName) {
  3483. var result = {
  3484. name: name,
  3485. kind: kind,
  3486. location: { uri: uri, range: range }
  3487. };
  3488. if (containerName) {
  3489. result.containerName = containerName;
  3490. }
  3491. return result;
  3492. }
  3493. SymbolInformation.create = create;
  3494. })(SymbolInformation || (SymbolInformation = {}));
  3495. /**
  3496. * Represents programming constructs like variables, classes, interfaces etc.
  3497. * that appear in a document. Document symbols can be hierarchical and they
  3498. * have two ranges: one that encloses its definition and one that points to
  3499. * its most interesting range, e.g. the range of an identifier.
  3500. */
  3501. var DocumentSymbol = /** @class */ (function () {
  3502. function DocumentSymbol() {
  3503. }
  3504. return DocumentSymbol;
  3505. }());
  3506. (function (DocumentSymbol) {
  3507. /**
  3508. * Creates a new symbol information literal.
  3509. *
  3510. * @param name The name of the symbol.
  3511. * @param detail The detail of the symbol.
  3512. * @param kind The kind of the symbol.
  3513. * @param range The range of the symbol.
  3514. * @param selectionRange The selectionRange of the symbol.
  3515. * @param children Children of the symbol.
  3516. */
  3517. function create(name, detail, kind, range, selectionRange, children) {
  3518. var result = {
  3519. name: name,
  3520. detail: detail,
  3521. kind: kind,
  3522. range: range,
  3523. selectionRange: selectionRange
  3524. };
  3525. if (children !== void 0) {
  3526. result.children = children;
  3527. }
  3528. return result;
  3529. }
  3530. DocumentSymbol.create = create;
  3531. /**
  3532. * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
  3533. */
  3534. function is(value) {
  3535. var candidate = value;
  3536. return candidate &&
  3537. Is.string(candidate.name) && Is.number(candidate.kind) &&
  3538. Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
  3539. (candidate.detail === void 0 || Is.string(candidate.detail)) &&
  3540. (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
  3541. (candidate.children === void 0 || Array.isArray(candidate.children));
  3542. }
  3543. DocumentSymbol.is = is;
  3544. })(DocumentSymbol || (DocumentSymbol = {}));
  3545. /**
  3546. * A set of predefined code action kinds
  3547. */
  3548. var CodeActionKind;
  3549. (function (CodeActionKind) {
  3550. /**
  3551. * Base kind for quickfix actions: 'quickfix'
  3552. */
  3553. CodeActionKind.QuickFix = 'quickfix';
  3554. /**
  3555. * Base kind for refactoring actions: 'refactor'
  3556. */
  3557. CodeActionKind.Refactor = 'refactor';
  3558. /**
  3559. * Base kind for refactoring extraction actions: 'refactor.extract'
  3560. *
  3561. * Example extract actions:
  3562. *
  3563. * - Extract method
  3564. * - Extract function
  3565. * - Extract variable
  3566. * - Extract interface from class
  3567. * - ...
  3568. */
  3569. CodeActionKind.RefactorExtract = 'refactor.extract';
  3570. /**
  3571. * Base kind for refactoring inline actions: 'refactor.inline'
  3572. *
  3573. * Example inline actions:
  3574. *
  3575. * - Inline function
  3576. * - Inline variable
  3577. * - Inline constant
  3578. * - ...
  3579. */
  3580. CodeActionKind.RefactorInline = 'refactor.inline';
  3581. /**
  3582. * Base kind for refactoring rewrite actions: 'refactor.rewrite'
  3583. *
  3584. * Example rewrite actions:
  3585. *
  3586. * - Convert JavaScript function to class
  3587. * - Add or remove parameter
  3588. * - Encapsulate field
  3589. * - Make method static
  3590. * - Move method to base class
  3591. * - ...
  3592. */
  3593. CodeActionKind.RefactorRewrite = 'refactor.rewrite';
  3594. /**
  3595. * Base kind for source actions: `source`
  3596. *
  3597. * Source code actions apply to the entire file.
  3598. */
  3599. CodeActionKind.Source = 'source';
  3600. /**
  3601. * Base kind for an organize imports source action: `source.organizeImports`
  3602. */
  3603. CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
  3604. })(CodeActionKind || (CodeActionKind = {}));
  3605. /**
  3606. * The CodeActionContext namespace provides helper functions to work with
  3607. * [CodeActionContext](#CodeActionContext) literals.
  3608. */
  3609. var CodeActionContext;
  3610. (function (CodeActionContext) {
  3611. /**
  3612. * Creates a new CodeActionContext literal.
  3613. */
  3614. function create(diagnostics, only) {
  3615. var result = { diagnostics: diagnostics };
  3616. if (only !== void 0 && only !== null) {
  3617. result.only = only;
  3618. }
  3619. return result;
  3620. }
  3621. CodeActionContext.create = create;
  3622. /**
  3623. * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
  3624. */
  3625. function is(value) {
  3626. var candidate = value;
  3627. return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
  3628. }
  3629. CodeActionContext.is = is;
  3630. })(CodeActionContext || (CodeActionContext = {}));
  3631. var CodeAction;
  3632. (function (CodeAction) {
  3633. function create(title, commandOrEdit, kind) {
  3634. var result = { title: title };
  3635. if (Command.is(commandOrEdit)) {
  3636. result.command = commandOrEdit;
  3637. }
  3638. else {
  3639. result.edit = commandOrEdit;
  3640. }
  3641. if (kind !== void null) {
  3642. result.kind = kind;
  3643. }
  3644. return result;
  3645. }
  3646. CodeAction.create = create;
  3647. function is(value) {
  3648. var candidate = value;
  3649. return candidate && Is.string(candidate.title) &&
  3650. (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
  3651. (candidate.kind === void 0 || Is.string(candidate.kind)) &&
  3652. (candidate.edit !== void 0 || candidate.command !== void 0) &&
  3653. (candidate.command === void 0 || Command.is(candidate.command)) &&
  3654. (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
  3655. }
  3656. CodeAction.is = is;
  3657. })(CodeAction || (CodeAction = {}));
  3658. /**
  3659. * The CodeLens namespace provides helper functions to work with
  3660. * [CodeLens](#CodeLens) literals.
  3661. */
  3662. var CodeLens;
  3663. (function (CodeLens) {
  3664. /**
  3665. * Creates a new CodeLens literal.
  3666. */
  3667. function create(range, data) {
  3668. var result = { range: range };
  3669. if (Is.defined(data))
  3670. result.data = data;
  3671. return result;
  3672. }
  3673. CodeLens.create = create;
  3674. /**
  3675. * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
  3676. */
  3677. function is(value) {
  3678. var candidate = value;
  3679. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
  3680. }
  3681. CodeLens.is = is;
  3682. })(CodeLens || (CodeLens = {}));
  3683. /**
  3684. * The FormattingOptions namespace provides helper functions to work with
  3685. * [FormattingOptions](#FormattingOptions) literals.
  3686. */
  3687. var FormattingOptions;
  3688. (function (FormattingOptions) {
  3689. /**
  3690. * Creates a new FormattingOptions literal.
  3691. */
  3692. function create(tabSize, insertSpaces) {
  3693. return { tabSize: tabSize, insertSpaces: insertSpaces };
  3694. }
  3695. FormattingOptions.create = create;
  3696. /**
  3697. * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
  3698. */
  3699. function is(value) {
  3700. var candidate = value;
  3701. return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
  3702. }
  3703. FormattingOptions.is = is;
  3704. })(FormattingOptions || (FormattingOptions = {}));
  3705. /**
  3706. * A document link is a range in a text document that links to an internal or external resource, like another
  3707. * text document or a web site.
  3708. */
  3709. var DocumentLink = /** @class */ (function () {
  3710. function DocumentLink() {
  3711. }
  3712. return DocumentLink;
  3713. }());
  3714. /**
  3715. * The DocumentLink namespace provides helper functions to work with
  3716. * [DocumentLink](#DocumentLink) literals.
  3717. */
  3718. (function (DocumentLink) {
  3719. /**
  3720. * Creates a new DocumentLink literal.
  3721. */
  3722. function create(range, target, data) {
  3723. return { range: range, target: target, data: data };
  3724. }
  3725. DocumentLink.create = create;
  3726. /**
  3727. * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
  3728. */
  3729. function is(value) {
  3730. var candidate = value;
  3731. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
  3732. }
  3733. DocumentLink.is = is;
  3734. })(DocumentLink || (DocumentLink = {}));
  3735. var EOL = ['\n', '\r\n', '\r'];
  3736. var TextDocument;
  3737. (function (TextDocument) {
  3738. /**
  3739. * Creates a new ITextDocument literal from the given uri and content.
  3740. * @param uri The document's uri.
  3741. * @param languageId The document's language Id.
  3742. * @param content The document's content.
  3743. */
  3744. function create(uri, languageId, version, content) {
  3745. return new FullTextDocument(uri, languageId, version, content);
  3746. }
  3747. TextDocument.create = create;
  3748. /**
  3749. * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
  3750. */
  3751. function is(value) {
  3752. var candidate = value;
  3753. return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
  3754. && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
  3755. }
  3756. TextDocument.is = is;
  3757. function applyEdits(document, edits) {
  3758. var text = document.getText();
  3759. var sortedEdits = mergeSort(edits, function (a, b) {
  3760. var diff = a.range.start.line - b.range.start.line;
  3761. if (diff === 0) {
  3762. return a.range.start.character - b.range.start.character;
  3763. }
  3764. return diff;
  3765. });
  3766. var lastModifiedOffset = text.length;
  3767. for (var i = sortedEdits.length - 1; i >= 0; i--) {
  3768. var e = sortedEdits[i];
  3769. var startOffset = document.offsetAt(e.range.start);
  3770. var endOffset = document.offsetAt(e.range.end);
  3771. if (endOffset <= lastModifiedOffset) {
  3772. text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
  3773. }
  3774. else {
  3775. throw new Error('Overlapping edit');
  3776. }
  3777. lastModifiedOffset = startOffset;
  3778. }
  3779. return text;
  3780. }
  3781. TextDocument.applyEdits = applyEdits;
  3782. function mergeSort(data, compare) {
  3783. if (data.length <= 1) {
  3784. // sorted
  3785. return data;
  3786. }
  3787. var p = (data.length / 2) | 0;
  3788. var left = data.slice(0, p);
  3789. var right = data.slice(p);
  3790. mergeSort(left, compare);
  3791. mergeSort(right, compare);
  3792. var leftIdx = 0;
  3793. var rightIdx = 0;
  3794. var i = 0;
  3795. while (leftIdx < left.length && rightIdx < right.length) {
  3796. var ret = compare(left[leftIdx], right[rightIdx]);
  3797. if (ret <= 0) {
  3798. // smaller_equal -> take left to preserve order
  3799. data[i++] = left[leftIdx++];
  3800. }
  3801. else {
  3802. // greater -> take right
  3803. data[i++] = right[rightIdx++];
  3804. }
  3805. }
  3806. while (leftIdx < left.length) {
  3807. data[i++] = left[leftIdx++];
  3808. }
  3809. while (rightIdx < right.length) {
  3810. data[i++] = right[rightIdx++];
  3811. }
  3812. return data;
  3813. }
  3814. })(TextDocument || (TextDocument = {}));
  3815. /**
  3816. * Represents reasons why a text document is saved.
  3817. */
  3818. var TextDocumentSaveReason;
  3819. (function (TextDocumentSaveReason) {
  3820. /**
  3821. * Manually triggered, e.g. by the user pressing save, by starting debugging,
  3822. * or by an API call.
  3823. */
  3824. TextDocumentSaveReason.Manual = 1;
  3825. /**
  3826. * Automatic after a delay.
  3827. */
  3828. TextDocumentSaveReason.AfterDelay = 2;
  3829. /**
  3830. * When the editor lost focus.
  3831. */
  3832. TextDocumentSaveReason.FocusOut = 3;
  3833. })(TextDocumentSaveReason || (TextDocumentSaveReason = {}));
  3834. var FullTextDocument = /** @class */ (function () {
  3835. function FullTextDocument(uri, languageId, version, content) {
  3836. this._uri = uri;
  3837. this._languageId = languageId;
  3838. this._version = version;
  3839. this._content = content;
  3840. this._lineOffsets = null;
  3841. }
  3842. Object.defineProperty(FullTextDocument.prototype, "uri", {
  3843. get: function () {
  3844. return this._uri;
  3845. },
  3846. enumerable: true,
  3847. configurable: true
  3848. });
  3849. Object.defineProperty(FullTextDocument.prototype, "languageId", {
  3850. get: function () {
  3851. return this._languageId;
  3852. },
  3853. enumerable: true,
  3854. configurable: true
  3855. });
  3856. Object.defineProperty(FullTextDocument.prototype, "version", {
  3857. get: function () {
  3858. return this._version;
  3859. },
  3860. enumerable: true,
  3861. configurable: true
  3862. });
  3863. FullTextDocument.prototype.getText = function (range) {
  3864. if (range) {
  3865. var start = this.offsetAt(range.start);
  3866. var end = this.offsetAt(range.end);
  3867. return this._content.substring(start, end);
  3868. }
  3869. return this._content;
  3870. };
  3871. FullTextDocument.prototype.update = function (event, version) {
  3872. this._content = event.text;
  3873. this._version = version;
  3874. this._lineOffsets = null;
  3875. };
  3876. FullTextDocument.prototype.getLineOffsets = function () {
  3877. if (this._lineOffsets === null) {
  3878. var lineOffsets = [];
  3879. var text = this._content;
  3880. var isLineStart = true;
  3881. for (var i = 0; i < text.length; i++) {
  3882. if (isLineStart) {
  3883. lineOffsets.push(i);
  3884. isLineStart = false;
  3885. }
  3886. var ch = text.charAt(i);
  3887. isLineStart = (ch === '\r' || ch === '\n');
  3888. if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
  3889. i++;
  3890. }
  3891. }
  3892. if (isLineStart && text.length > 0) {
  3893. lineOffsets.push(text.length);
  3894. }
  3895. this._lineOffsets = lineOffsets;
  3896. }
  3897. return this._lineOffsets;
  3898. };
  3899. FullTextDocument.prototype.positionAt = function (offset) {
  3900. offset = Math.max(Math.min(offset, this._content.length), 0);
  3901. var lineOffsets = this.getLineOffsets();
  3902. var low = 0, high = lineOffsets.length;
  3903. if (high === 0) {
  3904. return Position.create(0, offset);
  3905. }
  3906. while (low < high) {
  3907. var mid = Math.floor((low + high) / 2);
  3908. if (lineOffsets[mid] > offset) {
  3909. high = mid;
  3910. }
  3911. else {
  3912. low = mid + 1;
  3913. }
  3914. }
  3915. // low is the least x for which the line offset is larger than the current offset
  3916. // or array.length if no line offset is larger than the current offset
  3917. var line = low - 1;
  3918. return Position.create(line, offset - lineOffsets[line]);
  3919. };
  3920. FullTextDocument.prototype.offsetAt = function (position) {
  3921. var lineOffsets = this.getLineOffsets();
  3922. if (position.line >= lineOffsets.length) {
  3923. return this._content.length;
  3924. }
  3925. else if (position.line < 0) {
  3926. return 0;
  3927. }
  3928. var lineOffset = lineOffsets[position.line];
  3929. var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
  3930. return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
  3931. };
  3932. Object.defineProperty(FullTextDocument.prototype, "lineCount", {
  3933. get: function () {
  3934. return this.getLineOffsets().length;
  3935. },
  3936. enumerable: true,
  3937. configurable: true
  3938. });
  3939. return FullTextDocument;
  3940. }());
  3941. var Is;
  3942. (function (Is) {
  3943. var toString = Object.prototype.toString;
  3944. function defined(value) {
  3945. return typeof value !== 'undefined';
  3946. }
  3947. Is.defined = defined;
  3948. function undefined(value) {
  3949. return typeof value === 'undefined';
  3950. }
  3951. Is.undefined = undefined;
  3952. function boolean(value) {
  3953. return value === true || value === false;
  3954. }
  3955. Is.boolean = boolean;
  3956. function string(value) {
  3957. return toString.call(value) === '[object String]';
  3958. }
  3959. Is.string = string;
  3960. function number(value) {
  3961. return toString.call(value) === '[object Number]';
  3962. }
  3963. Is.number = number;
  3964. function func(value) {
  3965. return toString.call(value) === '[object Function]';
  3966. }
  3967. Is.func = func;
  3968. function objectLiteral(value) {
  3969. // Strictly speaking class instances pass this check as well. Since the LSP
  3970. // doesn't use classes we ignore this for now. If we do we need to add something
  3971. // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
  3972. return value !== null && typeof value === 'object';
  3973. }
  3974. Is.objectLiteral = objectLiteral;
  3975. function typedArray(value, check) {
  3976. return Array.isArray(value) && value.every(check);
  3977. }
  3978. Is.typedArray = typedArray;
  3979. })(Is || (Is = {}));
  3980. /***/ }),
  3981. /* 18 */
  3982. /***/ (function(module, exports, __webpack_require__) {
  3983. "use strict";
  3984. /* --------------------------------------------------------------------------------------------
  3985. * Copyright (c) Microsoft Corporation. All rights reserved.
  3986. * Licensed under the MIT License. See License.txt in the project root for license information.
  3987. * ------------------------------------------------------------------------------------------ */
  3988. Object.defineProperty(exports, "__esModule", { value: true });
  3989. const Is = __webpack_require__(19);
  3990. const vscode_jsonrpc_1 = __webpack_require__(4);
  3991. const protocol_implementation_1 = __webpack_require__(20);
  3992. exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
  3993. const protocol_typeDefinition_1 = __webpack_require__(21);
  3994. exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
  3995. const protocol_workspaceFolders_1 = __webpack_require__(22);
  3996. exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
  3997. exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
  3998. const protocol_configuration_1 = __webpack_require__(23);
  3999. exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
  4000. const protocol_colorProvider_1 = __webpack_require__(24);
  4001. exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
  4002. exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
  4003. const protocol_foldingRange_1 = __webpack_require__(25);
  4004. exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
  4005. const protocol_declaration_1 = __webpack_require__(26);
  4006. exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
  4007. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  4008. let __noDynamicImport;
  4009. var DocumentFilter;
  4010. (function (DocumentFilter) {
  4011. function is(value) {
  4012. let candidate = value;
  4013. return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
  4014. }
  4015. DocumentFilter.is = is;
  4016. })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));
  4017. /**
  4018. * The `client/registerCapability` request is sent from the server to the client to register a new capability
  4019. * handler on the client side.
  4020. */
  4021. var RegistrationRequest;
  4022. (function (RegistrationRequest) {
  4023. RegistrationRequest.type = new vscode_jsonrpc_1.RequestType('client/registerCapability');
  4024. })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
  4025. /**
  4026. * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
  4027. * handler on the client side.
  4028. */
  4029. var UnregistrationRequest;
  4030. (function (UnregistrationRequest) {
  4031. UnregistrationRequest.type = new vscode_jsonrpc_1.RequestType('client/unregisterCapability');
  4032. })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
  4033. var ResourceOperationKind;
  4034. (function (ResourceOperationKind) {
  4035. /**
  4036. * Supports creating new files and folders.
  4037. */
  4038. ResourceOperationKind.Create = 'create';
  4039. /**
  4040. * Supports renaming existing files and folders.
  4041. */
  4042. ResourceOperationKind.Rename = 'rename';
  4043. /**
  4044. * Supports deleting existing files and folders.
  4045. */
  4046. ResourceOperationKind.Delete = 'delete';
  4047. })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
  4048. var FailureHandlingKind;
  4049. (function (FailureHandlingKind) {
  4050. /**
  4051. * Applying the workspace change is simply aborted if one of the changes provided
  4052. * fails. All operations executed before the failing operation stay executed.
  4053. */
  4054. FailureHandlingKind.Abort = 'abort';
  4055. /**
  4056. * All operations are executed transactional. That means they either all
  4057. * succeed or no changes at all are applied to the workspace.
  4058. */
  4059. FailureHandlingKind.Transactional = 'transactional';
  4060. /**
  4061. * If the workspace edit contains only textual file changes they are executed transactional.
  4062. * If resource changes (create, rename or delete file) are part of the change the failure
  4063. * handling startegy is abort.
  4064. */
  4065. FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
  4066. /**
  4067. * The client tries to undo the operations already executed. But there is no
  4068. * guaruntee that this is succeeding.
  4069. */
  4070. FailureHandlingKind.Undo = 'undo';
  4071. })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
  4072. /**
  4073. * Defines how the host (editor) should sync
  4074. * document changes to the language server.
  4075. */
  4076. var TextDocumentSyncKind;
  4077. (function (TextDocumentSyncKind) {
  4078. /**
  4079. * Documents should not be synced at all.
  4080. */
  4081. TextDocumentSyncKind.None = 0;
  4082. /**
  4083. * Documents are synced by always sending the full content
  4084. * of the document.
  4085. */
  4086. TextDocumentSyncKind.Full = 1;
  4087. /**
  4088. * Documents are synced by sending the full content on open.
  4089. * After that only incremental updates to the document are
  4090. * send.
  4091. */
  4092. TextDocumentSyncKind.Incremental = 2;
  4093. })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
  4094. /**
  4095. * The initialize request is sent from the client to the server.
  4096. * It is sent once as the request after starting up the server.
  4097. * The requests parameter is of type [InitializeParams](#InitializeParams)
  4098. * the response if of type [InitializeResult](#InitializeResult) of a Thenable that
  4099. * resolves to such.
  4100. */
  4101. var InitializeRequest;
  4102. (function (InitializeRequest) {
  4103. InitializeRequest.type = new vscode_jsonrpc_1.RequestType('initialize');
  4104. })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
  4105. /**
  4106. * Known error codes for an `InitializeError`;
  4107. */
  4108. var InitializeError;
  4109. (function (InitializeError) {
  4110. /**
  4111. * If the protocol version provided by the client can't be handled by the server.
  4112. * @deprecated This initialize error got replaced by client capabilities. There is
  4113. * no version handshake in version 3.0x
  4114. */
  4115. InitializeError.unknownProtocolVersion = 1;
  4116. })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));
  4117. /**
  4118. * The intialized notification is sent from the client to the
  4119. * server after the client is fully initialized and the server
  4120. * is allowed to send requests from the server to the client.
  4121. */
  4122. var InitializedNotification;
  4123. (function (InitializedNotification) {
  4124. InitializedNotification.type = new vscode_jsonrpc_1.NotificationType('initialized');
  4125. })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
  4126. //---- Shutdown Method ----
  4127. /**
  4128. * A shutdown request is sent from the client to the server.
  4129. * It is sent once when the client decides to shutdown the
  4130. * server. The only notification that is sent after a shutdown request
  4131. * is the exit event.
  4132. */
  4133. var ShutdownRequest;
  4134. (function (ShutdownRequest) {
  4135. ShutdownRequest.type = new vscode_jsonrpc_1.RequestType0('shutdown');
  4136. })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
  4137. //---- Exit Notification ----
  4138. /**
  4139. * The exit event is sent from the client to the server to
  4140. * ask the server to exit its process.
  4141. */
  4142. var ExitNotification;
  4143. (function (ExitNotification) {
  4144. ExitNotification.type = new vscode_jsonrpc_1.NotificationType0('exit');
  4145. })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
  4146. //---- Configuration notification ----
  4147. /**
  4148. * The configuration change notification is sent from the client to the server
  4149. * when the client's configuration has changed. The notification contains
  4150. * the changed configuration as defined by the language client.
  4151. */
  4152. var DidChangeConfigurationNotification;
  4153. (function (DidChangeConfigurationNotification) {
  4154. DidChangeConfigurationNotification.type = new vscode_jsonrpc_1.NotificationType('workspace/didChangeConfiguration');
  4155. })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
  4156. //---- Message show and log notifications ----
  4157. /**
  4158. * The message type
  4159. */
  4160. var MessageType;
  4161. (function (MessageType) {
  4162. /**
  4163. * An error message.
  4164. */
  4165. MessageType.Error = 1;
  4166. /**
  4167. * A warning message.
  4168. */
  4169. MessageType.Warning = 2;
  4170. /**
  4171. * An information message.
  4172. */
  4173. MessageType.Info = 3;
  4174. /**
  4175. * A log message.
  4176. */
  4177. MessageType.Log = 4;
  4178. })(MessageType = exports.MessageType || (exports.MessageType = {}));
  4179. /**
  4180. * The show message notification is sent from a server to a client to ask
  4181. * the client to display a particular message in the user interface.
  4182. */
  4183. var ShowMessageNotification;
  4184. (function (ShowMessageNotification) {
  4185. ShowMessageNotification.type = new vscode_jsonrpc_1.NotificationType('window/showMessage');
  4186. })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
  4187. /**
  4188. * The show message request is sent from the server to the client to show a message
  4189. * and a set of options actions to the user.
  4190. */
  4191. var ShowMessageRequest;
  4192. (function (ShowMessageRequest) {
  4193. ShowMessageRequest.type = new vscode_jsonrpc_1.RequestType('window/showMessageRequest');
  4194. })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
  4195. /**
  4196. * The log message notification is sent from the server to the client to ask
  4197. * the client to log a particular message.
  4198. */
  4199. var LogMessageNotification;
  4200. (function (LogMessageNotification) {
  4201. LogMessageNotification.type = new vscode_jsonrpc_1.NotificationType('window/logMessage');
  4202. })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
  4203. //---- Telemetry notification
  4204. /**
  4205. * The telemetry event notification is sent from the server to the client to ask
  4206. * the client to log telemetry data.
  4207. */
  4208. var TelemetryEventNotification;
  4209. (function (TelemetryEventNotification) {
  4210. TelemetryEventNotification.type = new vscode_jsonrpc_1.NotificationType('telemetry/event');
  4211. })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
  4212. /**
  4213. * The document open notification is sent from the client to the server to signal
  4214. * newly opened text documents. The document's truth is now managed by the client
  4215. * and the server must not try to read the document's truth using the document's
  4216. * uri. Open in this sense means it is managed by the client. It doesn't necessarily
  4217. * mean that its content is presented in an editor. An open notification must not
  4218. * be sent more than once without a corresponding close notification send before.
  4219. * This means open and close notification must be balanced and the max open count
  4220. * is one.
  4221. */
  4222. var DidOpenTextDocumentNotification;
  4223. (function (DidOpenTextDocumentNotification) {
  4224. DidOpenTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/didOpen');
  4225. })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
  4226. /**
  4227. * The document change notification is sent from the client to the server to signal
  4228. * changes to a text document.
  4229. */
  4230. var DidChangeTextDocumentNotification;
  4231. (function (DidChangeTextDocumentNotification) {
  4232. DidChangeTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/didChange');
  4233. })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
  4234. /**
  4235. * The document close notification is sent from the client to the server when
  4236. * the document got closed in the client. The document's truth now exists where
  4237. * the document's uri points to (e.g. if the document's uri is a file uri the
  4238. * truth now exists on disk). As with the open notification the close notification
  4239. * is about managing the document's content. Receiving a close notification
  4240. * doesn't mean that the document was open in an editor before. A close
  4241. * notification requires a previous open notification to be sent.
  4242. */
  4243. var DidCloseTextDocumentNotification;
  4244. (function (DidCloseTextDocumentNotification) {
  4245. DidCloseTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/didClose');
  4246. })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
  4247. /**
  4248. * The document save notification is sent from the client to the server when
  4249. * the document got saved in the client.
  4250. */
  4251. var DidSaveTextDocumentNotification;
  4252. (function (DidSaveTextDocumentNotification) {
  4253. DidSaveTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/didSave');
  4254. })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
  4255. /**
  4256. * A document will save notification is sent from the client to the server before
  4257. * the document is actually saved.
  4258. */
  4259. var WillSaveTextDocumentNotification;
  4260. (function (WillSaveTextDocumentNotification) {
  4261. WillSaveTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/willSave');
  4262. })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
  4263. /**
  4264. * A document will save request is sent from the client to the server before
  4265. * the document is actually saved. The request can return an array of TextEdits
  4266. * which will be applied to the text document before it is saved. Please note that
  4267. * clients might drop results if computing the text edits took too long or if a
  4268. * server constantly fails on this request. This is done to keep the save fast and
  4269. * reliable.
  4270. */
  4271. var WillSaveTextDocumentWaitUntilRequest;
  4272. (function (WillSaveTextDocumentWaitUntilRequest) {
  4273. WillSaveTextDocumentWaitUntilRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/willSaveWaitUntil');
  4274. })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
  4275. //---- File eventing ----
  4276. /**
  4277. * The watched files notification is sent from the client to the server when
  4278. * the client detects changes to file watched by the language client.
  4279. */
  4280. var DidChangeWatchedFilesNotification;
  4281. (function (DidChangeWatchedFilesNotification) {
  4282. DidChangeWatchedFilesNotification.type = new vscode_jsonrpc_1.NotificationType('workspace/didChangeWatchedFiles');
  4283. })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
  4284. /**
  4285. * The file event type
  4286. */
  4287. var FileChangeType;
  4288. (function (FileChangeType) {
  4289. /**
  4290. * The file got created.
  4291. */
  4292. FileChangeType.Created = 1;
  4293. /**
  4294. * The file got changed.
  4295. */
  4296. FileChangeType.Changed = 2;
  4297. /**
  4298. * The file got deleted.
  4299. */
  4300. FileChangeType.Deleted = 3;
  4301. })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
  4302. var WatchKind;
  4303. (function (WatchKind) {
  4304. /**
  4305. * Interested in create events.
  4306. */
  4307. WatchKind.Create = 1;
  4308. /**
  4309. * Interested in change events
  4310. */
  4311. WatchKind.Change = 2;
  4312. /**
  4313. * Interested in delete events
  4314. */
  4315. WatchKind.Delete = 4;
  4316. })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
  4317. //---- Diagnostic notification ----
  4318. /**
  4319. * Diagnostics notification are sent from the server to the client to signal
  4320. * results of validation runs.
  4321. */
  4322. var PublishDiagnosticsNotification;
  4323. (function (PublishDiagnosticsNotification) {
  4324. PublishDiagnosticsNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/publishDiagnostics');
  4325. })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
  4326. /**
  4327. * How a completion was triggered
  4328. */
  4329. var CompletionTriggerKind;
  4330. (function (CompletionTriggerKind) {
  4331. /**
  4332. * Completion was triggered by typing an identifier (24x7 code
  4333. * complete), manual invocation (e.g Ctrl+Space) or via API.
  4334. */
  4335. CompletionTriggerKind.Invoked = 1;
  4336. /**
  4337. * Completion was triggered by a trigger character specified by
  4338. * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
  4339. */
  4340. CompletionTriggerKind.TriggerCharacter = 2;
  4341. /**
  4342. * Completion was re-triggered as current completion list is incomplete
  4343. */
  4344. CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
  4345. })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
  4346. /**
  4347. * Request to request completion at a given text document position. The request's
  4348. * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response
  4349. * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)
  4350. * or a Thenable that resolves to such.
  4351. *
  4352. * The request can delay the computation of the [`detail`](#CompletionItem.detail)
  4353. * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`
  4354. * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
  4355. * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
  4356. */
  4357. var CompletionRequest;
  4358. (function (CompletionRequest) {
  4359. CompletionRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/completion');
  4360. })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
  4361. /**
  4362. * Request to resolve additional information for a given completion item.The request's
  4363. * parameter is of type [CompletionItem](#CompletionItem) the response
  4364. * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.
  4365. */
  4366. var CompletionResolveRequest;
  4367. (function (CompletionResolveRequest) {
  4368. CompletionResolveRequest.type = new vscode_jsonrpc_1.RequestType('completionItem/resolve');
  4369. })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
  4370. //---- Hover Support -------------------------------
  4371. /**
  4372. * Request to request hover information at a given text document position. The request's
  4373. * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of
  4374. * type [Hover](#Hover) or a Thenable that resolves to such.
  4375. */
  4376. var HoverRequest;
  4377. (function (HoverRequest) {
  4378. HoverRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/hover');
  4379. })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
  4380. var SignatureHelpRequest;
  4381. (function (SignatureHelpRequest) {
  4382. SignatureHelpRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/signatureHelp');
  4383. })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
  4384. //---- Goto Definition -------------------------------------
  4385. /**
  4386. * A request to resolve the definition location of a symbol at a given text
  4387. * document position. The request's parameter is of type [TextDocumentPosition]
  4388. * (#TextDocumentPosition) the response is of either type [Definition](#Definition)
  4389. * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves
  4390. * to such.
  4391. */
  4392. var DefinitionRequest;
  4393. (function (DefinitionRequest) {
  4394. DefinitionRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/definition');
  4395. })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
  4396. /**
  4397. * A request to resolve project-wide references for the symbol denoted
  4398. * by the given text document position. The request's parameter is of
  4399. * type [ReferenceParams](#ReferenceParams) the response is of type
  4400. * [Location[]](#Location) or a Thenable that resolves to such.
  4401. */
  4402. var ReferencesRequest;
  4403. (function (ReferencesRequest) {
  4404. ReferencesRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/references');
  4405. })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
  4406. //---- Document Highlight ----------------------------------
  4407. /**
  4408. * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given
  4409. * text document position. The request's parameter is of type [TextDocumentPosition]
  4410. * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
  4411. * (#DocumentHighlight) or a Thenable that resolves to such.
  4412. */
  4413. var DocumentHighlightRequest;
  4414. (function (DocumentHighlightRequest) {
  4415. DocumentHighlightRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/documentHighlight');
  4416. })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
  4417. //---- Document Symbol Provider ---------------------------
  4418. /**
  4419. * A request to list all symbols found in a given text document. The request's
  4420. * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the
  4421. * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable
  4422. * that resolves to such.
  4423. */
  4424. var DocumentSymbolRequest;
  4425. (function (DocumentSymbolRequest) {
  4426. DocumentSymbolRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/documentSymbol');
  4427. })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
  4428. //---- Workspace Symbol Provider ---------------------------
  4429. /**
  4430. * A request to list project-wide symbols matching the query string given
  4431. * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is
  4432. * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that
  4433. * resolves to such.
  4434. */
  4435. var WorkspaceSymbolRequest;
  4436. (function (WorkspaceSymbolRequest) {
  4437. WorkspaceSymbolRequest.type = new vscode_jsonrpc_1.RequestType('workspace/symbol');
  4438. })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
  4439. /**
  4440. * A request to provide commands for the given text document and range.
  4441. */
  4442. var CodeActionRequest;
  4443. (function (CodeActionRequest) {
  4444. CodeActionRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/codeAction');
  4445. })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
  4446. /**
  4447. * A request to provide code lens for the given text document.
  4448. */
  4449. var CodeLensRequest;
  4450. (function (CodeLensRequest) {
  4451. CodeLensRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/codeLens');
  4452. })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
  4453. /**
  4454. * A request to resolve a command for a given code lens.
  4455. */
  4456. var CodeLensResolveRequest;
  4457. (function (CodeLensResolveRequest) {
  4458. CodeLensResolveRequest.type = new vscode_jsonrpc_1.RequestType('codeLens/resolve');
  4459. })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
  4460. /**
  4461. * A request to to format a whole document.
  4462. */
  4463. var DocumentFormattingRequest;
  4464. (function (DocumentFormattingRequest) {
  4465. DocumentFormattingRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/formatting');
  4466. })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
  4467. /**
  4468. * A request to to format a range in a document.
  4469. */
  4470. var DocumentRangeFormattingRequest;
  4471. (function (DocumentRangeFormattingRequest) {
  4472. DocumentRangeFormattingRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/rangeFormatting');
  4473. })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
  4474. /**
  4475. * A request to format a document on type.
  4476. */
  4477. var DocumentOnTypeFormattingRequest;
  4478. (function (DocumentOnTypeFormattingRequest) {
  4479. DocumentOnTypeFormattingRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/onTypeFormatting');
  4480. })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
  4481. /**
  4482. * A request to rename a symbol.
  4483. */
  4484. var RenameRequest;
  4485. (function (RenameRequest) {
  4486. RenameRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/rename');
  4487. })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
  4488. /**
  4489. * A request to test and perform the setup necessary for a rename.
  4490. */
  4491. var PrepareRenameRequest;
  4492. (function (PrepareRenameRequest) {
  4493. PrepareRenameRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/prepareRename');
  4494. })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
  4495. /**
  4496. * A request to provide document links
  4497. */
  4498. var DocumentLinkRequest;
  4499. (function (DocumentLinkRequest) {
  4500. DocumentLinkRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/documentLink');
  4501. })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
  4502. /**
  4503. * Request to resolve additional information for a given document link. The request's
  4504. * parameter is of type [DocumentLink](#DocumentLink) the response
  4505. * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.
  4506. */
  4507. var DocumentLinkResolveRequest;
  4508. (function (DocumentLinkResolveRequest) {
  4509. DocumentLinkResolveRequest.type = new vscode_jsonrpc_1.RequestType('documentLink/resolve');
  4510. })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
  4511. /**
  4512. * A request send from the client to the server to execute a command. The request might return
  4513. * a workspace edit which the client will apply to the workspace.
  4514. */
  4515. var ExecuteCommandRequest;
  4516. (function (ExecuteCommandRequest) {
  4517. ExecuteCommandRequest.type = new vscode_jsonrpc_1.RequestType('workspace/executeCommand');
  4518. })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
  4519. /**
  4520. * A request sent from the server to the client to modified certain resources.
  4521. */
  4522. var ApplyWorkspaceEditRequest;
  4523. (function (ApplyWorkspaceEditRequest) {
  4524. ApplyWorkspaceEditRequest.type = new vscode_jsonrpc_1.RequestType('workspace/applyEdit');
  4525. })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
  4526. /***/ }),
  4527. /* 19 */
  4528. /***/ (function(module, exports, __webpack_require__) {
  4529. "use strict";
  4530. /* --------------------------------------------------------------------------------------------
  4531. * Copyright (c) Microsoft Corporation. All rights reserved.
  4532. * Licensed under the MIT License. See License.txt in the project root for license information.
  4533. * ------------------------------------------------------------------------------------------ */
  4534. Object.defineProperty(exports, "__esModule", { value: true });
  4535. function boolean(value) {
  4536. return value === true || value === false;
  4537. }
  4538. exports.boolean = boolean;
  4539. function string(value) {
  4540. return typeof value === 'string' || value instanceof String;
  4541. }
  4542. exports.string = string;
  4543. function number(value) {
  4544. return typeof value === 'number' || value instanceof Number;
  4545. }
  4546. exports.number = number;
  4547. function error(value) {
  4548. return value instanceof Error;
  4549. }
  4550. exports.error = error;
  4551. function func(value) {
  4552. return typeof value === 'function';
  4553. }
  4554. exports.func = func;
  4555. function array(value) {
  4556. return Array.isArray(value);
  4557. }
  4558. exports.array = array;
  4559. function stringArray(value) {
  4560. return array(value) && value.every(elem => string(elem));
  4561. }
  4562. exports.stringArray = stringArray;
  4563. function typedArray(value, check) {
  4564. return Array.isArray(value) && value.every(check);
  4565. }
  4566. exports.typedArray = typedArray;
  4567. function thenable(value) {
  4568. return value && func(value.then);
  4569. }
  4570. exports.thenable = thenable;
  4571. /***/ }),
  4572. /* 20 */
  4573. /***/ (function(module, exports, __webpack_require__) {
  4574. "use strict";
  4575. /* --------------------------------------------------------------------------------------------
  4576. * Copyright (c) Microsoft Corporation. All rights reserved.
  4577. * Licensed under the MIT License. See License.txt in the project root for license information.
  4578. * ------------------------------------------------------------------------------------------ */
  4579. Object.defineProperty(exports, "__esModule", { value: true });
  4580. const vscode_jsonrpc_1 = __webpack_require__(4);
  4581. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  4582. let __noDynamicImport;
  4583. /**
  4584. * A request to resolve the implementation locations of a symbol at a given text
  4585. * document position. The request's parameter is of type [TextDocumentPositioParams]
  4586. * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
  4587. * Thenable that resolves to such.
  4588. */
  4589. var ImplementationRequest;
  4590. (function (ImplementationRequest) {
  4591. ImplementationRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/implementation');
  4592. })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
  4593. /***/ }),
  4594. /* 21 */
  4595. /***/ (function(module, exports, __webpack_require__) {
  4596. "use strict";
  4597. /* --------------------------------------------------------------------------------------------
  4598. * Copyright (c) Microsoft Corporation. All rights reserved.
  4599. * Licensed under the MIT License. See License.txt in the project root for license information.
  4600. * ------------------------------------------------------------------------------------------ */
  4601. Object.defineProperty(exports, "__esModule", { value: true });
  4602. const vscode_jsonrpc_1 = __webpack_require__(4);
  4603. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  4604. let __noDynamicImport;
  4605. /**
  4606. * A request to resolve the type definition locations of a symbol at a given text
  4607. * document position. The request's parameter is of type [TextDocumentPositioParams]
  4608. * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
  4609. * Thenable that resolves to such.
  4610. */
  4611. var TypeDefinitionRequest;
  4612. (function (TypeDefinitionRequest) {
  4613. TypeDefinitionRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/typeDefinition');
  4614. })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
  4615. /***/ }),
  4616. /* 22 */
  4617. /***/ (function(module, exports, __webpack_require__) {
  4618. "use strict";
  4619. /* --------------------------------------------------------------------------------------------
  4620. * Copyright (c) Microsoft Corporation. All rights reserved.
  4621. * Licensed under the MIT License. See License.txt in the project root for license information.
  4622. * ------------------------------------------------------------------------------------------ */
  4623. Object.defineProperty(exports, "__esModule", { value: true });
  4624. const vscode_jsonrpc_1 = __webpack_require__(4);
  4625. /**
  4626. * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
  4627. */
  4628. var WorkspaceFoldersRequest;
  4629. (function (WorkspaceFoldersRequest) {
  4630. WorkspaceFoldersRequest.type = new vscode_jsonrpc_1.RequestType0('workspace/workspaceFolders');
  4631. })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
  4632. /**
  4633. * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
  4634. * folder configuration changes.
  4635. */
  4636. var DidChangeWorkspaceFoldersNotification;
  4637. (function (DidChangeWorkspaceFoldersNotification) {
  4638. DidChangeWorkspaceFoldersNotification.type = new vscode_jsonrpc_1.NotificationType('workspace/didChangeWorkspaceFolders');
  4639. })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
  4640. /***/ }),
  4641. /* 23 */
  4642. /***/ (function(module, exports, __webpack_require__) {
  4643. "use strict";
  4644. /* --------------------------------------------------------------------------------------------
  4645. * Copyright (c) Microsoft Corporation. All rights reserved.
  4646. * Licensed under the MIT License. See License.txt in the project root for license information.
  4647. * ------------------------------------------------------------------------------------------ */
  4648. Object.defineProperty(exports, "__esModule", { value: true });
  4649. const vscode_jsonrpc_1 = __webpack_require__(4);
  4650. /**
  4651. * The 'workspace/configuration' request is sent from the server to the client to fetch a certain
  4652. * configuration setting.
  4653. *
  4654. * This pull model replaces the old push model were the client signaled configuration change via an
  4655. * event. If the server still needs to react to configuration changes (since the server caches the
  4656. * result of `workspace/configuration` requests) the server should register for an empty configuration
  4657. * change event and empty the cache if such an event is received.
  4658. */
  4659. var ConfigurationRequest;
  4660. (function (ConfigurationRequest) {
  4661. ConfigurationRequest.type = new vscode_jsonrpc_1.RequestType('workspace/configuration');
  4662. })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
  4663. /***/ }),
  4664. /* 24 */
  4665. /***/ (function(module, exports, __webpack_require__) {
  4666. "use strict";
  4667. /* --------------------------------------------------------------------------------------------
  4668. * Copyright (c) Microsoft Corporation. All rights reserved.
  4669. * Licensed under the MIT License. See License.txt in the project root for license information.
  4670. * ------------------------------------------------------------------------------------------ */
  4671. Object.defineProperty(exports, "__esModule", { value: true });
  4672. const vscode_jsonrpc_1 = __webpack_require__(4);
  4673. /**
  4674. * A request to list all color symbols found in a given text document. The request's
  4675. * parameter is of type [DocumentColorParams](#DocumentColorParams) the
  4676. * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
  4677. * that resolves to such.
  4678. */
  4679. var DocumentColorRequest;
  4680. (function (DocumentColorRequest) {
  4681. DocumentColorRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/documentColor');
  4682. })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
  4683. /**
  4684. * A request to list all presentation for a color. The request's
  4685. * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the
  4686. * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
  4687. * that resolves to such.
  4688. */
  4689. var ColorPresentationRequest;
  4690. (function (ColorPresentationRequest) {
  4691. ColorPresentationRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/colorPresentation');
  4692. })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
  4693. /***/ }),
  4694. /* 25 */
  4695. /***/ (function(module, exports, __webpack_require__) {
  4696. "use strict";
  4697. /*---------------------------------------------------------------------------------------------
  4698. * Copyright (c) Microsoft Corporation. All rights reserved.
  4699. * Licensed under the MIT License. See License.txt in the project root for license information.
  4700. *--------------------------------------------------------------------------------------------*/
  4701. Object.defineProperty(exports, "__esModule", { value: true });
  4702. const vscode_jsonrpc_1 = __webpack_require__(4);
  4703. /**
  4704. * Enum of known range kinds
  4705. */
  4706. var FoldingRangeKind;
  4707. (function (FoldingRangeKind) {
  4708. /**
  4709. * Folding range for a comment
  4710. */
  4711. FoldingRangeKind["Comment"] = "comment";
  4712. /**
  4713. * Folding range for a imports or includes
  4714. */
  4715. FoldingRangeKind["Imports"] = "imports";
  4716. /**
  4717. * Folding range for a region (e.g. `#region`)
  4718. */
  4719. FoldingRangeKind["Region"] = "region";
  4720. })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
  4721. /**
  4722. * A request to provide folding ranges in a document. The request's
  4723. * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the
  4724. * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable
  4725. * that resolves to such.
  4726. */
  4727. var FoldingRangeRequest;
  4728. (function (FoldingRangeRequest) {
  4729. FoldingRangeRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/foldingRange');
  4730. })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
  4731. /***/ }),
  4732. /* 26 */
  4733. /***/ (function(module, exports, __webpack_require__) {
  4734. "use strict";
  4735. /* --------------------------------------------------------------------------------------------
  4736. * Copyright (c) Microsoft Corporation. All rights reserved.
  4737. * Licensed under the MIT License. See License.txt in the project root for license information.
  4738. * ------------------------------------------------------------------------------------------ */
  4739. Object.defineProperty(exports, "__esModule", { value: true });
  4740. const vscode_jsonrpc_1 = __webpack_require__(4);
  4741. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  4742. let __noDynamicImport;
  4743. /**
  4744. * A request to resolve the type definition locations of a symbol at a given text
  4745. * document position. The request's parameter is of type [TextDocumentPositioParams]
  4746. * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)
  4747. * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves
  4748. * to such.
  4749. */
  4750. var DeclarationRequest;
  4751. (function (DeclarationRequest) {
  4752. DeclarationRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/declaration');
  4753. })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
  4754. /***/ }),
  4755. /* 27 */
  4756. /***/ (function(module, exports, __webpack_require__) {
  4757. "use strict";
  4758. /* --------------------------------------------------------------------------------------------
  4759. * Copyright (c) TypeFox and others. All rights reserved.
  4760. * Licensed under the MIT License. See License.txt in the project root for license information.
  4761. * ------------------------------------------------------------------------------------------ */
  4762. Object.defineProperty(exports, "__esModule", { value: true });
  4763. const vscode_jsonrpc_1 = __webpack_require__(4);
  4764. /**
  4765. * The direction of a call hierarchy request.
  4766. */
  4767. var CallHierarchyDirection;
  4768. (function (CallHierarchyDirection) {
  4769. /**
  4770. * The callers
  4771. */
  4772. CallHierarchyDirection.CallsFrom = 1;
  4773. /**
  4774. * The callees
  4775. */
  4776. CallHierarchyDirection.CallsTo = 2;
  4777. })(CallHierarchyDirection = exports.CallHierarchyDirection || (exports.CallHierarchyDirection = {}));
  4778. /**
  4779. * Request to provide the call hierarchy at a given text document position.
  4780. *
  4781. * The request's parameter is of type [CallHierarchyParams](#CallHierarchyParams). The response
  4782. * is of type [CallHierarchyCall[]](#CallHierarchyCall) or a Thenable that resolves to such.
  4783. *
  4784. * Evaluates the symbol defined (or referenced) at the given position, and returns all incoming or outgoing calls to the symbol(s).
  4785. */
  4786. var CallHierarchyRequest;
  4787. (function (CallHierarchyRequest) {
  4788. CallHierarchyRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/callHierarchy');
  4789. })(CallHierarchyRequest = exports.CallHierarchyRequest || (exports.CallHierarchyRequest = {}));
  4790. /***/ }),
  4791. /* 28 */
  4792. /***/ (function(module, exports, __webpack_require__) {
  4793. "use strict";
  4794. /* --------------------------------------------------------------------------------------------
  4795. * Copyright (c) Microsoft Corporation. All rights reserved.
  4796. * Licensed under the MIT License. See License.txt in the project root for license information.
  4797. * ------------------------------------------------------------------------------------------ */
  4798. Object.defineProperty(exports, "__esModule", { value: true });
  4799. const vscode_jsonrpc_1 = __webpack_require__(4);
  4800. /**
  4801. * The `window/progress/start` notification is sent from the server to the client
  4802. * to initiate a progress.
  4803. */
  4804. var ProgressStartNotification;
  4805. (function (ProgressStartNotification) {
  4806. ProgressStartNotification.type = new vscode_jsonrpc_1.NotificationType('window/progress/start');
  4807. })(ProgressStartNotification = exports.ProgressStartNotification || (exports.ProgressStartNotification = {}));
  4808. /**
  4809. * The `window/progress/report` notification is sent from the server to the client
  4810. * to initiate a progress.
  4811. */
  4812. var ProgressReportNotification;
  4813. (function (ProgressReportNotification) {
  4814. ProgressReportNotification.type = new vscode_jsonrpc_1.NotificationType('window/progress/report');
  4815. })(ProgressReportNotification = exports.ProgressReportNotification || (exports.ProgressReportNotification = {}));
  4816. /**
  4817. * The `window/progress/done` notification is sent from the server to the client
  4818. * to initiate a progress.
  4819. */
  4820. var ProgressDoneNotification;
  4821. (function (ProgressDoneNotification) {
  4822. ProgressDoneNotification.type = new vscode_jsonrpc_1.NotificationType('window/progress/done');
  4823. })(ProgressDoneNotification = exports.ProgressDoneNotification || (exports.ProgressDoneNotification = {}));
  4824. /**
  4825. * The `window/progress/cancel` notification is sent client to the server to cancel a progress
  4826. * initiated on the server side.
  4827. */
  4828. var ProgressCancelNotification;
  4829. (function (ProgressCancelNotification) {
  4830. ProgressCancelNotification.type = new vscode_jsonrpc_1.NotificationType('window/progress/cancel');
  4831. })(ProgressCancelNotification = exports.ProgressCancelNotification || (exports.ProgressCancelNotification = {}));
  4832. /***/ }),
  4833. /* 29 */
  4834. /***/ (function(module, exports, __webpack_require__) {
  4835. "use strict";
  4836. /*---------------------------------------------------------------------------------------------
  4837. * Copyright (c) Microsoft Corporation. All rights reserved.
  4838. * Licensed under the MIT License. See License.txt in the project root for license information.
  4839. *--------------------------------------------------------------------------------------------*/
  4840. Object.defineProperty(exports, "__esModule", { value: true });
  4841. const vscode_jsonrpc_1 = __webpack_require__(4);
  4842. const vscode_languageserver_types_1 = __webpack_require__(17);
  4843. /**
  4844. * The SelectionRange namespace provides helper function to work with
  4845. * SelectionRange literals.
  4846. */
  4847. var SelectionRange;
  4848. (function (SelectionRange) {
  4849. /**
  4850. * Creates a new SelectionRange
  4851. * @param range the range.
  4852. * @param parent an optional parent.
  4853. */
  4854. function create(range, parent) {
  4855. return { range, parent };
  4856. }
  4857. SelectionRange.create = create;
  4858. function is(value) {
  4859. let candidate = value;
  4860. return candidate !== undefined && vscode_languageserver_types_1.Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
  4861. }
  4862. SelectionRange.is = is;
  4863. })(SelectionRange = exports.SelectionRange || (exports.SelectionRange = {}));
  4864. /**
  4865. * A request to provide selection ranges in a document. The request's
  4866. * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the
  4867. * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable
  4868. * that resolves to such.
  4869. */
  4870. var SelectionRangeRequest;
  4871. (function (SelectionRangeRequest) {
  4872. SelectionRangeRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/selectionRange');
  4873. })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
  4874. /***/ }),
  4875. /* 30 */,
  4876. /* 31 */,
  4877. /* 32 */,
  4878. /* 33 */
  4879. /***/ (function(module, exports, __webpack_require__) {
  4880. "use strict";
  4881. /*---------------------------------------------------------------------------------------------
  4882. * Copyright (c) Microsoft Corporation. All rights reserved.
  4883. * Licensed under the MIT License. See License.txt in the project root for license information.
  4884. *--------------------------------------------------------------------------------------------*/
  4885. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  4886. return new (P || (P = Promise))(function (resolve, reject) {
  4887. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  4888. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  4889. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  4890. step((generator = generator.apply(thisArg, _arguments || [])).next());
  4891. });
  4892. };
  4893. var __importStar = (this && this.__importStar) || function (mod) {
  4894. if (mod && mod.__esModule) return mod;
  4895. var result = {};
  4896. if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  4897. result["default"] = mod;
  4898. return result;
  4899. };
  4900. Object.defineProperty(exports, "__esModule", { value: true });
  4901. const vscode_languageserver_1 = __webpack_require__(34);
  4902. const request_light_1 = __webpack_require__(49);
  4903. const fs = __importStar(__webpack_require__(2));
  4904. const vscode_uri_1 = __webpack_require__(77);
  4905. const URL = __importStar(__webpack_require__(40));
  4906. const runner_1 = __webpack_require__(78);
  4907. const vscode_json_languageservice_1 = __webpack_require__(79);
  4908. const languageModelCache_1 = __webpack_require__(101);
  4909. var SchemaAssociationNotification;
  4910. (function (SchemaAssociationNotification) {
  4911. SchemaAssociationNotification.type = new vscode_languageserver_1.NotificationType('json/schemaAssociations');
  4912. })(SchemaAssociationNotification || (SchemaAssociationNotification = {}));
  4913. var VSCodeContentRequest;
  4914. (function (VSCodeContentRequest) {
  4915. VSCodeContentRequest.type = new vscode_languageserver_1.RequestType('vscode/content');
  4916. })(VSCodeContentRequest || (VSCodeContentRequest = {}));
  4917. var SchemaContentChangeNotification;
  4918. (function (SchemaContentChangeNotification) {
  4919. SchemaContentChangeNotification.type = new vscode_languageserver_1.NotificationType('json/schemaContent');
  4920. })(SchemaContentChangeNotification || (SchemaContentChangeNotification = {}));
  4921. var ForceValidateRequest;
  4922. (function (ForceValidateRequest) {
  4923. ForceValidateRequest.type = new vscode_languageserver_1.RequestType('json/validate');
  4924. })(ForceValidateRequest || (ForceValidateRequest = {}));
  4925. // Create a connection for the server
  4926. const connection = vscode_languageserver_1.createConnection();
  4927. process.on('unhandledRejection', (e) => {
  4928. console.error(runner_1.formatError(`Unhandled exception`, e));
  4929. });
  4930. process.on('uncaughtException', (e) => {
  4931. console.error(runner_1.formatError(`Unhandled exception`, e));
  4932. });
  4933. console.log = connection.console.log.bind(connection.console);
  4934. console.error = connection.console.error.bind(connection.console);
  4935. const workspaceContext = {
  4936. resolveRelativePath: (relativePath, resource) => {
  4937. return URL.resolve(resource, relativePath);
  4938. }
  4939. };
  4940. function getSchemaRequestService(handledSchemas) {
  4941. return (uri) => {
  4942. const protocol = uri.substr(0, uri.indexOf(':'));
  4943. if (!handledSchemas || handledSchemas[protocol]) {
  4944. if (protocol === 'file') {
  4945. const fsPath = vscode_uri_1.URI.parse(uri).fsPath;
  4946. return new Promise((c, e) => {
  4947. fs.readFile(fsPath, 'UTF-8', (err, result) => {
  4948. err ? e(err.message || err.toString()) : c(result.toString());
  4949. });
  4950. });
  4951. }
  4952. else if (protocol === 'http' || protocol === 'https') {
  4953. if (uri.indexOf('//schema.management.azure.com/') !== -1) {
  4954. /* __GDPR__
  4955. "json.schema" : {
  4956. "schemaURL" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
  4957. }
  4958. */
  4959. connection.telemetry.logEvent({
  4960. key: 'json.schema',
  4961. value: {
  4962. schemaURL: uri
  4963. }
  4964. });
  4965. }
  4966. const headers = { 'Accept-Encoding': 'gzip, deflate' };
  4967. return request_light_1.xhr({ url: uri, followRedirects: 5, headers }).then(response => {
  4968. return response.responseText;
  4969. }, (error) => {
  4970. return Promise.reject(error.responseText || request_light_1.getErrorStatusDescription(error.status) || error.toString());
  4971. });
  4972. }
  4973. }
  4974. return connection.sendRequest(VSCodeContentRequest.type, uri).then(responseText => {
  4975. return responseText;
  4976. }, error => {
  4977. return Promise.reject(error.message);
  4978. });
  4979. };
  4980. }
  4981. // create the JSON language service
  4982. let languageService = vscode_json_languageservice_1.getLanguageService({
  4983. workspaceContext,
  4984. contributions: [],
  4985. });
  4986. // Create a simple text document manager. The text document manager
  4987. // supports full document sync only
  4988. const documents = new vscode_languageserver_1.TextDocuments();
  4989. // Make the text document manager listen on the connection
  4990. // for open, change and close text document events
  4991. documents.listen(connection);
  4992. let clientSnippetSupport = false;
  4993. let clientDynamicRegisterSupport = false;
  4994. let foldingRangeLimit = Number.MAX_VALUE;
  4995. let hierarchicalDocumentSymbolSupport = false;
  4996. // After the server has started the client sends an initialize request. The server receives
  4997. // in the passed params the rootPath of the workspace plus the client capabilities.
  4998. connection.onInitialize((params) => {
  4999. const handledProtocols = params.initializationOptions && params.initializationOptions['handledSchemaProtocols'];
  5000. languageService = vscode_json_languageservice_1.getLanguageService({
  5001. schemaRequestService: getSchemaRequestService(handledProtocols),
  5002. workspaceContext,
  5003. contributions: [],
  5004. clientCapabilities: params.capabilities
  5005. });
  5006. function getClientCapability(name, def) {
  5007. const keys = name.split('.');
  5008. let c = params.capabilities;
  5009. for (let i = 0; c && i < keys.length; i++) {
  5010. if (!c.hasOwnProperty(keys[i])) {
  5011. return def;
  5012. }
  5013. c = c[keys[i]];
  5014. }
  5015. return c;
  5016. }
  5017. clientSnippetSupport = getClientCapability('textDocument.completion.completionItem.snippetSupport', false);
  5018. clientDynamicRegisterSupport = getClientCapability('workspace.symbol.dynamicRegistration', false);
  5019. foldingRangeLimit = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE);
  5020. hierarchicalDocumentSymbolSupport = getClientCapability('textDocument.documentSymbol.hierarchicalDocumentSymbolSupport', false);
  5021. const capabilities = {
  5022. // Tell the client that the server works in FULL text document sync mode
  5023. textDocumentSync: documents.syncKind,
  5024. completionProvider: clientSnippetSupport ? { resolveProvider: true, triggerCharacters: ['"', ':'] } : undefined,
  5025. hoverProvider: true,
  5026. documentSymbolProvider: true,
  5027. documentRangeFormattingProvider: false,
  5028. colorProvider: {},
  5029. foldingRangeProvider: true
  5030. };
  5031. return { capabilities };
  5032. });
  5033. let jsonConfigurationSettings = undefined;
  5034. let schemaAssociations = undefined;
  5035. let formatterRegistration = null;
  5036. // The settings have changed. Is send on server activation as well.
  5037. connection.onDidChangeConfiguration((change) => {
  5038. let settings = change.settings;
  5039. request_light_1.configure(settings.http && settings.http.proxy, settings.http && settings.http.proxyStrictSSL);
  5040. jsonConfigurationSettings = settings.json && settings.json.schemas;
  5041. updateConfiguration();
  5042. // dynamically enable & disable the formatter
  5043. if (clientDynamicRegisterSupport) {
  5044. const enableFormatter = settings && settings.json && settings.json.format && settings.json.format.enable;
  5045. if (enableFormatter) {
  5046. if (!formatterRegistration) {
  5047. formatterRegistration = connection.client.register(vscode_languageserver_1.DocumentRangeFormattingRequest.type, { documentSelector: [{ language: 'json' }, { language: 'jsonc' }] });
  5048. }
  5049. }
  5050. else if (formatterRegistration) {
  5051. formatterRegistration.then(r => r.dispose());
  5052. formatterRegistration = null;
  5053. }
  5054. }
  5055. });
  5056. // The jsonValidation extension configuration has changed
  5057. connection.onNotification(SchemaAssociationNotification.type, associations => {
  5058. schemaAssociations = associations;
  5059. updateConfiguration();
  5060. });
  5061. // A schema has changed
  5062. connection.onNotification(SchemaContentChangeNotification.type, uri => {
  5063. languageService.resetSchema(uri);
  5064. });
  5065. // Retry schema validation on all open documents
  5066. connection.onRequest(ForceValidateRequest.type, uri => {
  5067. return new Promise(resolve => {
  5068. const document = documents.get(uri);
  5069. if (document) {
  5070. updateConfiguration();
  5071. validateTextDocument(document, diagnostics => {
  5072. resolve(diagnostics);
  5073. });
  5074. }
  5075. else {
  5076. resolve([]);
  5077. }
  5078. });
  5079. });
  5080. function updateConfiguration() {
  5081. const languageSettings = {
  5082. validate: true,
  5083. allowComments: true,
  5084. schemas: new Array()
  5085. };
  5086. if (schemaAssociations) {
  5087. for (const pattern in schemaAssociations) {
  5088. const association = schemaAssociations[pattern];
  5089. if (Array.isArray(association)) {
  5090. association.forEach(uri => {
  5091. languageSettings.schemas.push({ uri, fileMatch: [pattern] });
  5092. });
  5093. }
  5094. }
  5095. }
  5096. if (jsonConfigurationSettings) {
  5097. jsonConfigurationSettings.forEach((schema, index) => {
  5098. let uri = schema.url;
  5099. if (!uri && schema.schema) {
  5100. uri = schema.schema.id || `vscode://schemas/custom/${index}`;
  5101. }
  5102. if (uri) {
  5103. languageSettings.schemas.push({ uri, fileMatch: schema.fileMatch, schema: schema.schema });
  5104. }
  5105. });
  5106. }
  5107. languageService.configure(languageSettings);
  5108. // Revalidate any open text documents
  5109. documents.all().forEach(triggerValidation);
  5110. }
  5111. // The content of a text document has changed. This event is emitted
  5112. // when the text document first opened or when its content has changed.
  5113. documents.onDidChangeContent((change) => {
  5114. triggerValidation(change.document);
  5115. });
  5116. // a document has closed: clear all diagnostics
  5117. documents.onDidClose(event => {
  5118. cleanPendingValidation(event.document);
  5119. connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] });
  5120. });
  5121. const pendingValidationRequests = {};
  5122. const validationDelayMs = 500;
  5123. function cleanPendingValidation(textDocument) {
  5124. const request = pendingValidationRequests[textDocument.uri];
  5125. if (request) {
  5126. clearTimeout(request);
  5127. delete pendingValidationRequests[textDocument.uri];
  5128. }
  5129. }
  5130. function triggerValidation(textDocument) {
  5131. cleanPendingValidation(textDocument);
  5132. pendingValidationRequests[textDocument.uri] = setTimeout(() => {
  5133. delete pendingValidationRequests[textDocument.uri];
  5134. validateTextDocument(textDocument);
  5135. }, validationDelayMs);
  5136. }
  5137. function validateTextDocument(textDocument, callback) {
  5138. const respond = (diagnostics) => {
  5139. connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
  5140. if (callback) {
  5141. callback(diagnostics);
  5142. }
  5143. };
  5144. if (textDocument.getText().length === 0) {
  5145. respond([]); // ignore empty documents
  5146. return;
  5147. }
  5148. const jsonDocument = getJSONDocument(textDocument);
  5149. const version = textDocument.version;
  5150. const documentSettings = textDocument.languageId === 'jsonc' ? { comments: 'ignore', trailingCommas: 'ignore' } : { comments: 'error', trailingCommas: 'error' };
  5151. languageService.doValidation(textDocument, jsonDocument, documentSettings).then(diagnostics => {
  5152. setTimeout(() => {
  5153. const currDocument = documents.get(textDocument.uri);
  5154. if (currDocument && currDocument.version === version) {
  5155. respond(diagnostics); // Send the computed diagnostics to VSCode.
  5156. }
  5157. }, 100);
  5158. }, error => {
  5159. connection.console.error(runner_1.formatError(`Error while validating ${textDocument.uri}`, error));
  5160. });
  5161. }
  5162. connection.onDidChangeWatchedFiles((change) => {
  5163. // Monitored files have changed in VSCode
  5164. let hasChanges = false;
  5165. change.changes.forEach(c => {
  5166. if (languageService.resetSchema(c.uri)) {
  5167. hasChanges = true;
  5168. }
  5169. });
  5170. if (hasChanges) {
  5171. documents.all().forEach(triggerValidation);
  5172. }
  5173. });
  5174. const jsonDocuments = languageModelCache_1.getLanguageModelCache(10, 60, document => languageService.parseJSONDocument(document));
  5175. documents.onDidClose(e => {
  5176. jsonDocuments.onDocumentRemoved(e.document);
  5177. });
  5178. connection.onShutdown(() => {
  5179. jsonDocuments.dispose();
  5180. });
  5181. function getJSONDocument(document) {
  5182. return jsonDocuments.get(document);
  5183. }
  5184. connection.onCompletion((textDocumentPosition, token) => {
  5185. return runner_1.runSafeAsync(() => __awaiter(this, void 0, void 0, function* () {
  5186. const document = documents.get(textDocumentPosition.textDocument.uri);
  5187. if (document) {
  5188. const jsonDocument = getJSONDocument(document);
  5189. return languageService.doComplete(document, textDocumentPosition.position, jsonDocument);
  5190. }
  5191. return null;
  5192. }), null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`, token);
  5193. });
  5194. connection.onCompletionResolve((completionItem, token) => {
  5195. return runner_1.runSafeAsync(() => {
  5196. return languageService.doResolve(completionItem);
  5197. }, completionItem, `Error while resolving completion proposal`, token);
  5198. });
  5199. connection.onHover((textDocumentPositionParams, token) => {
  5200. return runner_1.runSafeAsync(() => __awaiter(this, void 0, void 0, function* () {
  5201. const document = documents.get(textDocumentPositionParams.textDocument.uri);
  5202. if (document) {
  5203. const jsonDocument = getJSONDocument(document);
  5204. return languageService.doHover(document, textDocumentPositionParams.position, jsonDocument);
  5205. }
  5206. return null;
  5207. }), null, `Error while computing hover for ${textDocumentPositionParams.textDocument.uri}`, token);
  5208. });
  5209. connection.onDocumentSymbol((documentSymbolParams, token) => {
  5210. return runner_1.runSafe(() => {
  5211. const document = documents.get(documentSymbolParams.textDocument.uri);
  5212. if (document) {
  5213. const jsonDocument = getJSONDocument(document);
  5214. if (hierarchicalDocumentSymbolSupport) {
  5215. return languageService.findDocumentSymbols2(document, jsonDocument);
  5216. }
  5217. else {
  5218. return languageService.findDocumentSymbols(document, jsonDocument);
  5219. }
  5220. }
  5221. return [];
  5222. }, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, token);
  5223. });
  5224. connection.onDocumentRangeFormatting((formatParams, token) => {
  5225. return runner_1.runSafe(() => {
  5226. const document = documents.get(formatParams.textDocument.uri);
  5227. if (document) {
  5228. return languageService.format(document, formatParams.range, formatParams.options);
  5229. }
  5230. return [];
  5231. }, [], `Error while formatting range for ${formatParams.textDocument.uri}`, token);
  5232. });
  5233. connection.onDocumentColor((params, token) => {
  5234. return runner_1.runSafeAsync(() => __awaiter(this, void 0, void 0, function* () {
  5235. const document = documents.get(params.textDocument.uri);
  5236. if (document) {
  5237. const jsonDocument = getJSONDocument(document);
  5238. return languageService.findDocumentColors(document, jsonDocument);
  5239. }
  5240. return [];
  5241. }), [], `Error while computing document colors for ${params.textDocument.uri}`, token);
  5242. });
  5243. connection.onColorPresentation((params, token) => {
  5244. return runner_1.runSafe(() => {
  5245. const document = documents.get(params.textDocument.uri);
  5246. if (document) {
  5247. const jsonDocument = getJSONDocument(document);
  5248. return languageService.getColorPresentations(document, jsonDocument, params.color, params.range);
  5249. }
  5250. return [];
  5251. }, [], `Error while computing color presentations for ${params.textDocument.uri}`, token);
  5252. });
  5253. connection.onFoldingRanges((params, token) => {
  5254. return runner_1.runSafe(() => {
  5255. const document = documents.get(params.textDocument.uri);
  5256. if (document) {
  5257. return languageService.getFoldingRanges(document, { rangeLimit: foldingRangeLimit });
  5258. }
  5259. return null;
  5260. }, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token);
  5261. });
  5262. connection.onRequest('$/textDocument/selectionRanges', (params, token) => __awaiter(this, void 0, void 0, function* () {
  5263. return runner_1.runSafe(() => {
  5264. const document = documents.get(params.textDocument.uri);
  5265. if (document) {
  5266. const jsonDocument = getJSONDocument(document);
  5267. return languageService.getSelectionRanges(document, params.positions, jsonDocument);
  5268. }
  5269. return [];
  5270. }, [], `Error while computing selection ranges for ${params.textDocument.uri}`, token);
  5271. }));
  5272. // Listen on the connection
  5273. connection.listen();
  5274. /***/ }),
  5275. /* 34 */
  5276. /***/ (function(module, exports, __webpack_require__) {
  5277. "use strict";
  5278. /* --------------------------------------------------------------------------------------------
  5279. * Copyright (c) Microsoft Corporation. All rights reserved.
  5280. * Licensed under the MIT License. See License.txt in the project root for license information.
  5281. * ------------------------------------------------------------------------------------------ */
  5282. /// <reference path="./thenable.ts" />
  5283. function __export(m) {
  5284. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  5285. }
  5286. Object.defineProperty(exports, "__esModule", { value: true });
  5287. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  5288. exports.Event = vscode_languageserver_protocol_1.Event;
  5289. const configuration_1 = __webpack_require__(35);
  5290. const workspaceFolders_1 = __webpack_require__(37);
  5291. const Is = __webpack_require__(36);
  5292. const UUID = __webpack_require__(38);
  5293. // ------------- Reexport the API surface of the language worker API ----------------------
  5294. __export(__webpack_require__(3));
  5295. const fm = __webpack_require__(39);
  5296. const vscode_textbuffer_1 = __webpack_require__(42);
  5297. const range_1 = __webpack_require__(47);
  5298. var Files;
  5299. (function (Files) {
  5300. Files.uriToFilePath = fm.uriToFilePath;
  5301. Files.resolveGlobalNodePath = fm.resolveGlobalNodePath;
  5302. Files.resolveGlobalYarnPath = fm.resolveGlobalYarnPath;
  5303. Files.resolve = fm.resolve;
  5304. Files.resolveModulePath = fm.resolveModulePath;
  5305. })(Files = exports.Files || (exports.Files = {}));
  5306. let shutdownReceived = false;
  5307. let exitTimer = undefined;
  5308. function setupExitTimer() {
  5309. const argName = '--clientProcessId';
  5310. function runTimer(value) {
  5311. try {
  5312. let processId = parseInt(value);
  5313. if (!isNaN(processId)) {
  5314. exitTimer = setInterval(() => {
  5315. try {
  5316. process.kill(processId, 0);
  5317. }
  5318. catch (ex) {
  5319. // Parent process doesn't exist anymore. Exit the server.
  5320. process.exit(shutdownReceived ? 0 : 1);
  5321. }
  5322. }, 3000);
  5323. }
  5324. }
  5325. catch (e) {
  5326. // Ignore errors;
  5327. }
  5328. }
  5329. for (let i = 2; i < process.argv.length; i++) {
  5330. let arg = process.argv[i];
  5331. if (arg === argName && i + 1 < process.argv.length) {
  5332. runTimer(process.argv[i + 1]);
  5333. return;
  5334. }
  5335. else {
  5336. let args = arg.split('=');
  5337. if (args[0] === argName) {
  5338. runTimer(args[1]);
  5339. }
  5340. }
  5341. }
  5342. }
  5343. setupExitTimer();
  5344. function null2Undefined(value) {
  5345. if (value === null) {
  5346. return void 0;
  5347. }
  5348. return value;
  5349. }
  5350. /**
  5351. * Incrementally-synchronized Text Document implementation that leverages a
  5352. * "Piece Tree" as text buffer. See the following for details:
  5353. * - https://github.com/microsoft/vscode-textbuffer
  5354. * - https://code.visualstudio.com/blogs/2018/03/23/text-buffer-reimplementation
  5355. *
  5356. * This text document implementation only supports "Incremental" text document
  5357. * sync. If you wish to use "Full" text document sync, use FullTextDocument, as it
  5358. * uses a simple JS string as an underlying text buffer, since the full text gets
  5359. * swapped out on every update.
  5360. */
  5361. class IncrementalTextDocument {
  5362. constructor(uri, languageId, version, content) {
  5363. this._uri = uri;
  5364. this._languageId = languageId;
  5365. this._version = version;
  5366. // Prepare Piece Tree
  5367. const ptBuilder = new vscode_textbuffer_1.PieceTreeTextBufferBuilder();
  5368. ptBuilder.acceptChunk(content);
  5369. const ptFactory = ptBuilder.finish(true);
  5370. this._tree = ptFactory.create(1 /* LF */);
  5371. }
  5372. get uri() {
  5373. return this._uri;
  5374. }
  5375. get languageId() {
  5376. return this._languageId;
  5377. }
  5378. get version() {
  5379. return this._version;
  5380. }
  5381. getText(range) {
  5382. if (range) {
  5383. const { start, end } = range;
  5384. // Clamp last line and last character appropriately when
  5385. // given range is beyond the document's end
  5386. const [clampedEndLine, clampedEndChar] = end.line + 1 > this.lineCount
  5387. ? [this.lineCount, this._tree.getLineLength(this.lineCount) + 1]
  5388. : [end.line + 1, end.character + 1];
  5389. const ptRange = new range_1.Range(start.line + 1, start.character + 1, clampedEndLine, clampedEndChar);
  5390. return this._tree.getValueInRange(ptRange);
  5391. }
  5392. return this._tree.getLinesRawContent();
  5393. }
  5394. update(event, version) {
  5395. const { text, range } = event;
  5396. if (range == null) {
  5397. throw new Error(`FullPieceTreeTextDocument#update called with invalid event range ${range}`);
  5398. }
  5399. const startOffset = this.offsetAt(range.start);
  5400. const endOffset = this.offsetAt(range.end);
  5401. // Delete previous text at range and insert new text at appropriate offset
  5402. this._tree.delete(startOffset, endOffset - startOffset);
  5403. this._tree.insert(startOffset, text);
  5404. this._version = version;
  5405. }
  5406. positionAt(offset) {
  5407. const clampedOffset = Math.min(offset, this._tree.getLength());
  5408. const ptPosition = this._tree.getPositionAt(clampedOffset);
  5409. return vscode_languageserver_protocol_1.Position.create(ptPosition.lineNumber - 1, ptPosition.column - 1);
  5410. }
  5411. offsetAt(position) {
  5412. if (position.line < 0) {
  5413. return 0;
  5414. }
  5415. const clampedChar = Math.max(1, position.character + 1);
  5416. return Math.min(this._tree.getOffsetAt(position.line + 1, clampedChar), this._tree.getLength());
  5417. }
  5418. get lineCount() {
  5419. return this._tree.getLineCount();
  5420. }
  5421. }
  5422. /**
  5423. * A manager for simple text documents
  5424. */
  5425. class TextDocuments {
  5426. /**
  5427. * Create a new text document manager.
  5428. */
  5429. constructor(syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) {
  5430. this._documents = Object.create(null);
  5431. this._syncKind = syncKind;
  5432. this._onDidChangeContent = new vscode_languageserver_protocol_1.Emitter();
  5433. this._onDidOpen = new vscode_languageserver_protocol_1.Emitter();
  5434. this._onDidClose = new vscode_languageserver_protocol_1.Emitter();
  5435. this._onDidSave = new vscode_languageserver_protocol_1.Emitter();
  5436. this._onWillSave = new vscode_languageserver_protocol_1.Emitter();
  5437. }
  5438. /**
  5439. * Returns the [TextDocumentSyncKind](#TextDocumentSyncKind) used by
  5440. * this text document manager.
  5441. */
  5442. get syncKind() {
  5443. return this._syncKind;
  5444. }
  5445. /**
  5446. * An event that fires when a text document managed by this manager
  5447. * has been opened or the content changes.
  5448. */
  5449. get onDidChangeContent() {
  5450. return this._onDidChangeContent.event;
  5451. }
  5452. /**
  5453. * An event that fires when a text document managed by this manager
  5454. * has been opened.
  5455. */
  5456. get onDidOpen() {
  5457. return this._onDidOpen.event;
  5458. }
  5459. /**
  5460. * An event that fires when a text document managed by this manager
  5461. * will be saved.
  5462. */
  5463. get onWillSave() {
  5464. return this._onWillSave.event;
  5465. }
  5466. /**
  5467. * Sets a handler that will be called if a participant wants to provide
  5468. * edits during a text document save.
  5469. */
  5470. onWillSaveWaitUntil(handler) {
  5471. this._willSaveWaitUntil = handler;
  5472. }
  5473. /**
  5474. * An event that fires when a text document managed by this manager
  5475. * has been saved.
  5476. */
  5477. get onDidSave() {
  5478. return this._onDidSave.event;
  5479. }
  5480. /**
  5481. * An event that fires when a text document managed by this manager
  5482. * has been closed.
  5483. */
  5484. get onDidClose() {
  5485. return this._onDidClose.event;
  5486. }
  5487. /**
  5488. * Returns the document for the given URI. Returns undefined if
  5489. * the document is not mananged by this instance.
  5490. *
  5491. * @param uri The text document's URI to retrieve.
  5492. * @return the text document or `undefined`.
  5493. */
  5494. get(uri) {
  5495. return this._documents[uri];
  5496. }
  5497. /**
  5498. * Returns all text documents managed by this instance.
  5499. *
  5500. * @return all text documents.
  5501. */
  5502. all() {
  5503. return Object.keys(this._documents).map(key => this._documents[key]);
  5504. }
  5505. /**
  5506. * Returns the URIs of all text documents managed by this instance.
  5507. *
  5508. * @return the URI's of all text documents.
  5509. */
  5510. keys() {
  5511. return Object.keys(this._documents);
  5512. }
  5513. /**
  5514. * Listens for `low level` notification on the given connection to
  5515. * update the text documents managed by this instance.
  5516. *
  5517. * @param connection The connection to listen on.
  5518. */
  5519. listen(connection) {
  5520. function isUpdateableDocument(value) {
  5521. return Is.func(value.update);
  5522. }
  5523. connection.__textDocumentSync = vscode_languageserver_protocol_1.TextDocumentSyncKind.Full;
  5524. connection.onDidOpenTextDocument((event) => {
  5525. let td = event.textDocument;
  5526. let document;
  5527. switch (this.syncKind) {
  5528. case vscode_languageserver_protocol_1.TextDocumentSyncKind.Full:
  5529. document = vscode_languageserver_protocol_1.TextDocument.create(td.uri, td.languageId, td.version, td.text);
  5530. break;
  5531. case vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental:
  5532. document = new IncrementalTextDocument(td.uri, td.languageId, td.version, td.text);
  5533. break;
  5534. default:
  5535. throw new Error(`Invalid TextDocumentSyncKind: ${this.syncKind}`);
  5536. }
  5537. this._documents[td.uri] = document;
  5538. let toFire = Object.freeze({ document });
  5539. this._onDidOpen.fire(toFire);
  5540. this._onDidChangeContent.fire(toFire);
  5541. });
  5542. connection.onDidChangeTextDocument((event) => {
  5543. let td = event.textDocument;
  5544. let changes = event.contentChanges;
  5545. if (changes.length === 0) {
  5546. return;
  5547. }
  5548. let document = this._documents[td.uri];
  5549. if (!document || !isUpdateableDocument(document)) {
  5550. return;
  5551. }
  5552. const { version } = td;
  5553. if (version == null || version === void 0) {
  5554. throw new Error(`Received document change event for ${td.uri} without valid version identifier`);
  5555. }
  5556. switch (this.syncKind) {
  5557. case vscode_languageserver_protocol_1.TextDocumentSyncKind.Full:
  5558. let last = changes[changes.length - 1];
  5559. document.update(last, version);
  5560. this._onDidChangeContent.fire(Object.freeze({ document }));
  5561. break;
  5562. case vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental:
  5563. let updatedDoc = changes.reduce((workingTextDoc, change) => {
  5564. workingTextDoc.update(change, version);
  5565. return workingTextDoc;
  5566. }, document);
  5567. this._onDidChangeContent.fire(Object.freeze({ document: updatedDoc }));
  5568. break;
  5569. case vscode_languageserver_protocol_1.TextDocumentSyncKind.None:
  5570. break;
  5571. }
  5572. });
  5573. connection.onDidCloseTextDocument((event) => {
  5574. let document = this._documents[event.textDocument.uri];
  5575. if (document) {
  5576. delete this._documents[event.textDocument.uri];
  5577. this._onDidClose.fire(Object.freeze({ document }));
  5578. }
  5579. });
  5580. connection.onWillSaveTextDocument((event) => {
  5581. let document = this._documents[event.textDocument.uri];
  5582. if (document) {
  5583. this._onWillSave.fire(Object.freeze({ document, reason: event.reason }));
  5584. }
  5585. });
  5586. connection.onWillSaveTextDocumentWaitUntil((event, token) => {
  5587. let document = this._documents[event.textDocument.uri];
  5588. if (document && this._willSaveWaitUntil) {
  5589. return this._willSaveWaitUntil(Object.freeze({ document, reason: event.reason }), token);
  5590. }
  5591. else {
  5592. return [];
  5593. }
  5594. });
  5595. connection.onDidSaveTextDocument((event) => {
  5596. let document = this._documents[event.textDocument.uri];
  5597. if (document) {
  5598. this._onDidSave.fire(Object.freeze({ document }));
  5599. }
  5600. });
  5601. }
  5602. }
  5603. exports.TextDocuments = TextDocuments;
  5604. /**
  5605. * Helps tracking error message. Equal occurences of the same
  5606. * message are only stored once. This class is for example
  5607. * useful if text documents are validated in a loop and equal
  5608. * error message should be folded into one.
  5609. */
  5610. class ErrorMessageTracker {
  5611. constructor() {
  5612. this._messages = Object.create(null);
  5613. }
  5614. /**
  5615. * Add a message to the tracker.
  5616. *
  5617. * @param message The message to add.
  5618. */
  5619. add(message) {
  5620. let count = this._messages[message];
  5621. if (!count) {
  5622. count = 0;
  5623. }
  5624. count++;
  5625. this._messages[message] = count;
  5626. }
  5627. /**
  5628. * Send all tracked messages to the connection's window.
  5629. *
  5630. * @param connection The connection established between client and server.
  5631. */
  5632. sendErrors(connection) {
  5633. Object.keys(this._messages).forEach(message => {
  5634. connection.window.showErrorMessage(message);
  5635. });
  5636. }
  5637. }
  5638. exports.ErrorMessageTracker = ErrorMessageTracker;
  5639. var BulkRegistration;
  5640. (function (BulkRegistration) {
  5641. /**
  5642. * Creates a new bulk registration.
  5643. * @return an empty bulk registration.
  5644. */
  5645. function create() {
  5646. return new BulkRegistrationImpl();
  5647. }
  5648. BulkRegistration.create = create;
  5649. })(BulkRegistration = exports.BulkRegistration || (exports.BulkRegistration = {}));
  5650. class BulkRegistrationImpl {
  5651. constructor() {
  5652. this._registrations = [];
  5653. this._registered = new Set();
  5654. }
  5655. add(type, registerOptions) {
  5656. const method = Is.string(type) ? type : type.method;
  5657. if (this._registered.has(method)) {
  5658. throw new Error(`${method} is already added to this registration`);
  5659. }
  5660. const id = UUID.generateUuid();
  5661. this._registrations.push({
  5662. id: id,
  5663. method: method,
  5664. registerOptions: registerOptions || {}
  5665. });
  5666. this._registered.add(method);
  5667. }
  5668. asRegistrationParams() {
  5669. return {
  5670. registrations: this._registrations
  5671. };
  5672. }
  5673. }
  5674. var BulkUnregistration;
  5675. (function (BulkUnregistration) {
  5676. function create() {
  5677. return new BulkUnregistrationImpl(undefined, []);
  5678. }
  5679. BulkUnregistration.create = create;
  5680. })(BulkUnregistration = exports.BulkUnregistration || (exports.BulkUnregistration = {}));
  5681. class BulkUnregistrationImpl {
  5682. constructor(_connection, unregistrations) {
  5683. this._connection = _connection;
  5684. this._unregistrations = new Map();
  5685. unregistrations.forEach(unregistration => {
  5686. this._unregistrations.set(unregistration.method, unregistration);
  5687. });
  5688. }
  5689. get isAttached() {
  5690. return !!this._connection;
  5691. }
  5692. attach(connection) {
  5693. this._connection = connection;
  5694. }
  5695. add(unregistration) {
  5696. this._unregistrations.set(unregistration.method, unregistration);
  5697. }
  5698. dispose() {
  5699. let unregistrations = [];
  5700. for (let unregistration of this._unregistrations.values()) {
  5701. unregistrations.push(unregistration);
  5702. }
  5703. let params = {
  5704. unregisterations: unregistrations
  5705. };
  5706. this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(undefined, (_error) => {
  5707. this._connection.console.info(`Bulk unregistration failed.`);
  5708. });
  5709. }
  5710. disposeSingle(arg) {
  5711. const method = Is.string(arg) ? arg : arg.method;
  5712. const unregistration = this._unregistrations.get(method);
  5713. if (!unregistration) {
  5714. return false;
  5715. }
  5716. let params = {
  5717. unregisterations: [unregistration]
  5718. };
  5719. this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(() => {
  5720. this._unregistrations.delete(method);
  5721. }, (_error) => {
  5722. this._connection.console.info(`Unregistering request handler for ${unregistration.id} failed.`);
  5723. });
  5724. return true;
  5725. }
  5726. }
  5727. class ConnectionLogger {
  5728. constructor() {
  5729. }
  5730. rawAttach(connection) {
  5731. this._rawConnection = connection;
  5732. }
  5733. attach(connection) {
  5734. this._connection = connection;
  5735. }
  5736. get connection() {
  5737. if (!this._connection) {
  5738. throw new Error('Remote is not attached to a connection yet.');
  5739. }
  5740. return this._connection;
  5741. }
  5742. fillServerCapabilities(_capabilities) {
  5743. }
  5744. initialize(_capabilities) {
  5745. }
  5746. error(message) {
  5747. this.send(vscode_languageserver_protocol_1.MessageType.Error, message);
  5748. }
  5749. warn(message) {
  5750. this.send(vscode_languageserver_protocol_1.MessageType.Warning, message);
  5751. }
  5752. info(message) {
  5753. this.send(vscode_languageserver_protocol_1.MessageType.Info, message);
  5754. }
  5755. log(message) {
  5756. this.send(vscode_languageserver_protocol_1.MessageType.Log, message);
  5757. }
  5758. send(type, message) {
  5759. if (this._rawConnection) {
  5760. this._rawConnection.sendNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, { type, message });
  5761. }
  5762. }
  5763. }
  5764. class RemoteWindowImpl {
  5765. constructor() {
  5766. }
  5767. attach(connection) {
  5768. this._connection = connection;
  5769. }
  5770. get connection() {
  5771. if (!this._connection) {
  5772. throw new Error('Remote is not attached to a connection yet.');
  5773. }
  5774. return this._connection;
  5775. }
  5776. initialize(_capabilities) {
  5777. }
  5778. fillServerCapabilities(_capabilities) {
  5779. }
  5780. showErrorMessage(message, ...actions) {
  5781. let params = { type: vscode_languageserver_protocol_1.MessageType.Error, message, actions };
  5782. return this._connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
  5783. }
  5784. showWarningMessage(message, ...actions) {
  5785. let params = { type: vscode_languageserver_protocol_1.MessageType.Warning, message, actions };
  5786. return this._connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
  5787. }
  5788. showInformationMessage(message, ...actions) {
  5789. let params = { type: vscode_languageserver_protocol_1.MessageType.Info, message, actions };
  5790. return this._connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
  5791. }
  5792. }
  5793. class RemoteClientImpl {
  5794. attach(connection) {
  5795. this._connection = connection;
  5796. }
  5797. get connection() {
  5798. if (!this._connection) {
  5799. throw new Error('Remote is not attached to a connection yet.');
  5800. }
  5801. return this._connection;
  5802. }
  5803. initialize(_capabilities) {
  5804. }
  5805. fillServerCapabilities(_capabilities) {
  5806. }
  5807. register(typeOrRegistrations, registerOptionsOrType, registerOptions) {
  5808. if (typeOrRegistrations instanceof BulkRegistrationImpl) {
  5809. return this.registerMany(typeOrRegistrations);
  5810. }
  5811. else if (typeOrRegistrations instanceof BulkUnregistrationImpl) {
  5812. return this.registerSingle1(typeOrRegistrations, registerOptionsOrType, registerOptions);
  5813. }
  5814. else {
  5815. return this.registerSingle2(typeOrRegistrations, registerOptionsOrType);
  5816. }
  5817. }
  5818. registerSingle1(unregistration, type, registerOptions) {
  5819. const method = Is.string(type) ? type : type.method;
  5820. const id = UUID.generateUuid();
  5821. let params = {
  5822. registrations: [{ id, method, registerOptions: registerOptions || {} }]
  5823. };
  5824. if (!unregistration.isAttached) {
  5825. unregistration.attach(this._connection);
  5826. }
  5827. return this._connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {
  5828. unregistration.add({ id: id, method: method });
  5829. return unregistration;
  5830. }, (_error) => {
  5831. this.connection.console.info(`Registering request handler for ${method} failed.`);
  5832. return Promise.reject(_error);
  5833. });
  5834. }
  5835. registerSingle2(type, registerOptions) {
  5836. const method = Is.string(type) ? type : type.method;
  5837. const id = UUID.generateUuid();
  5838. let params = {
  5839. registrations: [{ id, method, registerOptions: registerOptions || {} }]
  5840. };
  5841. return this._connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {
  5842. return vscode_languageserver_protocol_1.Disposable.create(() => {
  5843. this.unregisterSingle(id, method);
  5844. });
  5845. }, (_error) => {
  5846. this.connection.console.info(`Registering request handler for ${method} failed.`);
  5847. return Promise.reject(_error);
  5848. });
  5849. }
  5850. unregisterSingle(id, method) {
  5851. let params = {
  5852. unregisterations: [{ id, method }]
  5853. };
  5854. return this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(undefined, (_error) => {
  5855. this.connection.console.info(`Unregistering request handler for ${id} failed.`);
  5856. });
  5857. }
  5858. registerMany(registrations) {
  5859. let params = registrations.asRegistrationParams();
  5860. return this._connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then(() => {
  5861. return new BulkUnregistrationImpl(this._connection, params.registrations.map(registration => { return { id: registration.id, method: registration.method }; }));
  5862. }, (_error) => {
  5863. this.connection.console.info(`Bulk registration failed.`);
  5864. return Promise.reject(_error);
  5865. });
  5866. }
  5867. }
  5868. class _RemoteWorkspaceImpl {
  5869. constructor() {
  5870. }
  5871. attach(connection) {
  5872. this._connection = connection;
  5873. }
  5874. get connection() {
  5875. if (!this._connection) {
  5876. throw new Error('Remote is not attached to a connection yet.');
  5877. }
  5878. return this._connection;
  5879. }
  5880. initialize(_capabilities) {
  5881. }
  5882. fillServerCapabilities(_capabilities) {
  5883. }
  5884. applyEdit(paramOrEdit) {
  5885. function isApplyWorkspaceEditParams(value) {
  5886. return value && !!value.edit;
  5887. }
  5888. let params = isApplyWorkspaceEditParams(paramOrEdit) ? paramOrEdit : { edit: paramOrEdit };
  5889. return this._connection.sendRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, params);
  5890. }
  5891. }
  5892. const RemoteWorkspaceImpl = workspaceFolders_1.WorkspaceFoldersFeature(configuration_1.ConfigurationFeature(_RemoteWorkspaceImpl));
  5893. class TracerImpl {
  5894. constructor() {
  5895. this._trace = vscode_languageserver_protocol_1.Trace.Off;
  5896. }
  5897. attach(connection) {
  5898. this._connection = connection;
  5899. }
  5900. get connection() {
  5901. if (!this._connection) {
  5902. throw new Error('Remote is not attached to a connection yet.');
  5903. }
  5904. return this._connection;
  5905. }
  5906. initialize(_capabilities) {
  5907. }
  5908. fillServerCapabilities(_capabilities) {
  5909. }
  5910. set trace(value) {
  5911. this._trace = value;
  5912. }
  5913. log(message, verbose) {
  5914. if (this._trace === vscode_languageserver_protocol_1.Trace.Off) {
  5915. return;
  5916. }
  5917. this._connection.sendNotification(vscode_languageserver_protocol_1.LogTraceNotification.type, {
  5918. message: message,
  5919. verbose: this._trace === vscode_languageserver_protocol_1.Trace.Verbose ? verbose : undefined
  5920. });
  5921. }
  5922. }
  5923. class TelemetryImpl {
  5924. constructor() {
  5925. }
  5926. attach(connection) {
  5927. this._connection = connection;
  5928. }
  5929. get connection() {
  5930. if (!this._connection) {
  5931. throw new Error('Remote is not attached to a connection yet.');
  5932. }
  5933. return this._connection;
  5934. }
  5935. initialize(_capabilities) {
  5936. }
  5937. fillServerCapabilities(_capabilities) {
  5938. }
  5939. logEvent(data) {
  5940. this._connection.sendNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, data);
  5941. }
  5942. }
  5943. function combineConsoleFeatures(one, two) {
  5944. return function (Base) {
  5945. return two(one(Base));
  5946. };
  5947. }
  5948. exports.combineConsoleFeatures = combineConsoleFeatures;
  5949. function combineTelemetryFeatures(one, two) {
  5950. return function (Base) {
  5951. return two(one(Base));
  5952. };
  5953. }
  5954. exports.combineTelemetryFeatures = combineTelemetryFeatures;
  5955. function combineTracerFeatures(one, two) {
  5956. return function (Base) {
  5957. return two(one(Base));
  5958. };
  5959. }
  5960. exports.combineTracerFeatures = combineTracerFeatures;
  5961. function combineClientFeatures(one, two) {
  5962. return function (Base) {
  5963. return two(one(Base));
  5964. };
  5965. }
  5966. exports.combineClientFeatures = combineClientFeatures;
  5967. function combineWindowFeatures(one, two) {
  5968. return function (Base) {
  5969. return two(one(Base));
  5970. };
  5971. }
  5972. exports.combineWindowFeatures = combineWindowFeatures;
  5973. function combineWorkspaceFeatures(one, two) {
  5974. return function (Base) {
  5975. return two(one(Base));
  5976. };
  5977. }
  5978. exports.combineWorkspaceFeatures = combineWorkspaceFeatures;
  5979. function combineFeatures(one, two) {
  5980. function combine(one, two, func) {
  5981. if (one && two) {
  5982. return func(one, two);
  5983. }
  5984. else if (one) {
  5985. return one;
  5986. }
  5987. else {
  5988. return two;
  5989. }
  5990. }
  5991. let result = {
  5992. __brand: 'features',
  5993. console: combine(one.console, two.console, combineConsoleFeatures),
  5994. tracer: combine(one.tracer, two.tracer, combineTracerFeatures),
  5995. telemetry: combine(one.telemetry, two.telemetry, combineTelemetryFeatures),
  5996. client: combine(one.client, two.client, combineClientFeatures),
  5997. window: combine(one.window, two.window, combineWindowFeatures),
  5998. workspace: combine(one.workspace, two.workspace, combineWorkspaceFeatures)
  5999. };
  6000. return result;
  6001. }
  6002. exports.combineFeatures = combineFeatures;
  6003. function createConnection(arg1, arg2, arg3, arg4) {
  6004. let factories;
  6005. let input;
  6006. let output;
  6007. let strategy;
  6008. if (arg1 !== void 0 && arg1.__brand === 'features') {
  6009. factories = arg1;
  6010. arg1 = arg2;
  6011. arg2 = arg3;
  6012. arg3 = arg4;
  6013. }
  6014. if (vscode_languageserver_protocol_1.ConnectionStrategy.is(arg1)) {
  6015. strategy = arg1;
  6016. }
  6017. else {
  6018. input = arg1;
  6019. output = arg2;
  6020. strategy = arg3;
  6021. }
  6022. return _createConnection(input, output, strategy, factories);
  6023. }
  6024. exports.createConnection = createConnection;
  6025. function _createConnection(input, output, strategy, factories) {
  6026. if (!input && !output && process.argv.length > 2) {
  6027. let port = void 0;
  6028. let pipeName = void 0;
  6029. let argv = process.argv.slice(2);
  6030. for (let i = 0; i < argv.length; i++) {
  6031. let arg = argv[i];
  6032. if (arg === '--node-ipc') {
  6033. input = new vscode_languageserver_protocol_1.IPCMessageReader(process);
  6034. output = new vscode_languageserver_protocol_1.IPCMessageWriter(process);
  6035. break;
  6036. }
  6037. else if (arg === '--stdio') {
  6038. input = process.stdin;
  6039. output = process.stdout;
  6040. break;
  6041. }
  6042. else if (arg === '--socket') {
  6043. port = parseInt(argv[i + 1]);
  6044. break;
  6045. }
  6046. else if (arg === '--pipe') {
  6047. pipeName = argv[i + 1];
  6048. break;
  6049. }
  6050. else {
  6051. var args = arg.split('=');
  6052. if (args[0] === '--socket') {
  6053. port = parseInt(args[1]);
  6054. break;
  6055. }
  6056. else if (args[0] === '--pipe') {
  6057. pipeName = args[1];
  6058. break;
  6059. }
  6060. }
  6061. }
  6062. if (port) {
  6063. let transport = vscode_languageserver_protocol_1.createServerSocketTransport(port);
  6064. input = transport[0];
  6065. output = transport[1];
  6066. }
  6067. else if (pipeName) {
  6068. let transport = vscode_languageserver_protocol_1.createServerPipeTransport(pipeName);
  6069. input = transport[0];
  6070. output = transport[1];
  6071. }
  6072. }
  6073. var commandLineMessage = "Use arguments of createConnection or set command line parameters: '--node-ipc', '--stdio' or '--socket={number}'";
  6074. if (!input) {
  6075. throw new Error("Connection input stream is not set. " + commandLineMessage);
  6076. }
  6077. if (!output) {
  6078. throw new Error("Connection output stream is not set. " + commandLineMessage);
  6079. }
  6080. // Backwards compatibility
  6081. if (Is.func(input.read) && Is.func(input.on)) {
  6082. let inputStream = input;
  6083. inputStream.on('end', () => {
  6084. process.exit(shutdownReceived ? 0 : 1);
  6085. });
  6086. inputStream.on('close', () => {
  6087. process.exit(shutdownReceived ? 0 : 1);
  6088. });
  6089. }
  6090. const logger = (factories && factories.console ? new (factories.console(ConnectionLogger))() : new ConnectionLogger());
  6091. const connection = vscode_languageserver_protocol_1.createProtocolConnection(input, output, logger, strategy);
  6092. logger.rawAttach(connection);
  6093. const tracer = (factories && factories.tracer ? new (factories.tracer(TracerImpl))() : new TracerImpl());
  6094. const telemetry = (factories && factories.telemetry ? new (factories.telemetry(TelemetryImpl))() : new TelemetryImpl());
  6095. const client = (factories && factories.client ? new (factories.client(RemoteClientImpl))() : new RemoteClientImpl());
  6096. const remoteWindow = (factories && factories.window ? new (factories.window(RemoteWindowImpl))() : new RemoteWindowImpl());
  6097. const workspace = (factories && factories.workspace ? new (factories.workspace(RemoteWorkspaceImpl))() : new RemoteWorkspaceImpl());
  6098. const allRemotes = [logger, tracer, telemetry, client, remoteWindow, workspace];
  6099. function asThenable(value) {
  6100. if (Is.thenable(value)) {
  6101. return value;
  6102. }
  6103. else {
  6104. return Promise.resolve(value);
  6105. }
  6106. }
  6107. let shutdownHandler = undefined;
  6108. let initializeHandler = undefined;
  6109. let exitHandler = undefined;
  6110. let protocolConnection = {
  6111. listen: () => connection.listen(),
  6112. sendRequest: (type, ...params) => connection.sendRequest(Is.string(type) ? type : type.method, ...params),
  6113. onRequest: (type, handler) => connection.onRequest(type, handler),
  6114. sendNotification: (type, param) => {
  6115. const method = Is.string(type) ? type : type.method;
  6116. if (arguments.length === 1) {
  6117. connection.sendNotification(method);
  6118. }
  6119. else {
  6120. connection.sendNotification(method, param);
  6121. }
  6122. },
  6123. onNotification: (type, handler) => connection.onNotification(type, handler),
  6124. onInitialize: (handler) => initializeHandler = handler,
  6125. onInitialized: (handler) => connection.onNotification(vscode_languageserver_protocol_1.InitializedNotification.type, handler),
  6126. onShutdown: (handler) => shutdownHandler = handler,
  6127. onExit: (handler) => exitHandler = handler,
  6128. get console() { return logger; },
  6129. get telemetry() { return telemetry; },
  6130. get tracer() { return tracer; },
  6131. get client() { return client; },
  6132. get window() { return remoteWindow; },
  6133. get workspace() { return workspace; },
  6134. onDidChangeConfiguration: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, handler),
  6135. onDidChangeWatchedFiles: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, handler),
  6136. __textDocumentSync: undefined,
  6137. onDidOpenTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, handler),
  6138. onDidChangeTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, handler),
  6139. onDidCloseTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, handler),
  6140. onWillSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, handler),
  6141. onWillSaveTextDocumentWaitUntil: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, handler),
  6142. onDidSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, handler),
  6143. sendDiagnostics: (params) => connection.sendNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, params),
  6144. onHover: (handler) => connection.onRequest(vscode_languageserver_protocol_1.HoverRequest.type, handler),
  6145. onCompletion: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionRequest.type, handler),
  6146. onCompletionResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, handler),
  6147. onSignatureHelp: (handler) => connection.onRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, handler),
  6148. onDeclaration: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, handler),
  6149. onDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, handler),
  6150. onTypeDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, handler),
  6151. onImplementation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, handler),
  6152. onReferences: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, handler),
  6153. onDocumentHighlight: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, handler),
  6154. onDocumentSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, handler),
  6155. onWorkspaceSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, handler),
  6156. onCodeAction: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, handler),
  6157. onCodeLens: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, handler),
  6158. onCodeLensResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, handler),
  6159. onDocumentFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, handler),
  6160. onDocumentRangeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, handler),
  6161. onDocumentOnTypeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, handler),
  6162. onRenameRequest: (handler) => connection.onRequest(vscode_languageserver_protocol_1.RenameRequest.type, handler),
  6163. onPrepareRename: (handler) => connection.onRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, handler),
  6164. onDocumentLinks: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, handler),
  6165. onDocumentLinkResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, handler),
  6166. onDocumentColor: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, handler),
  6167. onColorPresentation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, handler),
  6168. onFoldingRanges: (handler) => connection.onRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, handler),
  6169. onExecuteCommand: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, handler),
  6170. dispose: () => connection.dispose()
  6171. };
  6172. for (let remote of allRemotes) {
  6173. remote.attach(protocolConnection);
  6174. }
  6175. connection.onRequest(vscode_languageserver_protocol_1.InitializeRequest.type, (params) => {
  6176. const processId = params.processId;
  6177. if (Is.number(processId) && exitTimer === void 0) {
  6178. // We received a parent process id. Set up a timer to periodically check
  6179. // if the parent is still alive.
  6180. setInterval(() => {
  6181. try {
  6182. process.kill(processId, 0);
  6183. }
  6184. catch (ex) {
  6185. // Parent process doesn't exist anymore. Exit the server.
  6186. process.exit(shutdownReceived ? 0 : 1);
  6187. }
  6188. }, 3000);
  6189. }
  6190. if (Is.string(params.trace)) {
  6191. tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.trace);
  6192. }
  6193. for (let remote of allRemotes) {
  6194. remote.initialize(params.capabilities);
  6195. }
  6196. if (initializeHandler) {
  6197. let result = initializeHandler(params, new vscode_languageserver_protocol_1.CancellationTokenSource().token);
  6198. return asThenable(result).then((value) => {
  6199. if (value instanceof vscode_languageserver_protocol_1.ResponseError) {
  6200. return value;
  6201. }
  6202. let result = value;
  6203. if (!result) {
  6204. result = { capabilities: {} };
  6205. }
  6206. let capabilities = result.capabilities;
  6207. if (!capabilities) {
  6208. capabilities = {};
  6209. result.capabilities = capabilities;
  6210. }
  6211. if (capabilities.textDocumentSync === void 0 || capabilities.textDocumentSync === null) {
  6212. capabilities.textDocumentSync = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
  6213. }
  6214. else if (!Is.number(capabilities.textDocumentSync) && !Is.number(capabilities.textDocumentSync.change)) {
  6215. capabilities.textDocumentSync.change = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
  6216. }
  6217. for (let remote of allRemotes) {
  6218. remote.fillServerCapabilities(capabilities);
  6219. }
  6220. return result;
  6221. });
  6222. }
  6223. else {
  6224. let result = { capabilities: { textDocumentSync: vscode_languageserver_protocol_1.TextDocumentSyncKind.None } };
  6225. for (let remote of allRemotes) {
  6226. remote.fillServerCapabilities(result.capabilities);
  6227. }
  6228. return result;
  6229. }
  6230. });
  6231. connection.onRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, () => {
  6232. shutdownReceived = true;
  6233. if (shutdownHandler) {
  6234. return shutdownHandler(new vscode_languageserver_protocol_1.CancellationTokenSource().token);
  6235. }
  6236. else {
  6237. return undefined;
  6238. }
  6239. });
  6240. connection.onNotification(vscode_languageserver_protocol_1.ExitNotification.type, () => {
  6241. try {
  6242. if (exitHandler) {
  6243. exitHandler();
  6244. }
  6245. }
  6246. finally {
  6247. if (shutdownReceived) {
  6248. process.exit(0);
  6249. }
  6250. else {
  6251. process.exit(1);
  6252. }
  6253. }
  6254. });
  6255. connection.onNotification(vscode_languageserver_protocol_1.SetTraceNotification.type, (params) => {
  6256. tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.value);
  6257. });
  6258. return protocolConnection;
  6259. }
  6260. // Export the protocol currently in proposed state.
  6261. const proposed_progress_1 = __webpack_require__(48);
  6262. var ProposedFeatures;
  6263. (function (ProposedFeatures) {
  6264. ProposedFeatures.all = {
  6265. __brand: 'features',
  6266. window: proposed_progress_1.ProgressFeature
  6267. };
  6268. })(ProposedFeatures = exports.ProposedFeatures || (exports.ProposedFeatures = {}));
  6269. /***/ }),
  6270. /* 35 */
  6271. /***/ (function(module, exports, __webpack_require__) {
  6272. "use strict";
  6273. /* --------------------------------------------------------------------------------------------
  6274. * Copyright (c) Microsoft Corporation. All rights reserved.
  6275. * Licensed under the MIT License. See License.txt in the project root for license information.
  6276. * ------------------------------------------------------------------------------------------ */
  6277. Object.defineProperty(exports, "__esModule", { value: true });
  6278. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  6279. const Is = __webpack_require__(36);
  6280. exports.ConfigurationFeature = (Base) => {
  6281. return class extends Base {
  6282. getConfiguration(arg) {
  6283. if (!arg) {
  6284. return this._getConfiguration({});
  6285. }
  6286. else if (Is.string(arg)) {
  6287. return this._getConfiguration({ section: arg });
  6288. }
  6289. else {
  6290. return this._getConfiguration(arg);
  6291. }
  6292. }
  6293. _getConfiguration(arg) {
  6294. let params = {
  6295. items: Array.isArray(arg) ? arg : [arg]
  6296. };
  6297. return this.connection.sendRequest(vscode_languageserver_protocol_1.ConfigurationRequest.type, params).then((result) => {
  6298. return Array.isArray(arg) ? result : result[0];
  6299. });
  6300. }
  6301. };
  6302. };
  6303. /***/ }),
  6304. /* 36 */
  6305. /***/ (function(module, exports, __webpack_require__) {
  6306. "use strict";
  6307. /* --------------------------------------------------------------------------------------------
  6308. * Copyright (c) Microsoft Corporation. All rights reserved.
  6309. * Licensed under the MIT License. See License.txt in the project root for license information.
  6310. * ------------------------------------------------------------------------------------------ */
  6311. Object.defineProperty(exports, "__esModule", { value: true });
  6312. function boolean(value) {
  6313. return value === true || value === false;
  6314. }
  6315. exports.boolean = boolean;
  6316. function string(value) {
  6317. return typeof value === 'string' || value instanceof String;
  6318. }
  6319. exports.string = string;
  6320. function number(value) {
  6321. return typeof value === 'number' || value instanceof Number;
  6322. }
  6323. exports.number = number;
  6324. function error(value) {
  6325. return value instanceof Error;
  6326. }
  6327. exports.error = error;
  6328. function func(value) {
  6329. return typeof value === 'function';
  6330. }
  6331. exports.func = func;
  6332. function array(value) {
  6333. return Array.isArray(value);
  6334. }
  6335. exports.array = array;
  6336. function stringArray(value) {
  6337. return array(value) && value.every(elem => string(elem));
  6338. }
  6339. exports.stringArray = stringArray;
  6340. function typedArray(value, check) {
  6341. return Array.isArray(value) && value.every(check);
  6342. }
  6343. exports.typedArray = typedArray;
  6344. function thenable(value) {
  6345. return value && func(value.then);
  6346. }
  6347. exports.thenable = thenable;
  6348. /***/ }),
  6349. /* 37 */
  6350. /***/ (function(module, exports, __webpack_require__) {
  6351. "use strict";
  6352. /* --------------------------------------------------------------------------------------------
  6353. * Copyright (c) Microsoft Corporation. All rights reserved.
  6354. * Licensed under the MIT License. See License.txt in the project root for license information.
  6355. * ------------------------------------------------------------------------------------------ */
  6356. Object.defineProperty(exports, "__esModule", { value: true });
  6357. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  6358. exports.WorkspaceFoldersFeature = (Base) => {
  6359. return class extends Base {
  6360. initialize(capabilities) {
  6361. let workspaceCapabilities = capabilities.workspace;
  6362. if (workspaceCapabilities && workspaceCapabilities.workspaceFolders) {
  6363. this._onDidChangeWorkspaceFolders = new vscode_languageserver_protocol_1.Emitter();
  6364. this.connection.onNotification(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type, (params) => {
  6365. this._onDidChangeWorkspaceFolders.fire(params.event);
  6366. });
  6367. }
  6368. }
  6369. getWorkspaceFolders() {
  6370. return this.connection.sendRequest(vscode_languageserver_protocol_1.WorkspaceFoldersRequest.type);
  6371. }
  6372. get onDidChangeWorkspaceFolders() {
  6373. if (!this._onDidChangeWorkspaceFolders) {
  6374. throw new Error('Client doesn\'t support sending workspace folder change events.');
  6375. }
  6376. if (!this._unregistration) {
  6377. this._unregistration = this.connection.client.register(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type);
  6378. }
  6379. return this._onDidChangeWorkspaceFolders.event;
  6380. }
  6381. };
  6382. };
  6383. /***/ }),
  6384. /* 38 */
  6385. /***/ (function(module, exports, __webpack_require__) {
  6386. "use strict";
  6387. /*---------------------------------------------------------------------------------------------
  6388. * Copyright (c) Microsoft Corporation. All rights reserved.
  6389. * Licensed under the MIT License. See License.txt in the project root for license information.
  6390. *--------------------------------------------------------------------------------------------*/
  6391. Object.defineProperty(exports, "__esModule", { value: true });
  6392. class ValueUUID {
  6393. constructor(_value) {
  6394. this._value = _value;
  6395. // empty
  6396. }
  6397. asHex() {
  6398. return this._value;
  6399. }
  6400. equals(other) {
  6401. return this.asHex() === other.asHex();
  6402. }
  6403. }
  6404. class V4UUID extends ValueUUID {
  6405. constructor() {
  6406. super([
  6407. V4UUID._randomHex(),
  6408. V4UUID._randomHex(),
  6409. V4UUID._randomHex(),
  6410. V4UUID._randomHex(),
  6411. V4UUID._randomHex(),
  6412. V4UUID._randomHex(),
  6413. V4UUID._randomHex(),
  6414. V4UUID._randomHex(),
  6415. '-',
  6416. V4UUID._randomHex(),
  6417. V4UUID._randomHex(),
  6418. V4UUID._randomHex(),
  6419. V4UUID._randomHex(),
  6420. '-',
  6421. '4',
  6422. V4UUID._randomHex(),
  6423. V4UUID._randomHex(),
  6424. V4UUID._randomHex(),
  6425. '-',
  6426. V4UUID._oneOf(V4UUID._timeHighBits),
  6427. V4UUID._randomHex(),
  6428. V4UUID._randomHex(),
  6429. V4UUID._randomHex(),
  6430. '-',
  6431. V4UUID._randomHex(),
  6432. V4UUID._randomHex(),
  6433. V4UUID._randomHex(),
  6434. V4UUID._randomHex(),
  6435. V4UUID._randomHex(),
  6436. V4UUID._randomHex(),
  6437. V4UUID._randomHex(),
  6438. V4UUID._randomHex(),
  6439. V4UUID._randomHex(),
  6440. V4UUID._randomHex(),
  6441. V4UUID._randomHex(),
  6442. V4UUID._randomHex(),
  6443. ].join(''));
  6444. }
  6445. static _oneOf(array) {
  6446. return array[Math.floor(array.length * Math.random())];
  6447. }
  6448. static _randomHex() {
  6449. return V4UUID._oneOf(V4UUID._chars);
  6450. }
  6451. }
  6452. V4UUID._chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
  6453. V4UUID._timeHighBits = ['8', '9', 'a', 'b'];
  6454. /**
  6455. * An empty UUID that contains only zeros.
  6456. */
  6457. exports.empty = new ValueUUID('00000000-0000-0000-0000-000000000000');
  6458. function v4() {
  6459. return new V4UUID();
  6460. }
  6461. exports.v4 = v4;
  6462. const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
  6463. function isUUID(value) {
  6464. return _UUIDPattern.test(value);
  6465. }
  6466. exports.isUUID = isUUID;
  6467. /**
  6468. * Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
  6469. * @param value A uuid string.
  6470. */
  6471. function parse(value) {
  6472. if (!isUUID(value)) {
  6473. throw new Error('invalid uuid');
  6474. }
  6475. return new ValueUUID(value);
  6476. }
  6477. exports.parse = parse;
  6478. function generateUuid() {
  6479. return v4().asHex();
  6480. }
  6481. exports.generateUuid = generateUuid;
  6482. /***/ }),
  6483. /* 39 */
  6484. /***/ (function(module, exports, __webpack_require__) {
  6485. "use strict";
  6486. /* WEBPACK VAR INJECTION */(function(__filename) {/* --------------------------------------------------------------------------------------------
  6487. * Copyright (c) Microsoft Corporation. All rights reserved.
  6488. * Licensed under the MIT License. See License.txt in the project root for license information.
  6489. * ------------------------------------------------------------------------------------------ */
  6490. Object.defineProperty(exports, "__esModule", { value: true });
  6491. const url = __webpack_require__(40);
  6492. const path = __webpack_require__(1);
  6493. const fs = __webpack_require__(2);
  6494. const child_process_1 = __webpack_require__(41);
  6495. /**
  6496. * @deprecated Use the `vscode-uri` npm module which provides a more
  6497. * complete implementation of handling VS Code URIs.
  6498. */
  6499. function uriToFilePath(uri) {
  6500. let parsed = url.parse(uri);
  6501. if (parsed.protocol !== 'file:' || !parsed.path) {
  6502. return undefined;
  6503. }
  6504. let segments = parsed.path.split('/');
  6505. for (var i = 0, len = segments.length; i < len; i++) {
  6506. segments[i] = decodeURIComponent(segments[i]);
  6507. }
  6508. if (process.platform === 'win32' && segments.length > 1) {
  6509. let first = segments[0];
  6510. let second = segments[1];
  6511. // Do we have a drive letter and we started with a / which is the
  6512. // case if the first segement is empty (see split above)
  6513. if (first.length === 0 && second.length > 1 && second[1] === ':') {
  6514. // Remove first slash
  6515. segments.shift();
  6516. }
  6517. }
  6518. return path.normalize(segments.join('/'));
  6519. }
  6520. exports.uriToFilePath = uriToFilePath;
  6521. function isWindows() {
  6522. return process.platform === 'win32';
  6523. }
  6524. function resolve(moduleName, nodePath, cwd, tracer) {
  6525. const nodePathKey = 'NODE_PATH';
  6526. const app = [
  6527. "var p = process;",
  6528. "p.on('message',function(m){",
  6529. "if(m.c==='e'){",
  6530. "p.exit(0);",
  6531. "}",
  6532. "else if(m.c==='rs'){",
  6533. "try{",
  6534. "var r=require.resolve(m.a);",
  6535. "p.send({c:'r',s:true,r:r});",
  6536. "}",
  6537. "catch(err){",
  6538. "p.send({c:'r',s:false});",
  6539. "}",
  6540. "}",
  6541. "});"
  6542. ].join('');
  6543. return new Promise((resolve, reject) => {
  6544. let env = process.env;
  6545. let newEnv = Object.create(null);
  6546. Object.keys(env).forEach(key => newEnv[key] = env[key]);
  6547. if (nodePath) {
  6548. if (newEnv[nodePathKey]) {
  6549. newEnv[nodePathKey] = nodePath + path.delimiter + newEnv[nodePathKey];
  6550. }
  6551. else {
  6552. newEnv[nodePathKey] = nodePath;
  6553. }
  6554. if (tracer) {
  6555. tracer(`NODE_PATH value is: ${newEnv[nodePathKey]}`);
  6556. }
  6557. }
  6558. newEnv['ELECTRON_RUN_AS_NODE'] = '1';
  6559. try {
  6560. let cp = child_process_1.fork('', [], {
  6561. cwd: cwd,
  6562. env: newEnv,
  6563. execArgv: ['-e', app]
  6564. });
  6565. if (cp.pid === void 0) {
  6566. reject(new Error(`Starting process to resolve node module ${moduleName} failed`));
  6567. return;
  6568. }
  6569. cp.on('error', (error) => {
  6570. reject(error);
  6571. });
  6572. cp.on('message', (message) => {
  6573. if (message.c === 'r') {
  6574. cp.send({ c: 'e' });
  6575. if (message.s) {
  6576. resolve(message.r);
  6577. }
  6578. else {
  6579. reject(new Error(`Failed to resolve module: ${moduleName}`));
  6580. }
  6581. }
  6582. });
  6583. let message = {
  6584. c: 'rs',
  6585. a: moduleName
  6586. };
  6587. cp.send(message);
  6588. }
  6589. catch (error) {
  6590. reject(error);
  6591. }
  6592. });
  6593. }
  6594. exports.resolve = resolve;
  6595. function resolveGlobalNodePath(tracer) {
  6596. let npmCommand = 'npm';
  6597. let options = {
  6598. encoding: 'utf8'
  6599. };
  6600. if (isWindows()) {
  6601. npmCommand = 'npm.cmd';
  6602. options.shell = true;
  6603. }
  6604. let handler = () => { };
  6605. try {
  6606. process.on('SIGPIPE', handler);
  6607. let stdout = child_process_1.spawnSync(npmCommand, ['config', 'get', 'prefix'], options).stdout;
  6608. if (!stdout) {
  6609. if (tracer) {
  6610. tracer(`'npm config get prefix' didn't return a value.`);
  6611. }
  6612. return undefined;
  6613. }
  6614. let prefix = stdout.trim();
  6615. if (tracer) {
  6616. tracer(`'npm config get prefix' value is: ${prefix}`);
  6617. }
  6618. if (prefix.length > 0) {
  6619. if (isWindows()) {
  6620. return path.join(prefix, 'node_modules');
  6621. }
  6622. else {
  6623. return path.join(prefix, 'lib', 'node_modules');
  6624. }
  6625. }
  6626. return undefined;
  6627. }
  6628. catch (err) {
  6629. return undefined;
  6630. }
  6631. finally {
  6632. process.removeListener('SIGPIPE', handler);
  6633. }
  6634. }
  6635. exports.resolveGlobalNodePath = resolveGlobalNodePath;
  6636. function resolveGlobalYarnPath(tracer) {
  6637. let yarnCommand = 'yarn';
  6638. let options = {
  6639. encoding: 'utf8'
  6640. };
  6641. if (isWindows()) {
  6642. yarnCommand = 'yarn.cmd';
  6643. options.shell = true;
  6644. }
  6645. let handler = () => { };
  6646. try {
  6647. process.on('SIGPIPE', handler);
  6648. let results = child_process_1.spawnSync(yarnCommand, ['global', 'dir', '--json'], options);
  6649. let stdout = results.stdout;
  6650. if (!stdout) {
  6651. if (tracer) {
  6652. tracer(`'yarn global dir' didn't return a value.`);
  6653. if (results.stderr) {
  6654. tracer(results.stderr);
  6655. }
  6656. }
  6657. return undefined;
  6658. }
  6659. let lines = stdout.trim().split(/\r?\n/);
  6660. for (let line of lines) {
  6661. try {
  6662. let yarn = JSON.parse(line);
  6663. if (yarn.type === 'log') {
  6664. return path.join(yarn.data, 'node_modules');
  6665. }
  6666. }
  6667. catch (e) {
  6668. // Do nothing. Ignore the line
  6669. }
  6670. }
  6671. return undefined;
  6672. }
  6673. catch (err) {
  6674. return undefined;
  6675. }
  6676. finally {
  6677. process.removeListener('SIGPIPE', handler);
  6678. }
  6679. }
  6680. exports.resolveGlobalYarnPath = resolveGlobalYarnPath;
  6681. var FileSystem;
  6682. (function (FileSystem) {
  6683. let _isCaseSensitive = undefined;
  6684. function isCaseSensitive() {
  6685. if (_isCaseSensitive !== void 0) {
  6686. return _isCaseSensitive;
  6687. }
  6688. if (process.platform === 'win32') {
  6689. _isCaseSensitive = false;
  6690. }
  6691. else {
  6692. // convert current file name to upper case / lower case and check if file exists
  6693. // (guards against cases when name is already all uppercase or lowercase)
  6694. _isCaseSensitive = !fs.existsSync(__filename.toUpperCase()) || !fs.existsSync(__filename.toLowerCase());
  6695. }
  6696. return _isCaseSensitive;
  6697. }
  6698. FileSystem.isCaseSensitive = isCaseSensitive;
  6699. function isParent(parent, child) {
  6700. if (isCaseSensitive()) {
  6701. return path.normalize(child).indexOf(path.normalize(parent)) === 0;
  6702. }
  6703. else {
  6704. return path.normalize(child).toLowerCase().indexOf(path.normalize(parent).toLowerCase()) == 0;
  6705. }
  6706. }
  6707. FileSystem.isParent = isParent;
  6708. })(FileSystem = exports.FileSystem || (exports.FileSystem = {}));
  6709. function resolveModulePath(workspaceRoot, moduleName, nodePath, tracer) {
  6710. if (nodePath) {
  6711. if (!path.isAbsolute(nodePath)) {
  6712. nodePath = path.join(workspaceRoot, nodePath);
  6713. }
  6714. return resolve(moduleName, nodePath, nodePath, tracer).then((value) => {
  6715. if (FileSystem.isParent(nodePath, value)) {
  6716. return value;
  6717. }
  6718. else {
  6719. return Promise.reject(new Error(`Failed to load ${moduleName} from node path location.`));
  6720. }
  6721. }).then(undefined, (_error) => {
  6722. return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer);
  6723. });
  6724. }
  6725. else {
  6726. return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer);
  6727. }
  6728. }
  6729. exports.resolveModulePath = resolveModulePath;
  6730. /* WEBPACK VAR INJECTION */}.call(this, "/index.js"))
  6731. /***/ }),
  6732. /* 40 */
  6733. /***/ (function(module, exports) {
  6734. module.exports = require("url");
  6735. /***/ }),
  6736. /* 41 */
  6737. /***/ (function(module, exports) {
  6738. module.exports = require("child_process");
  6739. /***/ }),
  6740. /* 42 */
  6741. /***/ (function(module, exports, __webpack_require__) {
  6742. "use strict";
  6743. function __export(m) {
  6744. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  6745. }
  6746. Object.defineProperty(exports, "__esModule", { value: true });
  6747. __export(__webpack_require__(43));
  6748. __export(__webpack_require__(46));
  6749. /***/ }),
  6750. /* 43 */
  6751. /***/ (function(module, exports, __webpack_require__) {
  6752. "use strict";
  6753. /*---------------------------------------------------------------------------------------------
  6754. * Copyright (c) Microsoft Corporation. All rights reserved.
  6755. * Licensed under the MIT License. See License.txt in the project root for license information.
  6756. *--------------------------------------------------------------------------------------------*/
  6757. Object.defineProperty(exports, "__esModule", { value: true });
  6758. const position_1 = __webpack_require__(44);
  6759. const rbTreeBase_1 = __webpack_require__(45);
  6760. // const lfRegex = new RegExp(/\r\n|\r|\n/g);
  6761. exports.AverageBufferSize = 65535;
  6762. function createUintArray(arr) {
  6763. let r;
  6764. if (arr[arr.length - 1] < 65536) {
  6765. r = new Uint16Array(arr.length);
  6766. }
  6767. else {
  6768. r = new Uint32Array(arr.length);
  6769. }
  6770. r.set(arr, 0);
  6771. return r;
  6772. }
  6773. exports.createUintArray = createUintArray;
  6774. class LineStarts {
  6775. constructor(lineStarts, cr, lf, crlf, isBasicASCII) {
  6776. this.lineStarts = lineStarts;
  6777. this.cr = cr;
  6778. this.lf = lf;
  6779. this.crlf = crlf;
  6780. this.isBasicASCII = isBasicASCII;
  6781. }
  6782. }
  6783. exports.LineStarts = LineStarts;
  6784. function createLineStartsFast(str, readonly = true) {
  6785. let r = [0], rLength = 1;
  6786. for (let i = 0, len = str.length; i < len; i++) {
  6787. const chr = str.charCodeAt(i);
  6788. if (chr === 13 /* CarriageReturn */) {
  6789. if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* LineFeed */) {
  6790. // \r\n... case
  6791. r[rLength++] = i + 2;
  6792. i++; // skip \n
  6793. }
  6794. else {
  6795. // \r... case
  6796. r[rLength++] = i + 1;
  6797. }
  6798. }
  6799. else if (chr === 10 /* LineFeed */) {
  6800. r[rLength++] = i + 1;
  6801. }
  6802. }
  6803. if (readonly) {
  6804. return createUintArray(r);
  6805. }
  6806. else {
  6807. return r;
  6808. }
  6809. }
  6810. exports.createLineStartsFast = createLineStartsFast;
  6811. function createLineStarts(r, str) {
  6812. r.length = 0;
  6813. r[0] = 0;
  6814. let rLength = 1;
  6815. let cr = 0, lf = 0, crlf = 0;
  6816. let isBasicASCII = true;
  6817. for (let i = 0, len = str.length; i < len; i++) {
  6818. const chr = str.charCodeAt(i);
  6819. if (chr === 13 /* CarriageReturn */) {
  6820. if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* LineFeed */) {
  6821. // \r\n... case
  6822. crlf++;
  6823. r[rLength++] = i + 2;
  6824. i++; // skip \n
  6825. }
  6826. else {
  6827. cr++;
  6828. // \r... case
  6829. r[rLength++] = i + 1;
  6830. }
  6831. }
  6832. else if (chr === 10 /* LineFeed */) {
  6833. lf++;
  6834. r[rLength++] = i + 1;
  6835. }
  6836. else {
  6837. if (isBasicASCII) {
  6838. if (chr !== 9 /* Tab */ && (chr < 32 || chr > 126)) {
  6839. isBasicASCII = false;
  6840. }
  6841. }
  6842. }
  6843. }
  6844. const result = new LineStarts(createUintArray(r), cr, lf, crlf, isBasicASCII);
  6845. r.length = 0;
  6846. return result;
  6847. }
  6848. exports.createLineStarts = createLineStarts;
  6849. class Piece {
  6850. constructor(bufferIndex, start, end, lineFeedCnt, length) {
  6851. this.bufferIndex = bufferIndex;
  6852. this.start = start;
  6853. this.end = end;
  6854. this.lineFeedCnt = lineFeedCnt;
  6855. this.length = length;
  6856. }
  6857. }
  6858. exports.Piece = Piece;
  6859. class StringBuffer {
  6860. constructor(buffer, lineStarts) {
  6861. this.buffer = buffer;
  6862. this.lineStarts = lineStarts;
  6863. }
  6864. }
  6865. exports.StringBuffer = StringBuffer;
  6866. /**
  6867. * Readonly snapshot for piece tree.
  6868. * In a real multiple thread environment, to make snapshot reading always work correctly, we need to
  6869. * 1. Make TreeNode.piece immutable, then reading and writing can run in parallel.
  6870. * 2. TreeNode/Buffers normalization should not happen during snapshot reading.
  6871. */
  6872. class PieceTreeSnapshot {
  6873. constructor(tree, BOM) {
  6874. this._pieces = [];
  6875. this._tree = tree;
  6876. this._BOM = BOM;
  6877. this._index = 0;
  6878. if (tree.root !== rbTreeBase_1.SENTINEL) {
  6879. tree.iterate(tree.root, node => {
  6880. if (node !== rbTreeBase_1.SENTINEL) {
  6881. this._pieces.push(node.piece);
  6882. }
  6883. return true;
  6884. });
  6885. }
  6886. }
  6887. read() {
  6888. if (this._pieces.length === 0) {
  6889. if (this._index === 0) {
  6890. this._index++;
  6891. return this._BOM;
  6892. }
  6893. else {
  6894. return null;
  6895. }
  6896. }
  6897. if (this._index > this._pieces.length - 1) {
  6898. return null;
  6899. }
  6900. if (this._index === 0) {
  6901. return this._BOM + this._tree.getPieceContent(this._pieces[this._index++]);
  6902. }
  6903. return this._tree.getPieceContent(this._pieces[this._index++]);
  6904. }
  6905. }
  6906. class PieceTreeSearchCache {
  6907. constructor(limit) {
  6908. this._limit = limit;
  6909. this._cache = [];
  6910. }
  6911. get(offset) {
  6912. for (let i = this._cache.length - 1; i >= 0; i--) {
  6913. let nodePos = this._cache[i];
  6914. if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) {
  6915. return nodePos;
  6916. }
  6917. }
  6918. return null;
  6919. }
  6920. get2(lineNumber) {
  6921. for (let i = this._cache.length - 1; i >= 0; i--) {
  6922. let nodePos = this._cache[i];
  6923. if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) {
  6924. return nodePos;
  6925. }
  6926. }
  6927. return null;
  6928. }
  6929. set(nodePosition) {
  6930. if (this._cache.length >= this._limit) {
  6931. this._cache.shift();
  6932. }
  6933. this._cache.push(nodePosition);
  6934. }
  6935. valdiate(offset) {
  6936. let hasInvalidVal = false;
  6937. let tmp = this._cache;
  6938. for (let i = 0; i < tmp.length; i++) {
  6939. let nodePos = tmp[i];
  6940. if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) {
  6941. tmp[i] = null;
  6942. hasInvalidVal = true;
  6943. continue;
  6944. }
  6945. }
  6946. if (hasInvalidVal) {
  6947. let newArr = [];
  6948. for (const entry of tmp) {
  6949. if (entry !== null) {
  6950. newArr.push(entry);
  6951. }
  6952. }
  6953. this._cache = newArr;
  6954. }
  6955. }
  6956. }
  6957. class PieceTreeBase {
  6958. constructor(chunks, eol, eolNormalized) {
  6959. this.create(chunks, eol, eolNormalized);
  6960. }
  6961. create(chunks, eol, eolNormalized) {
  6962. this._buffers = [
  6963. new StringBuffer('', [0])
  6964. ];
  6965. this._lastChangeBufferPos = { line: 0, column: 0 };
  6966. this.root = rbTreeBase_1.SENTINEL;
  6967. this._lineCnt = 1;
  6968. this._length = 0;
  6969. this._EOL = eol;
  6970. this._EOLLength = eol.length;
  6971. this._EOLNormalized = eolNormalized;
  6972. let lastNode = null;
  6973. for (let i = 0, len = chunks.length; i < len; i++) {
  6974. if (chunks[i].buffer.length > 0) {
  6975. if (!chunks[i].lineStarts) {
  6976. chunks[i].lineStarts = createLineStartsFast(chunks[i].buffer);
  6977. }
  6978. let piece = new Piece(i + 1, { line: 0, column: 0 }, { line: chunks[i].lineStarts.length - 1, column: chunks[i].buffer.length - chunks[i].lineStarts[chunks[i].lineStarts.length - 1] }, chunks[i].lineStarts.length - 1, chunks[i].buffer.length);
  6979. this._buffers.push(chunks[i]);
  6980. lastNode = this.rbInsertRight(lastNode, piece);
  6981. }
  6982. }
  6983. this._searchCache = new PieceTreeSearchCache(1);
  6984. this._lastVisitedLine = { lineNumber: 0, value: '' };
  6985. this.computeBufferMetadata();
  6986. }
  6987. normalizeEOL(eol) {
  6988. let averageBufferSize = exports.AverageBufferSize;
  6989. let min = averageBufferSize - Math.floor(averageBufferSize / 3);
  6990. let max = min * 2;
  6991. let tempChunk = '';
  6992. let tempChunkLen = 0;
  6993. let chunks = [];
  6994. this.iterate(this.root, node => {
  6995. let str = this.getNodeContent(node);
  6996. let len = str.length;
  6997. if (tempChunkLen <= min || tempChunkLen + len < max) {
  6998. tempChunk += str;
  6999. tempChunkLen += len;
  7000. return true;
  7001. }
  7002. // flush anyways
  7003. let text = tempChunk.replace(/\r\n|\r|\n/g, eol);
  7004. chunks.push(new StringBuffer(text, createLineStartsFast(text)));
  7005. tempChunk = str;
  7006. tempChunkLen = len;
  7007. return true;
  7008. });
  7009. if (tempChunkLen > 0) {
  7010. let text = tempChunk.replace(/\r\n|\r|\n/g, eol);
  7011. chunks.push(new StringBuffer(text, createLineStartsFast(text)));
  7012. }
  7013. this.create(chunks, eol, true);
  7014. }
  7015. // #region Buffer API
  7016. getEOL() {
  7017. return this._EOL;
  7018. }
  7019. setEOL(newEOL) {
  7020. this._EOL = newEOL;
  7021. this._EOLLength = this._EOL.length;
  7022. this.normalizeEOL(newEOL);
  7023. }
  7024. createSnapshot(BOM) {
  7025. return new PieceTreeSnapshot(this, BOM);
  7026. }
  7027. equal(other) {
  7028. if (this.getLength() !== other.getLength()) {
  7029. return false;
  7030. }
  7031. if (this.getLineCount() !== other.getLineCount()) {
  7032. return false;
  7033. }
  7034. let offset = 0;
  7035. let ret = this.iterate(this.root, node => {
  7036. if (node === rbTreeBase_1.SENTINEL) {
  7037. return true;
  7038. }
  7039. let str = this.getNodeContent(node);
  7040. let len = str.length;
  7041. let startPosition = other.nodeAt(offset);
  7042. let endPosition = other.nodeAt(offset + len);
  7043. let val = other.getValueInRange2(startPosition, endPosition);
  7044. return str === val;
  7045. });
  7046. return ret;
  7047. }
  7048. getOffsetAt(lineNumber, column) {
  7049. let leftLen = 0; // inorder
  7050. let x = this.root;
  7051. while (x !== rbTreeBase_1.SENTINEL) {
  7052. if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left + 1 >= lineNumber) {
  7053. x = x.left;
  7054. }
  7055. else if (x.lf_left + x.piece.lineFeedCnt + 1 >= lineNumber) {
  7056. leftLen += x.size_left;
  7057. // lineNumber >= 2
  7058. let accumualtedValInCurrentIndex = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
  7059. return leftLen += accumualtedValInCurrentIndex + column - 1;
  7060. }
  7061. else {
  7062. lineNumber -= x.lf_left + x.piece.lineFeedCnt;
  7063. leftLen += x.size_left + x.piece.length;
  7064. x = x.right;
  7065. }
  7066. }
  7067. return leftLen;
  7068. }
  7069. getPositionAt(offset) {
  7070. offset = Math.floor(offset);
  7071. offset = Math.max(0, offset);
  7072. let x = this.root;
  7073. let lfCnt = 0;
  7074. let originalOffset = offset;
  7075. while (x !== rbTreeBase_1.SENTINEL) {
  7076. if (x.size_left !== 0 && x.size_left >= offset) {
  7077. x = x.left;
  7078. }
  7079. else if (x.size_left + x.piece.length >= offset) {
  7080. let out = this.getIndexOf(x, offset - x.size_left);
  7081. lfCnt += x.lf_left + out.index;
  7082. if (out.index === 0) {
  7083. let lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
  7084. let column = originalOffset - lineStartOffset;
  7085. return new position_1.Position(lfCnt + 1, column + 1);
  7086. }
  7087. return new position_1.Position(lfCnt + 1, out.remainder + 1);
  7088. }
  7089. else {
  7090. offset -= x.size_left + x.piece.length;
  7091. lfCnt += x.lf_left + x.piece.lineFeedCnt;
  7092. if (x.right === rbTreeBase_1.SENTINEL) {
  7093. // last node
  7094. let lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
  7095. let column = originalOffset - offset - lineStartOffset;
  7096. return new position_1.Position(lfCnt + 1, column + 1);
  7097. }
  7098. else {
  7099. x = x.right;
  7100. }
  7101. }
  7102. }
  7103. return new position_1.Position(1, 1);
  7104. }
  7105. getValueInRange(range, eol) {
  7106. if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
  7107. return '';
  7108. }
  7109. let startPosition = this.nodeAt2(range.startLineNumber, range.startColumn);
  7110. let endPosition = this.nodeAt2(range.endLineNumber, range.endColumn);
  7111. let value = this.getValueInRange2(startPosition, endPosition);
  7112. if (eol) {
  7113. if (eol !== this._EOL || !this._EOLNormalized) {
  7114. return value.replace(/\r\n|\r|\n/g, eol);
  7115. }
  7116. if (eol === this.getEOL() && this._EOLNormalized) {
  7117. if (eol === '\r\n') {
  7118. }
  7119. return value;
  7120. }
  7121. return value.replace(/\r\n|\r|\n/g, eol);
  7122. }
  7123. return value;
  7124. }
  7125. getValueInRange2(startPosition, endPosition) {
  7126. if (startPosition.node === endPosition.node) {
  7127. let node = startPosition.node;
  7128. let buffer = this._buffers[node.piece.bufferIndex].buffer;
  7129. let startOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
  7130. return buffer.substring(startOffset + startPosition.remainder, startOffset + endPosition.remainder);
  7131. }
  7132. let x = startPosition.node;
  7133. let buffer = this._buffers[x.piece.bufferIndex].buffer;
  7134. let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  7135. let ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length);
  7136. x = x.next();
  7137. while (x !== rbTreeBase_1.SENTINEL) {
  7138. let buffer = this._buffers[x.piece.bufferIndex].buffer;
  7139. let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  7140. if (x === endPosition.node) {
  7141. ret += buffer.substring(startOffset, startOffset + endPosition.remainder);
  7142. break;
  7143. }
  7144. else {
  7145. ret += buffer.substr(startOffset, x.piece.length);
  7146. }
  7147. x = x.next();
  7148. }
  7149. return ret;
  7150. }
  7151. getLinesContent() {
  7152. return this.getContentOfSubTree(this.root).split(/\r\n|\r|\n/);
  7153. }
  7154. getLength() {
  7155. return this._length;
  7156. }
  7157. getLineCount() {
  7158. return this._lineCnt;
  7159. }
  7160. /**
  7161. * @param lineNumber 1 based
  7162. */
  7163. getLineContent(lineNumber) {
  7164. if (this._lastVisitedLine.lineNumber === lineNumber) {
  7165. return this._lastVisitedLine.value;
  7166. }
  7167. this._lastVisitedLine.lineNumber = lineNumber;
  7168. if (lineNumber === this._lineCnt) {
  7169. this._lastVisitedLine.value = this.getLineRawContent(lineNumber);
  7170. }
  7171. else if (this._EOLNormalized) {
  7172. this._lastVisitedLine.value = this.getLineRawContent(lineNumber, this._EOLLength);
  7173. }
  7174. else {
  7175. this._lastVisitedLine.value = this.getLineRawContent(lineNumber).replace(/(\r\n|\r|\n)$/, '');
  7176. }
  7177. return this._lastVisitedLine.value;
  7178. }
  7179. getLineCharCode(lineNumber, index) {
  7180. let nodePos = this.nodeAt2(lineNumber, index + 1);
  7181. if (nodePos.remainder === nodePos.node.piece.length) {
  7182. // the char we want to fetch is at the head of next node.
  7183. let matchingNode = nodePos.node.next();
  7184. if (!matchingNode) {
  7185. return 0;
  7186. }
  7187. let buffer = this._buffers[matchingNode.piece.bufferIndex];
  7188. let startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start);
  7189. return buffer.buffer.charCodeAt(startOffset);
  7190. }
  7191. else {
  7192. let buffer = this._buffers[nodePos.node.piece.bufferIndex];
  7193. let startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
  7194. let targetOffset = startOffset + nodePos.remainder;
  7195. return buffer.buffer.charCodeAt(targetOffset);
  7196. }
  7197. }
  7198. getLineLength(lineNumber) {
  7199. if (lineNumber === this.getLineCount()) {
  7200. let startOffset = this.getOffsetAt(lineNumber, 1);
  7201. return this.getLength() - startOffset;
  7202. }
  7203. return this.getOffsetAt(lineNumber + 1, 1) - this.getOffsetAt(lineNumber, 1) - this._EOLLength;
  7204. }
  7205. // #endregion
  7206. // #region Piece Table
  7207. insert(offset, value, eolNormalized = false) {
  7208. this._EOLNormalized = this._EOLNormalized && eolNormalized;
  7209. this._lastVisitedLine.lineNumber = 0;
  7210. this._lastVisitedLine.value = '';
  7211. if (this.root !== rbTreeBase_1.SENTINEL) {
  7212. let { node, remainder, nodeStartOffset } = this.nodeAt(offset);
  7213. let piece = node.piece;
  7214. let bufferIndex = piece.bufferIndex;
  7215. let insertPosInBuffer = this.positionInBuffer(node, remainder);
  7216. if (node.piece.bufferIndex === 0 &&
  7217. piece.end.line === this._lastChangeBufferPos.line &&
  7218. piece.end.column === this._lastChangeBufferPos.column &&
  7219. (nodeStartOffset + piece.length === offset) &&
  7220. value.length < exports.AverageBufferSize) {
  7221. // changed buffer
  7222. this.appendToNode(node, value);
  7223. this.computeBufferMetadata();
  7224. return;
  7225. }
  7226. if (nodeStartOffset === offset) {
  7227. this.insertContentToNodeLeft(value, node);
  7228. this._searchCache.valdiate(offset);
  7229. }
  7230. else if (nodeStartOffset + node.piece.length > offset) {
  7231. // we are inserting into the middle of a node.
  7232. let nodesToDel = [];
  7233. let newRightPiece = new Piece(piece.bufferIndex, insertPosInBuffer, piece.end, this.getLineFeedCnt(piece.bufferIndex, insertPosInBuffer, piece.end), this.offsetInBuffer(bufferIndex, piece.end) - this.offsetInBuffer(bufferIndex, insertPosInBuffer));
  7234. if (this.shouldCheckCRLF() && this.endWithCR(value)) {
  7235. let headOfRight = this.nodeCharCodeAt(node, remainder);
  7236. if (headOfRight === 10 /** \n */) {
  7237. let newStart = { line: newRightPiece.start.line + 1, column: 0 };
  7238. newRightPiece = new Piece(newRightPiece.bufferIndex, newStart, newRightPiece.end, this.getLineFeedCnt(newRightPiece.bufferIndex, newStart, newRightPiece.end), newRightPiece.length - 1);
  7239. value += '\n';
  7240. }
  7241. }
  7242. // reuse node for content before insertion point.
  7243. if (this.shouldCheckCRLF() && this.startWithLF(value)) {
  7244. let tailOfLeft = this.nodeCharCodeAt(node, remainder - 1);
  7245. if (tailOfLeft === 13 /** \r */) {
  7246. let previousPos = this.positionInBuffer(node, remainder - 1);
  7247. this.deleteNodeTail(node, previousPos);
  7248. value = '\r' + value;
  7249. if (node.piece.length === 0) {
  7250. nodesToDel.push(node);
  7251. }
  7252. }
  7253. else {
  7254. this.deleteNodeTail(node, insertPosInBuffer);
  7255. }
  7256. }
  7257. else {
  7258. this.deleteNodeTail(node, insertPosInBuffer);
  7259. }
  7260. let newPieces = this.createNewPieces(value);
  7261. if (newRightPiece.length > 0) {
  7262. this.rbInsertRight(node, newRightPiece);
  7263. }
  7264. let tmpNode = node;
  7265. for (let k = 0; k < newPieces.length; k++) {
  7266. tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
  7267. }
  7268. this.deleteNodes(nodesToDel);
  7269. }
  7270. else {
  7271. this.insertContentToNodeRight(value, node);
  7272. }
  7273. }
  7274. else {
  7275. // insert new node
  7276. let pieces = this.createNewPieces(value);
  7277. let node = this.rbInsertLeft(null, pieces[0]);
  7278. for (let k = 1; k < pieces.length; k++) {
  7279. node = this.rbInsertRight(node, pieces[k]);
  7280. }
  7281. }
  7282. // todo, this is too brutal. Total line feed count should be updated the same way as lf_left.
  7283. this.computeBufferMetadata();
  7284. }
  7285. delete(offset, cnt) {
  7286. this._lastVisitedLine.lineNumber = 0;
  7287. this._lastVisitedLine.value = '';
  7288. if (cnt <= 0 || this.root === rbTreeBase_1.SENTINEL) {
  7289. return;
  7290. }
  7291. let startPosition = this.nodeAt(offset);
  7292. let endPosition = this.nodeAt(offset + cnt);
  7293. let startNode = startPosition.node;
  7294. let endNode = endPosition.node;
  7295. if (startNode === endNode) {
  7296. let startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
  7297. let endSplitPosInBuffer = this.positionInBuffer(startNode, endPosition.remainder);
  7298. if (startPosition.nodeStartOffset === offset) {
  7299. if (cnt === startNode.piece.length) { // delete node
  7300. let next = startNode.next();
  7301. rbTreeBase_1.rbDelete(this, startNode);
  7302. this.validateCRLFWithPrevNode(next);
  7303. this.computeBufferMetadata();
  7304. return;
  7305. }
  7306. this.deleteNodeHead(startNode, endSplitPosInBuffer);
  7307. this._searchCache.valdiate(offset);
  7308. this.validateCRLFWithPrevNode(startNode);
  7309. this.computeBufferMetadata();
  7310. return;
  7311. }
  7312. if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) {
  7313. this.deleteNodeTail(startNode, startSplitPosInBuffer);
  7314. this.validateCRLFWithNextNode(startNode);
  7315. this.computeBufferMetadata();
  7316. return;
  7317. }
  7318. // delete content in the middle, this node will be splitted to nodes
  7319. this.shrinkNode(startNode, startSplitPosInBuffer, endSplitPosInBuffer);
  7320. this.computeBufferMetadata();
  7321. return;
  7322. }
  7323. let nodesToDel = [];
  7324. let startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
  7325. this.deleteNodeTail(startNode, startSplitPosInBuffer);
  7326. this._searchCache.valdiate(offset);
  7327. if (startNode.piece.length === 0) {
  7328. nodesToDel.push(startNode);
  7329. }
  7330. // update last touched node
  7331. let endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder);
  7332. this.deleteNodeHead(endNode, endSplitPosInBuffer);
  7333. if (endNode.piece.length === 0) {
  7334. nodesToDel.push(endNode);
  7335. }
  7336. // delete nodes in between
  7337. let secondNode = startNode.next();
  7338. for (let node = secondNode; node !== rbTreeBase_1.SENTINEL && node !== endNode; node = node.next()) {
  7339. nodesToDel.push(node);
  7340. }
  7341. let prev = startNode.piece.length === 0 ? startNode.prev() : startNode;
  7342. this.deleteNodes(nodesToDel);
  7343. this.validateCRLFWithNextNode(prev);
  7344. this.computeBufferMetadata();
  7345. }
  7346. insertContentToNodeLeft(value, node) {
  7347. // we are inserting content to the beginning of node
  7348. let nodesToDel = [];
  7349. if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node)) {
  7350. // move `\n` to new node.
  7351. let piece = node.piece;
  7352. let newStart = { line: piece.start.line + 1, column: 0 };
  7353. let nPiece = new Piece(piece.bufferIndex, newStart, piece.end, this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end), piece.length - 1);
  7354. node.piece = nPiece;
  7355. value += '\n';
  7356. rbTreeBase_1.updateTreeMetadata(this, node, -1, -1);
  7357. if (node.piece.length === 0) {
  7358. nodesToDel.push(node);
  7359. }
  7360. }
  7361. let newPieces = this.createNewPieces(value);
  7362. let newNode = this.rbInsertLeft(node, newPieces[newPieces.length - 1]);
  7363. for (let k = newPieces.length - 2; k >= 0; k--) {
  7364. newNode = this.rbInsertLeft(newNode, newPieces[k]);
  7365. }
  7366. this.validateCRLFWithPrevNode(newNode);
  7367. this.deleteNodes(nodesToDel);
  7368. }
  7369. insertContentToNodeRight(value, node) {
  7370. // we are inserting to the right of this node.
  7371. if (this.adjustCarriageReturnFromNext(value, node)) {
  7372. // move \n to the new node.
  7373. value += '\n';
  7374. }
  7375. let newPieces = this.createNewPieces(value);
  7376. let newNode = this.rbInsertRight(node, newPieces[0]);
  7377. let tmpNode = newNode;
  7378. for (let k = 1; k < newPieces.length; k++) {
  7379. tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
  7380. }
  7381. this.validateCRLFWithPrevNode(newNode);
  7382. }
  7383. positionInBuffer(node, remainder, ret) {
  7384. let piece = node.piece;
  7385. let bufferIndex = node.piece.bufferIndex;
  7386. let lineStarts = this._buffers[bufferIndex].lineStarts;
  7387. let startOffset = lineStarts[piece.start.line] + piece.start.column;
  7388. let offset = startOffset + remainder;
  7389. // binary search offset between startOffset and endOffset
  7390. let low = piece.start.line;
  7391. let high = piece.end.line;
  7392. let mid = 0;
  7393. let midStop = 0;
  7394. let midStart = 0;
  7395. while (low <= high) {
  7396. mid = low + ((high - low) / 2) | 0;
  7397. midStart = lineStarts[mid];
  7398. if (mid === high) {
  7399. break;
  7400. }
  7401. midStop = lineStarts[mid + 1];
  7402. if (offset < midStart) {
  7403. high = mid - 1;
  7404. }
  7405. else if (offset >= midStop) {
  7406. low = mid + 1;
  7407. }
  7408. else {
  7409. break;
  7410. }
  7411. }
  7412. if (ret) {
  7413. ret.line = mid;
  7414. ret.column = offset - midStart;
  7415. return null;
  7416. }
  7417. return {
  7418. line: mid,
  7419. column: offset - midStart
  7420. };
  7421. }
  7422. getLineFeedCnt(bufferIndex, start, end) {
  7423. // we don't need to worry about start: abc\r|\n, or abc|\r, or abc|\n, or abc|\r\n doesn't change the fact that, there is one line break after start.
  7424. // now let's take care of end: abc\r|\n, if end is in between \r and \n, we need to add line feed count by 1
  7425. if (end.column === 0) {
  7426. return end.line - start.line;
  7427. }
  7428. let lineStarts = this._buffers[bufferIndex].lineStarts;
  7429. if (end.line === lineStarts.length - 1) { // it means, there is no \n after end, otherwise, there will be one more lineStart.
  7430. return end.line - start.line;
  7431. }
  7432. let nextLineStartOffset = lineStarts[end.line + 1];
  7433. let endOffset = lineStarts[end.line] + end.column;
  7434. if (nextLineStartOffset > endOffset + 1) { // there are more than 1 character after end, which means it can't be \n
  7435. return end.line - start.line;
  7436. }
  7437. // endOffset + 1 === nextLineStartOffset
  7438. // character at endOffset is \n, so we check the character before first
  7439. // if character at endOffset is \r, end.column is 0 and we can't get here.
  7440. let previousCharOffset = endOffset - 1; // end.column > 0 so it's okay.
  7441. let buffer = this._buffers[bufferIndex].buffer;
  7442. if (buffer.charCodeAt(previousCharOffset) === 13) {
  7443. return end.line - start.line + 1;
  7444. }
  7445. else {
  7446. return end.line - start.line;
  7447. }
  7448. }
  7449. offsetInBuffer(bufferIndex, cursor) {
  7450. let lineStarts = this._buffers[bufferIndex].lineStarts;
  7451. return lineStarts[cursor.line] + cursor.column;
  7452. }
  7453. deleteNodes(nodes) {
  7454. for (let i = 0; i < nodes.length; i++) {
  7455. rbTreeBase_1.rbDelete(this, nodes[i]);
  7456. }
  7457. }
  7458. createNewPieces(text) {
  7459. if (text.length > exports.AverageBufferSize) {
  7460. // the content is large, operations like substring, charCode becomes slow
  7461. // so here we split it into smaller chunks, just like what we did for CR/LF normalization
  7462. let newPieces = [];
  7463. while (text.length > exports.AverageBufferSize) {
  7464. const lastChar = text.charCodeAt(exports.AverageBufferSize - 1);
  7465. let splitText;
  7466. if (lastChar === 13 /* CarriageReturn */ || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {
  7467. // last character is \r or a high surrogate => keep it back
  7468. splitText = text.substring(0, exports.AverageBufferSize - 1);
  7469. text = text.substring(exports.AverageBufferSize - 1);
  7470. }
  7471. else {
  7472. splitText = text.substring(0, exports.AverageBufferSize);
  7473. text = text.substring(exports.AverageBufferSize);
  7474. }
  7475. let lineStarts = createLineStartsFast(splitText);
  7476. newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts.length - 1, column: splitText.length - lineStarts[lineStarts.length - 1] }, lineStarts.length - 1, splitText.length));
  7477. this._buffers.push(new StringBuffer(splitText, lineStarts));
  7478. }
  7479. let lineStarts = createLineStartsFast(text);
  7480. newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts.length - 1, column: text.length - lineStarts[lineStarts.length - 1] }, lineStarts.length - 1, text.length));
  7481. this._buffers.push(new StringBuffer(text, lineStarts));
  7482. return newPieces;
  7483. }
  7484. let startOffset = this._buffers[0].buffer.length;
  7485. const lineStarts = createLineStartsFast(text, false);
  7486. let start = this._lastChangeBufferPos;
  7487. if (this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 1] === startOffset
  7488. && startOffset !== 0
  7489. && this.startWithLF(text)
  7490. && this.endWithCR(this._buffers[0].buffer) // todo, we can check this._lastChangeBufferPos's column as it's the last one
  7491. ) {
  7492. this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line, column: this._lastChangeBufferPos.column + 1 };
  7493. start = this._lastChangeBufferPos;
  7494. for (let i = 0; i < lineStarts.length; i++) {
  7495. lineStarts[i] += startOffset + 1;
  7496. }
  7497. this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
  7498. this._buffers[0].buffer += '_' + text;
  7499. startOffset += 1;
  7500. }
  7501. else {
  7502. if (startOffset !== 0) {
  7503. for (let i = 0; i < lineStarts.length; i++) {
  7504. lineStarts[i] += startOffset;
  7505. }
  7506. }
  7507. this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
  7508. this._buffers[0].buffer += text;
  7509. }
  7510. const endOffset = this._buffers[0].buffer.length;
  7511. let endIndex = this._buffers[0].lineStarts.length - 1;
  7512. let endColumn = endOffset - this._buffers[0].lineStarts[endIndex];
  7513. let endPos = { line: endIndex, column: endColumn };
  7514. let newPiece = new Piece(0, /** todo@peng */ start, endPos, this.getLineFeedCnt(0, start, endPos), endOffset - startOffset);
  7515. this._lastChangeBufferPos = endPos;
  7516. return [newPiece];
  7517. }
  7518. getLinesRawContent() {
  7519. return this.getContentOfSubTree(this.root);
  7520. }
  7521. getLineRawContent(lineNumber, endOffset = 0) {
  7522. let x = this.root;
  7523. let ret = '';
  7524. let cache = this._searchCache.get2(lineNumber);
  7525. if (cache) {
  7526. x = cache.node;
  7527. let prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber - 1);
  7528. let buffer = this._buffers[x.piece.bufferIndex].buffer;
  7529. let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  7530. if (cache.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) {
  7531. ret = buffer.substring(startOffset + prevAccumualtedValue, startOffset + x.piece.length);
  7532. }
  7533. else {
  7534. let accumualtedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber);
  7535. return buffer.substring(startOffset + prevAccumualtedValue, startOffset + accumualtedValue - endOffset);
  7536. }
  7537. }
  7538. else {
  7539. let nodeStartOffset = 0;
  7540. const originalLineNumber = lineNumber;
  7541. while (x !== rbTreeBase_1.SENTINEL) {
  7542. if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left >= lineNumber - 1) {
  7543. x = x.left;
  7544. }
  7545. else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
  7546. let prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
  7547. let accumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
  7548. let buffer = this._buffers[x.piece.bufferIndex].buffer;
  7549. let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  7550. nodeStartOffset += x.size_left;
  7551. this._searchCache.set({
  7552. node: x,
  7553. nodeStartOffset,
  7554. nodeStartLineNumber: originalLineNumber - (lineNumber - 1 - x.lf_left)
  7555. });
  7556. return buffer.substring(startOffset + prevAccumualtedValue, startOffset + accumualtedValue - endOffset);
  7557. }
  7558. else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
  7559. let prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
  7560. let buffer = this._buffers[x.piece.bufferIndex].buffer;
  7561. let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  7562. ret = buffer.substring(startOffset + prevAccumualtedValue, startOffset + x.piece.length);
  7563. break;
  7564. }
  7565. else {
  7566. lineNumber -= x.lf_left + x.piece.lineFeedCnt;
  7567. nodeStartOffset += x.size_left + x.piece.length;
  7568. x = x.right;
  7569. }
  7570. }
  7571. }
  7572. // search in order, to find the node contains end column
  7573. x = x.next();
  7574. while (x !== rbTreeBase_1.SENTINEL) {
  7575. let buffer = this._buffers[x.piece.bufferIndex].buffer;
  7576. if (x.piece.lineFeedCnt > 0) {
  7577. let accumualtedValue = this.getAccumulatedValue(x, 0);
  7578. let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  7579. ret += buffer.substring(startOffset, startOffset + accumualtedValue - endOffset);
  7580. return ret;
  7581. }
  7582. else {
  7583. let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  7584. ret += buffer.substr(startOffset, x.piece.length);
  7585. }
  7586. x = x.next();
  7587. }
  7588. return ret;
  7589. }
  7590. computeBufferMetadata() {
  7591. let x = this.root;
  7592. let lfCnt = 1;
  7593. let len = 0;
  7594. while (x !== rbTreeBase_1.SENTINEL) {
  7595. lfCnt += x.lf_left + x.piece.lineFeedCnt;
  7596. len += x.size_left + x.piece.length;
  7597. x = x.right;
  7598. }
  7599. this._lineCnt = lfCnt;
  7600. this._length = len;
  7601. this._searchCache.valdiate(this._length);
  7602. }
  7603. // #region node operations
  7604. getIndexOf(node, accumulatedValue) {
  7605. let piece = node.piece;
  7606. let pos = this.positionInBuffer(node, accumulatedValue);
  7607. let lineCnt = pos.line - piece.start.line;
  7608. if (this.offsetInBuffer(piece.bufferIndex, piece.end) - this.offsetInBuffer(piece.bufferIndex, piece.start) === accumulatedValue) {
  7609. // we are checking the end of this node, so a CRLF check is necessary.
  7610. let realLineCnt = this.getLineFeedCnt(node.piece.bufferIndex, piece.start, pos);
  7611. if (realLineCnt !== lineCnt) {
  7612. // aha yes, CRLF
  7613. return { index: realLineCnt, remainder: 0 };
  7614. }
  7615. }
  7616. return { index: lineCnt, remainder: pos.column };
  7617. }
  7618. getAccumulatedValue(node, index) {
  7619. if (index < 0) {
  7620. return 0;
  7621. }
  7622. let piece = node.piece;
  7623. let lineStarts = this._buffers[piece.bufferIndex].lineStarts;
  7624. let expectedLineStartIndex = piece.start.line + index + 1;
  7625. if (expectedLineStartIndex > piece.end.line) {
  7626. return lineStarts[piece.end.line] + piece.end.column - lineStarts[piece.start.line] - piece.start.column;
  7627. }
  7628. else {
  7629. return lineStarts[expectedLineStartIndex] - lineStarts[piece.start.line] - piece.start.column;
  7630. }
  7631. }
  7632. deleteNodeTail(node, pos) {
  7633. const piece = node.piece;
  7634. const originalLFCnt = piece.lineFeedCnt;
  7635. const originalEndOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
  7636. const newEnd = pos;
  7637. const newEndOffset = this.offsetInBuffer(piece.bufferIndex, newEnd);
  7638. const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
  7639. const lf_delta = newLineFeedCnt - originalLFCnt;
  7640. const size_delta = newEndOffset - originalEndOffset;
  7641. const newLength = piece.length + size_delta;
  7642. node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
  7643. rbTreeBase_1.updateTreeMetadata(this, node, size_delta, lf_delta);
  7644. }
  7645. deleteNodeHead(node, pos) {
  7646. const piece = node.piece;
  7647. const originalLFCnt = piece.lineFeedCnt;
  7648. const originalStartOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
  7649. const newStart = pos;
  7650. const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
  7651. const newStartOffset = this.offsetInBuffer(piece.bufferIndex, newStart);
  7652. const lf_delta = newLineFeedCnt - originalLFCnt;
  7653. const size_delta = originalStartOffset - newStartOffset;
  7654. const newLength = piece.length + size_delta;
  7655. node.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
  7656. rbTreeBase_1.updateTreeMetadata(this, node, size_delta, lf_delta);
  7657. }
  7658. shrinkNode(node, start, end) {
  7659. const piece = node.piece;
  7660. const originalStartPos = piece.start;
  7661. const originalEndPos = piece.end;
  7662. // old piece, originalStartPos, start
  7663. const oldLength = piece.length;
  7664. const oldLFCnt = piece.lineFeedCnt;
  7665. const newEnd = start;
  7666. const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
  7667. const newLength = this.offsetInBuffer(piece.bufferIndex, start) - this.offsetInBuffer(piece.bufferIndex, originalStartPos);
  7668. node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
  7669. rbTreeBase_1.updateTreeMetadata(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt);
  7670. // new right piece, end, originalEndPos
  7671. let newPiece = new Piece(piece.bufferIndex, end, originalEndPos, this.getLineFeedCnt(piece.bufferIndex, end, originalEndPos), this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end));
  7672. let newNode = this.rbInsertRight(node, newPiece);
  7673. this.validateCRLFWithPrevNode(newNode);
  7674. }
  7675. appendToNode(node, value) {
  7676. if (this.adjustCarriageReturnFromNext(value, node)) {
  7677. value += '\n';
  7678. }
  7679. const hitCRLF = this.shouldCheckCRLF() && this.startWithLF(value) && this.endWithCR(node);
  7680. const startOffset = this._buffers[0].buffer.length;
  7681. this._buffers[0].buffer += value;
  7682. const lineStarts = createLineStartsFast(value, false);
  7683. for (let i = 0; i < lineStarts.length; i++) {
  7684. lineStarts[i] += startOffset;
  7685. }
  7686. if (hitCRLF) {
  7687. let prevStartOffset = this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 2];
  7688. this._buffers[0].lineStarts.pop();
  7689. // _lastChangeBufferPos is already wrong
  7690. this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line - 1, column: startOffset - prevStartOffset };
  7691. }
  7692. this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
  7693. const endIndex = this._buffers[0].lineStarts.length - 1;
  7694. const endColumn = this._buffers[0].buffer.length - this._buffers[0].lineStarts[endIndex];
  7695. const newEnd = { line: endIndex, column: endColumn };
  7696. const newLength = node.piece.length + value.length;
  7697. const oldLineFeedCnt = node.piece.lineFeedCnt;
  7698. const newLineFeedCnt = this.getLineFeedCnt(0, node.piece.start, newEnd);
  7699. const lf_delta = newLineFeedCnt - oldLineFeedCnt;
  7700. node.piece = new Piece(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength);
  7701. this._lastChangeBufferPos = newEnd;
  7702. rbTreeBase_1.updateTreeMetadata(this, node, value.length, lf_delta);
  7703. }
  7704. nodeAt(offset) {
  7705. let x = this.root;
  7706. let cache = this._searchCache.get(offset);
  7707. if (cache) {
  7708. return {
  7709. node: cache.node,
  7710. nodeStartOffset: cache.nodeStartOffset,
  7711. remainder: offset - cache.nodeStartOffset
  7712. };
  7713. }
  7714. let nodeStartOffset = 0;
  7715. while (x !== rbTreeBase_1.SENTINEL) {
  7716. if (x.size_left > offset) {
  7717. x = x.left;
  7718. }
  7719. else if (x.size_left + x.piece.length >= offset) {
  7720. nodeStartOffset += x.size_left;
  7721. let ret = {
  7722. node: x,
  7723. remainder: offset - x.size_left,
  7724. nodeStartOffset
  7725. };
  7726. this._searchCache.set(ret);
  7727. return ret;
  7728. }
  7729. else {
  7730. offset -= x.size_left + x.piece.length;
  7731. nodeStartOffset += x.size_left + x.piece.length;
  7732. x = x.right;
  7733. }
  7734. }
  7735. return null;
  7736. }
  7737. nodeAt2(lineNumber, column) {
  7738. let x = this.root;
  7739. let nodeStartOffset = 0;
  7740. while (x !== rbTreeBase_1.SENTINEL) {
  7741. if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left >= lineNumber - 1) {
  7742. x = x.left;
  7743. }
  7744. else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
  7745. let prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
  7746. let accumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
  7747. nodeStartOffset += x.size_left;
  7748. return {
  7749. node: x,
  7750. remainder: Math.min(prevAccumualtedValue + column - 1, accumualtedValue),
  7751. nodeStartOffset
  7752. };
  7753. }
  7754. else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
  7755. let prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
  7756. if (prevAccumualtedValue + column - 1 <= x.piece.length) {
  7757. return {
  7758. node: x,
  7759. remainder: prevAccumualtedValue + column - 1,
  7760. nodeStartOffset
  7761. };
  7762. }
  7763. else {
  7764. column -= x.piece.length - prevAccumualtedValue;
  7765. break;
  7766. }
  7767. }
  7768. else {
  7769. lineNumber -= x.lf_left + x.piece.lineFeedCnt;
  7770. nodeStartOffset += x.size_left + x.piece.length;
  7771. x = x.right;
  7772. }
  7773. }
  7774. // search in order, to find the node contains position.column
  7775. x = x.next();
  7776. while (x !== rbTreeBase_1.SENTINEL) {
  7777. if (x.piece.lineFeedCnt > 0) {
  7778. let accumualtedValue = this.getAccumulatedValue(x, 0);
  7779. let nodeStartOffset = this.offsetOfNode(x);
  7780. return {
  7781. node: x,
  7782. remainder: Math.min(column - 1, accumualtedValue),
  7783. nodeStartOffset
  7784. };
  7785. }
  7786. else {
  7787. if (x.piece.length >= column - 1) {
  7788. let nodeStartOffset = this.offsetOfNode(x);
  7789. return {
  7790. node: x,
  7791. remainder: column - 1,
  7792. nodeStartOffset
  7793. };
  7794. }
  7795. else {
  7796. column -= x.piece.length;
  7797. }
  7798. }
  7799. x = x.next();
  7800. }
  7801. return null;
  7802. }
  7803. nodeCharCodeAt(node, offset) {
  7804. if (node.piece.lineFeedCnt < 1) {
  7805. return -1;
  7806. }
  7807. let buffer = this._buffers[node.piece.bufferIndex];
  7808. let newOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start) + offset;
  7809. return buffer.buffer.charCodeAt(newOffset);
  7810. }
  7811. offsetOfNode(node) {
  7812. if (!node) {
  7813. return 0;
  7814. }
  7815. let pos = node.size_left;
  7816. while (node !== this.root) {
  7817. if (node.parent.right === node) {
  7818. pos += node.parent.size_left + node.parent.piece.length;
  7819. }
  7820. node = node.parent;
  7821. }
  7822. return pos;
  7823. }
  7824. // #endregion
  7825. // #region CRLF
  7826. shouldCheckCRLF() {
  7827. return !(this._EOLNormalized && this._EOL === '\n');
  7828. }
  7829. startWithLF(val) {
  7830. if (typeof val === 'string') {
  7831. return val.charCodeAt(0) === 10;
  7832. }
  7833. if (val === rbTreeBase_1.SENTINEL || val.piece.lineFeedCnt === 0) {
  7834. return false;
  7835. }
  7836. let piece = val.piece;
  7837. let lineStarts = this._buffers[piece.bufferIndex].lineStarts;
  7838. let line = piece.start.line;
  7839. let startOffset = lineStarts[line] + piece.start.column;
  7840. if (line === lineStarts.length - 1) {
  7841. // last line, so there is no line feed at the end of this line
  7842. return false;
  7843. }
  7844. let nextLineOffset = lineStarts[line + 1];
  7845. if (nextLineOffset > startOffset + 1) {
  7846. return false;
  7847. }
  7848. return this._buffers[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10;
  7849. }
  7850. endWithCR(val) {
  7851. if (typeof val === 'string') {
  7852. return val.charCodeAt(val.length - 1) === 13;
  7853. }
  7854. if (val === rbTreeBase_1.SENTINEL || val.piece.lineFeedCnt === 0) {
  7855. return false;
  7856. }
  7857. return this.nodeCharCodeAt(val, val.piece.length - 1) === 13;
  7858. }
  7859. validateCRLFWithPrevNode(nextNode) {
  7860. if (this.shouldCheckCRLF() && this.startWithLF(nextNode)) {
  7861. let node = nextNode.prev();
  7862. if (this.endWithCR(node)) {
  7863. this.fixCRLF(node, nextNode);
  7864. }
  7865. }
  7866. }
  7867. validateCRLFWithNextNode(node) {
  7868. if (this.shouldCheckCRLF() && this.endWithCR(node)) {
  7869. let nextNode = node.next();
  7870. if (this.startWithLF(nextNode)) {
  7871. this.fixCRLF(node, nextNode);
  7872. }
  7873. }
  7874. }
  7875. fixCRLF(prev, next) {
  7876. let nodesToDel = [];
  7877. // update node
  7878. let lineStarts = this._buffers[prev.piece.bufferIndex].lineStarts;
  7879. let newEnd;
  7880. if (prev.piece.end.column === 0) {
  7881. // it means, last line ends with \r, not \r\n
  7882. newEnd = { line: prev.piece.end.line - 1, column: lineStarts[prev.piece.end.line] - lineStarts[prev.piece.end.line - 1] - 1 };
  7883. }
  7884. else {
  7885. // \r\n
  7886. newEnd = { line: prev.piece.end.line, column: prev.piece.end.column - 1 };
  7887. }
  7888. const prevNewLength = prev.piece.length - 1;
  7889. const prevNewLFCnt = prev.piece.lineFeedCnt - 1;
  7890. prev.piece = new Piece(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength);
  7891. rbTreeBase_1.updateTreeMetadata(this, prev, -1, -1);
  7892. if (prev.piece.length === 0) {
  7893. nodesToDel.push(prev);
  7894. }
  7895. // update nextNode
  7896. let newStart = { line: next.piece.start.line + 1, column: 0 };
  7897. const newLength = next.piece.length - 1;
  7898. const newLineFeedCnt = this.getLineFeedCnt(next.piece.bufferIndex, newStart, next.piece.end);
  7899. next.piece = new Piece(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength);
  7900. rbTreeBase_1.updateTreeMetadata(this, next, -1, -1);
  7901. if (next.piece.length === 0) {
  7902. nodesToDel.push(next);
  7903. }
  7904. // create new piece which contains \r\n
  7905. let pieces = this.createNewPieces('\r\n');
  7906. this.rbInsertRight(prev, pieces[0]);
  7907. // delete empty nodes
  7908. for (let i = 0; i < nodesToDel.length; i++) {
  7909. rbTreeBase_1.rbDelete(this, nodesToDel[i]);
  7910. }
  7911. }
  7912. adjustCarriageReturnFromNext(value, node) {
  7913. if (this.shouldCheckCRLF() && this.endWithCR(value)) {
  7914. let nextNode = node.next();
  7915. if (this.startWithLF(nextNode)) {
  7916. // move `\n` forward
  7917. value += '\n';
  7918. if (nextNode.piece.length === 1) {
  7919. rbTreeBase_1.rbDelete(this, nextNode);
  7920. }
  7921. else {
  7922. const piece = nextNode.piece;
  7923. const newStart = { line: piece.start.line + 1, column: 0 };
  7924. const newLength = piece.length - 1;
  7925. const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
  7926. nextNode.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
  7927. rbTreeBase_1.updateTreeMetadata(this, nextNode, -1, -1);
  7928. }
  7929. return true;
  7930. }
  7931. }
  7932. return false;
  7933. }
  7934. // #endregion
  7935. // #endregion
  7936. // #region Tree operations
  7937. iterate(node, callback) {
  7938. if (node === rbTreeBase_1.SENTINEL) {
  7939. return callback(rbTreeBase_1.SENTINEL);
  7940. }
  7941. let leftRet = this.iterate(node.left, callback);
  7942. if (!leftRet) {
  7943. return leftRet;
  7944. }
  7945. return callback(node) && this.iterate(node.right, callback);
  7946. }
  7947. getNodeContent(node) {
  7948. if (node === rbTreeBase_1.SENTINEL) {
  7949. return '';
  7950. }
  7951. let buffer = this._buffers[node.piece.bufferIndex];
  7952. let currentContent;
  7953. let piece = node.piece;
  7954. let startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
  7955. let endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
  7956. currentContent = buffer.buffer.substring(startOffset, endOffset);
  7957. return currentContent;
  7958. }
  7959. getPieceContent(piece) {
  7960. let buffer = this._buffers[piece.bufferIndex];
  7961. let startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
  7962. let endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
  7963. let currentContent = buffer.buffer.substring(startOffset, endOffset);
  7964. return currentContent;
  7965. }
  7966. /**
  7967. * node node
  7968. * / \ / \
  7969. * a b <---- a b
  7970. * /
  7971. * z
  7972. */
  7973. rbInsertRight(node, p) {
  7974. let z = new rbTreeBase_1.TreeNode(p, 1 /* Red */);
  7975. z.left = rbTreeBase_1.SENTINEL;
  7976. z.right = rbTreeBase_1.SENTINEL;
  7977. z.parent = rbTreeBase_1.SENTINEL;
  7978. z.size_left = 0;
  7979. z.lf_left = 0;
  7980. let x = this.root;
  7981. if (x === rbTreeBase_1.SENTINEL) {
  7982. this.root = z;
  7983. z.color = 0 /* Black */;
  7984. }
  7985. else if (node.right === rbTreeBase_1.SENTINEL) {
  7986. node.right = z;
  7987. z.parent = node;
  7988. }
  7989. else {
  7990. let nextNode = rbTreeBase_1.leftest(node.right);
  7991. nextNode.left = z;
  7992. z.parent = nextNode;
  7993. }
  7994. rbTreeBase_1.fixInsert(this, z);
  7995. return z;
  7996. }
  7997. /**
  7998. * node node
  7999. * / \ / \
  8000. * a b ----> a b
  8001. * \
  8002. * z
  8003. */
  8004. rbInsertLeft(node, p) {
  8005. let z = new rbTreeBase_1.TreeNode(p, 1 /* Red */);
  8006. z.left = rbTreeBase_1.SENTINEL;
  8007. z.right = rbTreeBase_1.SENTINEL;
  8008. z.parent = rbTreeBase_1.SENTINEL;
  8009. z.size_left = 0;
  8010. z.lf_left = 0;
  8011. if (this.root === rbTreeBase_1.SENTINEL) {
  8012. this.root = z;
  8013. z.color = 0 /* Black */;
  8014. }
  8015. else if (node.left === rbTreeBase_1.SENTINEL) {
  8016. node.left = z;
  8017. z.parent = node;
  8018. }
  8019. else {
  8020. let prevNode = rbTreeBase_1.righttest(node.left); // a
  8021. prevNode.right = z;
  8022. z.parent = prevNode;
  8023. }
  8024. rbTreeBase_1.fixInsert(this, z);
  8025. return z;
  8026. }
  8027. getContentOfSubTree(node) {
  8028. let str = '';
  8029. this.iterate(node, node => {
  8030. str += this.getNodeContent(node);
  8031. return true;
  8032. });
  8033. return str;
  8034. }
  8035. }
  8036. exports.PieceTreeBase = PieceTreeBase;
  8037. /***/ }),
  8038. /* 44 */
  8039. /***/ (function(module, exports, __webpack_require__) {
  8040. "use strict";
  8041. /*---------------------------------------------------------------------------------------------
  8042. * Copyright (c) Microsoft Corporation. All rights reserved.
  8043. * Licensed under the MIT License. See License.txt in the project root for license information.
  8044. *--------------------------------------------------------------------------------------------*/
  8045. Object.defineProperty(exports, "__esModule", { value: true });
  8046. /**
  8047. * A position in the editor.
  8048. */
  8049. class Position {
  8050. constructor(lineNumber, column) {
  8051. this.lineNumber = lineNumber;
  8052. this.column = column;
  8053. }
  8054. /**
  8055. * Create a new postion from this position.
  8056. *
  8057. * @param newLineNumber new line number
  8058. * @param newColumn new column
  8059. */
  8060. with(newLineNumber = this.lineNumber, newColumn = this.column) {
  8061. if (newLineNumber === this.lineNumber && newColumn === this.column) {
  8062. return this;
  8063. }
  8064. else {
  8065. return new Position(newLineNumber, newColumn);
  8066. }
  8067. }
  8068. /**
  8069. * Derive a new position from this position.
  8070. *
  8071. * @param deltaLineNumber line number delta
  8072. * @param deltaColumn column delta
  8073. */
  8074. delta(deltaLineNumber = 0, deltaColumn = 0) {
  8075. return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn);
  8076. }
  8077. /**
  8078. * Test if this position equals other position
  8079. */
  8080. equals(other) {
  8081. return Position.equals(this, other);
  8082. }
  8083. /**
  8084. * Test if position `a` equals position `b`
  8085. */
  8086. static equals(a, b) {
  8087. if (!a && !b) {
  8088. return true;
  8089. }
  8090. return (!!a &&
  8091. !!b &&
  8092. a.lineNumber === b.lineNumber &&
  8093. a.column === b.column);
  8094. }
  8095. /**
  8096. * Test if this position is before other position.
  8097. * If the two positions are equal, the result will be false.
  8098. */
  8099. isBefore(other) {
  8100. return Position.isBefore(this, other);
  8101. }
  8102. /**
  8103. * Test if position `a` is before position `b`.
  8104. * If the two positions are equal, the result will be false.
  8105. */
  8106. static isBefore(a, b) {
  8107. if (a.lineNumber < b.lineNumber) {
  8108. return true;
  8109. }
  8110. if (b.lineNumber < a.lineNumber) {
  8111. return false;
  8112. }
  8113. return a.column < b.column;
  8114. }
  8115. /**
  8116. * Test if this position is before other position.
  8117. * If the two positions are equal, the result will be true.
  8118. */
  8119. isBeforeOrEqual(other) {
  8120. return Position.isBeforeOrEqual(this, other);
  8121. }
  8122. /**
  8123. * Test if position `a` is before position `b`.
  8124. * If the two positions are equal, the result will be true.
  8125. */
  8126. static isBeforeOrEqual(a, b) {
  8127. if (a.lineNumber < b.lineNumber) {
  8128. return true;
  8129. }
  8130. if (b.lineNumber < a.lineNumber) {
  8131. return false;
  8132. }
  8133. return a.column <= b.column;
  8134. }
  8135. /**
  8136. * A function that compares positions, useful for sorting
  8137. */
  8138. static compare(a, b) {
  8139. let aLineNumber = a.lineNumber | 0;
  8140. let bLineNumber = b.lineNumber | 0;
  8141. if (aLineNumber === bLineNumber) {
  8142. let aColumn = a.column | 0;
  8143. let bColumn = b.column | 0;
  8144. return aColumn - bColumn;
  8145. }
  8146. return aLineNumber - bLineNumber;
  8147. }
  8148. /**
  8149. * Clone this position.
  8150. */
  8151. clone() {
  8152. return new Position(this.lineNumber, this.column);
  8153. }
  8154. /**
  8155. * Convert to a human-readable representation.
  8156. */
  8157. toString() {
  8158. return '(' + this.lineNumber + ',' + this.column + ')';
  8159. }
  8160. // ---
  8161. /**
  8162. * Create a `Position` from an `IPosition`.
  8163. */
  8164. static lift(pos) {
  8165. return new Position(pos.lineNumber, pos.column);
  8166. }
  8167. /**
  8168. * Test if `obj` is an `IPosition`.
  8169. */
  8170. static isIPosition(obj) {
  8171. return (obj
  8172. && (typeof obj.lineNumber === 'number')
  8173. && (typeof obj.column === 'number'));
  8174. }
  8175. }
  8176. exports.Position = Position;
  8177. /***/ }),
  8178. /* 45 */
  8179. /***/ (function(module, exports, __webpack_require__) {
  8180. "use strict";
  8181. /*---------------------------------------------------------------------------------------------
  8182. * Copyright (c) Microsoft Corporation. All rights reserved.
  8183. * Licensed under the MIT License. See License.txt in the project root for license information.
  8184. *--------------------------------------------------------------------------------------------*/
  8185. Object.defineProperty(exports, "__esModule", { value: true });
  8186. class TreeNode {
  8187. constructor(piece, color) {
  8188. this.piece = piece;
  8189. this.color = color;
  8190. this.size_left = 0;
  8191. this.lf_left = 0;
  8192. this.parent = this;
  8193. this.left = this;
  8194. this.right = this;
  8195. }
  8196. next() {
  8197. if (this.right !== exports.SENTINEL) {
  8198. return leftest(this.right);
  8199. }
  8200. let node = this;
  8201. while (node.parent !== exports.SENTINEL) {
  8202. if (node.parent.left === node) {
  8203. break;
  8204. }
  8205. node = node.parent;
  8206. }
  8207. if (node.parent === exports.SENTINEL) {
  8208. return exports.SENTINEL;
  8209. }
  8210. else {
  8211. return node.parent;
  8212. }
  8213. }
  8214. prev() {
  8215. if (this.left !== exports.SENTINEL) {
  8216. return righttest(this.left);
  8217. }
  8218. let node = this;
  8219. while (node.parent !== exports.SENTINEL) {
  8220. if (node.parent.right === node) {
  8221. break;
  8222. }
  8223. node = node.parent;
  8224. }
  8225. if (node.parent === exports.SENTINEL) {
  8226. return exports.SENTINEL;
  8227. }
  8228. else {
  8229. return node.parent;
  8230. }
  8231. }
  8232. detach() {
  8233. this.parent = null;
  8234. this.left = null;
  8235. this.right = null;
  8236. }
  8237. }
  8238. exports.TreeNode = TreeNode;
  8239. exports.SENTINEL = new TreeNode(null, 0 /* Black */);
  8240. exports.SENTINEL.parent = exports.SENTINEL;
  8241. exports.SENTINEL.left = exports.SENTINEL;
  8242. exports.SENTINEL.right = exports.SENTINEL;
  8243. exports.SENTINEL.color = 0 /* Black */;
  8244. function leftest(node) {
  8245. while (node.left !== exports.SENTINEL) {
  8246. node = node.left;
  8247. }
  8248. return node;
  8249. }
  8250. exports.leftest = leftest;
  8251. function righttest(node) {
  8252. while (node.right !== exports.SENTINEL) {
  8253. node = node.right;
  8254. }
  8255. return node;
  8256. }
  8257. exports.righttest = righttest;
  8258. function calculateSize(node) {
  8259. if (node === exports.SENTINEL) {
  8260. return 0;
  8261. }
  8262. return node.size_left + node.piece.length + calculateSize(node.right);
  8263. }
  8264. exports.calculateSize = calculateSize;
  8265. function calculateLF(node) {
  8266. if (node === exports.SENTINEL) {
  8267. return 0;
  8268. }
  8269. return node.lf_left + node.piece.lineFeedCnt + calculateLF(node.right);
  8270. }
  8271. exports.calculateLF = calculateLF;
  8272. function resetSentinel() {
  8273. exports.SENTINEL.parent = exports.SENTINEL;
  8274. }
  8275. exports.resetSentinel = resetSentinel;
  8276. function leftRotate(tree, x) {
  8277. let y = x.right;
  8278. // fix size_left
  8279. y.size_left += x.size_left + (x.piece ? x.piece.length : 0);
  8280. y.lf_left += x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
  8281. x.right = y.left;
  8282. if (y.left !== exports.SENTINEL) {
  8283. y.left.parent = x;
  8284. }
  8285. y.parent = x.parent;
  8286. if (x.parent === exports.SENTINEL) {
  8287. tree.root = y;
  8288. }
  8289. else if (x.parent.left === x) {
  8290. x.parent.left = y;
  8291. }
  8292. else {
  8293. x.parent.right = y;
  8294. }
  8295. y.left = x;
  8296. x.parent = y;
  8297. }
  8298. exports.leftRotate = leftRotate;
  8299. function rightRotate(tree, y) {
  8300. let x = y.left;
  8301. y.left = x.right;
  8302. if (x.right !== exports.SENTINEL) {
  8303. x.right.parent = y;
  8304. }
  8305. x.parent = y.parent;
  8306. // fix size_left
  8307. y.size_left -= x.size_left + (x.piece ? x.piece.length : 0);
  8308. y.lf_left -= x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
  8309. if (y.parent === exports.SENTINEL) {
  8310. tree.root = x;
  8311. }
  8312. else if (y === y.parent.right) {
  8313. y.parent.right = x;
  8314. }
  8315. else {
  8316. y.parent.left = x;
  8317. }
  8318. x.right = y;
  8319. y.parent = x;
  8320. }
  8321. exports.rightRotate = rightRotate;
  8322. function rbDelete(tree, z) {
  8323. let x;
  8324. let y;
  8325. if (z.left === exports.SENTINEL) {
  8326. y = z;
  8327. x = y.right;
  8328. }
  8329. else if (z.right === exports.SENTINEL) {
  8330. y = z;
  8331. x = y.left;
  8332. }
  8333. else {
  8334. y = leftest(z.right);
  8335. x = y.right;
  8336. }
  8337. if (y === tree.root) {
  8338. tree.root = x;
  8339. // if x is null, we are removing the only node
  8340. x.color = 0 /* Black */;
  8341. z.detach();
  8342. resetSentinel();
  8343. tree.root.parent = exports.SENTINEL;
  8344. return;
  8345. }
  8346. let yWasRed = (y.color === 1 /* Red */);
  8347. if (y === y.parent.left) {
  8348. y.parent.left = x;
  8349. }
  8350. else {
  8351. y.parent.right = x;
  8352. }
  8353. if (y === z) {
  8354. x.parent = y.parent;
  8355. recomputeTreeMetadata(tree, x);
  8356. }
  8357. else {
  8358. if (y.parent === z) {
  8359. x.parent = y;
  8360. }
  8361. else {
  8362. x.parent = y.parent;
  8363. }
  8364. // as we make changes to x's hierarchy, update size_left of subtree first
  8365. recomputeTreeMetadata(tree, x);
  8366. y.left = z.left;
  8367. y.right = z.right;
  8368. y.parent = z.parent;
  8369. y.color = z.color;
  8370. if (z === tree.root) {
  8371. tree.root = y;
  8372. }
  8373. else {
  8374. if (z === z.parent.left) {
  8375. z.parent.left = y;
  8376. }
  8377. else {
  8378. z.parent.right = y;
  8379. }
  8380. }
  8381. if (y.left !== exports.SENTINEL) {
  8382. y.left.parent = y;
  8383. }
  8384. if (y.right !== exports.SENTINEL) {
  8385. y.right.parent = y;
  8386. }
  8387. // update metadata
  8388. // we replace z with y, so in this sub tree, the length change is z.item.length
  8389. y.size_left = z.size_left;
  8390. y.lf_left = z.lf_left;
  8391. recomputeTreeMetadata(tree, y);
  8392. }
  8393. z.detach();
  8394. if (x.parent.left === x) {
  8395. let newSizeLeft = calculateSize(x);
  8396. let newLFLeft = calculateLF(x);
  8397. if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) {
  8398. let delta = newSizeLeft - x.parent.size_left;
  8399. let lf_delta = newLFLeft - x.parent.lf_left;
  8400. x.parent.size_left = newSizeLeft;
  8401. x.parent.lf_left = newLFLeft;
  8402. updateTreeMetadata(tree, x.parent, delta, lf_delta);
  8403. }
  8404. }
  8405. recomputeTreeMetadata(tree, x.parent);
  8406. if (yWasRed) {
  8407. resetSentinel();
  8408. return;
  8409. }
  8410. // RB-DELETE-FIXUP
  8411. let w;
  8412. while (x !== tree.root && x.color === 0 /* Black */) {
  8413. if (x === x.parent.left) {
  8414. w = x.parent.right;
  8415. if (w.color === 1 /* Red */) {
  8416. w.color = 0 /* Black */;
  8417. x.parent.color = 1 /* Red */;
  8418. leftRotate(tree, x.parent);
  8419. w = x.parent.right;
  8420. }
  8421. if (w.left.color === 0 /* Black */ && w.right.color === 0 /* Black */) {
  8422. w.color = 1 /* Red */;
  8423. x = x.parent;
  8424. }
  8425. else {
  8426. if (w.right.color === 0 /* Black */) {
  8427. w.left.color = 0 /* Black */;
  8428. w.color = 1 /* Red */;
  8429. rightRotate(tree, w);
  8430. w = x.parent.right;
  8431. }
  8432. w.color = x.parent.color;
  8433. x.parent.color = 0 /* Black */;
  8434. w.right.color = 0 /* Black */;
  8435. leftRotate(tree, x.parent);
  8436. x = tree.root;
  8437. }
  8438. }
  8439. else {
  8440. w = x.parent.left;
  8441. if (w.color === 1 /* Red */) {
  8442. w.color = 0 /* Black */;
  8443. x.parent.color = 1 /* Red */;
  8444. rightRotate(tree, x.parent);
  8445. w = x.parent.left;
  8446. }
  8447. if (w.left.color === 0 /* Black */ && w.right.color === 0 /* Black */) {
  8448. w.color = 1 /* Red */;
  8449. x = x.parent;
  8450. }
  8451. else {
  8452. if (w.left.color === 0 /* Black */) {
  8453. w.right.color = 0 /* Black */;
  8454. w.color = 1 /* Red */;
  8455. leftRotate(tree, w);
  8456. w = x.parent.left;
  8457. }
  8458. w.color = x.parent.color;
  8459. x.parent.color = 0 /* Black */;
  8460. w.left.color = 0 /* Black */;
  8461. rightRotate(tree, x.parent);
  8462. x = tree.root;
  8463. }
  8464. }
  8465. }
  8466. x.color = 0 /* Black */;
  8467. resetSentinel();
  8468. }
  8469. exports.rbDelete = rbDelete;
  8470. function fixInsert(tree, x) {
  8471. recomputeTreeMetadata(tree, x);
  8472. while (x !== tree.root && x.parent.color === 1 /* Red */) {
  8473. if (x.parent === x.parent.parent.left) {
  8474. const y = x.parent.parent.right;
  8475. if (y.color === 1 /* Red */) {
  8476. x.parent.color = 0 /* Black */;
  8477. y.color = 0 /* Black */;
  8478. x.parent.parent.color = 1 /* Red */;
  8479. x = x.parent.parent;
  8480. }
  8481. else {
  8482. if (x === x.parent.right) {
  8483. x = x.parent;
  8484. leftRotate(tree, x);
  8485. }
  8486. x.parent.color = 0 /* Black */;
  8487. x.parent.parent.color = 1 /* Red */;
  8488. rightRotate(tree, x.parent.parent);
  8489. }
  8490. }
  8491. else {
  8492. const y = x.parent.parent.left;
  8493. if (y.color === 1 /* Red */) {
  8494. x.parent.color = 0 /* Black */;
  8495. y.color = 0 /* Black */;
  8496. x.parent.parent.color = 1 /* Red */;
  8497. x = x.parent.parent;
  8498. }
  8499. else {
  8500. if (x === x.parent.left) {
  8501. x = x.parent;
  8502. rightRotate(tree, x);
  8503. }
  8504. x.parent.color = 0 /* Black */;
  8505. x.parent.parent.color = 1 /* Red */;
  8506. leftRotate(tree, x.parent.parent);
  8507. }
  8508. }
  8509. }
  8510. tree.root.color = 0 /* Black */;
  8511. }
  8512. exports.fixInsert = fixInsert;
  8513. function updateTreeMetadata(tree, x, delta, lineFeedCntDelta) {
  8514. // node length change or line feed count change
  8515. while (x !== tree.root && x !== exports.SENTINEL) {
  8516. if (x.parent.left === x) {
  8517. x.parent.size_left += delta;
  8518. x.parent.lf_left += lineFeedCntDelta;
  8519. }
  8520. x = x.parent;
  8521. }
  8522. }
  8523. exports.updateTreeMetadata = updateTreeMetadata;
  8524. function recomputeTreeMetadata(tree, x) {
  8525. let delta = 0;
  8526. let lf_delta = 0;
  8527. if (x === tree.root) {
  8528. return;
  8529. }
  8530. if (delta === 0) {
  8531. // go upwards till the node whose left subtree is changed.
  8532. while (x !== tree.root && x === x.parent.right) {
  8533. x = x.parent;
  8534. }
  8535. if (x === tree.root) {
  8536. // well, it means we add a node to the end (inorder)
  8537. return;
  8538. }
  8539. // x is the node whose right subtree is changed.
  8540. x = x.parent;
  8541. delta = calculateSize(x.left) - x.size_left;
  8542. lf_delta = calculateLF(x.left) - x.lf_left;
  8543. x.size_left += delta;
  8544. x.lf_left += lf_delta;
  8545. }
  8546. // go upwards till root. O(logN)
  8547. while (x !== tree.root && (delta !== 0 || lf_delta !== 0)) {
  8548. if (x.parent.left === x) {
  8549. x.parent.size_left += delta;
  8550. x.parent.lf_left += lf_delta;
  8551. }
  8552. x = x.parent;
  8553. }
  8554. }
  8555. exports.recomputeTreeMetadata = recomputeTreeMetadata;
  8556. /***/ }),
  8557. /* 46 */
  8558. /***/ (function(module, exports, __webpack_require__) {
  8559. "use strict";
  8560. /*---------------------------------------------------------------------------------------------
  8561. * Copyright (c) Microsoft Corporation. All rights reserved.
  8562. * Licensed under the MIT License. See License.txt in the project root for license information.
  8563. *--------------------------------------------------------------------------------------------*/
  8564. Object.defineProperty(exports, "__esModule", { value: true });
  8565. const pieceTreeBase_1 = __webpack_require__(43);
  8566. exports.UTF8_BOM_CHARACTER = String.fromCharCode(65279 /* UTF8_BOM */);
  8567. function startsWithUTF8BOM(str) {
  8568. return !!(str && str.length > 0 && str.charCodeAt(0) === 65279 /* UTF8_BOM */);
  8569. }
  8570. exports.startsWithUTF8BOM = startsWithUTF8BOM;
  8571. class PieceTreeTextBufferFactory {
  8572. constructor(_chunks, _bom, _cr, _lf, _crlf, _normalizeEOL) {
  8573. this._chunks = _chunks;
  8574. this._bom = _bom;
  8575. this._cr = _cr;
  8576. this._lf = _lf;
  8577. this._crlf = _crlf;
  8578. this._normalizeEOL = _normalizeEOL;
  8579. }
  8580. _getEOL(defaultEOL) {
  8581. const totalEOLCount = this._cr + this._lf + this._crlf;
  8582. const totalCRCount = this._cr + this._crlf;
  8583. if (totalEOLCount === 0) {
  8584. // This is an empty file or a file with precisely one line
  8585. return (defaultEOL === 1 /* LF */ ? '\n' : '\r\n');
  8586. }
  8587. if (totalCRCount > totalEOLCount / 2) {
  8588. // More than half of the file contains \r\n ending lines
  8589. return '\r\n';
  8590. }
  8591. // At least one line more ends in \n
  8592. return '\n';
  8593. }
  8594. create(defaultEOL) {
  8595. const eol = this._getEOL(defaultEOL);
  8596. let chunks = this._chunks;
  8597. if (this._normalizeEOL &&
  8598. ((eol === '\r\n' && (this._cr > 0 || this._lf > 0))
  8599. || (eol === '\n' && (this._cr > 0 || this._crlf > 0)))) {
  8600. // Normalize pieces
  8601. for (let i = 0, len = chunks.length; i < len; i++) {
  8602. let str = chunks[i].buffer.replace(/\r\n|\r|\n/g, eol);
  8603. let newLineStart = pieceTreeBase_1.createLineStartsFast(str);
  8604. chunks[i] = new pieceTreeBase_1.StringBuffer(str, newLineStart);
  8605. }
  8606. }
  8607. return new pieceTreeBase_1.PieceTreeBase(chunks, eol, this._normalizeEOL);
  8608. }
  8609. getFirstLineText(lengthLimit) {
  8610. return this._chunks[0].buffer.substr(0, 100).split(/\r\n|\r|\n/)[0];
  8611. }
  8612. }
  8613. exports.PieceTreeTextBufferFactory = PieceTreeTextBufferFactory;
  8614. class PieceTreeTextBufferBuilder {
  8615. constructor() {
  8616. this.chunks = [];
  8617. this.BOM = '';
  8618. this._hasPreviousChar = false;
  8619. this._previousChar = 0;
  8620. this._tmpLineStarts = [];
  8621. this.cr = 0;
  8622. this.lf = 0;
  8623. this.crlf = 0;
  8624. }
  8625. acceptChunk(chunk) {
  8626. if (chunk.length === 0) {
  8627. return;
  8628. }
  8629. if (this.chunks.length === 0) {
  8630. if (startsWithUTF8BOM(chunk)) {
  8631. this.BOM = exports.UTF8_BOM_CHARACTER;
  8632. chunk = chunk.substr(1);
  8633. }
  8634. }
  8635. const lastChar = chunk.charCodeAt(chunk.length - 1);
  8636. if (lastChar === 13 /* CarriageReturn */ || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {
  8637. // last character is \r or a high surrogate => keep it back
  8638. this._acceptChunk1(chunk.substr(0, chunk.length - 1), false);
  8639. this._hasPreviousChar = true;
  8640. this._previousChar = lastChar;
  8641. }
  8642. else {
  8643. this._acceptChunk1(chunk, false);
  8644. this._hasPreviousChar = false;
  8645. this._previousChar = lastChar;
  8646. }
  8647. }
  8648. _acceptChunk1(chunk, allowEmptyStrings) {
  8649. if (!allowEmptyStrings && chunk.length === 0) {
  8650. // Nothing to do
  8651. return;
  8652. }
  8653. if (this._hasPreviousChar) {
  8654. this._acceptChunk2(String.fromCharCode(this._previousChar) + chunk);
  8655. }
  8656. else {
  8657. this._acceptChunk2(chunk);
  8658. }
  8659. }
  8660. _acceptChunk2(chunk) {
  8661. const lineStarts = pieceTreeBase_1.createLineStarts(this._tmpLineStarts, chunk);
  8662. this.chunks.push(new pieceTreeBase_1.StringBuffer(chunk, lineStarts.lineStarts));
  8663. this.cr += lineStarts.cr;
  8664. this.lf += lineStarts.lf;
  8665. this.crlf += lineStarts.crlf;
  8666. }
  8667. finish(normalizeEOL = true) {
  8668. this._finish();
  8669. return new PieceTreeTextBufferFactory(this.chunks, this.BOM, this.cr, this.lf, this.crlf, normalizeEOL);
  8670. }
  8671. _finish() {
  8672. if (this.chunks.length === 0) {
  8673. this._acceptChunk1('', true);
  8674. }
  8675. if (this._hasPreviousChar) {
  8676. this._hasPreviousChar = false;
  8677. // recreate last chunk
  8678. let lastChunk = this.chunks[this.chunks.length - 1];
  8679. lastChunk.buffer += String.fromCharCode(this._previousChar);
  8680. let newLineStarts = pieceTreeBase_1.createLineStartsFast(lastChunk.buffer);
  8681. lastChunk.lineStarts = newLineStarts;
  8682. if (this._previousChar === 13 /* CarriageReturn */) {
  8683. this.cr++;
  8684. }
  8685. }
  8686. }
  8687. }
  8688. exports.PieceTreeTextBufferBuilder = PieceTreeTextBufferBuilder;
  8689. /***/ }),
  8690. /* 47 */
  8691. /***/ (function(module, exports, __webpack_require__) {
  8692. "use strict";
  8693. /*---------------------------------------------------------------------------------------------
  8694. * Copyright (c) Microsoft Corporation. All rights reserved.
  8695. * Licensed under the MIT License. See License.txt in the project root for license information.
  8696. *--------------------------------------------------------------------------------------------*/
  8697. Object.defineProperty(exports, "__esModule", { value: true });
  8698. const position_1 = __webpack_require__(44);
  8699. /**
  8700. * A range in the editor. (startLineNumber,startColumn) is <= (endLineNumber,endColumn)
  8701. */
  8702. class Range {
  8703. constructor(startLineNumber, startColumn, endLineNumber, endColumn) {
  8704. if ((startLineNumber > endLineNumber) || (startLineNumber === endLineNumber && startColumn > endColumn)) {
  8705. this.startLineNumber = endLineNumber;
  8706. this.startColumn = endColumn;
  8707. this.endLineNumber = startLineNumber;
  8708. this.endColumn = startColumn;
  8709. }
  8710. else {
  8711. this.startLineNumber = startLineNumber;
  8712. this.startColumn = startColumn;
  8713. this.endLineNumber = endLineNumber;
  8714. this.endColumn = endColumn;
  8715. }
  8716. }
  8717. /**
  8718. * Test if this range is empty.
  8719. */
  8720. isEmpty() {
  8721. return Range.isEmpty(this);
  8722. }
  8723. /**
  8724. * Test if `range` is empty.
  8725. */
  8726. static isEmpty(range) {
  8727. return (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn);
  8728. }
  8729. /**
  8730. * Test if position is in this range. If the position is at the edges, will return true.
  8731. */
  8732. containsPosition(position) {
  8733. return Range.containsPosition(this, position);
  8734. }
  8735. /**
  8736. * Test if `position` is in `range`. If the position is at the edges, will return true.
  8737. */
  8738. static containsPosition(range, position) {
  8739. if (position.lineNumber < range.startLineNumber || position.lineNumber > range.endLineNumber) {
  8740. return false;
  8741. }
  8742. if (position.lineNumber === range.startLineNumber && position.column < range.startColumn) {
  8743. return false;
  8744. }
  8745. if (position.lineNumber === range.endLineNumber && position.column > range.endColumn) {
  8746. return false;
  8747. }
  8748. return true;
  8749. }
  8750. /**
  8751. * Test if range is in this range. If the range is equal to this range, will return true.
  8752. */
  8753. containsRange(range) {
  8754. return Range.containsRange(this, range);
  8755. }
  8756. /**
  8757. * Test if `otherRange` is in `range`. If the ranges are equal, will return true.
  8758. */
  8759. static containsRange(range, otherRange) {
  8760. if (otherRange.startLineNumber < range.startLineNumber || otherRange.endLineNumber < range.startLineNumber) {
  8761. return false;
  8762. }
  8763. if (otherRange.startLineNumber > range.endLineNumber || otherRange.endLineNumber > range.endLineNumber) {
  8764. return false;
  8765. }
  8766. if (otherRange.startLineNumber === range.startLineNumber && otherRange.startColumn < range.startColumn) {
  8767. return false;
  8768. }
  8769. if (otherRange.endLineNumber === range.endLineNumber && otherRange.endColumn > range.endColumn) {
  8770. return false;
  8771. }
  8772. return true;
  8773. }
  8774. /**
  8775. * A reunion of the two ranges.
  8776. * The smallest position will be used as the start point, and the largest one as the end point.
  8777. */
  8778. plusRange(range) {
  8779. return Range.plusRange(this, range);
  8780. }
  8781. /**
  8782. * A reunion of the two ranges.
  8783. * The smallest position will be used as the start point, and the largest one as the end point.
  8784. */
  8785. static plusRange(a, b) {
  8786. let startLineNumber;
  8787. let startColumn;
  8788. let endLineNumber;
  8789. let endColumn;
  8790. if (b.startLineNumber < a.startLineNumber) {
  8791. startLineNumber = b.startLineNumber;
  8792. startColumn = b.startColumn;
  8793. }
  8794. else if (b.startLineNumber === a.startLineNumber) {
  8795. startLineNumber = b.startLineNumber;
  8796. startColumn = Math.min(b.startColumn, a.startColumn);
  8797. }
  8798. else {
  8799. startLineNumber = a.startLineNumber;
  8800. startColumn = a.startColumn;
  8801. }
  8802. if (b.endLineNumber > a.endLineNumber) {
  8803. endLineNumber = b.endLineNumber;
  8804. endColumn = b.endColumn;
  8805. }
  8806. else if (b.endLineNumber === a.endLineNumber) {
  8807. endLineNumber = b.endLineNumber;
  8808. endColumn = Math.max(b.endColumn, a.endColumn);
  8809. }
  8810. else {
  8811. endLineNumber = a.endLineNumber;
  8812. endColumn = a.endColumn;
  8813. }
  8814. return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
  8815. }
  8816. /**
  8817. * A intersection of the two ranges.
  8818. */
  8819. intersectRanges(range) {
  8820. return Range.intersectRanges(this, range);
  8821. }
  8822. /**
  8823. * A intersection of the two ranges.
  8824. */
  8825. static intersectRanges(a, b) {
  8826. let resultStartLineNumber = a.startLineNumber;
  8827. let resultStartColumn = a.startColumn;
  8828. let resultEndLineNumber = a.endLineNumber;
  8829. let resultEndColumn = a.endColumn;
  8830. let otherStartLineNumber = b.startLineNumber;
  8831. let otherStartColumn = b.startColumn;
  8832. let otherEndLineNumber = b.endLineNumber;
  8833. let otherEndColumn = b.endColumn;
  8834. if (resultStartLineNumber < otherStartLineNumber) {
  8835. resultStartLineNumber = otherStartLineNumber;
  8836. resultStartColumn = otherStartColumn;
  8837. }
  8838. else if (resultStartLineNumber === otherStartLineNumber) {
  8839. resultStartColumn = Math.max(resultStartColumn, otherStartColumn);
  8840. }
  8841. if (resultEndLineNumber > otherEndLineNumber) {
  8842. resultEndLineNumber = otherEndLineNumber;
  8843. resultEndColumn = otherEndColumn;
  8844. }
  8845. else if (resultEndLineNumber === otherEndLineNumber) {
  8846. resultEndColumn = Math.min(resultEndColumn, otherEndColumn);
  8847. }
  8848. // Check if selection is now empty
  8849. if (resultStartLineNumber > resultEndLineNumber) {
  8850. return null;
  8851. }
  8852. if (resultStartLineNumber === resultEndLineNumber && resultStartColumn > resultEndColumn) {
  8853. return null;
  8854. }
  8855. return new Range(resultStartLineNumber, resultStartColumn, resultEndLineNumber, resultEndColumn);
  8856. }
  8857. /**
  8858. * Test if this range equals other.
  8859. */
  8860. equalsRange(other) {
  8861. return Range.equalsRange(this, other);
  8862. }
  8863. /**
  8864. * Test if range `a` equals `b`.
  8865. */
  8866. static equalsRange(a, b) {
  8867. return (!!a &&
  8868. !!b &&
  8869. a.startLineNumber === b.startLineNumber &&
  8870. a.startColumn === b.startColumn &&
  8871. a.endLineNumber === b.endLineNumber &&
  8872. a.endColumn === b.endColumn);
  8873. }
  8874. /**
  8875. * Return the end position (which will be after or equal to the start position)
  8876. */
  8877. getEndPosition() {
  8878. return new position_1.Position(this.endLineNumber, this.endColumn);
  8879. }
  8880. /**
  8881. * Return the start position (which will be before or equal to the end position)
  8882. */
  8883. getStartPosition() {
  8884. return new position_1.Position(this.startLineNumber, this.startColumn);
  8885. }
  8886. /**
  8887. * Transform to a user presentable string representation.
  8888. */
  8889. toString() {
  8890. return '[' + this.startLineNumber + ',' + this.startColumn + ' -> ' + this.endLineNumber + ',' + this.endColumn + ']';
  8891. }
  8892. /**
  8893. * Create a new range using this range's start position, and using endLineNumber and endColumn as the end position.
  8894. */
  8895. setEndPosition(endLineNumber, endColumn) {
  8896. return new Range(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
  8897. }
  8898. /**
  8899. * Create a new range using this range's end position, and using startLineNumber and startColumn as the start position.
  8900. */
  8901. setStartPosition(startLineNumber, startColumn) {
  8902. return new Range(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
  8903. }
  8904. /**
  8905. * Create a new empty range using this range's start position.
  8906. */
  8907. collapseToStart() {
  8908. return Range.collapseToStart(this);
  8909. }
  8910. /**
  8911. * Create a new empty range using this range's start position.
  8912. */
  8913. static collapseToStart(range) {
  8914. return new Range(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn);
  8915. }
  8916. // ---
  8917. static fromPositions(start, end = start) {
  8918. return new Range(start.lineNumber, start.column, end.lineNumber, end.column);
  8919. }
  8920. static lift(range) {
  8921. if (!range) {
  8922. return null;
  8923. }
  8924. return new Range(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
  8925. }
  8926. /**
  8927. * Test if `obj` is an `IRange`.
  8928. */
  8929. static isIRange(obj) {
  8930. return (obj
  8931. && (typeof obj.startLineNumber === 'number')
  8932. && (typeof obj.startColumn === 'number')
  8933. && (typeof obj.endLineNumber === 'number')
  8934. && (typeof obj.endColumn === 'number'));
  8935. }
  8936. /**
  8937. * Test if the two ranges are touching in any way.
  8938. */
  8939. static areIntersectingOrTouching(a, b) {
  8940. // Check if `a` is before `b`
  8941. if (a.endLineNumber < b.startLineNumber || (a.endLineNumber === b.startLineNumber && a.endColumn < b.startColumn)) {
  8942. return false;
  8943. }
  8944. // Check if `b` is before `a`
  8945. if (b.endLineNumber < a.startLineNumber || (b.endLineNumber === a.startLineNumber && b.endColumn < a.startColumn)) {
  8946. return false;
  8947. }
  8948. // These ranges must intersect
  8949. return true;
  8950. }
  8951. /**
  8952. * Test if the two ranges are intersecting. If the ranges are touching it returns true.
  8953. */
  8954. static areIntersecting(a, b) {
  8955. // Check if `a` is before `b`
  8956. if (a.endLineNumber < b.startLineNumber || (a.endLineNumber === b.startLineNumber && a.endColumn <= b.startColumn)) {
  8957. return false;
  8958. }
  8959. // Check if `b` is before `a`
  8960. if (b.endLineNumber < a.startLineNumber || (b.endLineNumber === a.startLineNumber && b.endColumn <= a.startColumn)) {
  8961. return false;
  8962. }
  8963. // These ranges must intersect
  8964. return true;
  8965. }
  8966. /**
  8967. * A function that compares ranges, useful for sorting ranges
  8968. * It will first compare ranges on the startPosition and then on the endPosition
  8969. */
  8970. static compareRangesUsingStarts(a, b) {
  8971. if (a && b) {
  8972. const aStartLineNumber = a.startLineNumber | 0;
  8973. const bStartLineNumber = b.startLineNumber | 0;
  8974. if (aStartLineNumber === bStartLineNumber) {
  8975. const aStartColumn = a.startColumn | 0;
  8976. const bStartColumn = b.startColumn | 0;
  8977. if (aStartColumn === bStartColumn) {
  8978. const aEndLineNumber = a.endLineNumber | 0;
  8979. const bEndLineNumber = b.endLineNumber | 0;
  8980. if (aEndLineNumber === bEndLineNumber) {
  8981. const aEndColumn = a.endColumn | 0;
  8982. const bEndColumn = b.endColumn | 0;
  8983. return aEndColumn - bEndColumn;
  8984. }
  8985. return aEndLineNumber - bEndLineNumber;
  8986. }
  8987. return aStartColumn - bStartColumn;
  8988. }
  8989. return aStartLineNumber - bStartLineNumber;
  8990. }
  8991. const aExists = (a ? 1 : 0);
  8992. const bExists = (b ? 1 : 0);
  8993. return aExists - bExists;
  8994. }
  8995. /**
  8996. * A function that compares ranges, useful for sorting ranges
  8997. * It will first compare ranges on the endPosition and then on the startPosition
  8998. */
  8999. static compareRangesUsingEnds(a, b) {
  9000. if (a.endLineNumber === b.endLineNumber) {
  9001. if (a.endColumn === b.endColumn) {
  9002. if (a.startLineNumber === b.startLineNumber) {
  9003. return a.startColumn - b.startColumn;
  9004. }
  9005. return a.startLineNumber - b.startLineNumber;
  9006. }
  9007. return a.endColumn - b.endColumn;
  9008. }
  9009. return a.endLineNumber - b.endLineNumber;
  9010. }
  9011. /**
  9012. * Test if the range spans multiple lines.
  9013. */
  9014. static spansMultipleLines(range) {
  9015. return range.endLineNumber > range.startLineNumber;
  9016. }
  9017. }
  9018. exports.Range = Range;
  9019. /***/ }),
  9020. /* 48 */
  9021. /***/ (function(module, exports, __webpack_require__) {
  9022. "use strict";
  9023. /* --------------------------------------------------------------------------------------------
  9024. * Copyright (c) Microsoft Corporation. All rights reserved.
  9025. * Licensed under the MIT License. See License.txt in the project root for license information.
  9026. * ------------------------------------------------------------------------------------------ */
  9027. Object.defineProperty(exports, "__esModule", { value: true });
  9028. const vscode_languageserver_protocol_1 = __webpack_require__(3);
  9029. const uuid_1 = __webpack_require__(38);
  9030. class ProgressImpl {
  9031. constructor(_connection, title, percentage, message, cancellable) {
  9032. this._connection = _connection;
  9033. this._id = uuid_1.generateUuid();
  9034. let params = {
  9035. id: this._id,
  9036. title,
  9037. cancellable
  9038. };
  9039. if (percentage !== undefined) {
  9040. params.percentage = percentage;
  9041. }
  9042. if (message !== undefined) {
  9043. params.message = message;
  9044. }
  9045. if (cancellable !== undefined) {
  9046. params.cancellable = cancellable;
  9047. }
  9048. ProgressImpl.Instances.set(this._id, this);
  9049. this._source = new vscode_languageserver_protocol_1.CancellationTokenSource();
  9050. this._connection.sendNotification(vscode_languageserver_protocol_1.Proposed.ProgressStartNotification.type, params);
  9051. }
  9052. get token() {
  9053. return this._source.token;
  9054. }
  9055. report(arg0, arg1) {
  9056. let percentage;
  9057. let message;
  9058. if (typeof arg0 === 'number') {
  9059. percentage = arg0;
  9060. if (arg1 !== undefined) {
  9061. message = arg1;
  9062. }
  9063. }
  9064. else {
  9065. message = arg0;
  9066. }
  9067. this._connection.sendNotification(vscode_languageserver_protocol_1.Proposed.ProgressReportNotification.type, { id: this._id, percentage, message });
  9068. }
  9069. done() {
  9070. ProgressImpl.Instances.delete(this._id);
  9071. this._source.dispose();
  9072. this._connection.sendNotification(vscode_languageserver_protocol_1.Proposed.ProgressDoneNotification.type, { id: this._id });
  9073. }
  9074. cancel() {
  9075. this._source.cancel();
  9076. }
  9077. }
  9078. ProgressImpl.Instances = new Map();
  9079. class NullProgress {
  9080. constructor() {
  9081. this._source = new vscode_languageserver_protocol_1.CancellationTokenSource();
  9082. }
  9083. get token() {
  9084. return this._source.token;
  9085. }
  9086. report() {
  9087. }
  9088. done() {
  9089. }
  9090. }
  9091. exports.ProgressFeature = (Base) => {
  9092. return class extends Base {
  9093. initialize(cap) {
  9094. let capabilities = cap;
  9095. if (capabilities.window && capabilities.window.progress) {
  9096. this._progressSupported = true;
  9097. this.connection.onNotification(vscode_languageserver_protocol_1.Proposed.ProgressCancelNotification.type, (params) => {
  9098. let progress = ProgressImpl.Instances.get(params.id);
  9099. if (progress !== undefined) {
  9100. progress.cancel();
  9101. }
  9102. });
  9103. }
  9104. }
  9105. createProgress(title, percentage, message, cancellable) {
  9106. if (this._progressSupported) {
  9107. return new ProgressImpl(this.connection, title, percentage, message, cancellable);
  9108. }
  9109. else {
  9110. return new NullProgress();
  9111. }
  9112. }
  9113. };
  9114. };
  9115. /***/ }),
  9116. /* 49 */
  9117. /***/ (function(module, exports, __webpack_require__) {
  9118. "use strict";
  9119. /*---------------------------------------------------------------------------------------------
  9120. * Copyright (c) Microsoft Corporation. All rights reserved.
  9121. * Licensed under the MIT License. See License.txt in the project root for license information.
  9122. *--------------------------------------------------------------------------------------------*/
  9123. Object.defineProperty(exports, "__esModule", { value: true });
  9124. var url_1 = __webpack_require__(40);
  9125. var https = __webpack_require__(50);
  9126. var http = __webpack_require__(51);
  9127. var HttpProxyAgent = __webpack_require__(52);
  9128. var HttpsProxyAgent = __webpack_require__(69);
  9129. var zlib = __webpack_require__(75);
  9130. var nls = __webpack_require__(76);
  9131. nls.config(process.env['VSCODE_NLS_CONFIG']);
  9132. var localize = nls.loadMessageBundle();
  9133. var proxyUrl = null;
  9134. var strictSSL = true;
  9135. function configure(_proxyUrl, _strictSSL) {
  9136. proxyUrl = _proxyUrl;
  9137. strictSSL = _strictSSL;
  9138. }
  9139. exports.configure = configure;
  9140. function xhr(options) {
  9141. var agent = getProxyAgent(options.url, { proxyUrl: proxyUrl, strictSSL: strictSSL });
  9142. options = assign({}, options);
  9143. options = assign(options, { agent: agent, strictSSL: strictSSL });
  9144. if (typeof options.followRedirects !== 'number') {
  9145. options.followRedirects = 5;
  9146. }
  9147. return request(options).then(function (result) { return new Promise(function (c, e) {
  9148. var res = result.res;
  9149. var readable = res;
  9150. var encoding = res.headers && res.headers['content-encoding'];
  9151. var isCompleted = false;
  9152. if (encoding === 'gzip') {
  9153. var gunzip = zlib.createGunzip();
  9154. res.pipe(gunzip);
  9155. readable = gunzip;
  9156. }
  9157. else if (encoding === 'deflate') {
  9158. var inflate = zlib.createInflate();
  9159. res.pipe(inflate);
  9160. readable = inflate;
  9161. }
  9162. var data = [];
  9163. readable.on('data', function (c) { return data.push(c); });
  9164. readable.on('end', function () {
  9165. if (isCompleted) {
  9166. return;
  9167. }
  9168. isCompleted = true;
  9169. if (options.followRedirects > 0 && (res.statusCode >= 300 && res.statusCode <= 303 || res.statusCode === 307)) {
  9170. var location = res.headers['location'];
  9171. if (location) {
  9172. var newOptions = {
  9173. type: options.type, url: location, user: options.user, password: options.password, responseType: options.responseType, headers: options.headers,
  9174. timeout: options.timeout, followRedirects: options.followRedirects - 1, data: options.data
  9175. };
  9176. xhr(newOptions).then(c, e);
  9177. return;
  9178. }
  9179. }
  9180. var response = {
  9181. responseText: data.join(''),
  9182. status: res.statusCode
  9183. };
  9184. if ((res.statusCode >= 200 && res.statusCode < 300) || res.statusCode === 1223) {
  9185. c(response);
  9186. }
  9187. else {
  9188. e(response);
  9189. }
  9190. });
  9191. readable.on('error', function (err) {
  9192. var response = {
  9193. responseText: localize('error', 'Unable to access {0}. Error: {1}', options.url, err.message),
  9194. status: 500
  9195. };
  9196. isCompleted = true;
  9197. e(response);
  9198. });
  9199. }); }, function (err) {
  9200. var message;
  9201. if (agent) {
  9202. message = localize('error.cannot.connect.proxy', 'Unable to connect to {0} through a proxy . Error: {1}', options.url, err.message);
  9203. }
  9204. else {
  9205. message = localize('error.cannot.connect', 'Unable to connect to {0}. Error: {1}', options.url, err.message);
  9206. }
  9207. return Promise.reject({
  9208. responseText: message,
  9209. status: 404
  9210. });
  9211. });
  9212. }
  9213. exports.xhr = xhr;
  9214. function assign(destination) {
  9215. var sources = [];
  9216. for (var _i = 1; _i < arguments.length; _i++) {
  9217. sources[_i - 1] = arguments[_i];
  9218. }
  9219. sources.forEach(function (source) { return Object.keys(source).forEach(function (key) { return destination[key] = source[key]; }); });
  9220. return destination;
  9221. }
  9222. function request(options) {
  9223. var req;
  9224. return new Promise(function (c, e) {
  9225. var endpoint = url_1.parse(options.url);
  9226. var opts = {
  9227. hostname: endpoint.hostname,
  9228. port: endpoint.port ? parseInt(endpoint.port) : (endpoint.protocol === 'https:' ? 443 : 80),
  9229. path: endpoint.path,
  9230. method: options.type || 'GET',
  9231. headers: options.headers,
  9232. agent: options.agent,
  9233. rejectUnauthorized: (typeof options.strictSSL === 'boolean') ? options.strictSSL : true
  9234. };
  9235. if (options.user && options.password) {
  9236. opts.auth = options.user + ':' + options.password;
  9237. }
  9238. var handler = function (res) {
  9239. if (res.statusCode >= 300 && res.statusCode < 400 && options.followRedirects && options.followRedirects > 0 && res.headers['location']) {
  9240. c(request(assign({}, options, {
  9241. url: res.headers['location'],
  9242. followRedirects: options.followRedirects - 1
  9243. })));
  9244. }
  9245. else {
  9246. c({ req: req, res: res });
  9247. }
  9248. };
  9249. if (endpoint.protocol === 'https:') {
  9250. req = https.request(opts, handler);
  9251. }
  9252. else {
  9253. req = http.request(opts, handler);
  9254. }
  9255. req.on('error', e);
  9256. if (options.timeout) {
  9257. req.setTimeout(options.timeout);
  9258. }
  9259. if (options.data) {
  9260. req.write(options.data);
  9261. }
  9262. req.end();
  9263. });
  9264. }
  9265. function getErrorStatusDescription(status) {
  9266. if (status < 400) {
  9267. return void 0;
  9268. }
  9269. switch (status) {
  9270. case 400: return localize('status.400', 'Bad request. The request cannot be fulfilled due to bad syntax.');
  9271. case 401: return localize('status.401', 'Unauthorized. The server is refusing to respond.');
  9272. case 403: return localize('status.403', 'Forbidden. The server is refusing to respond.');
  9273. case 404: return localize('status.404', 'Not Found. The requested location could not be found.');
  9274. case 405: return localize('status.405', 'Method not allowed. A request was made using a request method not supported by that location.');
  9275. case 406: return localize('status.406', 'Not Acceptable. The server can only generate a response that is not accepted by the client.');
  9276. case 407: return localize('status.407', 'Proxy Authentication Required. The client must first authenticate itself with the proxy.');
  9277. case 408: return localize('status.408', 'Request Timeout. The server timed out waiting for the request.');
  9278. case 409: return localize('status.409', 'Conflict. The request could not be completed because of a conflict in the request.');
  9279. case 410: return localize('status.410', 'Gone. The requested page is no longer available.');
  9280. case 411: return localize('status.411', 'Length Required. The "Content-Length" is not defined.');
  9281. case 412: return localize('status.412', 'Precondition Failed. The precondition given in the request evaluated to false by the server.');
  9282. case 413: return localize('status.413', 'Request Entity Too Large. The server will not accept the request, because the request entity is too large.');
  9283. case 414: return localize('status.414', 'Request-URI Too Long. The server will not accept the request, because the URL is too long.');
  9284. case 415: return localize('status.415', 'Unsupported Media Type. The server will not accept the request, because the media type is not supported.');
  9285. case 500: return localize('status.500', 'Internal Server Error.');
  9286. case 501: return localize('status.501', 'Not Implemented. The server either does not recognize the request method, or it lacks the ability to fulfill the request.');
  9287. case 503: return localize('status.503', 'Service Unavailable. The server is currently unavailable (overloaded or down).');
  9288. default: return localize('status.416', 'HTTP status code {0}', status);
  9289. }
  9290. }
  9291. exports.getErrorStatusDescription = getErrorStatusDescription;
  9292. // proxy handling
  9293. function getSystemProxyURI(requestURL) {
  9294. if (requestURL.protocol === 'http:') {
  9295. return process.env.HTTP_PROXY || process.env.http_proxy || null;
  9296. }
  9297. else if (requestURL.protocol === 'https:') {
  9298. return process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null;
  9299. }
  9300. return null;
  9301. }
  9302. function getProxyAgent(rawRequestURL, options) {
  9303. if (options === void 0) { options = {}; }
  9304. var requestURL = url_1.parse(rawRequestURL);
  9305. var proxyURL = options.proxyUrl || getSystemProxyURI(requestURL);
  9306. if (!proxyURL) {
  9307. return null;
  9308. }
  9309. var proxyEndpoint = url_1.parse(proxyURL);
  9310. if (!/^https?:$/.test(proxyEndpoint.protocol)) {
  9311. return null;
  9312. }
  9313. var opts = {
  9314. host: proxyEndpoint.hostname,
  9315. port: Number(proxyEndpoint.port),
  9316. auth: proxyEndpoint.auth,
  9317. rejectUnauthorized: (typeof options.strictSSL === 'boolean') ? options.strictSSL : true
  9318. };
  9319. return requestURL.protocol === 'http:' ? new HttpProxyAgent(opts) : new HttpsProxyAgent(opts);
  9320. }
  9321. //# sourceMappingURL=main.js.map
  9322. /***/ }),
  9323. /* 50 */
  9324. /***/ (function(module, exports) {
  9325. module.exports = require("https");
  9326. /***/ }),
  9327. /* 51 */
  9328. /***/ (function(module, exports) {
  9329. module.exports = require("http");
  9330. /***/ }),
  9331. /* 52 */
  9332. /***/ (function(module, exports, __webpack_require__) {
  9333. /**
  9334. * Module dependencies.
  9335. */
  9336. var net = __webpack_require__(15);
  9337. var tls = __webpack_require__(53);
  9338. var url = __webpack_require__(40);
  9339. var Agent = __webpack_require__(54);
  9340. var inherits = __webpack_require__(56).inherits;
  9341. var debug = __webpack_require__(61)('http-proxy-agent');
  9342. /**
  9343. * Module exports.
  9344. */
  9345. module.exports = HttpProxyAgent;
  9346. /**
  9347. * The `HttpProxyAgent` implements an HTTP Agent subclass that connects to the
  9348. * specified "HTTP proxy server" in order to proxy HTTP requests.
  9349. *
  9350. * @api public
  9351. */
  9352. function HttpProxyAgent (opts) {
  9353. if (!(this instanceof HttpProxyAgent)) return new HttpProxyAgent(opts);
  9354. if ('string' == typeof opts) opts = url.parse(opts);
  9355. if (!opts) throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');
  9356. debug('creating new HttpProxyAgent instance: %o', opts);
  9357. Agent.call(this, opts);
  9358. var proxy = Object.assign({}, opts);
  9359. // if `true`, then connect to the proxy server over TLS. defaults to `false`.
  9360. this.secureProxy = proxy.protocol ? /^https:?$/i.test(proxy.protocol) : false;
  9361. // prefer `hostname` over `host`, and set the `port` if needed
  9362. proxy.host = proxy.hostname || proxy.host;
  9363. proxy.port = +proxy.port || (this.secureProxy ? 443 : 80);
  9364. if (proxy.host && proxy.path) {
  9365. // if both a `host` and `path` are specified then it's most likely the
  9366. // result of a `url.parse()` call... we need to remove the `path` portion so
  9367. // that `net.connect()` doesn't attempt to open that as a unix socket file.
  9368. delete proxy.path;
  9369. delete proxy.pathname;
  9370. }
  9371. this.proxy = proxy;
  9372. }
  9373. inherits(HttpProxyAgent, Agent);
  9374. /**
  9375. * Called when the node-core HTTP client library is creating a new HTTP request.
  9376. *
  9377. * @api public
  9378. */
  9379. HttpProxyAgent.prototype.callback = function connect (req, opts, fn) {
  9380. var proxy = this.proxy;
  9381. // change the `http.ClientRequest` instance's "path" field
  9382. // to the absolute path of the URL that will be requested
  9383. var parsed = url.parse(req.path);
  9384. if (null == parsed.protocol) parsed.protocol = 'http:';
  9385. if (null == parsed.hostname) parsed.hostname = opts.hostname || opts.host;
  9386. if (null == parsed.port) parsed.port = opts.port;
  9387. if (parsed.port == 80) {
  9388. // if port is 80, then we can remove the port so that the
  9389. // ":80" portion is not on the produced URL
  9390. delete parsed.port;
  9391. }
  9392. var absolute = url.format(parsed);
  9393. req.path = absolute;
  9394. // inject the `Proxy-Authorization` header if necessary
  9395. if (proxy.auth) {
  9396. req.setHeader(
  9397. 'Proxy-Authorization',
  9398. 'Basic ' + Buffer.from(proxy.auth).toString('base64')
  9399. );
  9400. }
  9401. // create a socket connection to the proxy server
  9402. var socket;
  9403. if (this.secureProxy) {
  9404. socket = tls.connect(proxy);
  9405. } else {
  9406. socket = net.connect(proxy);
  9407. }
  9408. // at this point, the http ClientRequest's internal `_header` field might have
  9409. // already been set. If this is the case then we'll need to re-generate the
  9410. // string since we just changed the `req.path`
  9411. if (req._header) {
  9412. debug('regenerating stored HTTP header string for request');
  9413. req._header = null;
  9414. req._implicitHeader();
  9415. if (req.output && req.output.length > 0) {
  9416. debug('patching connection write() output buffer with updated header');
  9417. // the _header has already been queued to be written to the socket
  9418. var first = req.output[0];
  9419. var endOfHeaders = first.indexOf('\r\n\r\n') + 4;
  9420. req.output[0] = req._header + first.substring(endOfHeaders);
  9421. debug('output buffer: %o', req.output);
  9422. }
  9423. }
  9424. fn(null, socket);
  9425. };
  9426. /***/ }),
  9427. /* 53 */
  9428. /***/ (function(module, exports) {
  9429. module.exports = require("tls");
  9430. /***/ }),
  9431. /* 54 */
  9432. /***/ (function(module, exports, __webpack_require__) {
  9433. "use strict";
  9434. __webpack_require__(55);
  9435. const inherits = __webpack_require__(56).inherits;
  9436. const promisify = __webpack_require__(57);
  9437. const EventEmitter = __webpack_require__(60).EventEmitter;
  9438. module.exports = Agent;
  9439. function isAgent(v) {
  9440. return v && typeof v.addRequest === 'function';
  9441. }
  9442. /**
  9443. * Base `http.Agent` implementation.
  9444. * No pooling/keep-alive is implemented by default.
  9445. *
  9446. * @param {Function} callback
  9447. * @api public
  9448. */
  9449. function Agent(callback, _opts) {
  9450. if (!(this instanceof Agent)) {
  9451. return new Agent(callback, _opts);
  9452. }
  9453. EventEmitter.call(this);
  9454. // The callback gets promisified if it has 3 parameters
  9455. // (i.e. it has a callback function) lazily
  9456. this._promisifiedCallback = false;
  9457. let opts = _opts;
  9458. if ('function' === typeof callback) {
  9459. this.callback = callback;
  9460. } else if (callback) {
  9461. opts = callback;
  9462. }
  9463. // timeout for the socket to be returned from the callback
  9464. this.timeout = (opts && opts.timeout) || null;
  9465. this.options = opts;
  9466. }
  9467. inherits(Agent, EventEmitter);
  9468. /**
  9469. * Override this function in your subclass!
  9470. */
  9471. Agent.prototype.callback = function callback(req, opts) {
  9472. throw new Error(
  9473. '"agent-base" has no default implementation, you must subclass and override `callback()`'
  9474. );
  9475. };
  9476. /**
  9477. * Called by node-core's "_http_client.js" module when creating
  9478. * a new HTTP request with this Agent instance.
  9479. *
  9480. * @api public
  9481. */
  9482. Agent.prototype.addRequest = function addRequest(req, _opts) {
  9483. const ownOpts = Object.assign({}, _opts);
  9484. // Set default `host` for HTTP to localhost
  9485. if (null == ownOpts.host) {
  9486. ownOpts.host = 'localhost';
  9487. }
  9488. // Set default `port` for HTTP if none was explicitly specified
  9489. if (null == ownOpts.port) {
  9490. ownOpts.port = ownOpts.secureEndpoint ? 443 : 80;
  9491. }
  9492. const opts = Object.assign({}, this.options, ownOpts);
  9493. if (opts.host && opts.path) {
  9494. // If both a `host` and `path` are specified then it's most likely the
  9495. // result of a `url.parse()` call... we need to remove the `path` portion so
  9496. // that `net.connect()` doesn't attempt to open that as a unix socket file.
  9497. delete opts.path;
  9498. }
  9499. delete opts.agent;
  9500. delete opts.hostname;
  9501. delete opts._defaultAgent;
  9502. delete opts.defaultPort;
  9503. delete opts.createConnection;
  9504. // Hint to use "Connection: close"
  9505. // XXX: non-documented `http` module API :(
  9506. req._last = true;
  9507. req.shouldKeepAlive = false;
  9508. // Create the `stream.Duplex` instance
  9509. let timeout;
  9510. let timedOut = false;
  9511. const timeoutMs = this.timeout;
  9512. const freeSocket = this.freeSocket;
  9513. function onerror(err) {
  9514. if (req._hadError) return;
  9515. req.emit('error', err);
  9516. // For Safety. Some additional errors might fire later on
  9517. // and we need to make sure we don't double-fire the error event.
  9518. req._hadError = true;
  9519. }
  9520. function ontimeout() {
  9521. timeout = null;
  9522. timedOut = true;
  9523. const err = new Error(
  9524. 'A "socket" was not created for HTTP request before ' + timeoutMs + 'ms'
  9525. );
  9526. err.code = 'ETIMEOUT';
  9527. onerror(err);
  9528. }
  9529. function callbackError(err) {
  9530. if (timedOut) return;
  9531. if (timeout != null) {
  9532. clearTimeout(timeout);
  9533. timeout = null;
  9534. }
  9535. onerror(err);
  9536. }
  9537. function onsocket(socket) {
  9538. if (timedOut) return;
  9539. if (timeout != null) {
  9540. clearTimeout(timeout);
  9541. timeout = null;
  9542. }
  9543. if (isAgent(socket)) {
  9544. // `socket` is actually an http.Agent instance, so relinquish
  9545. // responsibility for this `req` to the Agent from here on
  9546. socket.addRequest(req, opts);
  9547. } else if (socket) {
  9548. function onfree() {
  9549. freeSocket(socket, opts);
  9550. }
  9551. socket.on('free', onfree);
  9552. req.onSocket(socket);
  9553. } else {
  9554. const err = new Error(
  9555. 'no Duplex stream was returned to agent-base for `' + req.method + ' ' + req.path + '`'
  9556. );
  9557. onerror(err);
  9558. }
  9559. }
  9560. if (!this._promisifiedCallback && this.callback.length >= 3) {
  9561. // Legacy callback function - convert to a Promise
  9562. this.callback = promisify(this.callback, this);
  9563. this._promisifiedCallback = true;
  9564. }
  9565. if (timeoutMs > 0) {
  9566. timeout = setTimeout(ontimeout, timeoutMs);
  9567. }
  9568. try {
  9569. Promise.resolve(this.callback(req, opts)).then(onsocket, callbackError);
  9570. } catch (err) {
  9571. Promise.reject(err).catch(callbackError);
  9572. }
  9573. };
  9574. Agent.prototype.freeSocket = function freeSocket(socket, opts) {
  9575. // TODO reuse sockets
  9576. socket.destroy();
  9577. };
  9578. /***/ }),
  9579. /* 55 */
  9580. /***/ (function(module, exports, __webpack_require__) {
  9581. "use strict";
  9582. const url = __webpack_require__(40);
  9583. const https = __webpack_require__(50);
  9584. /**
  9585. * This currently needs to be applied to all Node.js versions
  9586. * in order to determine if the `req` is an HTTP or HTTPS request.
  9587. *
  9588. * There is currently no PR attempting to move this property upstream.
  9589. */
  9590. const patchMarker = "__agent_base_https_request_patched__";
  9591. if (!https.request[patchMarker]) {
  9592. https.request = (function(request) {
  9593. return function(_options, cb) {
  9594. let options;
  9595. if (typeof _options === 'string') {
  9596. options = url.parse(_options);
  9597. } else {
  9598. options = Object.assign({}, _options);
  9599. }
  9600. if (null == options.port) {
  9601. options.port = 443;
  9602. }
  9603. options.secureEndpoint = true;
  9604. return request.call(https, options, cb);
  9605. };
  9606. })(https.request);
  9607. https.request[patchMarker] = true;
  9608. }
  9609. /**
  9610. * This is needed for Node.js >= 9.0.0 to make sure `https.get()` uses the
  9611. * patched `https.request()`.
  9612. *
  9613. * Ref: https://github.com/nodejs/node/commit/5118f31
  9614. */
  9615. https.get = function (_url, _options, cb) {
  9616. let options;
  9617. if (typeof _url === 'string' && _options && typeof _options !== 'function') {
  9618. options = Object.assign({}, url.parse(_url), _options);
  9619. } else if (!_options && !cb) {
  9620. options = _url;
  9621. } else if (!cb) {
  9622. options = _url;
  9623. cb = _options;
  9624. }
  9625. const req = https.request(options, cb);
  9626. req.end();
  9627. return req;
  9628. };
  9629. /***/ }),
  9630. /* 56 */
  9631. /***/ (function(module, exports) {
  9632. module.exports = require("util");
  9633. /***/ }),
  9634. /* 57 */
  9635. /***/ (function(module, exports, __webpack_require__) {
  9636. "use strict";
  9637. /* global module, require */
  9638. module.exports = function () {
  9639. "use strict";
  9640. // Get a promise object. This may be native, or it may be polyfilled
  9641. var ES6Promise = __webpack_require__(58);
  9642. /**
  9643. * thatLooksLikeAPromiseToMe()
  9644. *
  9645. * Duck-types a promise.
  9646. *
  9647. * @param {object} o
  9648. * @return {bool} True if this resembles a promise
  9649. */
  9650. function thatLooksLikeAPromiseToMe(o) {
  9651. return o && typeof o.then === "function" && typeof o.catch === "function";
  9652. }
  9653. /**
  9654. * promisify()
  9655. *
  9656. * Transforms callback-based function -- func(arg1, arg2 .. argN, callback) -- into
  9657. * an ES6-compatible Promise. Promisify provides a default callback of the form (error, result)
  9658. * and rejects when `error` is truthy. You can also supply settings object as the second argument.
  9659. *
  9660. * @param {function} original - The function to promisify
  9661. * @param {object} settings - Settings object
  9662. * @param {object} settings.thisArg - A `this` context to use. If not set, assume `settings` _is_ `thisArg`
  9663. * @param {bool} settings.multiArgs - Should multiple arguments be returned as an array?
  9664. * @return {function} A promisified version of `original`
  9665. */
  9666. return function promisify(original, settings) {
  9667. return function () {
  9668. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  9669. args[_key] = arguments[_key];
  9670. }
  9671. var returnMultipleArguments = settings && settings.multiArgs;
  9672. var target = void 0;
  9673. if (settings && settings.thisArg) {
  9674. target = settings.thisArg;
  9675. } else if (settings) {
  9676. target = settings;
  9677. }
  9678. // Return the promisified function
  9679. return new ES6Promise(function (resolve, reject) {
  9680. // Append the callback bound to the context
  9681. args.push(function callback(err) {
  9682. if (err) {
  9683. return reject(err);
  9684. }
  9685. for (var _len2 = arguments.length, values = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  9686. values[_key2 - 1] = arguments[_key2];
  9687. }
  9688. if (false === !!returnMultipleArguments) {
  9689. return resolve(values[0]);
  9690. }
  9691. resolve(values);
  9692. });
  9693. // Call the function
  9694. var response = original.apply(target, args);
  9695. // If it looks like original already returns a promise,
  9696. // then just resolve with that promise. Hopefully, the callback function we added will just be ignored.
  9697. if (thatLooksLikeAPromiseToMe(response)) {
  9698. resolve(response);
  9699. }
  9700. });
  9701. };
  9702. };
  9703. }();
  9704. /***/ }),
  9705. /* 58 */
  9706. /***/ (function(module, exports, __webpack_require__) {
  9707. "use strict";
  9708. /* global self, window, module, global, require */
  9709. module.exports = function () {
  9710. "use strict";
  9711. var globalObject = void 0;
  9712. function isFunction(x) {
  9713. return typeof x === "function";
  9714. }
  9715. // Seek the global object
  9716. if (global !== undefined) {
  9717. globalObject = global;
  9718. } else if (window !== undefined && window.document) {
  9719. globalObject = window;
  9720. } else {
  9721. globalObject = self;
  9722. }
  9723. // Test for any native promise implementation, and if that
  9724. // implementation appears to conform to the specificaton.
  9725. // This code mostly nicked from the es6-promise module polyfill
  9726. // and then fooled with.
  9727. var hasPromiseSupport = function () {
  9728. // No promise object at all, and it's a non-starter
  9729. if (!globalObject.hasOwnProperty("Promise")) {
  9730. return false;
  9731. }
  9732. // There is a Promise object. Does it conform to the spec?
  9733. var P = globalObject.Promise;
  9734. // Some of these methods are missing from
  9735. // Firefox/Chrome experimental implementations
  9736. if (!P.hasOwnProperty("resolve") || !P.hasOwnProperty("reject")) {
  9737. return false;
  9738. }
  9739. if (!P.hasOwnProperty("all") || !P.hasOwnProperty("race")) {
  9740. return false;
  9741. }
  9742. // Older version of the spec had a resolver object
  9743. // as the arg rather than a function
  9744. return function () {
  9745. var resolve = void 0;
  9746. var p = new globalObject.Promise(function (r) {
  9747. resolve = r;
  9748. });
  9749. if (p) {
  9750. return isFunction(resolve);
  9751. }
  9752. return false;
  9753. }();
  9754. }();
  9755. // Export the native Promise implementation if it
  9756. // looks like it matches the spec
  9757. if (hasPromiseSupport) {
  9758. return globalObject.Promise;
  9759. }
  9760. // Otherwise, return the es6-promise polyfill by @jaffathecake.
  9761. return __webpack_require__(59).Promise;
  9762. }();
  9763. /***/ }),
  9764. /* 59 */
  9765. /***/ (function(module, exports, __webpack_require__) {
  9766. /*!
  9767. * @overview es6-promise - a tiny implementation of Promises/A+.
  9768. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  9769. * @license Licensed under MIT license
  9770. * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
  9771. * @version v4.2.8+1e68dce6
  9772. */
  9773. (function (global, factory) {
  9774. true ? module.exports = factory() :
  9775. undefined;
  9776. }(this, (function () { 'use strict';
  9777. function objectOrFunction(x) {
  9778. var type = typeof x;
  9779. return x !== null && (type === 'object' || type === 'function');
  9780. }
  9781. function isFunction(x) {
  9782. return typeof x === 'function';
  9783. }
  9784. var _isArray = void 0;
  9785. if (Array.isArray) {
  9786. _isArray = Array.isArray;
  9787. } else {
  9788. _isArray = function (x) {
  9789. return Object.prototype.toString.call(x) === '[object Array]';
  9790. };
  9791. }
  9792. var isArray = _isArray;
  9793. var len = 0;
  9794. var vertxNext = void 0;
  9795. var customSchedulerFn = void 0;
  9796. var asap = function asap(callback, arg) {
  9797. queue[len] = callback;
  9798. queue[len + 1] = arg;
  9799. len += 2;
  9800. if (len === 2) {
  9801. // If len is 2, that means that we need to schedule an async flush.
  9802. // If additional callbacks are queued before the queue is flushed, they
  9803. // will be processed by this flush that we are scheduling.
  9804. if (customSchedulerFn) {
  9805. customSchedulerFn(flush);
  9806. } else {
  9807. scheduleFlush();
  9808. }
  9809. }
  9810. };
  9811. function setScheduler(scheduleFn) {
  9812. customSchedulerFn = scheduleFn;
  9813. }
  9814. function setAsap(asapFn) {
  9815. asap = asapFn;
  9816. }
  9817. var browserWindow = typeof window !== 'undefined' ? window : undefined;
  9818. var browserGlobal = browserWindow || {};
  9819. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  9820. var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  9821. // test for web worker but not in IE10
  9822. var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
  9823. // node
  9824. function useNextTick() {
  9825. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  9826. // see https://github.com/cujojs/when/issues/410 for details
  9827. return function () {
  9828. return process.nextTick(flush);
  9829. };
  9830. }
  9831. // vertx
  9832. function useVertxTimer() {
  9833. if (typeof vertxNext !== 'undefined') {
  9834. return function () {
  9835. vertxNext(flush);
  9836. };
  9837. }
  9838. return useSetTimeout();
  9839. }
  9840. function useMutationObserver() {
  9841. var iterations = 0;
  9842. var observer = new BrowserMutationObserver(flush);
  9843. var node = document.createTextNode('');
  9844. observer.observe(node, { characterData: true });
  9845. return function () {
  9846. node.data = iterations = ++iterations % 2;
  9847. };
  9848. }
  9849. // web worker
  9850. function useMessageChannel() {
  9851. var channel = new MessageChannel();
  9852. channel.port1.onmessage = flush;
  9853. return function () {
  9854. return channel.port2.postMessage(0);
  9855. };
  9856. }
  9857. function useSetTimeout() {
  9858. // Store setTimeout reference so es6-promise will be unaffected by
  9859. // other code modifying setTimeout (like sinon.useFakeTimers())
  9860. var globalSetTimeout = setTimeout;
  9861. return function () {
  9862. return globalSetTimeout(flush, 1);
  9863. };
  9864. }
  9865. var queue = new Array(1000);
  9866. function flush() {
  9867. for (var i = 0; i < len; i += 2) {
  9868. var callback = queue[i];
  9869. var arg = queue[i + 1];
  9870. callback(arg);
  9871. queue[i] = undefined;
  9872. queue[i + 1] = undefined;
  9873. }
  9874. len = 0;
  9875. }
  9876. function attemptVertx() {
  9877. try {
  9878. var vertx = Function('return this')().require('vertx');
  9879. vertxNext = vertx.runOnLoop || vertx.runOnContext;
  9880. return useVertxTimer();
  9881. } catch (e) {
  9882. return useSetTimeout();
  9883. }
  9884. }
  9885. var scheduleFlush = void 0;
  9886. // Decide what async method to use to triggering processing of queued callbacks:
  9887. if (isNode) {
  9888. scheduleFlush = useNextTick();
  9889. } else if (BrowserMutationObserver) {
  9890. scheduleFlush = useMutationObserver();
  9891. } else if (isWorker) {
  9892. scheduleFlush = useMessageChannel();
  9893. } else if (browserWindow === undefined && "function" === 'function') {
  9894. scheduleFlush = attemptVertx();
  9895. } else {
  9896. scheduleFlush = useSetTimeout();
  9897. }
  9898. function then(onFulfillment, onRejection) {
  9899. var parent = this;
  9900. var child = new this.constructor(noop);
  9901. if (child[PROMISE_ID] === undefined) {
  9902. makePromise(child);
  9903. }
  9904. var _state = parent._state;
  9905. if (_state) {
  9906. var callback = arguments[_state - 1];
  9907. asap(function () {
  9908. return invokeCallback(_state, child, callback, parent._result);
  9909. });
  9910. } else {
  9911. subscribe(parent, child, onFulfillment, onRejection);
  9912. }
  9913. return child;
  9914. }
  9915. /**
  9916. `Promise.resolve` returns a promise that will become resolved with the
  9917. passed `value`. It is shorthand for the following:
  9918. ```javascript
  9919. let promise = new Promise(function(resolve, reject){
  9920. resolve(1);
  9921. });
  9922. promise.then(function(value){
  9923. // value === 1
  9924. });
  9925. ```
  9926. Instead of writing the above, your code now simply becomes the following:
  9927. ```javascript
  9928. let promise = Promise.resolve(1);
  9929. promise.then(function(value){
  9930. // value === 1
  9931. });
  9932. ```
  9933. @method resolve
  9934. @static
  9935. @param {Any} value value that the returned promise will be resolved with
  9936. Useful for tooling.
  9937. @return {Promise} a promise that will become fulfilled with the given
  9938. `value`
  9939. */
  9940. function resolve$1(object) {
  9941. /*jshint validthis:true */
  9942. var Constructor = this;
  9943. if (object && typeof object === 'object' && object.constructor === Constructor) {
  9944. return object;
  9945. }
  9946. var promise = new Constructor(noop);
  9947. resolve(promise, object);
  9948. return promise;
  9949. }
  9950. var PROMISE_ID = Math.random().toString(36).substring(2);
  9951. function noop() {}
  9952. var PENDING = void 0;
  9953. var FULFILLED = 1;
  9954. var REJECTED = 2;
  9955. function selfFulfillment() {
  9956. return new TypeError("You cannot resolve a promise with itself");
  9957. }
  9958. function cannotReturnOwn() {
  9959. return new TypeError('A promises callback cannot return that same promise.');
  9960. }
  9961. function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
  9962. try {
  9963. then$$1.call(value, fulfillmentHandler, rejectionHandler);
  9964. } catch (e) {
  9965. return e;
  9966. }
  9967. }
  9968. function handleForeignThenable(promise, thenable, then$$1) {
  9969. asap(function (promise) {
  9970. var sealed = false;
  9971. var error = tryThen(then$$1, thenable, function (value) {
  9972. if (sealed) {
  9973. return;
  9974. }
  9975. sealed = true;
  9976. if (thenable !== value) {
  9977. resolve(promise, value);
  9978. } else {
  9979. fulfill(promise, value);
  9980. }
  9981. }, function (reason) {
  9982. if (sealed) {
  9983. return;
  9984. }
  9985. sealed = true;
  9986. reject(promise, reason);
  9987. }, 'Settle: ' + (promise._label || ' unknown promise'));
  9988. if (!sealed && error) {
  9989. sealed = true;
  9990. reject(promise, error);
  9991. }
  9992. }, promise);
  9993. }
  9994. function handleOwnThenable(promise, thenable) {
  9995. if (thenable._state === FULFILLED) {
  9996. fulfill(promise, thenable._result);
  9997. } else if (thenable._state === REJECTED) {
  9998. reject(promise, thenable._result);
  9999. } else {
  10000. subscribe(thenable, undefined, function (value) {
  10001. return resolve(promise, value);
  10002. }, function (reason) {
  10003. return reject(promise, reason);
  10004. });
  10005. }
  10006. }
  10007. function handleMaybeThenable(promise, maybeThenable, then$$1) {
  10008. if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
  10009. handleOwnThenable(promise, maybeThenable);
  10010. } else {
  10011. if (then$$1 === undefined) {
  10012. fulfill(promise, maybeThenable);
  10013. } else if (isFunction(then$$1)) {
  10014. handleForeignThenable(promise, maybeThenable, then$$1);
  10015. } else {
  10016. fulfill(promise, maybeThenable);
  10017. }
  10018. }
  10019. }
  10020. function resolve(promise, value) {
  10021. if (promise === value) {
  10022. reject(promise, selfFulfillment());
  10023. } else if (objectOrFunction(value)) {
  10024. var then$$1 = void 0;
  10025. try {
  10026. then$$1 = value.then;
  10027. } catch (error) {
  10028. reject(promise, error);
  10029. return;
  10030. }
  10031. handleMaybeThenable(promise, value, then$$1);
  10032. } else {
  10033. fulfill(promise, value);
  10034. }
  10035. }
  10036. function publishRejection(promise) {
  10037. if (promise._onerror) {
  10038. promise._onerror(promise._result);
  10039. }
  10040. publish(promise);
  10041. }
  10042. function fulfill(promise, value) {
  10043. if (promise._state !== PENDING) {
  10044. return;
  10045. }
  10046. promise._result = value;
  10047. promise._state = FULFILLED;
  10048. if (promise._subscribers.length !== 0) {
  10049. asap(publish, promise);
  10050. }
  10051. }
  10052. function reject(promise, reason) {
  10053. if (promise._state !== PENDING) {
  10054. return;
  10055. }
  10056. promise._state = REJECTED;
  10057. promise._result = reason;
  10058. asap(publishRejection, promise);
  10059. }
  10060. function subscribe(parent, child, onFulfillment, onRejection) {
  10061. var _subscribers = parent._subscribers;
  10062. var length = _subscribers.length;
  10063. parent._onerror = null;
  10064. _subscribers[length] = child;
  10065. _subscribers[length + FULFILLED] = onFulfillment;
  10066. _subscribers[length + REJECTED] = onRejection;
  10067. if (length === 0 && parent._state) {
  10068. asap(publish, parent);
  10069. }
  10070. }
  10071. function publish(promise) {
  10072. var subscribers = promise._subscribers;
  10073. var settled = promise._state;
  10074. if (subscribers.length === 0) {
  10075. return;
  10076. }
  10077. var child = void 0,
  10078. callback = void 0,
  10079. detail = promise._result;
  10080. for (var i = 0; i < subscribers.length; i += 3) {
  10081. child = subscribers[i];
  10082. callback = subscribers[i + settled];
  10083. if (child) {
  10084. invokeCallback(settled, child, callback, detail);
  10085. } else {
  10086. callback(detail);
  10087. }
  10088. }
  10089. promise._subscribers.length = 0;
  10090. }
  10091. function invokeCallback(settled, promise, callback, detail) {
  10092. var hasCallback = isFunction(callback),
  10093. value = void 0,
  10094. error = void 0,
  10095. succeeded = true;
  10096. if (hasCallback) {
  10097. try {
  10098. value = callback(detail);
  10099. } catch (e) {
  10100. succeeded = false;
  10101. error = e;
  10102. }
  10103. if (promise === value) {
  10104. reject(promise, cannotReturnOwn());
  10105. return;
  10106. }
  10107. } else {
  10108. value = detail;
  10109. }
  10110. if (promise._state !== PENDING) {
  10111. // noop
  10112. } else if (hasCallback && succeeded) {
  10113. resolve(promise, value);
  10114. } else if (succeeded === false) {
  10115. reject(promise, error);
  10116. } else if (settled === FULFILLED) {
  10117. fulfill(promise, value);
  10118. } else if (settled === REJECTED) {
  10119. reject(promise, value);
  10120. }
  10121. }
  10122. function initializePromise(promise, resolver) {
  10123. try {
  10124. resolver(function resolvePromise(value) {
  10125. resolve(promise, value);
  10126. }, function rejectPromise(reason) {
  10127. reject(promise, reason);
  10128. });
  10129. } catch (e) {
  10130. reject(promise, e);
  10131. }
  10132. }
  10133. var id = 0;
  10134. function nextId() {
  10135. return id++;
  10136. }
  10137. function makePromise(promise) {
  10138. promise[PROMISE_ID] = id++;
  10139. promise._state = undefined;
  10140. promise._result = undefined;
  10141. promise._subscribers = [];
  10142. }
  10143. function validationError() {
  10144. return new Error('Array Methods must be provided an Array');
  10145. }
  10146. var Enumerator = function () {
  10147. function Enumerator(Constructor, input) {
  10148. this._instanceConstructor = Constructor;
  10149. this.promise = new Constructor(noop);
  10150. if (!this.promise[PROMISE_ID]) {
  10151. makePromise(this.promise);
  10152. }
  10153. if (isArray(input)) {
  10154. this.length = input.length;
  10155. this._remaining = input.length;
  10156. this._result = new Array(this.length);
  10157. if (this.length === 0) {
  10158. fulfill(this.promise, this._result);
  10159. } else {
  10160. this.length = this.length || 0;
  10161. this._enumerate(input);
  10162. if (this._remaining === 0) {
  10163. fulfill(this.promise, this._result);
  10164. }
  10165. }
  10166. } else {
  10167. reject(this.promise, validationError());
  10168. }
  10169. }
  10170. Enumerator.prototype._enumerate = function _enumerate(input) {
  10171. for (var i = 0; this._state === PENDING && i < input.length; i++) {
  10172. this._eachEntry(input[i], i);
  10173. }
  10174. };
  10175. Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
  10176. var c = this._instanceConstructor;
  10177. var resolve$$1 = c.resolve;
  10178. if (resolve$$1 === resolve$1) {
  10179. var _then = void 0;
  10180. var error = void 0;
  10181. var didError = false;
  10182. try {
  10183. _then = entry.then;
  10184. } catch (e) {
  10185. didError = true;
  10186. error = e;
  10187. }
  10188. if (_then === then && entry._state !== PENDING) {
  10189. this._settledAt(entry._state, i, entry._result);
  10190. } else if (typeof _then !== 'function') {
  10191. this._remaining--;
  10192. this._result[i] = entry;
  10193. } else if (c === Promise$1) {
  10194. var promise = new c(noop);
  10195. if (didError) {
  10196. reject(promise, error);
  10197. } else {
  10198. handleMaybeThenable(promise, entry, _then);
  10199. }
  10200. this._willSettleAt(promise, i);
  10201. } else {
  10202. this._willSettleAt(new c(function (resolve$$1) {
  10203. return resolve$$1(entry);
  10204. }), i);
  10205. }
  10206. } else {
  10207. this._willSettleAt(resolve$$1(entry), i);
  10208. }
  10209. };
  10210. Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
  10211. var promise = this.promise;
  10212. if (promise._state === PENDING) {
  10213. this._remaining--;
  10214. if (state === REJECTED) {
  10215. reject(promise, value);
  10216. } else {
  10217. this._result[i] = value;
  10218. }
  10219. }
  10220. if (this._remaining === 0) {
  10221. fulfill(promise, this._result);
  10222. }
  10223. };
  10224. Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
  10225. var enumerator = this;
  10226. subscribe(promise, undefined, function (value) {
  10227. return enumerator._settledAt(FULFILLED, i, value);
  10228. }, function (reason) {
  10229. return enumerator._settledAt(REJECTED, i, reason);
  10230. });
  10231. };
  10232. return Enumerator;
  10233. }();
  10234. /**
  10235. `Promise.all` accepts an array of promises, and returns a new promise which
  10236. is fulfilled with an array of fulfillment values for the passed promises, or
  10237. rejected with the reason of the first passed promise to be rejected. It casts all
  10238. elements of the passed iterable to promises as it runs this algorithm.
  10239. Example:
  10240. ```javascript
  10241. let promise1 = resolve(1);
  10242. let promise2 = resolve(2);
  10243. let promise3 = resolve(3);
  10244. let promises = [ promise1, promise2, promise3 ];
  10245. Promise.all(promises).then(function(array){
  10246. // The array here would be [ 1, 2, 3 ];
  10247. });
  10248. ```
  10249. If any of the `promises` given to `all` are rejected, the first promise
  10250. that is rejected will be given as an argument to the returned promises's
  10251. rejection handler. For example:
  10252. Example:
  10253. ```javascript
  10254. let promise1 = resolve(1);
  10255. let promise2 = reject(new Error("2"));
  10256. let promise3 = reject(new Error("3"));
  10257. let promises = [ promise1, promise2, promise3 ];
  10258. Promise.all(promises).then(function(array){
  10259. // Code here never runs because there are rejected promises!
  10260. }, function(error) {
  10261. // error.message === "2"
  10262. });
  10263. ```
  10264. @method all
  10265. @static
  10266. @param {Array} entries array of promises
  10267. @param {String} label optional string for labeling the promise.
  10268. Useful for tooling.
  10269. @return {Promise} promise that is fulfilled when all `promises` have been
  10270. fulfilled, or rejected if any of them become rejected.
  10271. @static
  10272. */
  10273. function all(entries) {
  10274. return new Enumerator(this, entries).promise;
  10275. }
  10276. /**
  10277. `Promise.race` returns a new promise which is settled in the same way as the
  10278. first passed promise to settle.
  10279. Example:
  10280. ```javascript
  10281. let promise1 = new Promise(function(resolve, reject){
  10282. setTimeout(function(){
  10283. resolve('promise 1');
  10284. }, 200);
  10285. });
  10286. let promise2 = new Promise(function(resolve, reject){
  10287. setTimeout(function(){
  10288. resolve('promise 2');
  10289. }, 100);
  10290. });
  10291. Promise.race([promise1, promise2]).then(function(result){
  10292. // result === 'promise 2' because it was resolved before promise1
  10293. // was resolved.
  10294. });
  10295. ```
  10296. `Promise.race` is deterministic in that only the state of the first
  10297. settled promise matters. For example, even if other promises given to the
  10298. `promises` array argument are resolved, but the first settled promise has
  10299. become rejected before the other promises became fulfilled, the returned
  10300. promise will become rejected:
  10301. ```javascript
  10302. let promise1 = new Promise(function(resolve, reject){
  10303. setTimeout(function(){
  10304. resolve('promise 1');
  10305. }, 200);
  10306. });
  10307. let promise2 = new Promise(function(resolve, reject){
  10308. setTimeout(function(){
  10309. reject(new Error('promise 2'));
  10310. }, 100);
  10311. });
  10312. Promise.race([promise1, promise2]).then(function(result){
  10313. // Code here never runs
  10314. }, function(reason){
  10315. // reason.message === 'promise 2' because promise 2 became rejected before
  10316. // promise 1 became fulfilled
  10317. });
  10318. ```
  10319. An example real-world use case is implementing timeouts:
  10320. ```javascript
  10321. Promise.race([ajax('foo.json'), timeout(5000)])
  10322. ```
  10323. @method race
  10324. @static
  10325. @param {Array} promises array of promises to observe
  10326. Useful for tooling.
  10327. @return {Promise} a promise which settles in the same way as the first passed
  10328. promise to settle.
  10329. */
  10330. function race(entries) {
  10331. /*jshint validthis:true */
  10332. var Constructor = this;
  10333. if (!isArray(entries)) {
  10334. return new Constructor(function (_, reject) {
  10335. return reject(new TypeError('You must pass an array to race.'));
  10336. });
  10337. } else {
  10338. return new Constructor(function (resolve, reject) {
  10339. var length = entries.length;
  10340. for (var i = 0; i < length; i++) {
  10341. Constructor.resolve(entries[i]).then(resolve, reject);
  10342. }
  10343. });
  10344. }
  10345. }
  10346. /**
  10347. `Promise.reject` returns a promise rejected with the passed `reason`.
  10348. It is shorthand for the following:
  10349. ```javascript
  10350. let promise = new Promise(function(resolve, reject){
  10351. reject(new Error('WHOOPS'));
  10352. });
  10353. promise.then(function(value){
  10354. // Code here doesn't run because the promise is rejected!
  10355. }, function(reason){
  10356. // reason.message === 'WHOOPS'
  10357. });
  10358. ```
  10359. Instead of writing the above, your code now simply becomes the following:
  10360. ```javascript
  10361. let promise = Promise.reject(new Error('WHOOPS'));
  10362. promise.then(function(value){
  10363. // Code here doesn't run because the promise is rejected!
  10364. }, function(reason){
  10365. // reason.message === 'WHOOPS'
  10366. });
  10367. ```
  10368. @method reject
  10369. @static
  10370. @param {Any} reason value that the returned promise will be rejected with.
  10371. Useful for tooling.
  10372. @return {Promise} a promise rejected with the given `reason`.
  10373. */
  10374. function reject$1(reason) {
  10375. /*jshint validthis:true */
  10376. var Constructor = this;
  10377. var promise = new Constructor(noop);
  10378. reject(promise, reason);
  10379. return promise;
  10380. }
  10381. function needsResolver() {
  10382. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  10383. }
  10384. function needsNew() {
  10385. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  10386. }
  10387. /**
  10388. Promise objects represent the eventual result of an asynchronous operation. The
  10389. primary way of interacting with a promise is through its `then` method, which
  10390. registers callbacks to receive either a promise's eventual value or the reason
  10391. why the promise cannot be fulfilled.
  10392. Terminology
  10393. -----------
  10394. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  10395. - `thenable` is an object or function that defines a `then` method.
  10396. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  10397. - `exception` is a value that is thrown using the throw statement.
  10398. - `reason` is a value that indicates why a promise was rejected.
  10399. - `settled` the final resting state of a promise, fulfilled or rejected.
  10400. A promise can be in one of three states: pending, fulfilled, or rejected.
  10401. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  10402. state. Promises that are rejected have a rejection reason and are in the
  10403. rejected state. A fulfillment value is never a thenable.
  10404. Promises can also be said to *resolve* a value. If this value is also a
  10405. promise, then the original promise's settled state will match the value's
  10406. settled state. So a promise that *resolves* a promise that rejects will
  10407. itself reject, and a promise that *resolves* a promise that fulfills will
  10408. itself fulfill.
  10409. Basic Usage:
  10410. ------------
  10411. ```js
  10412. let promise = new Promise(function(resolve, reject) {
  10413. // on success
  10414. resolve(value);
  10415. // on failure
  10416. reject(reason);
  10417. });
  10418. promise.then(function(value) {
  10419. // on fulfillment
  10420. }, function(reason) {
  10421. // on rejection
  10422. });
  10423. ```
  10424. Advanced Usage:
  10425. ---------------
  10426. Promises shine when abstracting away asynchronous interactions such as
  10427. `XMLHttpRequest`s.
  10428. ```js
  10429. function getJSON(url) {
  10430. return new Promise(function(resolve, reject){
  10431. let xhr = new XMLHttpRequest();
  10432. xhr.open('GET', url);
  10433. xhr.onreadystatechange = handler;
  10434. xhr.responseType = 'json';
  10435. xhr.setRequestHeader('Accept', 'application/json');
  10436. xhr.send();
  10437. function handler() {
  10438. if (this.readyState === this.DONE) {
  10439. if (this.status === 200) {
  10440. resolve(this.response);
  10441. } else {
  10442. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  10443. }
  10444. }
  10445. };
  10446. });
  10447. }
  10448. getJSON('/posts.json').then(function(json) {
  10449. // on fulfillment
  10450. }, function(reason) {
  10451. // on rejection
  10452. });
  10453. ```
  10454. Unlike callbacks, promises are great composable primitives.
  10455. ```js
  10456. Promise.all([
  10457. getJSON('/posts'),
  10458. getJSON('/comments')
  10459. ]).then(function(values){
  10460. values[0] // => postsJSON
  10461. values[1] // => commentsJSON
  10462. return values;
  10463. });
  10464. ```
  10465. @class Promise
  10466. @param {Function} resolver
  10467. Useful for tooling.
  10468. @constructor
  10469. */
  10470. var Promise$1 = function () {
  10471. function Promise(resolver) {
  10472. this[PROMISE_ID] = nextId();
  10473. this._result = this._state = undefined;
  10474. this._subscribers = [];
  10475. if (noop !== resolver) {
  10476. typeof resolver !== 'function' && needsResolver();
  10477. this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  10478. }
  10479. }
  10480. /**
  10481. The primary way of interacting with a promise is through its `then` method,
  10482. which registers callbacks to receive either a promise's eventual value or the
  10483. reason why the promise cannot be fulfilled.
  10484. ```js
  10485. findUser().then(function(user){
  10486. // user is available
  10487. }, function(reason){
  10488. // user is unavailable, and you are given the reason why
  10489. });
  10490. ```
  10491. Chaining
  10492. --------
  10493. The return value of `then` is itself a promise. This second, 'downstream'
  10494. promise is resolved with the return value of the first promise's fulfillment
  10495. or rejection handler, or rejected if the handler throws an exception.
  10496. ```js
  10497. findUser().then(function (user) {
  10498. return user.name;
  10499. }, function (reason) {
  10500. return 'default name';
  10501. }).then(function (userName) {
  10502. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  10503. // will be `'default name'`
  10504. });
  10505. findUser().then(function (user) {
  10506. throw new Error('Found user, but still unhappy');
  10507. }, function (reason) {
  10508. throw new Error('`findUser` rejected and we're unhappy');
  10509. }).then(function (value) {
  10510. // never reached
  10511. }, function (reason) {
  10512. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  10513. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  10514. });
  10515. ```
  10516. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  10517. ```js
  10518. findUser().then(function (user) {
  10519. throw new PedagogicalException('Upstream error');
  10520. }).then(function (value) {
  10521. // never reached
  10522. }).then(function (value) {
  10523. // never reached
  10524. }, function (reason) {
  10525. // The `PedgagocialException` is propagated all the way down to here
  10526. });
  10527. ```
  10528. Assimilation
  10529. ------------
  10530. Sometimes the value you want to propagate to a downstream promise can only be
  10531. retrieved asynchronously. This can be achieved by returning a promise in the
  10532. fulfillment or rejection handler. The downstream promise will then be pending
  10533. until the returned promise is settled. This is called *assimilation*.
  10534. ```js
  10535. findUser().then(function (user) {
  10536. return findCommentsByAuthor(user);
  10537. }).then(function (comments) {
  10538. // The user's comments are now available
  10539. });
  10540. ```
  10541. If the assimliated promise rejects, then the downstream promise will also reject.
  10542. ```js
  10543. findUser().then(function (user) {
  10544. return findCommentsByAuthor(user);
  10545. }).then(function (comments) {
  10546. // If `findCommentsByAuthor` fulfills, we'll have the value here
  10547. }, function (reason) {
  10548. // If `findCommentsByAuthor` rejects, we'll have the reason here
  10549. });
  10550. ```
  10551. Simple Example
  10552. --------------
  10553. Synchronous Example
  10554. ```javascript
  10555. let result;
  10556. try {
  10557. result = findResult();
  10558. // success
  10559. } catch(reason) {
  10560. // failure
  10561. }
  10562. ```
  10563. Errback Example
  10564. ```js
  10565. findResult(function(result, err){
  10566. if (err) {
  10567. // failure
  10568. } else {
  10569. // success
  10570. }
  10571. });
  10572. ```
  10573. Promise Example;
  10574. ```javascript
  10575. findResult().then(function(result){
  10576. // success
  10577. }, function(reason){
  10578. // failure
  10579. });
  10580. ```
  10581. Advanced Example
  10582. --------------
  10583. Synchronous Example
  10584. ```javascript
  10585. let author, books;
  10586. try {
  10587. author = findAuthor();
  10588. books = findBooksByAuthor(author);
  10589. // success
  10590. } catch(reason) {
  10591. // failure
  10592. }
  10593. ```
  10594. Errback Example
  10595. ```js
  10596. function foundBooks(books) {
  10597. }
  10598. function failure(reason) {
  10599. }
  10600. findAuthor(function(author, err){
  10601. if (err) {
  10602. failure(err);
  10603. // failure
  10604. } else {
  10605. try {
  10606. findBoooksByAuthor(author, function(books, err) {
  10607. if (err) {
  10608. failure(err);
  10609. } else {
  10610. try {
  10611. foundBooks(books);
  10612. } catch(reason) {
  10613. failure(reason);
  10614. }
  10615. }
  10616. });
  10617. } catch(error) {
  10618. failure(err);
  10619. }
  10620. // success
  10621. }
  10622. });
  10623. ```
  10624. Promise Example;
  10625. ```javascript
  10626. findAuthor().
  10627. then(findBooksByAuthor).
  10628. then(function(books){
  10629. // found books
  10630. }).catch(function(reason){
  10631. // something went wrong
  10632. });
  10633. ```
  10634. @method then
  10635. @param {Function} onFulfilled
  10636. @param {Function} onRejected
  10637. Useful for tooling.
  10638. @return {Promise}
  10639. */
  10640. /**
  10641. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  10642. as the catch block of a try/catch statement.
  10643. ```js
  10644. function findAuthor(){
  10645. throw new Error('couldn't find that author');
  10646. }
  10647. // synchronous
  10648. try {
  10649. findAuthor();
  10650. } catch(reason) {
  10651. // something went wrong
  10652. }
  10653. // async with promises
  10654. findAuthor().catch(function(reason){
  10655. // something went wrong
  10656. });
  10657. ```
  10658. @method catch
  10659. @param {Function} onRejection
  10660. Useful for tooling.
  10661. @return {Promise}
  10662. */
  10663. Promise.prototype.catch = function _catch(onRejection) {
  10664. return this.then(null, onRejection);
  10665. };
  10666. /**
  10667. `finally` will be invoked regardless of the promise's fate just as native
  10668. try/catch/finally behaves
  10669. Synchronous example:
  10670. ```js
  10671. findAuthor() {
  10672. if (Math.random() > 0.5) {
  10673. throw new Error();
  10674. }
  10675. return new Author();
  10676. }
  10677. try {
  10678. return findAuthor(); // succeed or fail
  10679. } catch(error) {
  10680. return findOtherAuther();
  10681. } finally {
  10682. // always runs
  10683. // doesn't affect the return value
  10684. }
  10685. ```
  10686. Asynchronous example:
  10687. ```js
  10688. findAuthor().catch(function(reason){
  10689. return findOtherAuther();
  10690. }).finally(function(){
  10691. // author was either found, or not
  10692. });
  10693. ```
  10694. @method finally
  10695. @param {Function} callback
  10696. @return {Promise}
  10697. */
  10698. Promise.prototype.finally = function _finally(callback) {
  10699. var promise = this;
  10700. var constructor = promise.constructor;
  10701. if (isFunction(callback)) {
  10702. return promise.then(function (value) {
  10703. return constructor.resolve(callback()).then(function () {
  10704. return value;
  10705. });
  10706. }, function (reason) {
  10707. return constructor.resolve(callback()).then(function () {
  10708. throw reason;
  10709. });
  10710. });
  10711. }
  10712. return promise.then(callback, callback);
  10713. };
  10714. return Promise;
  10715. }();
  10716. Promise$1.prototype.then = then;
  10717. Promise$1.all = all;
  10718. Promise$1.race = race;
  10719. Promise$1.resolve = resolve$1;
  10720. Promise$1.reject = reject$1;
  10721. Promise$1._setScheduler = setScheduler;
  10722. Promise$1._setAsap = setAsap;
  10723. Promise$1._asap = asap;
  10724. /*global self*/
  10725. function polyfill() {
  10726. var local = void 0;
  10727. if (typeof global !== 'undefined') {
  10728. local = global;
  10729. } else if (typeof self !== 'undefined') {
  10730. local = self;
  10731. } else {
  10732. try {
  10733. local = Function('return this')();
  10734. } catch (e) {
  10735. throw new Error('polyfill failed because global object is unavailable in this environment');
  10736. }
  10737. }
  10738. var P = local.Promise;
  10739. if (P) {
  10740. var promiseToString = null;
  10741. try {
  10742. promiseToString = Object.prototype.toString.call(P.resolve());
  10743. } catch (e) {
  10744. // silently ignored
  10745. }
  10746. if (promiseToString === '[object Promise]' && !P.cast) {
  10747. return;
  10748. }
  10749. }
  10750. local.Promise = Promise$1;
  10751. }
  10752. // Strange compat..
  10753. Promise$1.polyfill = polyfill;
  10754. Promise$1.Promise = Promise$1;
  10755. return Promise$1;
  10756. })));
  10757. //# sourceMappingURL=es6-promise.map
  10758. /***/ }),
  10759. /* 60 */
  10760. /***/ (function(module, exports) {
  10761. module.exports = require("events");
  10762. /***/ }),
  10763. /* 61 */
  10764. /***/ (function(module, exports, __webpack_require__) {
  10765. /**
  10766. * Detect Electron renderer process, which is node, but we should
  10767. * treat as a browser.
  10768. */
  10769. if (typeof process === 'undefined' || process.type === 'renderer') {
  10770. module.exports = __webpack_require__(62);
  10771. } else {
  10772. module.exports = __webpack_require__(65);
  10773. }
  10774. /***/ }),
  10775. /* 62 */
  10776. /***/ (function(module, exports, __webpack_require__) {
  10777. /**
  10778. * This is the web browser implementation of `debug()`.
  10779. *
  10780. * Expose `debug()` as the module.
  10781. */
  10782. exports = module.exports = __webpack_require__(63);
  10783. exports.log = log;
  10784. exports.formatArgs = formatArgs;
  10785. exports.save = save;
  10786. exports.load = load;
  10787. exports.useColors = useColors;
  10788. exports.storage = 'undefined' != typeof chrome
  10789. && 'undefined' != typeof chrome.storage
  10790. ? chrome.storage.local
  10791. : localstorage();
  10792. /**
  10793. * Colors.
  10794. */
  10795. exports.colors = [
  10796. '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC',
  10797. '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF',
  10798. '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC',
  10799. '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF',
  10800. '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC',
  10801. '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033',
  10802. '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366',
  10803. '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933',
  10804. '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC',
  10805. '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF',
  10806. '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'
  10807. ];
  10808. /**
  10809. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  10810. * and the Firebug extension (any Firefox version) are known
  10811. * to support "%c" CSS customizations.
  10812. *
  10813. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  10814. */
  10815. function useColors() {
  10816. // NB: In an Electron preload script, document will be defined but not fully
  10817. // initialized. Since we know we're in Chrome, we'll just detect this case
  10818. // explicitly
  10819. if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
  10820. return true;
  10821. }
  10822. // Internet Explorer and Edge do not support colors.
  10823. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  10824. return false;
  10825. }
  10826. // is webkit? http://stackoverflow.com/a/16459606/376773
  10827. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  10828. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  10829. // is firebug? http://stackoverflow.com/a/398120/376773
  10830. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  10831. // is firefox >= v31?
  10832. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  10833. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  10834. // double check webkit in userAgent just in case we are in a worker
  10835. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  10836. }
  10837. /**
  10838. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  10839. */
  10840. exports.formatters.j = function(v) {
  10841. try {
  10842. return JSON.stringify(v);
  10843. } catch (err) {
  10844. return '[UnexpectedJSONParseError]: ' + err.message;
  10845. }
  10846. };
  10847. /**
  10848. * Colorize log arguments if enabled.
  10849. *
  10850. * @api public
  10851. */
  10852. function formatArgs(args) {
  10853. var useColors = this.useColors;
  10854. args[0] = (useColors ? '%c' : '')
  10855. + this.namespace
  10856. + (useColors ? ' %c' : ' ')
  10857. + args[0]
  10858. + (useColors ? '%c ' : ' ')
  10859. + '+' + exports.humanize(this.diff);
  10860. if (!useColors) return;
  10861. var c = 'color: ' + this.color;
  10862. args.splice(1, 0, c, 'color: inherit')
  10863. // the final "%c" is somewhat tricky, because there could be other
  10864. // arguments passed either before or after the %c, so we need to
  10865. // figure out the correct index to insert the CSS into
  10866. var index = 0;
  10867. var lastC = 0;
  10868. args[0].replace(/%[a-zA-Z%]/g, function(match) {
  10869. if ('%%' === match) return;
  10870. index++;
  10871. if ('%c' === match) {
  10872. // we only are interested in the *last* %c
  10873. // (the user may have provided their own)
  10874. lastC = index;
  10875. }
  10876. });
  10877. args.splice(lastC, 0, c);
  10878. }
  10879. /**
  10880. * Invokes `console.log()` when available.
  10881. * No-op when `console.log` is not a "function".
  10882. *
  10883. * @api public
  10884. */
  10885. function log() {
  10886. // this hackery is required for IE8/9, where
  10887. // the `console.log` function doesn't have 'apply'
  10888. return 'object' === typeof console
  10889. && console.log
  10890. && Function.prototype.apply.call(console.log, console, arguments);
  10891. }
  10892. /**
  10893. * Save `namespaces`.
  10894. *
  10895. * @param {String} namespaces
  10896. * @api private
  10897. */
  10898. function save(namespaces) {
  10899. try {
  10900. if (null == namespaces) {
  10901. exports.storage.removeItem('debug');
  10902. } else {
  10903. exports.storage.debug = namespaces;
  10904. }
  10905. } catch(e) {}
  10906. }
  10907. /**
  10908. * Load `namespaces`.
  10909. *
  10910. * @return {String} returns the previously persisted debug modes
  10911. * @api private
  10912. */
  10913. function load() {
  10914. var r;
  10915. try {
  10916. r = exports.storage.debug;
  10917. } catch(e) {}
  10918. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  10919. if (!r && typeof process !== 'undefined' && 'env' in process) {
  10920. r = process.env.DEBUG;
  10921. }
  10922. return r;
  10923. }
  10924. /**
  10925. * Enable namespaces listed in `localStorage.debug` initially.
  10926. */
  10927. exports.enable(load());
  10928. /**
  10929. * Localstorage attempts to return the localstorage.
  10930. *
  10931. * This is necessary because safari throws
  10932. * when a user disables cookies/localstorage
  10933. * and you attempt to access it.
  10934. *
  10935. * @return {LocalStorage}
  10936. * @api private
  10937. */
  10938. function localstorage() {
  10939. try {
  10940. return window.localStorage;
  10941. } catch (e) {}
  10942. }
  10943. /***/ }),
  10944. /* 63 */
  10945. /***/ (function(module, exports, __webpack_require__) {
  10946. /**
  10947. * This is the common logic for both the Node.js and web browser
  10948. * implementations of `debug()`.
  10949. *
  10950. * Expose `debug()` as the module.
  10951. */
  10952. exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
  10953. exports.coerce = coerce;
  10954. exports.disable = disable;
  10955. exports.enable = enable;
  10956. exports.enabled = enabled;
  10957. exports.humanize = __webpack_require__(64);
  10958. /**
  10959. * Active `debug` instances.
  10960. */
  10961. exports.instances = [];
  10962. /**
  10963. * The currently active debug mode names, and names to skip.
  10964. */
  10965. exports.names = [];
  10966. exports.skips = [];
  10967. /**
  10968. * Map of special "%n" handling functions, for the debug "format" argument.
  10969. *
  10970. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  10971. */
  10972. exports.formatters = {};
  10973. /**
  10974. * Select a color.
  10975. * @param {String} namespace
  10976. * @return {Number}
  10977. * @api private
  10978. */
  10979. function selectColor(namespace) {
  10980. var hash = 0, i;
  10981. for (i in namespace) {
  10982. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  10983. hash |= 0; // Convert to 32bit integer
  10984. }
  10985. return exports.colors[Math.abs(hash) % exports.colors.length];
  10986. }
  10987. /**
  10988. * Create a debugger with the given `namespace`.
  10989. *
  10990. * @param {String} namespace
  10991. * @return {Function}
  10992. * @api public
  10993. */
  10994. function createDebug(namespace) {
  10995. var prevTime;
  10996. function debug() {
  10997. // disabled?
  10998. if (!debug.enabled) return;
  10999. var self = debug;
  11000. // set `diff` timestamp
  11001. var curr = +new Date();
  11002. var ms = curr - (prevTime || curr);
  11003. self.diff = ms;
  11004. self.prev = prevTime;
  11005. self.curr = curr;
  11006. prevTime = curr;
  11007. // turn the `arguments` into a proper Array
  11008. var args = new Array(arguments.length);
  11009. for (var i = 0; i < args.length; i++) {
  11010. args[i] = arguments[i];
  11011. }
  11012. args[0] = exports.coerce(args[0]);
  11013. if ('string' !== typeof args[0]) {
  11014. // anything else let's inspect with %O
  11015. args.unshift('%O');
  11016. }
  11017. // apply any `formatters` transformations
  11018. var index = 0;
  11019. args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
  11020. // if we encounter an escaped % then don't increase the array index
  11021. if (match === '%%') return match;
  11022. index++;
  11023. var formatter = exports.formatters[format];
  11024. if ('function' === typeof formatter) {
  11025. var val = args[index];
  11026. match = formatter.call(self, val);
  11027. // now we need to remove `args[index]` since it's inlined in the `format`
  11028. args.splice(index, 1);
  11029. index--;
  11030. }
  11031. return match;
  11032. });
  11033. // apply env-specific formatting (colors, etc.)
  11034. exports.formatArgs.call(self, args);
  11035. var logFn = debug.log || exports.log || console.log.bind(console);
  11036. logFn.apply(self, args);
  11037. }
  11038. debug.namespace = namespace;
  11039. debug.enabled = exports.enabled(namespace);
  11040. debug.useColors = exports.useColors();
  11041. debug.color = selectColor(namespace);
  11042. debug.destroy = destroy;
  11043. // env-specific initialization logic for debug instances
  11044. if ('function' === typeof exports.init) {
  11045. exports.init(debug);
  11046. }
  11047. exports.instances.push(debug);
  11048. return debug;
  11049. }
  11050. function destroy () {
  11051. var index = exports.instances.indexOf(this);
  11052. if (index !== -1) {
  11053. exports.instances.splice(index, 1);
  11054. return true;
  11055. } else {
  11056. return false;
  11057. }
  11058. }
  11059. /**
  11060. * Enables a debug mode by namespaces. This can include modes
  11061. * separated by a colon and wildcards.
  11062. *
  11063. * @param {String} namespaces
  11064. * @api public
  11065. */
  11066. function enable(namespaces) {
  11067. exports.save(namespaces);
  11068. exports.names = [];
  11069. exports.skips = [];
  11070. var i;
  11071. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  11072. var len = split.length;
  11073. for (i = 0; i < len; i++) {
  11074. if (!split[i]) continue; // ignore empty strings
  11075. namespaces = split[i].replace(/\*/g, '.*?');
  11076. if (namespaces[0] === '-') {
  11077. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  11078. } else {
  11079. exports.names.push(new RegExp('^' + namespaces + '$'));
  11080. }
  11081. }
  11082. for (i = 0; i < exports.instances.length; i++) {
  11083. var instance = exports.instances[i];
  11084. instance.enabled = exports.enabled(instance.namespace);
  11085. }
  11086. }
  11087. /**
  11088. * Disable debug output.
  11089. *
  11090. * @api public
  11091. */
  11092. function disable() {
  11093. exports.enable('');
  11094. }
  11095. /**
  11096. * Returns true if the given mode name is enabled, false otherwise.
  11097. *
  11098. * @param {String} name
  11099. * @return {Boolean}
  11100. * @api public
  11101. */
  11102. function enabled(name) {
  11103. if (name[name.length - 1] === '*') {
  11104. return true;
  11105. }
  11106. var i, len;
  11107. for (i = 0, len = exports.skips.length; i < len; i++) {
  11108. if (exports.skips[i].test(name)) {
  11109. return false;
  11110. }
  11111. }
  11112. for (i = 0, len = exports.names.length; i < len; i++) {
  11113. if (exports.names[i].test(name)) {
  11114. return true;
  11115. }
  11116. }
  11117. return false;
  11118. }
  11119. /**
  11120. * Coerce `val`.
  11121. *
  11122. * @param {Mixed} val
  11123. * @return {Mixed}
  11124. * @api private
  11125. */
  11126. function coerce(val) {
  11127. if (val instanceof Error) return val.stack || val.message;
  11128. return val;
  11129. }
  11130. /***/ }),
  11131. /* 64 */
  11132. /***/ (function(module, exports) {
  11133. /**
  11134. * Helpers.
  11135. */
  11136. var s = 1000;
  11137. var m = s * 60;
  11138. var h = m * 60;
  11139. var d = h * 24;
  11140. var y = d * 365.25;
  11141. /**
  11142. * Parse or format the given `val`.
  11143. *
  11144. * Options:
  11145. *
  11146. * - `long` verbose formatting [false]
  11147. *
  11148. * @param {String|Number} val
  11149. * @param {Object} [options]
  11150. * @throws {Error} throw an error if val is not a non-empty string or a number
  11151. * @return {String|Number}
  11152. * @api public
  11153. */
  11154. module.exports = function(val, options) {
  11155. options = options || {};
  11156. var type = typeof val;
  11157. if (type === 'string' && val.length > 0) {
  11158. return parse(val);
  11159. } else if (type === 'number' && isNaN(val) === false) {
  11160. return options.long ? fmtLong(val) : fmtShort(val);
  11161. }
  11162. throw new Error(
  11163. 'val is not a non-empty string or a valid number. val=' +
  11164. JSON.stringify(val)
  11165. );
  11166. };
  11167. /**
  11168. * Parse the given `str` and return milliseconds.
  11169. *
  11170. * @param {String} str
  11171. * @return {Number}
  11172. * @api private
  11173. */
  11174. function parse(str) {
  11175. str = String(str);
  11176. if (str.length > 100) {
  11177. return;
  11178. }
  11179. var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
  11180. str
  11181. );
  11182. if (!match) {
  11183. return;
  11184. }
  11185. var n = parseFloat(match[1]);
  11186. var type = (match[2] || 'ms').toLowerCase();
  11187. switch (type) {
  11188. case 'years':
  11189. case 'year':
  11190. case 'yrs':
  11191. case 'yr':
  11192. case 'y':
  11193. return n * y;
  11194. case 'days':
  11195. case 'day':
  11196. case 'd':
  11197. return n * d;
  11198. case 'hours':
  11199. case 'hour':
  11200. case 'hrs':
  11201. case 'hr':
  11202. case 'h':
  11203. return n * h;
  11204. case 'minutes':
  11205. case 'minute':
  11206. case 'mins':
  11207. case 'min':
  11208. case 'm':
  11209. return n * m;
  11210. case 'seconds':
  11211. case 'second':
  11212. case 'secs':
  11213. case 'sec':
  11214. case 's':
  11215. return n * s;
  11216. case 'milliseconds':
  11217. case 'millisecond':
  11218. case 'msecs':
  11219. case 'msec':
  11220. case 'ms':
  11221. return n;
  11222. default:
  11223. return undefined;
  11224. }
  11225. }
  11226. /**
  11227. * Short format for `ms`.
  11228. *
  11229. * @param {Number} ms
  11230. * @return {String}
  11231. * @api private
  11232. */
  11233. function fmtShort(ms) {
  11234. if (ms >= d) {
  11235. return Math.round(ms / d) + 'd';
  11236. }
  11237. if (ms >= h) {
  11238. return Math.round(ms / h) + 'h';
  11239. }
  11240. if (ms >= m) {
  11241. return Math.round(ms / m) + 'm';
  11242. }
  11243. if (ms >= s) {
  11244. return Math.round(ms / s) + 's';
  11245. }
  11246. return ms + 'ms';
  11247. }
  11248. /**
  11249. * Long format for `ms`.
  11250. *
  11251. * @param {Number} ms
  11252. * @return {String}
  11253. * @api private
  11254. */
  11255. function fmtLong(ms) {
  11256. return plural(ms, d, 'day') ||
  11257. plural(ms, h, 'hour') ||
  11258. plural(ms, m, 'minute') ||
  11259. plural(ms, s, 'second') ||
  11260. ms + ' ms';
  11261. }
  11262. /**
  11263. * Pluralization helper.
  11264. */
  11265. function plural(ms, n, name) {
  11266. if (ms < n) {
  11267. return;
  11268. }
  11269. if (ms < n * 1.5) {
  11270. return Math.floor(ms / n) + ' ' + name;
  11271. }
  11272. return Math.ceil(ms / n) + ' ' + name + 's';
  11273. }
  11274. /***/ }),
  11275. /* 65 */
  11276. /***/ (function(module, exports, __webpack_require__) {
  11277. /**
  11278. * Module dependencies.
  11279. */
  11280. var tty = __webpack_require__(66);
  11281. var util = __webpack_require__(56);
  11282. /**
  11283. * This is the Node.js implementation of `debug()`.
  11284. *
  11285. * Expose `debug()` as the module.
  11286. */
  11287. exports = module.exports = __webpack_require__(63);
  11288. exports.init = init;
  11289. exports.log = log;
  11290. exports.formatArgs = formatArgs;
  11291. exports.save = save;
  11292. exports.load = load;
  11293. exports.useColors = useColors;
  11294. /**
  11295. * Colors.
  11296. */
  11297. exports.colors = [ 6, 2, 3, 4, 5, 1 ];
  11298. try {
  11299. var supportsColor = __webpack_require__(67);
  11300. if (supportsColor && supportsColor.level >= 2) {
  11301. exports.colors = [
  11302. 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68,
  11303. 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134,
  11304. 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171,
  11305. 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204,
  11306. 205, 206, 207, 208, 209, 214, 215, 220, 221
  11307. ];
  11308. }
  11309. } catch (err) {
  11310. // swallow - we only care if `supports-color` is available; it doesn't have to be.
  11311. }
  11312. /**
  11313. * Build up the default `inspectOpts` object from the environment variables.
  11314. *
  11315. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  11316. */
  11317. exports.inspectOpts = Object.keys(process.env).filter(function (key) {
  11318. return /^debug_/i.test(key);
  11319. }).reduce(function (obj, key) {
  11320. // camel-case
  11321. var prop = key
  11322. .substring(6)
  11323. .toLowerCase()
  11324. .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
  11325. // coerce string value into JS value
  11326. var val = process.env[key];
  11327. if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
  11328. else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
  11329. else if (val === 'null') val = null;
  11330. else val = Number(val);
  11331. obj[prop] = val;
  11332. return obj;
  11333. }, {});
  11334. /**
  11335. * Is stdout a TTY? Colored output is enabled when `true`.
  11336. */
  11337. function useColors() {
  11338. return 'colors' in exports.inspectOpts
  11339. ? Boolean(exports.inspectOpts.colors)
  11340. : tty.isatty(process.stderr.fd);
  11341. }
  11342. /**
  11343. * Map %o to `util.inspect()`, all on a single line.
  11344. */
  11345. exports.formatters.o = function(v) {
  11346. this.inspectOpts.colors = this.useColors;
  11347. return util.inspect(v, this.inspectOpts)
  11348. .split('\n').map(function(str) {
  11349. return str.trim()
  11350. }).join(' ');
  11351. };
  11352. /**
  11353. * Map %o to `util.inspect()`, allowing multiple lines if needed.
  11354. */
  11355. exports.formatters.O = function(v) {
  11356. this.inspectOpts.colors = this.useColors;
  11357. return util.inspect(v, this.inspectOpts);
  11358. };
  11359. /**
  11360. * Adds ANSI color escape codes if enabled.
  11361. *
  11362. * @api public
  11363. */
  11364. function formatArgs(args) {
  11365. var name = this.namespace;
  11366. var useColors = this.useColors;
  11367. if (useColors) {
  11368. var c = this.color;
  11369. var colorCode = '\u001b[3' + (c < 8 ? c : '8;5;' + c);
  11370. var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m';
  11371. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  11372. args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
  11373. } else {
  11374. args[0] = getDate() + name + ' ' + args[0];
  11375. }
  11376. }
  11377. function getDate() {
  11378. if (exports.inspectOpts.hideDate) {
  11379. return '';
  11380. } else {
  11381. return new Date().toISOString() + ' ';
  11382. }
  11383. }
  11384. /**
  11385. * Invokes `util.format()` with the specified arguments and writes to stderr.
  11386. */
  11387. function log() {
  11388. return process.stderr.write(util.format.apply(util, arguments) + '\n');
  11389. }
  11390. /**
  11391. * Save `namespaces`.
  11392. *
  11393. * @param {String} namespaces
  11394. * @api private
  11395. */
  11396. function save(namespaces) {
  11397. if (null == namespaces) {
  11398. // If you set a process.env field to null or undefined, it gets cast to the
  11399. // string 'null' or 'undefined'. Just delete instead.
  11400. delete process.env.DEBUG;
  11401. } else {
  11402. process.env.DEBUG = namespaces;
  11403. }
  11404. }
  11405. /**
  11406. * Load `namespaces`.
  11407. *
  11408. * @return {String} returns the previously persisted debug modes
  11409. * @api private
  11410. */
  11411. function load() {
  11412. return process.env.DEBUG;
  11413. }
  11414. /**
  11415. * Init logic for `debug` instances.
  11416. *
  11417. * Create a new `inspectOpts` object in case `useColors` is set
  11418. * differently for a particular `debug` instance.
  11419. */
  11420. function init (debug) {
  11421. debug.inspectOpts = {};
  11422. var keys = Object.keys(exports.inspectOpts);
  11423. for (var i = 0; i < keys.length; i++) {
  11424. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  11425. }
  11426. }
  11427. /**
  11428. * Enable namespaces listed in `process.env.DEBUG` initially.
  11429. */
  11430. exports.enable(load());
  11431. /***/ }),
  11432. /* 66 */
  11433. /***/ (function(module, exports) {
  11434. module.exports = require("tty");
  11435. /***/ }),
  11436. /* 67 */
  11437. /***/ (function(module, exports, __webpack_require__) {
  11438. "use strict";
  11439. const os = __webpack_require__(13);
  11440. const hasFlag = __webpack_require__(68);
  11441. const env = process.env;
  11442. let forceColor;
  11443. if (hasFlag('no-color') ||
  11444. hasFlag('no-colors') ||
  11445. hasFlag('color=false')) {
  11446. forceColor = false;
  11447. } else if (hasFlag('color') ||
  11448. hasFlag('colors') ||
  11449. hasFlag('color=true') ||
  11450. hasFlag('color=always')) {
  11451. forceColor = true;
  11452. }
  11453. if ('FORCE_COLOR' in env) {
  11454. forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
  11455. }
  11456. function translateLevel(level) {
  11457. if (level === 0) {
  11458. return false;
  11459. }
  11460. return {
  11461. level,
  11462. hasBasic: true,
  11463. has256: level >= 2,
  11464. has16m: level >= 3
  11465. };
  11466. }
  11467. function supportsColor(stream) {
  11468. if (forceColor === false) {
  11469. return 0;
  11470. }
  11471. if (hasFlag('color=16m') ||
  11472. hasFlag('color=full') ||
  11473. hasFlag('color=truecolor')) {
  11474. return 3;
  11475. }
  11476. if (hasFlag('color=256')) {
  11477. return 2;
  11478. }
  11479. if (stream && !stream.isTTY && forceColor !== true) {
  11480. return 0;
  11481. }
  11482. const min = forceColor ? 1 : 0;
  11483. if (process.platform === 'win32') {
  11484. // Node.js 7.5.0 is the first version of Node.js to include a patch to
  11485. // libuv that enables 256 color output on Windows. Anything earlier and it
  11486. // won't work. However, here we target Node.js 8 at minimum as it is an LTS
  11487. // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
  11488. // release that supports 256 colors. Windows 10 build 14931 is the first release
  11489. // that supports 16m/TrueColor.
  11490. const osRelease = os.release().split('.');
  11491. if (
  11492. Number(process.versions.node.split('.')[0]) >= 8 &&
  11493. Number(osRelease[0]) >= 10 &&
  11494. Number(osRelease[2]) >= 10586
  11495. ) {
  11496. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  11497. }
  11498. return 1;
  11499. }
  11500. if ('CI' in env) {
  11501. if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
  11502. return 1;
  11503. }
  11504. return min;
  11505. }
  11506. if ('TEAMCITY_VERSION' in env) {
  11507. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  11508. }
  11509. if (env.COLORTERM === 'truecolor') {
  11510. return 3;
  11511. }
  11512. if ('TERM_PROGRAM' in env) {
  11513. const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
  11514. switch (env.TERM_PROGRAM) {
  11515. case 'iTerm.app':
  11516. return version >= 3 ? 3 : 2;
  11517. case 'Apple_Terminal':
  11518. return 2;
  11519. // No default
  11520. }
  11521. }
  11522. if (/-256(color)?$/i.test(env.TERM)) {
  11523. return 2;
  11524. }
  11525. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
  11526. return 1;
  11527. }
  11528. if ('COLORTERM' in env) {
  11529. return 1;
  11530. }
  11531. if (env.TERM === 'dumb') {
  11532. return min;
  11533. }
  11534. return min;
  11535. }
  11536. function getSupportLevel(stream) {
  11537. const level = supportsColor(stream);
  11538. return translateLevel(level);
  11539. }
  11540. module.exports = {
  11541. supportsColor: getSupportLevel,
  11542. stdout: getSupportLevel(process.stdout),
  11543. stderr: getSupportLevel(process.stderr)
  11544. };
  11545. /***/ }),
  11546. /* 68 */
  11547. /***/ (function(module, exports, __webpack_require__) {
  11548. "use strict";
  11549. module.exports = (flag, argv) => {
  11550. argv = argv || process.argv;
  11551. const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
  11552. const pos = argv.indexOf(prefix + flag);
  11553. const terminatorPos = argv.indexOf('--');
  11554. return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
  11555. };
  11556. /***/ }),
  11557. /* 69 */
  11558. /***/ (function(module, exports, __webpack_require__) {
  11559. /**
  11560. * Module dependencies.
  11561. */
  11562. var net = __webpack_require__(15);
  11563. var tls = __webpack_require__(53);
  11564. var url = __webpack_require__(40);
  11565. var Agent = __webpack_require__(54);
  11566. var inherits = __webpack_require__(56).inherits;
  11567. var debug = __webpack_require__(70)('https-proxy-agent');
  11568. /**
  11569. * Module exports.
  11570. */
  11571. module.exports = HttpsProxyAgent;
  11572. /**
  11573. * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to the
  11574. * specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
  11575. *
  11576. * @api public
  11577. */
  11578. function HttpsProxyAgent(opts) {
  11579. if (!(this instanceof HttpsProxyAgent)) return new HttpsProxyAgent(opts);
  11580. if ('string' == typeof opts) opts = url.parse(opts);
  11581. if (!opts)
  11582. throw new Error(
  11583. 'an HTTP(S) proxy server `host` and `port` must be specified!'
  11584. );
  11585. debug('creating new HttpsProxyAgent instance: %o', opts);
  11586. Agent.call(this, opts);
  11587. var proxy = Object.assign({}, opts);
  11588. // if `true`, then connect to the proxy server over TLS. defaults to `false`.
  11589. this.secureProxy = proxy.protocol ? /^https:?$/i.test(proxy.protocol) : false;
  11590. // prefer `hostname` over `host`, and set the `port` if needed
  11591. proxy.host = proxy.hostname || proxy.host;
  11592. proxy.port = +proxy.port || (this.secureProxy ? 443 : 80);
  11593. // ALPN is supported by Node.js >= v5.
  11594. // attempt to negotiate http/1.1 for proxy servers that support http/2
  11595. if (this.secureProxy && !('ALPNProtocols' in proxy)) {
  11596. proxy.ALPNProtocols = ['http 1.1']
  11597. }
  11598. if (proxy.host && proxy.path) {
  11599. // if both a `host` and `path` are specified then it's most likely the
  11600. // result of a `url.parse()` call... we need to remove the `path` portion so
  11601. // that `net.connect()` doesn't attempt to open that as a unix socket file.
  11602. delete proxy.path;
  11603. delete proxy.pathname;
  11604. }
  11605. this.proxy = proxy;
  11606. this.defaultPort = 443;
  11607. }
  11608. inherits(HttpsProxyAgent, Agent);
  11609. /**
  11610. * Called when the node-core HTTP client library is creating a new HTTP request.
  11611. *
  11612. * @api public
  11613. */
  11614. HttpsProxyAgent.prototype.callback = function connect(req, opts, fn) {
  11615. var proxy = this.proxy;
  11616. // create a socket connection to the proxy server
  11617. var socket;
  11618. if (this.secureProxy) {
  11619. socket = tls.connect(proxy);
  11620. } else {
  11621. socket = net.connect(proxy);
  11622. }
  11623. // we need to buffer any HTTP traffic that happens with the proxy before we get
  11624. // the CONNECT response, so that if the response is anything other than an "200"
  11625. // response code, then we can re-play the "data" events on the socket once the
  11626. // HTTP parser is hooked up...
  11627. var buffers = [];
  11628. var buffersLength = 0;
  11629. function read() {
  11630. var b = socket.read();
  11631. if (b) ondata(b);
  11632. else socket.once('readable', read);
  11633. }
  11634. function cleanup() {
  11635. socket.removeListener('data', ondata);
  11636. socket.removeListener('end', onend);
  11637. socket.removeListener('error', onerror);
  11638. socket.removeListener('close', onclose);
  11639. socket.removeListener('readable', read);
  11640. }
  11641. function onclose(err) {
  11642. debug('onclose had error %o', err);
  11643. }
  11644. function onend() {
  11645. debug('onend');
  11646. }
  11647. function onerror(err) {
  11648. cleanup();
  11649. fn(err);
  11650. }
  11651. function ondata(b) {
  11652. buffers.push(b);
  11653. buffersLength += b.length;
  11654. var buffered = Buffer.concat(buffers, buffersLength);
  11655. var str = buffered.toString('ascii');
  11656. if (!~str.indexOf('\r\n\r\n')) {
  11657. // keep buffering
  11658. debug('have not received end of HTTP headers yet...');
  11659. if (socket.read) {
  11660. read();
  11661. } else {
  11662. socket.once('data', ondata);
  11663. }
  11664. return;
  11665. }
  11666. var firstLine = str.substring(0, str.indexOf('\r\n'));
  11667. var statusCode = +firstLine.split(' ')[1];
  11668. debug('got proxy server response: %o', firstLine);
  11669. if (200 == statusCode) {
  11670. // 200 Connected status code!
  11671. var sock = socket;
  11672. // nullify the buffered data since we won't be needing it
  11673. buffers = buffered = null;
  11674. if (opts.secureEndpoint) {
  11675. // since the proxy is connecting to an SSL server, we have
  11676. // to upgrade this socket connection to an SSL connection
  11677. debug(
  11678. 'upgrading proxy-connected socket to TLS connection: %o',
  11679. opts.host
  11680. );
  11681. opts.socket = socket;
  11682. opts.servername = opts.servername || opts.host;
  11683. opts.host = null;
  11684. opts.hostname = null;
  11685. opts.port = null;
  11686. sock = tls.connect(opts);
  11687. }
  11688. cleanup();
  11689. fn(null, sock);
  11690. } else {
  11691. // some other status code that's not 200... need to re-play the HTTP header
  11692. // "data" events onto the socket once the HTTP machinery is attached so that
  11693. // the user can parse and handle the error status code
  11694. cleanup();
  11695. // save a reference to the concat'd Buffer for the `onsocket` callback
  11696. buffers = buffered;
  11697. // need to wait for the "socket" event to re-play the "data" events
  11698. req.once('socket', onsocket);
  11699. fn(null, socket);
  11700. }
  11701. }
  11702. function onsocket(socket) {
  11703. // replay the "buffers" Buffer onto the `socket`, since at this point
  11704. // the HTTP module machinery has been hooked up for the user
  11705. if ('function' == typeof socket.ondata) {
  11706. // node <= v0.11.3, the `ondata` function is set on the socket
  11707. socket.ondata(buffers, 0, buffers.length);
  11708. } else if (socket.listeners('data').length > 0) {
  11709. // node > v0.11.3, the "data" event is listened for directly
  11710. socket.emit('data', buffers);
  11711. } else {
  11712. // never?
  11713. throw new Error('should not happen...');
  11714. }
  11715. // nullify the cached Buffer instance
  11716. buffers = null;
  11717. }
  11718. socket.on('error', onerror);
  11719. socket.on('close', onclose);
  11720. socket.on('end', onend);
  11721. if (socket.read) {
  11722. read();
  11723. } else {
  11724. socket.once('data', ondata);
  11725. }
  11726. var hostname = opts.host + ':' + opts.port;
  11727. var msg = 'CONNECT ' + hostname + ' HTTP/1.1\r\n';
  11728. var headers = Object.assign({}, proxy.headers);
  11729. if (proxy.auth) {
  11730. headers['Proxy-Authorization'] =
  11731. 'Basic ' + Buffer.from(proxy.auth).toString('base64');
  11732. }
  11733. // the Host header should only include the port
  11734. // number when it is a non-standard port
  11735. var host = opts.host;
  11736. if (!isDefaultPort(opts.port, opts.secureEndpoint)) {
  11737. host += ':' + opts.port;
  11738. }
  11739. headers['Host'] = host;
  11740. headers['Connection'] = 'close';
  11741. Object.keys(headers).forEach(function(name) {
  11742. msg += name + ': ' + headers[name] + '\r\n';
  11743. });
  11744. socket.write(msg + '\r\n');
  11745. };
  11746. function isDefaultPort(port, secure) {
  11747. return Boolean((!secure && port === 80) || (secure && port === 443));
  11748. }
  11749. /***/ }),
  11750. /* 70 */
  11751. /***/ (function(module, exports, __webpack_require__) {
  11752. "use strict";
  11753. /**
  11754. * Detect Electron renderer / nwjs process, which is node, but we should
  11755. * treat as a browser.
  11756. */
  11757. if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
  11758. module.exports = __webpack_require__(71);
  11759. } else {
  11760. module.exports = __webpack_require__(74);
  11761. }
  11762. /***/ }),
  11763. /* 71 */
  11764. /***/ (function(module, exports, __webpack_require__) {
  11765. "use strict";
  11766. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  11767. /* eslint-env browser */
  11768. /**
  11769. * This is the web browser implementation of `debug()`.
  11770. */
  11771. exports.log = log;
  11772. exports.formatArgs = formatArgs;
  11773. exports.save = save;
  11774. exports.load = load;
  11775. exports.useColors = useColors;
  11776. exports.storage = localstorage();
  11777. /**
  11778. * Colors.
  11779. */
  11780. exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
  11781. /**
  11782. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  11783. * and the Firebug extension (any Firefox version) are known
  11784. * to support "%c" CSS customizations.
  11785. *
  11786. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  11787. */
  11788. // eslint-disable-next-line complexity
  11789. function useColors() {
  11790. // NB: In an Electron preload script, document will be defined but not fully
  11791. // initialized. Since we know we're in Chrome, we'll just detect this case
  11792. // explicitly
  11793. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  11794. return true;
  11795. } // Internet Explorer and Edge do not support colors.
  11796. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  11797. return false;
  11798. } // Is webkit? http://stackoverflow.com/a/16459606/376773
  11799. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  11800. return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
  11801. typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
  11802. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  11803. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
  11804. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
  11805. }
  11806. /**
  11807. * Colorize log arguments if enabled.
  11808. *
  11809. * @api public
  11810. */
  11811. function formatArgs(args) {
  11812. args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
  11813. if (!this.useColors) {
  11814. return;
  11815. }
  11816. var c = 'color: ' + this.color;
  11817. args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
  11818. // arguments passed either before or after the %c, so we need to
  11819. // figure out the correct index to insert the CSS into
  11820. var index = 0;
  11821. var lastC = 0;
  11822. args[0].replace(/%[a-zA-Z%]/g, function (match) {
  11823. if (match === '%%') {
  11824. return;
  11825. }
  11826. index++;
  11827. if (match === '%c') {
  11828. // We only are interested in the *last* %c
  11829. // (the user may have provided their own)
  11830. lastC = index;
  11831. }
  11832. });
  11833. args.splice(lastC, 0, c);
  11834. }
  11835. /**
  11836. * Invokes `console.log()` when available.
  11837. * No-op when `console.log` is not a "function".
  11838. *
  11839. * @api public
  11840. */
  11841. function log() {
  11842. var _console;
  11843. // This hackery is required for IE8/9, where
  11844. // the `console.log` function doesn't have 'apply'
  11845. return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
  11846. }
  11847. /**
  11848. * Save `namespaces`.
  11849. *
  11850. * @param {String} namespaces
  11851. * @api private
  11852. */
  11853. function save(namespaces) {
  11854. try {
  11855. if (namespaces) {
  11856. exports.storage.setItem('debug', namespaces);
  11857. } else {
  11858. exports.storage.removeItem('debug');
  11859. }
  11860. } catch (error) {// Swallow
  11861. // XXX (@Qix-) should we be logging these?
  11862. }
  11863. }
  11864. /**
  11865. * Load `namespaces`.
  11866. *
  11867. * @return {String} returns the previously persisted debug modes
  11868. * @api private
  11869. */
  11870. function load() {
  11871. var r;
  11872. try {
  11873. r = exports.storage.getItem('debug');
  11874. } catch (error) {} // Swallow
  11875. // XXX (@Qix-) should we be logging these?
  11876. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  11877. if (!r && typeof process !== 'undefined' && 'env' in process) {
  11878. r = process.env.DEBUG;
  11879. }
  11880. return r;
  11881. }
  11882. /**
  11883. * Localstorage attempts to return the localstorage.
  11884. *
  11885. * This is necessary because safari throws
  11886. * when a user disables cookies/localstorage
  11887. * and you attempt to access it.
  11888. *
  11889. * @return {LocalStorage}
  11890. * @api private
  11891. */
  11892. function localstorage() {
  11893. try {
  11894. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  11895. // The Browser also has localStorage in the global context.
  11896. return localStorage;
  11897. } catch (error) {// Swallow
  11898. // XXX (@Qix-) should we be logging these?
  11899. }
  11900. }
  11901. module.exports = __webpack_require__(72)(exports);
  11902. var formatters = module.exports.formatters;
  11903. /**
  11904. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  11905. */
  11906. formatters.j = function (v) {
  11907. try {
  11908. return JSON.stringify(v);
  11909. } catch (error) {
  11910. return '[UnexpectedJSONParseError]: ' + error.message;
  11911. }
  11912. };
  11913. /***/ }),
  11914. /* 72 */
  11915. /***/ (function(module, exports, __webpack_require__) {
  11916. "use strict";
  11917. /**
  11918. * This is the common logic for both the Node.js and web browser
  11919. * implementations of `debug()`.
  11920. */
  11921. function setup(env) {
  11922. createDebug.debug = createDebug;
  11923. createDebug.default = createDebug;
  11924. createDebug.coerce = coerce;
  11925. createDebug.disable = disable;
  11926. createDebug.enable = enable;
  11927. createDebug.enabled = enabled;
  11928. createDebug.humanize = __webpack_require__(73);
  11929. Object.keys(env).forEach(function (key) {
  11930. createDebug[key] = env[key];
  11931. });
  11932. /**
  11933. * Active `debug` instances.
  11934. */
  11935. createDebug.instances = [];
  11936. /**
  11937. * The currently active debug mode names, and names to skip.
  11938. */
  11939. createDebug.names = [];
  11940. createDebug.skips = [];
  11941. /**
  11942. * Map of special "%n" handling functions, for the debug "format" argument.
  11943. *
  11944. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  11945. */
  11946. createDebug.formatters = {};
  11947. /**
  11948. * Selects a color for a debug namespace
  11949. * @param {String} namespace The namespace string for the for the debug instance to be colored
  11950. * @return {Number|String} An ANSI color code for the given namespace
  11951. * @api private
  11952. */
  11953. function selectColor(namespace) {
  11954. var hash = 0;
  11955. for (var i = 0; i < namespace.length; i++) {
  11956. hash = (hash << 5) - hash + namespace.charCodeAt(i);
  11957. hash |= 0; // Convert to 32bit integer
  11958. }
  11959. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  11960. }
  11961. createDebug.selectColor = selectColor;
  11962. /**
  11963. * Create a debugger with the given `namespace`.
  11964. *
  11965. * @param {String} namespace
  11966. * @return {Function}
  11967. * @api public
  11968. */
  11969. function createDebug(namespace) {
  11970. var prevTime;
  11971. function debug() {
  11972. // Disabled?
  11973. if (!debug.enabled) {
  11974. return;
  11975. }
  11976. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  11977. args[_key] = arguments[_key];
  11978. }
  11979. var self = debug; // Set `diff` timestamp
  11980. var curr = Number(new Date());
  11981. var ms = curr - (prevTime || curr);
  11982. self.diff = ms;
  11983. self.prev = prevTime;
  11984. self.curr = curr;
  11985. prevTime = curr;
  11986. args[0] = createDebug.coerce(args[0]);
  11987. if (typeof args[0] !== 'string') {
  11988. // Anything else let's inspect with %O
  11989. args.unshift('%O');
  11990. } // Apply any `formatters` transformations
  11991. var index = 0;
  11992. args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
  11993. // If we encounter an escaped % then don't increase the array index
  11994. if (match === '%%') {
  11995. return match;
  11996. }
  11997. index++;
  11998. var formatter = createDebug.formatters[format];
  11999. if (typeof formatter === 'function') {
  12000. var val = args[index];
  12001. match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
  12002. args.splice(index, 1);
  12003. index--;
  12004. }
  12005. return match;
  12006. }); // Apply env-specific formatting (colors, etc.)
  12007. createDebug.formatArgs.call(self, args);
  12008. var logFn = self.log || createDebug.log;
  12009. logFn.apply(self, args);
  12010. }
  12011. debug.namespace = namespace;
  12012. debug.enabled = createDebug.enabled(namespace);
  12013. debug.useColors = createDebug.useColors();
  12014. debug.color = selectColor(namespace);
  12015. debug.destroy = destroy;
  12016. debug.extend = extend; // Debug.formatArgs = formatArgs;
  12017. // debug.rawLog = rawLog;
  12018. // env-specific initialization logic for debug instances
  12019. if (typeof createDebug.init === 'function') {
  12020. createDebug.init(debug);
  12021. }
  12022. createDebug.instances.push(debug);
  12023. return debug;
  12024. }
  12025. function destroy() {
  12026. var index = createDebug.instances.indexOf(this);
  12027. if (index !== -1) {
  12028. createDebug.instances.splice(index, 1);
  12029. return true;
  12030. }
  12031. return false;
  12032. }
  12033. function extend(namespace, delimiter) {
  12034. return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  12035. }
  12036. /**
  12037. * Enables a debug mode by namespaces. This can include modes
  12038. * separated by a colon and wildcards.
  12039. *
  12040. * @param {String} namespaces
  12041. * @api public
  12042. */
  12043. function enable(namespaces) {
  12044. createDebug.save(namespaces);
  12045. createDebug.names = [];
  12046. createDebug.skips = [];
  12047. var i;
  12048. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  12049. var len = split.length;
  12050. for (i = 0; i < len; i++) {
  12051. if (!split[i]) {
  12052. // ignore empty strings
  12053. continue;
  12054. }
  12055. namespaces = split[i].replace(/\*/g, '.*?');
  12056. if (namespaces[0] === '-') {
  12057. createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  12058. } else {
  12059. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  12060. }
  12061. }
  12062. for (i = 0; i < createDebug.instances.length; i++) {
  12063. var instance = createDebug.instances[i];
  12064. instance.enabled = createDebug.enabled(instance.namespace);
  12065. }
  12066. }
  12067. /**
  12068. * Disable debug output.
  12069. *
  12070. * @api public
  12071. */
  12072. function disable() {
  12073. createDebug.enable('');
  12074. }
  12075. /**
  12076. * Returns true if the given mode name is enabled, false otherwise.
  12077. *
  12078. * @param {String} name
  12079. * @return {Boolean}
  12080. * @api public
  12081. */
  12082. function enabled(name) {
  12083. if (name[name.length - 1] === '*') {
  12084. return true;
  12085. }
  12086. var i;
  12087. var len;
  12088. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  12089. if (createDebug.skips[i].test(name)) {
  12090. return false;
  12091. }
  12092. }
  12093. for (i = 0, len = createDebug.names.length; i < len; i++) {
  12094. if (createDebug.names[i].test(name)) {
  12095. return true;
  12096. }
  12097. }
  12098. return false;
  12099. }
  12100. /**
  12101. * Coerce `val`.
  12102. *
  12103. * @param {Mixed} val
  12104. * @return {Mixed}
  12105. * @api private
  12106. */
  12107. function coerce(val) {
  12108. if (val instanceof Error) {
  12109. return val.stack || val.message;
  12110. }
  12111. return val;
  12112. }
  12113. createDebug.enable(createDebug.load());
  12114. return createDebug;
  12115. }
  12116. module.exports = setup;
  12117. /***/ }),
  12118. /* 73 */
  12119. /***/ (function(module, exports) {
  12120. /**
  12121. * Helpers.
  12122. */
  12123. var s = 1000;
  12124. var m = s * 60;
  12125. var h = m * 60;
  12126. var d = h * 24;
  12127. var w = d * 7;
  12128. var y = d * 365.25;
  12129. /**
  12130. * Parse or format the given `val`.
  12131. *
  12132. * Options:
  12133. *
  12134. * - `long` verbose formatting [false]
  12135. *
  12136. * @param {String|Number} val
  12137. * @param {Object} [options]
  12138. * @throws {Error} throw an error if val is not a non-empty string or a number
  12139. * @return {String|Number}
  12140. * @api public
  12141. */
  12142. module.exports = function(val, options) {
  12143. options = options || {};
  12144. var type = typeof val;
  12145. if (type === 'string' && val.length > 0) {
  12146. return parse(val);
  12147. } else if (type === 'number' && isFinite(val)) {
  12148. return options.long ? fmtLong(val) : fmtShort(val);
  12149. }
  12150. throw new Error(
  12151. 'val is not a non-empty string or a valid number. val=' +
  12152. JSON.stringify(val)
  12153. );
  12154. };
  12155. /**
  12156. * Parse the given `str` and return milliseconds.
  12157. *
  12158. * @param {String} str
  12159. * @return {Number}
  12160. * @api private
  12161. */
  12162. function parse(str) {
  12163. str = String(str);
  12164. if (str.length > 100) {
  12165. return;
  12166. }
  12167. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  12168. str
  12169. );
  12170. if (!match) {
  12171. return;
  12172. }
  12173. var n = parseFloat(match[1]);
  12174. var type = (match[2] || 'ms').toLowerCase();
  12175. switch (type) {
  12176. case 'years':
  12177. case 'year':
  12178. case 'yrs':
  12179. case 'yr':
  12180. case 'y':
  12181. return n * y;
  12182. case 'weeks':
  12183. case 'week':
  12184. case 'w':
  12185. return n * w;
  12186. case 'days':
  12187. case 'day':
  12188. case 'd':
  12189. return n * d;
  12190. case 'hours':
  12191. case 'hour':
  12192. case 'hrs':
  12193. case 'hr':
  12194. case 'h':
  12195. return n * h;
  12196. case 'minutes':
  12197. case 'minute':
  12198. case 'mins':
  12199. case 'min':
  12200. case 'm':
  12201. return n * m;
  12202. case 'seconds':
  12203. case 'second':
  12204. case 'secs':
  12205. case 'sec':
  12206. case 's':
  12207. return n * s;
  12208. case 'milliseconds':
  12209. case 'millisecond':
  12210. case 'msecs':
  12211. case 'msec':
  12212. case 'ms':
  12213. return n;
  12214. default:
  12215. return undefined;
  12216. }
  12217. }
  12218. /**
  12219. * Short format for `ms`.
  12220. *
  12221. * @param {Number} ms
  12222. * @return {String}
  12223. * @api private
  12224. */
  12225. function fmtShort(ms) {
  12226. var msAbs = Math.abs(ms);
  12227. if (msAbs >= d) {
  12228. return Math.round(ms / d) + 'd';
  12229. }
  12230. if (msAbs >= h) {
  12231. return Math.round(ms / h) + 'h';
  12232. }
  12233. if (msAbs >= m) {
  12234. return Math.round(ms / m) + 'm';
  12235. }
  12236. if (msAbs >= s) {
  12237. return Math.round(ms / s) + 's';
  12238. }
  12239. return ms + 'ms';
  12240. }
  12241. /**
  12242. * Long format for `ms`.
  12243. *
  12244. * @param {Number} ms
  12245. * @return {String}
  12246. * @api private
  12247. */
  12248. function fmtLong(ms) {
  12249. var msAbs = Math.abs(ms);
  12250. if (msAbs >= d) {
  12251. return plural(ms, msAbs, d, 'day');
  12252. }
  12253. if (msAbs >= h) {
  12254. return plural(ms, msAbs, h, 'hour');
  12255. }
  12256. if (msAbs >= m) {
  12257. return plural(ms, msAbs, m, 'minute');
  12258. }
  12259. if (msAbs >= s) {
  12260. return plural(ms, msAbs, s, 'second');
  12261. }
  12262. return ms + ' ms';
  12263. }
  12264. /**
  12265. * Pluralization helper.
  12266. */
  12267. function plural(ms, msAbs, n, name) {
  12268. var isPlural = msAbs >= n * 1.5;
  12269. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  12270. }
  12271. /***/ }),
  12272. /* 74 */
  12273. /***/ (function(module, exports, __webpack_require__) {
  12274. "use strict";
  12275. /**
  12276. * Module dependencies.
  12277. */
  12278. var tty = __webpack_require__(66);
  12279. var util = __webpack_require__(56);
  12280. /**
  12281. * This is the Node.js implementation of `debug()`.
  12282. */
  12283. exports.init = init;
  12284. exports.log = log;
  12285. exports.formatArgs = formatArgs;
  12286. exports.save = save;
  12287. exports.load = load;
  12288. exports.useColors = useColors;
  12289. /**
  12290. * Colors.
  12291. */
  12292. exports.colors = [6, 2, 3, 4, 5, 1];
  12293. try {
  12294. // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
  12295. // eslint-disable-next-line import/no-extraneous-dependencies
  12296. var supportsColor = __webpack_require__(67);
  12297. if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
  12298. exports.colors = [20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221];
  12299. }
  12300. } catch (error) {} // Swallow - we only care if `supports-color` is available; it doesn't have to be.
  12301. /**
  12302. * Build up the default `inspectOpts` object from the environment variables.
  12303. *
  12304. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  12305. */
  12306. exports.inspectOpts = Object.keys(process.env).filter(function (key) {
  12307. return /^debug_/i.test(key);
  12308. }).reduce(function (obj, key) {
  12309. // Camel-case
  12310. var prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, function (_, k) {
  12311. return k.toUpperCase();
  12312. }); // Coerce string value into JS value
  12313. var val = process.env[key];
  12314. if (/^(yes|on|true|enabled)$/i.test(val)) {
  12315. val = true;
  12316. } else if (/^(no|off|false|disabled)$/i.test(val)) {
  12317. val = false;
  12318. } else if (val === 'null') {
  12319. val = null;
  12320. } else {
  12321. val = Number(val);
  12322. }
  12323. obj[prop] = val;
  12324. return obj;
  12325. }, {});
  12326. /**
  12327. * Is stdout a TTY? Colored output is enabled when `true`.
  12328. */
  12329. function useColors() {
  12330. return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd);
  12331. }
  12332. /**
  12333. * Adds ANSI color escape codes if enabled.
  12334. *
  12335. * @api public
  12336. */
  12337. function formatArgs(args) {
  12338. var name = this.namespace,
  12339. useColors = this.useColors;
  12340. if (useColors) {
  12341. var c = this.color;
  12342. var colorCode = "\x1B[3" + (c < 8 ? c : '8;5;' + c);
  12343. var prefix = " ".concat(colorCode, ";1m").concat(name, " \x1B[0m");
  12344. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  12345. args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + "\x1B[0m");
  12346. } else {
  12347. args[0] = getDate() + name + ' ' + args[0];
  12348. }
  12349. }
  12350. function getDate() {
  12351. if (exports.inspectOpts.hideDate) {
  12352. return '';
  12353. }
  12354. return new Date().toISOString() + ' ';
  12355. }
  12356. /**
  12357. * Invokes `util.format()` with the specified arguments and writes to stderr.
  12358. */
  12359. function log() {
  12360. return process.stderr.write(util.format.apply(util, arguments) + '\n');
  12361. }
  12362. /**
  12363. * Save `namespaces`.
  12364. *
  12365. * @param {String} namespaces
  12366. * @api private
  12367. */
  12368. function save(namespaces) {
  12369. if (namespaces) {
  12370. process.env.DEBUG = namespaces;
  12371. } else {
  12372. // If you set a process.env field to null or undefined, it gets cast to the
  12373. // string 'null' or 'undefined'. Just delete instead.
  12374. delete process.env.DEBUG;
  12375. }
  12376. }
  12377. /**
  12378. * Load `namespaces`.
  12379. *
  12380. * @return {String} returns the previously persisted debug modes
  12381. * @api private
  12382. */
  12383. function load() {
  12384. return process.env.DEBUG;
  12385. }
  12386. /**
  12387. * Init logic for `debug` instances.
  12388. *
  12389. * Create a new `inspectOpts` object in case `useColors` is set
  12390. * differently for a particular `debug` instance.
  12391. */
  12392. function init(debug) {
  12393. debug.inspectOpts = {};
  12394. var keys = Object.keys(exports.inspectOpts);
  12395. for (var i = 0; i < keys.length; i++) {
  12396. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  12397. }
  12398. }
  12399. module.exports = __webpack_require__(72)(exports);
  12400. var formatters = module.exports.formatters;
  12401. /**
  12402. * Map %o to `util.inspect()`, all on a single line.
  12403. */
  12404. formatters.o = function (v) {
  12405. this.inspectOpts.colors = this.useColors;
  12406. return util.inspect(v, this.inspectOpts).replace(/\s*\n\s*/g, ' ');
  12407. };
  12408. /**
  12409. * Map %O to `util.inspect()`, allowing multiple lines if needed.
  12410. */
  12411. formatters.O = function (v) {
  12412. this.inspectOpts.colors = this.useColors;
  12413. return util.inspect(v, this.inspectOpts);
  12414. };
  12415. /***/ }),
  12416. /* 75 */
  12417. /***/ (function(module, exports) {
  12418. module.exports = require("zlib");
  12419. /***/ }),
  12420. /* 76 */
  12421. /***/ (function(module, exports, __webpack_require__) {
  12422. "use strict";
  12423. /* --------------------------------------------------------------------------------------------
  12424. * Copyright (c) Microsoft Corporation. All rights reserved.
  12425. * Licensed under the MIT License. See License.txt in the project root for license information.
  12426. * ------------------------------------------------------------------------------------------ */
  12427. Object.defineProperty(exports, "__esModule", { value: true });
  12428. var path = __webpack_require__(1);
  12429. var fs = __webpack_require__(2);
  12430. var toString = Object.prototype.toString;
  12431. function isDefined(value) {
  12432. return typeof value !== 'undefined';
  12433. }
  12434. function isNumber(value) {
  12435. return toString.call(value) === '[object Number]';
  12436. }
  12437. function isString(value) {
  12438. return toString.call(value) === '[object String]';
  12439. }
  12440. function isBoolean(value) {
  12441. return value === true || value === false;
  12442. }
  12443. function readJsonFileSync(filename) {
  12444. return JSON.parse(fs.readFileSync(filename, 'utf8'));
  12445. }
  12446. var MessageFormat;
  12447. (function (MessageFormat) {
  12448. MessageFormat["file"] = "file";
  12449. MessageFormat["bundle"] = "bundle";
  12450. MessageFormat["both"] = "both";
  12451. })(MessageFormat = exports.MessageFormat || (exports.MessageFormat = {}));
  12452. var BundleFormat;
  12453. (function (BundleFormat) {
  12454. // the nls.bundle format
  12455. BundleFormat["standalone"] = "standalone";
  12456. BundleFormat["languagePack"] = "languagePack";
  12457. })(BundleFormat = exports.BundleFormat || (exports.BundleFormat = {}));
  12458. var LocalizeInfo;
  12459. (function (LocalizeInfo) {
  12460. function is(value) {
  12461. var candidate = value;
  12462. return candidate && isDefined(candidate.key) && isDefined(candidate.comment);
  12463. }
  12464. LocalizeInfo.is = is;
  12465. })(LocalizeInfo || (LocalizeInfo = {}));
  12466. var resolvedLanguage;
  12467. var resolvedBundles;
  12468. var options;
  12469. var isPseudo;
  12470. function initializeSettings() {
  12471. options = { locale: undefined, language: undefined, languagePackSupport: false, cacheLanguageResolution: true, messageFormat: MessageFormat.bundle };
  12472. if (isString(process.env.VSCODE_NLS_CONFIG)) {
  12473. try {
  12474. var vscodeOptions = JSON.parse(process.env.VSCODE_NLS_CONFIG);
  12475. var language = void 0;
  12476. var locale = void 0;
  12477. if (vscodeOptions.availableLanguages) {
  12478. var value = vscodeOptions.availableLanguages['*'];
  12479. if (isString(value)) {
  12480. language = value;
  12481. }
  12482. }
  12483. if (isString(vscodeOptions.locale)) {
  12484. options.locale = vscodeOptions.locale.toLowerCase();
  12485. }
  12486. if (language === undefined) {
  12487. options.language = options.locale;
  12488. }
  12489. else if (language !== 'en') {
  12490. options.language = language;
  12491. }
  12492. if (isBoolean(vscodeOptions._languagePackSupport)) {
  12493. options.languagePackSupport = vscodeOptions._languagePackSupport;
  12494. }
  12495. if (isString(vscodeOptions._cacheRoot)) {
  12496. options.cacheRoot = vscodeOptions._cacheRoot;
  12497. }
  12498. if (isString(vscodeOptions._languagePackId)) {
  12499. options.languagePackId = vscodeOptions._languagePackId;
  12500. }
  12501. if (isString(vscodeOptions._translationsConfigFile)) {
  12502. options.translationsConfigFile = vscodeOptions._translationsConfigFile;
  12503. try {
  12504. options.translationsConfig = readJsonFileSync(options.translationsConfigFile);
  12505. }
  12506. catch (error) {
  12507. // We can't read the translation config file. Mark the cache as corrupted.
  12508. if (vscodeOptions._corruptedFile) {
  12509. fs.writeFile(vscodeOptions._corruptedFile, 'corrupted', 'utf8', function (err) {
  12510. console.error(err);
  12511. });
  12512. }
  12513. }
  12514. }
  12515. }
  12516. catch (_a) {
  12517. // Do nothing.
  12518. }
  12519. }
  12520. isPseudo = options.locale === 'pseudo';
  12521. resolvedLanguage = undefined;
  12522. resolvedBundles = Object.create(null);
  12523. }
  12524. initializeSettings();
  12525. function supportsLanguagePack() {
  12526. return options.languagePackSupport === true && options.cacheRoot !== undefined && options.languagePackId !== undefined && options.translationsConfigFile !== undefined
  12527. && options.translationsConfig !== undefined;
  12528. }
  12529. function format(message, args) {
  12530. var result;
  12531. if (isPseudo) {
  12532. // FF3B and FF3D is the Unicode zenkaku representation for [ and ]
  12533. message = '\uFF3B' + message.replace(/[aouei]/g, '$&$&') + '\uFF3D';
  12534. }
  12535. if (args.length === 0) {
  12536. result = message;
  12537. }
  12538. else {
  12539. result = message.replace(/\{(\d+)\}/g, function (match, rest) {
  12540. var index = rest[0];
  12541. var arg = args[index];
  12542. var replacement = match;
  12543. if (typeof arg === 'string') {
  12544. replacement = arg;
  12545. }
  12546. else if (typeof arg === 'number' || typeof arg === 'boolean' || arg === void 0 || arg === null) {
  12547. replacement = String(arg);
  12548. }
  12549. return replacement;
  12550. });
  12551. }
  12552. return result;
  12553. }
  12554. function createScopedLocalizeFunction(messages) {
  12555. return function (key, message) {
  12556. var args = [];
  12557. for (var _i = 2; _i < arguments.length; _i++) {
  12558. args[_i - 2] = arguments[_i];
  12559. }
  12560. if (isNumber(key)) {
  12561. if (key >= messages.length) {
  12562. console.error("Broken localize call found. Index out of bounds. Stacktrace is\n: " + new Error('').stack);
  12563. return;
  12564. }
  12565. return format(messages[key], args);
  12566. }
  12567. else {
  12568. if (isString(message)) {
  12569. console.warn("Message " + message + " didn't get externalized correctly.");
  12570. return format(message, args);
  12571. }
  12572. else {
  12573. console.error("Broken localize call found. Stacktrace is\n: " + new Error('').stack);
  12574. }
  12575. }
  12576. };
  12577. }
  12578. function localize(key, message) {
  12579. var args = [];
  12580. for (var _i = 2; _i < arguments.length; _i++) {
  12581. args[_i - 2] = arguments[_i];
  12582. }
  12583. return format(message, args);
  12584. }
  12585. function resolveLanguage(file) {
  12586. var resolvedLanguage;
  12587. if (options.cacheLanguageResolution && resolvedLanguage) {
  12588. resolvedLanguage = resolvedLanguage;
  12589. }
  12590. else {
  12591. if (isPseudo || !options.language) {
  12592. resolvedLanguage = '.nls.json';
  12593. }
  12594. else {
  12595. var locale = options.language;
  12596. while (locale) {
  12597. var candidate = '.nls.' + locale + '.json';
  12598. if (fs.existsSync(file + candidate)) {
  12599. resolvedLanguage = candidate;
  12600. break;
  12601. }
  12602. else {
  12603. var index = locale.lastIndexOf('-');
  12604. if (index > 0) {
  12605. locale = locale.substring(0, index);
  12606. }
  12607. else {
  12608. resolvedLanguage = '.nls.json';
  12609. locale = null;
  12610. }
  12611. }
  12612. }
  12613. }
  12614. if (options.cacheLanguageResolution) {
  12615. resolvedLanguage = resolvedLanguage;
  12616. }
  12617. }
  12618. return file + resolvedLanguage;
  12619. }
  12620. function findInTheBoxBundle(root) {
  12621. var language = options.language;
  12622. while (language) {
  12623. var candidate = path.join(root, "nls.bundle." + language + ".json");
  12624. if (fs.existsSync(candidate)) {
  12625. return candidate;
  12626. }
  12627. else {
  12628. var index = language.lastIndexOf('-');
  12629. if (index > 0) {
  12630. language = language.substring(0, index);
  12631. }
  12632. else {
  12633. language = undefined;
  12634. }
  12635. }
  12636. }
  12637. // Test if we can reslove the default bundle.
  12638. if (language === undefined) {
  12639. var candidate = path.join(root, 'nls.bundle.json');
  12640. if (fs.existsSync(candidate)) {
  12641. return candidate;
  12642. }
  12643. }
  12644. return undefined;
  12645. }
  12646. function mkdir(directory) {
  12647. try {
  12648. fs.mkdirSync(directory);
  12649. }
  12650. catch (err) {
  12651. if (err.code === 'EEXIST') {
  12652. return;
  12653. }
  12654. else if (err.code === 'ENOENT') {
  12655. var parent = path.dirname(directory);
  12656. if (parent !== directory) {
  12657. mkdir(parent);
  12658. fs.mkdirSync(directory);
  12659. }
  12660. }
  12661. else {
  12662. throw err;
  12663. }
  12664. }
  12665. }
  12666. function createDefaultNlsBundle(folder) {
  12667. var metaData = readJsonFileSync(path.join(folder, 'nls.metadata.json'));
  12668. var result = Object.create(null);
  12669. for (var module_1 in metaData) {
  12670. var entry = metaData[module_1];
  12671. result[module_1] = entry.messages;
  12672. }
  12673. return result;
  12674. }
  12675. function createNLSBundle(header, metaDataPath) {
  12676. var languagePackLocation = options.translationsConfig[header.id];
  12677. if (!languagePackLocation) {
  12678. return undefined;
  12679. }
  12680. var languagePack = readJsonFileSync(languagePackLocation).contents;
  12681. var metaData = readJsonFileSync(path.join(metaDataPath, 'nls.metadata.json'));
  12682. var result = Object.create(null);
  12683. for (var module_2 in metaData) {
  12684. var entry = metaData[module_2];
  12685. var translations = languagePack[header.outDir + "/" + module_2];
  12686. if (translations) {
  12687. var resultMessages = [];
  12688. for (var i = 0; i < entry.keys.length; i++) {
  12689. var messageKey = entry.keys[i];
  12690. var key = isString(messageKey) ? messageKey : messageKey.key;
  12691. var translatedMessage = translations[key];
  12692. if (translatedMessage === undefined) {
  12693. translatedMessage = entry.messages[i];
  12694. }
  12695. resultMessages.push(translatedMessage);
  12696. }
  12697. result[module_2] = resultMessages;
  12698. }
  12699. else {
  12700. result[module_2] = entry.messages;
  12701. }
  12702. }
  12703. return result;
  12704. }
  12705. function touch(file) {
  12706. var d = new Date();
  12707. fs.utimes(file, d, d, function () {
  12708. // Do nothing. Ignore
  12709. });
  12710. }
  12711. function cacheBundle(key, bundle) {
  12712. resolvedBundles[key] = bundle;
  12713. return bundle;
  12714. }
  12715. function loadNlsBundleOrCreateFromI18n(header, bundlePath) {
  12716. var result;
  12717. var bundle = path.join(options.cacheRoot, header.id + "-" + header.hash + ".json");
  12718. var useMemoryOnly = false;
  12719. var writeBundle = false;
  12720. try {
  12721. result = JSON.parse(fs.readFileSync(bundle, { encoding: 'utf8', flag: 'r' }));
  12722. touch(bundle);
  12723. return result;
  12724. }
  12725. catch (err) {
  12726. if (err.code === 'ENOENT') {
  12727. writeBundle = true;
  12728. }
  12729. else if (err instanceof SyntaxError) {
  12730. // We have a syntax error. So no valid JSON. Use
  12731. console.log("Syntax error parsing message bundle: " + err.message + ".");
  12732. fs.unlink(bundle, function (err) {
  12733. if (err) {
  12734. console.error("Deleting corrupted bundle " + bundle + " failed.");
  12735. }
  12736. });
  12737. useMemoryOnly = true;
  12738. }
  12739. else {
  12740. throw err;
  12741. }
  12742. }
  12743. result = createNLSBundle(header, bundlePath);
  12744. if (!result || useMemoryOnly) {
  12745. return result;
  12746. }
  12747. if (writeBundle) {
  12748. try {
  12749. fs.writeFileSync(bundle, JSON.stringify(result), { encoding: 'utf8', flag: 'wx' });
  12750. }
  12751. catch (err) {
  12752. if (err.code === 'EEXIST') {
  12753. return result;
  12754. }
  12755. throw err;
  12756. }
  12757. }
  12758. return result;
  12759. }
  12760. function loadDefaultNlsBundle(bundlePath) {
  12761. try {
  12762. return createDefaultNlsBundle(bundlePath);
  12763. }
  12764. catch (err) {
  12765. console.log("Generating default bundle from meta data failed.", err);
  12766. return undefined;
  12767. }
  12768. }
  12769. function loadNlsBundle(header, bundlePath) {
  12770. var result;
  12771. // Core decided to use a language pack. Do the same in the extension
  12772. if (supportsLanguagePack()) {
  12773. try {
  12774. result = loadNlsBundleOrCreateFromI18n(header, bundlePath);
  12775. }
  12776. catch (err) {
  12777. console.log("Load or create bundle failed ", err);
  12778. }
  12779. }
  12780. if (!result) {
  12781. // No language pack found, but core is running in language pack mode
  12782. // Don't try to use old in the box bundles since the might be stale
  12783. // Fall right back to the default bundle.
  12784. if (options.languagePackSupport) {
  12785. return loadDefaultNlsBundle(bundlePath);
  12786. }
  12787. var candidate = findInTheBoxBundle(bundlePath);
  12788. if (candidate) {
  12789. try {
  12790. return readJsonFileSync(candidate);
  12791. }
  12792. catch (err) {
  12793. console.log("Loading in the box message bundle failed.", err);
  12794. }
  12795. }
  12796. result = loadDefaultNlsBundle(bundlePath);
  12797. }
  12798. return result;
  12799. }
  12800. function tryFindMetaDataHeaderFile(file) {
  12801. var result;
  12802. var dirname = path.dirname(file);
  12803. while (true) {
  12804. result = path.join(dirname, 'nls.metadata.header.json');
  12805. if (fs.existsSync(result)) {
  12806. break;
  12807. }
  12808. var parent = path.dirname(dirname);
  12809. if (parent === dirname) {
  12810. result = undefined;
  12811. break;
  12812. }
  12813. else {
  12814. dirname = parent;
  12815. }
  12816. }
  12817. return result;
  12818. }
  12819. function loadMessageBundle(file) {
  12820. if (!file) {
  12821. // No file. We are in dev mode. Return the default
  12822. // localize function.
  12823. return localize;
  12824. }
  12825. // Remove extension since we load json files.
  12826. var ext = path.extname(file);
  12827. if (ext) {
  12828. file = file.substr(0, file.length - ext.length);
  12829. }
  12830. if (options.messageFormat === MessageFormat.both || options.messageFormat === MessageFormat.bundle) {
  12831. var headerFile = tryFindMetaDataHeaderFile(file);
  12832. if (headerFile) {
  12833. var bundlePath = path.dirname(headerFile);
  12834. var bundle = resolvedBundles[bundlePath];
  12835. if (bundle === undefined) {
  12836. try {
  12837. var header = JSON.parse(fs.readFileSync(headerFile, 'utf8'));
  12838. try {
  12839. var nlsBundle = loadNlsBundle(header, bundlePath);
  12840. bundle = cacheBundle(bundlePath, nlsBundle ? { header: header, nlsBundle: nlsBundle } : null);
  12841. }
  12842. catch (err) {
  12843. console.error('Failed to load nls bundle', err);
  12844. bundle = cacheBundle(bundlePath, null);
  12845. }
  12846. }
  12847. catch (err) {
  12848. console.error('Failed to read header file', err);
  12849. bundle = cacheBundle(bundlePath, null);
  12850. }
  12851. }
  12852. if (bundle) {
  12853. var module_3 = file.substr(bundlePath.length + 1).replace(/\\/g, '/');
  12854. var messages = bundle.nlsBundle[module_3];
  12855. if (messages === undefined) {
  12856. console.error("Messages for file " + file + " not found. See console for details.");
  12857. return function () {
  12858. return 'Messages not found.';
  12859. };
  12860. }
  12861. return createScopedLocalizeFunction(messages);
  12862. }
  12863. }
  12864. }
  12865. if (options.messageFormat === MessageFormat.both || options.messageFormat === MessageFormat.file) {
  12866. // Try to load a single file bundle
  12867. try {
  12868. var json = readJsonFileSync(resolveLanguage(file));
  12869. if (Array.isArray(json)) {
  12870. return createScopedLocalizeFunction(json);
  12871. }
  12872. else {
  12873. if (isDefined(json.messages) && isDefined(json.keys)) {
  12874. return createScopedLocalizeFunction(json.messages);
  12875. }
  12876. else {
  12877. console.error("String bundle '" + file + "' uses an unsupported format.");
  12878. return function () {
  12879. return 'File bundle has unsupported format. See console for details';
  12880. };
  12881. }
  12882. }
  12883. }
  12884. catch (err) {
  12885. if (err.code !== 'ENOENT') {
  12886. console.error('Failed to load single file bundle', err);
  12887. }
  12888. }
  12889. }
  12890. console.error("Failed to load message bundle for file " + file);
  12891. return function () {
  12892. return 'Failed to load message bundle. See console for details.';
  12893. };
  12894. }
  12895. exports.loadMessageBundle = loadMessageBundle;
  12896. function config(opts) {
  12897. if (opts) {
  12898. if (isString(opts.locale)) {
  12899. options.locale = opts.locale.toLowerCase();
  12900. options.language = options.locale;
  12901. resolvedLanguage = undefined;
  12902. resolvedBundles = Object.create(null);
  12903. }
  12904. if (opts.messageFormat !== undefined) {
  12905. options.messageFormat = opts.messageFormat;
  12906. }
  12907. if (opts.bundleFormat === BundleFormat.standalone && options.languagePackSupport === true) {
  12908. options.languagePackSupport = false;
  12909. }
  12910. }
  12911. isPseudo = options.locale === 'pseudo';
  12912. return loadMessageBundle;
  12913. }
  12914. exports.config = config;
  12915. //# sourceMappingURL=main.js.map
  12916. /***/ }),
  12917. /* 77 */
  12918. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  12919. "use strict";
  12920. __webpack_require__.r(__webpack_exports__);
  12921. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setUriThrowOnMissingScheme", function() { return setUriThrowOnMissingScheme; });
  12922. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return URI; });
  12923. /*---------------------------------------------------------------------------------------------
  12924. * Copyright (c) Microsoft Corporation. All rights reserved.
  12925. * Licensed under the MIT License. See License.txt in the project root for license information.
  12926. *--------------------------------------------------------------------------------------------*/
  12927. var __extends = (undefined && undefined.__extends) || (function () {
  12928. var extendStatics = Object.setPrototypeOf ||
  12929. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  12930. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  12931. return function (d, b) {
  12932. extendStatics(d, b);
  12933. function __() { this.constructor = d; }
  12934. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12935. };
  12936. })();
  12937. var isWindows;
  12938. if (typeof process === 'object') {
  12939. isWindows = process.platform === 'win32';
  12940. }
  12941. else if (typeof navigator === 'object') {
  12942. var userAgent = navigator.userAgent;
  12943. isWindows = userAgent.indexOf('Windows') >= 0;
  12944. }
  12945. //#endregion
  12946. var _schemePattern = /^\w[\w\d+.-]*$/;
  12947. var _singleSlashStart = /^\//;
  12948. var _doubleSlashStart = /^\/\//;
  12949. var _throwOnMissingSchema = true;
  12950. /**
  12951. * @internal
  12952. */
  12953. function setUriThrowOnMissingScheme(value) {
  12954. var old = _throwOnMissingSchema;
  12955. _throwOnMissingSchema = value;
  12956. return old;
  12957. }
  12958. function _validateUri(ret, _strict) {
  12959. // scheme, must be set
  12960. if (!ret.scheme) {
  12961. if (_strict || _throwOnMissingSchema) {
  12962. throw new Error("[UriError]: Scheme is missing: {scheme: \"\", authority: \"" + ret.authority + "\", path: \"" + ret.path + "\", query: \"" + ret.query + "\", fragment: \"" + ret.fragment + "\"}");
  12963. }
  12964. else {
  12965. // console.warn(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`);
  12966. }
  12967. }
  12968. // scheme, https://tools.ietf.org/html/rfc3986#section-3.1
  12969. // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  12970. if (ret.scheme && !_schemePattern.test(ret.scheme)) {
  12971. throw new Error('[UriError]: Scheme contains illegal characters.');
  12972. }
  12973. // path, http://tools.ietf.org/html/rfc3986#section-3.3
  12974. // If a URI contains an authority component, then the path component
  12975. // must either be empty or begin with a slash ("/") character. If a URI
  12976. // does not contain an authority component, then the path cannot begin
  12977. // with two slash characters ("//").
  12978. if (ret.path) {
  12979. if (ret.authority) {
  12980. if (!_singleSlashStart.test(ret.path)) {
  12981. throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
  12982. }
  12983. }
  12984. else {
  12985. if (_doubleSlashStart.test(ret.path)) {
  12986. throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
  12987. }
  12988. }
  12989. }
  12990. }
  12991. // for a while we allowed uris *without* schemes and this is the migration
  12992. // for them, e.g. an uri without scheme and without strict-mode warns and falls
  12993. // back to the file-scheme. that should cause the least carnage and still be a
  12994. // clear warning
  12995. function _schemeFix(scheme, _strict) {
  12996. if (_strict || _throwOnMissingSchema) {
  12997. return scheme || _empty;
  12998. }
  12999. if (!scheme) {
  13000. // console.trace('BAD uri lacks scheme, falling back to file-scheme.');
  13001. scheme = 'file';
  13002. }
  13003. return scheme;
  13004. }
  13005. // implements a bit of https://tools.ietf.org/html/rfc3986#section-5
  13006. function _referenceResolution(scheme, path) {
  13007. // the slash-character is our 'default base' as we don't
  13008. // support constructing URIs relative to other URIs. This
  13009. // also means that we alter and potentially break paths.
  13010. // see https://tools.ietf.org/html/rfc3986#section-5.1.4
  13011. switch (scheme) {
  13012. case 'https':
  13013. case 'http':
  13014. case 'file':
  13015. if (!path) {
  13016. path = _slash;
  13017. }
  13018. else if (path[0] !== _slash) {
  13019. path = _slash + path;
  13020. }
  13021. break;
  13022. }
  13023. return path;
  13024. }
  13025. var _empty = '';
  13026. var _slash = '/';
  13027. var _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
  13028. function _isQueryStringScheme(scheme) {
  13029. switch (scheme.toLowerCase()) {
  13030. case 'http':
  13031. case 'https':
  13032. case 'ftp':
  13033. return true;
  13034. }
  13035. return false;
  13036. }
  13037. /**
  13038. * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
  13039. * This class is a simple parser which creates the basic component parts
  13040. * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
  13041. * and encoding.
  13042. *
  13043. * foo://example.com:8042/over/there?name=ferret#nose
  13044. * \_/ \______________/\_________/ \_________/ \__/
  13045. * | | | | |
  13046. * scheme authority path query fragment
  13047. * | _____________________|__
  13048. * / \ / \
  13049. * urn:example:animal:ferret:nose
  13050. */
  13051. var URI = (function () {
  13052. /**
  13053. * @internal
  13054. */
  13055. function URI(schemeOrData, authority, path, query, fragment, _strict) {
  13056. if (_strict === void 0) { _strict = false; }
  13057. if (typeof schemeOrData === 'object') {
  13058. this.scheme = schemeOrData.scheme || _empty;
  13059. this.authority = schemeOrData.authority || _empty;
  13060. this.path = schemeOrData.path || _empty;
  13061. this.query = schemeOrData.query || _empty;
  13062. this.fragment = schemeOrData.fragment || _empty;
  13063. // no validation because it's this URI
  13064. // that creates uri components.
  13065. // _validateUri(this);
  13066. }
  13067. else {
  13068. this.scheme = _schemeFix(schemeOrData, _strict);
  13069. this.authority = authority || _empty;
  13070. this.path = _referenceResolution(this.scheme, path || _empty);
  13071. this.query = query || _empty;
  13072. this.fragment = fragment || _empty;
  13073. _validateUri(this, _strict);
  13074. }
  13075. }
  13076. URI.isUri = function (thing) {
  13077. if (thing instanceof URI) {
  13078. return true;
  13079. }
  13080. if (!thing) {
  13081. return false;
  13082. }
  13083. return typeof thing.authority === 'string'
  13084. && typeof thing.fragment === 'string'
  13085. && typeof thing.path === 'string'
  13086. && typeof thing.query === 'string'
  13087. && typeof thing.scheme === 'string'
  13088. && typeof thing.fsPath === 'function'
  13089. && typeof thing.with === 'function'
  13090. && typeof thing.toString === 'function';
  13091. };
  13092. Object.defineProperty(URI.prototype, "fsPath", {
  13093. // ---- filesystem path -----------------------
  13094. /**
  13095. * Returns a string representing the corresponding file system path of this URI.
  13096. * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
  13097. * platform specific path separator.
  13098. *
  13099. * * Will *not* validate the path for invalid characters and semantics.
  13100. * * Will *not* look at the scheme of this URI.
  13101. * * The result shall *not* be used for display purposes but for accessing a file on disk.
  13102. *
  13103. *
  13104. * The *difference* to `URI#path` is the use of the platform specific separator and the handling
  13105. * of UNC paths. See the below sample of a file-uri with an authority (UNC path).
  13106. *
  13107. * ```ts
  13108. const u = URI.parse('file://server/c$/folder/file.txt')
  13109. u.authority === 'server'
  13110. u.path === '/shares/c$/file.txt'
  13111. u.fsPath === '\\server\c$\folder\file.txt'
  13112. ```
  13113. *
  13114. * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,
  13115. * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working
  13116. * with URIs that represent files on disk (`file` scheme).
  13117. */
  13118. get: function () {
  13119. // if (this.scheme !== 'file') {
  13120. // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
  13121. // }
  13122. return _makeFsPath(this);
  13123. },
  13124. enumerable: true,
  13125. configurable: true
  13126. });
  13127. // ---- modify to new -------------------------
  13128. URI.prototype.with = function (change) {
  13129. if (!change) {
  13130. return this;
  13131. }
  13132. var scheme = change.scheme, authority = change.authority, path = change.path, query = change.query, fragment = change.fragment;
  13133. if (scheme === undefined) {
  13134. scheme = this.scheme;
  13135. }
  13136. else if (scheme === null) {
  13137. scheme = _empty;
  13138. }
  13139. if (authority === undefined) {
  13140. authority = this.authority;
  13141. }
  13142. else if (authority === null) {
  13143. authority = _empty;
  13144. }
  13145. if (path === undefined) {
  13146. path = this.path;
  13147. }
  13148. else if (path === null) {
  13149. path = _empty;
  13150. }
  13151. if (query === undefined) {
  13152. query = this.query;
  13153. }
  13154. else if (query === null) {
  13155. query = _empty;
  13156. }
  13157. if (fragment === undefined) {
  13158. fragment = this.fragment;
  13159. }
  13160. else if (fragment === null) {
  13161. fragment = _empty;
  13162. }
  13163. if (scheme === this.scheme
  13164. && authority === this.authority
  13165. && path === this.path
  13166. && query === this.query
  13167. && fragment === this.fragment) {
  13168. return this;
  13169. }
  13170. return new _URI(scheme, authority, path, query, fragment);
  13171. };
  13172. // ---- parse & validate ------------------------
  13173. /**
  13174. * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`,
  13175. * `file:///usr/home`, or `scheme:with/path`.
  13176. *
  13177. * @param value A string which represents an URI (see `URI#toString`).
  13178. */
  13179. URI.parse = function (value, _strict) {
  13180. if (_strict === void 0) { _strict = false; }
  13181. var match = _regexp.exec(value);
  13182. if (!match) {
  13183. return new _URI(_empty, _empty, _empty, _empty, _empty, _strict);
  13184. }
  13185. return new _URI(match[2] || _empty, decodeURIComponentFast(match[4] || _empty, false, false), decodeURIComponentFast(match[5] || _empty, true, false), decodeURIComponentFast(match[7] || _empty, false, _isQueryStringScheme(match[2])), decodeURIComponentFast(match[9] || _empty, false, false), _strict);
  13186. };
  13187. /**
  13188. * Creates a new URI from a file system path, e.g. `c:\my\files`,
  13189. * `/usr/home`, or `\\server\share\some\path`.
  13190. *
  13191. * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
  13192. * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
  13193. * `URI.parse('file://' + path)` because the path might contain characters that are
  13194. * interpreted (# and ?). See the following sample:
  13195. * ```ts
  13196. const good = URI.file('/coding/c#/project1');
  13197. good.scheme === 'file';
  13198. good.path === '/coding/c#/project1';
  13199. good.fragment === '';
  13200. const bad = URI.parse('file://' + '/coding/c#/project1');
  13201. bad.scheme === 'file';
  13202. bad.path === '/coding/c'; // path is now broken
  13203. bad.fragment === '/project1';
  13204. ```
  13205. *
  13206. * @param path A file system path (see `URI#fsPath`)
  13207. */
  13208. URI.file = function (path) {
  13209. var authority = _empty;
  13210. // normalize to fwd-slashes on windows,
  13211. // on other systems bwd-slashes are valid
  13212. // filename character, eg /f\oo/ba\r.txt
  13213. if (isWindows) {
  13214. path = path.replace(/\\/g, _slash);
  13215. }
  13216. // check for authority as used in UNC shares
  13217. // or use the path as given
  13218. if (path[0] === _slash && path[1] === _slash) {
  13219. var idx = path.indexOf(_slash, 2);
  13220. if (idx === -1) {
  13221. authority = path.substring(2);
  13222. path = _slash;
  13223. }
  13224. else {
  13225. authority = path.substring(2, idx);
  13226. path = path.substring(idx) || _slash;
  13227. }
  13228. }
  13229. return new _URI('file', authority, path, _empty, _empty);
  13230. };
  13231. URI.from = function (components) {
  13232. return new _URI(components.scheme, components.authority, components.path, components.query, components.fragment);
  13233. };
  13234. // ---- printing/externalize ---------------------------
  13235. /**
  13236. * Creates a string representation for this URI. It's guaranteed that calling
  13237. * `URI.parse` with the result of this function creates an URI which is equal
  13238. * to this URI.
  13239. *
  13240. * * The result shall *not* be used for display purposes but for externalization or transport.
  13241. * * The result will be encoded using the percentage encoding and encoding happens mostly
  13242. * ignore the scheme-specific encoding rules.
  13243. *
  13244. * @param skipEncoding Do not encode the result, default is `false`
  13245. */
  13246. URI.prototype.toString = function (skipEncoding) {
  13247. if (skipEncoding === void 0) { skipEncoding = false; }
  13248. return _asFormatted(this, skipEncoding);
  13249. };
  13250. URI.prototype.toJSON = function () {
  13251. return this;
  13252. };
  13253. URI.revive = function (data) {
  13254. if (!data) {
  13255. return data;
  13256. }
  13257. else if (data instanceof URI) {
  13258. return data;
  13259. }
  13260. else {
  13261. var result = new _URI(data);
  13262. result._formatted = data.external;
  13263. result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null;
  13264. return result;
  13265. }
  13266. };
  13267. return URI;
  13268. }());
  13269. var _pathSepMarker = isWindows ? 1 : undefined;
  13270. // tslint:disable-next-line:class-name
  13271. var _URI = (function (_super) {
  13272. __extends(_URI, _super);
  13273. function _URI() {
  13274. var _this = _super !== null && _super.apply(this, arguments) || this;
  13275. _this._formatted = null;
  13276. _this._fsPath = null;
  13277. return _this;
  13278. }
  13279. Object.defineProperty(_URI.prototype, "fsPath", {
  13280. get: function () {
  13281. if (!this._fsPath) {
  13282. this._fsPath = _makeFsPath(this);
  13283. }
  13284. return this._fsPath;
  13285. },
  13286. enumerable: true,
  13287. configurable: true
  13288. });
  13289. _URI.prototype.toString = function (skipEncoding) {
  13290. if (skipEncoding === void 0) { skipEncoding = false; }
  13291. if (!skipEncoding) {
  13292. if (!this._formatted) {
  13293. this._formatted = _asFormatted(this, false);
  13294. }
  13295. return this._formatted;
  13296. }
  13297. else {
  13298. // we don't cache that
  13299. return _asFormatted(this, true);
  13300. }
  13301. };
  13302. _URI.prototype.toJSON = function () {
  13303. var res = {
  13304. $mid: 1
  13305. };
  13306. // cached state
  13307. if (this._fsPath) {
  13308. res.fsPath = this._fsPath;
  13309. res._sep = _pathSepMarker;
  13310. }
  13311. if (this._formatted) {
  13312. res.external = this._formatted;
  13313. }
  13314. // uri components
  13315. if (this.path) {
  13316. res.path = this.path;
  13317. }
  13318. if (this.scheme) {
  13319. res.scheme = this.scheme;
  13320. }
  13321. if (this.authority) {
  13322. res.authority = this.authority;
  13323. }
  13324. if (this.query) {
  13325. res.query = this.query;
  13326. }
  13327. if (this.fragment) {
  13328. res.fragment = this.fragment;
  13329. }
  13330. return res;
  13331. };
  13332. return _URI;
  13333. }(URI));
  13334. function isHex(value, pos) {
  13335. if (pos >= value.length) {
  13336. return false;
  13337. }
  13338. var code = value.charCodeAt(pos);
  13339. return (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */) // 0-9
  13340. || (code >= 97 /* a */ && code <= 102 /* f */) //a-f
  13341. || (code >= 65 /* A */ && code <= 70 /* F */); //A-F
  13342. }
  13343. function decodeURIComponentFast(uriComponent, isPath, isQueryString) {
  13344. var res;
  13345. var nativeDecodePos = -1;
  13346. for (var pos = 0; pos < uriComponent.length; pos++) {
  13347. var code = uriComponent.charCodeAt(pos);
  13348. // decoding needed
  13349. if (code === 37 /* PercentSign */ && isHex(uriComponent, pos + 1) && isHex(uriComponent, pos + 2)) {
  13350. var chA = uriComponent.charCodeAt(pos + 1);
  13351. var chB = uriComponent.charCodeAt(pos + 2);
  13352. // when in a path -> check and accept %2f and %2F (fwd slash)
  13353. // when in a query string -> check and accept %3D, %26, and %3B (equals, ampersand, semi-colon)
  13354. if ((isPath && chA === 50 /* Digit2 */ && (chB === 70 /* F */ || chB === 102 /* f */))
  13355. ||
  13356. (isQueryString && ((chA === 50 /* Digit2 */ && chB === 54 /* Digit6 */) // %26
  13357. ||
  13358. (chA === 51 /* Digit3 */ && (chB === 66 /* B */ || chB === 98 /* b */ || chB === 68 /* D */ || chB === 100 /* d */)) // %3D, %3D
  13359. ))) {
  13360. if (nativeDecodePos !== -1) {
  13361. res += decodeURIComponent(uriComponent.substring(nativeDecodePos, pos));
  13362. nativeDecodePos = -1;
  13363. }
  13364. if (res !== undefined) {
  13365. res += uriComponent.substr(pos, 3);
  13366. }
  13367. pos += 2;
  13368. continue;
  13369. }
  13370. if (res === undefined) {
  13371. res = uriComponent.substring(0, pos);
  13372. }
  13373. if (nativeDecodePos === -1) {
  13374. nativeDecodePos = pos;
  13375. }
  13376. pos += 2;
  13377. }
  13378. else {
  13379. if (nativeDecodePos !== -1) {
  13380. res += decodeURIComponent(uriComponent.substring(nativeDecodePos, pos));
  13381. nativeDecodePos = -1;
  13382. }
  13383. if (res !== undefined) {
  13384. res += String.fromCharCode(code);
  13385. }
  13386. }
  13387. }
  13388. if (nativeDecodePos !== -1) {
  13389. res += decodeURIComponent(uriComponent.substr(nativeDecodePos));
  13390. }
  13391. return res !== undefined ? res : uriComponent;
  13392. }
  13393. // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
  13394. var encodeTable = (_a = {},
  13395. _a[58 /* Colon */] = '%3A',
  13396. _a[47 /* Slash */] = '%2F',
  13397. _a[63 /* QuestionMark */] = '%3F',
  13398. _a[35 /* Hash */] = '%23',
  13399. _a[91 /* OpenSquareBracket */] = '%5B',
  13400. _a[93 /* CloseSquareBracket */] = '%5D',
  13401. _a[64 /* AtSign */] = '%40',
  13402. _a[33 /* ExclamationMark */] = '%21',
  13403. _a[36 /* DollarSign */] = '%24',
  13404. _a[38 /* Ampersand */] = '%26',
  13405. _a[39 /* SingleQuote */] = '%27',
  13406. _a[40 /* OpenParen */] = '%28',
  13407. _a[41 /* CloseParen */] = '%29',
  13408. _a[42 /* Asterisk */] = '%2A',
  13409. _a[43 /* Plus */] = '%2B',
  13410. _a[44 /* Comma */] = '%2C',
  13411. _a[59 /* Semicolon */] = '%3B',
  13412. _a[61 /* Equals */] = '%3D',
  13413. _a[32 /* Space */] = '%20',
  13414. _a);
  13415. function encodeURIComponentFast(uriComponent, isPath, isQueryString) {
  13416. var res = undefined;
  13417. var nativeEncodePos = -1;
  13418. for (var pos = 0; pos < uriComponent.length; pos++) {
  13419. var code = uriComponent.charCodeAt(pos);
  13420. // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3
  13421. if ((code >= 97 /* a */ && code <= 122 /* z */)
  13422. || (code >= 65 /* A */ && code <= 90 /* Z */)
  13423. || (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */)
  13424. || code === 45 /* Dash */
  13425. || code === 46 /* Period */
  13426. || code === 95 /* Underline */
  13427. || code === 126 /* Tilde */
  13428. || (isPath && code === 47 /* Slash */) // path => allow slash AS-IS
  13429. || (isQueryString && (code === 61 /* Equals */ || code === 38 /* Ampersand */ || code === 59 /* Semicolon */)) // query string => allow &=;
  13430. ) {
  13431. // check if we are delaying native encode
  13432. if (nativeEncodePos !== -1) {
  13433. res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
  13434. nativeEncodePos = -1;
  13435. }
  13436. // check if we write into a new string (by default we try to return the param)
  13437. if (res !== undefined) {
  13438. res += uriComponent.charAt(pos);
  13439. }
  13440. }
  13441. else if (code === 37 /* PercentSign */ && isHex(uriComponent, pos + 1) && isHex(uriComponent, pos + 2)) {
  13442. // at percentage encoded value
  13443. // check if we are delaying native encode
  13444. if (nativeEncodePos !== -1) {
  13445. res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
  13446. nativeEncodePos = -1;
  13447. }
  13448. // check if we write into a new string (by default we try to return the param)
  13449. if (res !== undefined) {
  13450. res += uriComponent.substr(pos, 3);
  13451. }
  13452. pos += 2;
  13453. }
  13454. else {
  13455. // encoding needed, we need to allocate a new string
  13456. if (res === undefined) {
  13457. res = uriComponent.substr(0, pos);
  13458. }
  13459. // check with default table first
  13460. var escaped = encodeTable[code];
  13461. if (escaped !== undefined) {
  13462. // check if we are delaying native encode
  13463. if (nativeEncodePos !== -1) {
  13464. res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
  13465. nativeEncodePos = -1;
  13466. }
  13467. // append escaped variant to result
  13468. res += escaped;
  13469. }
  13470. else if (nativeEncodePos === -1) {
  13471. // use native encode only when needed
  13472. nativeEncodePos = pos;
  13473. }
  13474. }
  13475. }
  13476. if (nativeEncodePos !== -1) {
  13477. res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
  13478. }
  13479. return res !== undefined ? res : uriComponent;
  13480. }
  13481. function encodeURIComponentMinimal(path) {
  13482. var res = undefined;
  13483. for (var pos = 0; pos < path.length; pos++) {
  13484. var code = path.charCodeAt(pos);
  13485. if (code === 35 /* Hash */ || code === 63 /* QuestionMark */) {
  13486. if (res === undefined) {
  13487. res = path.substr(0, pos);
  13488. }
  13489. res += encodeTable[code];
  13490. }
  13491. else {
  13492. if (res !== undefined) {
  13493. res += path[pos];
  13494. }
  13495. }
  13496. }
  13497. return res !== undefined ? res : path;
  13498. }
  13499. /**
  13500. * Compute `fsPath` for the given uri
  13501. */
  13502. function _makeFsPath(uri) {
  13503. var value;
  13504. if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') {
  13505. // unc path: file://shares/c$/far/boo
  13506. value = "//" + uri.authority + uri.path;
  13507. }
  13508. else if (uri.path.charCodeAt(0) === 47 /* Slash */
  13509. && (uri.path.charCodeAt(1) >= 65 /* A */ && uri.path.charCodeAt(1) <= 90 /* Z */ || uri.path.charCodeAt(1) >= 97 /* a */ && uri.path.charCodeAt(1) <= 122 /* z */)
  13510. && uri.path.charCodeAt(2) === 58 /* Colon */) {
  13511. // windows drive letter: file:///c:/far/boo
  13512. value = uri.path[1].toLowerCase() + uri.path.substr(2);
  13513. }
  13514. else {
  13515. // other path
  13516. value = uri.path;
  13517. }
  13518. if (isWindows) {
  13519. value = value.replace(/\//g, '\\');
  13520. }
  13521. return value;
  13522. }
  13523. /**
  13524. * Create the external version of a uri
  13525. */
  13526. function _asFormatted(uri, skipEncoding) {
  13527. var encoder = !skipEncoding
  13528. ? encodeURIComponentFast
  13529. : encodeURIComponentMinimal;
  13530. var res = '';
  13531. var scheme = uri.scheme, authority = uri.authority, path = uri.path, query = uri.query, fragment = uri.fragment;
  13532. if (scheme) {
  13533. res += scheme;
  13534. res += ':';
  13535. }
  13536. if (authority || scheme === 'file') {
  13537. res += _slash;
  13538. res += _slash;
  13539. }
  13540. if (authority) {
  13541. var idx = authority.indexOf('@');
  13542. if (idx !== -1) {
  13543. // <user>@<auth>
  13544. var userinfo = authority.substr(0, idx);
  13545. authority = authority.substr(idx + 1);
  13546. idx = userinfo.indexOf(':');
  13547. if (idx === -1) {
  13548. res += encoder(userinfo, false, false);
  13549. }
  13550. else {
  13551. // <user>:<pass>@<auth>
  13552. res += encoder(userinfo.substr(0, idx), false, false);
  13553. res += ':';
  13554. res += encoder(userinfo.substr(idx + 1), false, false);
  13555. }
  13556. res += '@';
  13557. }
  13558. authority = authority.toLowerCase();
  13559. idx = authority.indexOf(':');
  13560. if (idx === -1) {
  13561. res += encoder(authority, false, false);
  13562. }
  13563. else {
  13564. // <auth>:<port>
  13565. res += encoder(authority.substr(0, idx), false, false);
  13566. res += authority.substr(idx);
  13567. }
  13568. }
  13569. if (path) {
  13570. // lower-case windows drive letters in /C:/fff or C:/fff
  13571. if (path.length >= 3 && path.charCodeAt(0) === 47 /* Slash */ && path.charCodeAt(2) === 58 /* Colon */) {
  13572. var code = path.charCodeAt(1);
  13573. if (code >= 65 /* A */ && code <= 90 /* Z */) {
  13574. path = "/" + String.fromCharCode(code + 32) + ":" + path.substr(3); // "/c:".length === 3
  13575. }
  13576. }
  13577. else if (path.length >= 2 && path.charCodeAt(1) === 58 /* Colon */) {
  13578. var code = path.charCodeAt(0);
  13579. if (code >= 65 /* A */ && code <= 90 /* Z */) {
  13580. path = String.fromCharCode(code + 32) + ":" + path.substr(2); // "/c:".length === 3
  13581. }
  13582. }
  13583. // encode the rest of the path
  13584. res += encoder(path, true, false);
  13585. }
  13586. if (query) {
  13587. res += '?';
  13588. res += encoder(query, false, _isQueryStringScheme(scheme));
  13589. }
  13590. if (fragment) {
  13591. res += '#';
  13592. res += !skipEncoding ? encodeURIComponentFast(fragment, false, false) : fragment;
  13593. }
  13594. return res;
  13595. }
  13596. var _a;
  13597. /***/ }),
  13598. /* 78 */
  13599. /***/ (function(module, exports, __webpack_require__) {
  13600. "use strict";
  13601. /*---------------------------------------------------------------------------------------------
  13602. * Copyright (c) Microsoft Corporation. All rights reserved.
  13603. * Licensed under the MIT License. See License.txt in the project root for license information.
  13604. *--------------------------------------------------------------------------------------------*/
  13605. Object.defineProperty(exports, "__esModule", { value: true });
  13606. const vscode_languageserver_1 = __webpack_require__(34);
  13607. function formatError(message, err) {
  13608. if (err instanceof Error) {
  13609. let error = err;
  13610. return `${message}: ${error.message}\n${error.stack}`;
  13611. }
  13612. else if (typeof err === 'string') {
  13613. return `${message}: ${err}`;
  13614. }
  13615. else if (err) {
  13616. return `${message}: ${err.toString()}`;
  13617. }
  13618. return message;
  13619. }
  13620. exports.formatError = formatError;
  13621. function runSafeAsync(func, errorVal, errorMessage, token) {
  13622. return new Promise((resolve) => {
  13623. setImmediate(() => {
  13624. if (token.isCancellationRequested) {
  13625. resolve(cancelValue());
  13626. }
  13627. return func().then(result => {
  13628. if (token.isCancellationRequested) {
  13629. resolve(cancelValue());
  13630. return;
  13631. }
  13632. else {
  13633. resolve(result);
  13634. }
  13635. }, e => {
  13636. console.error(formatError(errorMessage, e));
  13637. resolve(errorVal);
  13638. });
  13639. });
  13640. });
  13641. }
  13642. exports.runSafeAsync = runSafeAsync;
  13643. function runSafe(func, errorVal, errorMessage, token) {
  13644. return new Promise((resolve) => {
  13645. setImmediate(() => {
  13646. if (token.isCancellationRequested) {
  13647. resolve(cancelValue());
  13648. }
  13649. else {
  13650. try {
  13651. let result = func();
  13652. if (token.isCancellationRequested) {
  13653. resolve(cancelValue());
  13654. return;
  13655. }
  13656. else {
  13657. resolve(result);
  13658. }
  13659. }
  13660. catch (e) {
  13661. console.error(formatError(errorMessage, e));
  13662. resolve(errorVal);
  13663. }
  13664. }
  13665. });
  13666. });
  13667. }
  13668. exports.runSafe = runSafe;
  13669. function cancelValue() {
  13670. console.log('cancelled');
  13671. return new vscode_languageserver_1.ResponseError(vscode_languageserver_1.ErrorCodes.RequestCancelled, 'Request cancelled');
  13672. }
  13673. /***/ }),
  13674. /* 79 */
  13675. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  13676. "use strict";
  13677. __webpack_require__.r(__webpack_exports__);
  13678. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLanguageService", function() { return getLanguageService; });
  13679. /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80);
  13680. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["TextDocument"]; });
  13681. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Position"]; });
  13682. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["CompletionItem"]; });
  13683. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["CompletionList"]; });
  13684. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Hover"]; });
  13685. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Range"]; });
  13686. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["SymbolInformation"]; });
  13687. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Diagnostic"]; });
  13688. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["TextEdit"]; });
  13689. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["FormattingOptions"]; });
  13690. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["MarkedString"]; });
  13691. /* harmony import */ var _services_jsonCompletion__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81);
  13692. /* harmony import */ var _services_jsonHover__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(92);
  13693. /* harmony import */ var _services_jsonValidation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(93);
  13694. /* harmony import */ var _services_jsonDocumentSymbols__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(96);
  13695. /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(82);
  13696. /* harmony import */ var _services_configuration__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(98);
  13697. /* harmony import */ var _services_jsonSchemaService__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(94);
  13698. /* harmony import */ var _services_jsonFolding__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(99);
  13699. /* harmony import */ var _services_jsonSelectionRanges__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(100);
  13700. /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(83);
  13701. /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(89);
  13702. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["Color"]; });
  13703. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["ColorInformation"]; });
  13704. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["ColorPresentation"]; });
  13705. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["FoldingRange"]; });
  13706. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["FoldingRangeKind"]; });
  13707. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["SelectionRange"]; });
  13708. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ErrorCode", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["ErrorCode"]; });
  13709. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClientCapabilities", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["ClientCapabilities"]; });
  13710. /*---------------------------------------------------------------------------------------------
  13711. * Copyright (c) Microsoft Corporation. All rights reserved.
  13712. * Licensed under the MIT License. See License.txt in the project root for license information.
  13713. *--------------------------------------------------------------------------------------------*/
  13714. function getLanguageService(params) {
  13715. var promise = params.promiseConstructor || Promise;
  13716. var jsonSchemaService = new _services_jsonSchemaService__WEBPACK_IMPORTED_MODULE_7__["JSONSchemaService"](params.schemaRequestService, params.workspaceContext, promise);
  13717. jsonSchemaService.setSchemaContributions(_services_configuration__WEBPACK_IMPORTED_MODULE_6__["schemaContributions"]);
  13718. var jsonCompletion = new _services_jsonCompletion__WEBPACK_IMPORTED_MODULE_1__["JSONCompletion"](jsonSchemaService, params.contributions, promise, params.clientCapabilities);
  13719. var jsonHover = new _services_jsonHover__WEBPACK_IMPORTED_MODULE_2__["JSONHover"](jsonSchemaService, params.contributions, promise);
  13720. var jsonDocumentSymbols = new _services_jsonDocumentSymbols__WEBPACK_IMPORTED_MODULE_4__["JSONDocumentSymbols"](jsonSchemaService);
  13721. var jsonValidation = new _services_jsonValidation__WEBPACK_IMPORTED_MODULE_3__["JSONValidation"](jsonSchemaService, promise);
  13722. return {
  13723. configure: function (settings) {
  13724. jsonSchemaService.clearExternalSchemas();
  13725. if (settings.schemas) {
  13726. settings.schemas.forEach(function (settings) {
  13727. jsonSchemaService.registerExternalSchema(settings.uri, settings.fileMatch, settings.schema);
  13728. });
  13729. }
  13730. jsonValidation.configure(settings);
  13731. },
  13732. resetSchema: function (uri) { return jsonSchemaService.onResourceChange(uri); },
  13733. doValidation: jsonValidation.doValidation.bind(jsonValidation),
  13734. parseJSONDocument: function (document) { return Object(_parser_jsonParser__WEBPACK_IMPORTED_MODULE_5__["parse"])(document, { collectComments: true }); },
  13735. newJSONDocument: function (root, diagnostics) { return Object(_parser_jsonParser__WEBPACK_IMPORTED_MODULE_5__["newJSONDocument"])(root, diagnostics); },
  13736. doResolve: jsonCompletion.doResolve.bind(jsonCompletion),
  13737. doComplete: jsonCompletion.doComplete.bind(jsonCompletion),
  13738. findDocumentSymbols: jsonDocumentSymbols.findDocumentSymbols.bind(jsonDocumentSymbols),
  13739. findDocumentSymbols2: jsonDocumentSymbols.findDocumentSymbols2.bind(jsonDocumentSymbols),
  13740. findColorSymbols: function (d, s) { return jsonDocumentSymbols.findDocumentColors(d, s).then(function (s) { return s.map(function (s) { return s.range; }); }); },
  13741. findDocumentColors: jsonDocumentSymbols.findDocumentColors.bind(jsonDocumentSymbols),
  13742. getColorPresentations: jsonDocumentSymbols.getColorPresentations.bind(jsonDocumentSymbols),
  13743. doHover: jsonHover.doHover.bind(jsonHover),
  13744. getFoldingRanges: _services_jsonFolding__WEBPACK_IMPORTED_MODULE_8__["getFoldingRanges"],
  13745. getSelectionRanges: _services_jsonSelectionRanges__WEBPACK_IMPORTED_MODULE_9__["getSelectionRanges"],
  13746. format: function (d, r, o) {
  13747. var range = void 0;
  13748. if (r) {
  13749. var offset = d.offsetAt(r.start);
  13750. var length = d.offsetAt(r.end) - offset;
  13751. range = { offset: offset, length: length };
  13752. }
  13753. var options = { tabSize: o ? o.tabSize : 4, insertSpaces: o ? o.insertSpaces : true, eol: '\n' };
  13754. return Object(jsonc_parser__WEBPACK_IMPORTED_MODULE_10__["format"])(d.getText(), range, options).map(function (e) {
  13755. return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["TextEdit"].replace(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Range"].create(d.positionAt(e.offset), d.positionAt(e.offset + e.length)), e.content);
  13756. });
  13757. }
  13758. };
  13759. }
  13760. /***/ }),
  13761. /* 80 */
  13762. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  13763. "use strict";
  13764. __webpack_require__.r(__webpack_exports__);
  13765. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
  13766. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
  13767. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
  13768. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
  13769. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
  13770. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
  13771. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
  13772. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
  13773. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
  13774. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
  13775. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
  13776. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
  13777. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
  13778. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
  13779. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
  13780. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
  13781. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
  13782. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
  13783. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
  13784. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
  13785. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
  13786. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
  13787. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
  13788. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
  13789. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
  13790. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
  13791. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
  13792. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
  13793. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
  13794. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
  13795. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
  13796. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
  13797. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
  13798. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
  13799. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
  13800. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
  13801. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
  13802. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
  13803. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
  13804. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
  13805. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
  13806. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
  13807. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
  13808. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
  13809. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
  13810. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
  13811. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
  13812. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
  13813. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentSaveReason", function() { return TextDocumentSaveReason; });
  13814. /* --------------------------------------------------------------------------------------------
  13815. * Copyright (c) Microsoft Corporation. All rights reserved.
  13816. * Licensed under the MIT License. See License.txt in the project root for license information.
  13817. * ------------------------------------------------------------------------------------------ */
  13818. /**
  13819. * The Position namespace provides helper functions to work with
  13820. * [Position](#Position) literals.
  13821. */
  13822. var Position;
  13823. (function (Position) {
  13824. /**
  13825. * Creates a new Position literal from the given line and character.
  13826. * @param line The position's line.
  13827. * @param character The position's character.
  13828. */
  13829. function create(line, character) {
  13830. return { line: line, character: character };
  13831. }
  13832. Position.create = create;
  13833. /**
  13834. * Checks whether the given liternal conforms to the [Position](#Position) interface.
  13835. */
  13836. function is(value) {
  13837. var candidate = value;
  13838. return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
  13839. }
  13840. Position.is = is;
  13841. })(Position || (Position = {}));
  13842. /**
  13843. * The Range namespace provides helper functions to work with
  13844. * [Range](#Range) literals.
  13845. */
  13846. var Range;
  13847. (function (Range) {
  13848. function create(one, two, three, four) {
  13849. if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
  13850. return { start: Position.create(one, two), end: Position.create(three, four) };
  13851. }
  13852. else if (Position.is(one) && Position.is(two)) {
  13853. return { start: one, end: two };
  13854. }
  13855. else {
  13856. throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
  13857. }
  13858. }
  13859. Range.create = create;
  13860. /**
  13861. * Checks whether the given literal conforms to the [Range](#Range) interface.
  13862. */
  13863. function is(value) {
  13864. var candidate = value;
  13865. return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
  13866. }
  13867. Range.is = is;
  13868. })(Range || (Range = {}));
  13869. /**
  13870. * The Location namespace provides helper functions to work with
  13871. * [Location](#Location) literals.
  13872. */
  13873. var Location;
  13874. (function (Location) {
  13875. /**
  13876. * Creates a Location literal.
  13877. * @param uri The location's uri.
  13878. * @param range The location's range.
  13879. */
  13880. function create(uri, range) {
  13881. return { uri: uri, range: range };
  13882. }
  13883. Location.create = create;
  13884. /**
  13885. * Checks whether the given literal conforms to the [Location](#Location) interface.
  13886. */
  13887. function is(value) {
  13888. var candidate = value;
  13889. return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
  13890. }
  13891. Location.is = is;
  13892. })(Location || (Location = {}));
  13893. /**
  13894. * The LocationLink namespace provides helper functions to work with
  13895. * [LocationLink](#LocationLink) literals.
  13896. */
  13897. var LocationLink;
  13898. (function (LocationLink) {
  13899. /**
  13900. * Creates a LocationLink literal.
  13901. * @param targetUri The definition's uri.
  13902. * @param targetRange The full range of the definition.
  13903. * @param targetSelectionRange The span of the symbol definition at the target.
  13904. * @param originSelectionRange The span of the symbol being defined in the originating source file.
  13905. */
  13906. function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
  13907. return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
  13908. }
  13909. LocationLink.create = create;
  13910. /**
  13911. * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
  13912. */
  13913. function is(value) {
  13914. var candidate = value;
  13915. return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
  13916. && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
  13917. && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
  13918. }
  13919. LocationLink.is = is;
  13920. })(LocationLink || (LocationLink = {}));
  13921. /**
  13922. * The Color namespace provides helper functions to work with
  13923. * [Color](#Color) literals.
  13924. */
  13925. var Color;
  13926. (function (Color) {
  13927. /**
  13928. * Creates a new Color literal.
  13929. */
  13930. function create(red, green, blue, alpha) {
  13931. return {
  13932. red: red,
  13933. green: green,
  13934. blue: blue,
  13935. alpha: alpha,
  13936. };
  13937. }
  13938. Color.create = create;
  13939. /**
  13940. * Checks whether the given literal conforms to the [Color](#Color) interface.
  13941. */
  13942. function is(value) {
  13943. var candidate = value;
  13944. return Is.number(candidate.red)
  13945. && Is.number(candidate.green)
  13946. && Is.number(candidate.blue)
  13947. && Is.number(candidate.alpha);
  13948. }
  13949. Color.is = is;
  13950. })(Color || (Color = {}));
  13951. /**
  13952. * The ColorInformation namespace provides helper functions to work with
  13953. * [ColorInformation](#ColorInformation) literals.
  13954. */
  13955. var ColorInformation;
  13956. (function (ColorInformation) {
  13957. /**
  13958. * Creates a new ColorInformation literal.
  13959. */
  13960. function create(range, color) {
  13961. return {
  13962. range: range,
  13963. color: color,
  13964. };
  13965. }
  13966. ColorInformation.create = create;
  13967. /**
  13968. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  13969. */
  13970. function is(value) {
  13971. var candidate = value;
  13972. return Range.is(candidate.range) && Color.is(candidate.color);
  13973. }
  13974. ColorInformation.is = is;
  13975. })(ColorInformation || (ColorInformation = {}));
  13976. /**
  13977. * The Color namespace provides helper functions to work with
  13978. * [ColorPresentation](#ColorPresentation) literals.
  13979. */
  13980. var ColorPresentation;
  13981. (function (ColorPresentation) {
  13982. /**
  13983. * Creates a new ColorInformation literal.
  13984. */
  13985. function create(label, textEdit, additionalTextEdits) {
  13986. return {
  13987. label: label,
  13988. textEdit: textEdit,
  13989. additionalTextEdits: additionalTextEdits,
  13990. };
  13991. }
  13992. ColorPresentation.create = create;
  13993. /**
  13994. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  13995. */
  13996. function is(value) {
  13997. var candidate = value;
  13998. return Is.string(candidate.label)
  13999. && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
  14000. && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
  14001. }
  14002. ColorPresentation.is = is;
  14003. })(ColorPresentation || (ColorPresentation = {}));
  14004. /**
  14005. * Enum of known range kinds
  14006. */
  14007. var FoldingRangeKind;
  14008. (function (FoldingRangeKind) {
  14009. /**
  14010. * Folding range for a comment
  14011. */
  14012. FoldingRangeKind["Comment"] = "comment";
  14013. /**
  14014. * Folding range for a imports or includes
  14015. */
  14016. FoldingRangeKind["Imports"] = "imports";
  14017. /**
  14018. * Folding range for a region (e.g. `#region`)
  14019. */
  14020. FoldingRangeKind["Region"] = "region";
  14021. })(FoldingRangeKind || (FoldingRangeKind = {}));
  14022. /**
  14023. * The folding range namespace provides helper functions to work with
  14024. * [FoldingRange](#FoldingRange) literals.
  14025. */
  14026. var FoldingRange;
  14027. (function (FoldingRange) {
  14028. /**
  14029. * Creates a new FoldingRange literal.
  14030. */
  14031. function create(startLine, endLine, startCharacter, endCharacter, kind) {
  14032. var result = {
  14033. startLine: startLine,
  14034. endLine: endLine
  14035. };
  14036. if (Is.defined(startCharacter)) {
  14037. result.startCharacter = startCharacter;
  14038. }
  14039. if (Is.defined(endCharacter)) {
  14040. result.endCharacter = endCharacter;
  14041. }
  14042. if (Is.defined(kind)) {
  14043. result.kind = kind;
  14044. }
  14045. return result;
  14046. }
  14047. FoldingRange.create = create;
  14048. /**
  14049. * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
  14050. */
  14051. function is(value) {
  14052. var candidate = value;
  14053. return Is.number(candidate.startLine) && Is.number(candidate.startLine)
  14054. && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
  14055. && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
  14056. && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
  14057. }
  14058. FoldingRange.is = is;
  14059. })(FoldingRange || (FoldingRange = {}));
  14060. /**
  14061. * The DiagnosticRelatedInformation namespace provides helper functions to work with
  14062. * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
  14063. */
  14064. var DiagnosticRelatedInformation;
  14065. (function (DiagnosticRelatedInformation) {
  14066. /**
  14067. * Creates a new DiagnosticRelatedInformation literal.
  14068. */
  14069. function create(location, message) {
  14070. return {
  14071. location: location,
  14072. message: message
  14073. };
  14074. }
  14075. DiagnosticRelatedInformation.create = create;
  14076. /**
  14077. * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
  14078. */
  14079. function is(value) {
  14080. var candidate = value;
  14081. return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
  14082. }
  14083. DiagnosticRelatedInformation.is = is;
  14084. })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
  14085. /**
  14086. * The diagnostic's severity.
  14087. */
  14088. var DiagnosticSeverity;
  14089. (function (DiagnosticSeverity) {
  14090. /**
  14091. * Reports an error.
  14092. */
  14093. DiagnosticSeverity.Error = 1;
  14094. /**
  14095. * Reports a warning.
  14096. */
  14097. DiagnosticSeverity.Warning = 2;
  14098. /**
  14099. * Reports an information.
  14100. */
  14101. DiagnosticSeverity.Information = 3;
  14102. /**
  14103. * Reports a hint.
  14104. */
  14105. DiagnosticSeverity.Hint = 4;
  14106. })(DiagnosticSeverity || (DiagnosticSeverity = {}));
  14107. var DiagnosticTag;
  14108. (function (DiagnosticTag) {
  14109. /**
  14110. * Unused or unnecessary code.
  14111. *
  14112. * Clients are allowed to render diagnostics with this tag faded out instead of having
  14113. * an error squiggle.
  14114. */
  14115. DiagnosticTag.Unnecessary = 1;
  14116. })(DiagnosticTag || (DiagnosticTag = {}));
  14117. /**
  14118. * The Diagnostic namespace provides helper functions to work with
  14119. * [Diagnostic](#Diagnostic) literals.
  14120. */
  14121. var Diagnostic;
  14122. (function (Diagnostic) {
  14123. /**
  14124. * Creates a new Diagnostic literal.
  14125. */
  14126. function create(range, message, severity, code, source, relatedInformation) {
  14127. var result = { range: range, message: message };
  14128. if (Is.defined(severity)) {
  14129. result.severity = severity;
  14130. }
  14131. if (Is.defined(code)) {
  14132. result.code = code;
  14133. }
  14134. if (Is.defined(source)) {
  14135. result.source = source;
  14136. }
  14137. if (Is.defined(relatedInformation)) {
  14138. result.relatedInformation = relatedInformation;
  14139. }
  14140. return result;
  14141. }
  14142. Diagnostic.create = create;
  14143. /**
  14144. * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
  14145. */
  14146. function is(value) {
  14147. var candidate = value;
  14148. return Is.defined(candidate)
  14149. && Range.is(candidate.range)
  14150. && Is.string(candidate.message)
  14151. && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
  14152. && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
  14153. && (Is.string(candidate.source) || Is.undefined(candidate.source))
  14154. && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
  14155. }
  14156. Diagnostic.is = is;
  14157. })(Diagnostic || (Diagnostic = {}));
  14158. /**
  14159. * The Command namespace provides helper functions to work with
  14160. * [Command](#Command) literals.
  14161. */
  14162. var Command;
  14163. (function (Command) {
  14164. /**
  14165. * Creates a new Command literal.
  14166. */
  14167. function create(title, command) {
  14168. var args = [];
  14169. for (var _i = 2; _i < arguments.length; _i++) {
  14170. args[_i - 2] = arguments[_i];
  14171. }
  14172. var result = { title: title, command: command };
  14173. if (Is.defined(args) && args.length > 0) {
  14174. result.arguments = args;
  14175. }
  14176. return result;
  14177. }
  14178. Command.create = create;
  14179. /**
  14180. * Checks whether the given literal conforms to the [Command](#Command) interface.
  14181. */
  14182. function is(value) {
  14183. var candidate = value;
  14184. return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
  14185. }
  14186. Command.is = is;
  14187. })(Command || (Command = {}));
  14188. /**
  14189. * The TextEdit namespace provides helper function to create replace,
  14190. * insert and delete edits more easily.
  14191. */
  14192. var TextEdit;
  14193. (function (TextEdit) {
  14194. /**
  14195. * Creates a replace text edit.
  14196. * @param range The range of text to be replaced.
  14197. * @param newText The new text.
  14198. */
  14199. function replace(range, newText) {
  14200. return { range: range, newText: newText };
  14201. }
  14202. TextEdit.replace = replace;
  14203. /**
  14204. * Creates a insert text edit.
  14205. * @param position The position to insert the text at.
  14206. * @param newText The text to be inserted.
  14207. */
  14208. function insert(position, newText) {
  14209. return { range: { start: position, end: position }, newText: newText };
  14210. }
  14211. TextEdit.insert = insert;
  14212. /**
  14213. * Creates a delete text edit.
  14214. * @param range The range of text to be deleted.
  14215. */
  14216. function del(range) {
  14217. return { range: range, newText: '' };
  14218. }
  14219. TextEdit.del = del;
  14220. function is(value) {
  14221. var candidate = value;
  14222. return Is.objectLiteral(candidate)
  14223. && Is.string(candidate.newText)
  14224. && Range.is(candidate.range);
  14225. }
  14226. TextEdit.is = is;
  14227. })(TextEdit || (TextEdit = {}));
  14228. /**
  14229. * The TextDocumentEdit namespace provides helper function to create
  14230. * an edit that manipulates a text document.
  14231. */
  14232. var TextDocumentEdit;
  14233. (function (TextDocumentEdit) {
  14234. /**
  14235. * Creates a new `TextDocumentEdit`
  14236. */
  14237. function create(textDocument, edits) {
  14238. return { textDocument: textDocument, edits: edits };
  14239. }
  14240. TextDocumentEdit.create = create;
  14241. function is(value) {
  14242. var candidate = value;
  14243. return Is.defined(candidate)
  14244. && VersionedTextDocumentIdentifier.is(candidate.textDocument)
  14245. && Array.isArray(candidate.edits);
  14246. }
  14247. TextDocumentEdit.is = is;
  14248. })(TextDocumentEdit || (TextDocumentEdit = {}));
  14249. var CreateFile;
  14250. (function (CreateFile) {
  14251. function create(uri, options) {
  14252. var result = {
  14253. kind: 'create',
  14254. uri: uri
  14255. };
  14256. if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
  14257. result.options = options;
  14258. }
  14259. return result;
  14260. }
  14261. CreateFile.create = create;
  14262. function is(value) {
  14263. var candidate = value;
  14264. return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
  14265. (candidate.options === void 0 ||
  14266. ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
  14267. }
  14268. CreateFile.is = is;
  14269. })(CreateFile || (CreateFile = {}));
  14270. var RenameFile;
  14271. (function (RenameFile) {
  14272. function create(oldUri, newUri, options) {
  14273. var result = {
  14274. kind: 'rename',
  14275. oldUri: oldUri,
  14276. newUri: newUri
  14277. };
  14278. if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
  14279. result.options = options;
  14280. }
  14281. return result;
  14282. }
  14283. RenameFile.create = create;
  14284. function is(value) {
  14285. var candidate = value;
  14286. return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
  14287. (candidate.options === void 0 ||
  14288. ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
  14289. }
  14290. RenameFile.is = is;
  14291. })(RenameFile || (RenameFile = {}));
  14292. var DeleteFile;
  14293. (function (DeleteFile) {
  14294. function create(uri, options) {
  14295. var result = {
  14296. kind: 'delete',
  14297. uri: uri
  14298. };
  14299. if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
  14300. result.options = options;
  14301. }
  14302. return result;
  14303. }
  14304. DeleteFile.create = create;
  14305. function is(value) {
  14306. var candidate = value;
  14307. return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
  14308. (candidate.options === void 0 ||
  14309. ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
  14310. }
  14311. DeleteFile.is = is;
  14312. })(DeleteFile || (DeleteFile = {}));
  14313. var WorkspaceEdit;
  14314. (function (WorkspaceEdit) {
  14315. function is(value) {
  14316. var candidate = value;
  14317. return candidate &&
  14318. (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
  14319. (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
  14320. if (Is.string(change.kind)) {
  14321. return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
  14322. }
  14323. else {
  14324. return TextDocumentEdit.is(change);
  14325. }
  14326. }));
  14327. }
  14328. WorkspaceEdit.is = is;
  14329. })(WorkspaceEdit || (WorkspaceEdit = {}));
  14330. var TextEditChangeImpl = /** @class */ (function () {
  14331. function TextEditChangeImpl(edits) {
  14332. this.edits = edits;
  14333. }
  14334. TextEditChangeImpl.prototype.insert = function (position, newText) {
  14335. this.edits.push(TextEdit.insert(position, newText));
  14336. };
  14337. TextEditChangeImpl.prototype.replace = function (range, newText) {
  14338. this.edits.push(TextEdit.replace(range, newText));
  14339. };
  14340. TextEditChangeImpl.prototype.delete = function (range) {
  14341. this.edits.push(TextEdit.del(range));
  14342. };
  14343. TextEditChangeImpl.prototype.add = function (edit) {
  14344. this.edits.push(edit);
  14345. };
  14346. TextEditChangeImpl.prototype.all = function () {
  14347. return this.edits;
  14348. };
  14349. TextEditChangeImpl.prototype.clear = function () {
  14350. this.edits.splice(0, this.edits.length);
  14351. };
  14352. return TextEditChangeImpl;
  14353. }());
  14354. /**
  14355. * A workspace change helps constructing changes to a workspace.
  14356. */
  14357. var WorkspaceChange = /** @class */ (function () {
  14358. function WorkspaceChange(workspaceEdit) {
  14359. var _this = this;
  14360. this._textEditChanges = Object.create(null);
  14361. if (workspaceEdit) {
  14362. this._workspaceEdit = workspaceEdit;
  14363. if (workspaceEdit.documentChanges) {
  14364. workspaceEdit.documentChanges.forEach(function (change) {
  14365. if (TextDocumentEdit.is(change)) {
  14366. var textEditChange = new TextEditChangeImpl(change.edits);
  14367. _this._textEditChanges[change.textDocument.uri] = textEditChange;
  14368. }
  14369. });
  14370. }
  14371. else if (workspaceEdit.changes) {
  14372. Object.keys(workspaceEdit.changes).forEach(function (key) {
  14373. var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
  14374. _this._textEditChanges[key] = textEditChange;
  14375. });
  14376. }
  14377. }
  14378. }
  14379. Object.defineProperty(WorkspaceChange.prototype, "edit", {
  14380. /**
  14381. * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
  14382. * use to be returned from a workspace edit operation like rename.
  14383. */
  14384. get: function () {
  14385. return this._workspaceEdit;
  14386. },
  14387. enumerable: true,
  14388. configurable: true
  14389. });
  14390. WorkspaceChange.prototype.getTextEditChange = function (key) {
  14391. if (VersionedTextDocumentIdentifier.is(key)) {
  14392. if (!this._workspaceEdit) {
  14393. this._workspaceEdit = {
  14394. documentChanges: []
  14395. };
  14396. }
  14397. if (!this._workspaceEdit.documentChanges) {
  14398. throw new Error('Workspace edit is not configured for document changes.');
  14399. }
  14400. var textDocument = key;
  14401. var result = this._textEditChanges[textDocument.uri];
  14402. if (!result) {
  14403. var edits = [];
  14404. var textDocumentEdit = {
  14405. textDocument: textDocument,
  14406. edits: edits
  14407. };
  14408. this._workspaceEdit.documentChanges.push(textDocumentEdit);
  14409. result = new TextEditChangeImpl(edits);
  14410. this._textEditChanges[textDocument.uri] = result;
  14411. }
  14412. return result;
  14413. }
  14414. else {
  14415. if (!this._workspaceEdit) {
  14416. this._workspaceEdit = {
  14417. changes: Object.create(null)
  14418. };
  14419. }
  14420. if (!this._workspaceEdit.changes) {
  14421. throw new Error('Workspace edit is not configured for normal text edit changes.');
  14422. }
  14423. var result = this._textEditChanges[key];
  14424. if (!result) {
  14425. var edits = [];
  14426. this._workspaceEdit.changes[key] = edits;
  14427. result = new TextEditChangeImpl(edits);
  14428. this._textEditChanges[key] = result;
  14429. }
  14430. return result;
  14431. }
  14432. };
  14433. WorkspaceChange.prototype.createFile = function (uri, options) {
  14434. this.checkDocumentChanges();
  14435. this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
  14436. };
  14437. WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
  14438. this.checkDocumentChanges();
  14439. this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
  14440. };
  14441. WorkspaceChange.prototype.deleteFile = function (uri, options) {
  14442. this.checkDocumentChanges();
  14443. this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
  14444. };
  14445. WorkspaceChange.prototype.checkDocumentChanges = function () {
  14446. if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
  14447. throw new Error('Workspace edit is not configured for document changes.');
  14448. }
  14449. };
  14450. return WorkspaceChange;
  14451. }());
  14452. /**
  14453. * The TextDocumentIdentifier namespace provides helper functions to work with
  14454. * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
  14455. */
  14456. var TextDocumentIdentifier;
  14457. (function (TextDocumentIdentifier) {
  14458. /**
  14459. * Creates a new TextDocumentIdentifier literal.
  14460. * @param uri The document's uri.
  14461. */
  14462. function create(uri) {
  14463. return { uri: uri };
  14464. }
  14465. TextDocumentIdentifier.create = create;
  14466. /**
  14467. * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
  14468. */
  14469. function is(value) {
  14470. var candidate = value;
  14471. return Is.defined(candidate) && Is.string(candidate.uri);
  14472. }
  14473. TextDocumentIdentifier.is = is;
  14474. })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
  14475. /**
  14476. * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
  14477. * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
  14478. */
  14479. var VersionedTextDocumentIdentifier;
  14480. (function (VersionedTextDocumentIdentifier) {
  14481. /**
  14482. * Creates a new VersionedTextDocumentIdentifier literal.
  14483. * @param uri The document's uri.
  14484. * @param uri The document's text.
  14485. */
  14486. function create(uri, version) {
  14487. return { uri: uri, version: version };
  14488. }
  14489. VersionedTextDocumentIdentifier.create = create;
  14490. /**
  14491. * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
  14492. */
  14493. function is(value) {
  14494. var candidate = value;
  14495. return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
  14496. }
  14497. VersionedTextDocumentIdentifier.is = is;
  14498. })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
  14499. /**
  14500. * The TextDocumentItem namespace provides helper functions to work with
  14501. * [TextDocumentItem](#TextDocumentItem) literals.
  14502. */
  14503. var TextDocumentItem;
  14504. (function (TextDocumentItem) {
  14505. /**
  14506. * Creates a new TextDocumentItem literal.
  14507. * @param uri The document's uri.
  14508. * @param languageId The document's language identifier.
  14509. * @param version The document's version number.
  14510. * @param text The document's text.
  14511. */
  14512. function create(uri, languageId, version, text) {
  14513. return { uri: uri, languageId: languageId, version: version, text: text };
  14514. }
  14515. TextDocumentItem.create = create;
  14516. /**
  14517. * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
  14518. */
  14519. function is(value) {
  14520. var candidate = value;
  14521. return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
  14522. }
  14523. TextDocumentItem.is = is;
  14524. })(TextDocumentItem || (TextDocumentItem = {}));
  14525. /**
  14526. * Describes the content type that a client supports in various
  14527. * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
  14528. *
  14529. * Please note that `MarkupKinds` must not start with a `$`. This kinds
  14530. * are reserved for internal usage.
  14531. */
  14532. var MarkupKind;
  14533. (function (MarkupKind) {
  14534. /**
  14535. * Plain text is supported as a content format
  14536. */
  14537. MarkupKind.PlainText = 'plaintext';
  14538. /**
  14539. * Markdown is supported as a content format
  14540. */
  14541. MarkupKind.Markdown = 'markdown';
  14542. })(MarkupKind || (MarkupKind = {}));
  14543. (function (MarkupKind) {
  14544. /**
  14545. * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
  14546. */
  14547. function is(value) {
  14548. var candidate = value;
  14549. return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
  14550. }
  14551. MarkupKind.is = is;
  14552. })(MarkupKind || (MarkupKind = {}));
  14553. var MarkupContent;
  14554. (function (MarkupContent) {
  14555. /**
  14556. * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
  14557. */
  14558. function is(value) {
  14559. var candidate = value;
  14560. return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
  14561. }
  14562. MarkupContent.is = is;
  14563. })(MarkupContent || (MarkupContent = {}));
  14564. /**
  14565. * The kind of a completion entry.
  14566. */
  14567. var CompletionItemKind;
  14568. (function (CompletionItemKind) {
  14569. CompletionItemKind.Text = 1;
  14570. CompletionItemKind.Method = 2;
  14571. CompletionItemKind.Function = 3;
  14572. CompletionItemKind.Constructor = 4;
  14573. CompletionItemKind.Field = 5;
  14574. CompletionItemKind.Variable = 6;
  14575. CompletionItemKind.Class = 7;
  14576. CompletionItemKind.Interface = 8;
  14577. CompletionItemKind.Module = 9;
  14578. CompletionItemKind.Property = 10;
  14579. CompletionItemKind.Unit = 11;
  14580. CompletionItemKind.Value = 12;
  14581. CompletionItemKind.Enum = 13;
  14582. CompletionItemKind.Keyword = 14;
  14583. CompletionItemKind.Snippet = 15;
  14584. CompletionItemKind.Color = 16;
  14585. CompletionItemKind.File = 17;
  14586. CompletionItemKind.Reference = 18;
  14587. CompletionItemKind.Folder = 19;
  14588. CompletionItemKind.EnumMember = 20;
  14589. CompletionItemKind.Constant = 21;
  14590. CompletionItemKind.Struct = 22;
  14591. CompletionItemKind.Event = 23;
  14592. CompletionItemKind.Operator = 24;
  14593. CompletionItemKind.TypeParameter = 25;
  14594. })(CompletionItemKind || (CompletionItemKind = {}));
  14595. /**
  14596. * Defines whether the insert text in a completion item should be interpreted as
  14597. * plain text or a snippet.
  14598. */
  14599. var InsertTextFormat;
  14600. (function (InsertTextFormat) {
  14601. /**
  14602. * The primary text to be inserted is treated as a plain string.
  14603. */
  14604. InsertTextFormat.PlainText = 1;
  14605. /**
  14606. * The primary text to be inserted is treated as a snippet.
  14607. *
  14608. * A snippet can define tab stops and placeholders with `$1`, `$2`
  14609. * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
  14610. * the end of the snippet. Placeholders with equal identifiers are linked,
  14611. * that is typing in one will update others too.
  14612. *
  14613. * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
  14614. */
  14615. InsertTextFormat.Snippet = 2;
  14616. })(InsertTextFormat || (InsertTextFormat = {}));
  14617. /**
  14618. * The CompletionItem namespace provides functions to deal with
  14619. * completion items.
  14620. */
  14621. var CompletionItem;
  14622. (function (CompletionItem) {
  14623. /**
  14624. * Create a completion item and seed it with a label.
  14625. * @param label The completion item's label
  14626. */
  14627. function create(label) {
  14628. return { label: label };
  14629. }
  14630. CompletionItem.create = create;
  14631. })(CompletionItem || (CompletionItem = {}));
  14632. /**
  14633. * The CompletionList namespace provides functions to deal with
  14634. * completion lists.
  14635. */
  14636. var CompletionList;
  14637. (function (CompletionList) {
  14638. /**
  14639. * Creates a new completion list.
  14640. *
  14641. * @param items The completion items.
  14642. * @param isIncomplete The list is not complete.
  14643. */
  14644. function create(items, isIncomplete) {
  14645. return { items: items ? items : [], isIncomplete: !!isIncomplete };
  14646. }
  14647. CompletionList.create = create;
  14648. })(CompletionList || (CompletionList = {}));
  14649. var MarkedString;
  14650. (function (MarkedString) {
  14651. /**
  14652. * Creates a marked string from plain text.
  14653. *
  14654. * @param plainText The plain text.
  14655. */
  14656. function fromPlainText(plainText) {
  14657. return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
  14658. }
  14659. MarkedString.fromPlainText = fromPlainText;
  14660. /**
  14661. * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
  14662. */
  14663. function is(value) {
  14664. var candidate = value;
  14665. return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
  14666. }
  14667. MarkedString.is = is;
  14668. })(MarkedString || (MarkedString = {}));
  14669. var Hover;
  14670. (function (Hover) {
  14671. /**
  14672. * Checks whether the given value conforms to the [Hover](#Hover) interface.
  14673. */
  14674. function is(value) {
  14675. var candidate = value;
  14676. return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
  14677. MarkedString.is(candidate.contents) ||
  14678. Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
  14679. }
  14680. Hover.is = is;
  14681. })(Hover || (Hover = {}));
  14682. /**
  14683. * The ParameterInformation namespace provides helper functions to work with
  14684. * [ParameterInformation](#ParameterInformation) literals.
  14685. */
  14686. var ParameterInformation;
  14687. (function (ParameterInformation) {
  14688. /**
  14689. * Creates a new parameter information literal.
  14690. *
  14691. * @param label A label string.
  14692. * @param documentation A doc string.
  14693. */
  14694. function create(label, documentation) {
  14695. return documentation ? { label: label, documentation: documentation } : { label: label };
  14696. }
  14697. ParameterInformation.create = create;
  14698. ;
  14699. })(ParameterInformation || (ParameterInformation = {}));
  14700. /**
  14701. * The SignatureInformation namespace provides helper functions to work with
  14702. * [SignatureInformation](#SignatureInformation) literals.
  14703. */
  14704. var SignatureInformation;
  14705. (function (SignatureInformation) {
  14706. function create(label, documentation) {
  14707. var parameters = [];
  14708. for (var _i = 2; _i < arguments.length; _i++) {
  14709. parameters[_i - 2] = arguments[_i];
  14710. }
  14711. var result = { label: label };
  14712. if (Is.defined(documentation)) {
  14713. result.documentation = documentation;
  14714. }
  14715. if (Is.defined(parameters)) {
  14716. result.parameters = parameters;
  14717. }
  14718. else {
  14719. result.parameters = [];
  14720. }
  14721. return result;
  14722. }
  14723. SignatureInformation.create = create;
  14724. })(SignatureInformation || (SignatureInformation = {}));
  14725. /**
  14726. * A document highlight kind.
  14727. */
  14728. var DocumentHighlightKind;
  14729. (function (DocumentHighlightKind) {
  14730. /**
  14731. * A textual occurrence.
  14732. */
  14733. DocumentHighlightKind.Text = 1;
  14734. /**
  14735. * Read-access of a symbol, like reading a variable.
  14736. */
  14737. DocumentHighlightKind.Read = 2;
  14738. /**
  14739. * Write-access of a symbol, like writing to a variable.
  14740. */
  14741. DocumentHighlightKind.Write = 3;
  14742. })(DocumentHighlightKind || (DocumentHighlightKind = {}));
  14743. /**
  14744. * DocumentHighlight namespace to provide helper functions to work with
  14745. * [DocumentHighlight](#DocumentHighlight) literals.
  14746. */
  14747. var DocumentHighlight;
  14748. (function (DocumentHighlight) {
  14749. /**
  14750. * Create a DocumentHighlight object.
  14751. * @param range The range the highlight applies to.
  14752. */
  14753. function create(range, kind) {
  14754. var result = { range: range };
  14755. if (Is.number(kind)) {
  14756. result.kind = kind;
  14757. }
  14758. return result;
  14759. }
  14760. DocumentHighlight.create = create;
  14761. })(DocumentHighlight || (DocumentHighlight = {}));
  14762. /**
  14763. * A symbol kind.
  14764. */
  14765. var SymbolKind;
  14766. (function (SymbolKind) {
  14767. SymbolKind.File = 1;
  14768. SymbolKind.Module = 2;
  14769. SymbolKind.Namespace = 3;
  14770. SymbolKind.Package = 4;
  14771. SymbolKind.Class = 5;
  14772. SymbolKind.Method = 6;
  14773. SymbolKind.Property = 7;
  14774. SymbolKind.Field = 8;
  14775. SymbolKind.Constructor = 9;
  14776. SymbolKind.Enum = 10;
  14777. SymbolKind.Interface = 11;
  14778. SymbolKind.Function = 12;
  14779. SymbolKind.Variable = 13;
  14780. SymbolKind.Constant = 14;
  14781. SymbolKind.String = 15;
  14782. SymbolKind.Number = 16;
  14783. SymbolKind.Boolean = 17;
  14784. SymbolKind.Array = 18;
  14785. SymbolKind.Object = 19;
  14786. SymbolKind.Key = 20;
  14787. SymbolKind.Null = 21;
  14788. SymbolKind.EnumMember = 22;
  14789. SymbolKind.Struct = 23;
  14790. SymbolKind.Event = 24;
  14791. SymbolKind.Operator = 25;
  14792. SymbolKind.TypeParameter = 26;
  14793. })(SymbolKind || (SymbolKind = {}));
  14794. var SymbolInformation;
  14795. (function (SymbolInformation) {
  14796. /**
  14797. * Creates a new symbol information literal.
  14798. *
  14799. * @param name The name of the symbol.
  14800. * @param kind The kind of the symbol.
  14801. * @param range The range of the location of the symbol.
  14802. * @param uri The resource of the location of symbol, defaults to the current document.
  14803. * @param containerName The name of the symbol containing the symbol.
  14804. */
  14805. function create(name, kind, range, uri, containerName) {
  14806. var result = {
  14807. name: name,
  14808. kind: kind,
  14809. location: { uri: uri, range: range }
  14810. };
  14811. if (containerName) {
  14812. result.containerName = containerName;
  14813. }
  14814. return result;
  14815. }
  14816. SymbolInformation.create = create;
  14817. })(SymbolInformation || (SymbolInformation = {}));
  14818. /**
  14819. * Represents programming constructs like variables, classes, interfaces etc.
  14820. * that appear in a document. Document symbols can be hierarchical and they
  14821. * have two ranges: one that encloses its definition and one that points to
  14822. * its most interesting range, e.g. the range of an identifier.
  14823. */
  14824. var DocumentSymbol = /** @class */ (function () {
  14825. function DocumentSymbol() {
  14826. }
  14827. return DocumentSymbol;
  14828. }());
  14829. (function (DocumentSymbol) {
  14830. /**
  14831. * Creates a new symbol information literal.
  14832. *
  14833. * @param name The name of the symbol.
  14834. * @param detail The detail of the symbol.
  14835. * @param kind The kind of the symbol.
  14836. * @param range The range of the symbol.
  14837. * @param selectionRange The selectionRange of the symbol.
  14838. * @param children Children of the symbol.
  14839. */
  14840. function create(name, detail, kind, range, selectionRange, children) {
  14841. var result = {
  14842. name: name,
  14843. detail: detail,
  14844. kind: kind,
  14845. range: range,
  14846. selectionRange: selectionRange
  14847. };
  14848. if (children !== void 0) {
  14849. result.children = children;
  14850. }
  14851. return result;
  14852. }
  14853. DocumentSymbol.create = create;
  14854. /**
  14855. * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
  14856. */
  14857. function is(value) {
  14858. var candidate = value;
  14859. return candidate &&
  14860. Is.string(candidate.name) && Is.number(candidate.kind) &&
  14861. Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
  14862. (candidate.detail === void 0 || Is.string(candidate.detail)) &&
  14863. (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
  14864. (candidate.children === void 0 || Array.isArray(candidate.children));
  14865. }
  14866. DocumentSymbol.is = is;
  14867. })(DocumentSymbol || (DocumentSymbol = {}));
  14868. /**
  14869. * A set of predefined code action kinds
  14870. */
  14871. var CodeActionKind;
  14872. (function (CodeActionKind) {
  14873. /**
  14874. * Base kind for quickfix actions: 'quickfix'
  14875. */
  14876. CodeActionKind.QuickFix = 'quickfix';
  14877. /**
  14878. * Base kind for refactoring actions: 'refactor'
  14879. */
  14880. CodeActionKind.Refactor = 'refactor';
  14881. /**
  14882. * Base kind for refactoring extraction actions: 'refactor.extract'
  14883. *
  14884. * Example extract actions:
  14885. *
  14886. * - Extract method
  14887. * - Extract function
  14888. * - Extract variable
  14889. * - Extract interface from class
  14890. * - ...
  14891. */
  14892. CodeActionKind.RefactorExtract = 'refactor.extract';
  14893. /**
  14894. * Base kind for refactoring inline actions: 'refactor.inline'
  14895. *
  14896. * Example inline actions:
  14897. *
  14898. * - Inline function
  14899. * - Inline variable
  14900. * - Inline constant
  14901. * - ...
  14902. */
  14903. CodeActionKind.RefactorInline = 'refactor.inline';
  14904. /**
  14905. * Base kind for refactoring rewrite actions: 'refactor.rewrite'
  14906. *
  14907. * Example rewrite actions:
  14908. *
  14909. * - Convert JavaScript function to class
  14910. * - Add or remove parameter
  14911. * - Encapsulate field
  14912. * - Make method static
  14913. * - Move method to base class
  14914. * - ...
  14915. */
  14916. CodeActionKind.RefactorRewrite = 'refactor.rewrite';
  14917. /**
  14918. * Base kind for source actions: `source`
  14919. *
  14920. * Source code actions apply to the entire file.
  14921. */
  14922. CodeActionKind.Source = 'source';
  14923. /**
  14924. * Base kind for an organize imports source action: `source.organizeImports`
  14925. */
  14926. CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
  14927. })(CodeActionKind || (CodeActionKind = {}));
  14928. /**
  14929. * The CodeActionContext namespace provides helper functions to work with
  14930. * [CodeActionContext](#CodeActionContext) literals.
  14931. */
  14932. var CodeActionContext;
  14933. (function (CodeActionContext) {
  14934. /**
  14935. * Creates a new CodeActionContext literal.
  14936. */
  14937. function create(diagnostics, only) {
  14938. var result = { diagnostics: diagnostics };
  14939. if (only !== void 0 && only !== null) {
  14940. result.only = only;
  14941. }
  14942. return result;
  14943. }
  14944. CodeActionContext.create = create;
  14945. /**
  14946. * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
  14947. */
  14948. function is(value) {
  14949. var candidate = value;
  14950. return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
  14951. }
  14952. CodeActionContext.is = is;
  14953. })(CodeActionContext || (CodeActionContext = {}));
  14954. var CodeAction;
  14955. (function (CodeAction) {
  14956. function create(title, commandOrEdit, kind) {
  14957. var result = { title: title };
  14958. if (Command.is(commandOrEdit)) {
  14959. result.command = commandOrEdit;
  14960. }
  14961. else {
  14962. result.edit = commandOrEdit;
  14963. }
  14964. if (kind !== void null) {
  14965. result.kind = kind;
  14966. }
  14967. return result;
  14968. }
  14969. CodeAction.create = create;
  14970. function is(value) {
  14971. var candidate = value;
  14972. return candidate && Is.string(candidate.title) &&
  14973. (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
  14974. (candidate.kind === void 0 || Is.string(candidate.kind)) &&
  14975. (candidate.edit !== void 0 || candidate.command !== void 0) &&
  14976. (candidate.command === void 0 || Command.is(candidate.command)) &&
  14977. (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
  14978. }
  14979. CodeAction.is = is;
  14980. })(CodeAction || (CodeAction = {}));
  14981. /**
  14982. * The CodeLens namespace provides helper functions to work with
  14983. * [CodeLens](#CodeLens) literals.
  14984. */
  14985. var CodeLens;
  14986. (function (CodeLens) {
  14987. /**
  14988. * Creates a new CodeLens literal.
  14989. */
  14990. function create(range, data) {
  14991. var result = { range: range };
  14992. if (Is.defined(data))
  14993. result.data = data;
  14994. return result;
  14995. }
  14996. CodeLens.create = create;
  14997. /**
  14998. * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
  14999. */
  15000. function is(value) {
  15001. var candidate = value;
  15002. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
  15003. }
  15004. CodeLens.is = is;
  15005. })(CodeLens || (CodeLens = {}));
  15006. /**
  15007. * The FormattingOptions namespace provides helper functions to work with
  15008. * [FormattingOptions](#FormattingOptions) literals.
  15009. */
  15010. var FormattingOptions;
  15011. (function (FormattingOptions) {
  15012. /**
  15013. * Creates a new FormattingOptions literal.
  15014. */
  15015. function create(tabSize, insertSpaces) {
  15016. return { tabSize: tabSize, insertSpaces: insertSpaces };
  15017. }
  15018. FormattingOptions.create = create;
  15019. /**
  15020. * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
  15021. */
  15022. function is(value) {
  15023. var candidate = value;
  15024. return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
  15025. }
  15026. FormattingOptions.is = is;
  15027. })(FormattingOptions || (FormattingOptions = {}));
  15028. /**
  15029. * A document link is a range in a text document that links to an internal or external resource, like another
  15030. * text document or a web site.
  15031. */
  15032. var DocumentLink = /** @class */ (function () {
  15033. function DocumentLink() {
  15034. }
  15035. return DocumentLink;
  15036. }());
  15037. /**
  15038. * The DocumentLink namespace provides helper functions to work with
  15039. * [DocumentLink](#DocumentLink) literals.
  15040. */
  15041. (function (DocumentLink) {
  15042. /**
  15043. * Creates a new DocumentLink literal.
  15044. */
  15045. function create(range, target, data) {
  15046. return { range: range, target: target, data: data };
  15047. }
  15048. DocumentLink.create = create;
  15049. /**
  15050. * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
  15051. */
  15052. function is(value) {
  15053. var candidate = value;
  15054. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
  15055. }
  15056. DocumentLink.is = is;
  15057. })(DocumentLink || (DocumentLink = {}));
  15058. /**
  15059. * The SelectionRange namespace provides helper function to work with
  15060. * SelectionRange literals.
  15061. */
  15062. var SelectionRange;
  15063. (function (SelectionRange) {
  15064. /**
  15065. * Creates a new SelectionRange
  15066. * @param range the range.
  15067. * @param parent an optional parent.
  15068. */
  15069. function create(range, parent) {
  15070. return { range: range, parent: parent };
  15071. }
  15072. SelectionRange.create = create;
  15073. function is(value) {
  15074. var candidate = value;
  15075. return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
  15076. }
  15077. SelectionRange.is = is;
  15078. })(SelectionRange || (SelectionRange = {}));
  15079. var EOL = ['\n', '\r\n', '\r'];
  15080. var TextDocument;
  15081. (function (TextDocument) {
  15082. /**
  15083. * Creates a new ITextDocument literal from the given uri and content.
  15084. * @param uri The document's uri.
  15085. * @param languageId The document's language Id.
  15086. * @param content The document's content.
  15087. */
  15088. function create(uri, languageId, version, content) {
  15089. return new FullTextDocument(uri, languageId, version, content);
  15090. }
  15091. TextDocument.create = create;
  15092. /**
  15093. * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
  15094. */
  15095. function is(value) {
  15096. var candidate = value;
  15097. return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
  15098. && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
  15099. }
  15100. TextDocument.is = is;
  15101. function applyEdits(document, edits) {
  15102. var text = document.getText();
  15103. var sortedEdits = mergeSort(edits, function (a, b) {
  15104. var diff = a.range.start.line - b.range.start.line;
  15105. if (diff === 0) {
  15106. return a.range.start.character - b.range.start.character;
  15107. }
  15108. return diff;
  15109. });
  15110. var lastModifiedOffset = text.length;
  15111. for (var i = sortedEdits.length - 1; i >= 0; i--) {
  15112. var e = sortedEdits[i];
  15113. var startOffset = document.offsetAt(e.range.start);
  15114. var endOffset = document.offsetAt(e.range.end);
  15115. if (endOffset <= lastModifiedOffset) {
  15116. text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
  15117. }
  15118. else {
  15119. throw new Error('Overlapping edit');
  15120. }
  15121. lastModifiedOffset = startOffset;
  15122. }
  15123. return text;
  15124. }
  15125. TextDocument.applyEdits = applyEdits;
  15126. function mergeSort(data, compare) {
  15127. if (data.length <= 1) {
  15128. // sorted
  15129. return data;
  15130. }
  15131. var p = (data.length / 2) | 0;
  15132. var left = data.slice(0, p);
  15133. var right = data.slice(p);
  15134. mergeSort(left, compare);
  15135. mergeSort(right, compare);
  15136. var leftIdx = 0;
  15137. var rightIdx = 0;
  15138. var i = 0;
  15139. while (leftIdx < left.length && rightIdx < right.length) {
  15140. var ret = compare(left[leftIdx], right[rightIdx]);
  15141. if (ret <= 0) {
  15142. // smaller_equal -> take left to preserve order
  15143. data[i++] = left[leftIdx++];
  15144. }
  15145. else {
  15146. // greater -> take right
  15147. data[i++] = right[rightIdx++];
  15148. }
  15149. }
  15150. while (leftIdx < left.length) {
  15151. data[i++] = left[leftIdx++];
  15152. }
  15153. while (rightIdx < right.length) {
  15154. data[i++] = right[rightIdx++];
  15155. }
  15156. return data;
  15157. }
  15158. })(TextDocument || (TextDocument = {}));
  15159. /**
  15160. * Represents reasons why a text document is saved.
  15161. */
  15162. var TextDocumentSaveReason;
  15163. (function (TextDocumentSaveReason) {
  15164. /**
  15165. * Manually triggered, e.g. by the user pressing save, by starting debugging,
  15166. * or by an API call.
  15167. */
  15168. TextDocumentSaveReason.Manual = 1;
  15169. /**
  15170. * Automatic after a delay.
  15171. */
  15172. TextDocumentSaveReason.AfterDelay = 2;
  15173. /**
  15174. * When the editor lost focus.
  15175. */
  15176. TextDocumentSaveReason.FocusOut = 3;
  15177. })(TextDocumentSaveReason || (TextDocumentSaveReason = {}));
  15178. var FullTextDocument = /** @class */ (function () {
  15179. function FullTextDocument(uri, languageId, version, content) {
  15180. this._uri = uri;
  15181. this._languageId = languageId;
  15182. this._version = version;
  15183. this._content = content;
  15184. this._lineOffsets = null;
  15185. }
  15186. Object.defineProperty(FullTextDocument.prototype, "uri", {
  15187. get: function () {
  15188. return this._uri;
  15189. },
  15190. enumerable: true,
  15191. configurable: true
  15192. });
  15193. Object.defineProperty(FullTextDocument.prototype, "languageId", {
  15194. get: function () {
  15195. return this._languageId;
  15196. },
  15197. enumerable: true,
  15198. configurable: true
  15199. });
  15200. Object.defineProperty(FullTextDocument.prototype, "version", {
  15201. get: function () {
  15202. return this._version;
  15203. },
  15204. enumerable: true,
  15205. configurable: true
  15206. });
  15207. FullTextDocument.prototype.getText = function (range) {
  15208. if (range) {
  15209. var start = this.offsetAt(range.start);
  15210. var end = this.offsetAt(range.end);
  15211. return this._content.substring(start, end);
  15212. }
  15213. return this._content;
  15214. };
  15215. FullTextDocument.prototype.update = function (event, version) {
  15216. this._content = event.text;
  15217. this._version = version;
  15218. this._lineOffsets = null;
  15219. };
  15220. FullTextDocument.prototype.getLineOffsets = function () {
  15221. if (this._lineOffsets === null) {
  15222. var lineOffsets = [];
  15223. var text = this._content;
  15224. var isLineStart = true;
  15225. for (var i = 0; i < text.length; i++) {
  15226. if (isLineStart) {
  15227. lineOffsets.push(i);
  15228. isLineStart = false;
  15229. }
  15230. var ch = text.charAt(i);
  15231. isLineStart = (ch === '\r' || ch === '\n');
  15232. if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
  15233. i++;
  15234. }
  15235. }
  15236. if (isLineStart && text.length > 0) {
  15237. lineOffsets.push(text.length);
  15238. }
  15239. this._lineOffsets = lineOffsets;
  15240. }
  15241. return this._lineOffsets;
  15242. };
  15243. FullTextDocument.prototype.positionAt = function (offset) {
  15244. offset = Math.max(Math.min(offset, this._content.length), 0);
  15245. var lineOffsets = this.getLineOffsets();
  15246. var low = 0, high = lineOffsets.length;
  15247. if (high === 0) {
  15248. return Position.create(0, offset);
  15249. }
  15250. while (low < high) {
  15251. var mid = Math.floor((low + high) / 2);
  15252. if (lineOffsets[mid] > offset) {
  15253. high = mid;
  15254. }
  15255. else {
  15256. low = mid + 1;
  15257. }
  15258. }
  15259. // low is the least x for which the line offset is larger than the current offset
  15260. // or array.length if no line offset is larger than the current offset
  15261. var line = low - 1;
  15262. return Position.create(line, offset - lineOffsets[line]);
  15263. };
  15264. FullTextDocument.prototype.offsetAt = function (position) {
  15265. var lineOffsets = this.getLineOffsets();
  15266. if (position.line >= lineOffsets.length) {
  15267. return this._content.length;
  15268. }
  15269. else if (position.line < 0) {
  15270. return 0;
  15271. }
  15272. var lineOffset = lineOffsets[position.line];
  15273. var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
  15274. return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
  15275. };
  15276. Object.defineProperty(FullTextDocument.prototype, "lineCount", {
  15277. get: function () {
  15278. return this.getLineOffsets().length;
  15279. },
  15280. enumerable: true,
  15281. configurable: true
  15282. });
  15283. return FullTextDocument;
  15284. }());
  15285. var Is;
  15286. (function (Is) {
  15287. var toString = Object.prototype.toString;
  15288. function defined(value) {
  15289. return typeof value !== 'undefined';
  15290. }
  15291. Is.defined = defined;
  15292. function undefined(value) {
  15293. return typeof value === 'undefined';
  15294. }
  15295. Is.undefined = undefined;
  15296. function boolean(value) {
  15297. return value === true || value === false;
  15298. }
  15299. Is.boolean = boolean;
  15300. function string(value) {
  15301. return toString.call(value) === '[object String]';
  15302. }
  15303. Is.string = string;
  15304. function number(value) {
  15305. return toString.call(value) === '[object Number]';
  15306. }
  15307. Is.number = number;
  15308. function func(value) {
  15309. return toString.call(value) === '[object Function]';
  15310. }
  15311. Is.func = func;
  15312. function objectLiteral(value) {
  15313. // Strictly speaking class instances pass this check as well. Since the LSP
  15314. // doesn't use classes we ignore this for now. If we do we need to add something
  15315. // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
  15316. return value !== null && typeof value === 'object';
  15317. }
  15318. Is.objectLiteral = objectLiteral;
  15319. function typedArray(value, check) {
  15320. return Array.isArray(value) && value.every(check);
  15321. }
  15322. Is.typedArray = typedArray;
  15323. })(Is || (Is = {}));
  15324. /***/ }),
  15325. /* 81 */
  15326. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  15327. "use strict";
  15328. __webpack_require__.r(__webpack_exports__);
  15329. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONCompletion", function() { return JSONCompletion; });
  15330. /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82);
  15331. /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(83);
  15332. /* harmony import */ var _utils_json__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(90);
  15333. /* harmony import */ var _utils_strings__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(91);
  15334. /* harmony import */ var _utils_objects__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(88);
  15335. /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(80);
  15336. /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(76);
  15337. /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_6__);
  15338. /*---------------------------------------------------------------------------------------------
  15339. * Copyright (c) Microsoft Corporation. All rights reserved.
  15340. * Licensed under the MIT License. See License.txt in the project root for license information.
  15341. *--------------------------------------------------------------------------------------------*/
  15342. var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_6__["loadMessageBundle"]();
  15343. var JSONCompletion = /** @class */ (function () {
  15344. function JSONCompletion(schemaService, contributions, promiseConstructor, clientCapabilities) {
  15345. if (contributions === void 0) { contributions = []; }
  15346. if (promiseConstructor === void 0) { promiseConstructor = Promise; }
  15347. if (clientCapabilities === void 0) { clientCapabilities = {}; }
  15348. this.schemaService = schemaService;
  15349. this.contributions = contributions;
  15350. this.promiseConstructor = promiseConstructor;
  15351. this.clientCapabilities = clientCapabilities;
  15352. this.templateVarIdCounter = 0;
  15353. }
  15354. JSONCompletion.prototype.doResolve = function (item) {
  15355. for (var i = this.contributions.length - 1; i >= 0; i--) {
  15356. if (this.contributions[i].resolveCompletion) {
  15357. var resolver = this.contributions[i].resolveCompletion(item);
  15358. if (resolver) {
  15359. return resolver;
  15360. }
  15361. }
  15362. }
  15363. return this.promiseConstructor.resolve(item);
  15364. };
  15365. JSONCompletion.prototype.doComplete = function (document, position, doc) {
  15366. var _this = this;
  15367. var result = {
  15368. items: [],
  15369. isIncomplete: false
  15370. };
  15371. var offset = document.offsetAt(position);
  15372. var node = doc.getNodeFromOffset(offset, true);
  15373. if (this.isInComment(document, node ? node.offset : 0, offset)) {
  15374. return Promise.resolve(result);
  15375. }
  15376. var currentWord = this.getCurrentWord(document, offset);
  15377. var overwriteRange = null;
  15378. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  15379. overwriteRange = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["Range"].create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
  15380. }
  15381. else {
  15382. var overwriteStart = offset - currentWord.length;
  15383. if (overwriteStart > 0 && document.getText()[overwriteStart - 1] === '"') {
  15384. overwriteStart--;
  15385. }
  15386. overwriteRange = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["Range"].create(document.positionAt(overwriteStart), position);
  15387. }
  15388. var proposed = {};
  15389. var collector = {
  15390. add: function (suggestion) {
  15391. var existing = proposed[suggestion.label];
  15392. if (!existing) {
  15393. proposed[suggestion.label] = suggestion;
  15394. if (overwriteRange) {
  15395. suggestion.textEdit = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["TextEdit"].replace(overwriteRange, suggestion.insertText);
  15396. }
  15397. result.items.push(suggestion);
  15398. }
  15399. else if (!existing.documentation) {
  15400. existing.documentation = suggestion.documentation;
  15401. }
  15402. },
  15403. setAsIncomplete: function () {
  15404. result.isIncomplete = true;
  15405. },
  15406. error: function (message) {
  15407. console.error(message);
  15408. },
  15409. log: function (message) {
  15410. console.log(message);
  15411. },
  15412. getNumberOfProposals: function () {
  15413. return result.items.length;
  15414. }
  15415. };
  15416. return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
  15417. var collectionPromises = [];
  15418. var addValue = true;
  15419. var currentKey = '';
  15420. var currentProperty = null;
  15421. if (node) {
  15422. if (node.type === 'string') {
  15423. var parent = node.parent;
  15424. if (parent && parent.type === 'property' && parent.keyNode === node) {
  15425. addValue = !parent.valueNode;
  15426. currentProperty = parent;
  15427. currentKey = document.getText().substr(node.offset + 1, node.length - 2);
  15428. if (parent) {
  15429. node = parent.parent;
  15430. }
  15431. }
  15432. }
  15433. }
  15434. // proposals for properties
  15435. if (node && node.type === 'object') {
  15436. // don't suggest keys when the cursor is just before the opening curly brace
  15437. if (node.offset === offset) {
  15438. return result;
  15439. }
  15440. // don't suggest properties that are already present
  15441. var properties = node.properties;
  15442. properties.forEach(function (p) {
  15443. if (!currentProperty || currentProperty !== p) {
  15444. proposed[p.keyNode.value] = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItem"].create('__');
  15445. }
  15446. });
  15447. var separatorAfter_1 = '';
  15448. if (addValue) {
  15449. separatorAfter_1 = _this.evaluateSeparatorAfter(document, document.offsetAt(overwriteRange.end));
  15450. }
  15451. if (schema) {
  15452. // property proposals with schema
  15453. _this.getPropertyCompletions(schema, doc, node, addValue, separatorAfter_1, collector);
  15454. }
  15455. else {
  15456. // property proposals without schema
  15457. _this.getSchemaLessPropertyCompletions(doc, node, currentKey, collector);
  15458. }
  15459. var location_1 = _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodePath"](node);
  15460. _this.contributions.forEach(function (contribution) {
  15461. var collectPromise = contribution.collectPropertyCompletions(document.uri, location_1, currentWord, addValue, separatorAfter_1 === '', collector);
  15462. if (collectPromise) {
  15463. collectionPromises.push(collectPromise);
  15464. }
  15465. });
  15466. if ((!schema && currentWord.length > 0 && document.getText().charAt(offset - currentWord.length - 1) !== '"')) {
  15467. collector.add({
  15468. kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property,
  15469. label: _this.getLabelForValue(currentWord),
  15470. insertText: _this.getInsertTextForProperty(currentWord, null, false, separatorAfter_1),
  15471. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet, documentation: '',
  15472. });
  15473. collector.setAsIncomplete();
  15474. }
  15475. }
  15476. // proposals for values
  15477. var types = {};
  15478. if (schema) {
  15479. // value proposals with schema
  15480. _this.getValueCompletions(schema, doc, node, offset, document, collector, types);
  15481. }
  15482. else {
  15483. // value proposals without schema
  15484. _this.getSchemaLessValueCompletions(doc, node, offset, document, collector);
  15485. }
  15486. if (_this.contributions.length > 0) {
  15487. _this.getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises);
  15488. }
  15489. return _this.promiseConstructor.all(collectionPromises).then(function () {
  15490. if (collector.getNumberOfProposals() === 0) {
  15491. var offsetForSeparator = offset;
  15492. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  15493. offsetForSeparator = node.offset + node.length;
  15494. }
  15495. var separatorAfter = _this.evaluateSeparatorAfter(document, offsetForSeparator);
  15496. _this.addFillerValueCompletions(types, separatorAfter, collector);
  15497. }
  15498. return result;
  15499. });
  15500. });
  15501. };
  15502. JSONCompletion.prototype.getPropertyCompletions = function (schema, doc, node, addValue, separatorAfter, collector) {
  15503. var _this = this;
  15504. var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
  15505. matchingSchemas.forEach(function (s) {
  15506. if (s.node === node && !s.inverted) {
  15507. var schemaProperties_1 = s.schema.properties;
  15508. if (schemaProperties_1) {
  15509. Object.keys(schemaProperties_1).forEach(function (key) {
  15510. var propertySchema = schemaProperties_1[key];
  15511. if (typeof propertySchema === 'object' && !propertySchema.deprecationMessage && !propertySchema.doNotSuggest) {
  15512. var proposal = {
  15513. kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property,
  15514. label: _this.sanitizeLabel(key),
  15515. insertText: _this.getInsertTextForProperty(key, propertySchema, addValue, separatorAfter),
  15516. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
  15517. filterText: _this.getFilterTextForValue(key),
  15518. documentation: _this.fromMarkup(propertySchema.markdownDescription) || propertySchema.description || '',
  15519. };
  15520. if (Object(_utils_strings__WEBPACK_IMPORTED_MODULE_3__["endsWith"])(proposal.insertText, "$1" + separatorAfter)) {
  15521. proposal.command = {
  15522. title: 'Suggest',
  15523. command: 'editor.action.triggerSuggest'
  15524. };
  15525. }
  15526. collector.add(proposal);
  15527. }
  15528. });
  15529. }
  15530. }
  15531. });
  15532. };
  15533. JSONCompletion.prototype.getSchemaLessPropertyCompletions = function (doc, node, currentKey, collector) {
  15534. var _this = this;
  15535. var collectCompletionsForSimilarObject = function (obj) {
  15536. obj.properties.forEach(function (p) {
  15537. var key = p.keyNode.value;
  15538. collector.add({
  15539. kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property,
  15540. label: _this.sanitizeLabel(key),
  15541. insertText: _this.getInsertTextForValue(key, ''),
  15542. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
  15543. filterText: _this.getFilterTextForValue(key),
  15544. documentation: ''
  15545. });
  15546. });
  15547. };
  15548. if (node.parent) {
  15549. if (node.parent.type === 'property') {
  15550. // if the object is a property value, check the tree for other objects that hang under a property of the same name
  15551. var parentKey_1 = node.parent.keyNode.value;
  15552. doc.visit(function (n) {
  15553. if (n.type === 'property' && n !== node.parent && n.keyNode.value === parentKey_1 && n.valueNode && n.valueNode.type === 'object') {
  15554. collectCompletionsForSimilarObject(n.valueNode);
  15555. }
  15556. return true;
  15557. });
  15558. }
  15559. else if (node.parent.type === 'array') {
  15560. // if the object is in an array, use all other array elements as similar objects
  15561. node.parent.items.forEach(function (n) {
  15562. if (n.type === 'object' && n !== node) {
  15563. collectCompletionsForSimilarObject(n);
  15564. }
  15565. });
  15566. }
  15567. }
  15568. else if (node.type === 'object') {
  15569. collector.add({
  15570. kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property,
  15571. label: '$schema',
  15572. insertText: this.getInsertTextForProperty('$schema', null, true, ''),
  15573. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet, documentation: '',
  15574. filterText: this.getFilterTextForValue("$schema")
  15575. });
  15576. }
  15577. };
  15578. JSONCompletion.prototype.getSchemaLessValueCompletions = function (doc, node, offset, document, collector) {
  15579. var _this = this;
  15580. var offsetForSeparator = offset;
  15581. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  15582. offsetForSeparator = node.offset + node.length;
  15583. node = node.parent;
  15584. }
  15585. if (!node) {
  15586. collector.add({
  15587. kind: this.getSuggestionKind('object'),
  15588. label: 'Empty object',
  15589. insertText: this.getInsertTextForValue({}, ''),
  15590. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
  15591. documentation: ''
  15592. });
  15593. collector.add({
  15594. kind: this.getSuggestionKind('array'),
  15595. label: 'Empty array',
  15596. insertText: this.getInsertTextForValue([], ''),
  15597. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
  15598. documentation: ''
  15599. });
  15600. return;
  15601. }
  15602. var separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
  15603. var collectSuggestionsForValues = function (value) {
  15604. if (!_parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["contains"](value.parent, offset, true)) {
  15605. collector.add({
  15606. kind: _this.getSuggestionKind(value.type),
  15607. label: _this.getLabelTextForMatchingNode(value, document),
  15608. insertText: _this.getInsertTextForMatchingNode(value, document, separatorAfter),
  15609. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet, documentation: ''
  15610. });
  15611. }
  15612. if (value.type === 'boolean') {
  15613. _this.addBooleanValueCompletion(!value.value, separatorAfter, collector);
  15614. }
  15615. };
  15616. if (node.type === 'property') {
  15617. if (offset > node.colonOffset) {
  15618. var valueNode = node.valueNode;
  15619. if (valueNode && (offset > (valueNode.offset + valueNode.length) || valueNode.type === 'object' || valueNode.type === 'array')) {
  15620. return;
  15621. }
  15622. // suggest values at the same key
  15623. var parentKey_2 = node.keyNode.value;
  15624. doc.visit(function (n) {
  15625. if (n.type === 'property' && n.keyNode.value === parentKey_2 && n.valueNode) {
  15626. collectSuggestionsForValues(n.valueNode);
  15627. }
  15628. return true;
  15629. });
  15630. if (parentKey_2 === '$schema' && node.parent && !node.parent.parent) {
  15631. this.addDollarSchemaCompletions(separatorAfter, collector);
  15632. }
  15633. }
  15634. }
  15635. if (node.type === 'array') {
  15636. if (node.parent && node.parent.type === 'property') {
  15637. // suggest items of an array at the same key
  15638. var parentKey_3 = node.parent.keyNode.value;
  15639. doc.visit(function (n) {
  15640. if (n.type === 'property' && n.keyNode.value === parentKey_3 && n.valueNode && n.valueNode.type === 'array') {
  15641. n.valueNode.items.forEach(collectSuggestionsForValues);
  15642. }
  15643. return true;
  15644. });
  15645. }
  15646. else {
  15647. // suggest items in the same array
  15648. node.items.forEach(collectSuggestionsForValues);
  15649. }
  15650. }
  15651. };
  15652. JSONCompletion.prototype.getValueCompletions = function (schema, doc, node, offset, document, collector, types) {
  15653. var _this = this;
  15654. var offsetForSeparator = offset;
  15655. var parentKey = null;
  15656. var valueNode = null;
  15657. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  15658. offsetForSeparator = node.offset + node.length;
  15659. valueNode = node;
  15660. node = node.parent;
  15661. }
  15662. if (!node) {
  15663. this.addSchemaValueCompletions(schema.schema, '', collector, types);
  15664. return;
  15665. }
  15666. if ((node.type === 'property') && offset > node.colonOffset) {
  15667. var valueNode_1 = node.valueNode;
  15668. if (valueNode_1 && offset > (valueNode_1.offset + valueNode_1.length)) {
  15669. return; // we are past the value node
  15670. }
  15671. parentKey = node.keyNode.value;
  15672. node = node.parent;
  15673. }
  15674. if (node && (parentKey !== null || node.type === 'array')) {
  15675. var separatorAfter_2 = this.evaluateSeparatorAfter(document, offsetForSeparator);
  15676. var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset, valueNode);
  15677. matchingSchemas.forEach(function (s) {
  15678. if (s.node === node && !s.inverted && s.schema) {
  15679. if (node.type === 'array' && s.schema.items) {
  15680. if (Array.isArray(s.schema.items)) {
  15681. var index = _this.findItemAtOffset(node, document, offset);
  15682. if (index < s.schema.items.length) {
  15683. _this.addSchemaValueCompletions(s.schema.items[index], separatorAfter_2, collector, types);
  15684. }
  15685. }
  15686. else {
  15687. _this.addSchemaValueCompletions(s.schema.items, separatorAfter_2, collector, types);
  15688. }
  15689. }
  15690. if (s.schema.properties) {
  15691. var propertySchema = s.schema.properties[parentKey];
  15692. if (propertySchema) {
  15693. _this.addSchemaValueCompletions(propertySchema, separatorAfter_2, collector, types);
  15694. }
  15695. }
  15696. }
  15697. });
  15698. if (parentKey === '$schema' && !node.parent) {
  15699. this.addDollarSchemaCompletions(separatorAfter_2, collector);
  15700. }
  15701. if (types['boolean']) {
  15702. this.addBooleanValueCompletion(true, separatorAfter_2, collector);
  15703. this.addBooleanValueCompletion(false, separatorAfter_2, collector);
  15704. }
  15705. if (types['null']) {
  15706. this.addNullValueCompletion(separatorAfter_2, collector);
  15707. }
  15708. }
  15709. };
  15710. JSONCompletion.prototype.getContributedValueCompletions = function (doc, node, offset, document, collector, collectionPromises) {
  15711. if (!node) {
  15712. this.contributions.forEach(function (contribution) {
  15713. var collectPromise = contribution.collectDefaultCompletions(document.uri, collector);
  15714. if (collectPromise) {
  15715. collectionPromises.push(collectPromise);
  15716. }
  15717. });
  15718. }
  15719. else {
  15720. if (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null') {
  15721. node = node.parent;
  15722. }
  15723. if ((node.type === 'property') && offset > node.colonOffset) {
  15724. var parentKey_4 = node.keyNode.value;
  15725. var valueNode = node.valueNode;
  15726. if (!valueNode || offset <= (valueNode.offset + valueNode.length)) {
  15727. var location_2 = _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodePath"](node.parent);
  15728. this.contributions.forEach(function (contribution) {
  15729. var collectPromise = contribution.collectValueCompletions(document.uri, location_2, parentKey_4, collector);
  15730. if (collectPromise) {
  15731. collectionPromises.push(collectPromise);
  15732. }
  15733. });
  15734. }
  15735. }
  15736. }
  15737. };
  15738. JSONCompletion.prototype.addSchemaValueCompletions = function (schema, separatorAfter, collector, types) {
  15739. var _this = this;
  15740. if (typeof schema === 'object') {
  15741. this.addEnumValueCompletions(schema, separatorAfter, collector);
  15742. this.addDefaultValueCompletions(schema, separatorAfter, collector);
  15743. this.collectTypes(schema, types);
  15744. if (Array.isArray(schema.allOf)) {
  15745. schema.allOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
  15746. }
  15747. if (Array.isArray(schema.anyOf)) {
  15748. schema.anyOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
  15749. }
  15750. if (Array.isArray(schema.oneOf)) {
  15751. schema.oneOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
  15752. }
  15753. }
  15754. };
  15755. JSONCompletion.prototype.addDefaultValueCompletions = function (schema, separatorAfter, collector, arrayDepth) {
  15756. var _this = this;
  15757. if (arrayDepth === void 0) { arrayDepth = 0; }
  15758. var hasProposals = false;
  15759. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(schema.default)) {
  15760. var type = schema.type;
  15761. var value = schema.default;
  15762. for (var i = arrayDepth; i > 0; i--) {
  15763. value = [value];
  15764. type = 'array';
  15765. }
  15766. collector.add({
  15767. kind: this.getSuggestionKind(type),
  15768. label: this.getLabelForValue(value),
  15769. insertText: this.getInsertTextForValue(value, separatorAfter),
  15770. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
  15771. detail: localize('json.suggest.default', 'Default value')
  15772. });
  15773. hasProposals = true;
  15774. }
  15775. if (Array.isArray(schema.examples)) {
  15776. schema.examples.forEach(function (example) {
  15777. var type = schema.type;
  15778. var value = example;
  15779. for (var i = arrayDepth; i > 0; i--) {
  15780. value = [value];
  15781. type = 'array';
  15782. }
  15783. collector.add({
  15784. kind: _this.getSuggestionKind(type),
  15785. label: _this.getLabelForValue(value),
  15786. insertText: _this.getInsertTextForValue(value, separatorAfter),
  15787. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet
  15788. });
  15789. hasProposals = true;
  15790. });
  15791. }
  15792. if (Array.isArray(schema.defaultSnippets)) {
  15793. schema.defaultSnippets.forEach(function (s) {
  15794. var type = schema.type;
  15795. var value = s.body;
  15796. var label = s.label;
  15797. var insertText;
  15798. var filterText;
  15799. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(value)) {
  15800. var type_1 = schema.type;
  15801. for (var i = arrayDepth; i > 0; i--) {
  15802. value = [value];
  15803. type_1 = 'array';
  15804. }
  15805. insertText = _this.getInsertTextForSnippetValue(value, separatorAfter);
  15806. filterText = _this.getFilterTextForSnippetValue(value);
  15807. label = label || _this.getLabelForSnippetValue(value);
  15808. }
  15809. else if (typeof s.bodyText === 'string') {
  15810. var prefix = '', suffix = '', indent = '';
  15811. for (var i = arrayDepth; i > 0; i--) {
  15812. prefix = prefix + indent + '[\n';
  15813. suffix = suffix + '\n' + indent + ']';
  15814. indent += '\t';
  15815. type = 'array';
  15816. }
  15817. insertText = prefix + indent + s.bodyText.split('\n').join('\n' + indent) + suffix + separatorAfter;
  15818. label = label || _this.sanitizeLabel(insertText),
  15819. filterText = insertText.replace(/[\n]/g, ''); // remove new lines
  15820. }
  15821. collector.add({
  15822. kind: _this.getSuggestionKind(type),
  15823. label: label,
  15824. documentation: _this.fromMarkup(s.markdownDescription) || s.description,
  15825. insertText: insertText,
  15826. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
  15827. filterText: filterText
  15828. });
  15829. hasProposals = true;
  15830. });
  15831. }
  15832. if (!hasProposals && typeof schema.items === 'object' && !Array.isArray(schema.items)) {
  15833. this.addDefaultValueCompletions(schema.items, separatorAfter, collector, arrayDepth + 1);
  15834. }
  15835. };
  15836. JSONCompletion.prototype.addEnumValueCompletions = function (schema, separatorAfter, collector) {
  15837. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(schema.const)) {
  15838. collector.add({
  15839. kind: this.getSuggestionKind(schema.type),
  15840. label: this.getLabelForValue(schema.const),
  15841. insertText: this.getInsertTextForValue(schema.const, separatorAfter),
  15842. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
  15843. documentation: this.fromMarkup(schema.markdownDescription) || schema.description
  15844. });
  15845. }
  15846. if (Array.isArray(schema.enum)) {
  15847. for (var i = 0, length = schema.enum.length; i < length; i++) {
  15848. var enm = schema.enum[i];
  15849. var documentation = this.fromMarkup(schema.markdownDescription) || schema.description;
  15850. if (schema.markdownEnumDescriptions && i < schema.markdownEnumDescriptions.length && this.doesSupportMarkdown()) {
  15851. documentation = this.fromMarkup(schema.markdownEnumDescriptions[i]);
  15852. }
  15853. else if (schema.enumDescriptions && i < schema.enumDescriptions.length) {
  15854. documentation = schema.enumDescriptions[i];
  15855. }
  15856. collector.add({
  15857. kind: this.getSuggestionKind(schema.type),
  15858. label: this.getLabelForValue(enm),
  15859. insertText: this.getInsertTextForValue(enm, separatorAfter),
  15860. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
  15861. documentation: documentation
  15862. });
  15863. }
  15864. }
  15865. };
  15866. JSONCompletion.prototype.collectTypes = function (schema, types) {
  15867. if (Array.isArray(schema.enum) || Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(schema.const)) {
  15868. return;
  15869. }
  15870. var type = schema.type;
  15871. if (Array.isArray(type)) {
  15872. type.forEach(function (t) { return types[t] = true; });
  15873. }
  15874. else {
  15875. types[type] = true;
  15876. }
  15877. };
  15878. JSONCompletion.prototype.addFillerValueCompletions = function (types, separatorAfter, collector) {
  15879. if (types['object']) {
  15880. collector.add({
  15881. kind: this.getSuggestionKind('object'),
  15882. label: '{}',
  15883. insertText: this.getInsertTextForGuessedValue({}, separatorAfter),
  15884. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
  15885. detail: localize('defaults.object', 'New object'),
  15886. documentation: ''
  15887. });
  15888. }
  15889. if (types['array']) {
  15890. collector.add({
  15891. kind: this.getSuggestionKind('array'),
  15892. label: '[]',
  15893. insertText: this.getInsertTextForGuessedValue([], separatorAfter),
  15894. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
  15895. detail: localize('defaults.array', 'New array'),
  15896. documentation: ''
  15897. });
  15898. }
  15899. };
  15900. JSONCompletion.prototype.addBooleanValueCompletion = function (value, separatorAfter, collector) {
  15901. collector.add({
  15902. kind: this.getSuggestionKind('boolean'),
  15903. label: value ? 'true' : 'false',
  15904. insertText: this.getInsertTextForValue(value, separatorAfter),
  15905. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
  15906. documentation: ''
  15907. });
  15908. };
  15909. JSONCompletion.prototype.addNullValueCompletion = function (separatorAfter, collector) {
  15910. collector.add({
  15911. kind: this.getSuggestionKind('null'),
  15912. label: 'null',
  15913. insertText: 'null' + separatorAfter,
  15914. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
  15915. documentation: ''
  15916. });
  15917. };
  15918. JSONCompletion.prototype.addDollarSchemaCompletions = function (separatorAfter, collector) {
  15919. var _this = this;
  15920. var schemaIds = this.schemaService.getRegisteredSchemaIds(function (schema) { return schema === 'http' || schema === 'https'; });
  15921. schemaIds.forEach(function (schemaId) { return collector.add({
  15922. kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Module,
  15923. label: _this.getLabelForValue(schemaId),
  15924. filterText: _this.getFilterTextForValue(schemaId),
  15925. insertText: _this.getInsertTextForValue(schemaId, separatorAfter),
  15926. insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet, documentation: ''
  15927. }); });
  15928. };
  15929. JSONCompletion.prototype.sanitizeLabel = function (label) {
  15930. label = label.replace(/[\n]/g, '↵');
  15931. if (label.length > 57) {
  15932. label = label.substr(0, 57).trim() + '...';
  15933. }
  15934. return label;
  15935. };
  15936. JSONCompletion.prototype.getLabelForValue = function (value) {
  15937. return this.sanitizeLabel(JSON.stringify(value));
  15938. };
  15939. JSONCompletion.prototype.getFilterTextForValue = function (value) {
  15940. return JSON.stringify(value);
  15941. };
  15942. JSONCompletion.prototype.getFilterTextForSnippetValue = function (value) {
  15943. return JSON.stringify(value).replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
  15944. };
  15945. JSONCompletion.prototype.getLabelForSnippetValue = function (value) {
  15946. var label = JSON.stringify(value);
  15947. label = label.replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
  15948. return this.sanitizeLabel(label);
  15949. };
  15950. JSONCompletion.prototype.getInsertTextForPlainText = function (text) {
  15951. return text.replace(/[\\\$\}]/g, '\\$&'); // escape $, \ and }
  15952. };
  15953. JSONCompletion.prototype.getInsertTextForValue = function (value, separatorAfter) {
  15954. var text = JSON.stringify(value, null, '\t');
  15955. if (text === '{}') {
  15956. return '{$1}' + separatorAfter;
  15957. }
  15958. else if (text === '[]') {
  15959. return '[$1]' + separatorAfter;
  15960. }
  15961. return this.getInsertTextForPlainText(text + separatorAfter);
  15962. };
  15963. JSONCompletion.prototype.getInsertTextForSnippetValue = function (value, separatorAfter) {
  15964. var replacer = function (value) {
  15965. if (typeof value === 'string') {
  15966. if (value[0] === '^') {
  15967. return value.substr(1);
  15968. }
  15969. }
  15970. return JSON.stringify(value);
  15971. };
  15972. return Object(_utils_json__WEBPACK_IMPORTED_MODULE_2__["stringifyObject"])(value, '', replacer) + separatorAfter;
  15973. };
  15974. JSONCompletion.prototype.getInsertTextForGuessedValue = function (value, separatorAfter) {
  15975. switch (typeof value) {
  15976. case 'object':
  15977. if (value === null) {
  15978. return '${1:null}' + separatorAfter;
  15979. }
  15980. return this.getInsertTextForValue(value, separatorAfter);
  15981. case 'string':
  15982. var snippetValue = JSON.stringify(value);
  15983. snippetValue = snippetValue.substr(1, snippetValue.length - 2); // remove quotes
  15984. snippetValue = this.getInsertTextForPlainText(snippetValue); // escape \ and }
  15985. return '"${1:' + snippetValue + '}"' + separatorAfter;
  15986. case 'number':
  15987. case 'boolean':
  15988. return '${1:' + JSON.stringify(value) + '}' + separatorAfter;
  15989. }
  15990. return this.getInsertTextForValue(value, separatorAfter);
  15991. };
  15992. JSONCompletion.prototype.getSuggestionKind = function (type) {
  15993. if (Array.isArray(type)) {
  15994. var array = type;
  15995. type = array.length > 0 ? array[0] : null;
  15996. }
  15997. if (!type) {
  15998. return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Value;
  15999. }
  16000. switch (type) {
  16001. case 'string': return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Value;
  16002. case 'object': return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Module;
  16003. case 'property': return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property;
  16004. default: return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Value;
  16005. }
  16006. };
  16007. JSONCompletion.prototype.getLabelTextForMatchingNode = function (node, document) {
  16008. switch (node.type) {
  16009. case 'array':
  16010. return '[]';
  16011. case 'object':
  16012. return '{}';
  16013. default:
  16014. var content = document.getText().substr(node.offset, node.length);
  16015. return content;
  16016. }
  16017. };
  16018. JSONCompletion.prototype.getInsertTextForMatchingNode = function (node, document, separatorAfter) {
  16019. switch (node.type) {
  16020. case 'array':
  16021. return this.getInsertTextForValue([], separatorAfter);
  16022. case 'object':
  16023. return this.getInsertTextForValue({}, separatorAfter);
  16024. default:
  16025. var content = document.getText().substr(node.offset, node.length) + separatorAfter;
  16026. return this.getInsertTextForPlainText(content);
  16027. }
  16028. };
  16029. JSONCompletion.prototype.getInsertTextForProperty = function (key, propertySchema, addValue, separatorAfter) {
  16030. var propertyText = this.getInsertTextForValue(key, '');
  16031. if (!addValue) {
  16032. return propertyText;
  16033. }
  16034. var resultText = propertyText + ': ';
  16035. var value;
  16036. var nValueProposals = 0;
  16037. if (propertySchema) {
  16038. if (Array.isArray(propertySchema.defaultSnippets)) {
  16039. if (propertySchema.defaultSnippets.length === 1) {
  16040. var body = propertySchema.defaultSnippets[0].body;
  16041. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(body)) {
  16042. value = this.getInsertTextForSnippetValue(body, '');
  16043. }
  16044. }
  16045. nValueProposals += propertySchema.defaultSnippets.length;
  16046. }
  16047. if (propertySchema.enum) {
  16048. if (!value && propertySchema.enum.length === 1) {
  16049. value = this.getInsertTextForGuessedValue(propertySchema.enum[0], '');
  16050. }
  16051. nValueProposals += propertySchema.enum.length;
  16052. }
  16053. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(propertySchema.default)) {
  16054. if (!value) {
  16055. value = this.getInsertTextForGuessedValue(propertySchema.default, '');
  16056. }
  16057. nValueProposals++;
  16058. }
  16059. if (nValueProposals === 0) {
  16060. var type = Array.isArray(propertySchema.type) ? propertySchema.type[0] : propertySchema.type;
  16061. if (!type) {
  16062. if (propertySchema.properties) {
  16063. type = 'object';
  16064. }
  16065. else if (propertySchema.items) {
  16066. type = 'array';
  16067. }
  16068. }
  16069. switch (type) {
  16070. case 'boolean':
  16071. value = '$1';
  16072. break;
  16073. case 'string':
  16074. value = '"$1"';
  16075. break;
  16076. case 'object':
  16077. value = '{$1}';
  16078. break;
  16079. case 'array':
  16080. value = '[$1]';
  16081. break;
  16082. case 'number':
  16083. case 'integer':
  16084. value = '${1:0}';
  16085. break;
  16086. case 'null':
  16087. value = '${1:null}';
  16088. break;
  16089. default:
  16090. return propertyText;
  16091. }
  16092. }
  16093. }
  16094. if (!value || nValueProposals > 1) {
  16095. value = '$1';
  16096. }
  16097. return resultText + value + separatorAfter;
  16098. };
  16099. JSONCompletion.prototype.getCurrentWord = function (document, offset) {
  16100. var i = offset - 1;
  16101. var text = document.getText();
  16102. while (i >= 0 && ' \t\n\r\v":{[,]}'.indexOf(text.charAt(i)) === -1) {
  16103. i--;
  16104. }
  16105. return text.substring(i + 1, offset);
  16106. };
  16107. JSONCompletion.prototype.evaluateSeparatorAfter = function (document, offset) {
  16108. var scanner = jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"](document.getText(), true);
  16109. scanner.setPosition(offset);
  16110. var token = scanner.scan();
  16111. switch (token) {
  16112. case 5 /* CommaToken */:
  16113. case 2 /* CloseBraceToken */:
  16114. case 4 /* CloseBracketToken */:
  16115. case 17 /* EOF */:
  16116. return '';
  16117. default:
  16118. return ',';
  16119. }
  16120. };
  16121. JSONCompletion.prototype.findItemAtOffset = function (node, document, offset) {
  16122. var scanner = jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"](document.getText(), true);
  16123. var children = node.items;
  16124. for (var i = children.length - 1; i >= 0; i--) {
  16125. var child = children[i];
  16126. if (offset > child.offset + child.length) {
  16127. scanner.setPosition(child.offset + child.length);
  16128. var token = scanner.scan();
  16129. if (token === 5 /* CommaToken */ && offset >= scanner.getTokenOffset() + scanner.getTokenLength()) {
  16130. return i + 1;
  16131. }
  16132. return i;
  16133. }
  16134. else if (offset >= child.offset) {
  16135. return i;
  16136. }
  16137. }
  16138. return 0;
  16139. };
  16140. JSONCompletion.prototype.isInComment = function (document, start, offset) {
  16141. var scanner = jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"](document.getText(), false);
  16142. scanner.setPosition(start);
  16143. var token = scanner.scan();
  16144. while (token !== 17 /* EOF */ && (scanner.getTokenOffset() + scanner.getTokenLength() < offset)) {
  16145. token = scanner.scan();
  16146. }
  16147. return (token === 12 /* LineCommentTrivia */ || token === 13 /* BlockCommentTrivia */) && scanner.getTokenOffset() <= offset;
  16148. };
  16149. JSONCompletion.prototype.fromMarkup = function (markupString) {
  16150. if (markupString && this.doesSupportMarkdown()) {
  16151. return {
  16152. kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["MarkupKind"].Markdown,
  16153. value: markupString
  16154. };
  16155. }
  16156. return undefined;
  16157. };
  16158. JSONCompletion.prototype.doesSupportMarkdown = function () {
  16159. if (!Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(this.supportsMarkdown)) {
  16160. var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
  16161. this.supportsMarkdown = completion && completion.completionItem && Array.isArray(completion.completionItem.documentationFormat) && completion.completionItem.documentationFormat.indexOf(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["MarkupKind"].Markdown) !== -1;
  16162. }
  16163. return this.supportsMarkdown;
  16164. };
  16165. return JSONCompletion;
  16166. }());
  16167. /***/ }),
  16168. /* 82 */
  16169. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  16170. "use strict";
  16171. __webpack_require__.r(__webpack_exports__);
  16172. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ASTNodeImpl", function() { return ASTNodeImpl; });
  16173. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NullASTNodeImpl", function() { return NullASTNodeImpl; });
  16174. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BooleanASTNodeImpl", function() { return BooleanASTNodeImpl; });
  16175. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrayASTNodeImpl", function() { return ArrayASTNodeImpl; });
  16176. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NumberASTNodeImpl", function() { return NumberASTNodeImpl; });
  16177. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringASTNodeImpl", function() { return StringASTNodeImpl; });
  16178. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PropertyASTNodeImpl", function() { return PropertyASTNodeImpl; });
  16179. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObjectASTNodeImpl", function() { return ObjectASTNodeImpl; });
  16180. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asSchema", function() { return asSchema; });
  16181. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EnumMatch", function() { return EnumMatch; });
  16182. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ValidationResult", function() { return ValidationResult; });
  16183. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "newJSONDocument", function() { return newJSONDocument; });
  16184. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; });
  16185. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; });
  16186. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return contains; });
  16187. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONDocument", function() { return JSONDocument; });
  16188. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
  16189. /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(83);
  16190. /* harmony import */ var _utils_objects__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(88);
  16191. /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(89);
  16192. /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(76);
  16193. /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_3__);
  16194. /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(80);
  16195. /*---------------------------------------------------------------------------------------------
  16196. * Copyright (c) Microsoft Corporation. All rights reserved.
  16197. * Licensed under the MIT License. See License.txt in the project root for license information.
  16198. *--------------------------------------------------------------------------------------------*/
  16199. var __extends = (undefined && undefined.__extends) || (function () {
  16200. var extendStatics = function (d, b) {
  16201. extendStatics = Object.setPrototypeOf ||
  16202. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  16203. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  16204. return extendStatics(d, b);
  16205. };
  16206. return function (d, b) {
  16207. extendStatics(d, b);
  16208. function __() { this.constructor = d; }
  16209. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16210. };
  16211. })();
  16212. var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_3__["loadMessageBundle"]();
  16213. var colorHexPattern = /^#([0-9A-Fa-f]{3,4}|([0-9A-Fa-f]{2}){3,4})$/;
  16214. var emailPattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  16215. var ASTNodeImpl = /** @class */ (function () {
  16216. function ASTNodeImpl(parent, offset, length) {
  16217. this.offset = offset;
  16218. this.length = length;
  16219. this.parent = parent;
  16220. }
  16221. Object.defineProperty(ASTNodeImpl.prototype, "children", {
  16222. get: function () {
  16223. return [];
  16224. },
  16225. enumerable: true,
  16226. configurable: true
  16227. });
  16228. ASTNodeImpl.prototype.toString = function () {
  16229. return 'type: ' + this.type + ' (' + this.offset + '/' + this.length + ')' + (this.parent ? ' parent: {' + this.parent.toString() + '}' : '');
  16230. };
  16231. return ASTNodeImpl;
  16232. }());
  16233. var NullASTNodeImpl = /** @class */ (function (_super) {
  16234. __extends(NullASTNodeImpl, _super);
  16235. function NullASTNodeImpl(parent, offset) {
  16236. var _this = _super.call(this, parent, offset) || this;
  16237. _this.type = 'null';
  16238. _this.value = null;
  16239. return _this;
  16240. }
  16241. return NullASTNodeImpl;
  16242. }(ASTNodeImpl));
  16243. var BooleanASTNodeImpl = /** @class */ (function (_super) {
  16244. __extends(BooleanASTNodeImpl, _super);
  16245. function BooleanASTNodeImpl(parent, boolValue, offset) {
  16246. var _this = _super.call(this, parent, offset) || this;
  16247. _this.type = 'boolean';
  16248. _this.value = boolValue;
  16249. return _this;
  16250. }
  16251. return BooleanASTNodeImpl;
  16252. }(ASTNodeImpl));
  16253. var ArrayASTNodeImpl = /** @class */ (function (_super) {
  16254. __extends(ArrayASTNodeImpl, _super);
  16255. function ArrayASTNodeImpl(parent, offset) {
  16256. var _this = _super.call(this, parent, offset) || this;
  16257. _this.type = 'array';
  16258. _this.items = [];
  16259. return _this;
  16260. }
  16261. Object.defineProperty(ArrayASTNodeImpl.prototype, "children", {
  16262. get: function () {
  16263. return this.items;
  16264. },
  16265. enumerable: true,
  16266. configurable: true
  16267. });
  16268. return ArrayASTNodeImpl;
  16269. }(ASTNodeImpl));
  16270. var NumberASTNodeImpl = /** @class */ (function (_super) {
  16271. __extends(NumberASTNodeImpl, _super);
  16272. function NumberASTNodeImpl(parent, offset) {
  16273. var _this = _super.call(this, parent, offset) || this;
  16274. _this.type = 'number';
  16275. _this.isInteger = true;
  16276. _this.value = Number.NaN;
  16277. return _this;
  16278. }
  16279. return NumberASTNodeImpl;
  16280. }(ASTNodeImpl));
  16281. var StringASTNodeImpl = /** @class */ (function (_super) {
  16282. __extends(StringASTNodeImpl, _super);
  16283. function StringASTNodeImpl(parent, offset, length) {
  16284. var _this = _super.call(this, parent, offset, length) || this;
  16285. _this.type = 'string';
  16286. _this.value = '';
  16287. return _this;
  16288. }
  16289. return StringASTNodeImpl;
  16290. }(ASTNodeImpl));
  16291. var PropertyASTNodeImpl = /** @class */ (function (_super) {
  16292. __extends(PropertyASTNodeImpl, _super);
  16293. function PropertyASTNodeImpl(parent, offset) {
  16294. var _this = _super.call(this, parent, offset) || this;
  16295. _this.type = 'property';
  16296. _this.colonOffset = -1;
  16297. return _this;
  16298. }
  16299. Object.defineProperty(PropertyASTNodeImpl.prototype, "children", {
  16300. get: function () {
  16301. return this.valueNode ? [this.keyNode, this.valueNode] : [this.keyNode];
  16302. },
  16303. enumerable: true,
  16304. configurable: true
  16305. });
  16306. return PropertyASTNodeImpl;
  16307. }(ASTNodeImpl));
  16308. var ObjectASTNodeImpl = /** @class */ (function (_super) {
  16309. __extends(ObjectASTNodeImpl, _super);
  16310. function ObjectASTNodeImpl(parent, offset) {
  16311. var _this = _super.call(this, parent, offset) || this;
  16312. _this.type = 'object';
  16313. _this.properties = [];
  16314. return _this;
  16315. }
  16316. Object.defineProperty(ObjectASTNodeImpl.prototype, "children", {
  16317. get: function () {
  16318. return this.properties;
  16319. },
  16320. enumerable: true,
  16321. configurable: true
  16322. });
  16323. return ObjectASTNodeImpl;
  16324. }(ASTNodeImpl));
  16325. function asSchema(schema) {
  16326. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(schema)) {
  16327. return schema ? {} : { "not": {} };
  16328. }
  16329. return schema;
  16330. }
  16331. var EnumMatch;
  16332. (function (EnumMatch) {
  16333. EnumMatch[EnumMatch["Key"] = 0] = "Key";
  16334. EnumMatch[EnumMatch["Enum"] = 1] = "Enum";
  16335. })(EnumMatch || (EnumMatch = {}));
  16336. var SchemaCollector = /** @class */ (function () {
  16337. function SchemaCollector(focusOffset, exclude) {
  16338. if (focusOffset === void 0) { focusOffset = -1; }
  16339. if (exclude === void 0) { exclude = null; }
  16340. this.focusOffset = focusOffset;
  16341. this.exclude = exclude;
  16342. this.schemas = [];
  16343. }
  16344. SchemaCollector.prototype.add = function (schema) {
  16345. this.schemas.push(schema);
  16346. };
  16347. SchemaCollector.prototype.merge = function (other) {
  16348. var _a;
  16349. (_a = this.schemas).push.apply(_a, other.schemas);
  16350. };
  16351. SchemaCollector.prototype.include = function (node) {
  16352. return (this.focusOffset === -1 || contains(node, this.focusOffset)) && (node !== this.exclude);
  16353. };
  16354. SchemaCollector.prototype.newSub = function () {
  16355. return new SchemaCollector(-1, this.exclude);
  16356. };
  16357. return SchemaCollector;
  16358. }());
  16359. var NoOpSchemaCollector = /** @class */ (function () {
  16360. function NoOpSchemaCollector() {
  16361. }
  16362. Object.defineProperty(NoOpSchemaCollector.prototype, "schemas", {
  16363. get: function () { return []; },
  16364. enumerable: true,
  16365. configurable: true
  16366. });
  16367. NoOpSchemaCollector.prototype.add = function (schema) { };
  16368. NoOpSchemaCollector.prototype.merge = function (other) { };
  16369. NoOpSchemaCollector.prototype.include = function (node) { return true; };
  16370. NoOpSchemaCollector.prototype.newSub = function () { return this; };
  16371. NoOpSchemaCollector.instance = new NoOpSchemaCollector();
  16372. return NoOpSchemaCollector;
  16373. }());
  16374. var ValidationResult = /** @class */ (function () {
  16375. function ValidationResult() {
  16376. this.problems = [];
  16377. this.propertiesMatches = 0;
  16378. this.propertiesValueMatches = 0;
  16379. this.primaryValueMatches = 0;
  16380. this.enumValueMatch = false;
  16381. this.enumValues = null;
  16382. }
  16383. ValidationResult.prototype.hasProblems = function () {
  16384. return !!this.problems.length;
  16385. };
  16386. ValidationResult.prototype.mergeAll = function (validationResults) {
  16387. for (var _i = 0, validationResults_1 = validationResults; _i < validationResults_1.length; _i++) {
  16388. var validationResult = validationResults_1[_i];
  16389. this.merge(validationResult);
  16390. }
  16391. };
  16392. ValidationResult.prototype.merge = function (validationResult) {
  16393. this.problems = this.problems.concat(validationResult.problems);
  16394. };
  16395. ValidationResult.prototype.mergeEnumValues = function (validationResult) {
  16396. if (!this.enumValueMatch && !validationResult.enumValueMatch && this.enumValues && validationResult.enumValues) {
  16397. this.enumValues = this.enumValues.concat(validationResult.enumValues);
  16398. for (var _i = 0, _a = this.problems; _i < _a.length; _i++) {
  16399. var error = _a[_i];
  16400. if (error.code === _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].EnumValueMismatch) {
  16401. error.message = localize('enumWarning', 'Value is not accepted. Valid values: {0}.', this.enumValues.map(function (v) { return JSON.stringify(v); }).join(', '));
  16402. }
  16403. }
  16404. }
  16405. };
  16406. ValidationResult.prototype.mergePropertyMatch = function (propertyValidationResult) {
  16407. this.merge(propertyValidationResult);
  16408. this.propertiesMatches++;
  16409. if (propertyValidationResult.enumValueMatch || !propertyValidationResult.hasProblems() && propertyValidationResult.propertiesMatches) {
  16410. this.propertiesValueMatches++;
  16411. }
  16412. if (propertyValidationResult.enumValueMatch && propertyValidationResult.enumValues && propertyValidationResult.enumValues.length === 1) {
  16413. this.primaryValueMatches++;
  16414. }
  16415. };
  16416. ValidationResult.prototype.compare = function (other) {
  16417. var hasProblems = this.hasProblems();
  16418. if (hasProblems !== other.hasProblems()) {
  16419. return hasProblems ? -1 : 1;
  16420. }
  16421. if (this.enumValueMatch !== other.enumValueMatch) {
  16422. return other.enumValueMatch ? -1 : 1;
  16423. }
  16424. if (this.primaryValueMatches !== other.primaryValueMatches) {
  16425. return this.primaryValueMatches - other.primaryValueMatches;
  16426. }
  16427. if (this.propertiesValueMatches !== other.propertiesValueMatches) {
  16428. return this.propertiesValueMatches - other.propertiesValueMatches;
  16429. }
  16430. return this.propertiesMatches - other.propertiesMatches;
  16431. };
  16432. return ValidationResult;
  16433. }());
  16434. function newJSONDocument(root, diagnostics) {
  16435. if (diagnostics === void 0) { diagnostics = []; }
  16436. return new JSONDocument(root, diagnostics, []);
  16437. }
  16438. function getNodeValue(node) {
  16439. return jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](node);
  16440. }
  16441. function getNodePath(node) {
  16442. return jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["getNodePath"](node);
  16443. }
  16444. function contains(node, offset, includeRightBound) {
  16445. if (includeRightBound === void 0) { includeRightBound = false; }
  16446. return offset >= node.offset && offset < (node.offset + node.length) || includeRightBound && offset === (node.offset + node.length);
  16447. }
  16448. var JSONDocument = /** @class */ (function () {
  16449. function JSONDocument(root, syntaxErrors, comments) {
  16450. if (syntaxErrors === void 0) { syntaxErrors = []; }
  16451. if (comments === void 0) { comments = []; }
  16452. this.root = root;
  16453. this.syntaxErrors = syntaxErrors;
  16454. this.comments = comments;
  16455. }
  16456. JSONDocument.prototype.getNodeFromOffset = function (offset, includeRightBound) {
  16457. if (includeRightBound === void 0) { includeRightBound = false; }
  16458. if (this.root) {
  16459. return jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["findNodeAtOffset"](this.root, offset, includeRightBound);
  16460. }
  16461. return void 0;
  16462. };
  16463. JSONDocument.prototype.visit = function (visitor) {
  16464. if (this.root) {
  16465. var doVisit_1 = function (node) {
  16466. var ctn = visitor(node);
  16467. var children = node.children;
  16468. if (Array.isArray(children)) {
  16469. for (var i = 0; i < children.length && ctn; i++) {
  16470. ctn = doVisit_1(children[i]);
  16471. }
  16472. }
  16473. return ctn;
  16474. };
  16475. doVisit_1(this.root);
  16476. }
  16477. };
  16478. JSONDocument.prototype.validate = function (textDocument, schema) {
  16479. if (this.root && schema) {
  16480. var validationResult = new ValidationResult();
  16481. validate(this.root, schema, validationResult, NoOpSchemaCollector.instance);
  16482. return validationResult.problems.map(function (p) {
  16483. var range = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["Range"].create(textDocument.positionAt(p.location.offset), textDocument.positionAt(p.location.offset + p.location.length));
  16484. return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["Diagnostic"].create(range, p.message, p.severity, p.code);
  16485. });
  16486. }
  16487. return null;
  16488. };
  16489. JSONDocument.prototype.getMatchingSchemas = function (schema, focusOffset, exclude) {
  16490. if (focusOffset === void 0) { focusOffset = -1; }
  16491. if (exclude === void 0) { exclude = null; }
  16492. var matchingSchemas = new SchemaCollector(focusOffset, exclude);
  16493. if (this.root && schema) {
  16494. validate(this.root, schema, new ValidationResult(), matchingSchemas);
  16495. }
  16496. return matchingSchemas.schemas;
  16497. };
  16498. return JSONDocument;
  16499. }());
  16500. function validate(node, schema, validationResult, matchingSchemas) {
  16501. if (!node || !matchingSchemas.include(node)) {
  16502. return;
  16503. }
  16504. switch (node.type) {
  16505. case 'object':
  16506. _validateObjectNode(node, schema, validationResult, matchingSchemas);
  16507. break;
  16508. case 'array':
  16509. _validateArrayNode(node, schema, validationResult, matchingSchemas);
  16510. break;
  16511. case 'string':
  16512. _validateStringNode(node, schema, validationResult, matchingSchemas);
  16513. break;
  16514. case 'number':
  16515. _validateNumberNode(node, schema, validationResult, matchingSchemas);
  16516. break;
  16517. case 'property':
  16518. return validate(node.valueNode, schema, validationResult, matchingSchemas);
  16519. }
  16520. _validateNode();
  16521. matchingSchemas.add({ node: node, schema: schema });
  16522. function _validateNode() {
  16523. function matchesType(type) {
  16524. return node.type === type || (type === 'integer' && node.type === 'number' && node.isInteger);
  16525. }
  16526. if (Array.isArray(schema.type)) {
  16527. if (!schema.type.some(matchesType)) {
  16528. validationResult.problems.push({
  16529. location: { offset: node.offset, length: node.length },
  16530. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16531. message: schema.errorMessage || localize('typeArrayMismatchWarning', 'Incorrect type. Expected one of {0}.', schema.type.join(', '))
  16532. });
  16533. }
  16534. }
  16535. else if (schema.type) {
  16536. if (!matchesType(schema.type)) {
  16537. validationResult.problems.push({
  16538. location: { offset: node.offset, length: node.length },
  16539. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16540. message: schema.errorMessage || localize('typeMismatchWarning', 'Incorrect type. Expected "{0}".', schema.type)
  16541. });
  16542. }
  16543. }
  16544. if (Array.isArray(schema.allOf)) {
  16545. for (var _i = 0, _a = schema.allOf; _i < _a.length; _i++) {
  16546. var subSchemaRef = _a[_i];
  16547. validate(node, asSchema(subSchemaRef), validationResult, matchingSchemas);
  16548. }
  16549. }
  16550. var notSchema = asSchema(schema.not);
  16551. if (notSchema) {
  16552. var subValidationResult = new ValidationResult();
  16553. var subMatchingSchemas = matchingSchemas.newSub();
  16554. validate(node, notSchema, subValidationResult, subMatchingSchemas);
  16555. if (!subValidationResult.hasProblems()) {
  16556. validationResult.problems.push({
  16557. location: { offset: node.offset, length: node.length },
  16558. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16559. message: localize('notSchemaWarning', "Matches a schema that is not allowed.")
  16560. });
  16561. }
  16562. for (var _b = 0, _c = subMatchingSchemas.schemas; _b < _c.length; _b++) {
  16563. var ms = _c[_b];
  16564. ms.inverted = !ms.inverted;
  16565. matchingSchemas.add(ms);
  16566. }
  16567. }
  16568. var testAlternatives = function (alternatives, maxOneMatch) {
  16569. var matches = [];
  16570. // remember the best match that is used for error messages
  16571. var bestMatch = null;
  16572. for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
  16573. var subSchemaRef = alternatives_1[_i];
  16574. var subSchema = asSchema(subSchemaRef);
  16575. var subValidationResult = new ValidationResult();
  16576. var subMatchingSchemas = matchingSchemas.newSub();
  16577. validate(node, subSchema, subValidationResult, subMatchingSchemas);
  16578. if (!subValidationResult.hasProblems()) {
  16579. matches.push(subSchema);
  16580. }
  16581. if (!bestMatch) {
  16582. bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
  16583. }
  16584. else {
  16585. if (!maxOneMatch && !subValidationResult.hasProblems() && !bestMatch.validationResult.hasProblems()) {
  16586. // no errors, both are equally good matches
  16587. bestMatch.matchingSchemas.merge(subMatchingSchemas);
  16588. bestMatch.validationResult.propertiesMatches += subValidationResult.propertiesMatches;
  16589. bestMatch.validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
  16590. }
  16591. else {
  16592. var compareResult = subValidationResult.compare(bestMatch.validationResult);
  16593. if (compareResult > 0) {
  16594. // our node is the best matching so far
  16595. bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
  16596. }
  16597. else if (compareResult === 0) {
  16598. // there's already a best matching but we are as good
  16599. bestMatch.matchingSchemas.merge(subMatchingSchemas);
  16600. bestMatch.validationResult.mergeEnumValues(subValidationResult);
  16601. }
  16602. }
  16603. }
  16604. }
  16605. if (matches.length > 1 && maxOneMatch) {
  16606. validationResult.problems.push({
  16607. location: { offset: node.offset, length: 1 },
  16608. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16609. message: localize('oneOfWarning', "Matches multiple schemas when only one must validate.")
  16610. });
  16611. }
  16612. if (bestMatch !== null) {
  16613. validationResult.merge(bestMatch.validationResult);
  16614. validationResult.propertiesMatches += bestMatch.validationResult.propertiesMatches;
  16615. validationResult.propertiesValueMatches += bestMatch.validationResult.propertiesValueMatches;
  16616. matchingSchemas.merge(bestMatch.matchingSchemas);
  16617. }
  16618. return matches.length;
  16619. };
  16620. if (Array.isArray(schema.anyOf)) {
  16621. testAlternatives(schema.anyOf, false);
  16622. }
  16623. if (Array.isArray(schema.oneOf)) {
  16624. testAlternatives(schema.oneOf, true);
  16625. }
  16626. var testBranch = function (schema) {
  16627. var subValidationResult = new ValidationResult();
  16628. var subMatchingSchemas = matchingSchemas.newSub();
  16629. validate(node, asSchema(schema), subValidationResult, subMatchingSchemas);
  16630. validationResult.merge(subValidationResult);
  16631. validationResult.propertiesMatches += subValidationResult.propertiesMatches;
  16632. validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
  16633. matchingSchemas.merge(subMatchingSchemas);
  16634. };
  16635. var testCondition = function (ifSchema, thenSchema, elseSchema) {
  16636. var subSchema = asSchema(ifSchema);
  16637. var subValidationResult = new ValidationResult();
  16638. var subMatchingSchemas = matchingSchemas.newSub();
  16639. validate(node, subSchema, subValidationResult, subMatchingSchemas);
  16640. matchingSchemas.merge(subMatchingSchemas);
  16641. if (!subValidationResult.hasProblems()) {
  16642. if (thenSchema) {
  16643. testBranch(thenSchema);
  16644. }
  16645. }
  16646. else if (elseSchema) {
  16647. testBranch(elseSchema);
  16648. }
  16649. };
  16650. var ifSchema = asSchema(schema.if);
  16651. if (ifSchema) {
  16652. testCondition(ifSchema, asSchema(schema.then), asSchema(schema.else));
  16653. }
  16654. if (Array.isArray(schema.enum)) {
  16655. var val = getNodeValue(node);
  16656. var enumValueMatch = false;
  16657. for (var _d = 0, _e = schema.enum; _d < _e.length; _d++) {
  16658. var e = _e[_d];
  16659. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["equals"])(val, e)) {
  16660. enumValueMatch = true;
  16661. break;
  16662. }
  16663. }
  16664. validationResult.enumValues = schema.enum;
  16665. validationResult.enumValueMatch = enumValueMatch;
  16666. if (!enumValueMatch) {
  16667. validationResult.problems.push({
  16668. location: { offset: node.offset, length: node.length },
  16669. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16670. code: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].EnumValueMismatch,
  16671. message: schema.errorMessage || localize('enumWarning', 'Value is not accepted. Valid values: {0}.', schema.enum.map(function (v) { return JSON.stringify(v); }).join(', '))
  16672. });
  16673. }
  16674. }
  16675. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isDefined"])(schema.const)) {
  16676. var val = getNodeValue(node);
  16677. if (!Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["equals"])(val, schema.const)) {
  16678. validationResult.problems.push({
  16679. location: { offset: node.offset, length: node.length },
  16680. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16681. code: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].EnumValueMismatch,
  16682. message: schema.errorMessage || localize('constWarning', 'Value must be {0}.', JSON.stringify(schema.const))
  16683. });
  16684. validationResult.enumValueMatch = false;
  16685. }
  16686. else {
  16687. validationResult.enumValueMatch = true;
  16688. }
  16689. validationResult.enumValues = [schema.const];
  16690. }
  16691. if (schema.deprecationMessage && node.parent) {
  16692. validationResult.problems.push({
  16693. location: { offset: node.parent.offset, length: node.parent.length },
  16694. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16695. message: schema.deprecationMessage
  16696. });
  16697. }
  16698. }
  16699. function _validateNumberNode(node, schema, validationResult, matchingSchemas) {
  16700. var val = node.value;
  16701. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.multipleOf)) {
  16702. if (val % schema.multipleOf !== 0) {
  16703. validationResult.problems.push({
  16704. location: { offset: node.offset, length: node.length },
  16705. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16706. message: localize('multipleOfWarning', 'Value is not divisible by {0}.', schema.multipleOf)
  16707. });
  16708. }
  16709. }
  16710. function getExclusiveLimit(limit, exclusive) {
  16711. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(exclusive)) {
  16712. return exclusive;
  16713. }
  16714. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(exclusive) && exclusive) {
  16715. return limit;
  16716. }
  16717. return void 0;
  16718. }
  16719. function getLimit(limit, exclusive) {
  16720. if (!Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(exclusive) || !exclusive) {
  16721. return limit;
  16722. }
  16723. return void 0;
  16724. }
  16725. var exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum);
  16726. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(exclusiveMinimum) && val <= exclusiveMinimum) {
  16727. validationResult.problems.push({
  16728. location: { offset: node.offset, length: node.length },
  16729. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16730. message: localize('exclusiveMinimumWarning', 'Value is below the exclusive minimum of {0}.', exclusiveMinimum)
  16731. });
  16732. }
  16733. var exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum);
  16734. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(exclusiveMaximum) && val >= exclusiveMaximum) {
  16735. validationResult.problems.push({
  16736. location: { offset: node.offset, length: node.length },
  16737. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16738. message: localize('exclusiveMaximumWarning', 'Value is above the exclusive maximum of {0}.', exclusiveMaximum)
  16739. });
  16740. }
  16741. var minimum = getLimit(schema.minimum, schema.exclusiveMinimum);
  16742. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(minimum) && val < minimum) {
  16743. validationResult.problems.push({
  16744. location: { offset: node.offset, length: node.length },
  16745. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16746. message: localize('minimumWarning', 'Value is below the minimum of {0}.', minimum)
  16747. });
  16748. }
  16749. var maximum = getLimit(schema.maximum, schema.exclusiveMaximum);
  16750. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(maximum) && val > maximum) {
  16751. validationResult.problems.push({
  16752. location: { offset: node.offset, length: node.length },
  16753. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16754. message: localize('maximumWarning', 'Value is above the maximum of {0}.', maximum)
  16755. });
  16756. }
  16757. }
  16758. function _validateStringNode(node, schema, validationResult, matchingSchemas) {
  16759. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.minLength) && node.value.length < schema.minLength) {
  16760. validationResult.problems.push({
  16761. location: { offset: node.offset, length: node.length },
  16762. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16763. message: localize('minLengthWarning', 'String is shorter than the minimum length of {0}.', schema.minLength)
  16764. });
  16765. }
  16766. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.maxLength) && node.value.length > schema.maxLength) {
  16767. validationResult.problems.push({
  16768. location: { offset: node.offset, length: node.length },
  16769. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16770. message: localize('maxLengthWarning', 'String is longer than the maximum length of {0}.', schema.maxLength)
  16771. });
  16772. }
  16773. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isString"])(schema.pattern)) {
  16774. var regex = new RegExp(schema.pattern);
  16775. if (!regex.test(node.value)) {
  16776. validationResult.problems.push({
  16777. location: { offset: node.offset, length: node.length },
  16778. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16779. message: schema.patternErrorMessage || schema.errorMessage || localize('patternWarning', 'String does not match the pattern of "{0}".', schema.pattern)
  16780. });
  16781. }
  16782. }
  16783. if (schema.format) {
  16784. switch (schema.format) {
  16785. case 'uri':
  16786. case 'uri-reference':
  16787. {
  16788. var errorMessage = void 0;
  16789. if (!node.value) {
  16790. errorMessage = localize('uriEmpty', 'URI expected.');
  16791. }
  16792. else {
  16793. var match = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(node.value);
  16794. if (!match) {
  16795. errorMessage = localize('uriMissing', 'URI is expected.');
  16796. }
  16797. else if (!match[2] && schema.format === 'uri') {
  16798. errorMessage = localize('uriSchemeMissing', 'URI with a scheme is expected.');
  16799. }
  16800. }
  16801. if (errorMessage) {
  16802. validationResult.problems.push({
  16803. location: { offset: node.offset, length: node.length },
  16804. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16805. message: schema.patternErrorMessage || schema.errorMessage || localize('uriFormatWarning', 'String is not a URI: {0}', errorMessage)
  16806. });
  16807. }
  16808. }
  16809. break;
  16810. case 'email':
  16811. {
  16812. if (!node.value.match(emailPattern)) {
  16813. validationResult.problems.push({
  16814. location: { offset: node.offset, length: node.length },
  16815. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16816. message: schema.patternErrorMessage || schema.errorMessage || localize('emailFormatWarning', 'String is not an e-mail address.')
  16817. });
  16818. }
  16819. }
  16820. break;
  16821. case 'color-hex':
  16822. {
  16823. if (!node.value.match(colorHexPattern)) {
  16824. validationResult.problems.push({
  16825. location: { offset: node.offset, length: node.length },
  16826. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16827. message: schema.patternErrorMessage || schema.errorMessage || localize('colorHexFormatWarning', 'Invalid color format. Use #RGB, #RGBA, #RRGGBB or #RRGGBBAA.')
  16828. });
  16829. }
  16830. }
  16831. break;
  16832. default:
  16833. }
  16834. }
  16835. }
  16836. function _validateArrayNode(node, schema, validationResult, matchingSchemas) {
  16837. if (Array.isArray(schema.items)) {
  16838. var subSchemas = schema.items;
  16839. for (var index = 0; index < subSchemas.length; index++) {
  16840. var subSchemaRef = subSchemas[index];
  16841. var subSchema = asSchema(subSchemaRef);
  16842. var itemValidationResult = new ValidationResult();
  16843. var item = node.items[index];
  16844. if (item) {
  16845. validate(item, subSchema, itemValidationResult, matchingSchemas);
  16846. validationResult.mergePropertyMatch(itemValidationResult);
  16847. }
  16848. else if (node.items.length >= subSchemas.length) {
  16849. validationResult.propertiesValueMatches++;
  16850. }
  16851. }
  16852. if (node.items.length > subSchemas.length) {
  16853. if (typeof schema.additionalItems === 'object') {
  16854. for (var i = subSchemas.length; i < node.items.length; i++) {
  16855. var itemValidationResult = new ValidationResult();
  16856. validate(node.items[i], schema.additionalItems, itemValidationResult, matchingSchemas);
  16857. validationResult.mergePropertyMatch(itemValidationResult);
  16858. }
  16859. }
  16860. else if (schema.additionalItems === false) {
  16861. validationResult.problems.push({
  16862. location: { offset: node.offset, length: node.length },
  16863. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16864. message: localize('additionalItemsWarning', 'Array has too many items according to schema. Expected {0} or fewer.', subSchemas.length)
  16865. });
  16866. }
  16867. }
  16868. }
  16869. else {
  16870. var itemSchema = asSchema(schema.items);
  16871. if (itemSchema) {
  16872. for (var _i = 0, _a = node.items; _i < _a.length; _i++) {
  16873. var item = _a[_i];
  16874. var itemValidationResult = new ValidationResult();
  16875. validate(item, itemSchema, itemValidationResult, matchingSchemas);
  16876. validationResult.mergePropertyMatch(itemValidationResult);
  16877. }
  16878. }
  16879. }
  16880. var containsSchema = asSchema(schema.contains);
  16881. if (containsSchema) {
  16882. var doesContain = node.items.some(function (item) {
  16883. var itemValidationResult = new ValidationResult();
  16884. validate(item, containsSchema, itemValidationResult, NoOpSchemaCollector.instance);
  16885. return !itemValidationResult.hasProblems();
  16886. });
  16887. if (!doesContain) {
  16888. validationResult.problems.push({
  16889. location: { offset: node.offset, length: node.length },
  16890. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16891. message: schema.errorMessage || localize('requiredItemMissingWarning', 'Array does not contain required item.')
  16892. });
  16893. }
  16894. }
  16895. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.minItems) && node.items.length < schema.minItems) {
  16896. validationResult.problems.push({
  16897. location: { offset: node.offset, length: node.length },
  16898. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16899. message: localize('minItemsWarning', 'Array has too few items. Expected {0} or more.', schema.minItems)
  16900. });
  16901. }
  16902. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.maxItems) && node.items.length > schema.maxItems) {
  16903. validationResult.problems.push({
  16904. location: { offset: node.offset, length: node.length },
  16905. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16906. message: localize('maxItemsWarning', 'Array has too many items. Expected {0} or fewer.', schema.maxItems)
  16907. });
  16908. }
  16909. if (schema.uniqueItems === true) {
  16910. var values_1 = getNodeValue(node);
  16911. var duplicates = values_1.some(function (value, index) {
  16912. return index !== values_1.lastIndexOf(value);
  16913. });
  16914. if (duplicates) {
  16915. validationResult.problems.push({
  16916. location: { offset: node.offset, length: node.length },
  16917. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16918. message: localize('uniqueItemsWarning', 'Array has duplicate items.')
  16919. });
  16920. }
  16921. }
  16922. }
  16923. function _validateObjectNode(node, schema, validationResult, matchingSchemas) {
  16924. var seenKeys = Object.create(null);
  16925. var unprocessedProperties = [];
  16926. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
  16927. var propertyNode = _a[_i];
  16928. var key = propertyNode.keyNode.value;
  16929. seenKeys[key] = propertyNode.valueNode;
  16930. unprocessedProperties.push(key);
  16931. }
  16932. if (Array.isArray(schema.required)) {
  16933. for (var _b = 0, _c = schema.required; _b < _c.length; _b++) {
  16934. var propertyName = _c[_b];
  16935. if (!seenKeys[propertyName]) {
  16936. var keyNode = node.parent && node.parent.type === 'property' && node.parent.keyNode;
  16937. var location = keyNode ? { offset: keyNode.offset, length: keyNode.length } : { offset: node.offset, length: 1 };
  16938. validationResult.problems.push({
  16939. location: location,
  16940. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16941. message: localize('MissingRequiredPropWarning', 'Missing property "{0}".', propertyName)
  16942. });
  16943. }
  16944. }
  16945. }
  16946. var propertyProcessed = function (prop) {
  16947. var index = unprocessedProperties.indexOf(prop);
  16948. while (index >= 0) {
  16949. unprocessedProperties.splice(index, 1);
  16950. index = unprocessedProperties.indexOf(prop);
  16951. }
  16952. };
  16953. if (schema.properties) {
  16954. for (var _d = 0, _e = Object.keys(schema.properties); _d < _e.length; _d++) {
  16955. var propertyName = _e[_d];
  16956. propertyProcessed(propertyName);
  16957. var propertySchema = schema.properties[propertyName];
  16958. var child = seenKeys[propertyName];
  16959. if (child) {
  16960. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(propertySchema)) {
  16961. if (!propertySchema) {
  16962. var propertyNode = child.parent;
  16963. validationResult.problems.push({
  16964. location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
  16965. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16966. message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
  16967. });
  16968. }
  16969. else {
  16970. validationResult.propertiesMatches++;
  16971. validationResult.propertiesValueMatches++;
  16972. }
  16973. }
  16974. else {
  16975. var propertyValidationResult = new ValidationResult();
  16976. validate(child, propertySchema, propertyValidationResult, matchingSchemas);
  16977. validationResult.mergePropertyMatch(propertyValidationResult);
  16978. }
  16979. }
  16980. }
  16981. }
  16982. if (schema.patternProperties) {
  16983. for (var _f = 0, _g = Object.keys(schema.patternProperties); _f < _g.length; _f++) {
  16984. var propertyPattern = _g[_f];
  16985. var regex = new RegExp(propertyPattern);
  16986. for (var _h = 0, _j = unprocessedProperties.slice(0); _h < _j.length; _h++) {
  16987. var propertyName = _j[_h];
  16988. if (regex.test(propertyName)) {
  16989. propertyProcessed(propertyName);
  16990. var child = seenKeys[propertyName];
  16991. if (child) {
  16992. var propertySchema = schema.patternProperties[propertyPattern];
  16993. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(propertySchema)) {
  16994. if (!propertySchema) {
  16995. var propertyNode = child.parent;
  16996. validationResult.problems.push({
  16997. location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
  16998. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  16999. message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
  17000. });
  17001. }
  17002. else {
  17003. validationResult.propertiesMatches++;
  17004. validationResult.propertiesValueMatches++;
  17005. }
  17006. }
  17007. else {
  17008. var propertyValidationResult = new ValidationResult();
  17009. validate(child, propertySchema, propertyValidationResult, matchingSchemas);
  17010. validationResult.mergePropertyMatch(propertyValidationResult);
  17011. }
  17012. }
  17013. }
  17014. }
  17015. }
  17016. }
  17017. if (typeof schema.additionalProperties === 'object') {
  17018. for (var _k = 0, unprocessedProperties_1 = unprocessedProperties; _k < unprocessedProperties_1.length; _k++) {
  17019. var propertyName = unprocessedProperties_1[_k];
  17020. var child = seenKeys[propertyName];
  17021. if (child) {
  17022. var propertyValidationResult = new ValidationResult();
  17023. validate(child, schema.additionalProperties, propertyValidationResult, matchingSchemas);
  17024. validationResult.mergePropertyMatch(propertyValidationResult);
  17025. }
  17026. }
  17027. }
  17028. else if (schema.additionalProperties === false) {
  17029. if (unprocessedProperties.length > 0) {
  17030. for (var _l = 0, unprocessedProperties_2 = unprocessedProperties; _l < unprocessedProperties_2.length; _l++) {
  17031. var propertyName = unprocessedProperties_2[_l];
  17032. var child = seenKeys[propertyName];
  17033. if (child) {
  17034. var propertyNode = child.parent;
  17035. validationResult.problems.push({
  17036. location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
  17037. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  17038. message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
  17039. });
  17040. }
  17041. }
  17042. }
  17043. }
  17044. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.maxProperties)) {
  17045. if (node.properties.length > schema.maxProperties) {
  17046. validationResult.problems.push({
  17047. location: { offset: node.offset, length: node.length },
  17048. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  17049. message: localize('MaxPropWarning', 'Object has more properties than limit of {0}.', schema.maxProperties)
  17050. });
  17051. }
  17052. }
  17053. if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.minProperties)) {
  17054. if (node.properties.length < schema.minProperties) {
  17055. validationResult.problems.push({
  17056. location: { offset: node.offset, length: node.length },
  17057. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  17058. message: localize('MinPropWarning', 'Object has fewer properties than the required number of {0}', schema.minProperties)
  17059. });
  17060. }
  17061. }
  17062. if (schema.dependencies) {
  17063. for (var _m = 0, _o = Object.keys(schema.dependencies); _m < _o.length; _m++) {
  17064. var key = _o[_m];
  17065. var prop = seenKeys[key];
  17066. if (prop) {
  17067. var propertyDep = schema.dependencies[key];
  17068. if (Array.isArray(propertyDep)) {
  17069. for (var _p = 0, propertyDep_1 = propertyDep; _p < propertyDep_1.length; _p++) {
  17070. var requiredProp = propertyDep_1[_p];
  17071. if (!seenKeys[requiredProp]) {
  17072. validationResult.problems.push({
  17073. location: { offset: node.offset, length: node.length },
  17074. severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
  17075. message: localize('RequiredDependentPropWarning', 'Object is missing property {0} required by property {1}.', requiredProp, key)
  17076. });
  17077. }
  17078. else {
  17079. validationResult.propertiesValueMatches++;
  17080. }
  17081. }
  17082. }
  17083. else {
  17084. var propertySchema = asSchema(propertyDep);
  17085. if (propertySchema) {
  17086. var propertyValidationResult = new ValidationResult();
  17087. validate(node, propertySchema, propertyValidationResult, matchingSchemas);
  17088. validationResult.mergePropertyMatch(propertyValidationResult);
  17089. }
  17090. }
  17091. }
  17092. }
  17093. }
  17094. var propertyNames = asSchema(schema.propertyNames);
  17095. if (propertyNames) {
  17096. for (var _q = 0, _r = node.properties; _q < _r.length; _q++) {
  17097. var f = _r[_q];
  17098. var key = f.keyNode;
  17099. if (key) {
  17100. validate(key, propertyNames, validationResult, NoOpSchemaCollector.instance);
  17101. }
  17102. }
  17103. }
  17104. }
  17105. }
  17106. function parse(textDocument, config) {
  17107. var problems = [];
  17108. var lastProblemOffset = -1;
  17109. var text = textDocument.getText();
  17110. var scanner = jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["createScanner"](text, false);
  17111. var commentRanges = config && config.collectComments ? [] : void 0;
  17112. function _scanNext() {
  17113. while (true) {
  17114. var token_1 = scanner.scan();
  17115. _checkScanError();
  17116. switch (token_1) {
  17117. case 12 /* LineCommentTrivia */:
  17118. case 13 /* BlockCommentTrivia */:
  17119. if (Array.isArray(commentRanges)) {
  17120. commentRanges.push(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["Range"].create(textDocument.positionAt(scanner.getTokenOffset()), textDocument.positionAt(scanner.getTokenOffset() + scanner.getTokenLength())));
  17121. }
  17122. break;
  17123. case 15 /* Trivia */:
  17124. case 14 /* LineBreakTrivia */:
  17125. break;
  17126. default:
  17127. return token_1;
  17128. }
  17129. }
  17130. }
  17131. function _accept(token) {
  17132. if (scanner.getToken() === token) {
  17133. _scanNext();
  17134. return true;
  17135. }
  17136. return false;
  17137. }
  17138. function _errorAtRange(message, code, startOffset, endOffset, severity) {
  17139. if (severity === void 0) { severity = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Error; }
  17140. if (problems.length === 0 || startOffset !== lastProblemOffset) {
  17141. var range = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["Range"].create(textDocument.positionAt(startOffset), textDocument.positionAt(endOffset));
  17142. problems.push(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["Diagnostic"].create(range, message, severity, code, textDocument.languageId));
  17143. lastProblemOffset = startOffset;
  17144. }
  17145. }
  17146. function _error(message, code, node, skipUntilAfter, skipUntil) {
  17147. if (node === void 0) { node = null; }
  17148. if (skipUntilAfter === void 0) { skipUntilAfter = []; }
  17149. if (skipUntil === void 0) { skipUntil = []; }
  17150. var start = scanner.getTokenOffset();
  17151. var end = scanner.getTokenOffset() + scanner.getTokenLength();
  17152. if (start === end && start > 0) {
  17153. start--;
  17154. while (start > 0 && /\s/.test(text.charAt(start))) {
  17155. start--;
  17156. }
  17157. end = start + 1;
  17158. }
  17159. _errorAtRange(message, code, start, end);
  17160. if (node) {
  17161. _finalize(node, false);
  17162. }
  17163. if (skipUntilAfter.length + skipUntil.length > 0) {
  17164. var token_2 = scanner.getToken();
  17165. while (token_2 !== 17 /* EOF */) {
  17166. if (skipUntilAfter.indexOf(token_2) !== -1) {
  17167. _scanNext();
  17168. break;
  17169. }
  17170. else if (skipUntil.indexOf(token_2) !== -1) {
  17171. break;
  17172. }
  17173. token_2 = _scanNext();
  17174. }
  17175. }
  17176. return node;
  17177. }
  17178. function _checkScanError() {
  17179. switch (scanner.getTokenError()) {
  17180. case 4 /* InvalidUnicode */:
  17181. _error(localize('InvalidUnicode', 'Invalid unicode sequence in string.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].InvalidUnicode);
  17182. return true;
  17183. case 5 /* InvalidEscapeCharacter */:
  17184. _error(localize('InvalidEscapeCharacter', 'Invalid escape character in string.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].InvalidEscapeCharacter);
  17185. return true;
  17186. case 3 /* UnexpectedEndOfNumber */:
  17187. _error(localize('UnexpectedEndOfNumber', 'Unexpected end of number.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].UnexpectedEndOfNumber);
  17188. return true;
  17189. case 1 /* UnexpectedEndOfComment */:
  17190. _error(localize('UnexpectedEndOfComment', 'Unexpected end of comment.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].UnexpectedEndOfComment);
  17191. return true;
  17192. case 2 /* UnexpectedEndOfString */:
  17193. _error(localize('UnexpectedEndOfString', 'Unexpected end of string.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].UnexpectedEndOfString);
  17194. return true;
  17195. case 6 /* InvalidCharacter */:
  17196. _error(localize('InvalidCharacter', 'Invalid characters in string. Control characters must be escaped.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].InvalidCharacter);
  17197. return true;
  17198. }
  17199. return false;
  17200. }
  17201. function _finalize(node, scanNext) {
  17202. node.length = scanner.getTokenOffset() + scanner.getTokenLength() - node.offset;
  17203. if (scanNext) {
  17204. _scanNext();
  17205. }
  17206. return node;
  17207. }
  17208. function _parseArray(parent) {
  17209. if (scanner.getToken() !== 3 /* OpenBracketToken */) {
  17210. return null;
  17211. }
  17212. var node = new ArrayASTNodeImpl(parent, scanner.getTokenOffset());
  17213. _scanNext(); // consume OpenBracketToken
  17214. var count = 0;
  17215. var needsComma = false;
  17216. while (scanner.getToken() !== 4 /* CloseBracketToken */ && scanner.getToken() !== 17 /* EOF */) {
  17217. if (scanner.getToken() === 5 /* CommaToken */) {
  17218. if (!needsComma) {
  17219. _error(localize('ValueExpected', 'Value expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].ValueExpected);
  17220. }
  17221. var commaOffset = scanner.getTokenOffset();
  17222. _scanNext(); // consume comma
  17223. if (scanner.getToken() === 4 /* CloseBracketToken */) {
  17224. if (needsComma) {
  17225. _errorAtRange(localize('TrailingComma', 'Trailing comma'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].TrailingComma, commaOffset, commaOffset + 1);
  17226. }
  17227. continue;
  17228. }
  17229. }
  17230. else if (needsComma) {
  17231. _error(localize('ExpectedComma', 'Expected comma'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommaExpected);
  17232. }
  17233. var item = _parseValue(node, count++);
  17234. if (!item) {
  17235. _error(localize('PropertyExpected', 'Value expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].ValueExpected, null, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
  17236. }
  17237. else {
  17238. node.items.push(item);
  17239. }
  17240. needsComma = true;
  17241. }
  17242. if (scanner.getToken() !== 4 /* CloseBracketToken */) {
  17243. return _error(localize('ExpectedCloseBracket', 'Expected comma or closing bracket'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommaOrCloseBacketExpected, node);
  17244. }
  17245. return _finalize(node, true);
  17246. }
  17247. function _parseProperty(parent, keysSeen) {
  17248. var node = new PropertyASTNodeImpl(parent, scanner.getTokenOffset());
  17249. var key = _parseString(node);
  17250. if (!key) {
  17251. if (scanner.getToken() === 16 /* Unknown */) {
  17252. // give a more helpful error message
  17253. _error(localize('DoubleQuotesExpected', 'Property keys must be doublequoted'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined);
  17254. var keyNode = new StringASTNodeImpl(node, scanner.getTokenOffset(), scanner.getTokenLength());
  17255. keyNode.value = scanner.getTokenValue();
  17256. key = keyNode;
  17257. _scanNext(); // consume Unknown
  17258. }
  17259. else {
  17260. return null;
  17261. }
  17262. }
  17263. node.keyNode = key;
  17264. var seen = keysSeen[key.value];
  17265. if (seen) {
  17266. _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].DuplicateKey, node.keyNode.offset, node.keyNode.offset + node.keyNode.length, vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning);
  17267. if (typeof seen === 'object') {
  17268. _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].DuplicateKey, seen.keyNode.offset, seen.keyNode.offset + seen.keyNode.length, vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning);
  17269. }
  17270. keysSeen[key.value] = true; // if the same key is duplicate again, avoid duplicate error reporting
  17271. }
  17272. else {
  17273. keysSeen[key.value] = node;
  17274. }
  17275. if (scanner.getToken() === 6 /* ColonToken */) {
  17276. node.colonOffset = scanner.getTokenOffset();
  17277. _scanNext(); // consume ColonToken
  17278. }
  17279. else {
  17280. _error(localize('ColonExpected', 'Colon expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].ColonExpected);
  17281. if (scanner.getToken() === 10 /* StringLiteral */ && textDocument.positionAt(key.offset + key.length).line < textDocument.positionAt(scanner.getTokenOffset()).line) {
  17282. node.length = key.length;
  17283. return node;
  17284. }
  17285. }
  17286. var value = _parseValue(node, key.value);
  17287. if (!value) {
  17288. return _error(localize('ValueExpected', 'Value expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].ValueExpected, node, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  17289. }
  17290. node.valueNode = value;
  17291. node.length = value.offset + value.length - node.offset;
  17292. return node;
  17293. }
  17294. function _parseObject(parent) {
  17295. if (scanner.getToken() !== 1 /* OpenBraceToken */) {
  17296. return null;
  17297. }
  17298. var node = new ObjectASTNodeImpl(parent, scanner.getTokenOffset());
  17299. var keysSeen = Object.create(null);
  17300. _scanNext(); // consume OpenBraceToken
  17301. var needsComma = false;
  17302. while (scanner.getToken() !== 2 /* CloseBraceToken */ && scanner.getToken() !== 17 /* EOF */) {
  17303. if (scanner.getToken() === 5 /* CommaToken */) {
  17304. if (!needsComma) {
  17305. _error(localize('PropertyExpected', 'Property expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].PropertyExpected);
  17306. }
  17307. var commaOffset = scanner.getTokenOffset();
  17308. _scanNext(); // consume comma
  17309. if (scanner.getToken() === 2 /* CloseBraceToken */) {
  17310. if (needsComma) {
  17311. _errorAtRange(localize('TrailingComma', 'Trailing comma'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].TrailingComma, commaOffset, commaOffset + 1);
  17312. }
  17313. continue;
  17314. }
  17315. }
  17316. else if (needsComma) {
  17317. _error(localize('ExpectedComma', 'Expected comma'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommaExpected);
  17318. }
  17319. var property = _parseProperty(node, keysSeen);
  17320. if (!property) {
  17321. _error(localize('PropertyExpected', 'Property expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].PropertyExpected, null, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  17322. }
  17323. else {
  17324. node.properties.push(property);
  17325. }
  17326. needsComma = true;
  17327. }
  17328. if (scanner.getToken() !== 2 /* CloseBraceToken */) {
  17329. return _error(localize('ExpectedCloseBrace', 'Expected comma or closing brace'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommaOrCloseBraceExpected, node);
  17330. }
  17331. return _finalize(node, true);
  17332. }
  17333. function _parseString(parent) {
  17334. if (scanner.getToken() !== 10 /* StringLiteral */) {
  17335. return null;
  17336. }
  17337. var node = new StringASTNodeImpl(parent, scanner.getTokenOffset());
  17338. node.value = scanner.getTokenValue();
  17339. return _finalize(node, true);
  17340. }
  17341. function _parseNumber(parent) {
  17342. if (scanner.getToken() !== 11 /* NumericLiteral */) {
  17343. return null;
  17344. }
  17345. var node = new NumberASTNodeImpl(parent, scanner.getTokenOffset());
  17346. if (scanner.getTokenError() === 0 /* None */) {
  17347. var tokenValue = scanner.getTokenValue();
  17348. try {
  17349. var numberValue = JSON.parse(tokenValue);
  17350. if (!Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(numberValue)) {
  17351. return _error(localize('InvalidNumberFormat', 'Invalid number format.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined, node);
  17352. }
  17353. node.value = numberValue;
  17354. }
  17355. catch (e) {
  17356. return _error(localize('InvalidNumberFormat', 'Invalid number format.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined, node);
  17357. }
  17358. node.isInteger = tokenValue.indexOf('.') === -1;
  17359. }
  17360. return _finalize(node, true);
  17361. }
  17362. function _parseLiteral(parent) {
  17363. var node;
  17364. switch (scanner.getToken()) {
  17365. case 7 /* NullKeyword */:
  17366. return _finalize(new NullASTNodeImpl(parent, scanner.getTokenOffset()), true);
  17367. case 8 /* TrueKeyword */:
  17368. return _finalize(new BooleanASTNodeImpl(parent, true, scanner.getTokenOffset()), true);
  17369. case 9 /* FalseKeyword */:
  17370. return _finalize(new BooleanASTNodeImpl(parent, false, scanner.getTokenOffset()), true);
  17371. default:
  17372. return null;
  17373. }
  17374. }
  17375. function _parseValue(parent, name) {
  17376. return _parseArray(parent) || _parseObject(parent) || _parseString(parent) || _parseNumber(parent) || _parseLiteral(parent);
  17377. }
  17378. var _root = null;
  17379. var token = _scanNext();
  17380. if (token !== 17 /* EOF */) {
  17381. _root = _parseValue(null, null);
  17382. if (!_root) {
  17383. _error(localize('Invalid symbol', 'Expected a JSON object, array or literal.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined);
  17384. }
  17385. else if (scanner.getToken() !== 17 /* EOF */) {
  17386. _error(localize('End of file expected', 'End of file expected.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined);
  17387. }
  17388. }
  17389. return new JSONDocument(_root, problems, commentRanges);
  17390. }
  17391. /***/ }),
  17392. /* 83 */
  17393. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  17394. "use strict";
  17395. __webpack_require__.r(__webpack_exports__);
  17396. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createScanner", function() { return createScanner; });
  17397. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocation", function() { return getLocation; });
  17398. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
  17399. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTree", function() { return parseTree; });
  17400. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtLocation", function() { return findNodeAtLocation; });
  17401. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtOffset", function() { return findNodeAtOffset; });
  17402. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; });
  17403. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; });
  17404. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "visit", function() { return visit; });
  17405. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripComments", function() { return stripComments; });
  17406. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "printParseErrorCode", function() { return printParseErrorCode; });
  17407. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; });
  17408. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "modify", function() { return modify; });
  17409. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEdits", function() { return applyEdits; });
  17410. /* harmony import */ var _impl_format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(84);
  17411. /* harmony import */ var _impl_edit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(86);
  17412. /* harmony import */ var _impl_scanner__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(85);
  17413. /* harmony import */ var _impl_parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(87);
  17414. /*---------------------------------------------------------------------------------------------
  17415. * Copyright (c) Microsoft Corporation. All rights reserved.
  17416. * Licensed under the MIT License. See License.txt in the project root for license information.
  17417. *--------------------------------------------------------------------------------------------*/
  17418. /**
  17419. * Creates a JSON scanner on the given text.
  17420. * If ignoreTrivia is set, whitespaces or comments are ignored.
  17421. */
  17422. var createScanner = _impl_scanner__WEBPACK_IMPORTED_MODULE_2__["createScanner"];
  17423. /**
  17424. * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
  17425. */
  17426. var getLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getLocation"];
  17427. /**
  17428. * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
  17429. * Therefore, always check the errors list to find out if the input was valid.
  17430. */
  17431. var parse = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["parse"];
  17432. /**
  17433. * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
  17434. */
  17435. var parseTree = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["parseTree"];
  17436. /**
  17437. * Finds the node at the given path in a JSON DOM.
  17438. */
  17439. var findNodeAtLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["findNodeAtLocation"];
  17440. /**
  17441. * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
  17442. */
  17443. var findNodeAtOffset = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["findNodeAtOffset"];
  17444. /**
  17445. * Gets the JSON path of the given JSON DOM node
  17446. */
  17447. var getNodePath = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getNodePath"];
  17448. /**
  17449. * Evaluates the JavaScript object of the given JSON DOM node
  17450. */
  17451. var getNodeValue = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getNodeValue"];
  17452. /**
  17453. * Parses the given text and invokes the visitor functions for each object, array and literal reached.
  17454. */
  17455. var visit = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["visit"];
  17456. /**
  17457. * Takes JSON with JavaScript-style comments and remove
  17458. * them. Optionally replaces every none-newline character
  17459. * of comments with a replaceCharacter
  17460. */
  17461. var stripComments = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["stripComments"];
  17462. function printParseErrorCode(code) {
  17463. switch (code) {
  17464. case 1 /* InvalidSymbol */: return 'InvalidSymbol';
  17465. case 2 /* InvalidNumberFormat */: return 'InvalidNumberFormat';
  17466. case 3 /* PropertyNameExpected */: return 'PropertyNameExpected';
  17467. case 4 /* ValueExpected */: return 'ValueExpected';
  17468. case 5 /* ColonExpected */: return 'ColonExpected';
  17469. case 6 /* CommaExpected */: return 'CommaExpected';
  17470. case 7 /* CloseBraceExpected */: return 'CloseBraceExpected';
  17471. case 8 /* CloseBracketExpected */: return 'CloseBracketExpected';
  17472. case 9 /* EndOfFileExpected */: return 'EndOfFileExpected';
  17473. case 10 /* InvalidCommentToken */: return 'InvalidCommentToken';
  17474. case 11 /* UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';
  17475. case 12 /* UnexpectedEndOfString */: return 'UnexpectedEndOfString';
  17476. case 13 /* UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';
  17477. case 14 /* InvalidUnicode */: return 'InvalidUnicode';
  17478. case 15 /* InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';
  17479. case 16 /* InvalidCharacter */: return 'InvalidCharacter';
  17480. }
  17481. return '<unknown ParseErrorCode>';
  17482. }
  17483. /**
  17484. * Computes the edits needed to format a JSON document.
  17485. *
  17486. * @param documentText The input text
  17487. * @param range The range to format or `undefined` to format the full content
  17488. * @param options The formatting options
  17489. * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
  17490. * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
  17491. * text in the original document. However, multiple edits can have
  17492. * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
  17493. * To apply edits to an input, you can use `applyEdits`.
  17494. */
  17495. function format(documentText, range, options) {
  17496. return _impl_format__WEBPACK_IMPORTED_MODULE_0__["format"](documentText, range, options);
  17497. }
  17498. /**
  17499. * Computes the edits needed to modify a value in the JSON document.
  17500. *
  17501. * @param documentText The input text
  17502. * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
  17503. * If the path points to an non-existing property or item, it will be created.
  17504. * @param value The new value for the specified property or item. If the value is undefined,
  17505. * the property or item will be removed.
  17506. * @param options Options
  17507. * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
  17508. * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
  17509. * text in the original document. However, multiple edits can have
  17510. * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
  17511. * To apply edits to an input, you can use `applyEdits`.
  17512. */
  17513. function modify(text, path, value, options) {
  17514. return _impl_edit__WEBPACK_IMPORTED_MODULE_1__["setProperty"](text, path, value, options.formattingOptions, options.getInsertionIndex);
  17515. }
  17516. /**
  17517. * Applies edits to a input string.
  17518. */
  17519. function applyEdits(text, edits) {
  17520. for (var i = edits.length - 1; i >= 0; i--) {
  17521. text = _impl_edit__WEBPACK_IMPORTED_MODULE_1__["applyEdit"](text, edits[i]);
  17522. }
  17523. return text;
  17524. }
  17525. //# sourceMappingURL=main.js.map
  17526. /***/ }),
  17527. /* 84 */
  17528. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  17529. "use strict";
  17530. __webpack_require__.r(__webpack_exports__);
  17531. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; });
  17532. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isEOL", function() { return isEOL; });
  17533. /* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85);
  17534. /*---------------------------------------------------------------------------------------------
  17535. * Copyright (c) Microsoft Corporation. All rights reserved.
  17536. * Licensed under the MIT License. See License.txt in the project root for license information.
  17537. *--------------------------------------------------------------------------------------------*/
  17538. function format(documentText, range, options) {
  17539. var initialIndentLevel;
  17540. var formatText;
  17541. var formatTextStart;
  17542. var rangeStart;
  17543. var rangeEnd;
  17544. if (range) {
  17545. rangeStart = range.offset;
  17546. rangeEnd = rangeStart + range.length;
  17547. formatTextStart = rangeStart;
  17548. while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
  17549. formatTextStart--;
  17550. }
  17551. var endOffset = rangeEnd;
  17552. while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
  17553. endOffset++;
  17554. }
  17555. formatText = documentText.substring(formatTextStart, endOffset);
  17556. initialIndentLevel = computeIndentLevel(formatText, options);
  17557. }
  17558. else {
  17559. formatText = documentText;
  17560. initialIndentLevel = 0;
  17561. formatTextStart = 0;
  17562. rangeStart = 0;
  17563. rangeEnd = documentText.length;
  17564. }
  17565. var eol = getEOL(options, documentText);
  17566. var lineBreak = false;
  17567. var indentLevel = 0;
  17568. var indentValue;
  17569. if (options.insertSpaces) {
  17570. indentValue = repeat(' ', options.tabSize || 4);
  17571. }
  17572. else {
  17573. indentValue = '\t';
  17574. }
  17575. var scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(formatText, false);
  17576. var hasError = false;
  17577. function newLineAndIndent() {
  17578. return eol + repeat(indentValue, initialIndentLevel + indentLevel);
  17579. }
  17580. function scanNext() {
  17581. var token = scanner.scan();
  17582. lineBreak = false;
  17583. while (token === 15 /* Trivia */ || token === 14 /* LineBreakTrivia */) {
  17584. lineBreak = lineBreak || (token === 14 /* LineBreakTrivia */);
  17585. token = scanner.scan();
  17586. }
  17587. hasError = token === 16 /* Unknown */ || scanner.getTokenError() !== 0 /* None */;
  17588. return token;
  17589. }
  17590. var editOperations = [];
  17591. function addEdit(text, startOffset, endOffset) {
  17592. if (!hasError && startOffset < rangeEnd && endOffset > rangeStart && documentText.substring(startOffset, endOffset) !== text) {
  17593. editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
  17594. }
  17595. }
  17596. var firstToken = scanNext();
  17597. if (firstToken !== 17 /* EOF */) {
  17598. var firstTokenStart = scanner.getTokenOffset() + formatTextStart;
  17599. var initialIndent = repeat(indentValue, initialIndentLevel);
  17600. addEdit(initialIndent, formatTextStart, firstTokenStart);
  17601. }
  17602. while (firstToken !== 17 /* EOF */) {
  17603. var firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
  17604. var secondToken = scanNext();
  17605. var replaceContent = '';
  17606. while (!lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
  17607. // comments on the same line: keep them on the same line, but ignore them otherwise
  17608. var commentTokenStart = scanner.getTokenOffset() + formatTextStart;
  17609. addEdit(' ', firstTokenEnd, commentTokenStart);
  17610. firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
  17611. replaceContent = secondToken === 12 /* LineCommentTrivia */ ? newLineAndIndent() : '';
  17612. secondToken = scanNext();
  17613. }
  17614. if (secondToken === 2 /* CloseBraceToken */) {
  17615. if (firstToken !== 1 /* OpenBraceToken */) {
  17616. indentLevel--;
  17617. replaceContent = newLineAndIndent();
  17618. }
  17619. }
  17620. else if (secondToken === 4 /* CloseBracketToken */) {
  17621. if (firstToken !== 3 /* OpenBracketToken */) {
  17622. indentLevel--;
  17623. replaceContent = newLineAndIndent();
  17624. }
  17625. }
  17626. else {
  17627. switch (firstToken) {
  17628. case 3 /* OpenBracketToken */:
  17629. case 1 /* OpenBraceToken */:
  17630. indentLevel++;
  17631. replaceContent = newLineAndIndent();
  17632. break;
  17633. case 5 /* CommaToken */:
  17634. case 12 /* LineCommentTrivia */:
  17635. replaceContent = newLineAndIndent();
  17636. break;
  17637. case 13 /* BlockCommentTrivia */:
  17638. if (lineBreak) {
  17639. replaceContent = newLineAndIndent();
  17640. }
  17641. else {
  17642. // symbol following comment on the same line: keep on same line, separate with ' '
  17643. replaceContent = ' ';
  17644. }
  17645. break;
  17646. case 6 /* ColonToken */:
  17647. replaceContent = ' ';
  17648. break;
  17649. case 10 /* StringLiteral */:
  17650. if (secondToken === 6 /* ColonToken */) {
  17651. replaceContent = '';
  17652. break;
  17653. }
  17654. // fall through
  17655. case 7 /* NullKeyword */:
  17656. case 8 /* TrueKeyword */:
  17657. case 9 /* FalseKeyword */:
  17658. case 11 /* NumericLiteral */:
  17659. case 2 /* CloseBraceToken */:
  17660. case 4 /* CloseBracketToken */:
  17661. if (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */) {
  17662. replaceContent = ' ';
  17663. }
  17664. else if (secondToken !== 5 /* CommaToken */ && secondToken !== 17 /* EOF */) {
  17665. hasError = true;
  17666. }
  17667. break;
  17668. case 16 /* Unknown */:
  17669. hasError = true;
  17670. break;
  17671. }
  17672. if (lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
  17673. replaceContent = newLineAndIndent();
  17674. }
  17675. }
  17676. var secondTokenStart = scanner.getTokenOffset() + formatTextStart;
  17677. addEdit(replaceContent, firstTokenEnd, secondTokenStart);
  17678. firstToken = secondToken;
  17679. }
  17680. return editOperations;
  17681. }
  17682. function repeat(s, count) {
  17683. var result = '';
  17684. for (var i = 0; i < count; i++) {
  17685. result += s;
  17686. }
  17687. return result;
  17688. }
  17689. function computeIndentLevel(content, options) {
  17690. var i = 0;
  17691. var nChars = 0;
  17692. var tabSize = options.tabSize || 4;
  17693. while (i < content.length) {
  17694. var ch = content.charAt(i);
  17695. if (ch === ' ') {
  17696. nChars++;
  17697. }
  17698. else if (ch === '\t') {
  17699. nChars += tabSize;
  17700. }
  17701. else {
  17702. break;
  17703. }
  17704. i++;
  17705. }
  17706. return Math.floor(nChars / tabSize);
  17707. }
  17708. function getEOL(options, text) {
  17709. for (var i = 0; i < text.length; i++) {
  17710. var ch = text.charAt(i);
  17711. if (ch === '\r') {
  17712. if (i + 1 < text.length && text.charAt(i + 1) === '\n') {
  17713. return '\r\n';
  17714. }
  17715. return '\r';
  17716. }
  17717. else if (ch === '\n') {
  17718. return '\n';
  17719. }
  17720. }
  17721. return (options && options.eol) || '\n';
  17722. }
  17723. function isEOL(text, offset) {
  17724. return '\r\n'.indexOf(text.charAt(offset)) !== -1;
  17725. }
  17726. //# sourceMappingURL=format.js.map
  17727. /***/ }),
  17728. /* 85 */
  17729. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  17730. "use strict";
  17731. __webpack_require__.r(__webpack_exports__);
  17732. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createScanner", function() { return createScanner; });
  17733. /*---------------------------------------------------------------------------------------------
  17734. * Copyright (c) Microsoft Corporation. All rights reserved.
  17735. * Licensed under the MIT License. See License.txt in the project root for license information.
  17736. *--------------------------------------------------------------------------------------------*/
  17737. /**
  17738. * Creates a JSON scanner on the given text.
  17739. * If ignoreTrivia is set, whitespaces or comments are ignored.
  17740. */
  17741. function createScanner(text, ignoreTrivia) {
  17742. if (ignoreTrivia === void 0) { ignoreTrivia = false; }
  17743. var pos = 0, len = text.length, value = '', tokenOffset = 0, token = 16 /* Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* None */;
  17744. function scanHexDigits(count, exact) {
  17745. var digits = 0;
  17746. var value = 0;
  17747. while (digits < count || !exact) {
  17748. var ch = text.charCodeAt(pos);
  17749. if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
  17750. value = value * 16 + ch - 48 /* _0 */;
  17751. }
  17752. else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
  17753. value = value * 16 + ch - 65 /* A */ + 10;
  17754. }
  17755. else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
  17756. value = value * 16 + ch - 97 /* a */ + 10;
  17757. }
  17758. else {
  17759. break;
  17760. }
  17761. pos++;
  17762. digits++;
  17763. }
  17764. if (digits < count) {
  17765. value = -1;
  17766. }
  17767. return value;
  17768. }
  17769. function setPosition(newPosition) {
  17770. pos = newPosition;
  17771. value = '';
  17772. tokenOffset = 0;
  17773. token = 16 /* Unknown */;
  17774. scanError = 0 /* None */;
  17775. }
  17776. function scanNumber() {
  17777. var start = pos;
  17778. if (text.charCodeAt(pos) === 48 /* _0 */) {
  17779. pos++;
  17780. }
  17781. else {
  17782. pos++;
  17783. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  17784. pos++;
  17785. }
  17786. }
  17787. if (pos < text.length && text.charCodeAt(pos) === 46 /* dot */) {
  17788. pos++;
  17789. if (pos < text.length && isDigit(text.charCodeAt(pos))) {
  17790. pos++;
  17791. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  17792. pos++;
  17793. }
  17794. }
  17795. else {
  17796. scanError = 3 /* UnexpectedEndOfNumber */;
  17797. return text.substring(start, pos);
  17798. }
  17799. }
  17800. var end = pos;
  17801. if (pos < text.length && (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */)) {
  17802. pos++;
  17803. if (pos < text.length && text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) {
  17804. pos++;
  17805. }
  17806. if (pos < text.length && isDigit(text.charCodeAt(pos))) {
  17807. pos++;
  17808. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  17809. pos++;
  17810. }
  17811. end = pos;
  17812. }
  17813. else {
  17814. scanError = 3 /* UnexpectedEndOfNumber */;
  17815. }
  17816. }
  17817. return text.substring(start, end);
  17818. }
  17819. function scanString() {
  17820. var result = '', start = pos;
  17821. while (true) {
  17822. if (pos >= len) {
  17823. result += text.substring(start, pos);
  17824. scanError = 2 /* UnexpectedEndOfString */;
  17825. break;
  17826. }
  17827. var ch = text.charCodeAt(pos);
  17828. if (ch === 34 /* doubleQuote */) {
  17829. result += text.substring(start, pos);
  17830. pos++;
  17831. break;
  17832. }
  17833. if (ch === 92 /* backslash */) {
  17834. result += text.substring(start, pos);
  17835. pos++;
  17836. if (pos >= len) {
  17837. scanError = 2 /* UnexpectedEndOfString */;
  17838. break;
  17839. }
  17840. ch = text.charCodeAt(pos++);
  17841. switch (ch) {
  17842. case 34 /* doubleQuote */:
  17843. result += '\"';
  17844. break;
  17845. case 92 /* backslash */:
  17846. result += '\\';
  17847. break;
  17848. case 47 /* slash */:
  17849. result += '/';
  17850. break;
  17851. case 98 /* b */:
  17852. result += '\b';
  17853. break;
  17854. case 102 /* f */:
  17855. result += '\f';
  17856. break;
  17857. case 110 /* n */:
  17858. result += '\n';
  17859. break;
  17860. case 114 /* r */:
  17861. result += '\r';
  17862. break;
  17863. case 116 /* t */:
  17864. result += '\t';
  17865. break;
  17866. case 117 /* u */:
  17867. var ch_1 = scanHexDigits(4, true);
  17868. if (ch_1 >= 0) {
  17869. result += String.fromCharCode(ch_1);
  17870. }
  17871. else {
  17872. scanError = 4 /* InvalidUnicode */;
  17873. }
  17874. break;
  17875. default:
  17876. scanError = 5 /* InvalidEscapeCharacter */;
  17877. }
  17878. start = pos;
  17879. continue;
  17880. }
  17881. if (ch >= 0 && ch <= 0x1f) {
  17882. if (isLineBreak(ch)) {
  17883. result += text.substring(start, pos);
  17884. scanError = 2 /* UnexpectedEndOfString */;
  17885. break;
  17886. }
  17887. else {
  17888. scanError = 6 /* InvalidCharacter */;
  17889. // mark as error but continue with string
  17890. }
  17891. }
  17892. pos++;
  17893. }
  17894. return result;
  17895. }
  17896. function scanNext() {
  17897. value = '';
  17898. scanError = 0 /* None */;
  17899. tokenOffset = pos;
  17900. lineStartOffset = lineNumber;
  17901. prevTokenLineStartOffset = tokenLineStartOffset;
  17902. if (pos >= len) {
  17903. // at the end
  17904. tokenOffset = len;
  17905. return token = 17 /* EOF */;
  17906. }
  17907. var code = text.charCodeAt(pos);
  17908. // trivia: whitespace
  17909. if (isWhiteSpace(code)) {
  17910. do {
  17911. pos++;
  17912. value += String.fromCharCode(code);
  17913. code = text.charCodeAt(pos);
  17914. } while (isWhiteSpace(code));
  17915. return token = 15 /* Trivia */;
  17916. }
  17917. // trivia: newlines
  17918. if (isLineBreak(code)) {
  17919. pos++;
  17920. value += String.fromCharCode(code);
  17921. if (code === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
  17922. pos++;
  17923. value += '\n';
  17924. }
  17925. lineNumber++;
  17926. tokenLineStartOffset = pos;
  17927. return token = 14 /* LineBreakTrivia */;
  17928. }
  17929. switch (code) {
  17930. // tokens: []{}:,
  17931. case 123 /* openBrace */:
  17932. pos++;
  17933. return token = 1 /* OpenBraceToken */;
  17934. case 125 /* closeBrace */:
  17935. pos++;
  17936. return token = 2 /* CloseBraceToken */;
  17937. case 91 /* openBracket */:
  17938. pos++;
  17939. return token = 3 /* OpenBracketToken */;
  17940. case 93 /* closeBracket */:
  17941. pos++;
  17942. return token = 4 /* CloseBracketToken */;
  17943. case 58 /* colon */:
  17944. pos++;
  17945. return token = 6 /* ColonToken */;
  17946. case 44 /* comma */:
  17947. pos++;
  17948. return token = 5 /* CommaToken */;
  17949. // strings
  17950. case 34 /* doubleQuote */:
  17951. pos++;
  17952. value = scanString();
  17953. return token = 10 /* StringLiteral */;
  17954. // comments
  17955. case 47 /* slash */:
  17956. var start = pos - 1;
  17957. // Single-line comment
  17958. if (text.charCodeAt(pos + 1) === 47 /* slash */) {
  17959. pos += 2;
  17960. while (pos < len) {
  17961. if (isLineBreak(text.charCodeAt(pos))) {
  17962. break;
  17963. }
  17964. pos++;
  17965. }
  17966. value = text.substring(start, pos);
  17967. return token = 12 /* LineCommentTrivia */;
  17968. }
  17969. // Multi-line comment
  17970. if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
  17971. pos += 2;
  17972. var safeLength = len - 1; // For lookahead.
  17973. var commentClosed = false;
  17974. while (pos < safeLength) {
  17975. var ch = text.charCodeAt(pos);
  17976. if (ch === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
  17977. pos += 2;
  17978. commentClosed = true;
  17979. break;
  17980. }
  17981. pos++;
  17982. if (isLineBreak(ch)) {
  17983. if (ch === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
  17984. pos++;
  17985. }
  17986. lineNumber++;
  17987. tokenLineStartOffset = pos;
  17988. }
  17989. }
  17990. if (!commentClosed) {
  17991. pos++;
  17992. scanError = 1 /* UnexpectedEndOfComment */;
  17993. }
  17994. value = text.substring(start, pos);
  17995. return token = 13 /* BlockCommentTrivia */;
  17996. }
  17997. // just a single slash
  17998. value += String.fromCharCode(code);
  17999. pos++;
  18000. return token = 16 /* Unknown */;
  18001. // numbers
  18002. case 45 /* minus */:
  18003. value += String.fromCharCode(code);
  18004. pos++;
  18005. if (pos === len || !isDigit(text.charCodeAt(pos))) {
  18006. return token = 16 /* Unknown */;
  18007. }
  18008. // found a minus, followed by a number so
  18009. // we fall through to proceed with scanning
  18010. // numbers
  18011. case 48 /* _0 */:
  18012. case 49 /* _1 */:
  18013. case 50 /* _2 */:
  18014. case 51 /* _3 */:
  18015. case 52 /* _4 */:
  18016. case 53 /* _5 */:
  18017. case 54 /* _6 */:
  18018. case 55 /* _7 */:
  18019. case 56 /* _8 */:
  18020. case 57 /* _9 */:
  18021. value += scanNumber();
  18022. return token = 11 /* NumericLiteral */;
  18023. // literals and unknown symbols
  18024. default:
  18025. // is a literal? Read the full word.
  18026. while (pos < len && isUnknownContentCharacter(code)) {
  18027. pos++;
  18028. code = text.charCodeAt(pos);
  18029. }
  18030. if (tokenOffset !== pos) {
  18031. value = text.substring(tokenOffset, pos);
  18032. // keywords: true, false, null
  18033. switch (value) {
  18034. case 'true': return token = 8 /* TrueKeyword */;
  18035. case 'false': return token = 9 /* FalseKeyword */;
  18036. case 'null': return token = 7 /* NullKeyword */;
  18037. }
  18038. return token = 16 /* Unknown */;
  18039. }
  18040. // some
  18041. value += String.fromCharCode(code);
  18042. pos++;
  18043. return token = 16 /* Unknown */;
  18044. }
  18045. }
  18046. function isUnknownContentCharacter(code) {
  18047. if (isWhiteSpace(code) || isLineBreak(code)) {
  18048. return false;
  18049. }
  18050. switch (code) {
  18051. case 125 /* closeBrace */:
  18052. case 93 /* closeBracket */:
  18053. case 123 /* openBrace */:
  18054. case 91 /* openBracket */:
  18055. case 34 /* doubleQuote */:
  18056. case 58 /* colon */:
  18057. case 44 /* comma */:
  18058. case 47 /* slash */:
  18059. return false;
  18060. }
  18061. return true;
  18062. }
  18063. function scanNextNonTrivia() {
  18064. var result;
  18065. do {
  18066. result = scanNext();
  18067. } while (result >= 12 /* LineCommentTrivia */ && result <= 15 /* Trivia */);
  18068. return result;
  18069. }
  18070. return {
  18071. setPosition: setPosition,
  18072. getPosition: function () { return pos; },
  18073. scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
  18074. getToken: function () { return token; },
  18075. getTokenValue: function () { return value; },
  18076. getTokenOffset: function () { return tokenOffset; },
  18077. getTokenLength: function () { return pos - tokenOffset; },
  18078. getTokenStartLine: function () { return lineStartOffset; },
  18079. getTokenStartCharacter: function () { return tokenOffset - prevTokenLineStartOffset; },
  18080. getTokenError: function () { return scanError; },
  18081. };
  18082. }
  18083. function isWhiteSpace(ch) {
  18084. return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ ||
  18085. ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
  18086. ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */;
  18087. }
  18088. function isLineBreak(ch) {
  18089. return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */;
  18090. }
  18091. function isDigit(ch) {
  18092. return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
  18093. }
  18094. //# sourceMappingURL=scanner.js.map
  18095. /***/ }),
  18096. /* 86 */
  18097. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  18098. "use strict";
  18099. __webpack_require__.r(__webpack_exports__);
  18100. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeProperty", function() { return removeProperty; });
  18101. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setProperty", function() { return setProperty; });
  18102. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEdit", function() { return applyEdit; });
  18103. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isWS", function() { return isWS; });
  18104. /* harmony import */ var _format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(84);
  18105. /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(87);
  18106. /*---------------------------------------------------------------------------------------------
  18107. * Copyright (c) Microsoft Corporation. All rights reserved.
  18108. * Licensed under the MIT License. See License.txt in the project root for license information.
  18109. *--------------------------------------------------------------------------------------------*/
  18110. function removeProperty(text, path, formattingOptions) {
  18111. return setProperty(text, path, void 0, formattingOptions);
  18112. }
  18113. function setProperty(text, originalPath, value, formattingOptions, getInsertionIndex) {
  18114. var _a;
  18115. var path = originalPath.slice();
  18116. var errors = [];
  18117. var root = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["parseTree"])(text, errors);
  18118. var parent = void 0;
  18119. var lastSegment = void 0;
  18120. while (path.length > 0) {
  18121. lastSegment = path.pop();
  18122. parent = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["findNodeAtLocation"])(root, path);
  18123. if (parent === void 0 && value !== void 0) {
  18124. if (typeof lastSegment === 'string') {
  18125. value = (_a = {}, _a[lastSegment] = value, _a);
  18126. }
  18127. else {
  18128. value = [value];
  18129. }
  18130. }
  18131. else {
  18132. break;
  18133. }
  18134. }
  18135. if (!parent) {
  18136. // empty document
  18137. if (value === void 0) { // delete
  18138. throw new Error('Can not delete in empty document');
  18139. }
  18140. return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, formattingOptions);
  18141. }
  18142. else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {
  18143. var existing = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["findNodeAtLocation"])(parent, [lastSegment]);
  18144. if (existing !== void 0) {
  18145. if (value === void 0) { // delete
  18146. if (!existing.parent) {
  18147. throw new Error('Malformed AST');
  18148. }
  18149. var propertyIndex = parent.children.indexOf(existing.parent);
  18150. var removeBegin = void 0;
  18151. var removeEnd = existing.parent.offset + existing.parent.length;
  18152. if (propertyIndex > 0) {
  18153. // remove the comma of the previous node
  18154. var previous = parent.children[propertyIndex - 1];
  18155. removeBegin = previous.offset + previous.length;
  18156. }
  18157. else {
  18158. removeBegin = parent.offset + 1;
  18159. if (parent.children.length > 1) {
  18160. // remove the comma of the next node
  18161. var next = parent.children[1];
  18162. removeEnd = next.offset;
  18163. }
  18164. }
  18165. return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, formattingOptions);
  18166. }
  18167. else {
  18168. // set value of existing property
  18169. return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, formattingOptions);
  18170. }
  18171. }
  18172. else {
  18173. if (value === void 0) { // delete
  18174. return []; // property does not exist, nothing to do
  18175. }
  18176. var newProperty = JSON.stringify(lastSegment) + ": " + JSON.stringify(value);
  18177. var index = getInsertionIndex ? getInsertionIndex(parent.children.map(function (p) { return p.children[0].value; })) : parent.children.length;
  18178. var edit = void 0;
  18179. if (index > 0) {
  18180. var previous = parent.children[index - 1];
  18181. edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
  18182. }
  18183. else if (parent.children.length === 0) {
  18184. edit = { offset: parent.offset + 1, length: 0, content: newProperty };
  18185. }
  18186. else {
  18187. edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };
  18188. }
  18189. return withFormatting(text, edit, formattingOptions);
  18190. }
  18191. }
  18192. else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {
  18193. var insertIndex = lastSegment;
  18194. if (insertIndex === -1) {
  18195. // Insert
  18196. var newProperty = "" + JSON.stringify(value);
  18197. var edit = void 0;
  18198. if (parent.children.length === 0) {
  18199. edit = { offset: parent.offset + 1, length: 0, content: newProperty };
  18200. }
  18201. else {
  18202. var previous = parent.children[parent.children.length - 1];
  18203. edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
  18204. }
  18205. return withFormatting(text, edit, formattingOptions);
  18206. }
  18207. else {
  18208. if (value === void 0 && parent.children.length >= 0) {
  18209. //Removal
  18210. var removalIndex = lastSegment;
  18211. var toRemove = parent.children[removalIndex];
  18212. var edit = void 0;
  18213. if (parent.children.length === 1) {
  18214. // only item
  18215. edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };
  18216. }
  18217. else if (parent.children.length - 1 === removalIndex) {
  18218. // last item
  18219. var previous = parent.children[removalIndex - 1];
  18220. var offset = previous.offset + previous.length;
  18221. var parentEndOffset = parent.offset + parent.length;
  18222. edit = { offset: offset, length: parentEndOffset - 2 - offset, content: '' };
  18223. }
  18224. else {
  18225. edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };
  18226. }
  18227. return withFormatting(text, edit, formattingOptions);
  18228. }
  18229. else {
  18230. throw new Error('Array modification not supported yet');
  18231. }
  18232. }
  18233. }
  18234. else {
  18235. throw new Error("Can not add " + (typeof lastSegment !== 'number' ? 'index' : 'property') + " to parent of type " + parent.type);
  18236. }
  18237. }
  18238. function withFormatting(text, edit, formattingOptions) {
  18239. // apply the edit
  18240. var newText = applyEdit(text, edit);
  18241. // format the new text
  18242. var begin = edit.offset;
  18243. var end = edit.offset + edit.content.length;
  18244. if (edit.length === 0 || edit.content.length === 0) { // insert or remove
  18245. while (begin > 0 && !Object(_format__WEBPACK_IMPORTED_MODULE_0__["isEOL"])(newText, begin - 1)) {
  18246. begin--;
  18247. }
  18248. while (end < newText.length && !Object(_format__WEBPACK_IMPORTED_MODULE_0__["isEOL"])(newText, end)) {
  18249. end++;
  18250. }
  18251. }
  18252. var edits = Object(_format__WEBPACK_IMPORTED_MODULE_0__["format"])(newText, { offset: begin, length: end - begin }, formattingOptions);
  18253. // apply the formatting edits and track the begin and end offsets of the changes
  18254. for (var i = edits.length - 1; i >= 0; i--) {
  18255. var edit_1 = edits[i];
  18256. newText = applyEdit(newText, edit_1);
  18257. begin = Math.min(begin, edit_1.offset);
  18258. end = Math.max(end, edit_1.offset + edit_1.length);
  18259. end += edit_1.content.length - edit_1.length;
  18260. }
  18261. // create a single edit with all changes
  18262. var editLength = text.length - (newText.length - end) - begin;
  18263. return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
  18264. }
  18265. function applyEdit(text, edit) {
  18266. return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
  18267. }
  18268. function isWS(text, offset) {
  18269. return '\r\n \t'.indexOf(text.charAt(offset)) !== -1;
  18270. }
  18271. //# sourceMappingURL=edit.js.map
  18272. /***/ }),
  18273. /* 87 */
  18274. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  18275. "use strict";
  18276. __webpack_require__.r(__webpack_exports__);
  18277. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocation", function() { return getLocation; });
  18278. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
  18279. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTree", function() { return parseTree; });
  18280. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtLocation", function() { return findNodeAtLocation; });
  18281. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; });
  18282. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; });
  18283. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return contains; });
  18284. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtOffset", function() { return findNodeAtOffset; });
  18285. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "visit", function() { return visit; });
  18286. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripComments", function() { return stripComments; });
  18287. /* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85);
  18288. /*---------------------------------------------------------------------------------------------
  18289. * Copyright (c) Microsoft Corporation. All rights reserved.
  18290. * Licensed under the MIT License. See License.txt in the project root for license information.
  18291. *--------------------------------------------------------------------------------------------*/
  18292. var ParseOptions;
  18293. (function (ParseOptions) {
  18294. ParseOptions.DEFAULT = {
  18295. allowTrailingComma: false
  18296. };
  18297. })(ParseOptions || (ParseOptions = {}));
  18298. /**
  18299. * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
  18300. */
  18301. function getLocation(text, position) {
  18302. var segments = []; // strings or numbers
  18303. var earlyReturnException = new Object();
  18304. var previousNode = void 0;
  18305. var previousNodeInst = {
  18306. value: {},
  18307. offset: 0,
  18308. length: 0,
  18309. type: 'object',
  18310. parent: void 0
  18311. };
  18312. var isAtPropertyKey = false;
  18313. function setPreviousNode(value, offset, length, type) {
  18314. previousNodeInst.value = value;
  18315. previousNodeInst.offset = offset;
  18316. previousNodeInst.length = length;
  18317. previousNodeInst.type = type;
  18318. previousNodeInst.colonOffset = void 0;
  18319. previousNode = previousNodeInst;
  18320. }
  18321. try {
  18322. visit(text, {
  18323. onObjectBegin: function (offset, length) {
  18324. if (position <= offset) {
  18325. throw earlyReturnException;
  18326. }
  18327. previousNode = void 0;
  18328. isAtPropertyKey = position > offset;
  18329. segments.push(''); // push a placeholder (will be replaced)
  18330. },
  18331. onObjectProperty: function (name, offset, length) {
  18332. if (position < offset) {
  18333. throw earlyReturnException;
  18334. }
  18335. setPreviousNode(name, offset, length, 'property');
  18336. segments[segments.length - 1] = name;
  18337. if (position <= offset + length) {
  18338. throw earlyReturnException;
  18339. }
  18340. },
  18341. onObjectEnd: function (offset, length) {
  18342. if (position <= offset) {
  18343. throw earlyReturnException;
  18344. }
  18345. previousNode = void 0;
  18346. segments.pop();
  18347. },
  18348. onArrayBegin: function (offset, length) {
  18349. if (position <= offset) {
  18350. throw earlyReturnException;
  18351. }
  18352. previousNode = void 0;
  18353. segments.push(0);
  18354. },
  18355. onArrayEnd: function (offset, length) {
  18356. if (position <= offset) {
  18357. throw earlyReturnException;
  18358. }
  18359. previousNode = void 0;
  18360. segments.pop();
  18361. },
  18362. onLiteralValue: function (value, offset, length) {
  18363. if (position < offset) {
  18364. throw earlyReturnException;
  18365. }
  18366. setPreviousNode(value, offset, length, getLiteralNodeType(value));
  18367. if (position <= offset + length) {
  18368. throw earlyReturnException;
  18369. }
  18370. },
  18371. onSeparator: function (sep, offset, length) {
  18372. if (position <= offset) {
  18373. throw earlyReturnException;
  18374. }
  18375. if (sep === ':' && previousNode && previousNode.type === 'property') {
  18376. previousNode.colonOffset = offset;
  18377. isAtPropertyKey = false;
  18378. previousNode = void 0;
  18379. }
  18380. else if (sep === ',') {
  18381. var last = segments[segments.length - 1];
  18382. if (typeof last === 'number') {
  18383. segments[segments.length - 1] = last + 1;
  18384. }
  18385. else {
  18386. isAtPropertyKey = true;
  18387. segments[segments.length - 1] = '';
  18388. }
  18389. previousNode = void 0;
  18390. }
  18391. }
  18392. });
  18393. }
  18394. catch (e) {
  18395. if (e !== earlyReturnException) {
  18396. throw e;
  18397. }
  18398. }
  18399. return {
  18400. path: segments,
  18401. previousNode: previousNode,
  18402. isAtPropertyKey: isAtPropertyKey,
  18403. matches: function (pattern) {
  18404. var k = 0;
  18405. for (var i = 0; k < pattern.length && i < segments.length; i++) {
  18406. if (pattern[k] === segments[i] || pattern[k] === '*') {
  18407. k++;
  18408. }
  18409. else if (pattern[k] !== '**') {
  18410. return false;
  18411. }
  18412. }
  18413. return k === pattern.length;
  18414. }
  18415. };
  18416. }
  18417. /**
  18418. * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
  18419. * Therefore always check the errors list to find out if the input was valid.
  18420. */
  18421. function parse(text, errors, options) {
  18422. if (errors === void 0) { errors = []; }
  18423. if (options === void 0) { options = ParseOptions.DEFAULT; }
  18424. var currentProperty = null;
  18425. var currentParent = [];
  18426. var previousParents = [];
  18427. function onValue(value) {
  18428. if (Array.isArray(currentParent)) {
  18429. currentParent.push(value);
  18430. }
  18431. else if (currentProperty) {
  18432. currentParent[currentProperty] = value;
  18433. }
  18434. }
  18435. var visitor = {
  18436. onObjectBegin: function () {
  18437. var object = {};
  18438. onValue(object);
  18439. previousParents.push(currentParent);
  18440. currentParent = object;
  18441. currentProperty = null;
  18442. },
  18443. onObjectProperty: function (name) {
  18444. currentProperty = name;
  18445. },
  18446. onObjectEnd: function () {
  18447. currentParent = previousParents.pop();
  18448. },
  18449. onArrayBegin: function () {
  18450. var array = [];
  18451. onValue(array);
  18452. previousParents.push(currentParent);
  18453. currentParent = array;
  18454. currentProperty = null;
  18455. },
  18456. onArrayEnd: function () {
  18457. currentParent = previousParents.pop();
  18458. },
  18459. onLiteralValue: onValue,
  18460. onError: function (error, offset, length) {
  18461. errors.push({ error: error, offset: offset, length: length });
  18462. }
  18463. };
  18464. visit(text, visitor, options);
  18465. return currentParent[0];
  18466. }
  18467. /**
  18468. * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
  18469. */
  18470. function parseTree(text, errors, options) {
  18471. if (errors === void 0) { errors = []; }
  18472. if (options === void 0) { options = ParseOptions.DEFAULT; }
  18473. var currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: void 0 }; // artificial root
  18474. function ensurePropertyComplete(endOffset) {
  18475. if (currentParent.type === 'property') {
  18476. currentParent.length = endOffset - currentParent.offset;
  18477. currentParent = currentParent.parent;
  18478. }
  18479. }
  18480. function onValue(valueNode) {
  18481. currentParent.children.push(valueNode);
  18482. return valueNode;
  18483. }
  18484. var visitor = {
  18485. onObjectBegin: function (offset) {
  18486. currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });
  18487. },
  18488. onObjectProperty: function (name, offset, length) {
  18489. currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });
  18490. currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });
  18491. },
  18492. onObjectEnd: function (offset, length) {
  18493. currentParent.length = offset + length - currentParent.offset;
  18494. currentParent = currentParent.parent;
  18495. ensurePropertyComplete(offset + length);
  18496. },
  18497. onArrayBegin: function (offset, length) {
  18498. currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });
  18499. },
  18500. onArrayEnd: function (offset, length) {
  18501. currentParent.length = offset + length - currentParent.offset;
  18502. currentParent = currentParent.parent;
  18503. ensurePropertyComplete(offset + length);
  18504. },
  18505. onLiteralValue: function (value, offset, length) {
  18506. onValue({ type: getLiteralNodeType(value), offset: offset, length: length, parent: currentParent, value: value });
  18507. ensurePropertyComplete(offset + length);
  18508. },
  18509. onSeparator: function (sep, offset, length) {
  18510. if (currentParent.type === 'property') {
  18511. if (sep === ':') {
  18512. currentParent.colonOffset = offset;
  18513. }
  18514. else if (sep === ',') {
  18515. ensurePropertyComplete(offset);
  18516. }
  18517. }
  18518. },
  18519. onError: function (error, offset, length) {
  18520. errors.push({ error: error, offset: offset, length: length });
  18521. }
  18522. };
  18523. visit(text, visitor, options);
  18524. var result = currentParent.children[0];
  18525. if (result) {
  18526. delete result.parent;
  18527. }
  18528. return result;
  18529. }
  18530. /**
  18531. * Finds the node at the given path in a JSON DOM.
  18532. */
  18533. function findNodeAtLocation(root, path) {
  18534. if (!root) {
  18535. return void 0;
  18536. }
  18537. var node = root;
  18538. for (var _i = 0, path_1 = path; _i < path_1.length; _i++) {
  18539. var segment = path_1[_i];
  18540. if (typeof segment === 'string') {
  18541. if (node.type !== 'object' || !Array.isArray(node.children)) {
  18542. return void 0;
  18543. }
  18544. var found = false;
  18545. for (var _a = 0, _b = node.children; _a < _b.length; _a++) {
  18546. var propertyNode = _b[_a];
  18547. if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) {
  18548. node = propertyNode.children[1];
  18549. found = true;
  18550. break;
  18551. }
  18552. }
  18553. if (!found) {
  18554. return void 0;
  18555. }
  18556. }
  18557. else {
  18558. var index = segment;
  18559. if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
  18560. return void 0;
  18561. }
  18562. node = node.children[index];
  18563. }
  18564. }
  18565. return node;
  18566. }
  18567. /**
  18568. * Gets the JSON path of the given JSON DOM node
  18569. */
  18570. function getNodePath(node) {
  18571. if (!node.parent || !node.parent.children) {
  18572. return [];
  18573. }
  18574. var path = getNodePath(node.parent);
  18575. if (node.parent.type === 'property') {
  18576. var key = node.parent.children[0].value;
  18577. path.push(key);
  18578. }
  18579. else if (node.parent.type === 'array') {
  18580. var index = node.parent.children.indexOf(node);
  18581. if (index !== -1) {
  18582. path.push(index);
  18583. }
  18584. }
  18585. return path;
  18586. }
  18587. /**
  18588. * Evaluates the JavaScript object of the given JSON DOM node
  18589. */
  18590. function getNodeValue(node) {
  18591. switch (node.type) {
  18592. case 'array':
  18593. return node.children.map(getNodeValue);
  18594. case 'object':
  18595. var obj = Object.create(null);
  18596. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  18597. var prop = _a[_i];
  18598. var valueNode = prop.children[1];
  18599. if (valueNode) {
  18600. obj[prop.children[0].value] = getNodeValue(valueNode);
  18601. }
  18602. }
  18603. return obj;
  18604. case 'null':
  18605. case 'string':
  18606. case 'number':
  18607. case 'boolean':
  18608. return node.value;
  18609. default:
  18610. return void 0;
  18611. }
  18612. }
  18613. function contains(node, offset, includeRightBound) {
  18614. if (includeRightBound === void 0) { includeRightBound = false; }
  18615. return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));
  18616. }
  18617. /**
  18618. * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
  18619. */
  18620. function findNodeAtOffset(node, offset, includeRightBound) {
  18621. if (includeRightBound === void 0) { includeRightBound = false; }
  18622. if (contains(node, offset, includeRightBound)) {
  18623. var children = node.children;
  18624. if (Array.isArray(children)) {
  18625. for (var i = 0; i < children.length && children[i].offset <= offset; i++) {
  18626. var item = findNodeAtOffset(children[i], offset, includeRightBound);
  18627. if (item) {
  18628. return item;
  18629. }
  18630. }
  18631. }
  18632. return node;
  18633. }
  18634. return void 0;
  18635. }
  18636. /**
  18637. * Parses the given text and invokes the visitor functions for each object, array and literal reached.
  18638. */
  18639. function visit(text, visitor, options) {
  18640. if (options === void 0) { options = ParseOptions.DEFAULT; }
  18641. var _scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(text, false);
  18642. function toNoArgVisit(visitFunction) {
  18643. return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
  18644. }
  18645. function toOneArgVisit(visitFunction) {
  18646. return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
  18647. }
  18648. var onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
  18649. var disallowComments = options && options.disallowComments;
  18650. var allowTrailingComma = options && options.allowTrailingComma;
  18651. function scanNext() {
  18652. while (true) {
  18653. var token = _scanner.scan();
  18654. switch (_scanner.getTokenError()) {
  18655. case 4 /* InvalidUnicode */:
  18656. handleError(14 /* InvalidUnicode */);
  18657. break;
  18658. case 5 /* InvalidEscapeCharacter */:
  18659. handleError(15 /* InvalidEscapeCharacter */);
  18660. break;
  18661. case 3 /* UnexpectedEndOfNumber */:
  18662. handleError(13 /* UnexpectedEndOfNumber */);
  18663. break;
  18664. case 1 /* UnexpectedEndOfComment */:
  18665. if (!disallowComments) {
  18666. handleError(11 /* UnexpectedEndOfComment */);
  18667. }
  18668. break;
  18669. case 2 /* UnexpectedEndOfString */:
  18670. handleError(12 /* UnexpectedEndOfString */);
  18671. break;
  18672. case 6 /* InvalidCharacter */:
  18673. handleError(16 /* InvalidCharacter */);
  18674. break;
  18675. }
  18676. switch (token) {
  18677. case 12 /* LineCommentTrivia */:
  18678. case 13 /* BlockCommentTrivia */:
  18679. if (disallowComments) {
  18680. handleError(10 /* InvalidCommentToken */);
  18681. }
  18682. else {
  18683. onComment();
  18684. }
  18685. break;
  18686. case 16 /* Unknown */:
  18687. handleError(1 /* InvalidSymbol */);
  18688. break;
  18689. case 15 /* Trivia */:
  18690. case 14 /* LineBreakTrivia */:
  18691. break;
  18692. default:
  18693. return token;
  18694. }
  18695. }
  18696. }
  18697. function handleError(error, skipUntilAfter, skipUntil) {
  18698. if (skipUntilAfter === void 0) { skipUntilAfter = []; }
  18699. if (skipUntil === void 0) { skipUntil = []; }
  18700. onError(error);
  18701. if (skipUntilAfter.length + skipUntil.length > 0) {
  18702. var token = _scanner.getToken();
  18703. while (token !== 17 /* EOF */) {
  18704. if (skipUntilAfter.indexOf(token) !== -1) {
  18705. scanNext();
  18706. break;
  18707. }
  18708. else if (skipUntil.indexOf(token) !== -1) {
  18709. break;
  18710. }
  18711. token = scanNext();
  18712. }
  18713. }
  18714. }
  18715. function parseString(isValue) {
  18716. var value = _scanner.getTokenValue();
  18717. if (isValue) {
  18718. onLiteralValue(value);
  18719. }
  18720. else {
  18721. onObjectProperty(value);
  18722. }
  18723. scanNext();
  18724. return true;
  18725. }
  18726. function parseLiteral() {
  18727. switch (_scanner.getToken()) {
  18728. case 11 /* NumericLiteral */:
  18729. var value = 0;
  18730. try {
  18731. value = JSON.parse(_scanner.getTokenValue());
  18732. if (typeof value !== 'number') {
  18733. handleError(2 /* InvalidNumberFormat */);
  18734. value = 0;
  18735. }
  18736. }
  18737. catch (e) {
  18738. handleError(2 /* InvalidNumberFormat */);
  18739. }
  18740. onLiteralValue(value);
  18741. break;
  18742. case 7 /* NullKeyword */:
  18743. onLiteralValue(null);
  18744. break;
  18745. case 8 /* TrueKeyword */:
  18746. onLiteralValue(true);
  18747. break;
  18748. case 9 /* FalseKeyword */:
  18749. onLiteralValue(false);
  18750. break;
  18751. default:
  18752. return false;
  18753. }
  18754. scanNext();
  18755. return true;
  18756. }
  18757. function parseProperty() {
  18758. if (_scanner.getToken() !== 10 /* StringLiteral */) {
  18759. handleError(3 /* PropertyNameExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  18760. return false;
  18761. }
  18762. parseString(false);
  18763. if (_scanner.getToken() === 6 /* ColonToken */) {
  18764. onSeparator(':');
  18765. scanNext(); // consume colon
  18766. if (!parseValue()) {
  18767. handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  18768. }
  18769. }
  18770. else {
  18771. handleError(5 /* ColonExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  18772. }
  18773. return true;
  18774. }
  18775. function parseObject() {
  18776. onObjectBegin();
  18777. scanNext(); // consume open brace
  18778. var needsComma = false;
  18779. while (_scanner.getToken() !== 2 /* CloseBraceToken */ && _scanner.getToken() !== 17 /* EOF */) {
  18780. if (_scanner.getToken() === 5 /* CommaToken */) {
  18781. if (!needsComma) {
  18782. handleError(4 /* ValueExpected */, [], []);
  18783. }
  18784. onSeparator(',');
  18785. scanNext(); // consume comma
  18786. if (_scanner.getToken() === 2 /* CloseBraceToken */ && allowTrailingComma) {
  18787. break;
  18788. }
  18789. }
  18790. else if (needsComma) {
  18791. handleError(6 /* CommaExpected */, [], []);
  18792. }
  18793. if (!parseProperty()) {
  18794. handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  18795. }
  18796. needsComma = true;
  18797. }
  18798. onObjectEnd();
  18799. if (_scanner.getToken() !== 2 /* CloseBraceToken */) {
  18800. handleError(7 /* CloseBraceExpected */, [2 /* CloseBraceToken */], []);
  18801. }
  18802. else {
  18803. scanNext(); // consume close brace
  18804. }
  18805. return true;
  18806. }
  18807. function parseArray() {
  18808. onArrayBegin();
  18809. scanNext(); // consume open bracket
  18810. var needsComma = false;
  18811. while (_scanner.getToken() !== 4 /* CloseBracketToken */ && _scanner.getToken() !== 17 /* EOF */) {
  18812. if (_scanner.getToken() === 5 /* CommaToken */) {
  18813. if (!needsComma) {
  18814. handleError(4 /* ValueExpected */, [], []);
  18815. }
  18816. onSeparator(',');
  18817. scanNext(); // consume comma
  18818. if (_scanner.getToken() === 4 /* CloseBracketToken */ && allowTrailingComma) {
  18819. break;
  18820. }
  18821. }
  18822. else if (needsComma) {
  18823. handleError(6 /* CommaExpected */, [], []);
  18824. }
  18825. if (!parseValue()) {
  18826. handleError(4 /* ValueExpected */, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
  18827. }
  18828. needsComma = true;
  18829. }
  18830. onArrayEnd();
  18831. if (_scanner.getToken() !== 4 /* CloseBracketToken */) {
  18832. handleError(8 /* CloseBracketExpected */, [4 /* CloseBracketToken */], []);
  18833. }
  18834. else {
  18835. scanNext(); // consume close bracket
  18836. }
  18837. return true;
  18838. }
  18839. function parseValue() {
  18840. switch (_scanner.getToken()) {
  18841. case 3 /* OpenBracketToken */:
  18842. return parseArray();
  18843. case 1 /* OpenBraceToken */:
  18844. return parseObject();
  18845. case 10 /* StringLiteral */:
  18846. return parseString(true);
  18847. default:
  18848. return parseLiteral();
  18849. }
  18850. }
  18851. scanNext();
  18852. if (_scanner.getToken() === 17 /* EOF */) {
  18853. return true;
  18854. }
  18855. if (!parseValue()) {
  18856. handleError(4 /* ValueExpected */, [], []);
  18857. return false;
  18858. }
  18859. if (_scanner.getToken() !== 17 /* EOF */) {
  18860. handleError(9 /* EndOfFileExpected */, [], []);
  18861. }
  18862. return true;
  18863. }
  18864. /**
  18865. * Takes JSON with JavaScript-style comments and remove
  18866. * them. Optionally replaces every none-newline character
  18867. * of comments with a replaceCharacter
  18868. */
  18869. function stripComments(text, replaceCh) {
  18870. var _scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(text), parts = [], kind, offset = 0, pos;
  18871. do {
  18872. pos = _scanner.getPosition();
  18873. kind = _scanner.scan();
  18874. switch (kind) {
  18875. case 12 /* LineCommentTrivia */:
  18876. case 13 /* BlockCommentTrivia */:
  18877. case 17 /* EOF */:
  18878. if (offset !== pos) {
  18879. parts.push(text.substring(offset, pos));
  18880. }
  18881. if (replaceCh !== void 0) {
  18882. parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh));
  18883. }
  18884. offset = _scanner.getPosition();
  18885. break;
  18886. }
  18887. } while (kind !== 17 /* EOF */);
  18888. return parts.join('');
  18889. }
  18890. function getLiteralNodeType(value) {
  18891. switch (typeof value) {
  18892. case 'boolean': return 'boolean';
  18893. case 'number': return 'number';
  18894. case 'string': return 'string';
  18895. default: return 'null';
  18896. }
  18897. }
  18898. //# sourceMappingURL=parser.js.map
  18899. /***/ }),
  18900. /* 88 */
  18901. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  18902. "use strict";
  18903. __webpack_require__.r(__webpack_exports__);
  18904. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "equals", function() { return equals; });
  18905. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNumber", function() { return isNumber; });
  18906. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDefined", function() { return isDefined; });
  18907. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBoolean", function() { return isBoolean; });
  18908. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isString", function() { return isString; });
  18909. /*---------------------------------------------------------------------------------------------
  18910. * Copyright (c) Microsoft Corporation. All rights reserved.
  18911. * Licensed under the MIT License. See License.txt in the project root for license information.
  18912. *--------------------------------------------------------------------------------------------*/
  18913. function equals(one, other) {
  18914. if (one === other) {
  18915. return true;
  18916. }
  18917. if (one === null || one === undefined || other === null || other === undefined) {
  18918. return false;
  18919. }
  18920. if (typeof one !== typeof other) {
  18921. return false;
  18922. }
  18923. if (typeof one !== 'object') {
  18924. return false;
  18925. }
  18926. if ((Array.isArray(one)) !== (Array.isArray(other))) {
  18927. return false;
  18928. }
  18929. var i, key;
  18930. if (Array.isArray(one)) {
  18931. if (one.length !== other.length) {
  18932. return false;
  18933. }
  18934. for (i = 0; i < one.length; i++) {
  18935. if (!equals(one[i], other[i])) {
  18936. return false;
  18937. }
  18938. }
  18939. }
  18940. else {
  18941. var oneKeys = [];
  18942. for (key in one) {
  18943. oneKeys.push(key);
  18944. }
  18945. oneKeys.sort();
  18946. var otherKeys = [];
  18947. for (key in other) {
  18948. otherKeys.push(key);
  18949. }
  18950. otherKeys.sort();
  18951. if (!equals(oneKeys, otherKeys)) {
  18952. return false;
  18953. }
  18954. for (i = 0; i < oneKeys.length; i++) {
  18955. if (!equals(one[oneKeys[i]], other[oneKeys[i]])) {
  18956. return false;
  18957. }
  18958. }
  18959. }
  18960. return true;
  18961. }
  18962. function isNumber(val) {
  18963. return typeof val === 'number';
  18964. }
  18965. function isDefined(val) {
  18966. return typeof val !== 'undefined';
  18967. }
  18968. function isBoolean(val) {
  18969. return typeof val === 'boolean';
  18970. }
  18971. function isString(val) {
  18972. return typeof val === 'string';
  18973. }
  18974. /***/ }),
  18975. /* 89 */
  18976. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  18977. "use strict";
  18978. __webpack_require__.r(__webpack_exports__);
  18979. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorCode", function() { return ErrorCode; });
  18980. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClientCapabilities", function() { return ClientCapabilities; });
  18981. /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80);
  18982. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Range"]; });
  18983. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["TextEdit"]; });
  18984. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Color"]; });
  18985. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["ColorInformation"]; });
  18986. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["ColorPresentation"]; });
  18987. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["FoldingRange"]; });
  18988. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["FoldingRangeKind"]; });
  18989. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["SelectionRange"]; });
  18990. /**
  18991. * Error codes used by diagnostics
  18992. */
  18993. var ErrorCode;
  18994. (function (ErrorCode) {
  18995. ErrorCode[ErrorCode["Undefined"] = 0] = "Undefined";
  18996. ErrorCode[ErrorCode["EnumValueMismatch"] = 1] = "EnumValueMismatch";
  18997. ErrorCode[ErrorCode["UnexpectedEndOfComment"] = 257] = "UnexpectedEndOfComment";
  18998. ErrorCode[ErrorCode["UnexpectedEndOfString"] = 258] = "UnexpectedEndOfString";
  18999. ErrorCode[ErrorCode["UnexpectedEndOfNumber"] = 259] = "UnexpectedEndOfNumber";
  19000. ErrorCode[ErrorCode["InvalidUnicode"] = 260] = "InvalidUnicode";
  19001. ErrorCode[ErrorCode["InvalidEscapeCharacter"] = 261] = "InvalidEscapeCharacter";
  19002. ErrorCode[ErrorCode["InvalidCharacter"] = 262] = "InvalidCharacter";
  19003. ErrorCode[ErrorCode["PropertyExpected"] = 513] = "PropertyExpected";
  19004. ErrorCode[ErrorCode["CommaExpected"] = 514] = "CommaExpected";
  19005. ErrorCode[ErrorCode["ColonExpected"] = 515] = "ColonExpected";
  19006. ErrorCode[ErrorCode["ValueExpected"] = 516] = "ValueExpected";
  19007. ErrorCode[ErrorCode["CommaOrCloseBacketExpected"] = 517] = "CommaOrCloseBacketExpected";
  19008. ErrorCode[ErrorCode["CommaOrCloseBraceExpected"] = 518] = "CommaOrCloseBraceExpected";
  19009. ErrorCode[ErrorCode["TrailingComma"] = 519] = "TrailingComma";
  19010. ErrorCode[ErrorCode["DuplicateKey"] = 520] = "DuplicateKey";
  19011. ErrorCode[ErrorCode["CommentNotPermitted"] = 521] = "CommentNotPermitted";
  19012. ErrorCode[ErrorCode["SchemaResolveError"] = 768] = "SchemaResolveError";
  19013. })(ErrorCode || (ErrorCode = {}));
  19014. var ClientCapabilities;
  19015. (function (ClientCapabilities) {
  19016. ClientCapabilities.LATEST = {
  19017. textDocument: {
  19018. completion: {
  19019. completionItem: {
  19020. documentationFormat: [vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["MarkupKind"].Markdown, vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["MarkupKind"].PlainText]
  19021. }
  19022. }
  19023. }
  19024. };
  19025. })(ClientCapabilities || (ClientCapabilities = {}));
  19026. /***/ }),
  19027. /* 90 */
  19028. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  19029. "use strict";
  19030. __webpack_require__.r(__webpack_exports__);
  19031. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stringifyObject", function() { return stringifyObject; });
  19032. /*---------------------------------------------------------------------------------------------
  19033. * Copyright (c) Microsoft Corporation. All rights reserved.
  19034. * Licensed under the MIT License. See License.txt in the project root for license information.
  19035. *--------------------------------------------------------------------------------------------*/
  19036. function stringifyObject(obj, indent, stringifyLiteral) {
  19037. if (obj !== null && typeof obj === 'object') {
  19038. var newIndent = indent + '\t';
  19039. if (Array.isArray(obj)) {
  19040. if (obj.length === 0) {
  19041. return '[]';
  19042. }
  19043. var result = '[\n';
  19044. for (var i = 0; i < obj.length; i++) {
  19045. result += newIndent + stringifyObject(obj[i], newIndent, stringifyLiteral);
  19046. if (i < obj.length - 1) {
  19047. result += ',';
  19048. }
  19049. result += '\n';
  19050. }
  19051. result += indent + ']';
  19052. return result;
  19053. }
  19054. else {
  19055. var keys = Object.keys(obj);
  19056. if (keys.length === 0) {
  19057. return '{}';
  19058. }
  19059. var result = '{\n';
  19060. for (var i = 0; i < keys.length; i++) {
  19061. var key = keys[i];
  19062. result += newIndent + JSON.stringify(key) + ': ' + stringifyObject(obj[key], newIndent, stringifyLiteral);
  19063. if (i < keys.length - 1) {
  19064. result += ',';
  19065. }
  19066. result += '\n';
  19067. }
  19068. result += indent + '}';
  19069. return result;
  19070. }
  19071. }
  19072. return stringifyLiteral(obj);
  19073. }
  19074. /***/ }),
  19075. /* 91 */
  19076. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  19077. "use strict";
  19078. __webpack_require__.r(__webpack_exports__);
  19079. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startsWith", function() { return startsWith; });
  19080. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "endsWith", function() { return endsWith; });
  19081. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertSimple2RegExpPattern", function() { return convertSimple2RegExpPattern; });
  19082. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "repeat", function() { return repeat; });
  19083. /*---------------------------------------------------------------------------------------------
  19084. * Copyright (c) Microsoft Corporation. All rights reserved.
  19085. * Licensed under the MIT License. See License.txt in the project root for license information.
  19086. *--------------------------------------------------------------------------------------------*/
  19087. function startsWith(haystack, needle) {
  19088. if (haystack.length < needle.length) {
  19089. return false;
  19090. }
  19091. for (var i = 0; i < needle.length; i++) {
  19092. if (haystack[i] !== needle[i]) {
  19093. return false;
  19094. }
  19095. }
  19096. return true;
  19097. }
  19098. /**
  19099. * Determines if haystack ends with needle.
  19100. */
  19101. function endsWith(haystack, needle) {
  19102. var diff = haystack.length - needle.length;
  19103. if (diff > 0) {
  19104. return haystack.lastIndexOf(needle) === diff;
  19105. }
  19106. else if (diff === 0) {
  19107. return haystack === needle;
  19108. }
  19109. else {
  19110. return false;
  19111. }
  19112. }
  19113. function convertSimple2RegExpPattern(pattern) {
  19114. return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*');
  19115. }
  19116. function repeat(value, count) {
  19117. var s = '';
  19118. while (count > 0) {
  19119. if ((count & 1) === 1) {
  19120. s += value;
  19121. }
  19122. value += value;
  19123. count = count >>> 1;
  19124. }
  19125. return s;
  19126. }
  19127. /***/ }),
  19128. /* 92 */
  19129. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  19130. "use strict";
  19131. __webpack_require__.r(__webpack_exports__);
  19132. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONHover", function() { return JSONHover; });
  19133. /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82);
  19134. /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(80);
  19135. /*---------------------------------------------------------------------------------------------
  19136. * Copyright (c) Microsoft Corporation. All rights reserved.
  19137. * Licensed under the MIT License. See License.txt in the project root for license information.
  19138. *--------------------------------------------------------------------------------------------*/
  19139. var JSONHover = /** @class */ (function () {
  19140. function JSONHover(schemaService, contributions, promiseConstructor) {
  19141. if (contributions === void 0) { contributions = []; }
  19142. this.schemaService = schemaService;
  19143. this.contributions = contributions;
  19144. this.promise = promiseConstructor || Promise;
  19145. }
  19146. JSONHover.prototype.doHover = function (document, position, doc) {
  19147. var offset = document.offsetAt(position);
  19148. var node = doc.getNodeFromOffset(offset);
  19149. if (!node || (node.type === 'object' || node.type === 'array') && offset > node.offset + 1 && offset < node.offset + node.length - 1) {
  19150. return this.promise.resolve(null);
  19151. }
  19152. var hoverRangeNode = node;
  19153. // use the property description when hovering over an object key
  19154. if (node.type === 'string') {
  19155. var parent = node.parent;
  19156. if (parent && parent.type === 'property' && parent.keyNode === node) {
  19157. node = parent.valueNode;
  19158. if (!node) {
  19159. return this.promise.resolve(null);
  19160. }
  19161. }
  19162. }
  19163. var hoverRange = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["Range"].create(document.positionAt(hoverRangeNode.offset), document.positionAt(hoverRangeNode.offset + hoverRangeNode.length));
  19164. var createHover = function (contents) {
  19165. var result = {
  19166. contents: contents,
  19167. range: hoverRange
  19168. };
  19169. return result;
  19170. };
  19171. var location = _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodePath"](node);
  19172. for (var i = this.contributions.length - 1; i >= 0; i--) {
  19173. var contribution = this.contributions[i];
  19174. var promise = contribution.getInfoContribution(document.uri, location);
  19175. if (promise) {
  19176. return promise.then(function (htmlContent) { return createHover(htmlContent); });
  19177. }
  19178. }
  19179. return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
  19180. if (schema) {
  19181. var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
  19182. var title_1 = null;
  19183. var markdownDescription_1 = null;
  19184. var markdownEnumValueDescription_1 = null, enumValue_1 = null;
  19185. matchingSchemas.every(function (s) {
  19186. if (s.node === node && !s.inverted && s.schema) {
  19187. title_1 = title_1 || s.schema.title;
  19188. markdownDescription_1 = markdownDescription_1 || s.schema.markdownDescription || toMarkdown(s.schema.description);
  19189. if (s.schema.enum) {
  19190. var idx = s.schema.enum.indexOf(_parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](node));
  19191. if (s.schema.markdownEnumDescriptions) {
  19192. markdownEnumValueDescription_1 = s.schema.markdownEnumDescriptions[idx];
  19193. }
  19194. else if (s.schema.enumDescriptions) {
  19195. markdownEnumValueDescription_1 = toMarkdown(s.schema.enumDescriptions[idx]);
  19196. }
  19197. if (markdownEnumValueDescription_1) {
  19198. enumValue_1 = s.schema.enum[idx];
  19199. if (typeof enumValue_1 !== 'string') {
  19200. enumValue_1 = JSON.stringify(enumValue_1);
  19201. }
  19202. }
  19203. }
  19204. }
  19205. return true;
  19206. });
  19207. var result = '';
  19208. if (title_1) {
  19209. result = toMarkdown(title_1);
  19210. }
  19211. if (markdownDescription_1) {
  19212. if (result.length > 0) {
  19213. result += "\n\n";
  19214. }
  19215. result += markdownDescription_1;
  19216. }
  19217. if (markdownEnumValueDescription_1) {
  19218. if (result.length > 0) {
  19219. result += "\n\n";
  19220. }
  19221. result += "`" + toMarkdownCodeBlock(enumValue_1) + "`: " + markdownEnumValueDescription_1;
  19222. }
  19223. return createHover([result]);
  19224. }
  19225. return null;
  19226. });
  19227. };
  19228. return JSONHover;
  19229. }());
  19230. function toMarkdown(plain) {
  19231. if (plain) {
  19232. var res = plain.replace(/([^\n\r])(\r?\n)([^\n\r])/gm, '$1\n\n$3'); // single new lines to \n\n (Markdown paragraph)
  19233. return res.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
  19234. }
  19235. return void 0;
  19236. }
  19237. function toMarkdownCodeBlock(content) {
  19238. // see https://daringfireball.net/projects/markdown/syntax#precode
  19239. if (content.indexOf('`') !== -1) {
  19240. return '`` ' + content + ' ``';
  19241. }
  19242. return content;
  19243. }
  19244. /***/ }),
  19245. /* 93 */
  19246. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  19247. "use strict";
  19248. __webpack_require__.r(__webpack_exports__);
  19249. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONValidation", function() { return JSONValidation; });
  19250. /* harmony import */ var _jsonSchemaService__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(94);
  19251. /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(80);
  19252. /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(89);
  19253. /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(76);
  19254. /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_3__);
  19255. /*---------------------------------------------------------------------------------------------
  19256. * Copyright (c) Microsoft Corporation. All rights reserved.
  19257. * Licensed under the MIT License. See License.txt in the project root for license information.
  19258. *--------------------------------------------------------------------------------------------*/
  19259. var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_3__["loadMessageBundle"]();
  19260. var JSONValidation = /** @class */ (function () {
  19261. function JSONValidation(jsonSchemaService, promiseConstructor) {
  19262. this.jsonSchemaService = jsonSchemaService;
  19263. this.promise = promiseConstructor;
  19264. this.validationEnabled = true;
  19265. }
  19266. JSONValidation.prototype.configure = function (raw) {
  19267. if (raw) {
  19268. this.validationEnabled = raw.validate;
  19269. this.commentSeverity = raw.allowComments ? void 0 : vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Error;
  19270. }
  19271. };
  19272. JSONValidation.prototype.doValidation = function (textDocument, jsonDocument, documentSettings, schema) {
  19273. var _this = this;
  19274. if (!this.validationEnabled) {
  19275. return this.promise.resolve([]);
  19276. }
  19277. var diagnostics = [];
  19278. var added = {};
  19279. var addProblem = function (problem) {
  19280. // remove duplicated messages
  19281. var signature = problem.range.start.line + ' ' + problem.range.start.character + ' ' + problem.message;
  19282. if (!added[signature]) {
  19283. added[signature] = true;
  19284. diagnostics.push(problem);
  19285. }
  19286. };
  19287. var getDiagnostics = function (schema) {
  19288. var trailingCommaSeverity = documentSettings ? toDiagnosticSeverity(documentSettings.trailingCommas) : vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Error;
  19289. var commentSeverity = documentSettings ? toDiagnosticSeverity(documentSettings.comments) : _this.commentSeverity;
  19290. if (schema) {
  19291. if (schema.errors.length && jsonDocument.root) {
  19292. var astRoot = jsonDocument.root;
  19293. var property = astRoot.type === 'object' ? astRoot.properties[0] : null;
  19294. if (property && property.keyNode.value === '$schema') {
  19295. var node = property.valueNode || property;
  19296. var range = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["Range"].create(textDocument.positionAt(node.offset), textDocument.positionAt(node.offset + node.length));
  19297. addProblem(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["Diagnostic"].create(range, schema.errors[0], vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Warning, _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].SchemaResolveError));
  19298. }
  19299. else {
  19300. var range = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["Range"].create(textDocument.positionAt(astRoot.offset), textDocument.positionAt(astRoot.offset + 1));
  19301. addProblem(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["Diagnostic"].create(range, schema.errors[0], vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Warning, _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].SchemaResolveError));
  19302. }
  19303. }
  19304. else {
  19305. var semanticErrors = jsonDocument.validate(textDocument, schema.schema);
  19306. if (semanticErrors) {
  19307. semanticErrors.forEach(addProblem);
  19308. }
  19309. }
  19310. if (schemaAllowsComments(schema.schema)) {
  19311. trailingCommaSeverity = commentSeverity = void 0;
  19312. }
  19313. }
  19314. for (var _i = 0, _a = jsonDocument.syntaxErrors; _i < _a.length; _i++) {
  19315. var p = _a[_i];
  19316. if (p.code === _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].TrailingComma) {
  19317. if (typeof trailingCommaSeverity !== 'number') {
  19318. continue;
  19319. }
  19320. p.severity = trailingCommaSeverity;
  19321. }
  19322. addProblem(p);
  19323. }
  19324. if (typeof commentSeverity === 'number') {
  19325. var message_1 = localize('InvalidCommentToken', 'Comments are not permitted in JSON.');
  19326. jsonDocument.comments.forEach(function (c) {
  19327. addProblem(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["Diagnostic"].create(c, message_1, commentSeverity, _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommentNotPermitted));
  19328. });
  19329. }
  19330. return diagnostics;
  19331. };
  19332. if (schema) {
  19333. var id = schema.id || ('schemaservice://untitled/' + idCounter++);
  19334. return this.jsonSchemaService.resolveSchemaContent(new _jsonSchemaService__WEBPACK_IMPORTED_MODULE_0__["UnresolvedSchema"](schema), id, {}).then(function (resolvedSchema) {
  19335. return getDiagnostics(resolvedSchema);
  19336. });
  19337. }
  19338. return this.jsonSchemaService.getSchemaForResource(textDocument.uri, jsonDocument).then(function (schema) {
  19339. return getDiagnostics(schema);
  19340. });
  19341. };
  19342. return JSONValidation;
  19343. }());
  19344. var idCounter = 0;
  19345. function schemaAllowsComments(schemaRef) {
  19346. if (schemaRef && typeof schemaRef === 'object') {
  19347. if (schemaRef.allowComments) {
  19348. return true;
  19349. }
  19350. if (schemaRef.allOf) {
  19351. return schemaRef.allOf.some(schemaAllowsComments);
  19352. }
  19353. }
  19354. return false;
  19355. }
  19356. function toDiagnosticSeverity(severityLevel) {
  19357. switch (severityLevel) {
  19358. case 'error': return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Error;
  19359. case 'warning': return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Warning;
  19360. case 'ignore': return void 0;
  19361. }
  19362. return void 0;
  19363. }
  19364. /***/ }),
  19365. /* 94 */
  19366. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  19367. "use strict";
  19368. __webpack_require__.r(__webpack_exports__);
  19369. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnresolvedSchema", function() { return UnresolvedSchema; });
  19370. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ResolvedSchema", function() { return ResolvedSchema; });
  19371. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONSchemaService", function() { return JSONSchemaService; });
  19372. /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(83);
  19373. /* harmony import */ var vscode_uri__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(95);
  19374. /* harmony import */ var _utils_strings__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(91);
  19375. /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(82);
  19376. /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(76);
  19377. /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_4__);
  19378. /*---------------------------------------------------------------------------------------------
  19379. * Copyright (c) Microsoft Corporation. All rights reserved.
  19380. * Licensed under the MIT License. See License.txt in the project root for license information.
  19381. *--------------------------------------------------------------------------------------------*/
  19382. var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_4__["loadMessageBundle"]();
  19383. var FilePatternAssociation = /** @class */ (function () {
  19384. function FilePatternAssociation(pattern) {
  19385. try {
  19386. this.patternRegExp = new RegExp(_utils_strings__WEBPACK_IMPORTED_MODULE_2__["convertSimple2RegExpPattern"](pattern) + '$');
  19387. }
  19388. catch (e) {
  19389. // invalid pattern
  19390. this.patternRegExp = null;
  19391. }
  19392. this.schemas = [];
  19393. }
  19394. FilePatternAssociation.prototype.addSchema = function (id) {
  19395. this.schemas.push(id);
  19396. };
  19397. FilePatternAssociation.prototype.matchesPattern = function (fileName) {
  19398. return this.patternRegExp && this.patternRegExp.test(fileName);
  19399. };
  19400. FilePatternAssociation.prototype.getSchemas = function () {
  19401. return this.schemas;
  19402. };
  19403. return FilePatternAssociation;
  19404. }());
  19405. var SchemaHandle = /** @class */ (function () {
  19406. function SchemaHandle(service, url, unresolvedSchemaContent) {
  19407. this.service = service;
  19408. this.url = url;
  19409. this.dependencies = {};
  19410. if (unresolvedSchemaContent) {
  19411. this.unresolvedSchema = this.service.promise.resolve(new UnresolvedSchema(unresolvedSchemaContent));
  19412. }
  19413. }
  19414. SchemaHandle.prototype.getUnresolvedSchema = function () {
  19415. if (!this.unresolvedSchema) {
  19416. this.unresolvedSchema = this.service.loadSchema(this.url);
  19417. }
  19418. return this.unresolvedSchema;
  19419. };
  19420. SchemaHandle.prototype.getResolvedSchema = function () {
  19421. var _this = this;
  19422. if (!this.resolvedSchema) {
  19423. this.resolvedSchema = this.getUnresolvedSchema().then(function (unresolved) {
  19424. return _this.service.resolveSchemaContent(unresolved, _this.url, _this.dependencies);
  19425. });
  19426. }
  19427. return this.resolvedSchema;
  19428. };
  19429. SchemaHandle.prototype.clearSchema = function () {
  19430. this.resolvedSchema = null;
  19431. this.unresolvedSchema = null;
  19432. this.dependencies = {};
  19433. };
  19434. return SchemaHandle;
  19435. }());
  19436. var UnresolvedSchema = /** @class */ (function () {
  19437. function UnresolvedSchema(schema, errors) {
  19438. if (errors === void 0) { errors = []; }
  19439. this.schema = schema;
  19440. this.errors = errors;
  19441. }
  19442. return UnresolvedSchema;
  19443. }());
  19444. var ResolvedSchema = /** @class */ (function () {
  19445. function ResolvedSchema(schema, errors) {
  19446. if (errors === void 0) { errors = []; }
  19447. this.schema = schema;
  19448. this.errors = errors;
  19449. }
  19450. ResolvedSchema.prototype.getSection = function (path) {
  19451. return _parser_jsonParser__WEBPACK_IMPORTED_MODULE_3__["asSchema"](this.getSectionRecursive(path, this.schema));
  19452. };
  19453. ResolvedSchema.prototype.getSectionRecursive = function (path, schema) {
  19454. if (!schema || typeof schema === 'boolean' || path.length === 0) {
  19455. return schema;
  19456. }
  19457. var next = path.shift();
  19458. if (schema.properties && typeof schema.properties[next]) {
  19459. return this.getSectionRecursive(path, schema.properties[next]);
  19460. }
  19461. else if (schema.patternProperties) {
  19462. for (var _i = 0, _a = Object.keys(schema.patternProperties); _i < _a.length; _i++) {
  19463. var pattern = _a[_i];
  19464. var regex = new RegExp(pattern);
  19465. if (regex.test(next)) {
  19466. return this.getSectionRecursive(path, schema.patternProperties[pattern]);
  19467. }
  19468. }
  19469. }
  19470. else if (typeof schema.additionalProperties === 'object') {
  19471. return this.getSectionRecursive(path, schema.additionalProperties);
  19472. }
  19473. else if (next.match('[0-9]+')) {
  19474. if (Array.isArray(schema.items)) {
  19475. var index = parseInt(next, 10);
  19476. if (!isNaN(index) && schema.items[index]) {
  19477. return this.getSectionRecursive(path, schema.items[index]);
  19478. }
  19479. }
  19480. else if (schema.items) {
  19481. return this.getSectionRecursive(path, schema.items);
  19482. }
  19483. }
  19484. return null;
  19485. };
  19486. return ResolvedSchema;
  19487. }());
  19488. var JSONSchemaService = /** @class */ (function () {
  19489. function JSONSchemaService(requestService, contextService, promiseConstructor) {
  19490. this.contextService = contextService;
  19491. this.requestService = requestService;
  19492. this.promiseConstructor = promiseConstructor || Promise;
  19493. this.callOnDispose = [];
  19494. this.contributionSchemas = {};
  19495. this.contributionAssociations = {};
  19496. this.schemasById = {};
  19497. this.filePatternAssociations = [];
  19498. this.filePatternAssociationById = {};
  19499. this.registeredSchemasIds = {};
  19500. }
  19501. JSONSchemaService.prototype.getRegisteredSchemaIds = function (filter) {
  19502. return Object.keys(this.registeredSchemasIds).filter(function (id) {
  19503. var scheme = vscode_uri__WEBPACK_IMPORTED_MODULE_1__["URI"].parse(id).scheme;
  19504. return scheme !== 'schemaservice' && (!filter || filter(scheme));
  19505. });
  19506. };
  19507. Object.defineProperty(JSONSchemaService.prototype, "promise", {
  19508. get: function () {
  19509. return this.promiseConstructor;
  19510. },
  19511. enumerable: true,
  19512. configurable: true
  19513. });
  19514. JSONSchemaService.prototype.dispose = function () {
  19515. while (this.callOnDispose.length > 0) {
  19516. this.callOnDispose.pop()();
  19517. }
  19518. };
  19519. JSONSchemaService.prototype.onResourceChange = function (uri) {
  19520. var _this = this;
  19521. var hasChanges = false;
  19522. uri = this.normalizeId(uri);
  19523. var toWalk = [uri];
  19524. var all = Object.keys(this.schemasById).map(function (key) { return _this.schemasById[key]; });
  19525. while (toWalk.length) {
  19526. var curr = toWalk.pop();
  19527. for (var i = 0; i < all.length; i++) {
  19528. var handle = all[i];
  19529. if (handle && (handle.url === curr || handle.dependencies[curr])) {
  19530. if (handle.url !== curr) {
  19531. toWalk.push(handle.url);
  19532. }
  19533. handle.clearSchema();
  19534. all[i] = undefined;
  19535. hasChanges = true;
  19536. }
  19537. }
  19538. }
  19539. return hasChanges;
  19540. };
  19541. JSONSchemaService.prototype.normalizeId = function (id) {
  19542. // remove trailing '#', normalize drive capitalization
  19543. try {
  19544. return vscode_uri__WEBPACK_IMPORTED_MODULE_1__["URI"].parse(id).toString();
  19545. }
  19546. catch (e) {
  19547. return id;
  19548. }
  19549. };
  19550. JSONSchemaService.prototype.setSchemaContributions = function (schemaContributions) {
  19551. if (schemaContributions.schemas) {
  19552. var schemas = schemaContributions.schemas;
  19553. for (var id in schemas) {
  19554. var normalizedId = this.normalizeId(id);
  19555. this.contributionSchemas[normalizedId] = this.addSchemaHandle(normalizedId, schemas[id]);
  19556. }
  19557. }
  19558. if (schemaContributions.schemaAssociations) {
  19559. var schemaAssociations = schemaContributions.schemaAssociations;
  19560. for (var pattern in schemaAssociations) {
  19561. var associations = schemaAssociations[pattern];
  19562. this.contributionAssociations[pattern] = associations;
  19563. var fpa = this.getOrAddFilePatternAssociation(pattern);
  19564. for (var _i = 0, associations_1 = associations; _i < associations_1.length; _i++) {
  19565. var schemaId = associations_1[_i];
  19566. var id = this.normalizeId(schemaId);
  19567. fpa.addSchema(id);
  19568. }
  19569. }
  19570. }
  19571. };
  19572. JSONSchemaService.prototype.addSchemaHandle = function (id, unresolvedSchemaContent) {
  19573. var schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent);
  19574. this.schemasById[id] = schemaHandle;
  19575. return schemaHandle;
  19576. };
  19577. JSONSchemaService.prototype.getOrAddSchemaHandle = function (id, unresolvedSchemaContent) {
  19578. return this.schemasById[id] || this.addSchemaHandle(id, unresolvedSchemaContent);
  19579. };
  19580. JSONSchemaService.prototype.getOrAddFilePatternAssociation = function (pattern) {
  19581. var fpa = this.filePatternAssociationById[pattern];
  19582. if (!fpa) {
  19583. fpa = new FilePatternAssociation(pattern);
  19584. this.filePatternAssociationById[pattern] = fpa;
  19585. this.filePatternAssociations.push(fpa);
  19586. }
  19587. return fpa;
  19588. };
  19589. JSONSchemaService.prototype.registerExternalSchema = function (uri, filePatterns, unresolvedSchemaContent) {
  19590. if (filePatterns === void 0) { filePatterns = null; }
  19591. var id = this.normalizeId(uri);
  19592. this.registeredSchemasIds[id] = true;
  19593. if (filePatterns) {
  19594. for (var _i = 0, filePatterns_1 = filePatterns; _i < filePatterns_1.length; _i++) {
  19595. var pattern = filePatterns_1[_i];
  19596. this.getOrAddFilePatternAssociation(pattern).addSchema(id);
  19597. }
  19598. }
  19599. return unresolvedSchemaContent ? this.addSchemaHandle(id, unresolvedSchemaContent) : this.getOrAddSchemaHandle(id);
  19600. };
  19601. JSONSchemaService.prototype.clearExternalSchemas = function () {
  19602. this.schemasById = {};
  19603. this.filePatternAssociations = [];
  19604. this.filePatternAssociationById = {};
  19605. this.registeredSchemasIds = {};
  19606. for (var id in this.contributionSchemas) {
  19607. this.schemasById[id] = this.contributionSchemas[id];
  19608. this.registeredSchemasIds[id] = true;
  19609. }
  19610. for (var pattern in this.contributionAssociations) {
  19611. var fpa = this.getOrAddFilePatternAssociation(pattern);
  19612. for (var _i = 0, _a = this.contributionAssociations[pattern]; _i < _a.length; _i++) {
  19613. var schemaId = _a[_i];
  19614. var id = this.normalizeId(schemaId);
  19615. fpa.addSchema(id);
  19616. }
  19617. }
  19618. };
  19619. JSONSchemaService.prototype.getResolvedSchema = function (schemaId) {
  19620. var id = this.normalizeId(schemaId);
  19621. var schemaHandle = this.schemasById[id];
  19622. if (schemaHandle) {
  19623. return schemaHandle.getResolvedSchema();
  19624. }
  19625. return this.promise.resolve(null);
  19626. };
  19627. JSONSchemaService.prototype.loadSchema = function (url) {
  19628. if (!this.requestService) {
  19629. var errorMessage = localize('json.schema.norequestservice', 'Unable to load schema from \'{0}\'. No schema request service available', toDisplayString(url));
  19630. return this.promise.resolve(new UnresolvedSchema({}, [errorMessage]));
  19631. }
  19632. return this.requestService(url).then(function (content) {
  19633. if (!content) {
  19634. var errorMessage = localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': No content.', toDisplayString(url));
  19635. return new UnresolvedSchema({}, [errorMessage]);
  19636. }
  19637. var schemaContent = {};
  19638. var jsonErrors = [];
  19639. schemaContent = jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["parse"](content, jsonErrors);
  19640. var errors = jsonErrors.length ? [localize('json.schema.invalidFormat', 'Unable to parse content from \'{0}\': Parse error at offset {1}.', toDisplayString(url), jsonErrors[0].offset)] : [];
  19641. return new UnresolvedSchema(schemaContent, errors);
  19642. }, function (error) {
  19643. var errorMessage = error.toString();
  19644. var errorSplit = error.toString().split('Error: ');
  19645. if (errorSplit.length > 1) {
  19646. // more concise error message, URL and context are attached by caller anyways
  19647. errorMessage = errorSplit[1];
  19648. }
  19649. return new UnresolvedSchema({}, [errorMessage]);
  19650. });
  19651. };
  19652. JSONSchemaService.prototype.resolveSchemaContent = function (schemaToResolve, schemaURL, dependencies) {
  19653. var _this = this;
  19654. var resolveErrors = schemaToResolve.errors.slice(0);
  19655. var schema = schemaToResolve.schema;
  19656. var contextService = this.contextService;
  19657. var findSection = function (schema, path) {
  19658. if (!path) {
  19659. return schema;
  19660. }
  19661. var current = schema;
  19662. if (path[0] === '/') {
  19663. path = path.substr(1);
  19664. }
  19665. path.split('/').some(function (part) {
  19666. current = current[part];
  19667. return !current;
  19668. });
  19669. return current;
  19670. };
  19671. var merge = function (target, sourceRoot, sourceURI, path) {
  19672. var section = findSection(sourceRoot, path);
  19673. if (section) {
  19674. for (var key in section) {
  19675. if (section.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
  19676. target[key] = section[key];
  19677. }
  19678. }
  19679. }
  19680. else {
  19681. resolveErrors.push(localize('json.schema.invalidref', '$ref \'{0}\' in \'{1}\' can not be resolved.', path, sourceURI));
  19682. }
  19683. };
  19684. var resolveExternalLink = function (node, uri, linkPath, parentSchemaURL, parentSchemaDependencies) {
  19685. if (contextService && !/^\w+:\/\/.*/.test(uri)) {
  19686. uri = contextService.resolveRelativePath(uri, parentSchemaURL);
  19687. }
  19688. uri = _this.normalizeId(uri);
  19689. var referencedHandle = _this.getOrAddSchemaHandle(uri);
  19690. return referencedHandle.getUnresolvedSchema().then(function (unresolvedSchema) {
  19691. parentSchemaDependencies[uri] = true;
  19692. if (unresolvedSchema.errors.length) {
  19693. var loc = linkPath ? uri + '#' + linkPath : uri;
  19694. resolveErrors.push(localize('json.schema.problemloadingref', 'Problems loading reference \'{0}\': {1}', loc, unresolvedSchema.errors[0]));
  19695. }
  19696. merge(node, unresolvedSchema.schema, uri, linkPath);
  19697. return resolveRefs(node, unresolvedSchema.schema, uri, referencedHandle.dependencies);
  19698. });
  19699. };
  19700. var resolveRefs = function (node, parentSchema, parentSchemaURL, parentSchemaDependencies) {
  19701. if (!node || typeof node !== 'object') {
  19702. return Promise.resolve(null);
  19703. }
  19704. var toWalk = [node];
  19705. var seen = [];
  19706. var openPromises = [];
  19707. var collectEntries = function () {
  19708. var entries = [];
  19709. for (var _i = 0; _i < arguments.length; _i++) {
  19710. entries[_i] = arguments[_i];
  19711. }
  19712. for (var _a = 0, entries_1 = entries; _a < entries_1.length; _a++) {
  19713. var entry = entries_1[_a];
  19714. if (typeof entry === 'object') {
  19715. toWalk.push(entry);
  19716. }
  19717. }
  19718. };
  19719. var collectMapEntries = function () {
  19720. var maps = [];
  19721. for (var _i = 0; _i < arguments.length; _i++) {
  19722. maps[_i] = arguments[_i];
  19723. }
  19724. for (var _a = 0, maps_1 = maps; _a < maps_1.length; _a++) {
  19725. var map = maps_1[_a];
  19726. if (typeof map === 'object') {
  19727. for (var key in map) {
  19728. var entry = map[key];
  19729. if (typeof entry === 'object') {
  19730. toWalk.push(entry);
  19731. }
  19732. }
  19733. }
  19734. }
  19735. };
  19736. var collectArrayEntries = function () {
  19737. var arrays = [];
  19738. for (var _i = 0; _i < arguments.length; _i++) {
  19739. arrays[_i] = arguments[_i];
  19740. }
  19741. for (var _a = 0, arrays_1 = arrays; _a < arrays_1.length; _a++) {
  19742. var array = arrays_1[_a];
  19743. if (Array.isArray(array)) {
  19744. for (var _b = 0, array_1 = array; _b < array_1.length; _b++) {
  19745. var entry = array_1[_b];
  19746. if (typeof entry === 'object') {
  19747. toWalk.push(entry);
  19748. }
  19749. }
  19750. }
  19751. }
  19752. };
  19753. var handleRef = function (next) {
  19754. var seenRefs = [];
  19755. while (next.$ref) {
  19756. var ref = next.$ref;
  19757. var segments = ref.split('#', 2);
  19758. delete next.$ref;
  19759. if (segments[0].length > 0) {
  19760. openPromises.push(resolveExternalLink(next, segments[0], segments[1], parentSchemaURL, parentSchemaDependencies));
  19761. return;
  19762. }
  19763. else {
  19764. if (seenRefs.indexOf(ref) === -1) {
  19765. merge(next, parentSchema, parentSchemaURL, segments[1]); // can set next.$ref again, use seenRefs to avoid circle
  19766. seenRefs.push(ref);
  19767. }
  19768. }
  19769. }
  19770. collectEntries(next.items, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else);
  19771. collectMapEntries(next.definitions, next.properties, next.patternProperties, next.dependencies);
  19772. collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.items);
  19773. };
  19774. while (toWalk.length) {
  19775. var next = toWalk.pop();
  19776. if (seen.indexOf(next) >= 0) {
  19777. continue;
  19778. }
  19779. seen.push(next);
  19780. handleRef(next);
  19781. }
  19782. return _this.promise.all(openPromises);
  19783. };
  19784. return resolveRefs(schema, schema, schemaURL, dependencies).then(function (_) { return new ResolvedSchema(schema, resolveErrors); });
  19785. };
  19786. JSONSchemaService.prototype.getSchemaForResource = function (resource, document) {
  19787. // first use $schema if present
  19788. if (document && document.root && document.root.type === 'object') {
  19789. var schemaProperties = document.root.properties.filter(function (p) { return (p.keyNode.value === '$schema') && p.valueNode && p.valueNode.type === 'string'; });
  19790. if (schemaProperties.length > 0) {
  19791. var schemeId = _parser_jsonParser__WEBPACK_IMPORTED_MODULE_3__["getNodeValue"](schemaProperties[0].valueNode);
  19792. if (schemeId && _utils_strings__WEBPACK_IMPORTED_MODULE_2__["startsWith"](schemeId, '.') && this.contextService) {
  19793. schemeId = this.contextService.resolveRelativePath(schemeId, resource);
  19794. }
  19795. if (schemeId) {
  19796. var id = this.normalizeId(schemeId);
  19797. return this.getOrAddSchemaHandle(id).getResolvedSchema();
  19798. }
  19799. }
  19800. }
  19801. var seen = Object.create(null);
  19802. var schemas = [];
  19803. for (var _i = 0, _a = this.filePatternAssociations; _i < _a.length; _i++) {
  19804. var entry = _a[_i];
  19805. if (entry.matchesPattern(resource)) {
  19806. for (var _b = 0, _c = entry.getSchemas(); _b < _c.length; _b++) {
  19807. var schemaId = _c[_b];
  19808. if (!seen[schemaId]) {
  19809. schemas.push(schemaId);
  19810. seen[schemaId] = true;
  19811. }
  19812. }
  19813. }
  19814. }
  19815. if (schemas.length > 0) {
  19816. return this.createCombinedSchema(resource, schemas).getResolvedSchema();
  19817. }
  19818. return this.promise.resolve(null);
  19819. };
  19820. JSONSchemaService.prototype.createCombinedSchema = function (resource, schemaIds) {
  19821. if (schemaIds.length === 1) {
  19822. return this.getOrAddSchemaHandle(schemaIds[0]);
  19823. }
  19824. else {
  19825. var combinedSchemaId = 'schemaservice://combinedSchema/' + encodeURIComponent(resource);
  19826. var combinedSchema = {
  19827. allOf: schemaIds.map(function (schemaId) { return ({ $ref: schemaId }); })
  19828. };
  19829. return this.addSchemaHandle(combinedSchemaId, combinedSchema);
  19830. }
  19831. };
  19832. return JSONSchemaService;
  19833. }());
  19834. function toDisplayString(url) {
  19835. try {
  19836. var uri = vscode_uri__WEBPACK_IMPORTED_MODULE_1__["URI"].parse(url);
  19837. if (uri.scheme === 'file') {
  19838. return uri.fsPath;
  19839. }
  19840. }
  19841. catch (e) {
  19842. // ignore
  19843. }
  19844. return url;
  19845. }
  19846. /***/ }),
  19847. /* 95 */
  19848. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  19849. "use strict";
  19850. __webpack_require__.r(__webpack_exports__);
  19851. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setUriThrowOnMissingScheme", function() { return setUriThrowOnMissingScheme; });
  19852. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return URI; });
  19853. /*---------------------------------------------------------------------------------------------
  19854. * Copyright (c) Microsoft Corporation. All rights reserved.
  19855. * Licensed under the MIT License. See License.txt in the project root for license information.
  19856. *--------------------------------------------------------------------------------------------*/
  19857. var __extends = (undefined && undefined.__extends) || (function () {
  19858. var extendStatics = Object.setPrototypeOf ||
  19859. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  19860. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  19861. return function (d, b) {
  19862. extendStatics(d, b);
  19863. function __() { this.constructor = d; }
  19864. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19865. };
  19866. })();
  19867. var isWindows;
  19868. if (typeof process === 'object') {
  19869. isWindows = process.platform === 'win32';
  19870. }
  19871. else if (typeof navigator === 'object') {
  19872. var userAgent = navigator.userAgent;
  19873. isWindows = userAgent.indexOf('Windows') >= 0;
  19874. }
  19875. //#endregion
  19876. var _schemePattern = /^\w[\w\d+.-]*$/;
  19877. var _singleSlashStart = /^\//;
  19878. var _doubleSlashStart = /^\/\//;
  19879. var _throwOnMissingSchema = true;
  19880. /**
  19881. * @internal
  19882. */
  19883. function setUriThrowOnMissingScheme(value) {
  19884. var old = _throwOnMissingSchema;
  19885. _throwOnMissingSchema = value;
  19886. return old;
  19887. }
  19888. function _validateUri(ret, _strict) {
  19889. // scheme, must be set
  19890. if (!ret.scheme) {
  19891. if (_strict || _throwOnMissingSchema) {
  19892. throw new Error("[UriError]: Scheme is missing: {scheme: \"\", authority: \"" + ret.authority + "\", path: \"" + ret.path + "\", query: \"" + ret.query + "\", fragment: \"" + ret.fragment + "\"}");
  19893. }
  19894. else {
  19895. // console.warn(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`);
  19896. }
  19897. }
  19898. // scheme, https://tools.ietf.org/html/rfc3986#section-3.1
  19899. // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  19900. if (ret.scheme && !_schemePattern.test(ret.scheme)) {
  19901. throw new Error('[UriError]: Scheme contains illegal characters.');
  19902. }
  19903. // path, http://tools.ietf.org/html/rfc3986#section-3.3
  19904. // If a URI contains an authority component, then the path component
  19905. // must either be empty or begin with a slash ("/") character. If a URI
  19906. // does not contain an authority component, then the path cannot begin
  19907. // with two slash characters ("//").
  19908. if (ret.path) {
  19909. if (ret.authority) {
  19910. if (!_singleSlashStart.test(ret.path)) {
  19911. throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
  19912. }
  19913. }
  19914. else {
  19915. if (_doubleSlashStart.test(ret.path)) {
  19916. throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
  19917. }
  19918. }
  19919. }
  19920. }
  19921. // for a while we allowed uris *without* schemes and this is the migration
  19922. // for them, e.g. an uri without scheme and without strict-mode warns and falls
  19923. // back to the file-scheme. that should cause the least carnage and still be a
  19924. // clear warning
  19925. function _schemeFix(scheme, _strict) {
  19926. if (_strict || _throwOnMissingSchema) {
  19927. return scheme || _empty;
  19928. }
  19929. if (!scheme) {
  19930. // console.trace('BAD uri lacks scheme, falling back to file-scheme.');
  19931. scheme = 'file';
  19932. }
  19933. return scheme;
  19934. }
  19935. // implements a bit of https://tools.ietf.org/html/rfc3986#section-5
  19936. function _referenceResolution(scheme, path) {
  19937. // the slash-character is our 'default base' as we don't
  19938. // support constructing URIs relative to other URIs. This
  19939. // also means that we alter and potentially break paths.
  19940. // see https://tools.ietf.org/html/rfc3986#section-5.1.4
  19941. switch (scheme) {
  19942. case 'https':
  19943. case 'http':
  19944. case 'file':
  19945. if (!path) {
  19946. path = _slash;
  19947. }
  19948. else if (path[0] !== _slash) {
  19949. path = _slash + path;
  19950. }
  19951. break;
  19952. }
  19953. return path;
  19954. }
  19955. var _empty = '';
  19956. var _slash = '/';
  19957. var _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
  19958. function _isQueryStringScheme(scheme) {
  19959. if (!scheme) {
  19960. return false;
  19961. }
  19962. switch (scheme.toLowerCase()) {
  19963. case 'http':
  19964. case 'https':
  19965. case 'ftp':
  19966. return true;
  19967. }
  19968. return false;
  19969. }
  19970. /**
  19971. * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
  19972. * This class is a simple parser which creates the basic component parts
  19973. * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
  19974. * and encoding.
  19975. *
  19976. * foo://example.com:8042/over/there?name=ferret#nose
  19977. * \_/ \______________/\_________/ \_________/ \__/
  19978. * | | | | |
  19979. * scheme authority path query fragment
  19980. * | _____________________|__
  19981. * / \ / \
  19982. * urn:example:animal:ferret:nose
  19983. */
  19984. var URI = (function () {
  19985. /**
  19986. * @internal
  19987. */
  19988. function URI(schemeOrData, authority, path, query, fragment, _strict) {
  19989. if (_strict === void 0) { _strict = false; }
  19990. if (typeof schemeOrData === 'object') {
  19991. this.scheme = schemeOrData.scheme || _empty;
  19992. this.authority = schemeOrData.authority || _empty;
  19993. this.path = schemeOrData.path || _empty;
  19994. this.query = schemeOrData.query || _empty;
  19995. this.fragment = schemeOrData.fragment || _empty;
  19996. // no validation because it's this URI
  19997. // that creates uri components.
  19998. // _validateUri(this);
  19999. }
  20000. else {
  20001. this.scheme = _schemeFix(schemeOrData, _strict);
  20002. this.authority = authority || _empty;
  20003. this.path = _referenceResolution(this.scheme, path || _empty);
  20004. this.query = query || _empty;
  20005. this.fragment = fragment || _empty;
  20006. _validateUri(this, _strict);
  20007. }
  20008. }
  20009. URI.isUri = function (thing) {
  20010. if (thing instanceof URI) {
  20011. return true;
  20012. }
  20013. if (!thing) {
  20014. return false;
  20015. }
  20016. return typeof thing.authority === 'string'
  20017. && typeof thing.fragment === 'string'
  20018. && typeof thing.path === 'string'
  20019. && typeof thing.query === 'string'
  20020. && typeof thing.scheme === 'string'
  20021. && typeof thing.fsPath === 'function'
  20022. && typeof thing.with === 'function'
  20023. && typeof thing.toString === 'function';
  20024. };
  20025. Object.defineProperty(URI.prototype, "fsPath", {
  20026. // ---- filesystem path -----------------------
  20027. /**
  20028. * Returns a string representing the corresponding file system path of this URI.
  20029. * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
  20030. * platform specific path separator.
  20031. *
  20032. * * Will *not* validate the path for invalid characters and semantics.
  20033. * * Will *not* look at the scheme of this URI.
  20034. * * The result shall *not* be used for display purposes but for accessing a file on disk.
  20035. *
  20036. *
  20037. * The *difference* to `URI#path` is the use of the platform specific separator and the handling
  20038. * of UNC paths. See the below sample of a file-uri with an authority (UNC path).
  20039. *
  20040. * ```ts
  20041. const u = URI.parse('file://server/c$/folder/file.txt')
  20042. u.authority === 'server'
  20043. u.path === '/shares/c$/file.txt'
  20044. u.fsPath === '\\server\c$\folder\file.txt'
  20045. ```
  20046. *
  20047. * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,
  20048. * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working
  20049. * with URIs that represent files on disk (`file` scheme).
  20050. */
  20051. get: function () {
  20052. // if (this.scheme !== 'file') {
  20053. // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
  20054. // }
  20055. return _makeFsPath(this);
  20056. },
  20057. enumerable: true,
  20058. configurable: true
  20059. });
  20060. // ---- modify to new -------------------------
  20061. URI.prototype.with = function (change) {
  20062. if (!change) {
  20063. return this;
  20064. }
  20065. var scheme = change.scheme, authority = change.authority, path = change.path, query = change.query, fragment = change.fragment;
  20066. if (scheme === undefined) {
  20067. scheme = this.scheme;
  20068. }
  20069. else if (scheme === null) {
  20070. scheme = _empty;
  20071. }
  20072. if (authority === undefined) {
  20073. authority = this.authority;
  20074. }
  20075. else if (authority === null) {
  20076. authority = _empty;
  20077. }
  20078. if (path === undefined) {
  20079. path = this.path;
  20080. }
  20081. else if (path === null) {
  20082. path = _empty;
  20083. }
  20084. if (query === undefined) {
  20085. query = this.query;
  20086. }
  20087. else if (query === null) {
  20088. query = _empty;
  20089. }
  20090. if (fragment === undefined) {
  20091. fragment = this.fragment;
  20092. }
  20093. else if (fragment === null) {
  20094. fragment = _empty;
  20095. }
  20096. if (scheme === this.scheme
  20097. && authority === this.authority
  20098. && path === this.path
  20099. && query === this.query
  20100. && fragment === this.fragment) {
  20101. return this;
  20102. }
  20103. return new _URI(scheme, authority, path, query, fragment);
  20104. };
  20105. // ---- parse & validate ------------------------
  20106. /**
  20107. * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`,
  20108. * `file:///usr/home`, or `scheme:with/path`.
  20109. *
  20110. * @param value A string which represents an URI (see `URI#toString`).
  20111. */
  20112. URI.parse = function (value, _strict) {
  20113. if (_strict === void 0) { _strict = false; }
  20114. var match = _regexp.exec(value);
  20115. if (!match) {
  20116. return new _URI(_empty, _empty, _empty, _empty, _empty, _strict);
  20117. }
  20118. return new _URI(match[2] || _empty, decodeURIComponentFast(match[4] || _empty, false, false), decodeURIComponentFast(match[5] || _empty, true, false), decodeURIComponentFast(match[7] || _empty, false, _isQueryStringScheme(match[2])), decodeURIComponentFast(match[9] || _empty, false, false), _strict);
  20119. };
  20120. /**
  20121. * Creates a new URI from a file system path, e.g. `c:\my\files`,
  20122. * `/usr/home`, or `\\server\share\some\path`.
  20123. *
  20124. * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
  20125. * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
  20126. * `URI.parse('file://' + path)` because the path might contain characters that are
  20127. * interpreted (# and ?). See the following sample:
  20128. * ```ts
  20129. const good = URI.file('/coding/c#/project1');
  20130. good.scheme === 'file';
  20131. good.path === '/coding/c#/project1';
  20132. good.fragment === '';
  20133. const bad = URI.parse('file://' + '/coding/c#/project1');
  20134. bad.scheme === 'file';
  20135. bad.path === '/coding/c'; // path is now broken
  20136. bad.fragment === '/project1';
  20137. ```
  20138. *
  20139. * @param path A file system path (see `URI#fsPath`)
  20140. */
  20141. URI.file = function (path) {
  20142. var authority = _empty;
  20143. // normalize to fwd-slashes on windows,
  20144. // on other systems bwd-slashes are valid
  20145. // filename character, e.g. /f\oo/ba\r.txt
  20146. if (isWindows) {
  20147. path = path.replace(/\\/g, _slash);
  20148. }
  20149. // check for authority as used in UNC shares
  20150. // or use the path as given
  20151. if (path[0] === _slash && path[1] === _slash) {
  20152. var idx = path.indexOf(_slash, 2);
  20153. if (idx === -1) {
  20154. authority = path.substring(2);
  20155. path = _slash;
  20156. }
  20157. else {
  20158. authority = path.substring(2, idx);
  20159. path = path.substring(idx) || _slash;
  20160. }
  20161. }
  20162. return new _URI('file', authority, path, _empty, _empty);
  20163. };
  20164. URI.from = function (components) {
  20165. return new _URI(components.scheme, components.authority, components.path, components.query, components.fragment);
  20166. };
  20167. // ---- printing/externalize ---------------------------
  20168. /**
  20169. * Creates a string representation for this URI. It's guaranteed that calling
  20170. * `URI.parse` with the result of this function creates an URI which is equal
  20171. * to this URI.
  20172. *
  20173. * * The result shall *not* be used for display purposes but for externalization or transport.
  20174. * * The result will be encoded using the percentage encoding and encoding happens mostly
  20175. * ignore the scheme-specific encoding rules.
  20176. *
  20177. * @param skipEncoding Do not encode the result, default is `false`
  20178. */
  20179. URI.prototype.toString = function (skipEncoding) {
  20180. if (skipEncoding === void 0) { skipEncoding = false; }
  20181. return _asFormatted(this, skipEncoding);
  20182. };
  20183. URI.prototype.toJSON = function () {
  20184. return this;
  20185. };
  20186. URI.revive = function (data) {
  20187. if (!data) {
  20188. return data;
  20189. }
  20190. else if (data instanceof URI) {
  20191. return data;
  20192. }
  20193. else {
  20194. var result = new _URI(data);
  20195. result._formatted = data.external;
  20196. result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null;
  20197. return result;
  20198. }
  20199. };
  20200. return URI;
  20201. }());
  20202. var _pathSepMarker = isWindows ? 1 : undefined;
  20203. // tslint:disable-next-line:class-name
  20204. var _URI = (function (_super) {
  20205. __extends(_URI, _super);
  20206. function _URI() {
  20207. var _this = _super !== null && _super.apply(this, arguments) || this;
  20208. _this._formatted = null;
  20209. _this._fsPath = null;
  20210. return _this;
  20211. }
  20212. Object.defineProperty(_URI.prototype, "fsPath", {
  20213. get: function () {
  20214. if (!this._fsPath) {
  20215. this._fsPath = _makeFsPath(this);
  20216. }
  20217. return this._fsPath;
  20218. },
  20219. enumerable: true,
  20220. configurable: true
  20221. });
  20222. _URI.prototype.toString = function (skipEncoding) {
  20223. if (skipEncoding === void 0) { skipEncoding = false; }
  20224. if (!skipEncoding) {
  20225. if (!this._formatted) {
  20226. this._formatted = _asFormatted(this, false);
  20227. }
  20228. return this._formatted;
  20229. }
  20230. else {
  20231. // we don't cache that
  20232. return _asFormatted(this, true);
  20233. }
  20234. };
  20235. _URI.prototype.toJSON = function () {
  20236. var res = {
  20237. $mid: 1
  20238. };
  20239. // cached state
  20240. if (this._fsPath) {
  20241. res.fsPath = this._fsPath;
  20242. res._sep = _pathSepMarker;
  20243. }
  20244. if (this._formatted) {
  20245. res.external = this._formatted;
  20246. }
  20247. // uri components
  20248. if (this.path) {
  20249. res.path = this.path;
  20250. }
  20251. if (this.scheme) {
  20252. res.scheme = this.scheme;
  20253. }
  20254. if (this.authority) {
  20255. res.authority = this.authority;
  20256. }
  20257. if (this.query) {
  20258. res.query = this.query;
  20259. }
  20260. if (this.fragment) {
  20261. res.fragment = this.fragment;
  20262. }
  20263. return res;
  20264. };
  20265. return _URI;
  20266. }(URI));
  20267. function isHex(value, pos) {
  20268. if (pos >= value.length) {
  20269. return false;
  20270. }
  20271. var code = value.charCodeAt(pos);
  20272. return (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */) // 0-9
  20273. || (code >= 97 /* a */ && code <= 102 /* f */) //a-f
  20274. || (code >= 65 /* A */ && code <= 70 /* F */); //A-F
  20275. }
  20276. function decodeURIComponentFast(uriComponent, isPath, isQueryString) {
  20277. var res;
  20278. var nativeDecodePos = -1;
  20279. for (var pos = 0; pos < uriComponent.length; pos++) {
  20280. var code = uriComponent.charCodeAt(pos);
  20281. // decoding needed
  20282. if (code === 37 /* PercentSign */ && isHex(uriComponent, pos + 1) && isHex(uriComponent, pos + 2)) {
  20283. var chA = uriComponent.charCodeAt(pos + 1);
  20284. var chB = uriComponent.charCodeAt(pos + 2);
  20285. // when in a path -> check and accept %2f and %2F (fwd slash)
  20286. // when in a query string -> check and accept %3D, %26, and %3B (equals, ampersand, semi-colon)
  20287. if ((isPath && chA === 50 /* Digit2 */ && (chB === 70 /* F */ || chB === 102 /* f */))
  20288. ||
  20289. (isQueryString && ((chA === 50 /* Digit2 */ && chB === 54 /* Digit6 */) // %26
  20290. ||
  20291. (chA === 51 /* Digit3 */ && (chB === 66 /* B */ || chB === 98 /* b */ || chB === 68 /* D */ || chB === 100 /* d */)) // %3D, %3D
  20292. ))) {
  20293. if (nativeDecodePos !== -1) {
  20294. res += decodeURIComponent(uriComponent.substring(nativeDecodePos, pos));
  20295. nativeDecodePos = -1;
  20296. }
  20297. if (res !== undefined) {
  20298. res += uriComponent.substr(pos, 3);
  20299. }
  20300. pos += 2;
  20301. continue;
  20302. }
  20303. if (res === undefined) {
  20304. res = uriComponent.substring(0, pos);
  20305. }
  20306. if (nativeDecodePos === -1) {
  20307. nativeDecodePos = pos;
  20308. }
  20309. pos += 2;
  20310. }
  20311. else {
  20312. if (nativeDecodePos !== -1) {
  20313. res += decodeURIComponent(uriComponent.substring(nativeDecodePos, pos));
  20314. nativeDecodePos = -1;
  20315. }
  20316. if (res !== undefined) {
  20317. res += String.fromCharCode(code);
  20318. }
  20319. }
  20320. }
  20321. if (nativeDecodePos !== -1) {
  20322. res += decodeURIComponent(uriComponent.substr(nativeDecodePos));
  20323. }
  20324. return res !== undefined ? res : uriComponent;
  20325. }
  20326. // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
  20327. var encodeTable = (_a = {},
  20328. _a[58 /* Colon */] = '%3A',
  20329. _a[47 /* Slash */] = '%2F',
  20330. _a[63 /* QuestionMark */] = '%3F',
  20331. _a[35 /* Hash */] = '%23',
  20332. _a[91 /* OpenSquareBracket */] = '%5B',
  20333. _a[93 /* CloseSquareBracket */] = '%5D',
  20334. _a[64 /* AtSign */] = '%40',
  20335. _a[33 /* ExclamationMark */] = '%21',
  20336. _a[36 /* DollarSign */] = '%24',
  20337. _a[38 /* Ampersand */] = '%26',
  20338. _a[39 /* SingleQuote */] = '%27',
  20339. _a[40 /* OpenParen */] = '%28',
  20340. _a[41 /* CloseParen */] = '%29',
  20341. _a[42 /* Asterisk */] = '%2A',
  20342. _a[43 /* Plus */] = '%2B',
  20343. _a[44 /* Comma */] = '%2C',
  20344. _a[59 /* Semicolon */] = '%3B',
  20345. _a[61 /* Equals */] = '%3D',
  20346. _a[32 /* Space */] = '%20',
  20347. _a);
  20348. function encodeURIComponentFast(uriComponent, isPath, isQueryString) {
  20349. var res = undefined;
  20350. var nativeEncodePos = -1;
  20351. for (var pos = 0; pos < uriComponent.length; pos++) {
  20352. var code = uriComponent.charCodeAt(pos);
  20353. // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3
  20354. if ((code >= 97 /* a */ && code <= 122 /* z */)
  20355. || (code >= 65 /* A */ && code <= 90 /* Z */)
  20356. || (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */)
  20357. || code === 45 /* Dash */
  20358. || code === 46 /* Period */
  20359. || code === 95 /* Underline */
  20360. || code === 126 /* Tilde */
  20361. || (isPath && code === 47 /* Slash */) // path => allow slash AS-IS
  20362. || (isQueryString && (code === 61 /* Equals */ || code === 38 /* Ampersand */ || code === 59 /* Semicolon */)) // query string => allow &=;
  20363. ) {
  20364. // check if we are delaying native encode
  20365. if (nativeEncodePos !== -1) {
  20366. res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
  20367. nativeEncodePos = -1;
  20368. }
  20369. // check if we write into a new string (by default we try to return the param)
  20370. if (res !== undefined) {
  20371. res += uriComponent.charAt(pos);
  20372. }
  20373. }
  20374. else if (code === 37 /* PercentSign */ && isHex(uriComponent, pos + 1) && isHex(uriComponent, pos + 2)) {
  20375. // at percentage encoded value
  20376. // check if we are delaying native encode
  20377. if (nativeEncodePos !== -1) {
  20378. res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
  20379. nativeEncodePos = -1;
  20380. }
  20381. // check if we write into a new string (by default we try to return the param)
  20382. if (res !== undefined) {
  20383. res += uriComponent.substr(pos, 3);
  20384. }
  20385. pos += 2;
  20386. }
  20387. else {
  20388. // encoding needed, we need to allocate a new string
  20389. if (res === undefined) {
  20390. res = uriComponent.substr(0, pos);
  20391. }
  20392. // check with default table first
  20393. var escaped = encodeTable[code];
  20394. if (escaped !== undefined) {
  20395. // check if we are delaying native encode
  20396. if (nativeEncodePos !== -1) {
  20397. res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
  20398. nativeEncodePos = -1;
  20399. }
  20400. // append escaped variant to result
  20401. res += escaped;
  20402. }
  20403. else if (nativeEncodePos === -1) {
  20404. // use native encode only when needed
  20405. nativeEncodePos = pos;
  20406. }
  20407. }
  20408. }
  20409. if (nativeEncodePos !== -1) {
  20410. res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
  20411. }
  20412. return res !== undefined ? res : uriComponent;
  20413. }
  20414. function encodeURIComponentMinimal(path) {
  20415. var res = undefined;
  20416. for (var pos = 0; pos < path.length; pos++) {
  20417. var code = path.charCodeAt(pos);
  20418. if (code === 35 /* Hash */ || code === 63 /* QuestionMark */) {
  20419. if (res === undefined) {
  20420. res = path.substr(0, pos);
  20421. }
  20422. res += encodeTable[code];
  20423. }
  20424. else {
  20425. if (res !== undefined) {
  20426. res += path[pos];
  20427. }
  20428. }
  20429. }
  20430. return res !== undefined ? res : path;
  20431. }
  20432. /**
  20433. * Compute `fsPath` for the given uri
  20434. */
  20435. function _makeFsPath(uri) {
  20436. var value;
  20437. if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') {
  20438. // unc path: file://shares/c$/far/boo
  20439. value = "//" + uri.authority + uri.path;
  20440. }
  20441. else if (uri.path.charCodeAt(0) === 47 /* Slash */
  20442. && (uri.path.charCodeAt(1) >= 65 /* A */ && uri.path.charCodeAt(1) <= 90 /* Z */ || uri.path.charCodeAt(1) >= 97 /* a */ && uri.path.charCodeAt(1) <= 122 /* z */)
  20443. && uri.path.charCodeAt(2) === 58 /* Colon */) {
  20444. // windows drive letter: file:///c:/far/boo
  20445. value = uri.path[1].toLowerCase() + uri.path.substr(2);
  20446. }
  20447. else {
  20448. // other path
  20449. value = uri.path;
  20450. }
  20451. if (isWindows) {
  20452. value = value.replace(/\//g, '\\');
  20453. }
  20454. return value;
  20455. }
  20456. /**
  20457. * Create the external version of a uri
  20458. */
  20459. function _asFormatted(uri, skipEncoding) {
  20460. var encoder = !skipEncoding
  20461. ? encodeURIComponentFast
  20462. : encodeURIComponentMinimal;
  20463. var res = '';
  20464. var scheme = uri.scheme, authority = uri.authority, path = uri.path, query = uri.query, fragment = uri.fragment;
  20465. if (scheme) {
  20466. res += scheme;
  20467. res += ':';
  20468. }
  20469. if (authority || scheme === 'file') {
  20470. res += _slash;
  20471. res += _slash;
  20472. }
  20473. if (authority) {
  20474. var idx = authority.indexOf('@');
  20475. if (idx !== -1) {
  20476. // <user>@<auth>
  20477. var userinfo = authority.substr(0, idx);
  20478. authority = authority.substr(idx + 1);
  20479. idx = userinfo.indexOf(':');
  20480. if (idx === -1) {
  20481. res += encoder(userinfo, false, false);
  20482. }
  20483. else {
  20484. // <user>:<pass>@<auth>
  20485. res += encoder(userinfo.substr(0, idx), false, false);
  20486. res += ':';
  20487. res += encoder(userinfo.substr(idx + 1), false, false);
  20488. }
  20489. res += '@';
  20490. }
  20491. authority = authority.toLowerCase();
  20492. idx = authority.indexOf(':');
  20493. if (idx === -1) {
  20494. res += encoder(authority, false, false);
  20495. }
  20496. else {
  20497. // <auth>:<port>
  20498. res += encoder(authority.substr(0, idx), false, false);
  20499. res += authority.substr(idx);
  20500. }
  20501. }
  20502. if (path) {
  20503. // lower-case windows drive letters in /C:/fff or C:/fff
  20504. if (path.length >= 3 && path.charCodeAt(0) === 47 /* Slash */ && path.charCodeAt(2) === 58 /* Colon */) {
  20505. var code = path.charCodeAt(1);
  20506. if (code >= 65 /* A */ && code <= 90 /* Z */) {
  20507. path = "/" + String.fromCharCode(code + 32) + ":" + path.substr(3); // "/c:".length === 3
  20508. }
  20509. }
  20510. else if (path.length >= 2 && path.charCodeAt(1) === 58 /* Colon */) {
  20511. var code = path.charCodeAt(0);
  20512. if (code >= 65 /* A */ && code <= 90 /* Z */) {
  20513. path = String.fromCharCode(code + 32) + ":" + path.substr(2); // "/c:".length === 3
  20514. }
  20515. }
  20516. // encode the rest of the path
  20517. res += encoder(path, true, false);
  20518. }
  20519. if (query) {
  20520. res += '?';
  20521. res += encoder(query, false, _isQueryStringScheme(scheme));
  20522. }
  20523. if (fragment) {
  20524. res += '#';
  20525. res += !skipEncoding ? encodeURIComponentFast(fragment, false, false) : fragment;
  20526. }
  20527. return res;
  20528. }
  20529. var _a;
  20530. /***/ }),
  20531. /* 96 */
  20532. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  20533. "use strict";
  20534. __webpack_require__.r(__webpack_exports__);
  20535. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONDocumentSymbols", function() { return JSONDocumentSymbols; });
  20536. /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82);
  20537. /* harmony import */ var _utils_strings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(91);
  20538. /* harmony import */ var _utils_colors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97);
  20539. /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(80);
  20540. /*---------------------------------------------------------------------------------------------
  20541. * Copyright (c) Microsoft Corporation. All rights reserved.
  20542. * Licensed under the MIT License. See License.txt in the project root for license information.
  20543. *--------------------------------------------------------------------------------------------*/
  20544. var JSONDocumentSymbols = /** @class */ (function () {
  20545. function JSONDocumentSymbols(schemaService) {
  20546. this.schemaService = schemaService;
  20547. }
  20548. JSONDocumentSymbols.prototype.findDocumentSymbols = function (document, doc) {
  20549. var _this = this;
  20550. var root = doc.root;
  20551. if (!root) {
  20552. return null;
  20553. }
  20554. // special handling for key bindings
  20555. var resourceString = document.uri;
  20556. if ((resourceString === 'vscode://defaultsettings/keybindings.json') || _utils_strings__WEBPACK_IMPORTED_MODULE_1__["endsWith"](resourceString.toLowerCase(), '/user/keybindings.json')) {
  20557. if (root.type === 'array') {
  20558. var result_1 = [];
  20559. root.items.forEach(function (item) {
  20560. if (item.type === 'object') {
  20561. for (var _i = 0, _a = item.properties; _i < _a.length; _i++) {
  20562. var property = _a[_i];
  20563. if (property.keyNode.value === 'key') {
  20564. if (property.valueNode) {
  20565. if (property.valueNode) {
  20566. var location = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["Location"].create(document.uri, getRange(document, item));
  20567. result_1.push({ name: _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](property.valueNode), kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Function, location: location });
  20568. }
  20569. return;
  20570. }
  20571. }
  20572. }
  20573. }
  20574. });
  20575. return result_1;
  20576. }
  20577. }
  20578. var collectOutlineEntries = function (result, node, containerName) {
  20579. if (node.type === 'array') {
  20580. node.items.forEach(function (node) { return collectOutlineEntries(result, node, containerName); });
  20581. }
  20582. else if (node.type === 'object') {
  20583. node.properties.forEach(function (property) {
  20584. var location = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["Location"].create(document.uri, getRange(document, property));
  20585. var valueNode = property.valueNode;
  20586. if (valueNode) {
  20587. var childContainerName = containerName ? containerName + '.' + property.keyNode.value : property.keyNode.value;
  20588. result.push({ name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), location: location, containerName: containerName });
  20589. collectOutlineEntries(result, valueNode, childContainerName);
  20590. }
  20591. });
  20592. }
  20593. return result;
  20594. };
  20595. var result = collectOutlineEntries([], root, void 0);
  20596. return result;
  20597. };
  20598. JSONDocumentSymbols.prototype.findDocumentSymbols2 = function (document, doc) {
  20599. var _this = this;
  20600. var root = doc.root;
  20601. if (!root) {
  20602. return null;
  20603. }
  20604. // special handling for key bindings
  20605. var resourceString = document.uri;
  20606. if ((resourceString === 'vscode://defaultsettings/keybindings.json') || _utils_strings__WEBPACK_IMPORTED_MODULE_1__["endsWith"](resourceString.toLowerCase(), '/user/keybindings.json')) {
  20607. if (root.type === 'array') {
  20608. var result_2 = [];
  20609. root.items.forEach(function (item) {
  20610. if (item.type === 'object') {
  20611. for (var _i = 0, _a = item.properties; _i < _a.length; _i++) {
  20612. var property = _a[_i];
  20613. if (property.keyNode.value === 'key') {
  20614. if (property.valueNode) {
  20615. var range = getRange(document, item);
  20616. var selectionRange = getRange(document, property.keyNode);
  20617. result_2.push({ name: _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](property.valueNode), kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Function, range: range, selectionRange: selectionRange });
  20618. }
  20619. return;
  20620. }
  20621. }
  20622. }
  20623. });
  20624. return result_2;
  20625. }
  20626. }
  20627. var collectOutlineEntries = function (result, node) {
  20628. if (node.type === 'array') {
  20629. node.items.forEach(function (node, index) {
  20630. if (node) {
  20631. var range = getRange(document, node);
  20632. var selectionRange = range;
  20633. var name = String(index);
  20634. var children = collectOutlineEntries([], node);
  20635. result.push({ name: name, kind: _this.getSymbolKind(node.type), range: range, selectionRange: selectionRange, children: children });
  20636. }
  20637. });
  20638. }
  20639. else if (node.type === 'object') {
  20640. node.properties.forEach(function (property) {
  20641. var valueNode = property.valueNode;
  20642. if (valueNode) {
  20643. var range = getRange(document, property);
  20644. var selectionRange = getRange(document, property.keyNode);
  20645. var children = collectOutlineEntries([], valueNode);
  20646. result.push({ name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), range: range, selectionRange: selectionRange, children: children });
  20647. }
  20648. });
  20649. }
  20650. return result;
  20651. };
  20652. var result = collectOutlineEntries([], root);
  20653. return result;
  20654. };
  20655. JSONDocumentSymbols.prototype.getSymbolKind = function (nodeType) {
  20656. switch (nodeType) {
  20657. case 'object':
  20658. return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Module;
  20659. case 'string':
  20660. return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].String;
  20661. case 'number':
  20662. return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Number;
  20663. case 'array':
  20664. return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Array;
  20665. case 'boolean':
  20666. return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Boolean;
  20667. default: // 'null'
  20668. return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Variable;
  20669. }
  20670. };
  20671. JSONDocumentSymbols.prototype.getKeyLabel = function (property) {
  20672. var name = property.keyNode.value;
  20673. if (name) {
  20674. name = name.replace(/[\n]/g, '↵');
  20675. }
  20676. if (name && name.trim()) {
  20677. return name;
  20678. }
  20679. return "\"" + name + "\"";
  20680. };
  20681. JSONDocumentSymbols.prototype.findDocumentColors = function (document, doc) {
  20682. return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
  20683. var result = [];
  20684. if (schema) {
  20685. var matchingSchemas = doc.getMatchingSchemas(schema.schema);
  20686. var visitedNode = {};
  20687. for (var _i = 0, matchingSchemas_1 = matchingSchemas; _i < matchingSchemas_1.length; _i++) {
  20688. var s = matchingSchemas_1[_i];
  20689. if (!s.inverted && s.schema && (s.schema.format === 'color' || s.schema.format === 'color-hex') && s.node && s.node.type === 'string') {
  20690. var nodeId = String(s.node.offset);
  20691. if (!visitedNode[nodeId]) {
  20692. var color = Object(_utils_colors__WEBPACK_IMPORTED_MODULE_2__["colorFromHex"])(_parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](s.node));
  20693. if (color) {
  20694. var range = getRange(document, s.node);
  20695. result.push({ color: color, range: range });
  20696. }
  20697. visitedNode[nodeId] = true;
  20698. }
  20699. }
  20700. }
  20701. }
  20702. return result;
  20703. });
  20704. };
  20705. JSONDocumentSymbols.prototype.getColorPresentations = function (document, doc, color, range) {
  20706. var result = [];
  20707. var red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255);
  20708. function toTwoDigitHex(n) {
  20709. var r = n.toString(16);
  20710. return r.length !== 2 ? '0' + r : r;
  20711. }
  20712. var label;
  20713. if (color.alpha === 1) {
  20714. label = "#" + toTwoDigitHex(red256) + toTwoDigitHex(green256) + toTwoDigitHex(blue256);
  20715. }
  20716. else {
  20717. label = "#" + toTwoDigitHex(red256) + toTwoDigitHex(green256) + toTwoDigitHex(blue256) + toTwoDigitHex(Math.round(color.alpha * 255));
  20718. }
  20719. result.push({ label: label, textEdit: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["TextEdit"].replace(range, JSON.stringify(label)) });
  20720. return result;
  20721. };
  20722. return JSONDocumentSymbols;
  20723. }());
  20724. function getRange(document, node) {
  20725. return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["Range"].create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
  20726. }
  20727. /***/ }),
  20728. /* 97 */
  20729. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  20730. "use strict";
  20731. __webpack_require__.r(__webpack_exports__);
  20732. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hexDigit", function() { return hexDigit; });
  20733. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "colorFromHex", function() { return colorFromHex; });
  20734. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "colorFrom256RGB", function() { return colorFrom256RGB; });
  20735. /*---------------------------------------------------------------------------------------------
  20736. * Copyright (c) Microsoft Corporation. All rights reserved.
  20737. * Licensed under the MIT License. See License.txt in the project root for license information.
  20738. *--------------------------------------------------------------------------------------------*/
  20739. var Digit0 = 48;
  20740. var Digit9 = 57;
  20741. var A = 65;
  20742. var a = 97;
  20743. var f = 102;
  20744. function hexDigit(charCode) {
  20745. if (charCode < Digit0) {
  20746. return 0;
  20747. }
  20748. if (charCode <= Digit9) {
  20749. return charCode - Digit0;
  20750. }
  20751. if (charCode < a) {
  20752. charCode += (a - A);
  20753. }
  20754. if (charCode >= a && charCode <= f) {
  20755. return charCode - a + 10;
  20756. }
  20757. return 0;
  20758. }
  20759. function colorFromHex(text) {
  20760. if (text[0] !== '#') {
  20761. return null;
  20762. }
  20763. switch (text.length) {
  20764. case 4:
  20765. return {
  20766. red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0,
  20767. green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0,
  20768. blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0,
  20769. alpha: 1
  20770. };
  20771. case 5:
  20772. return {
  20773. red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0,
  20774. green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0,
  20775. blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0,
  20776. alpha: (hexDigit(text.charCodeAt(4)) * 0x11) / 255.0,
  20777. };
  20778. case 7:
  20779. return {
  20780. red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0,
  20781. green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0,
  20782. blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0,
  20783. alpha: 1
  20784. };
  20785. case 9:
  20786. return {
  20787. red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0,
  20788. green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0,
  20789. blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0,
  20790. alpha: (hexDigit(text.charCodeAt(7)) * 0x10 + hexDigit(text.charCodeAt(8))) / 255.0
  20791. };
  20792. }
  20793. return null;
  20794. }
  20795. function colorFrom256RGB(red, green, blue, alpha) {
  20796. if (alpha === void 0) { alpha = 1.0; }
  20797. return {
  20798. red: red / 255.0,
  20799. green: green / 255.0,
  20800. blue: blue / 255.0,
  20801. alpha: alpha
  20802. };
  20803. }
  20804. /***/ }),
  20805. /* 98 */
  20806. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  20807. "use strict";
  20808. __webpack_require__.r(__webpack_exports__);
  20809. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "schemaContributions", function() { return schemaContributions; });
  20810. /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(76);
  20811. /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_0__);
  20812. /*---------------------------------------------------------------------------------------------
  20813. * Copyright (c) Microsoft Corporation. All rights reserved.
  20814. * Licensed under the MIT License. See License.txt in the project root for license information.
  20815. *--------------------------------------------------------------------------------------------*/
  20816. var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_0__["loadMessageBundle"]();
  20817. var schemaContributions = {
  20818. schemaAssociations: {},
  20819. schemas: {
  20820. // bundle the schema-schema to include (localized) descriptions
  20821. 'http://json-schema.org/draft-04/schema#': {
  20822. 'title': localize('schema.json', 'Describes a JSON file using a schema. See json-schema.org for more info.'),
  20823. '$schema': 'http://json-schema.org/draft-04/schema#',
  20824. 'definitions': {
  20825. 'schemaArray': {
  20826. 'type': 'array',
  20827. 'minItems': 1,
  20828. 'items': {
  20829. '$ref': '#'
  20830. }
  20831. },
  20832. 'positiveInteger': {
  20833. 'type': 'integer',
  20834. 'minimum': 0
  20835. },
  20836. 'positiveIntegerDefault0': {
  20837. 'allOf': [
  20838. {
  20839. '$ref': '#/definitions/positiveInteger'
  20840. },
  20841. {
  20842. 'default': 0
  20843. }
  20844. ]
  20845. },
  20846. 'simpleTypes': {
  20847. 'type': 'string',
  20848. 'enum': [
  20849. 'array',
  20850. 'boolean',
  20851. 'integer',
  20852. 'null',
  20853. 'number',
  20854. 'object',
  20855. 'string'
  20856. ]
  20857. },
  20858. 'stringArray': {
  20859. 'type': 'array',
  20860. 'items': {
  20861. 'type': 'string'
  20862. },
  20863. 'minItems': 1,
  20864. 'uniqueItems': true
  20865. }
  20866. },
  20867. 'type': 'object',
  20868. 'properties': {
  20869. 'id': {
  20870. 'type': 'string',
  20871. 'format': 'uri'
  20872. },
  20873. '$schema': {
  20874. 'type': 'string',
  20875. 'format': 'uri'
  20876. },
  20877. 'title': {
  20878. 'type': 'string'
  20879. },
  20880. 'description': {
  20881. 'type': 'string'
  20882. },
  20883. 'default': {},
  20884. 'multipleOf': {
  20885. 'type': 'number',
  20886. 'minimum': 0,
  20887. 'exclusiveMinimum': true
  20888. },
  20889. 'maximum': {
  20890. 'type': 'number'
  20891. },
  20892. 'exclusiveMaximum': {
  20893. 'type': 'boolean',
  20894. 'default': false
  20895. },
  20896. 'minimum': {
  20897. 'type': 'number'
  20898. },
  20899. 'exclusiveMinimum': {
  20900. 'type': 'boolean',
  20901. 'default': false
  20902. },
  20903. 'maxLength': {
  20904. 'allOf': [
  20905. {
  20906. '$ref': '#/definitions/positiveInteger'
  20907. }
  20908. ]
  20909. },
  20910. 'minLength': {
  20911. 'allOf': [
  20912. {
  20913. '$ref': '#/definitions/positiveIntegerDefault0'
  20914. }
  20915. ]
  20916. },
  20917. 'pattern': {
  20918. 'type': 'string',
  20919. 'format': 'regex'
  20920. },
  20921. 'additionalItems': {
  20922. 'anyOf': [
  20923. {
  20924. 'type': 'boolean'
  20925. },
  20926. {
  20927. '$ref': '#'
  20928. }
  20929. ],
  20930. 'default': {}
  20931. },
  20932. 'items': {
  20933. 'anyOf': [
  20934. {
  20935. '$ref': '#'
  20936. },
  20937. {
  20938. '$ref': '#/definitions/schemaArray'
  20939. }
  20940. ],
  20941. 'default': {}
  20942. },
  20943. 'maxItems': {
  20944. 'allOf': [
  20945. {
  20946. '$ref': '#/definitions/positiveInteger'
  20947. }
  20948. ]
  20949. },
  20950. 'minItems': {
  20951. 'allOf': [
  20952. {
  20953. '$ref': '#/definitions/positiveIntegerDefault0'
  20954. }
  20955. ]
  20956. },
  20957. 'uniqueItems': {
  20958. 'type': 'boolean',
  20959. 'default': false
  20960. },
  20961. 'maxProperties': {
  20962. 'allOf': [
  20963. {
  20964. '$ref': '#/definitions/positiveInteger'
  20965. }
  20966. ]
  20967. },
  20968. 'minProperties': {
  20969. 'allOf': [
  20970. {
  20971. '$ref': '#/definitions/positiveIntegerDefault0'
  20972. }
  20973. ]
  20974. },
  20975. 'required': {
  20976. 'allOf': [
  20977. {
  20978. '$ref': '#/definitions/stringArray'
  20979. }
  20980. ]
  20981. },
  20982. 'additionalProperties': {
  20983. 'anyOf': [
  20984. {
  20985. 'type': 'boolean'
  20986. },
  20987. {
  20988. '$ref': '#'
  20989. }
  20990. ],
  20991. 'default': {}
  20992. },
  20993. 'definitions': {
  20994. 'type': 'object',
  20995. 'additionalProperties': {
  20996. '$ref': '#'
  20997. },
  20998. 'default': {}
  20999. },
  21000. 'properties': {
  21001. 'type': 'object',
  21002. 'additionalProperties': {
  21003. '$ref': '#'
  21004. },
  21005. 'default': {}
  21006. },
  21007. 'patternProperties': {
  21008. 'type': 'object',
  21009. 'additionalProperties': {
  21010. '$ref': '#'
  21011. },
  21012. 'default': {}
  21013. },
  21014. 'dependencies': {
  21015. 'type': 'object',
  21016. 'additionalProperties': {
  21017. 'anyOf': [
  21018. {
  21019. '$ref': '#'
  21020. },
  21021. {
  21022. '$ref': '#/definitions/stringArray'
  21023. }
  21024. ]
  21025. }
  21026. },
  21027. 'enum': {
  21028. 'type': 'array',
  21029. 'minItems': 1,
  21030. 'uniqueItems': true
  21031. },
  21032. 'type': {
  21033. 'anyOf': [
  21034. {
  21035. '$ref': '#/definitions/simpleTypes'
  21036. },
  21037. {
  21038. 'type': 'array',
  21039. 'items': {
  21040. '$ref': '#/definitions/simpleTypes'
  21041. },
  21042. 'minItems': 1,
  21043. 'uniqueItems': true
  21044. }
  21045. ]
  21046. },
  21047. 'format': {
  21048. 'anyOf': [
  21049. {
  21050. 'type': 'string',
  21051. 'enum': [
  21052. 'date-time',
  21053. 'uri',
  21054. 'email',
  21055. 'hostname',
  21056. 'ipv4',
  21057. 'ipv6',
  21058. 'regex'
  21059. ]
  21060. },
  21061. {
  21062. 'type': 'string'
  21063. }
  21064. ]
  21065. },
  21066. 'allOf': {
  21067. 'allOf': [
  21068. {
  21069. '$ref': '#/definitions/schemaArray'
  21070. }
  21071. ]
  21072. },
  21073. 'anyOf': {
  21074. 'allOf': [
  21075. {
  21076. '$ref': '#/definitions/schemaArray'
  21077. }
  21078. ]
  21079. },
  21080. 'oneOf': {
  21081. 'allOf': [
  21082. {
  21083. '$ref': '#/definitions/schemaArray'
  21084. }
  21085. ]
  21086. },
  21087. 'not': {
  21088. 'allOf': [
  21089. {
  21090. '$ref': '#'
  21091. }
  21092. ]
  21093. }
  21094. },
  21095. 'dependencies': {
  21096. 'exclusiveMaximum': [
  21097. 'maximum'
  21098. ],
  21099. 'exclusiveMinimum': [
  21100. 'minimum'
  21101. ]
  21102. },
  21103. 'default': {}
  21104. },
  21105. 'http://json-schema.org/draft-07/schema#': {
  21106. 'title': localize('schema.json', 'Describes a JSON file using a schema. See json-schema.org for more info.'),
  21107. 'definitions': {
  21108. 'schemaArray': {
  21109. 'type': 'array',
  21110. 'minItems': 1,
  21111. 'items': { '$ref': '#' }
  21112. },
  21113. 'nonNegativeInteger': {
  21114. 'type': 'integer',
  21115. 'minimum': 0
  21116. },
  21117. 'nonNegativeIntegerDefault0': {
  21118. 'allOf': [
  21119. { '$ref': '#/definitions/nonNegativeInteger' },
  21120. { 'default': 0 }
  21121. ]
  21122. },
  21123. 'simpleTypes': {
  21124. 'enum': [
  21125. 'array',
  21126. 'boolean',
  21127. 'integer',
  21128. 'null',
  21129. 'number',
  21130. 'object',
  21131. 'string'
  21132. ]
  21133. },
  21134. 'stringArray': {
  21135. 'type': 'array',
  21136. 'items': { 'type': 'string' },
  21137. 'uniqueItems': true,
  21138. 'default': []
  21139. }
  21140. },
  21141. 'type': ['object', 'boolean'],
  21142. 'properties': {
  21143. '$id': {
  21144. 'type': 'string',
  21145. 'format': 'uri-reference'
  21146. },
  21147. '$schema': {
  21148. 'type': 'string',
  21149. 'format': 'uri'
  21150. },
  21151. '$ref': {
  21152. 'type': 'string',
  21153. 'format': 'uri-reference'
  21154. },
  21155. '$comment': {
  21156. 'type': 'string'
  21157. },
  21158. 'title': {
  21159. 'type': 'string'
  21160. },
  21161. 'description': {
  21162. 'type': 'string'
  21163. },
  21164. 'default': true,
  21165. 'readOnly': {
  21166. 'type': 'boolean',
  21167. 'default': false
  21168. },
  21169. 'examples': {
  21170. 'type': 'array',
  21171. 'items': true
  21172. },
  21173. 'multipleOf': {
  21174. 'type': 'number',
  21175. 'exclusiveMinimum': 0
  21176. },
  21177. 'maximum': {
  21178. 'type': 'number'
  21179. },
  21180. 'exclusiveMaximum': {
  21181. 'type': 'number'
  21182. },
  21183. 'minimum': {
  21184. 'type': 'number'
  21185. },
  21186. 'exclusiveMinimum': {
  21187. 'type': 'number'
  21188. },
  21189. 'maxLength': { '$ref': '#/definitions/nonNegativeInteger' },
  21190. 'minLength': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
  21191. 'pattern': {
  21192. 'type': 'string',
  21193. 'format': 'regex'
  21194. },
  21195. 'additionalItems': { '$ref': '#' },
  21196. 'items': {
  21197. 'anyOf': [
  21198. { '$ref': '#' },
  21199. { '$ref': '#/definitions/schemaArray' }
  21200. ],
  21201. 'default': true
  21202. },
  21203. 'maxItems': { '$ref': '#/definitions/nonNegativeInteger' },
  21204. 'minItems': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
  21205. 'uniqueItems': {
  21206. 'type': 'boolean',
  21207. 'default': false
  21208. },
  21209. 'contains': { '$ref': '#' },
  21210. 'maxProperties': { '$ref': '#/definitions/nonNegativeInteger' },
  21211. 'minProperties': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
  21212. 'required': { '$ref': '#/definitions/stringArray' },
  21213. 'additionalProperties': { '$ref': '#' },
  21214. 'definitions': {
  21215. 'type': 'object',
  21216. 'additionalProperties': { '$ref': '#' },
  21217. 'default': {}
  21218. },
  21219. 'properties': {
  21220. 'type': 'object',
  21221. 'additionalProperties': { '$ref': '#' },
  21222. 'default': {}
  21223. },
  21224. 'patternProperties': {
  21225. 'type': 'object',
  21226. 'additionalProperties': { '$ref': '#' },
  21227. 'propertyNames': { 'format': 'regex' },
  21228. 'default': {}
  21229. },
  21230. 'dependencies': {
  21231. 'type': 'object',
  21232. 'additionalProperties': {
  21233. 'anyOf': [
  21234. { '$ref': '#' },
  21235. { '$ref': '#/definitions/stringArray' }
  21236. ]
  21237. }
  21238. },
  21239. 'propertyNames': { '$ref': '#' },
  21240. 'const': true,
  21241. 'enum': {
  21242. 'type': 'array',
  21243. 'items': true,
  21244. 'minItems': 1,
  21245. 'uniqueItems': true
  21246. },
  21247. 'type': {
  21248. 'anyOf': [
  21249. { '$ref': '#/definitions/simpleTypes' },
  21250. {
  21251. 'type': 'array',
  21252. 'items': { '$ref': '#/definitions/simpleTypes' },
  21253. 'minItems': 1,
  21254. 'uniqueItems': true
  21255. }
  21256. ]
  21257. },
  21258. 'format': { 'type': 'string' },
  21259. 'contentMediaType': { 'type': 'string' },
  21260. 'contentEncoding': { 'type': 'string' },
  21261. 'if': { '$ref': '#' },
  21262. 'then': { '$ref': '#' },
  21263. 'else': { '$ref': '#' },
  21264. 'allOf': { '$ref': '#/definitions/schemaArray' },
  21265. 'anyOf': { '$ref': '#/definitions/schemaArray' },
  21266. 'oneOf': { '$ref': '#/definitions/schemaArray' },
  21267. 'not': { '$ref': '#' }
  21268. },
  21269. 'default': true
  21270. }
  21271. }
  21272. };
  21273. var descriptions = {
  21274. id: localize('schema.json.id', "A unique identifier for the schema."),
  21275. $schema: localize('schema.json.$schema', "The schema to verify this document against."),
  21276. title: localize('schema.json.title', "A descriptive title of the element."),
  21277. description: localize('schema.json.description', "A long description of the element. Used in hover menus and suggestions."),
  21278. default: localize('schema.json.default', "A default value. Used by suggestions."),
  21279. multipleOf: localize('schema.json.multipleOf', "A number that should cleanly divide the current value (i.e. have no remainder)."),
  21280. maximum: localize('schema.json.maximum', "The maximum numerical value, inclusive by default."),
  21281. exclusiveMaximum: localize('schema.json.exclusiveMaximum', "Makes the maximum property exclusive."),
  21282. minimum: localize('schema.json.minimum', "The minimum numerical value, inclusive by default."),
  21283. exclusiveMinimum: localize('schema.json.exclusiveMininum', "Makes the minimum property exclusive."),
  21284. maxLength: localize('schema.json.maxLength', "The maximum length of a string."),
  21285. minLength: localize('schema.json.minLength', "The minimum length of a string."),
  21286. pattern: localize('schema.json.pattern', "A regular expression to match the string against. It is not implicitly anchored."),
  21287. additionalItems: localize('schema.json.additionalItems', "For arrays, only when items is set as an array. If it is a schema, then this schema validates items after the ones specified by the items array. If it is false, then additional items will cause validation to fail."),
  21288. items: localize('schema.json.items', "For arrays. Can either be a schema to validate every element against or an array of schemas to validate each item against in order (the first schema will validate the first element, the second schema will validate the second element, and so on."),
  21289. maxItems: localize('schema.json.maxItems', "The maximum number of items that can be inside an array. Inclusive."),
  21290. minItems: localize('schema.json.minItems', "The minimum number of items that can be inside an array. Inclusive."),
  21291. uniqueItems: localize('schema.json.uniqueItems', "If all of the items in the array must be unique. Defaults to false."),
  21292. maxProperties: localize('schema.json.maxProperties', "The maximum number of properties an object can have. Inclusive."),
  21293. minProperties: localize('schema.json.minProperties', "The minimum number of properties an object can have. Inclusive."),
  21294. required: localize('schema.json.required', "An array of strings that lists the names of all properties required on this object."),
  21295. additionalProperties: localize('schema.json.additionalProperties', "Either a schema or a boolean. If a schema, then used to validate all properties not matched by 'properties' or 'patternProperties'. If false, then any properties not matched by either will cause this schema to fail."),
  21296. definitions: localize('schema.json.definitions', "Not used for validation. Place subschemas here that you wish to reference inline with $ref."),
  21297. properties: localize('schema.json.properties', "A map of property names to schemas for each property."),
  21298. patternProperties: localize('schema.json.patternProperties', "A map of regular expressions on property names to schemas for matching properties."),
  21299. dependencies: localize('schema.json.dependencies', "A map of property names to either an array of property names or a schema. An array of property names means the property named in the key depends on the properties in the array being present in the object in order to be valid. If the value is a schema, then the schema is only applied to the object if the property in the key exists on the object."),
  21300. enum: localize('schema.json.enum', "The set of literal values that are valid."),
  21301. type: localize('schema.json.type', "Either a string of one of the basic schema types (number, integer, null, array, object, boolean, string) or an array of strings specifying a subset of those types."),
  21302. format: localize('schema.json.format', "Describes the format expected for the value."),
  21303. allOf: localize('schema.json.allOf', "An array of schemas, all of which must match."),
  21304. anyOf: localize('schema.json.anyOf', "An array of schemas, where at least one must match."),
  21305. oneOf: localize('schema.json.oneOf', "An array of schemas, exactly one of which must match."),
  21306. not: localize('schema.json.not', "A schema which must not match."),
  21307. $id: localize('schema.json.$id', "A unique identifier for the schema."),
  21308. $ref: localize('schema.json.$ref', "Reference a definition hosted on any location."),
  21309. $comment: localize('schema.json.$comment', "Comments from schema authors to readers or maintainers of the schema."),
  21310. readOnly: localize('schema.json.readOnly', "Indicates that the value of the instance is managed exclusively by the owning authority."),
  21311. examples: localize('schema.json.examples', "Sample JSON values associated with a particular schema, for the purpose of illustrating usage."),
  21312. contains: localize('schema.json.contains', "An array instance is valid against \"contains\" if at least one of its elements is valid against the given schema."),
  21313. propertyNames: localize('schema.json.propertyNames', "If the instance is an object, this keyword validates if every property name in the instance validates against the provided schema."),
  21314. const: localize('schema.json.const', "An instance validates successfully against this keyword if its value is equal to the value of the keyword."),
  21315. contentMediaType: localize('schema.json.contentMediaType', "Describes the media type of a string property."),
  21316. contentEncoding: localize('schema.json.contentEncoding', "Describes the content encoding of a string property."),
  21317. if: localize('schema.json.if', "The validation outcome of the \"if\" subschema controls which of the \"then\" or \"else\" keywords are evaluated."),
  21318. then: localize('schema.json.then', "The \"if\" subschema is used for validation when the \"if\" subschema succeeds."),
  21319. else: localize('schema.json.else', "The \"else\" subschema is used for validation when the \"if\" subschema fails.")
  21320. };
  21321. for (var schemaName in schemaContributions.schemas) {
  21322. var schema = schemaContributions.schemas[schemaName];
  21323. for (var property in schema.properties) {
  21324. var propertyObject = schema.properties[property];
  21325. if (propertyObject === true) {
  21326. propertyObject = schema.properties[property] = {};
  21327. }
  21328. var description = descriptions[property];
  21329. if (description) {
  21330. propertyObject['description'] = description;
  21331. }
  21332. else {
  21333. console.log(property + ": localize('schema.json." + property + "', \"\")");
  21334. }
  21335. }
  21336. }
  21337. /***/ }),
  21338. /* 99 */
  21339. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  21340. "use strict";
  21341. __webpack_require__.r(__webpack_exports__);
  21342. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFoldingRanges", function() { return getFoldingRanges; });
  21343. /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80);
  21344. /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(83);
  21345. /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(89);
  21346. /*---------------------------------------------------------------------------------------------
  21347. * Copyright (c) Microsoft Corporation. All rights reserved.
  21348. * Licensed under the MIT License. See License.txt in the project root for license information.
  21349. *--------------------------------------------------------------------------------------------*/
  21350. function getFoldingRanges(document, context) {
  21351. var ranges = [];
  21352. var nestingLevels = [];
  21353. var stack = [];
  21354. var prevStart = -1;
  21355. var scanner = Object(jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"])(document.getText(), false);
  21356. var token = scanner.scan();
  21357. function addRange(range) {
  21358. ranges.push(range);
  21359. nestingLevels.push(stack.length);
  21360. }
  21361. while (token !== 17 /* EOF */) {
  21362. switch (token) {
  21363. case 1 /* OpenBraceToken */:
  21364. case 3 /* OpenBracketToken */: {
  21365. var startLine = document.positionAt(scanner.getTokenOffset()).line;
  21366. var range = { startLine: startLine, endLine: startLine, kind: token === 1 /* OpenBraceToken */ ? 'object' : 'array' };
  21367. stack.push(range);
  21368. break;
  21369. }
  21370. case 2 /* CloseBraceToken */:
  21371. case 4 /* CloseBracketToken */: {
  21372. var kind = token === 2 /* CloseBraceToken */ ? 'object' : 'array';
  21373. if (stack.length > 0 && stack[stack.length - 1].kind === kind) {
  21374. var range = stack.pop();
  21375. var line = document.positionAt(scanner.getTokenOffset()).line;
  21376. if (range && line > range.startLine + 1 && prevStart !== range.startLine) {
  21377. range.endLine = line - 1;
  21378. addRange(range);
  21379. prevStart = range.startLine;
  21380. }
  21381. }
  21382. break;
  21383. }
  21384. case 13 /* BlockCommentTrivia */: {
  21385. var startLine = document.positionAt(scanner.getTokenOffset()).line;
  21386. var endLine = document.positionAt(scanner.getTokenOffset() + scanner.getTokenLength()).line;
  21387. if (scanner.getTokenError() === 1 /* UnexpectedEndOfComment */ && startLine + 1 < document.lineCount) {
  21388. scanner.setPosition(document.offsetAt(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Position"].create(startLine + 1, 0)));
  21389. }
  21390. else {
  21391. if (startLine < endLine) {
  21392. addRange({ startLine: startLine, endLine: endLine, kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["FoldingRangeKind"].Comment });
  21393. prevStart = startLine;
  21394. }
  21395. }
  21396. break;
  21397. }
  21398. case 12 /* LineCommentTrivia */: {
  21399. var text = document.getText().substr(scanner.getTokenOffset(), scanner.getTokenLength());
  21400. var m = text.match(/^\/\/\s*#(region\b)|(endregion\b)/);
  21401. if (m) {
  21402. var line = document.positionAt(scanner.getTokenOffset()).line;
  21403. if (m[1]) { // start pattern match
  21404. var range = { startLine: line, endLine: line, kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["FoldingRangeKind"].Region };
  21405. stack.push(range);
  21406. }
  21407. else {
  21408. var i = stack.length - 1;
  21409. while (i >= 0 && stack[i].kind !== _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["FoldingRangeKind"].Region) {
  21410. i--;
  21411. }
  21412. if (i >= 0) {
  21413. var range = stack[i];
  21414. stack.length = i;
  21415. if (line > range.startLine && prevStart !== range.startLine) {
  21416. range.endLine = line;
  21417. addRange(range);
  21418. prevStart = range.startLine;
  21419. }
  21420. }
  21421. }
  21422. }
  21423. break;
  21424. }
  21425. }
  21426. token = scanner.scan();
  21427. }
  21428. var rangeLimit = context && context.rangeLimit;
  21429. if (typeof rangeLimit !== 'number' || ranges.length <= rangeLimit) {
  21430. return ranges;
  21431. }
  21432. var counts = [];
  21433. for (var _i = 0, nestingLevels_1 = nestingLevels; _i < nestingLevels_1.length; _i++) {
  21434. var level = nestingLevels_1[_i];
  21435. if (level < 30) {
  21436. counts[level] = (counts[level] || 0) + 1;
  21437. }
  21438. }
  21439. var entries = 0;
  21440. var maxLevel = 0;
  21441. for (var i = 0; i < counts.length; i++) {
  21442. var n = counts[i];
  21443. if (n) {
  21444. if (n + entries > rangeLimit) {
  21445. maxLevel = i;
  21446. break;
  21447. }
  21448. entries += n;
  21449. }
  21450. }
  21451. var result = [];
  21452. for (var i = 0; i < ranges.length; i++) {
  21453. var level = nestingLevels[i];
  21454. if (typeof level === 'number') {
  21455. if (level < maxLevel || (level === maxLevel && entries++ < rangeLimit)) {
  21456. result.push(ranges[i]);
  21457. }
  21458. }
  21459. }
  21460. return result;
  21461. }
  21462. /***/ }),
  21463. /* 100 */
  21464. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  21465. "use strict";
  21466. __webpack_require__.r(__webpack_exports__);
  21467. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSelectionRanges", function() { return getSelectionRanges; });
  21468. /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80);
  21469. /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(83);
  21470. /*---------------------------------------------------------------------------------------------
  21471. * Copyright (c) Microsoft Corporation. All rights reserved.
  21472. * Licensed under the MIT License. See License.txt in the project root for license information.
  21473. *--------------------------------------------------------------------------------------------*/
  21474. function getSelectionRanges(document, positions, doc) {
  21475. function getSelectionRange(position) {
  21476. var offset = document.offsetAt(position);
  21477. var node = doc.getNodeFromOffset(offset, true);
  21478. var result = [];
  21479. while (node) {
  21480. switch (node.type) {
  21481. case 'string':
  21482. case 'object':
  21483. case 'array':
  21484. // range without ", [ or {
  21485. var cStart = node.offset + 1, cEnd = node.offset + node.length - 1;
  21486. if (cStart < cEnd && offset >= cStart && offset <= cEnd) {
  21487. result.push(newRange(cStart, cEnd));
  21488. }
  21489. result.push(newRange(node.offset, node.offset + node.length));
  21490. break;
  21491. case 'number':
  21492. case 'boolean':
  21493. case 'null':
  21494. case 'property':
  21495. result.push(newRange(node.offset, node.offset + node.length));
  21496. break;
  21497. }
  21498. if (node.type === 'property' || node.parent && node.parent.type === 'array') {
  21499. var afterCommaOffset = getOffsetAfterNextToken(node.offset + node.length, 5 /* CommaToken */);
  21500. if (afterCommaOffset !== -1) {
  21501. result.push(newRange(node.offset, afterCommaOffset));
  21502. }
  21503. }
  21504. node = node.parent;
  21505. }
  21506. var current = undefined;
  21507. for (var index = result.length - 1; index >= 0; index--) {
  21508. current = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["SelectionRange"].create(result[index], current);
  21509. }
  21510. if (!current) {
  21511. current = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["SelectionRange"].create(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Range"].create(position, position));
  21512. }
  21513. return current;
  21514. }
  21515. function newRange(start, end) {
  21516. return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Range"].create(document.positionAt(start), document.positionAt(end));
  21517. }
  21518. var scanner = Object(jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"])(document.getText(), true);
  21519. function getOffsetAfterNextToken(offset, expectedToken) {
  21520. scanner.setPosition(offset);
  21521. var token = scanner.scan();
  21522. if (token === expectedToken) {
  21523. return scanner.getTokenOffset() + scanner.getTokenLength();
  21524. }
  21525. return -1;
  21526. }
  21527. return positions.map(getSelectionRange);
  21528. }
  21529. /***/ }),
  21530. /* 101 */
  21531. /***/ (function(module, exports, __webpack_require__) {
  21532. "use strict";
  21533. /*---------------------------------------------------------------------------------------------
  21534. * Copyright (c) Microsoft Corporation. All rights reserved.
  21535. * Licensed under the MIT License. See License.txt in the project root for license information.
  21536. *--------------------------------------------------------------------------------------------*/
  21537. Object.defineProperty(exports, "__esModule", { value: true });
  21538. function getLanguageModelCache(maxEntries, cleanupIntervalTimeInSec, parse) {
  21539. let languageModels = {};
  21540. let nModels = 0;
  21541. let cleanupInterval = undefined;
  21542. if (cleanupIntervalTimeInSec > 0) {
  21543. cleanupInterval = setInterval(() => {
  21544. let cutoffTime = Date.now() - cleanupIntervalTimeInSec * 1000;
  21545. let uris = Object.keys(languageModels);
  21546. for (let uri of uris) {
  21547. let languageModelInfo = languageModels[uri];
  21548. if (languageModelInfo.cTime < cutoffTime) {
  21549. delete languageModels[uri];
  21550. nModels--;
  21551. }
  21552. }
  21553. }, cleanupIntervalTimeInSec * 1000);
  21554. }
  21555. return {
  21556. get(document) {
  21557. let version = document.version;
  21558. let languageId = document.languageId;
  21559. let languageModelInfo = languageModels[document.uri];
  21560. if (languageModelInfo && languageModelInfo.version === version && languageModelInfo.languageId === languageId) {
  21561. languageModelInfo.cTime = Date.now();
  21562. return languageModelInfo.languageModel;
  21563. }
  21564. let languageModel = parse(document);
  21565. languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now() };
  21566. if (!languageModelInfo) {
  21567. nModels++;
  21568. }
  21569. if (nModels === maxEntries) {
  21570. let oldestTime = Number.MAX_VALUE;
  21571. let oldestUri = null;
  21572. for (let uri in languageModels) {
  21573. let languageModelInfo = languageModels[uri];
  21574. if (languageModelInfo.cTime < oldestTime) {
  21575. oldestUri = uri;
  21576. oldestTime = languageModelInfo.cTime;
  21577. }
  21578. }
  21579. if (oldestUri) {
  21580. delete languageModels[oldestUri];
  21581. nModels--;
  21582. }
  21583. }
  21584. return languageModel;
  21585. },
  21586. onDocumentRemoved(document) {
  21587. let uri = document.uri;
  21588. if (languageModels[uri]) {
  21589. delete languageModels[uri];
  21590. nModels--;
  21591. }
  21592. },
  21593. dispose() {
  21594. if (typeof cleanupInterval !== 'undefined') {
  21595. clearInterval(cleanupInterval);
  21596. cleanupInterval = undefined;
  21597. languageModels = {};
  21598. nModels = 0;
  21599. }
  21600. }
  21601. };
  21602. }
  21603. exports.getLanguageModelCache = getLanguageModelCache;
  21604. /***/ })
  21605. /******/ ])));