1 (function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
2 /******/ // The module cache
3 /******/ var installedModules = {};
5 /******/ // The require function
6 /******/ function __webpack_require__(moduleId) {
8 /******/ // Check if module is in cache
9 /******/ if(installedModules[moduleId]) {
10 /******/ return installedModules[moduleId].exports;
12 /******/ // Create a new module (and put it into the cache)
13 /******/ var module = installedModules[moduleId] = {
19 /******/ // Execute the module function
20 /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
22 /******/ // Flag the module as loaded
23 /******/ module.l = true;
25 /******/ // Return the exports of the module
26 /******/ return module.exports;
30 /******/ // expose the modules object (__webpack_modules__)
31 /******/ __webpack_require__.m = modules;
33 /******/ // expose the module cache
34 /******/ __webpack_require__.c = installedModules;
36 /******/ // define getter function for harmony exports
37 /******/ __webpack_require__.d = function(exports, name, getter) {
38 /******/ if(!__webpack_require__.o(exports, name)) {
39 /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
43 /******/ // define __esModule on exports
44 /******/ __webpack_require__.r = function(exports) {
45 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
46 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
48 /******/ Object.defineProperty(exports, '__esModule', { value: true });
51 /******/ // create a fake namespace object
52 /******/ // mode & 1: value is a module id, require it
53 /******/ // mode & 2: merge all properties of value into the ns
54 /******/ // mode & 4: return value when already ns object
55 /******/ // mode & 8|1: behave like require
56 /******/ __webpack_require__.t = function(value, mode) {
57 /******/ if(mode & 1) value = __webpack_require__(value);
58 /******/ if(mode & 8) return value;
59 /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
60 /******/ var ns = Object.create(null);
61 /******/ __webpack_require__.r(ns);
62 /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
63 /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
67 /******/ // getDefaultExport function for compatibility with non-harmony modules
68 /******/ __webpack_require__.n = function(module) {
69 /******/ var getter = module && module.__esModule ?
70 /******/ function getDefault() { return module['default']; } :
71 /******/ function getModuleExports() { return module; };
72 /******/ __webpack_require__.d(getter, 'a', getter);
73 /******/ return getter;
76 /******/ // Object.prototype.hasOwnProperty.call
77 /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
79 /******/ // __webpack_public_path__
80 /******/ __webpack_require__.p = "";
83 /******/ // Load entry module and return exports
84 /******/ return __webpack_require__(__webpack_require__.s = 39);
86 /************************************************************************/
90 /***/ (function(module, exports) {
92 module.exports = require("path");
96 /***/ (function(module, exports) {
98 module.exports = require("fs");
102 /***/ (function(module, exports) {
104 module.exports = require("util");
118 /***/ (function(module, exports) {
120 module.exports = require("os");
124 /***/ (function(module, exports) {
126 module.exports = require("crypto");
130 /***/ (function(module, exports) {
132 module.exports = require("net");
137 /***/ (function(module, __webpack_exports__, __webpack_require__) {
140 __webpack_require__.r(__webpack_exports__);
141 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
142 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
143 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
144 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
145 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
146 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
147 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
148 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
149 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
150 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
151 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
152 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
153 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
154 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
155 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
156 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
157 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
158 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
159 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
160 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
161 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
162 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
163 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
164 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
165 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
166 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
167 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
168 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
169 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemTag", function() { return CompletionItemTag; });
170 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
171 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
172 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
173 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
174 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
175 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
176 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
177 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
178 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
179 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolTag", function() { return SymbolTag; });
180 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
181 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
182 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
183 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
184 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
185 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
186 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
187 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
188 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
189 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
190 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
191 /* --------------------------------------------------------------------------------------------
\r
192 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
193 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
194 * ------------------------------------------------------------------------------------------ */
\r
197 * The Position namespace provides helper functions to work with
\r
198 * [Position](#Position) literals.
\r
201 (function (Position) {
\r
203 * Creates a new Position literal from the given line and character.
\r
204 * @param line The position's line.
\r
205 * @param character The position's character.
\r
207 function create(line, character) {
\r
208 return { line: line, character: character };
\r
210 Position.create = create;
\r
212 * Checks whether the given liternal conforms to the [Position](#Position) interface.
\r
214 function is(value) {
\r
215 var candidate = value;
\r
216 return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
\r
219 })(Position || (Position = {}));
\r
221 * The Range namespace provides helper functions to work with
\r
222 * [Range](#Range) literals.
\r
225 (function (Range) {
\r
226 function create(one, two, three, four) {
\r
227 if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
\r
228 return { start: Position.create(one, two), end: Position.create(three, four) };
\r
230 else if (Position.is(one) && Position.is(two)) {
\r
231 return { start: one, end: two };
\r
234 throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
\r
237 Range.create = create;
\r
239 * Checks whether the given literal conforms to the [Range](#Range) interface.
\r
241 function is(value) {
\r
242 var candidate = value;
\r
243 return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
\r
246 })(Range || (Range = {}));
\r
248 * The Location namespace provides helper functions to work with
\r
249 * [Location](#Location) literals.
\r
252 (function (Location) {
\r
254 * Creates a Location literal.
\r
255 * @param uri The location's uri.
\r
256 * @param range The location's range.
\r
258 function create(uri, range) {
\r
259 return { uri: uri, range: range };
\r
261 Location.create = create;
\r
263 * Checks whether the given literal conforms to the [Location](#Location) interface.
\r
265 function is(value) {
\r
266 var candidate = value;
\r
267 return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
\r
270 })(Location || (Location = {}));
\r
272 * The LocationLink namespace provides helper functions to work with
\r
273 * [LocationLink](#LocationLink) literals.
\r
276 (function (LocationLink) {
\r
278 * Creates a LocationLink literal.
\r
279 * @param targetUri The definition's uri.
\r
280 * @param targetRange The full range of the definition.
\r
281 * @param targetSelectionRange The span of the symbol definition at the target.
\r
282 * @param originSelectionRange The span of the symbol being defined in the originating source file.
\r
284 function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
\r
285 return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
\r
287 LocationLink.create = create;
\r
289 * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
\r
291 function is(value) {
\r
292 var candidate = value;
\r
293 return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
\r
294 && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
\r
295 && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
\r
297 LocationLink.is = is;
\r
298 })(LocationLink || (LocationLink = {}));
\r
300 * The Color namespace provides helper functions to work with
\r
301 * [Color](#Color) literals.
\r
304 (function (Color) {
\r
306 * Creates a new Color literal.
\r
308 function create(red, green, blue, alpha) {
\r
316 Color.create = create;
\r
318 * Checks whether the given literal conforms to the [Color](#Color) interface.
\r
320 function is(value) {
\r
321 var candidate = value;
\r
322 return Is.number(candidate.red)
\r
323 && Is.number(candidate.green)
\r
324 && Is.number(candidate.blue)
\r
325 && Is.number(candidate.alpha);
\r
328 })(Color || (Color = {}));
\r
330 * The ColorInformation namespace provides helper functions to work with
\r
331 * [ColorInformation](#ColorInformation) literals.
\r
333 var ColorInformation;
\r
334 (function (ColorInformation) {
\r
336 * Creates a new ColorInformation literal.
\r
338 function create(range, color) {
\r
344 ColorInformation.create = create;
\r
346 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
\r
348 function is(value) {
\r
349 var candidate = value;
\r
350 return Range.is(candidate.range) && Color.is(candidate.color);
\r
352 ColorInformation.is = is;
\r
353 })(ColorInformation || (ColorInformation = {}));
\r
355 * The Color namespace provides helper functions to work with
\r
356 * [ColorPresentation](#ColorPresentation) literals.
\r
358 var ColorPresentation;
\r
359 (function (ColorPresentation) {
\r
361 * Creates a new ColorInformation literal.
\r
363 function create(label, textEdit, additionalTextEdits) {
\r
366 textEdit: textEdit,
\r
367 additionalTextEdits: additionalTextEdits,
\r
370 ColorPresentation.create = create;
\r
372 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
\r
374 function is(value) {
\r
375 var candidate = value;
\r
376 return Is.string(candidate.label)
\r
377 && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
\r
378 && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
\r
380 ColorPresentation.is = is;
\r
381 })(ColorPresentation || (ColorPresentation = {}));
\r
383 * Enum of known range kinds
\r
385 var FoldingRangeKind;
\r
386 (function (FoldingRangeKind) {
\r
388 * Folding range for a comment
\r
390 FoldingRangeKind["Comment"] = "comment";
\r
392 * Folding range for a imports or includes
\r
394 FoldingRangeKind["Imports"] = "imports";
\r
396 * Folding range for a region (e.g. `#region`)
\r
398 FoldingRangeKind["Region"] = "region";
\r
399 })(FoldingRangeKind || (FoldingRangeKind = {}));
\r
401 * The folding range namespace provides helper functions to work with
\r
402 * [FoldingRange](#FoldingRange) literals.
\r
405 (function (FoldingRange) {
\r
407 * Creates a new FoldingRange literal.
\r
409 function create(startLine, endLine, startCharacter, endCharacter, kind) {
\r
411 startLine: startLine,
\r
414 if (Is.defined(startCharacter)) {
\r
415 result.startCharacter = startCharacter;
\r
417 if (Is.defined(endCharacter)) {
\r
418 result.endCharacter = endCharacter;
\r
420 if (Is.defined(kind)) {
\r
421 result.kind = kind;
\r
425 FoldingRange.create = create;
\r
427 * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
\r
429 function is(value) {
\r
430 var candidate = value;
\r
431 return Is.number(candidate.startLine) && Is.number(candidate.startLine)
\r
432 && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
\r
433 && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
\r
434 && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
\r
436 FoldingRange.is = is;
\r
437 })(FoldingRange || (FoldingRange = {}));
\r
439 * The DiagnosticRelatedInformation namespace provides helper functions to work with
\r
440 * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
\r
442 var DiagnosticRelatedInformation;
\r
443 (function (DiagnosticRelatedInformation) {
\r
445 * Creates a new DiagnosticRelatedInformation literal.
\r
447 function create(location, message) {
\r
449 location: location,
\r
453 DiagnosticRelatedInformation.create = create;
\r
455 * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
\r
457 function is(value) {
\r
458 var candidate = value;
\r
459 return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
\r
461 DiagnosticRelatedInformation.is = is;
\r
462 })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
\r
464 * The diagnostic's severity.
\r
466 var DiagnosticSeverity;
\r
467 (function (DiagnosticSeverity) {
\r
469 * Reports an error.
\r
471 DiagnosticSeverity.Error = 1;
\r
473 * Reports a warning.
\r
475 DiagnosticSeverity.Warning = 2;
\r
477 * Reports an information.
\r
479 DiagnosticSeverity.Information = 3;
\r
483 DiagnosticSeverity.Hint = 4;
\r
484 })(DiagnosticSeverity || (DiagnosticSeverity = {}));
\r
486 * The diagnostic tags.
\r
491 (function (DiagnosticTag) {
\r
493 * Unused or unnecessary code.
\r
495 * Clients are allowed to render diagnostics with this tag faded out instead of having
\r
496 * an error squiggle.
\r
498 DiagnosticTag.Unnecessary = 1;
\r
500 * Deprecated or obsolete code.
\r
502 * Clients are allowed to rendered diagnostics with this tag strike through.
\r
504 DiagnosticTag.Deprecated = 2;
\r
505 })(DiagnosticTag || (DiagnosticTag = {}));
\r
507 * The Diagnostic namespace provides helper functions to work with
\r
508 * [Diagnostic](#Diagnostic) literals.
\r
511 (function (Diagnostic) {
\r
513 * Creates a new Diagnostic literal.
\r
515 function create(range, message, severity, code, source, relatedInformation) {
\r
516 var result = { range: range, message: message };
\r
517 if (Is.defined(severity)) {
\r
518 result.severity = severity;
\r
520 if (Is.defined(code)) {
\r
521 result.code = code;
\r
523 if (Is.defined(source)) {
\r
524 result.source = source;
\r
526 if (Is.defined(relatedInformation)) {
\r
527 result.relatedInformation = relatedInformation;
\r
531 Diagnostic.create = create;
\r
533 * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
\r
535 function is(value) {
\r
536 var candidate = value;
\r
537 return Is.defined(candidate)
\r
538 && Range.is(candidate.range)
\r
539 && Is.string(candidate.message)
\r
540 && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
\r
541 && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
\r
542 && (Is.string(candidate.source) || Is.undefined(candidate.source))
\r
543 && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
\r
545 Diagnostic.is = is;
\r
546 })(Diagnostic || (Diagnostic = {}));
\r
548 * The Command namespace provides helper functions to work with
\r
549 * [Command](#Command) literals.
\r
552 (function (Command) {
\r
554 * Creates a new Command literal.
\r
556 function create(title, command) {
\r
558 for (var _i = 2; _i < arguments.length; _i++) {
\r
559 args[_i - 2] = arguments[_i];
\r
561 var result = { title: title, command: command };
\r
562 if (Is.defined(args) && args.length > 0) {
\r
563 result.arguments = args;
\r
567 Command.create = create;
\r
569 * Checks whether the given literal conforms to the [Command](#Command) interface.
\r
571 function is(value) {
\r
572 var candidate = value;
\r
573 return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
\r
576 })(Command || (Command = {}));
\r
578 * The TextEdit namespace provides helper function to create replace,
\r
579 * insert and delete edits more easily.
\r
582 (function (TextEdit) {
\r
584 * Creates a replace text edit.
\r
585 * @param range The range of text to be replaced.
\r
586 * @param newText The new text.
\r
588 function replace(range, newText) {
\r
589 return { range: range, newText: newText };
\r
591 TextEdit.replace = replace;
\r
593 * Creates a insert text edit.
\r
594 * @param position The position to insert the text at.
\r
595 * @param newText The text to be inserted.
\r
597 function insert(position, newText) {
\r
598 return { range: { start: position, end: position }, newText: newText };
\r
600 TextEdit.insert = insert;
\r
602 * Creates a delete text edit.
\r
603 * @param range The range of text to be deleted.
\r
605 function del(range) {
\r
606 return { range: range, newText: '' };
\r
608 TextEdit.del = del;
\r
609 function is(value) {
\r
610 var candidate = value;
\r
611 return Is.objectLiteral(candidate)
\r
612 && Is.string(candidate.newText)
\r
613 && Range.is(candidate.range);
\r
616 })(TextEdit || (TextEdit = {}));
\r
618 * The TextDocumentEdit namespace provides helper function to create
\r
619 * an edit that manipulates a text document.
\r
621 var TextDocumentEdit;
\r
622 (function (TextDocumentEdit) {
\r
624 * Creates a new `TextDocumentEdit`
\r
626 function create(textDocument, edits) {
\r
627 return { textDocument: textDocument, edits: edits };
\r
629 TextDocumentEdit.create = create;
\r
630 function is(value) {
\r
631 var candidate = value;
\r
632 return Is.defined(candidate)
\r
633 && VersionedTextDocumentIdentifier.is(candidate.textDocument)
\r
634 && Array.isArray(candidate.edits);
\r
636 TextDocumentEdit.is = is;
\r
637 })(TextDocumentEdit || (TextDocumentEdit = {}));
\r
639 (function (CreateFile) {
\r
640 function create(uri, options) {
\r
645 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
\r
646 result.options = options;
\r
650 CreateFile.create = create;
\r
651 function is(value) {
\r
652 var candidate = value;
\r
653 return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
\r
654 (candidate.options === void 0 ||
\r
655 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
\r
657 CreateFile.is = is;
\r
658 })(CreateFile || (CreateFile = {}));
\r
660 (function (RenameFile) {
\r
661 function create(oldUri, newUri, options) {
\r
667 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
\r
668 result.options = options;
\r
672 RenameFile.create = create;
\r
673 function is(value) {
\r
674 var candidate = value;
\r
675 return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
\r
676 (candidate.options === void 0 ||
\r
677 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
\r
679 RenameFile.is = is;
\r
680 })(RenameFile || (RenameFile = {}));
\r
682 (function (DeleteFile) {
\r
683 function create(uri, options) {
\r
688 if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
\r
689 result.options = options;
\r
693 DeleteFile.create = create;
\r
694 function is(value) {
\r
695 var candidate = value;
\r
696 return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
\r
697 (candidate.options === void 0 ||
\r
698 ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
\r
700 DeleteFile.is = is;
\r
701 })(DeleteFile || (DeleteFile = {}));
\r
703 (function (WorkspaceEdit) {
\r
704 function is(value) {
\r
705 var candidate = value;
\r
706 return candidate &&
\r
707 (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
\r
708 (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
\r
709 if (Is.string(change.kind)) {
\r
710 return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
\r
713 return TextDocumentEdit.is(change);
\r
717 WorkspaceEdit.is = is;
\r
718 })(WorkspaceEdit || (WorkspaceEdit = {}));
\r
719 var TextEditChangeImpl = /** @class */ (function () {
\r
720 function TextEditChangeImpl(edits) {
\r
721 this.edits = edits;
\r
723 TextEditChangeImpl.prototype.insert = function (position, newText) {
\r
724 this.edits.push(TextEdit.insert(position, newText));
\r
726 TextEditChangeImpl.prototype.replace = function (range, newText) {
\r
727 this.edits.push(TextEdit.replace(range, newText));
\r
729 TextEditChangeImpl.prototype.delete = function (range) {
\r
730 this.edits.push(TextEdit.del(range));
\r
732 TextEditChangeImpl.prototype.add = function (edit) {
\r
733 this.edits.push(edit);
\r
735 TextEditChangeImpl.prototype.all = function () {
\r
738 TextEditChangeImpl.prototype.clear = function () {
\r
739 this.edits.splice(0, this.edits.length);
\r
741 return TextEditChangeImpl;
\r
744 * A workspace change helps constructing changes to a workspace.
\r
746 var WorkspaceChange = /** @class */ (function () {
\r
747 function WorkspaceChange(workspaceEdit) {
\r
749 this._textEditChanges = Object.create(null);
\r
750 if (workspaceEdit) {
\r
751 this._workspaceEdit = workspaceEdit;
\r
752 if (workspaceEdit.documentChanges) {
\r
753 workspaceEdit.documentChanges.forEach(function (change) {
\r
754 if (TextDocumentEdit.is(change)) {
\r
755 var textEditChange = new TextEditChangeImpl(change.edits);
\r
756 _this._textEditChanges[change.textDocument.uri] = textEditChange;
\r
760 else if (workspaceEdit.changes) {
\r
761 Object.keys(workspaceEdit.changes).forEach(function (key) {
\r
762 var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
\r
763 _this._textEditChanges[key] = textEditChange;
\r
768 Object.defineProperty(WorkspaceChange.prototype, "edit", {
\r
770 * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
\r
771 * use to be returned from a workspace edit operation like rename.
\r
774 return this._workspaceEdit;
\r
779 WorkspaceChange.prototype.getTextEditChange = function (key) {
\r
780 if (VersionedTextDocumentIdentifier.is(key)) {
\r
781 if (!this._workspaceEdit) {
\r
782 this._workspaceEdit = {
\r
783 documentChanges: []
\r
786 if (!this._workspaceEdit.documentChanges) {
\r
787 throw new Error('Workspace edit is not configured for document changes.');
\r
789 var textDocument = key;
\r
790 var result = this._textEditChanges[textDocument.uri];
\r
793 var textDocumentEdit = {
\r
794 textDocument: textDocument,
\r
797 this._workspaceEdit.documentChanges.push(textDocumentEdit);
\r
798 result = new TextEditChangeImpl(edits);
\r
799 this._textEditChanges[textDocument.uri] = result;
\r
804 if (!this._workspaceEdit) {
\r
805 this._workspaceEdit = {
\r
806 changes: Object.create(null)
\r
809 if (!this._workspaceEdit.changes) {
\r
810 throw new Error('Workspace edit is not configured for normal text edit changes.');
\r
812 var result = this._textEditChanges[key];
\r
815 this._workspaceEdit.changes[key] = edits;
\r
816 result = new TextEditChangeImpl(edits);
\r
817 this._textEditChanges[key] = result;
\r
822 WorkspaceChange.prototype.createFile = function (uri, options) {
\r
823 this.checkDocumentChanges();
\r
824 this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
\r
826 WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
\r
827 this.checkDocumentChanges();
\r
828 this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
\r
830 WorkspaceChange.prototype.deleteFile = function (uri, options) {
\r
831 this.checkDocumentChanges();
\r
832 this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
\r
834 WorkspaceChange.prototype.checkDocumentChanges = function () {
\r
835 if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
\r
836 throw new Error('Workspace edit is not configured for document changes.');
\r
839 return WorkspaceChange;
\r
843 * The TextDocumentIdentifier namespace provides helper functions to work with
\r
844 * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
\r
846 var TextDocumentIdentifier;
\r
847 (function (TextDocumentIdentifier) {
\r
849 * Creates a new TextDocumentIdentifier literal.
\r
850 * @param uri The document's uri.
\r
852 function create(uri) {
\r
853 return { uri: uri };
\r
855 TextDocumentIdentifier.create = create;
\r
857 * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
\r
859 function is(value) {
\r
860 var candidate = value;
\r
861 return Is.defined(candidate) && Is.string(candidate.uri);
\r
863 TextDocumentIdentifier.is = is;
\r
864 })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
\r
866 * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
\r
867 * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
\r
869 var VersionedTextDocumentIdentifier;
\r
870 (function (VersionedTextDocumentIdentifier) {
\r
872 * Creates a new VersionedTextDocumentIdentifier literal.
\r
873 * @param uri The document's uri.
\r
874 * @param uri The document's text.
\r
876 function create(uri, version) {
\r
877 return { uri: uri, version: version };
\r
879 VersionedTextDocumentIdentifier.create = create;
\r
881 * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
\r
883 function is(value) {
\r
884 var candidate = value;
\r
885 return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
\r
887 VersionedTextDocumentIdentifier.is = is;
\r
888 })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
\r
890 * The TextDocumentItem namespace provides helper functions to work with
\r
891 * [TextDocumentItem](#TextDocumentItem) literals.
\r
893 var TextDocumentItem;
\r
894 (function (TextDocumentItem) {
\r
896 * Creates a new TextDocumentItem literal.
\r
897 * @param uri The document's uri.
\r
898 * @param languageId The document's language identifier.
\r
899 * @param version The document's version number.
\r
900 * @param text The document's text.
\r
902 function create(uri, languageId, version, text) {
\r
903 return { uri: uri, languageId: languageId, version: version, text: text };
\r
905 TextDocumentItem.create = create;
\r
907 * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
\r
909 function is(value) {
\r
910 var candidate = value;
\r
911 return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
\r
913 TextDocumentItem.is = is;
\r
914 })(TextDocumentItem || (TextDocumentItem = {}));
\r
916 * Describes the content type that a client supports in various
\r
917 * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
\r
919 * Please note that `MarkupKinds` must not start with a `$`. This kinds
\r
920 * are reserved for internal usage.
\r
923 (function (MarkupKind) {
\r
925 * Plain text is supported as a content format
\r
927 MarkupKind.PlainText = 'plaintext';
\r
929 * Markdown is supported as a content format
\r
931 MarkupKind.Markdown = 'markdown';
\r
932 })(MarkupKind || (MarkupKind = {}));
\r
933 (function (MarkupKind) {
\r
935 * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
\r
937 function is(value) {
\r
938 var candidate = value;
\r
939 return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
\r
941 MarkupKind.is = is;
\r
942 })(MarkupKind || (MarkupKind = {}));
\r
944 (function (MarkupContent) {
\r
946 * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
\r
948 function is(value) {
\r
949 var candidate = value;
\r
950 return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
\r
952 MarkupContent.is = is;
\r
953 })(MarkupContent || (MarkupContent = {}));
\r
955 * The kind of a completion entry.
\r
957 var CompletionItemKind;
\r
958 (function (CompletionItemKind) {
\r
959 CompletionItemKind.Text = 1;
\r
960 CompletionItemKind.Method = 2;
\r
961 CompletionItemKind.Function = 3;
\r
962 CompletionItemKind.Constructor = 4;
\r
963 CompletionItemKind.Field = 5;
\r
964 CompletionItemKind.Variable = 6;
\r
965 CompletionItemKind.Class = 7;
\r
966 CompletionItemKind.Interface = 8;
\r
967 CompletionItemKind.Module = 9;
\r
968 CompletionItemKind.Property = 10;
\r
969 CompletionItemKind.Unit = 11;
\r
970 CompletionItemKind.Value = 12;
\r
971 CompletionItemKind.Enum = 13;
\r
972 CompletionItemKind.Keyword = 14;
\r
973 CompletionItemKind.Snippet = 15;
\r
974 CompletionItemKind.Color = 16;
\r
975 CompletionItemKind.File = 17;
\r
976 CompletionItemKind.Reference = 18;
\r
977 CompletionItemKind.Folder = 19;
\r
978 CompletionItemKind.EnumMember = 20;
\r
979 CompletionItemKind.Constant = 21;
\r
980 CompletionItemKind.Struct = 22;
\r
981 CompletionItemKind.Event = 23;
\r
982 CompletionItemKind.Operator = 24;
\r
983 CompletionItemKind.TypeParameter = 25;
\r
984 })(CompletionItemKind || (CompletionItemKind = {}));
\r
986 * Defines whether the insert text in a completion item should be interpreted as
\r
987 * plain text or a snippet.
\r
989 var InsertTextFormat;
\r
990 (function (InsertTextFormat) {
\r
992 * The primary text to be inserted is treated as a plain string.
\r
994 InsertTextFormat.PlainText = 1;
\r
996 * The primary text to be inserted is treated as a snippet.
\r
998 * A snippet can define tab stops and placeholders with `$1`, `$2`
\r
999 * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
\r
1000 * the end of the snippet. Placeholders with equal identifiers are linked,
\r
1001 * that is typing in one will update others too.
\r
1003 * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
\r
1005 InsertTextFormat.Snippet = 2;
\r
1006 })(InsertTextFormat || (InsertTextFormat = {}));
\r
1008 * Completion item tags are extra annotations that tweak the rendering of a completion
\r
1013 var CompletionItemTag;
\r
1014 (function (CompletionItemTag) {
\r
1016 * Render a completion as obsolete, usually using a strike-out.
\r
1018 CompletionItemTag.Deprecated = 1;
\r
1019 })(CompletionItemTag || (CompletionItemTag = {}));
\r
1021 * The CompletionItem namespace provides functions to deal with
\r
1022 * completion items.
\r
1024 var CompletionItem;
\r
1025 (function (CompletionItem) {
\r
1027 * Create a completion item and seed it with a label.
\r
1028 * @param label The completion item's label
\r
1030 function create(label) {
\r
1031 return { label: label };
\r
1033 CompletionItem.create = create;
\r
1034 })(CompletionItem || (CompletionItem = {}));
\r
1036 * The CompletionList namespace provides functions to deal with
\r
1037 * completion lists.
\r
1039 var CompletionList;
\r
1040 (function (CompletionList) {
\r
1042 * Creates a new completion list.
\r
1044 * @param items The completion items.
\r
1045 * @param isIncomplete The list is not complete.
\r
1047 function create(items, isIncomplete) {
\r
1048 return { items: items ? items : [], isIncomplete: !!isIncomplete };
\r
1050 CompletionList.create = create;
\r
1051 })(CompletionList || (CompletionList = {}));
\r
1053 (function (MarkedString) {
\r
1055 * Creates a marked string from plain text.
\r
1057 * @param plainText The plain text.
\r
1059 function fromPlainText(plainText) {
\r
1060 return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
\r
1062 MarkedString.fromPlainText = fromPlainText;
\r
1064 * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
\r
1066 function is(value) {
\r
1067 var candidate = value;
\r
1068 return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
\r
1070 MarkedString.is = is;
\r
1071 })(MarkedString || (MarkedString = {}));
\r
1073 (function (Hover) {
\r
1075 * Checks whether the given value conforms to the [Hover](#Hover) interface.
\r
1077 function is(value) {
\r
1078 var candidate = value;
\r
1079 return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
\r
1080 MarkedString.is(candidate.contents) ||
\r
1081 Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
\r
1084 })(Hover || (Hover = {}));
\r
1086 * The ParameterInformation namespace provides helper functions to work with
\r
1087 * [ParameterInformation](#ParameterInformation) literals.
\r
1089 var ParameterInformation;
\r
1090 (function (ParameterInformation) {
\r
1092 * Creates a new parameter information literal.
\r
1094 * @param label A label string.
\r
1095 * @param documentation A doc string.
\r
1097 function create(label, documentation) {
\r
1098 return documentation ? { label: label, documentation: documentation } : { label: label };
\r
1100 ParameterInformation.create = create;
\r
1101 })(ParameterInformation || (ParameterInformation = {}));
\r
1103 * The SignatureInformation namespace provides helper functions to work with
\r
1104 * [SignatureInformation](#SignatureInformation) literals.
\r
1106 var SignatureInformation;
\r
1107 (function (SignatureInformation) {
\r
1108 function create(label, documentation) {
\r
1109 var parameters = [];
\r
1110 for (var _i = 2; _i < arguments.length; _i++) {
\r
1111 parameters[_i - 2] = arguments[_i];
\r
1113 var result = { label: label };
\r
1114 if (Is.defined(documentation)) {
\r
1115 result.documentation = documentation;
\r
1117 if (Is.defined(parameters)) {
\r
1118 result.parameters = parameters;
\r
1121 result.parameters = [];
\r
1125 SignatureInformation.create = create;
\r
1126 })(SignatureInformation || (SignatureInformation = {}));
\r
1128 * A document highlight kind.
\r
1130 var DocumentHighlightKind;
\r
1131 (function (DocumentHighlightKind) {
\r
1133 * A textual occurrence.
\r
1135 DocumentHighlightKind.Text = 1;
\r
1137 * Read-access of a symbol, like reading a variable.
\r
1139 DocumentHighlightKind.Read = 2;
\r
1141 * Write-access of a symbol, like writing to a variable.
\r
1143 DocumentHighlightKind.Write = 3;
\r
1144 })(DocumentHighlightKind || (DocumentHighlightKind = {}));
\r
1146 * DocumentHighlight namespace to provide helper functions to work with
\r
1147 * [DocumentHighlight](#DocumentHighlight) literals.
\r
1149 var DocumentHighlight;
\r
1150 (function (DocumentHighlight) {
\r
1152 * Create a DocumentHighlight object.
\r
1153 * @param range The range the highlight applies to.
\r
1155 function create(range, kind) {
\r
1156 var result = { range: range };
\r
1157 if (Is.number(kind)) {
\r
1158 result.kind = kind;
\r
1162 DocumentHighlight.create = create;
\r
1163 })(DocumentHighlight || (DocumentHighlight = {}));
\r
1168 (function (SymbolKind) {
\r
1169 SymbolKind.File = 1;
\r
1170 SymbolKind.Module = 2;
\r
1171 SymbolKind.Namespace = 3;
\r
1172 SymbolKind.Package = 4;
\r
1173 SymbolKind.Class = 5;
\r
1174 SymbolKind.Method = 6;
\r
1175 SymbolKind.Property = 7;
\r
1176 SymbolKind.Field = 8;
\r
1177 SymbolKind.Constructor = 9;
\r
1178 SymbolKind.Enum = 10;
\r
1179 SymbolKind.Interface = 11;
\r
1180 SymbolKind.Function = 12;
\r
1181 SymbolKind.Variable = 13;
\r
1182 SymbolKind.Constant = 14;
\r
1183 SymbolKind.String = 15;
\r
1184 SymbolKind.Number = 16;
\r
1185 SymbolKind.Boolean = 17;
\r
1186 SymbolKind.Array = 18;
\r
1187 SymbolKind.Object = 19;
\r
1188 SymbolKind.Key = 20;
\r
1189 SymbolKind.Null = 21;
\r
1190 SymbolKind.EnumMember = 22;
\r
1191 SymbolKind.Struct = 23;
\r
1192 SymbolKind.Event = 24;
\r
1193 SymbolKind.Operator = 25;
\r
1194 SymbolKind.TypeParameter = 26;
\r
1195 })(SymbolKind || (SymbolKind = {}));
\r
1197 * Symbol tags are extra annotations that tweak the rendering of a symbol.
\r
1201 (function (SymbolTag) {
\r
1203 * Render a symbol as obsolete, usually using a strike-out.
\r
1205 SymbolTag.Deprecated = 1;
\r
1206 })(SymbolTag || (SymbolTag = {}));
\r
1207 var SymbolInformation;
\r
1208 (function (SymbolInformation) {
\r
1210 * Creates a new symbol information literal.
\r
1212 * @param name The name of the symbol.
\r
1213 * @param kind The kind of the symbol.
\r
1214 * @param range The range of the location of the symbol.
\r
1215 * @param uri The resource of the location of symbol, defaults to the current document.
\r
1216 * @param containerName The name of the symbol containing the symbol.
\r
1218 function create(name, kind, range, uri, containerName) {
\r
1222 location: { uri: uri, range: range }
\r
1224 if (containerName) {
\r
1225 result.containerName = containerName;
\r
1229 SymbolInformation.create = create;
\r
1230 })(SymbolInformation || (SymbolInformation = {}));
\r
1231 var DocumentSymbol;
\r
1232 (function (DocumentSymbol) {
\r
1234 * Creates a new symbol information literal.
\r
1236 * @param name The name of the symbol.
\r
1237 * @param detail The detail of the symbol.
\r
1238 * @param kind The kind of the symbol.
\r
1239 * @param range The range of the symbol.
\r
1240 * @param selectionRange The selectionRange of the symbol.
\r
1241 * @param children Children of the symbol.
\r
1243 function create(name, detail, kind, range, selectionRange, children) {
\r
1249 selectionRange: selectionRange
\r
1251 if (children !== void 0) {
\r
1252 result.children = children;
\r
1256 DocumentSymbol.create = create;
\r
1258 * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
\r
1260 function is(value) {
\r
1261 var candidate = value;
\r
1262 return candidate &&
\r
1263 Is.string(candidate.name) && Is.number(candidate.kind) &&
\r
1264 Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
\r
1265 (candidate.detail === void 0 || Is.string(candidate.detail)) &&
\r
1266 (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
\r
1267 (candidate.children === void 0 || Array.isArray(candidate.children));
\r
1269 DocumentSymbol.is = is;
\r
1270 })(DocumentSymbol || (DocumentSymbol = {}));
\r
1272 * A set of predefined code action kinds
\r
1274 var CodeActionKind;
\r
1275 (function (CodeActionKind) {
\r
1279 CodeActionKind.Empty = '';
\r
1281 * Base kind for quickfix actions: 'quickfix'
\r
1283 CodeActionKind.QuickFix = 'quickfix';
\r
1285 * Base kind for refactoring actions: 'refactor'
\r
1287 CodeActionKind.Refactor = 'refactor';
\r
1289 * Base kind for refactoring extraction actions: 'refactor.extract'
\r
1291 * Example extract actions:
\r
1293 * - Extract method
\r
1294 * - Extract function
\r
1295 * - Extract variable
\r
1296 * - Extract interface from class
\r
1299 CodeActionKind.RefactorExtract = 'refactor.extract';
\r
1301 * Base kind for refactoring inline actions: 'refactor.inline'
\r
1303 * Example inline actions:
\r
1305 * - Inline function
\r
1306 * - Inline variable
\r
1307 * - Inline constant
\r
1310 CodeActionKind.RefactorInline = 'refactor.inline';
\r
1312 * Base kind for refactoring rewrite actions: 'refactor.rewrite'
\r
1314 * Example rewrite actions:
\r
1316 * - Convert JavaScript function to class
\r
1317 * - Add or remove parameter
\r
1318 * - Encapsulate field
\r
1319 * - Make method static
\r
1320 * - Move method to base class
\r
1323 CodeActionKind.RefactorRewrite = 'refactor.rewrite';
\r
1325 * Base kind for source actions: `source`
\r
1327 * Source code actions apply to the entire file.
\r
1329 CodeActionKind.Source = 'source';
\r
1331 * Base kind for an organize imports source action: `source.organizeImports`
\r
1333 CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
\r
1335 * Base kind for auto-fix source actions: `source.fixAll`.
\r
1337 * Fix all actions automatically fix errors that have a clear fix that do not require user input.
\r
1338 * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
\r
1342 CodeActionKind.SourceFixAll = 'source.fixAll';
\r
1343 })(CodeActionKind || (CodeActionKind = {}));
\r
1345 * The CodeActionContext namespace provides helper functions to work with
\r
1346 * [CodeActionContext](#CodeActionContext) literals.
\r
1348 var CodeActionContext;
\r
1349 (function (CodeActionContext) {
\r
1351 * Creates a new CodeActionContext literal.
\r
1353 function create(diagnostics, only) {
\r
1354 var result = { diagnostics: diagnostics };
\r
1355 if (only !== void 0 && only !== null) {
\r
1356 result.only = only;
\r
1360 CodeActionContext.create = create;
\r
1362 * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
\r
1364 function is(value) {
\r
1365 var candidate = value;
\r
1366 return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
\r
1368 CodeActionContext.is = is;
\r
1369 })(CodeActionContext || (CodeActionContext = {}));
\r
1371 (function (CodeAction) {
\r
1372 function create(title, commandOrEdit, kind) {
\r
1373 var result = { title: title };
\r
1374 if (Command.is(commandOrEdit)) {
\r
1375 result.command = commandOrEdit;
\r
1378 result.edit = commandOrEdit;
\r
1380 if (kind !== void 0) {
\r
1381 result.kind = kind;
\r
1385 CodeAction.create = create;
\r
1386 function is(value) {
\r
1387 var candidate = value;
\r
1388 return candidate && Is.string(candidate.title) &&
\r
1389 (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
\r
1390 (candidate.kind === void 0 || Is.string(candidate.kind)) &&
\r
1391 (candidate.edit !== void 0 || candidate.command !== void 0) &&
\r
1392 (candidate.command === void 0 || Command.is(candidate.command)) &&
\r
1393 (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&
\r
1394 (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
\r
1396 CodeAction.is = is;
\r
1397 })(CodeAction || (CodeAction = {}));
\r
1399 * The CodeLens namespace provides helper functions to work with
\r
1400 * [CodeLens](#CodeLens) literals.
\r
1403 (function (CodeLens) {
\r
1405 * Creates a new CodeLens literal.
\r
1407 function create(range, data) {
\r
1408 var result = { range: range };
\r
1409 if (Is.defined(data)) {
\r
1410 result.data = data;
\r
1414 CodeLens.create = create;
\r
1416 * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
\r
1418 function is(value) {
\r
1419 var candidate = value;
\r
1420 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
\r
1423 })(CodeLens || (CodeLens = {}));
\r
1425 * The FormattingOptions namespace provides helper functions to work with
\r
1426 * [FormattingOptions](#FormattingOptions) literals.
\r
1428 var FormattingOptions;
\r
1429 (function (FormattingOptions) {
\r
1431 * Creates a new FormattingOptions literal.
\r
1433 function create(tabSize, insertSpaces) {
\r
1434 return { tabSize: tabSize, insertSpaces: insertSpaces };
\r
1436 FormattingOptions.create = create;
\r
1438 * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
\r
1440 function is(value) {
\r
1441 var candidate = value;
\r
1442 return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
\r
1444 FormattingOptions.is = is;
\r
1445 })(FormattingOptions || (FormattingOptions = {}));
\r
1447 * The DocumentLink namespace provides helper functions to work with
\r
1448 * [DocumentLink](#DocumentLink) literals.
\r
1451 (function (DocumentLink) {
\r
1453 * Creates a new DocumentLink literal.
\r
1455 function create(range, target, data) {
\r
1456 return { range: range, target: target, data: data };
\r
1458 DocumentLink.create = create;
\r
1460 * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
\r
1462 function is(value) {
\r
1463 var candidate = value;
\r
1464 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
\r
1466 DocumentLink.is = is;
\r
1467 })(DocumentLink || (DocumentLink = {}));
\r
1469 * The SelectionRange namespace provides helper function to work with
\r
1470 * SelectionRange literals.
\r
1472 var SelectionRange;
\r
1473 (function (SelectionRange) {
\r
1475 * Creates a new SelectionRange
\r
1476 * @param range the range.
\r
1477 * @param parent an optional parent.
\r
1479 function create(range, parent) {
\r
1480 return { range: range, parent: parent };
\r
1482 SelectionRange.create = create;
\r
1483 function is(value) {
\r
1484 var candidate = value;
\r
1485 return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
\r
1487 SelectionRange.is = is;
\r
1488 })(SelectionRange || (SelectionRange = {}));
\r
1489 var EOL = ['\n', '\r\n', '\r'];
\r
1491 * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
\r
1494 (function (TextDocument) {
\r
1496 * Creates a new ITextDocument literal from the given uri and content.
\r
1497 * @param uri The document's uri.
\r
1498 * @param languageId The document's language Id.
\r
1499 * @param content The document's content.
\r
1501 function create(uri, languageId, version, content) {
\r
1502 return new FullTextDocument(uri, languageId, version, content);
\r
1504 TextDocument.create = create;
\r
1506 * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
\r
1508 function is(value) {
\r
1509 var candidate = value;
\r
1510 return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
\r
1511 && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
\r
1513 TextDocument.is = is;
\r
1514 function applyEdits(document, edits) {
\r
1515 var text = document.getText();
\r
1516 var sortedEdits = mergeSort(edits, function (a, b) {
\r
1517 var diff = a.range.start.line - b.range.start.line;
\r
1519 return a.range.start.character - b.range.start.character;
\r
1523 var lastModifiedOffset = text.length;
\r
1524 for (var i = sortedEdits.length - 1; i >= 0; i--) {
\r
1525 var e = sortedEdits[i];
\r
1526 var startOffset = document.offsetAt(e.range.start);
\r
1527 var endOffset = document.offsetAt(e.range.end);
\r
1528 if (endOffset <= lastModifiedOffset) {
\r
1529 text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
\r
1532 throw new Error('Overlapping edit');
\r
1534 lastModifiedOffset = startOffset;
\r
1538 TextDocument.applyEdits = applyEdits;
\r
1539 function mergeSort(data, compare) {
\r
1540 if (data.length <= 1) {
\r
1544 var p = (data.length / 2) | 0;
\r
1545 var left = data.slice(0, p);
\r
1546 var right = data.slice(p);
\r
1547 mergeSort(left, compare);
\r
1548 mergeSort(right, compare);
\r
1552 while (leftIdx < left.length && rightIdx < right.length) {
\r
1553 var ret = compare(left[leftIdx], right[rightIdx]);
\r
1555 // smaller_equal -> take left to preserve order
\r
1556 data[i++] = left[leftIdx++];
\r
1559 // greater -> take right
\r
1560 data[i++] = right[rightIdx++];
\r
1563 while (leftIdx < left.length) {
\r
1564 data[i++] = left[leftIdx++];
\r
1566 while (rightIdx < right.length) {
\r
1567 data[i++] = right[rightIdx++];
\r
1571 })(TextDocument || (TextDocument = {}));
\r
1572 var FullTextDocument = /** @class */ (function () {
\r
1573 function FullTextDocument(uri, languageId, version, content) {
\r
1575 this._languageId = languageId;
\r
1576 this._version = version;
\r
1577 this._content = content;
\r
1578 this._lineOffsets = undefined;
\r
1580 Object.defineProperty(FullTextDocument.prototype, "uri", {
\r
1581 get: function () {
\r
1585 configurable: true
\r
1587 Object.defineProperty(FullTextDocument.prototype, "languageId", {
\r
1588 get: function () {
\r
1589 return this._languageId;
\r
1592 configurable: true
\r
1594 Object.defineProperty(FullTextDocument.prototype, "version", {
\r
1595 get: function () {
\r
1596 return this._version;
\r
1599 configurable: true
\r
1601 FullTextDocument.prototype.getText = function (range) {
\r
1603 var start = this.offsetAt(range.start);
\r
1604 var end = this.offsetAt(range.end);
\r
1605 return this._content.substring(start, end);
\r
1607 return this._content;
\r
1609 FullTextDocument.prototype.update = function (event, version) {
\r
1610 this._content = event.text;
\r
1611 this._version = version;
\r
1612 this._lineOffsets = undefined;
\r
1614 FullTextDocument.prototype.getLineOffsets = function () {
\r
1615 if (this._lineOffsets === undefined) {
\r
1616 var lineOffsets = [];
\r
1617 var text = this._content;
\r
1618 var isLineStart = true;
\r
1619 for (var i = 0; i < text.length; i++) {
\r
1620 if (isLineStart) {
\r
1621 lineOffsets.push(i);
\r
1622 isLineStart = false;
\r
1624 var ch = text.charAt(i);
\r
1625 isLineStart = (ch === '\r' || ch === '\n');
\r
1626 if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
\r
1630 if (isLineStart && text.length > 0) {
\r
1631 lineOffsets.push(text.length);
\r
1633 this._lineOffsets = lineOffsets;
\r
1635 return this._lineOffsets;
\r
1637 FullTextDocument.prototype.positionAt = function (offset) {
\r
1638 offset = Math.max(Math.min(offset, this._content.length), 0);
\r
1639 var lineOffsets = this.getLineOffsets();
\r
1640 var low = 0, high = lineOffsets.length;
\r
1642 return Position.create(0, offset);
\r
1644 while (low < high) {
\r
1645 var mid = Math.floor((low + high) / 2);
\r
1646 if (lineOffsets[mid] > offset) {
\r
1653 // low is the least x for which the line offset is larger than the current offset
\r
1654 // or array.length if no line offset is larger than the current offset
\r
1655 var line = low - 1;
\r
1656 return Position.create(line, offset - lineOffsets[line]);
\r
1658 FullTextDocument.prototype.offsetAt = function (position) {
\r
1659 var lineOffsets = this.getLineOffsets();
\r
1660 if (position.line >= lineOffsets.length) {
\r
1661 return this._content.length;
\r
1663 else if (position.line < 0) {
\r
1666 var lineOffset = lineOffsets[position.line];
\r
1667 var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
\r
1668 return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
\r
1670 Object.defineProperty(FullTextDocument.prototype, "lineCount", {
\r
1671 get: function () {
\r
1672 return this.getLineOffsets().length;
\r
1675 configurable: true
\r
1677 return FullTextDocument;
\r
1681 var toString = Object.prototype.toString;
\r
1682 function defined(value) {
\r
1683 return typeof value !== 'undefined';
\r
1685 Is.defined = defined;
\r
1686 function undefined(value) {
\r
1687 return typeof value === 'undefined';
\r
1689 Is.undefined = undefined;
\r
1690 function boolean(value) {
\r
1691 return value === true || value === false;
\r
1693 Is.boolean = boolean;
\r
1694 function string(value) {
\r
1695 return toString.call(value) === '[object String]';
\r
1697 Is.string = string;
\r
1698 function number(value) {
\r
1699 return toString.call(value) === '[object Number]';
\r
1701 Is.number = number;
\r
1702 function func(value) {
\r
1703 return toString.call(value) === '[object Function]';
\r
1706 function objectLiteral(value) {
\r
1707 // Strictly speaking class instances pass this check as well. Since the LSP
\r
1708 // doesn't use classes we ignore this for now. If we do we need to add something
\r
1709 // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
\r
1710 return value !== null && typeof value === 'object';
\r
1712 Is.objectLiteral = objectLiteral;
\r
1713 function typedArray(value, check) {
\r
1714 return Array.isArray(value) && value.every(check);
\r
1716 Is.typedArray = typedArray;
\r
1717 })(Is || (Is = {}));
\r
1738 /***/ (function(module, __webpack_exports__, __webpack_require__) {
1741 __webpack_require__.r(__webpack_exports__);
1742 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return URI; });
1743 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "uriToFsPath", function() { return uriToFsPath; });
1744 /*---------------------------------------------------------------------------------------------
1745 * Copyright (c) Microsoft Corporation. All rights reserved.
1746 * Licensed under the MIT License. See License.txt in the project root for license information.
1747 *--------------------------------------------------------------------------------------------*/
1749 var __extends = (undefined && undefined.__extends) || (function () {
1750 var extendStatics = function (d, b) {
1751 extendStatics = Object.setPrototypeOf ||
1752 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
1753 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
1754 return extendStatics(d, b);
1756 return function (d, b) {
1757 extendStatics(d, b);
1758 function __() { this.constructor = d; }
1759 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
1764 if (typeof process === 'object') {
1765 isWindows = process.platform === 'win32';
1767 else if (typeof navigator === 'object') {
1768 var userAgent = navigator.userAgent;
1769 isWindows = userAgent.indexOf('Windows') >= 0;
1771 function isHighSurrogate(charCode) {
1772 return (0xD800 <= charCode && charCode <= 0xDBFF);
1774 function isLowSurrogate(charCode) {
1775 return (0xDC00 <= charCode && charCode <= 0xDFFF);
1777 function isLowerAsciiHex(code) {
1778 return code >= 97 /* a */ && code <= 102 /* f */;
1780 function isLowerAsciiLetter(code) {
1781 return code >= 97 /* a */ && code <= 122 /* z */;
1783 function isUpperAsciiLetter(code) {
1784 return code >= 65 /* A */ && code <= 90 /* Z */;
1786 function isAsciiLetter(code) {
1787 return isLowerAsciiLetter(code) || isUpperAsciiLetter(code);
1790 var _schemePattern = /^\w[\w\d+.-]*$/;
1791 var _singleSlashStart = /^\//;
1792 var _doubleSlashStart = /^\/\//;
1793 function _validateUri(ret, _strict) {
1794 // scheme, must be set
1795 if (!ret.scheme && _strict) {
1796 throw new Error("[UriError]: Scheme is missing: {scheme: \"\", authority: \"" + ret.authority + "\", path: \"" + ret.path + "\", query: \"" + ret.query + "\", fragment: \"" + ret.fragment + "\"}");
1798 // scheme, https://tools.ietf.org/html/rfc3986#section-3.1
1799 // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
1800 if (ret.scheme && !_schemePattern.test(ret.scheme)) {
1801 throw new Error('[UriError]: Scheme contains illegal characters.');
1803 // path, http://tools.ietf.org/html/rfc3986#section-3.3
1804 // If a URI contains an authority component, then the path component
1805 // must either be empty or begin with a slash ("/") character. If a URI
1806 // does not contain an authority component, then the path cannot begin
1807 // with two slash characters ("//").
1809 if (ret.authority) {
1810 if (!_singleSlashStart.test(ret.path)) {
1811 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');
1815 if (_doubleSlashStart.test(ret.path)) {
1816 throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
1821 // for a while we allowed uris *without* schemes and this is the migration
1822 // for them, e.g. an uri without scheme and without strict-mode warns and falls
1823 // back to the file-scheme. that should cause the least carnage and still be a
1825 function _schemeFix(scheme, _strict) {
1826 if (!scheme && !_strict) {
1831 // implements a bit of https://tools.ietf.org/html/rfc3986#section-5
1832 function _referenceResolution(scheme, path) {
1833 // the slash-character is our 'default base' as we don't
1834 // support constructing URIs relative to other URIs. This
1835 // also means that we alter and potentially break paths.
1836 // see https://tools.ietf.org/html/rfc3986#section-5.1.4
1844 else if (path[0] !== _slash) {
1845 path = _slash + path;
1853 var _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
1855 * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
1856 * This class is a simple parser which creates the basic component parts
1857 * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
1861 * foo://example.com:8042/over/there?name=ferret#nose
1862 * \_/ \______________/\_________/ \_________/ \__/
1864 * scheme authority path query fragment
1865 * | _____________________|__
1867 * urn:example:animal:ferret:nose
1870 var URI = /** @class */ (function () {
1874 function URI(schemeOrData, authority, path, query, fragment, _strict) {
1875 if (_strict === void 0) { _strict = false; }
1876 if (typeof schemeOrData === 'object') {
1877 this.scheme = schemeOrData.scheme || _empty;
1878 this.authority = schemeOrData.authority || _empty;
1879 this.path = schemeOrData.path || _empty;
1880 this.query = schemeOrData.query || _empty;
1881 this.fragment = schemeOrData.fragment || _empty;
1882 // no validation because it's this URI
1883 // that creates uri components.
1884 // _validateUri(this);
1887 this.scheme = _schemeFix(schemeOrData, _strict);
1888 this.authority = authority || _empty;
1889 this.path = _referenceResolution(this.scheme, path || _empty);
1890 this.query = query || _empty;
1891 this.fragment = fragment || _empty;
1892 _validateUri(this, _strict);
1895 URI.isUri = function (thing) {
1896 if (thing instanceof URI) {
1902 return typeof thing.authority === 'string'
1903 && typeof thing.fragment === 'string'
1904 && typeof thing.path === 'string'
1905 && typeof thing.query === 'string'
1906 && typeof thing.scheme === 'string'
1907 && typeof thing.fsPath === 'function'
1908 && typeof thing.with === 'function'
1909 && typeof thing.toString === 'function';
1911 Object.defineProperty(URI.prototype, "fsPath", {
1912 // ---- filesystem path -----------------------
1914 * Returns a string representing the corresponding file system path of this URI.
1915 * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
1916 * platform specific path separator.
1918 * * Will *not* validate the path for invalid characters and semantics.
1919 * * Will *not* look at the scheme of this URI.
1920 * * The result shall *not* be used for display purposes but for accessing a file on disk.
1923 * The *difference* to `URI#path` is the use of the platform specific separator and the handling
1924 * of UNC paths. See the below sample of a file-uri with an authority (UNC path).
1927 const u = URI.parse('file://server/c$/folder/file.txt')
1928 u.authority === 'server'
1929 u.path === '/shares/c$/file.txt'
1930 u.fsPath === '\\server\c$\folder\file.txt'
1933 * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,
1934 * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working
1935 * with URIs that represent files on disk (`file` scheme).
1938 // if (this.scheme !== 'file') {
1939 // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
1941 return uriToFsPath(this, false);
1946 // ---- modify to new -------------------------
1947 URI.prototype.with = function (change) {
1951 var scheme = change.scheme, authority = change.authority, path = change.path, query = change.query, fragment = change.fragment;
1952 if (scheme === undefined) {
1953 scheme = this.scheme;
1955 else if (scheme === null) {
1958 if (authority === undefined) {
1959 authority = this.authority;
1961 else if (authority === null) {
1964 if (path === undefined) {
1967 else if (path === null) {
1970 if (query === undefined) {
1973 else if (query === null) {
1976 if (fragment === undefined) {
1977 fragment = this.fragment;
1979 else if (fragment === null) {
1982 if (scheme === this.scheme
1983 && authority === this.authority
1984 && path === this.path
1985 && query === this.query
1986 && fragment === this.fragment) {
1989 return new _URI(scheme, authority, path, query, fragment);
1991 // ---- parse & validate ------------------------
1993 * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`,
1994 * `file:///usr/home`, or `scheme:with/path`.
1996 * @param value A string which represents an URI (see `URI#toString`).
1998 URI.parse = function (value, _strict) {
1999 if (_strict === void 0) { _strict = false; }
2000 var match = _regexp.exec(value);
2002 return new _URI(_empty, _empty, _empty, _empty, _empty);
2004 return new _URI(match[2] || _empty, percentDecode(match[4] || _empty), percentDecode(match[5] || _empty), percentDecode(match[7] || _empty), percentDecode(match[9] || _empty), _strict);
2007 * Creates a new URI from a file system path, e.g. `c:\my\files`,
2008 * `/usr/home`, or `\\server\share\some\path`.
2010 * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
2011 * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
2012 * `URI.parse('file://' + path)` because the path might contain characters that are
2013 * interpreted (# and ?). See the following sample:
2015 const good = URI.file('/coding/c#/project1');
2016 good.scheme === 'file';
2017 good.path === '/coding/c#/project1';
2018 good.fragment === '';
2019 const bad = URI.parse('file://' + '/coding/c#/project1');
2020 bad.scheme === 'file';
2021 bad.path === '/coding/c'; // path is now broken
2022 bad.fragment === '/project1';
2025 * @param path A file system path (see `URI#fsPath`)
2027 URI.file = function (path) {
2028 var authority = _empty;
2029 // normalize to fwd-slashes on windows,
2030 // on other systems bwd-slashes are valid
2031 // filename character, eg /f\oo/ba\r.txt
2033 path = path.replace(/\\/g, _slash);
2035 // check for authority as used in UNC shares
2036 // or use the path as given
2037 if (path[0] === _slash && path[1] === _slash) {
2038 var idx = path.indexOf(_slash, 2);
2040 authority = path.substring(2);
2044 authority = path.substring(2, idx);
2045 path = path.substring(idx) || _slash;
2048 return new _URI('file', authority, path, _empty, _empty);
2050 URI.from = function (components) {
2051 return new _URI(components.scheme, components.authority, components.path, components.query, components.fragment);
2054 // * Join a URI path with path fragments and normalizes the resulting path.
2056 // * @param uri The input URI.
2057 // * @param pathFragment The path fragment to add to the URI path.
2058 // * @returns The resulting URI.
2060 // static joinPath(uri: URI, ...pathFragment: string[]): URI {
2062 // throw new Error(`[UriError]: cannot call joinPaths on URI without path`);
2064 // let newPath: string;
2065 // if (isWindows && uri.scheme === 'file') {
2066 // newPath = URI.file(paths.win32.join(uriToFsPath(uri, true), ...pathFragment)).path;
2068 // newPath = paths.posix.join(uri.path, ...pathFragment);
2070 // return uri.with({ path: newPath });
2072 // ---- printing/externalize ---------------------------
2074 * Creates a string representation for this URI. It's guaranteed that calling
2075 * `URI.parse` with the result of this function creates an URI which is equal
2078 * * The result shall *not* be used for display purposes but for externalization or transport.
2079 * * The result will be encoded using the percentage encoding and encoding happens mostly
2080 * ignore the scheme-specific encoding rules.
2082 * @param skipEncoding Do not encode the result, default is `false`
2084 URI.prototype.toString = function (skipEncoding) {
2085 if (skipEncoding === void 0) { skipEncoding = false; }
2086 return _asFormatted(this, skipEncoding);
2088 URI.prototype.toJSON = function () {
2091 URI.revive = function (data) {
2095 else if (data instanceof URI) {
2099 var result = new _URI(data);
2100 result._formatted = data.external;
2101 result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null;
2108 var _pathSepMarker = isWindows ? 1 : undefined;
2109 // eslint-disable-next-line @typescript-eslint/class-name-casing
2110 var _URI = /** @class */ (function (_super) {
2111 __extends(_URI, _super);
2113 var _this = _super !== null && _super.apply(this, arguments) || this;
2114 _this._formatted = null;
2115 _this._fsPath = null;
2118 Object.defineProperty(_URI.prototype, "fsPath", {
2120 if (!this._fsPath) {
2121 this._fsPath = uriToFsPath(this, false);
2123 return this._fsPath;
2128 _URI.prototype.toString = function (skipEncoding) {
2129 if (skipEncoding === void 0) { skipEncoding = false; }
2130 if (!skipEncoding) {
2131 if (!this._formatted) {
2132 this._formatted = _asFormatted(this, false);
2134 return this._formatted;
2137 // we don't cache that
2138 return _asFormatted(this, true);
2141 _URI.prototype.toJSON = function () {
2147 res.fsPath = this._fsPath;
2148 res._sep = _pathSepMarker;
2150 if (this._formatted) {
2151 res.external = this._formatted;
2155 res.path = this.path;
2158 res.scheme = this.scheme;
2160 if (this.authority) {
2161 res.authority = this.authority;
2164 res.query = this.query;
2166 if (this.fragment) {
2167 res.fragment = this.fragment;
2173 // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
2174 var encodeTable = (_a = {},
2175 _a[58 /* Colon */] = '%3A',
2176 _a[47 /* Slash */] = '%2F',
2177 _a[63 /* QuestionMark */] = '%3F',
2178 _a[35 /* Hash */] = '%23',
2179 _a[91 /* OpenSquareBracket */] = '%5B',
2180 _a[93 /* CloseSquareBracket */] = '%5D',
2181 _a[64 /* AtSign */] = '%40',
2182 _a[33 /* ExclamationMark */] = '%21',
2183 _a[36 /* DollarSign */] = '%24',
2184 _a[38 /* Ampersand */] = '%26',
2185 _a[39 /* SingleQuote */] = '%27',
2186 _a[40 /* OpenParen */] = '%28',
2187 _a[41 /* CloseParen */] = '%29',
2188 _a[42 /* Asterisk */] = '%2A',
2189 _a[43 /* Plus */] = '%2B',
2190 _a[44 /* Comma */] = '%2C',
2191 _a[59 /* Semicolon */] = '%3B',
2192 _a[61 /* Equals */] = '%3D',
2193 _a[32 /* Space */] = '%20',
2195 function encodeURIComponentFast(uriComponent, allowSlash) {
2196 var res = undefined;
2197 var nativeEncodePos = -1;
2198 for (var pos = 0; pos < uriComponent.length; pos++) {
2199 var code = uriComponent.charCodeAt(pos);
2200 // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3
2201 if ((code >= 97 /* a */ && code <= 122 /* z */)
2202 || (code >= 65 /* A */ && code <= 90 /* Z */)
2203 || (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */)
2204 || code === 45 /* Dash */
2205 || code === 46 /* Period */
2206 || code === 95 /* Underline */
2207 || code === 126 /* Tilde */
2208 || (allowSlash && code === 47 /* Slash */)) {
2209 // check if we are delaying native encode
2210 if (nativeEncodePos !== -1) {
2211 res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
2212 nativeEncodePos = -1;
2214 // check if we write into a new string (by default we try to return the param)
2215 if (res !== undefined) {
2216 res += uriComponent.charAt(pos);
2220 // encoding needed, we need to allocate a new string
2221 if (res === undefined) {
2222 res = uriComponent.substr(0, pos);
2224 // check with default table first
2225 var escaped = encodeTable[code];
2226 if (escaped !== undefined) {
2227 // check if we are delaying native encode
2228 if (nativeEncodePos !== -1) {
2229 res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
2230 nativeEncodePos = -1;
2232 // append escaped variant to result
2235 else if (nativeEncodePos === -1) {
2236 // use native encode only when needed
2237 nativeEncodePos = pos;
2241 if (nativeEncodePos !== -1) {
2242 res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
2244 return res !== undefined ? res : uriComponent;
2246 function encodeURIComponentMinimal(path) {
2247 var res = undefined;
2248 for (var pos = 0; pos < path.length; pos++) {
2249 var code = path.charCodeAt(pos);
2250 if (code === 35 /* Hash */ || code === 63 /* QuestionMark */) {
2251 if (res === undefined) {
2252 res = path.substr(0, pos);
2254 res += encodeTable[code];
2257 if (res !== undefined) {
2262 return res !== undefined ? res : path;
2265 * Compute `fsPath` for the given uri
2267 function uriToFsPath(uri, keepDriveLetterCasing) {
2269 if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') {
2270 // unc path: file://shares/c$/far/boo
2271 value = "//" + uri.authority + uri.path;
2273 else if (uri.path.charCodeAt(0) === 47 /* Slash */
2274 && (uri.path.charCodeAt(1) >= 65 /* A */ && uri.path.charCodeAt(1) <= 90 /* Z */ || uri.path.charCodeAt(1) >= 97 /* a */ && uri.path.charCodeAt(1) <= 122 /* z */)
2275 && uri.path.charCodeAt(2) === 58 /* Colon */) {
2276 if (!keepDriveLetterCasing) {
2277 // windows drive letter: file:///c:/far/boo
2278 value = uri.path[1].toLowerCase() + uri.path.substr(2);
2281 value = uri.path.substr(1);
2289 value = value.replace(/\//g, '\\');
2294 * Create the external version of a uri
2296 function _asFormatted(uri, skipEncoding) {
2297 var encoder = !skipEncoding
2298 ? encodeURIComponentFast
2299 : encodeURIComponentMinimal;
2301 var scheme = uri.scheme, authority = uri.authority, path = uri.path, query = uri.query, fragment = uri.fragment;
2306 if (authority || scheme === 'file') {
2311 var idx = authority.indexOf('@');
2314 var userinfo = authority.substr(0, idx);
2315 authority = authority.substr(idx + 1);
2316 idx = userinfo.indexOf(':');
2318 res += encoder(userinfo, false);
2321 // <user>:<pass>@<auth>
2322 res += encoder(userinfo.substr(0, idx), false);
2324 res += encoder(userinfo.substr(idx + 1), false);
2328 authority = authority.toLowerCase();
2329 idx = authority.indexOf(':');
2331 res += encoder(authority, false);
2335 res += encoder(authority.substr(0, idx), false);
2336 res += authority.substr(idx);
2340 // lower-case windows drive letters in /C:/fff or C:/fff
2341 if (path.length >= 3 && path.charCodeAt(0) === 47 /* Slash */ && path.charCodeAt(2) === 58 /* Colon */) {
2342 var code = path.charCodeAt(1);
2343 if (code >= 65 /* A */ && code <= 90 /* Z */) {
2344 path = "/" + String.fromCharCode(code + 32) + ":" + path.substr(3); // "/c:".length === 3
2347 else if (path.length >= 2 && path.charCodeAt(1) === 58 /* Colon */) {
2348 var code = path.charCodeAt(0);
2349 if (code >= 65 /* A */ && code <= 90 /* Z */) {
2350 path = String.fromCharCode(code + 32) + ":" + path.substr(2); // "/c:".length === 3
2353 // encode the rest of the path
2354 res += encoder(path, true);
2358 res += encoder(query, false);
2362 res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment;
2367 function decodeURIComponentGraceful(str) {
2369 return decodeURIComponent(str);
2372 if (str.length > 3) {
2373 return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3));
2380 var _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g;
2381 function percentDecode(str) {
2382 if (!str.match(_rEncodedAsHex)) {
2385 return str.replace(_rEncodedAsHex, function (match) { return decodeURIComponentGraceful(match); });
2394 /***/ (function(module, exports, __webpack_require__) {
2398 /*---------------------------------------------------------------------------------------------
2399 * Copyright (c) Microsoft Corporation. All rights reserved.
2400 * Licensed under the MIT License. See License.txt in the project root for license information.
2401 *--------------------------------------------------------------------------------------------*/
2402 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
2403 if (k2 === undefined) k2 = k;
2404 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
2405 }) : (function(o, m, k, k2) {
2406 if (k2 === undefined) k2 = k;
2409 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
2410 Object.defineProperty(o, "default", { enumerable: true, value: v });
2411 }) : function(o, v) {
2414 var __importStar = (this && this.__importStar) || function (mod) {
2415 if (mod && mod.__esModule) return mod;
2417 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
2418 __setModuleDefault(result, mod);
2421 Object.defineProperty(exports, "__esModule", { value: true });
2422 const node_1 = __webpack_require__(40);
2423 const runner_1 = __webpack_require__(88);
2424 const jsonServer_1 = __webpack_require__(89);
2425 const request_light_1 = __webpack_require__(115);
2426 const vscode_uri_1 = __webpack_require__(35);
2427 const fs = __importStar(__webpack_require__(2));
2428 // Create a connection for the server.
2429 const connection = node_1.createConnection();
2430 console.log = connection.console.log.bind(connection.console);
2431 console.error = connection.console.error.bind(connection.console);
2432 process.on('unhandledRejection', (e) => {
2433 connection.console.error(runner_1.formatError(`Unhandled exception`, e));
2435 function getHTTPRequestService() {
2437 getContent(uri, _encoding) {
2438 const headers = { 'Accept-Encoding': 'gzip, deflate' };
2439 return request_light_1.xhr({ url: uri, followRedirects: 5, headers }).then(response => {
2440 return response.responseText;
2442 return Promise.reject(error.responseText || request_light_1.getErrorStatusDescription(error.status) || error.toString());
2447 function getFileRequestService() {
2449 getContent(location, encoding) {
2450 return new Promise((c, e) => {
2451 const uri = vscode_uri_1.URI.parse(location);
2452 fs.readFile(uri.fsPath, encoding, (err, buf) => {
2462 jsonServer_1.startServer(connection, { file: getFileRequestService(), http: getHTTPRequestService(), configureHttpRequests: request_light_1.configure });
2467 /***/ (function(module, exports, __webpack_require__) {
2470 /* --------------------------------------------------------------------------------------------
2471 * Copyright (c) Microsoft Corporation. All rights reserved.
2472 * Licensed under the MIT License. See License.txt in the project root for license information.
2473 * ----------------------------------------------------------------------------------------- */
2476 module.exports = __webpack_require__(41);
2480 /***/ (function(module, exports, __webpack_require__) {
2484 /* --------------------------------------------------------------------------------------------
2485 * Copyright (c) Microsoft Corporation. All rights reserved.
2486 * Licensed under the MIT License. See License.txt in the project root for license information.
2487 * ------------------------------------------------------------------------------------------ */
2488 /// <reference path="../../typings/thenable.d.ts" />
2489 function __export(m) {
2490 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
2492 Object.defineProperty(exports, "__esModule", { value: true });
2493 const Is = __webpack_require__(42);
2494 const server_1 = __webpack_require__(43);
2495 const fm = __webpack_require__(82);
2496 const node_1 = __webpack_require__(85);
2497 __export(__webpack_require__(86));
2500 Files.uriToFilePath = fm.uriToFilePath;
2501 Files.resolveGlobalNodePath = fm.resolveGlobalNodePath;
2502 Files.resolveGlobalYarnPath = fm.resolveGlobalYarnPath;
2503 Files.resolve = fm.resolve;
2504 Files.resolveModulePath = fm.resolveModulePath;
2505 })(Files = exports.Files || (exports.Files = {}));
2506 let _shutdownReceived = false;
2507 let exitTimer = undefined;
2508 function setupExitTimer() {
2509 const argName = '--clientProcessId';
2510 function runTimer(value) {
2512 let processId = parseInt(value);
2513 if (!isNaN(processId)) {
2514 exitTimer = setInterval(() => {
2516 process.kill(processId, 0);
2519 // Parent process doesn't exist anymore. Exit the server.
2520 process.exit(_shutdownReceived ? 0 : 1);
2529 for (let i = 2; i < process.argv.length; i++) {
2530 let arg = process.argv[i];
2531 if (arg === argName && i + 1 < process.argv.length) {
2532 runTimer(process.argv[i + 1]);
2536 let args = arg.split('=');
2537 if (args[0] === argName) {
2545 initialize: (params) => {
2546 const processId = params.processId;
2547 if (Is.number(processId) && exitTimer === undefined) {
2548 // We received a parent process id. Set up a timer to periodically check
2549 // if the parent is still alive.
2552 process.kill(processId, 0);
2555 // Parent process doesn't exist anymore. Exit the server.
2556 process.exit(_shutdownReceived ? 0 : 1);
2561 get shutdownReceived() {
2562 return _shutdownReceived;
2564 set shutdownReceived(value) {
2565 _shutdownReceived = value;
2571 function createConnection(arg1, arg2, arg3, arg4) {
2576 if (arg1 !== void 0 && arg1.__brand === 'features') {
2582 if (node_1.ConnectionStrategy.is(arg1) || node_1.ConnectionOptions.is(arg1)) {
2590 return _createConnection(input, output, options, factories);
2592 exports.createConnection = createConnection;
2593 function _createConnection(input, output, options, factories) {
2594 if (!input && !output && process.argv.length > 2) {
2596 let pipeName = void 0;
2597 let argv = process.argv.slice(2);
2598 for (let i = 0; i < argv.length; i++) {
2600 if (arg === '--node-ipc') {
2601 input = new node_1.IPCMessageReader(process);
2602 output = new node_1.IPCMessageWriter(process);
2605 else if (arg === '--stdio') {
2606 input = process.stdin;
2607 output = process.stdout;
2610 else if (arg === '--socket') {
2611 port = parseInt(argv[i + 1]);
2614 else if (arg === '--pipe') {
2615 pipeName = argv[i + 1];
2619 var args = arg.split('=');
2620 if (args[0] === '--socket') {
2621 port = parseInt(args[1]);
2624 else if (args[0] === '--pipe') {
2631 let transport = node_1.createServerSocketTransport(port);
2632 input = transport[0];
2633 output = transport[1];
2635 else if (pipeName) {
2636 let transport = node_1.createServerPipeTransport(pipeName);
2637 input = transport[0];
2638 output = transport[1];
2641 var commandLineMessage = 'Use arguments of createConnection or set command line parameters: \'--node-ipc\', \'--stdio\' or \'--socket={number}\'';
2643 throw new Error('Connection input stream is not set. ' + commandLineMessage);
2646 throw new Error('Connection output stream is not set. ' + commandLineMessage);
2648 // Backwards compatibility
2649 if (Is.func(input.read) && Is.func(input.on)) {
2650 let inputStream = input;
2651 inputStream.on('end', () => {
2652 process.exit(_shutdownReceived ? 0 : 1);
2654 inputStream.on('close', () => {
2655 process.exit(_shutdownReceived ? 0 : 1);
2658 const connectionFactory = (logger) => {
2659 return node_1.createProtocolConnection(input, output, logger, options);
2661 return server_1.createConnection(connectionFactory, watchDog, factories);
2663 //# sourceMappingURL=main.js.map
2667 /***/ (function(module, exports, __webpack_require__) {
2671 /* --------------------------------------------------------------------------------------------
2672 * Copyright (c) Microsoft Corporation. All rights reserved.
2673 * Licensed under the MIT License. See License.txt in the project root for license information.
2674 * ------------------------------------------------------------------------------------------ */
2675 Object.defineProperty(exports, "__esModule", { value: true });
2676 function boolean(value) {
2677 return value === true || value === false;
2679 exports.boolean = boolean;
2680 function string(value) {
2681 return typeof value === 'string' || value instanceof String;
2683 exports.string = string;
2684 function number(value) {
2685 return typeof value === 'number' || value instanceof Number;
2687 exports.number = number;
2688 function error(value) {
2689 return value instanceof Error;
2691 exports.error = error;
2692 function func(value) {
2693 return typeof value === 'function';
2695 exports.func = func;
2696 function array(value) {
2697 return Array.isArray(value);
2699 exports.array = array;
2700 function stringArray(value) {
2701 return array(value) && value.every(elem => string(elem));
2703 exports.stringArray = stringArray;
2704 function typedArray(value, check) {
2705 return Array.isArray(value) && value.every(check);
2707 exports.typedArray = typedArray;
2708 function thenable(value) {
2709 return value && func(value.then);
2711 exports.thenable = thenable;
2712 //# sourceMappingURL=is.js.map
2716 /***/ (function(module, exports, __webpack_require__) {
2720 /* --------------------------------------------------------------------------------------------
2721 * Copyright (c) Microsoft Corporation. All rights reserved.
2722 * Licensed under the MIT License. See License.txt in the project root for license information.
2723 * ------------------------------------------------------------------------------------------ */
2724 Object.defineProperty(exports, "__esModule", { value: true });
2725 const vscode_languageserver_protocol_1 = __webpack_require__(44);
2726 const Is = __webpack_require__(42);
2727 const UUID = __webpack_require__(77);
2728 const progress_1 = __webpack_require__(78);
2729 const configuration_1 = __webpack_require__(79);
2730 const workspaceFolders_1 = __webpack_require__(80);
2731 const callHierarchy_1 = __webpack_require__(81);
2732 function null2Undefined(value) {
2733 if (value === null) {
2739 * A manager for simple text documents
2741 class TextDocuments {
2743 * Create a new text document manager.
2745 constructor(configuration) {
2746 this._documents = Object.create(null);
2747 this._configuration = configuration;
2748 this._onDidChangeContent = new vscode_languageserver_protocol_1.Emitter();
2749 this._onDidOpen = new vscode_languageserver_protocol_1.Emitter();
2750 this._onDidClose = new vscode_languageserver_protocol_1.Emitter();
2751 this._onDidSave = new vscode_languageserver_protocol_1.Emitter();
2752 this._onWillSave = new vscode_languageserver_protocol_1.Emitter();
2755 * An event that fires when a text document managed by this manager
2756 * has been opened or the content changes.
2758 get onDidChangeContent() {
2759 return this._onDidChangeContent.event;
2762 * An event that fires when a text document managed by this manager
2766 return this._onDidOpen.event;
2769 * An event that fires when a text document managed by this manager
2773 return this._onWillSave.event;
2776 * Sets a handler that will be called if a participant wants to provide
2777 * edits during a text document save.
2779 onWillSaveWaitUntil(handler) {
2780 this._willSaveWaitUntil = handler;
2783 * An event that fires when a text document managed by this manager
2787 return this._onDidSave.event;
2790 * An event that fires when a text document managed by this manager
2794 return this._onDidClose.event;
2797 * Returns the document for the given URI. Returns undefined if
2798 * the document is not mananged by this instance.
2800 * @param uri The text document's URI to retrieve.
2801 * @return the text document or `undefined`.
2804 return this._documents[uri];
2807 * Returns all text documents managed by this instance.
2809 * @return all text documents.
2812 return Object.keys(this._documents).map(key => this._documents[key]);
2815 * Returns the URIs of all text documents managed by this instance.
2817 * @return the URI's of all text documents.
2820 return Object.keys(this._documents);
2823 * Listens for `low level` notification on the given connection to
2824 * update the text documents managed by this instance.
2826 * Please note that the connection only provides handlers not an event model. Therefore
2827 * listening on a connection will overwrite the following handlers on a connection:
2828 * `onDidOpenTextDocument`, `onDidChangeTextDocument`, `onDidCloseTextDocument`,
2829 * `onWillSaveTextDocument`, `onWillSaveTextDocumentWaitUntil` and `onDidSaveTextDocument`.
2831 * Use the correspnding events on the TextDocuments instance instead.
2833 * @param connection The connection to listen on.
2835 listen(connection) {
2836 connection.__textDocumentSync = vscode_languageserver_protocol_1.TextDocumentSyncKind.Full;
2837 connection.onDidOpenTextDocument((event) => {
2838 let td = event.textDocument;
2839 let document = this._configuration.create(td.uri, td.languageId, td.version, td.text);
2840 this._documents[td.uri] = document;
2841 let toFire = Object.freeze({ document });
2842 this._onDidOpen.fire(toFire);
2843 this._onDidChangeContent.fire(toFire);
2845 connection.onDidChangeTextDocument((event) => {
2846 let td = event.textDocument;
2847 let changes = event.contentChanges;
2848 if (changes.length === 0) {
2851 let document = this._documents[td.uri];
2852 const { version } = td;
2853 if (version === null || version === undefined) {
2854 throw new Error(`Received document change event for ${td.uri} without valid version identifier`);
2856 document = this._configuration.update(document, changes, version);
2857 this._documents[td.uri] = document;
2858 this._onDidChangeContent.fire(Object.freeze({ document }));
2860 connection.onDidCloseTextDocument((event) => {
2861 let document = this._documents[event.textDocument.uri];
2863 delete this._documents[event.textDocument.uri];
2864 this._onDidClose.fire(Object.freeze({ document }));
2867 connection.onWillSaveTextDocument((event) => {
2868 let document = this._documents[event.textDocument.uri];
2870 this._onWillSave.fire(Object.freeze({ document, reason: event.reason }));
2873 connection.onWillSaveTextDocumentWaitUntil((event, token) => {
2874 let document = this._documents[event.textDocument.uri];
2875 if (document && this._willSaveWaitUntil) {
2876 return this._willSaveWaitUntil(Object.freeze({ document, reason: event.reason }), token);
2882 connection.onDidSaveTextDocument((event) => {
2883 let document = this._documents[event.textDocument.uri];
2885 this._onDidSave.fire(Object.freeze({ document }));
2890 exports.TextDocuments = TextDocuments;
2892 * Helps tracking error message. Equal occurences of the same
2893 * message are only stored once. This class is for example
2894 * useful if text documents are validated in a loop and equal
2895 * error message should be folded into one.
2897 class ErrorMessageTracker {
2899 this._messages = Object.create(null);
2902 * Add a message to the tracker.
2904 * @param message The message to add.
2907 let count = this._messages[message];
2912 this._messages[message] = count;
2915 * Send all tracked messages to the connection's window.
2917 * @param connection The connection established between client and server.
2919 sendErrors(connection) {
2920 Object.keys(this._messages).forEach(message => {
2921 connection.window.showErrorMessage(message);
2925 exports.ErrorMessageTracker = ErrorMessageTracker;
2926 class RemoteConsoleImpl {
2929 rawAttach(connection) {
2930 this._rawConnection = connection;
2932 attach(connection) {
2933 this._connection = connection;
2936 if (!this._connection) {
2937 throw new Error('Remote is not attached to a connection yet.');
2939 return this._connection;
2941 fillServerCapabilities(_capabilities) {
2943 initialize(_capabilities) {
2946 this.send(vscode_languageserver_protocol_1.MessageType.Error, message);
2949 this.send(vscode_languageserver_protocol_1.MessageType.Warning, message);
2952 this.send(vscode_languageserver_protocol_1.MessageType.Info, message);
2955 this.send(vscode_languageserver_protocol_1.MessageType.Log, message);
2957 send(type, message) {
2958 if (this._rawConnection) {
2959 this._rawConnection.sendNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, { type, message });
2963 class _RemoteWindowImpl {
2966 attach(connection) {
2967 this._connection = connection;
2970 if (!this._connection) {
2971 throw new Error('Remote is not attached to a connection yet.');
2973 return this._connection;
2975 initialize(_capabilities) {
2977 fillServerCapabilities(_capabilities) {
2979 showErrorMessage(message, ...actions) {
2980 let params = { type: vscode_languageserver_protocol_1.MessageType.Error, message, actions };
2981 return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
2983 showWarningMessage(message, ...actions) {
2984 let params = { type: vscode_languageserver_protocol_1.MessageType.Warning, message, actions };
2985 return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
2987 showInformationMessage(message, ...actions) {
2988 let params = { type: vscode_languageserver_protocol_1.MessageType.Info, message, actions };
2989 return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
2992 const RemoteWindowImpl = progress_1.ProgressFeature(_RemoteWindowImpl);
2993 var BulkRegistration;
2994 (function (BulkRegistration) {
2996 * Creates a new bulk registration.
2997 * @return an empty bulk registration.
3000 return new BulkRegistrationImpl();
3002 BulkRegistration.create = create;
3003 })(BulkRegistration = exports.BulkRegistration || (exports.BulkRegistration = {}));
3004 class BulkRegistrationImpl {
3006 this._registrations = [];
3007 this._registered = new Set();
3009 add(type, registerOptions) {
3010 const method = Is.string(type) ? type : type.method;
3011 if (this._registered.has(method)) {
3012 throw new Error(`${method} is already added to this registration`);
3014 const id = UUID.generateUuid();
3015 this._registrations.push({
3018 registerOptions: registerOptions || {}
3020 this._registered.add(method);
3022 asRegistrationParams() {
3024 registrations: this._registrations
3028 var BulkUnregistration;
3029 (function (BulkUnregistration) {
3031 return new BulkUnregistrationImpl(undefined, []);
3033 BulkUnregistration.create = create;
3034 })(BulkUnregistration = exports.BulkUnregistration || (exports.BulkUnregistration = {}));
3035 class BulkUnregistrationImpl {
3036 constructor(_connection, unregistrations) {
3037 this._connection = _connection;
3038 this._unregistrations = new Map();
3039 unregistrations.forEach(unregistration => {
3040 this._unregistrations.set(unregistration.method, unregistration);
3044 return !!this._connection;
3046 attach(connection) {
3047 this._connection = connection;
3049 add(unregistration) {
3050 this._unregistrations.set(unregistration.method, unregistration);
3053 let unregistrations = [];
3054 for (let unregistration of this._unregistrations.values()) {
3055 unregistrations.push(unregistration);
3058 unregisterations: unregistrations
3060 this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(undefined, (_error) => {
3061 this._connection.console.info(`Bulk unregistration failed.`);
3064 disposeSingle(arg) {
3065 const method = Is.string(arg) ? arg : arg.method;
3066 const unregistration = this._unregistrations.get(method);
3067 if (!unregistration) {
3071 unregisterations: [unregistration]
3073 this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(() => {
3074 this._unregistrations.delete(method);
3076 this._connection.console.info(`Unregistering request handler for ${unregistration.id} failed.`);
3081 class RemoteClientImpl {
3082 attach(connection) {
3083 this._connection = connection;
3086 if (!this._connection) {
3087 throw new Error('Remote is not attached to a connection yet.');
3089 return this._connection;
3091 initialize(_capabilities) {
3093 fillServerCapabilities(_capabilities) {
3095 register(typeOrRegistrations, registerOptionsOrType, registerOptions) {
3096 if (typeOrRegistrations instanceof BulkRegistrationImpl) {
3097 return this.registerMany(typeOrRegistrations);
3099 else if (typeOrRegistrations instanceof BulkUnregistrationImpl) {
3100 return this.registerSingle1(typeOrRegistrations, registerOptionsOrType, registerOptions);
3103 return this.registerSingle2(typeOrRegistrations, registerOptionsOrType);
3106 registerSingle1(unregistration, type, registerOptions) {
3107 const method = Is.string(type) ? type : type.method;
3108 const id = UUID.generateUuid();
3110 registrations: [{ id, method, registerOptions: registerOptions || {} }]
3112 if (!unregistration.isAttached) {
3113 unregistration.attach(this.connection);
3115 return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {
3116 unregistration.add({ id: id, method: method });
3117 return unregistration;
3119 this.connection.console.info(`Registering request handler for ${method} failed.`);
3120 return Promise.reject(_error);
3123 registerSingle2(type, registerOptions) {
3124 const method = Is.string(type) ? type : type.method;
3125 const id = UUID.generateUuid();
3127 registrations: [{ id, method, registerOptions: registerOptions || {} }]
3129 return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {
3130 return vscode_languageserver_protocol_1.Disposable.create(() => {
3131 this.unregisterSingle(id, method);
3134 this.connection.console.info(`Registering request handler for ${method} failed.`);
3135 return Promise.reject(_error);
3138 unregisterSingle(id, method) {
3140 unregisterations: [{ id, method }]
3142 return this.connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(undefined, (_error) => {
3143 this.connection.console.info(`Unregistering request handler for ${id} failed.`);
3146 registerMany(registrations) {
3147 let params = registrations.asRegistrationParams();
3148 return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then(() => {
3149 return new BulkUnregistrationImpl(this._connection, params.registrations.map(registration => { return { id: registration.id, method: registration.method }; }));
3151 this.connection.console.info(`Bulk registration failed.`);
3152 return Promise.reject(_error);
3156 class _RemoteWorkspaceImpl {
3159 attach(connection) {
3160 this._connection = connection;
3163 if (!this._connection) {
3164 throw new Error('Remote is not attached to a connection yet.');
3166 return this._connection;
3168 initialize(_capabilities) {
3170 fillServerCapabilities(_capabilities) {
3172 applyEdit(paramOrEdit) {
3173 function isApplyWorkspaceEditParams(value) {
3174 return value && !!value.edit;
3176 let params = isApplyWorkspaceEditParams(paramOrEdit) ? paramOrEdit : { edit: paramOrEdit };
3177 return this.connection.sendRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, params);
3180 const RemoteWorkspaceImpl = workspaceFolders_1.WorkspaceFoldersFeature(configuration_1.ConfigurationFeature(_RemoteWorkspaceImpl));
3183 this._trace = vscode_languageserver_protocol_1.Trace.Off;
3185 attach(connection) {
3186 this._connection = connection;
3189 if (!this._connection) {
3190 throw new Error('Remote is not attached to a connection yet.');
3192 return this._connection;
3194 initialize(_capabilities) {
3196 fillServerCapabilities(_capabilities) {
3199 this._trace = value;
3201 log(message, verbose) {
3202 if (this._trace === vscode_languageserver_protocol_1.Trace.Off) {
3205 this.connection.sendNotification(vscode_languageserver_protocol_1.LogTraceNotification.type, {
3207 verbose: this._trace === vscode_languageserver_protocol_1.Trace.Verbose ? verbose : undefined
3211 class TelemetryImpl {
3214 attach(connection) {
3215 this._connection = connection;
3218 if (!this._connection) {
3219 throw new Error('Remote is not attached to a connection yet.');
3221 return this._connection;
3223 initialize(_capabilities) {
3225 fillServerCapabilities(_capabilities) {
3228 this.connection.sendNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, data);
3231 class _LanguagesImpl {
3234 attach(connection) {
3235 this._connection = connection;
3238 if (!this._connection) {
3239 throw new Error('Remote is not attached to a connection yet.');
3241 return this._connection;
3243 initialize(_capabilities) {
3245 fillServerCapabilities(_capabilities) {
3247 attachWorkDoneProgress(params) {
3248 return progress_1.attachWorkDone(this.connection, params);
3250 attachPartialResultProgress(_type, params) {
3251 return progress_1.attachPartialResult(this.connection, params);
3254 exports._LanguagesImpl = _LanguagesImpl;
3255 const LanguagesImpl = callHierarchy_1.CallHierarchyFeature(_LanguagesImpl);
3256 function combineConsoleFeatures(one, two) {
3257 return function (Base) {
3258 return two(one(Base));
3261 exports.combineConsoleFeatures = combineConsoleFeatures;
3262 function combineTelemetryFeatures(one, two) {
3263 return function (Base) {
3264 return two(one(Base));
3267 exports.combineTelemetryFeatures = combineTelemetryFeatures;
3268 function combineTracerFeatures(one, two) {
3269 return function (Base) {
3270 return two(one(Base));
3273 exports.combineTracerFeatures = combineTracerFeatures;
3274 function combineClientFeatures(one, two) {
3275 return function (Base) {
3276 return two(one(Base));
3279 exports.combineClientFeatures = combineClientFeatures;
3280 function combineWindowFeatures(one, two) {
3281 return function (Base) {
3282 return two(one(Base));
3285 exports.combineWindowFeatures = combineWindowFeatures;
3286 function combineWorkspaceFeatures(one, two) {
3287 return function (Base) {
3288 return two(one(Base));
3291 exports.combineWorkspaceFeatures = combineWorkspaceFeatures;
3292 function combineLanguagesFeatures(one, two) {
3293 return function (Base) {
3294 return two(one(Base));
3297 exports.combineLanguagesFeatures = combineLanguagesFeatures;
3298 function combineFeatures(one, two) {
3299 function combine(one, two, func) {
3301 return func(one, two);
3311 __brand: 'features',
3312 console: combine(one.console, two.console, combineConsoleFeatures),
3313 tracer: combine(one.tracer, two.tracer, combineTracerFeatures),
3314 telemetry: combine(one.telemetry, two.telemetry, combineTelemetryFeatures),
3315 client: combine(one.client, two.client, combineClientFeatures),
3316 window: combine(one.window, two.window, combineWindowFeatures),
3317 workspace: combine(one.workspace, two.workspace, combineWorkspaceFeatures)
3321 exports.combineFeatures = combineFeatures;
3322 function createConnection(connectionFactory, watchDog, factories) {
3323 const logger = (factories && factories.console ? new (factories.console(RemoteConsoleImpl))() : new RemoteConsoleImpl());
3324 const connection = connectionFactory(logger);
3325 logger.rawAttach(connection);
3326 const tracer = (factories && factories.tracer ? new (factories.tracer(TracerImpl))() : new TracerImpl());
3327 const telemetry = (factories && factories.telemetry ? new (factories.telemetry(TelemetryImpl))() : new TelemetryImpl());
3328 const client = (factories && factories.client ? new (factories.client(RemoteClientImpl))() : new RemoteClientImpl());
3329 const remoteWindow = (factories && factories.window ? new (factories.window(RemoteWindowImpl))() : new RemoteWindowImpl());
3330 const workspace = (factories && factories.workspace ? new (factories.workspace(RemoteWorkspaceImpl))() : new RemoteWorkspaceImpl());
3331 const languages = (factories && factories.languages ? new (factories.languages(LanguagesImpl))() : new LanguagesImpl());
3332 const allRemotes = [logger, tracer, telemetry, client, remoteWindow, workspace, languages];
3333 function asPromise(value) {
3334 if (value instanceof Promise) {
3337 else if (Is.thenable(value)) {
3338 return new Promise((resolve, reject) => {
3339 value.then((resolved) => resolve(resolved), (error) => reject(error));
3343 return Promise.resolve(value);
3346 let shutdownHandler = undefined;
3347 let initializeHandler = undefined;
3348 let exitHandler = undefined;
3349 let protocolConnection = {
3350 listen: () => connection.listen(),
3351 sendRequest: (type, ...params) => connection.sendRequest(Is.string(type) ? type : type.method, ...params),
3352 onRequest: (type, handler) => connection.onRequest(type, handler),
3353 sendNotification: (type, param) => {
3354 const method = Is.string(type) ? type : type.method;
3355 if (arguments.length === 1) {
3356 connection.sendNotification(method);
3359 connection.sendNotification(method, param);
3362 onNotification: (type, handler) => connection.onNotification(type, handler),
3363 onProgress: connection.onProgress,
3364 sendProgress: connection.sendProgress,
3365 onInitialize: (handler) => initializeHandler = handler,
3366 onInitialized: (handler) => connection.onNotification(vscode_languageserver_protocol_1.InitializedNotification.type, handler),
3367 onShutdown: (handler) => shutdownHandler = handler,
3368 onExit: (handler) => exitHandler = handler,
3369 get console() { return logger; },
3370 get telemetry() { return telemetry; },
3371 get tracer() { return tracer; },
3372 get client() { return client; },
3373 get window() { return remoteWindow; },
3374 get workspace() { return workspace; },
3375 get languages() { return languages; },
3376 onDidChangeConfiguration: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, handler),
3377 onDidChangeWatchedFiles: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, handler),
3378 __textDocumentSync: undefined,
3379 onDidOpenTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, handler),
3380 onDidChangeTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, handler),
3381 onDidCloseTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, handler),
3382 onWillSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, handler),
3383 onWillSaveTextDocumentWaitUntil: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, handler),
3384 onDidSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, handler),
3385 sendDiagnostics: (params) => connection.sendNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, params),
3386 onHover: (handler) => connection.onRequest(vscode_languageserver_protocol_1.HoverRequest.type, (params, cancel) => {
3387 return handler(params, cancel, progress_1.attachWorkDone(connection, params), undefined);
3389 onCompletion: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionRequest.type, (params, cancel) => {
3390 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3392 onCompletionResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, handler),
3393 onSignatureHelp: (handler) => connection.onRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, (params, cancel) => {
3394 return handler(params, cancel, progress_1.attachWorkDone(connection, params), undefined);
3396 onDeclaration: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, (params, cancel) => {
3397 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3399 onDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, (params, cancel) => {
3400 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3402 onTypeDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, (params, cancel) => {
3403 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3405 onImplementation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, (params, cancel) => {
3406 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3408 onReferences: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, (params, cancel) => {
3409 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3411 onDocumentHighlight: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, (params, cancel) => {
3412 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3414 onDocumentSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, (params, cancel) => {
3415 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3417 onWorkspaceSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, (params, cancel) => {
3418 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3420 onCodeAction: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, (params, cancel) => {
3421 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3423 onCodeLens: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, (params, cancel) => {
3424 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3426 onCodeLensResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, (params, cancel) => {
3427 return handler(params, cancel);
3429 onDocumentFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, (params, cancel) => {
3430 return handler(params, cancel, progress_1.attachWorkDone(connection, params), undefined);
3432 onDocumentRangeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, (params, cancel) => {
3433 return handler(params, cancel, progress_1.attachWorkDone(connection, params), undefined);
3435 onDocumentOnTypeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, (params, cancel) => {
3436 return handler(params, cancel);
3438 onRenameRequest: (handler) => connection.onRequest(vscode_languageserver_protocol_1.RenameRequest.type, (params, cancel) => {
3439 return handler(params, cancel, progress_1.attachWorkDone(connection, params), undefined);
3441 onPrepareRename: (handler) => connection.onRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, (params, cancel) => {
3442 return handler(params, cancel);
3444 onDocumentLinks: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, (params, cancel) => {
3445 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3447 onDocumentLinkResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, (params, cancel) => {
3448 return handler(params, cancel);
3450 onDocumentColor: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, (params, cancel) => {
3451 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3453 onColorPresentation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, (params, cancel) => {
3454 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3456 onFoldingRanges: (handler) => connection.onRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, (params, cancel) => {
3457 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3459 onSelectionRanges: (handler) => connection.onRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, (params, cancel) => {
3460 return handler(params, cancel, progress_1.attachWorkDone(connection, params), progress_1.attachPartialResult(connection, params));
3462 onExecuteCommand: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, (params, cancel) => {
3463 return handler(params, cancel, progress_1.attachWorkDone(connection, params), undefined);
3465 dispose: () => connection.dispose()
3467 for (let remote of allRemotes) {
3468 remote.attach(protocolConnection);
3470 connection.onRequest(vscode_languageserver_protocol_1.InitializeRequest.type, (params) => {
3471 watchDog.initialize(params);
3472 if (Is.string(params.trace)) {
3473 tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.trace);
3475 for (let remote of allRemotes) {
3476 remote.initialize(params.capabilities);
3478 if (initializeHandler) {
3479 let result = initializeHandler(params, new vscode_languageserver_protocol_1.CancellationTokenSource().token, progress_1.attachWorkDone(connection, params), undefined);
3480 return asPromise(result).then((value) => {
3481 if (value instanceof vscode_languageserver_protocol_1.ResponseError) {
3486 result = { capabilities: {} };
3488 let capabilities = result.capabilities;
3489 if (!capabilities) {
3491 result.capabilities = capabilities;
3493 if (capabilities.textDocumentSync === undefined || capabilities.textDocumentSync === null) {
3494 capabilities.textDocumentSync = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
3496 else if (!Is.number(capabilities.textDocumentSync) && !Is.number(capabilities.textDocumentSync.change)) {
3497 capabilities.textDocumentSync.change = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
3499 for (let remote of allRemotes) {
3500 remote.fillServerCapabilities(capabilities);
3506 let result = { capabilities: { textDocumentSync: vscode_languageserver_protocol_1.TextDocumentSyncKind.None } };
3507 for (let remote of allRemotes) {
3508 remote.fillServerCapabilities(result.capabilities);
3513 connection.onRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, () => {
3514 watchDog.shutdownReceived = true;
3515 if (shutdownHandler) {
3516 return shutdownHandler(new vscode_languageserver_protocol_1.CancellationTokenSource().token);
3522 connection.onNotification(vscode_languageserver_protocol_1.ExitNotification.type, () => {
3529 if (watchDog.shutdownReceived) {
3537 connection.onNotification(vscode_languageserver_protocol_1.SetTraceNotification.type, (params) => {
3538 tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.value);
3540 return protocolConnection;
3542 exports.createConnection = createConnection;
3543 //# sourceMappingURL=server.js.map
3547 /***/ (function(module, exports, __webpack_require__) {
3551 /* --------------------------------------------------------------------------------------------
3552 * Copyright (c) Microsoft Corporation. All rights reserved.
3553 * Licensed under the MIT License. See License.txt in the project root for license information.
3554 * ------------------------------------------------------------------------------------------ */
3555 function __export(m) {
3556 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
3558 Object.defineProperty(exports, "__esModule", { value: true });
3559 const node_1 = __webpack_require__(45);
3560 __export(__webpack_require__(45));
3561 __export(__webpack_require__(60));
3562 function createProtocolConnection(input, output, logger, options) {
3563 return node_1.createMessageConnection(input, output, logger, options);
3565 exports.createProtocolConnection = createProtocolConnection;
3566 //# sourceMappingURL=main.js.map
3570 /***/ (function(module, exports, __webpack_require__) {
3573 /* --------------------------------------------------------------------------------------------
3574 * Copyright (c) Microsoft Corporation. All rights reserved.
3575 * Licensed under the MIT License. See License.txt in the project root for license information.
3576 * ----------------------------------------------------------------------------------------- */
3579 module.exports = __webpack_require__(46);
3583 /***/ (function(module, exports, __webpack_require__) {
3587 function __export(m) {
3588 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
3590 Object.defineProperty(exports, "__esModule", { value: true });
3591 /* --------------------------------------------------------------------------------------------
3592 * Copyright (c) Microsoft Corporation. All rights reserved.
3593 * Licensed under the MIT License. See License.txt in the project root for license information.
3594 * ----------------------------------------------------------------------------------------- */
3595 const ril_1 = __webpack_require__(47);
3596 // Install the node runtime abstract.
3597 ril_1.default.install();
3598 const api_1 = __webpack_require__(50);
3599 const path = __webpack_require__(1);
3600 const os = __webpack_require__(14);
3601 const crypto_1 = __webpack_require__(15);
3602 const net_1 = __webpack_require__(16);
3603 __export(__webpack_require__(50));
3604 class IPCMessageReader extends api_1.AbstractMessageReader {
3605 constructor(process) {
3607 this.process = process;
3608 let eventEmitter = this.process;
3609 eventEmitter.on('error', (error) => this.fireError(error));
3610 eventEmitter.on('close', () => this.fireClose());
3613 this.process.on('message', callback);
3614 return api_1.Disposable.create(() => this.process.off('message', callback));
3617 exports.IPCMessageReader = IPCMessageReader;
3618 class IPCMessageWriter extends api_1.AbstractMessageWriter {
3619 constructor(process) {
3621 this.process = process;
3622 this.errorCount = 0;
3623 let eventEmitter = this.process;
3624 eventEmitter.on('error', (error) => this.fireError(error));
3625 eventEmitter.on('close', () => this.fireClose);
3629 if (typeof this.process.send === 'function') {
3630 this.process.send(msg, undefined, undefined, (error) => {
3633 this.handleError(error, msg);
3636 this.errorCount = 0;
3640 return Promise.resolve();
3643 this.handleError(error, msg);
3644 return Promise.reject(error);
3647 handleError(error, msg) {
3649 this.fireError(error, msg, this.errorCount);
3652 exports.IPCMessageWriter = IPCMessageWriter;
3653 class SocketMessageReader extends api_1.ReadableStreamMessageReader {
3654 constructor(socket, encoding = 'utf-8') {
3655 super(ril_1.default().stream.asReadableStream(socket), encoding);
3658 exports.SocketMessageReader = SocketMessageReader;
3659 class SocketMessageWriter extends api_1.WriteableStreamMessageWriter {
3660 constructor(socket, options) {
3661 super(ril_1.default().stream.asWritableStream(socket), options);
3662 this.socket = socket;
3666 this.socket.destroy();
3669 exports.SocketMessageWriter = SocketMessageWriter;
3670 class StreamMessageReader extends api_1.ReadableStreamMessageReader {
3671 constructor(readble, encoding) {
3672 super(ril_1.default().stream.asReadableStream(readble), encoding);
3675 exports.StreamMessageReader = StreamMessageReader;
3676 class StreamMessageWriter extends api_1.WriteableStreamMessageWriter {
3677 constructor(writable, options) {
3678 super(ril_1.default().stream.asWritableStream(writable), options);
3681 exports.StreamMessageWriter = StreamMessageWriter;
3682 function generateRandomPipeName() {
3683 const randomSuffix = crypto_1.randomBytes(21).toString('hex');
3684 if (process.platform === 'win32') {
3685 return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
3688 // Mac/Unix: use socket file
3689 return path.join(os.tmpdir(), `vscode-${randomSuffix}.sock`);
3692 exports.generateRandomPipeName = generateRandomPipeName;
3693 function createClientPipeTransport(pipeName, encoding = 'utf-8') {
3695 const connected = new Promise((resolve, _reject) => {
3696 connectResolve = resolve;
3698 return new Promise((resolve, reject) => {
3699 let server = net_1.createServer((socket) => {
3702 new SocketMessageReader(socket, encoding),
3703 new SocketMessageWriter(socket, encoding)
3706 server.on('error', reject);
3707 server.listen(pipeName, () => {
3708 server.removeListener('error', reject);
3710 onConnected: () => { return connected; }
3715 exports.createClientPipeTransport = createClientPipeTransport;
3716 function createServerPipeTransport(pipeName, encoding = 'utf-8') {
3717 const socket = net_1.createConnection(pipeName);
3719 new SocketMessageReader(socket, encoding),
3720 new SocketMessageWriter(socket, encoding)
3723 exports.createServerPipeTransport = createServerPipeTransport;
3724 function createClientSocketTransport(port, encoding = 'utf-8') {
3726 const connected = new Promise((resolve, _reject) => {
3727 connectResolve = resolve;
3729 return new Promise((resolve, reject) => {
3730 const server = net_1.createServer((socket) => {
3733 new SocketMessageReader(socket, encoding),
3734 new SocketMessageWriter(socket, encoding)
3737 server.on('error', reject);
3738 server.listen(port, '127.0.0.1', () => {
3739 server.removeListener('error', reject);
3741 onConnected: () => { return connected; }
3746 exports.createClientSocketTransport = createClientSocketTransport;
3747 function createServerSocketTransport(port, encoding = 'utf-8') {
3748 const socket = net_1.createConnection(port, '127.0.0.1');
3750 new SocketMessageReader(socket, encoding),
3751 new SocketMessageWriter(socket, encoding)
3754 exports.createServerSocketTransport = createServerSocketTransport;
3755 function isMessageReader(value) {
3756 return value.listen !== undefined && value.read === undefined;
3758 function isMessageWriter(value) {
3759 return value.write !== undefined && value.end === undefined;
3761 function createMessageConnection(input, output, logger, options) {
3763 logger = api_1.NullLogger;
3765 const reader = isMessageReader(input) ? input : new StreamMessageReader(input);
3766 const writer = isMessageWriter(output) ? output : new StreamMessageWriter(output);
3767 if (api_1.ConnectionStrategy.is(options)) {
3768 options = { connectionStrategy: options };
3770 return api_1.createMessageConnection(reader, writer, logger, options);
3772 exports.createMessageConnection = createMessageConnection;
3773 //# sourceMappingURL=main.js.map
3777 /***/ (function(module, exports, __webpack_require__) {
3781 /* --------------------------------------------------------------------------------------------
3782 * Copyright (c) Microsoft Corporation. All rights reserved.
3783 * Licensed under the MIT License. See License.txt in the project root for license information.
3784 * ------------------------------------------------------------------------------------------ */
3785 Object.defineProperty(exports, "__esModule", { value: true });
3786 const ral_1 = __webpack_require__(48);
3787 const disposable_1 = __webpack_require__(49);
3788 const util_1 = __webpack_require__(3);
3789 const DefaultSize = 8192;
3790 const CR = Buffer.from('\r', 'ascii')[0];
3791 const LF = Buffer.from('\n', 'ascii')[0];
3792 const CRLF = '\r\n';
3793 class MessageBuffer {
3794 constructor(encoding = 'utf-8') {
3795 this._encoding = encoding;
3797 this.buffer = Buffer.allocUnsafe(DefaultSize);
3800 return this._encoding;
3804 if (typeof chunk === 'string') {
3805 toAppend = Buffer.from(chunk, this._encoding);
3810 if (this.buffer.length - this.index >= toAppend.length) {
3811 this.buffer.set(toAppend, this.index);
3814 var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
3815 if (this.index === 0) {
3816 this.buffer = Buffer.allocUnsafe(newSize);
3817 this.buffer.set(toAppend);
3820 this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
3823 this.index += toAppend.length;
3827 while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {
3830 // No header / body separator found (e.g CRLFCRLF)
3831 if (current + 3 >= this.index) {
3834 const result = new Map();
3835 const headers = this.buffer.toString('ascii', 0, current).split(CRLF);
3836 headers.forEach((header) => {
3837 let index = header.indexOf(':');
3839 throw new Error('Message header must separate key and value using :');
3841 let key = header.substr(0, index);
3842 let value = header.substr(index + 1).trim();
3843 result.set(key, value);
3845 let nextStart = current + 4;
3846 this.buffer = this.buffer.slice(nextStart);
3847 this.index = this.index - nextStart;
3850 tryReadBody(length) {
3851 if (this.index < length) {
3854 const result = Buffer.alloc(length);
3855 this.buffer.copy(result, 0, 0, length);
3856 const nextStart = length;
3857 this.buffer.copy(this.buffer, 0, nextStart);
3858 this.index = this.index - nextStart;
3861 get numberOfBytes() {
3865 class ReadableStreamWrapper {
3866 constructor(stream) {
3867 this.stream = stream;
3870 this.stream.on('close', listener);
3871 return disposable_1.Disposable.create(() => this.stream.off('close', listener));
3874 this.stream.on('error', listener);
3875 return disposable_1.Disposable.create(() => this.stream.off('error', listener));
3878 this.stream.on('end', listener);
3879 return disposable_1.Disposable.create(() => this.stream.off('end', listener));
3882 this.stream.on('data', listener);
3883 return disposable_1.Disposable.create(() => this.stream.off('data', listener));
3886 class WritableStreamWrapper {
3887 constructor(stream) {
3888 this.stream = stream;
3891 this.stream.on('close', listener);
3892 return disposable_1.Disposable.create(() => this.stream.off('close', listener));
3895 this.stream.on('error', listener);
3896 return disposable_1.Disposable.create(() => this.stream.off('error', listener));
3899 this.stream.on('end', listener);
3900 return disposable_1.Disposable.create(() => this.stream.off('end', listener));
3902 write(data, encoding) {
3903 return new Promise((resolve, reject) => {
3904 const callback = (error) => {
3905 if (error === undefined || error === null) {
3912 if (typeof data === 'string') {
3913 this.stream.write(data, encoding, callback);
3916 this.stream.write(data, callback);
3924 const _ril = Object.freeze({
3925 messageBuffer: Object.freeze({
3926 create: (encoding) => new MessageBuffer(encoding)
3928 applicationJson: Object.freeze({
3929 encoder: Object.freeze({
3930 name: 'application/json',
3931 encode: (msg, options) => {
3932 return Promise.resolve(Buffer.from(JSON.stringify(msg, undefined, 0), options.charset));
3935 decoder: Object.freeze({
3936 name: 'application/json',
3937 decode: (buffer, options) => {
3938 if (buffer instanceof Buffer) {
3939 return Promise.resolve(JSON.parse(buffer.toString(options.charset)));
3942 return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer)));
3947 stream: Object.freeze({
3948 asReadableStream: (socket) => new ReadableStreamWrapper(socket),
3949 asWritableStream: (socket) => new WritableStreamWrapper(socket)
3952 timer: Object.freeze({
3953 setTimeout(callback, ms, ...args) {
3954 return setTimeout(callback, ms, ...args);
3956 clearTimeout(handle) {
3957 clearTimeout(handle);
3959 setImmediate(callback, ...args) {
3960 return setImmediate(callback, ...args);
3962 clearImmediate(handle) {
3963 clearImmediate(handle);
3971 function install() {
3972 ral_1.default.install(_ril);
3974 RIL.install = install;
3975 })(RIL || (RIL = {}));
3976 exports.default = RIL;
3977 //# sourceMappingURL=ril.js.map
3981 /***/ (function(module, exports, __webpack_require__) {
3985 /* --------------------------------------------------------------------------------------------
3986 * Copyright (c) Microsoft Corporation. All rights reserved.
3987 * Licensed under the MIT License. See License.txt in the project root for license information.
3988 * ------------------------------------------------------------------------------------------ */
3989 Object.defineProperty(exports, "__esModule", { value: true });
3992 if (_ral === undefined) {
3993 throw new Error(`No runtime abstraction layer installed`);
3998 function install(ral) {
3999 if (ral === undefined) {
4000 throw new Error(`No runtime abstraction layer provided`);
4004 RAL.install = install;
4005 })(RAL || (RAL = {}));
4006 exports.default = RAL;
4007 //# sourceMappingURL=ral.js.map
4011 /***/ (function(module, exports, __webpack_require__) {
4015 /*---------------------------------------------------------------------------------------------
4016 * Copyright (c) Microsoft Corporation. All rights reserved.
4017 * Licensed under the MIT License. See License.txt in the project root for license information.
4018 *--------------------------------------------------------------------------------------------*/
4019 Object.defineProperty(exports, "__esModule", { value: true });
4021 (function (Disposable) {
4022 function create(func) {
4027 Disposable.create = create;
4028 })(Disposable = exports.Disposable || (exports.Disposable = {}));
4029 //# sourceMappingURL=disposable.js.map
4033 /***/ (function(module, exports, __webpack_require__) {
4037 /* --------------------------------------------------------------------------------------------
4038 * Copyright (c) Microsoft Corporation. All rights reserved.
4039 * Licensed under the MIT License. See License.txt in the project root for license information.
4040 * ------------------------------------------------------------------------------------------ */
4041 /// <reference path="../../typings/thenable.d.ts" />
4042 Object.defineProperty(exports, "__esModule", { value: true });
4043 const messages_1 = __webpack_require__(51);
4044 exports.RequestType = messages_1.RequestType;
4045 exports.RequestType0 = messages_1.RequestType0;
4046 exports.RequestType1 = messages_1.RequestType1;
4047 exports.RequestType2 = messages_1.RequestType2;
4048 exports.RequestType3 = messages_1.RequestType3;
4049 exports.RequestType4 = messages_1.RequestType4;
4050 exports.RequestType5 = messages_1.RequestType5;
4051 exports.RequestType6 = messages_1.RequestType6;
4052 exports.RequestType7 = messages_1.RequestType7;
4053 exports.RequestType8 = messages_1.RequestType8;
4054 exports.RequestType9 = messages_1.RequestType9;
4055 exports.ResponseError = messages_1.ResponseError;
4056 exports.ErrorCodes = messages_1.ErrorCodes;
4057 exports.NotificationType = messages_1.NotificationType;
4058 exports.NotificationType0 = messages_1.NotificationType0;
4059 exports.NotificationType1 = messages_1.NotificationType1;
4060 exports.NotificationType2 = messages_1.NotificationType2;
4061 exports.NotificationType3 = messages_1.NotificationType3;
4062 exports.NotificationType4 = messages_1.NotificationType4;
4063 exports.NotificationType5 = messages_1.NotificationType5;
4064 exports.NotificationType6 = messages_1.NotificationType6;
4065 exports.NotificationType7 = messages_1.NotificationType7;
4066 exports.NotificationType8 = messages_1.NotificationType8;
4067 exports.NotificationType9 = messages_1.NotificationType9;
4068 const disposable_1 = __webpack_require__(49);
4069 exports.Disposable = disposable_1.Disposable;
4070 const events_1 = __webpack_require__(53);
4071 exports.Event = events_1.Event;
4072 exports.Emitter = events_1.Emitter;
4073 const cancellation_1 = __webpack_require__(54);
4074 exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
4075 exports.CancellationToken = cancellation_1.CancellationToken;
4076 const messageReader_1 = __webpack_require__(55);
4077 exports.MessageReader = messageReader_1.MessageReader;
4078 exports.AbstractMessageReader = messageReader_1.AbstractMessageReader;
4079 exports.ReadableStreamMessageReader = messageReader_1.ReadableStreamMessageReader;
4080 const messageWriter_1 = __webpack_require__(56);
4081 exports.MessageWriter = messageWriter_1.MessageWriter;
4082 exports.AbstractMessageWriter = messageWriter_1.AbstractMessageWriter;
4083 exports.WriteableStreamMessageWriter = messageWriter_1.WriteableStreamMessageWriter;
4084 const connection_1 = __webpack_require__(58);
4085 exports.ConnectionStrategy = connection_1.ConnectionStrategy;
4086 exports.ConnectionOptions = connection_1.ConnectionOptions;
4087 exports.NullLogger = connection_1.NullLogger;
4088 exports.createMessageConnection = connection_1.createMessageConnection;
4089 exports.ProgressType = connection_1.ProgressType;
4090 exports.Trace = connection_1.Trace;
4091 exports.TraceFormat = connection_1.TraceFormat;
4092 exports.SetTraceNotification = connection_1.SetTraceNotification;
4093 exports.LogTraceNotification = connection_1.LogTraceNotification;
4094 exports.ConnectionErrors = connection_1.ConnectionErrors;
4095 exports.ConnectionError = connection_1.ConnectionError;
4096 exports.CancellationReceiverStrategy = connection_1.CancellationReceiverStrategy;
4097 exports.CancellationSenderStrategy = connection_1.CancellationSenderStrategy;
4098 exports.CancellationStrategy = connection_1.CancellationStrategy;
4099 const ral_1 = __webpack_require__(48);
4100 exports.RAL = ral_1.default;
4101 //# sourceMappingURL=api.js.map
4105 /***/ (function(module, exports, __webpack_require__) {
4109 /* --------------------------------------------------------------------------------------------
4110 * Copyright (c) Microsoft Corporation. All rights reserved.
4111 * Licensed under the MIT License. See License.txt in the project root for license information.
4112 * ------------------------------------------------------------------------------------------ */
4113 Object.defineProperty(exports, "__esModule", { value: true });
4114 const is = __webpack_require__(52);
4116 * Predefined error codes.
4119 (function (ErrorCodes) {
4120 // Defined by JSON RPC
4121 ErrorCodes.ParseError = -32700;
4122 ErrorCodes.InvalidRequest = -32600;
4123 ErrorCodes.MethodNotFound = -32601;
4124 ErrorCodes.InvalidParams = -32602;
4125 ErrorCodes.InternalError = -32603;
4126 ErrorCodes.serverErrorStart = -32099;
4127 ErrorCodes.serverErrorEnd = -32000;
4128 ErrorCodes.ServerNotInitialized = -32002;
4129 ErrorCodes.UnknownErrorCode = -32001;
4130 // Defined by the protocol.
4131 ErrorCodes.RequestCancelled = -32800;
4132 ErrorCodes.ContentModified = -32801;
4133 // Defined by VSCode library.
4134 ErrorCodes.MessageWriteError = 1;
4135 ErrorCodes.MessageReadError = 2;
4136 })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
4138 * An error object return in a response in case a request
4141 class ResponseError extends Error {
4142 constructor(code, message, data) {
4144 this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
4146 Object.setPrototypeOf(this, ResponseError.prototype);
4151 message: this.message,
4156 exports.ResponseError = ResponseError;
4158 * An abstract implementation of a MessageType.
4160 class AbstractMessageSignature {
4161 constructor(_method, _numberOfParams) {
4162 this._method = _method;
4163 this._numberOfParams = _numberOfParams;
4166 return this._method;
4168 get numberOfParams() {
4169 return this._numberOfParams;
4172 exports.AbstractMessageSignature = AbstractMessageSignature;
4174 * Classes to type request response pairs
4176 * The type parameter RO will be removed in the next major version
4177 * of the JSON RPC library since it is a LSP concept and doesn't
4178 * belong here. For now it is tagged as default never.
4180 class RequestType0 extends AbstractMessageSignature {
4181 constructor(method) {
4185 exports.RequestType0 = RequestType0;
4186 class RequestType extends AbstractMessageSignature {
4187 constructor(method) {
4191 exports.RequestType = RequestType;
4192 class RequestType1 extends AbstractMessageSignature {
4193 constructor(method) {
4197 exports.RequestType1 = RequestType1;
4198 class RequestType2 extends AbstractMessageSignature {
4199 constructor(method) {
4203 exports.RequestType2 = RequestType2;
4204 class RequestType3 extends AbstractMessageSignature {
4205 constructor(method) {
4209 exports.RequestType3 = RequestType3;
4210 class RequestType4 extends AbstractMessageSignature {
4211 constructor(method) {
4215 exports.RequestType4 = RequestType4;
4216 class RequestType5 extends AbstractMessageSignature {
4217 constructor(method) {
4221 exports.RequestType5 = RequestType5;
4222 class RequestType6 extends AbstractMessageSignature {
4223 constructor(method) {
4227 exports.RequestType6 = RequestType6;
4228 class RequestType7 extends AbstractMessageSignature {
4229 constructor(method) {
4233 exports.RequestType7 = RequestType7;
4234 class RequestType8 extends AbstractMessageSignature {
4235 constructor(method) {
4239 exports.RequestType8 = RequestType8;
4240 class RequestType9 extends AbstractMessageSignature {
4241 constructor(method) {
4245 exports.RequestType9 = RequestType9;
4247 * The type parameter RO will be removed in the next major version
4248 * of the JSON RPC library since it is a LSP concept and doesn't
4249 * belong here. For now it is tagged as default never.
4251 class NotificationType extends AbstractMessageSignature {
4252 constructor(method) {
4257 exports.NotificationType = NotificationType;
4258 class NotificationType0 extends AbstractMessageSignature {
4259 constructor(method) {
4263 exports.NotificationType0 = NotificationType0;
4264 class NotificationType1 extends AbstractMessageSignature {
4265 constructor(method) {
4269 exports.NotificationType1 = NotificationType1;
4270 class NotificationType2 extends AbstractMessageSignature {
4271 constructor(method) {
4275 exports.NotificationType2 = NotificationType2;
4276 class NotificationType3 extends AbstractMessageSignature {
4277 constructor(method) {
4281 exports.NotificationType3 = NotificationType3;
4282 class NotificationType4 extends AbstractMessageSignature {
4283 constructor(method) {
4287 exports.NotificationType4 = NotificationType4;
4288 class NotificationType5 extends AbstractMessageSignature {
4289 constructor(method) {
4293 exports.NotificationType5 = NotificationType5;
4294 class NotificationType6 extends AbstractMessageSignature {
4295 constructor(method) {
4299 exports.NotificationType6 = NotificationType6;
4300 class NotificationType7 extends AbstractMessageSignature {
4301 constructor(method) {
4305 exports.NotificationType7 = NotificationType7;
4306 class NotificationType8 extends AbstractMessageSignature {
4307 constructor(method) {
4311 exports.NotificationType8 = NotificationType8;
4312 class NotificationType9 extends AbstractMessageSignature {
4313 constructor(method) {
4317 exports.NotificationType9 = NotificationType9;
4319 * Tests if the given message is a request message
4321 function isRequestMessage(message) {
4322 const candidate = message;
4323 return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
4325 exports.isRequestMessage = isRequestMessage;
4327 * Tests if the given message is a notification message
4329 function isNotificationMessage(message) {
4330 const candidate = message;
4331 return candidate && is.string(candidate.method) && message.id === void 0;
4333 exports.isNotificationMessage = isNotificationMessage;
4335 * Tests if the given message is a response message
4337 function isResponseMessage(message) {
4338 const candidate = message;
4339 return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
4341 exports.isResponseMessage = isResponseMessage;
4342 //# sourceMappingURL=messages.js.map
4346 /***/ (function(module, exports, __webpack_require__) {
4350 /* --------------------------------------------------------------------------------------------
4351 * Copyright (c) Microsoft Corporation. All rights reserved.
4352 * Licensed under the MIT License. See License.txt in the project root for license information.
4353 * ------------------------------------------------------------------------------------------ */
4354 Object.defineProperty(exports, "__esModule", { value: true });
4355 function boolean(value) {
4356 return value === true || value === false;
4358 exports.boolean = boolean;
4359 function string(value) {
4360 return typeof value === 'string' || value instanceof String;
4362 exports.string = string;
4363 function number(value) {
4364 return typeof value === 'number' || value instanceof Number;
4366 exports.number = number;
4367 function error(value) {
4368 return value instanceof Error;
4370 exports.error = error;
4371 function func(value) {
4372 return typeof value === 'function';
4374 exports.func = func;
4375 function array(value) {
4376 return Array.isArray(value);
4378 exports.array = array;
4379 function stringArray(value) {
4380 return array(value) && value.every(elem => string(elem));
4382 exports.stringArray = stringArray;
4383 //# sourceMappingURL=is.js.map
4387 /***/ (function(module, exports, __webpack_require__) {
4391 /* --------------------------------------------------------------------------------------------
4392 * Copyright (c) Microsoft Corporation. All rights reserved.
4393 * Licensed under the MIT License. See License.txt in the project root for license information.
4394 * ------------------------------------------------------------------------------------------ */
4395 Object.defineProperty(exports, "__esModule", { value: true });
4396 const ral_1 = __webpack_require__(48);
4399 const _disposable = { dispose() { } };
4400 Event.None = function () { return _disposable; };
4401 })(Event = exports.Event || (exports.Event = {}));
4402 class CallbackList {
4403 add(callback, context = null, bucket) {
4404 if (!this._callbacks) {
4405 this._callbacks = [];
4406 this._contexts = [];
4408 this._callbacks.push(callback);
4409 this._contexts.push(context);
4410 if (Array.isArray(bucket)) {
4411 bucket.push({ dispose: () => this.remove(callback, context) });
4414 remove(callback, context = null) {
4415 if (!this._callbacks) {
4418 let foundCallbackWithDifferentContext = false;
4419 for (let i = 0, len = this._callbacks.length; i < len; i++) {
4420 if (this._callbacks[i] === callback) {
4421 if (this._contexts[i] === context) {
4422 // callback & context match => remove it
4423 this._callbacks.splice(i, 1);
4424 this._contexts.splice(i, 1);
4428 foundCallbackWithDifferentContext = true;
4432 if (foundCallbackWithDifferentContext) {
4433 throw new Error('When adding a listener with a context, you should remove it with the same context');
4437 if (!this._callbacks) {
4440 const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
4441 for (let i = 0, len = callbacks.length; i < len; i++) {
4443 ret.push(callbacks[i].apply(contexts[i], args));
4446 // eslint-disable-next-line no-console
4447 ral_1.default().console.error(e);
4453 return !this._callbacks || this._callbacks.length === 0;
4456 this._callbacks = undefined;
4457 this._contexts = undefined;
4461 constructor(_options) {
4462 this._options = _options;
4465 * For the public to allow to subscribe
4466 * to events from this Emitter
4470 this._event = (listener, thisArgs, disposables) => {
4471 if (!this._callbacks) {
4472 this._callbacks = new CallbackList();
4474 if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
4475 this._options.onFirstListenerAdd(this);
4477 this._callbacks.add(listener, thisArgs);
4480 if (!this._callbacks) {
4481 // disposable is disposed after emitter is disposed.
4484 this._callbacks.remove(listener, thisArgs);
4485 result.dispose = Emitter._noop;
4486 if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
4487 this._options.onLastListenerRemove(this);
4491 if (Array.isArray(disposables)) {
4492 disposables.push(result);
4500 * To be kept private to fire an event to
4504 if (this._callbacks) {
4505 this._callbacks.invoke.call(this._callbacks, event);
4509 if (this._callbacks) {
4510 this._callbacks.dispose();
4511 this._callbacks = undefined;
4515 exports.Emitter = Emitter;
4516 Emitter._noop = function () { };
4517 //# sourceMappingURL=events.js.map
4521 /***/ (function(module, exports, __webpack_require__) {
4525 /*---------------------------------------------------------------------------------------------
4526 * Copyright (c) Microsoft Corporation. All rights reserved.
4527 * Licensed under the MIT License. See License.txt in the project root for license information.
4528 *--------------------------------------------------------------------------------------------*/
4529 Object.defineProperty(exports, "__esModule", { value: true });
4530 const ral_1 = __webpack_require__(48);
4531 const Is = __webpack_require__(52);
4532 const events_1 = __webpack_require__(53);
4533 var CancellationToken;
4534 (function (CancellationToken) {
4535 CancellationToken.None = Object.freeze({
4536 isCancellationRequested: false,
4537 onCancellationRequested: events_1.Event.None
4539 CancellationToken.Cancelled = Object.freeze({
4540 isCancellationRequested: true,
4541 onCancellationRequested: events_1.Event.None
4543 function is(value) {
4544 const candidate = value;
4545 return candidate && (candidate === CancellationToken.None
4546 || candidate === CancellationToken.Cancelled
4547 || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
4549 CancellationToken.is = is;
4550 })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
4551 const shortcutEvent = Object.freeze(function (callback, context) {
4552 const handle = ral_1.default().timer.setTimeout(callback.bind(context), 0);
4553 return { dispose() { ral_1.default().timer.clearTimeout(handle); } };
4555 class MutableToken {
4557 this._isCancelled = false;
4560 if (!this._isCancelled) {
4561 this._isCancelled = true;
4562 if (this._emitter) {
4563 this._emitter.fire(undefined);
4568 get isCancellationRequested() {
4569 return this._isCancelled;
4571 get onCancellationRequested() {
4572 if (this._isCancelled) {
4573 return shortcutEvent;
4575 if (!this._emitter) {
4576 this._emitter = new events_1.Emitter();
4578 return this._emitter.event;
4581 if (this._emitter) {
4582 this._emitter.dispose();
4583 this._emitter = undefined;
4587 class CancellationTokenSource {
4590 // be lazy and create the token only when
4592 this._token = new MutableToken();
4598 // save an object by returning the default
4599 // cancelled token when cancellation happens
4600 // before someone asks for the token
4601 this._token = CancellationToken.Cancelled;
4604 this._token.cancel();
4609 // ensure to initialize with an empty token if we had none
4610 this._token = CancellationToken.None;
4612 else if (this._token instanceof MutableToken) {
4614 this._token.dispose();
4618 exports.CancellationTokenSource = CancellationTokenSource;
4619 //# sourceMappingURL=cancellation.js.map
4623 /***/ (function(module, exports, __webpack_require__) {
4627 /* --------------------------------------------------------------------------------------------
4628 * Copyright (c) Microsoft Corporation. All rights reserved.
4629 * Licensed under the MIT License. See License.txt in the project root for license information.
4630 * ------------------------------------------------------------------------------------------ */
4631 Object.defineProperty(exports, "__esModule", { value: true });
4632 const ral_1 = __webpack_require__(48);
4633 const Is = __webpack_require__(52);
4634 const events_1 = __webpack_require__(53);
4636 (function (MessageReader) {
4637 function is(value) {
4638 let candidate = value;
4639 return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
4640 Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
4642 MessageReader.is = is;
4643 })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
4644 class AbstractMessageReader {
4646 this.errorEmitter = new events_1.Emitter();
4647 this.closeEmitter = new events_1.Emitter();
4648 this.partialMessageEmitter = new events_1.Emitter();
4651 this.errorEmitter.dispose();
4652 this.closeEmitter.dispose();
4655 return this.errorEmitter.event;
4658 this.errorEmitter.fire(this.asError(error));
4661 return this.closeEmitter.event;
4664 this.closeEmitter.fire(undefined);
4666 get onPartialMessage() {
4667 return this.partialMessageEmitter.event;
4669 firePartialMessage(info) {
4670 this.partialMessageEmitter.fire(info);
4673 if (error instanceof Error) {
4677 return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
4681 exports.AbstractMessageReader = AbstractMessageReader;
4682 var ResolvedMessageReaderOptions;
4683 (function (ResolvedMessageReaderOptions) {
4684 function fromOptions(options) {
4689 const contentDecoders = new Map();
4690 let contentTypeDecoder;
4691 const contentTypeDecoders = new Map();
4692 if (options === undefined || typeof options === 'string') {
4693 charset = options !== null && options !== void 0 ? options : 'utf-8';
4696 charset = (_a = options.charset) !== null && _a !== void 0 ? _a : 'utf-8';
4697 if (options.contentDecoder !== undefined) {
4698 contentDecoder = options.contentDecoder;
4699 contentDecoders.set(contentDecoder.name, contentDecoder);
4701 if (options.contentDecoders !== undefined) {
4702 for (const decoder of options.contentDecoders) {
4703 contentDecoders.set(decoder.name, decoder);
4706 if (options.contentTypeDecoder !== undefined) {
4707 contentTypeDecoder = options.contentTypeDecoder;
4708 contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
4710 if (options.contentTypeDecoders !== undefined) {
4711 for (const decoder of options.contentTypeDecoders) {
4712 contentTypeDecoders.set(decoder.name, decoder);
4716 if (contentTypeDecoder === undefined) {
4717 contentTypeDecoder = ral_1.default().applicationJson.decoder;
4718 contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
4720 return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders };
4722 ResolvedMessageReaderOptions.fromOptions = fromOptions;
4723 })(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));
4724 class ReadableStreamMessageReader extends AbstractMessageReader {
4725 constructor(readable, options) {
4727 this.readable = readable;
4728 this.options = ResolvedMessageReaderOptions.fromOptions(options);
4729 this.buffer = ral_1.default().messageBuffer.create(this.options.charset);
4730 this._partialMessageTimeout = 10000;
4731 this.nextMessageLength = -1;
4732 this.messageToken = 0;
4734 set partialMessageTimeout(timeout) {
4735 this._partialMessageTimeout = timeout;
4737 get partialMessageTimeout() {
4738 return this._partialMessageTimeout;
4741 this.nextMessageLength = -1;
4742 this.messageToken = 0;
4743 this.partialMessageTimer = undefined;
4744 this.callback = callback;
4745 const result = this.readable.onData((data) => {
4748 this.readable.onError((error) => this.fireError(error));
4749 this.readable.onClose(() => this.fireClose());
4753 this.buffer.append(data);
4755 if (this.nextMessageLength === -1) {
4756 const headers = this.buffer.tryReadHeaders();
4760 const contentLength = headers.get('Content-Length');
4761 if (!contentLength) {
4762 throw new Error('Header must provide a Content-Length property.');
4764 const length = parseInt(contentLength);
4765 if (isNaN(length)) {
4766 throw new Error('Content-Length value must be a number.');
4768 this.nextMessageLength = length;
4770 const body = this.buffer.tryReadBody(this.nextMessageLength);
4771 if (body === undefined) {
4772 /** We haven't received the full message yet. */
4773 this.setPartialMessageTimer();
4776 this.clearPartialMessageTimer();
4777 this.nextMessageLength = -1;
4779 if (this.options.contentDecoder !== undefined) {
4780 p = this.options.contentDecoder.decode(body);
4783 p = Promise.resolve(body);
4786 this.options.contentTypeDecoder.decode(value, this.options).then((msg) => {
4789 this.fireError(error);
4792 this.fireError(error);
4796 clearPartialMessageTimer() {
4797 if (this.partialMessageTimer) {
4798 ral_1.default().timer.clearTimeout(this.partialMessageTimer);
4799 this.partialMessageTimer = undefined;
4802 setPartialMessageTimer() {
4803 this.clearPartialMessageTimer();
4804 if (this._partialMessageTimeout <= 0) {
4807 this.partialMessageTimer = ral_1.default().timer.setTimeout((token, timeout) => {
4808 this.partialMessageTimer = undefined;
4809 if (token === this.messageToken) {
4810 this.firePartialMessage({ messageToken: token, waitingTime: timeout });
4811 this.setPartialMessageTimer();
4813 }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
4816 exports.ReadableStreamMessageReader = ReadableStreamMessageReader;
4817 //# sourceMappingURL=messageReader.js.map
4821 /***/ (function(module, exports, __webpack_require__) {
4825 /* --------------------------------------------------------------------------------------------
4826 * Copyright (c) Microsoft Corporation. All rights reserved.
4827 * Licensed under the MIT License. See License.txt in the project root for license information.
4828 * ------------------------------------------------------------------------------------------ */
4829 Object.defineProperty(exports, "__esModule", { value: true });
4830 const ral_1 = __webpack_require__(48);
4831 const Is = __webpack_require__(52);
4832 const semaphore_1 = __webpack_require__(57);
4833 const events_1 = __webpack_require__(53);
4834 const ContentLength = 'Content-Length: ';
4835 const CRLF = '\r\n';
4837 (function (MessageWriter) {
4838 function is(value) {
4839 let candidate = value;
4840 return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
4841 Is.func(candidate.onError) && Is.func(candidate.write);
4843 MessageWriter.is = is;
4844 })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
4845 class AbstractMessageWriter {
4847 this.errorEmitter = new events_1.Emitter();
4848 this.closeEmitter = new events_1.Emitter();
4851 this.errorEmitter.dispose();
4852 this.closeEmitter.dispose();
4855 return this.errorEmitter.event;
4857 fireError(error, message, count) {
4858 this.errorEmitter.fire([this.asError(error), message, count]);
4861 return this.closeEmitter.event;
4864 this.closeEmitter.fire(undefined);
4867 if (error instanceof Error) {
4871 return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
4875 exports.AbstractMessageWriter = AbstractMessageWriter;
4876 var ResolvedMessageWriterOptions;
4877 (function (ResolvedMessageWriterOptions) {
4878 function fromOptions(options) {
4880 if (options === undefined || typeof options === 'string') {
4881 return { charset: options !== null && options !== void 0 ? options : 'utf-8', contentTypeEncoder: ral_1.default().applicationJson.encoder };
4884 return { charset: (_a = options.charset) !== null && _a !== void 0 ? _a : 'utf-8', contentEncoder: options.contentEncoder, contentTypeEncoder: (_b = options.contentTypeEncoder) !== null && _b !== void 0 ? _b : ral_1.default().applicationJson.encoder };
4887 ResolvedMessageWriterOptions.fromOptions = fromOptions;
4888 })(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));
4889 class WriteableStreamMessageWriter extends AbstractMessageWriter {
4890 constructor(writable, options) {
4892 this.writable = writable;
4893 this.options = ResolvedMessageWriterOptions.fromOptions(options);
4894 this.errorCount = 0;
4895 this.writeSemaphore = new semaphore_1.Semaphore(1);
4896 this.writable.onError((error) => this.fireError(error));
4897 this.writable.onClose(() => this.fireClose());
4900 const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {
4901 if (this.options.contentEncoder !== undefined) {
4902 return this.options.contentEncoder.encode(buffer);
4908 return payload.then((buffer) => {
4910 headers.push(ContentLength, buffer.byteLength.toString(), CRLF);
4912 return this.doWrite(msg, headers, buffer);
4914 this.fireError(error);
4918 doWrite(msg, headers, data) {
4919 return this.writeSemaphore.lock(async () => {
4921 await this.writable.write(headers.join(''), 'ascii');
4922 return this.writable.write(data);
4925 this.handleError(error, msg);
4929 handleError(error, msg) {
4931 this.fireError(error, msg, this.errorCount);
4934 exports.WriteableStreamMessageWriter = WriteableStreamMessageWriter;
4935 //# sourceMappingURL=messageWriter.js.map
4939 /***/ (function(module, exports, __webpack_require__) {
4943 /* --------------------------------------------------------------------------------------------
4944 * Copyright (c) Microsoft Corporation. All rights reserved.
4945 * Licensed under the MIT License. See License.txt in the project root for license information.
4946 * ------------------------------------------------------------------------------------------ */
4947 Object.defineProperty(exports, "__esModule", { value: true });
4948 const ral_1 = __webpack_require__(48);
4950 constructor(capacity = 1) {
4951 if (capacity <= 0) {
4952 throw new Error('Capacity must be greater than 0');
4954 this._capacity = capacity;
4959 return new Promise((resolve, reject) => {
4960 this._waiting.push({ thunk, resolve, reject });
4965 return this._active;
4968 if (this._waiting.length === 0 || this._active === this._capacity) {
4971 ral_1.default().timer.setImmediate(() => this.doRunNext());
4974 if (this._waiting.length === 0 || this._active === this._capacity) {
4977 const next = this._waiting.shift();
4979 if (this._active > this._capacity) {
4980 throw new Error(`To many thunks active`);
4983 const result = next.thunk();
4984 if (result instanceof Promise) {
4985 result.then((value) => {
4987 next.resolve(value);
4997 next.resolve(result);
5008 exports.Semaphore = Semaphore;
5009 //# sourceMappingURL=semaphore.js.map
5013 /***/ (function(module, exports, __webpack_require__) {
5017 /* --------------------------------------------------------------------------------------------
5018 * Copyright (c) Microsoft Corporation. All rights reserved.
5019 * Licensed under the MIT License. See License.txt in the project root for license information.
5020 * ------------------------------------------------------------------------------------------ */
5021 Object.defineProperty(exports, "__esModule", { value: true });
5022 const ral_1 = __webpack_require__(48);
5023 const Is = __webpack_require__(52);
5024 const messages_1 = __webpack_require__(51);
5025 const linkedMap_1 = __webpack_require__(59);
5026 const events_1 = __webpack_require__(53);
5027 const cancellation_1 = __webpack_require__(54);
5028 var CancelNotification;
5029 (function (CancelNotification) {
5030 CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
5031 })(CancelNotification || (CancelNotification = {}));
5032 var ProgressNotification;
5033 (function (ProgressNotification) {
5034 ProgressNotification.type = new messages_1.NotificationType('$/progress');
5035 })(ProgressNotification || (ProgressNotification = {}));
5036 class ProgressType {
5040 exports.ProgressType = ProgressType;
5041 exports.NullLogger = Object.freeze({
5049 Trace[Trace["Off"] = 0] = "Off";
5050 Trace[Trace["Messages"] = 1] = "Messages";
5051 Trace[Trace["Verbose"] = 2] = "Verbose";
5052 })(Trace = exports.Trace || (exports.Trace = {}));
5054 function fromString(value) {
5055 if (!Is.string(value)) {
5058 value = value.toLowerCase();
5063 return Trace.Messages;
5065 return Trace.Verbose;
5070 Trace.fromString = fromString;
5071 function toString(value) {
5075 case Trace.Messages:
5083 Trace.toString = toString;
5084 })(Trace = exports.Trace || (exports.Trace = {}));
5086 (function (TraceFormat) {
5087 TraceFormat["Text"] = "text";
5088 TraceFormat["JSON"] = "json";
5089 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
5090 (function (TraceFormat) {
5091 function fromString(value) {
5092 value = value.toLowerCase();
5093 if (value === 'json') {
5094 return TraceFormat.JSON;
5097 return TraceFormat.Text;
5100 TraceFormat.fromString = fromString;
5101 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
5102 var SetTraceNotification;
5103 (function (SetTraceNotification) {
5104 SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');
5105 })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
5106 var LogTraceNotification;
5107 (function (LogTraceNotification) {
5108 LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');
5109 })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
5110 var ConnectionErrors;
5111 (function (ConnectionErrors) {
5113 * The connection is closed.
5115 ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
5117 * The connection got disposed.
5119 ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
5121 * The connection is already in listening mode.
5123 ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
5124 })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
5125 class ConnectionError extends Error {
5126 constructor(code, message) {
5129 Object.setPrototypeOf(this, ConnectionError.prototype);
5132 exports.ConnectionError = ConnectionError;
5133 var ConnectionStrategy;
5134 (function (ConnectionStrategy) {
5135 function is(value) {
5136 const candidate = value;
5137 return candidate && Is.func(candidate.cancelUndispatched);
5139 ConnectionStrategy.is = is;
5140 })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
5141 var CancellationReceiverStrategy;
5142 (function (CancellationReceiverStrategy) {
5143 CancellationReceiverStrategy.Message = Object.freeze({
5144 createCancellationTokenSource(_) {
5145 return new cancellation_1.CancellationTokenSource();
5148 function is(value) {
5149 const candidate = value;
5150 return candidate && Is.func(candidate.createCancellationTokenSource);
5152 CancellationReceiverStrategy.is = is;
5153 })(CancellationReceiverStrategy = exports.CancellationReceiverStrategy || (exports.CancellationReceiverStrategy = {}));
5154 var CancellationSenderStrategy;
5155 (function (CancellationSenderStrategy) {
5156 CancellationSenderStrategy.Message = Object.freeze({
5157 sendCancellation(conn, id) {
5158 conn.sendNotification(CancelNotification.type, { id });
5162 function is(value) {
5163 const candidate = value;
5164 return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup);
5166 CancellationSenderStrategy.is = is;
5167 })(CancellationSenderStrategy = exports.CancellationSenderStrategy || (exports.CancellationSenderStrategy = {}));
5168 var CancellationStrategy;
5169 (function (CancellationStrategy) {
5170 CancellationStrategy.Message = Object.freeze({
5171 receiver: CancellationReceiverStrategy.Message,
5172 sender: CancellationSenderStrategy.Message
5174 function is(value) {
5175 const candidate = value;
5176 return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);
5178 CancellationStrategy.is = is;
5179 })(CancellationStrategy = exports.CancellationStrategy || (exports.CancellationStrategy = {}));
5180 var ConnectionOptions;
5181 (function (ConnectionOptions) {
5182 function is(value) {
5183 const candidate = value;
5184 return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy));
5186 ConnectionOptions.is = is;
5187 })(ConnectionOptions = exports.ConnectionOptions || (exports.ConnectionOptions = {}));
5188 var ConnectionState;
5189 (function (ConnectionState) {
5190 ConnectionState[ConnectionState["New"] = 1] = "New";
5191 ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
5192 ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
5193 ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
5194 })(ConnectionState || (ConnectionState = {}));
5195 function createMessageConnection(messageReader, messageWriter, _logger, options) {
5196 const logger = _logger !== undefined ? _logger : exports.NullLogger;
5197 let sequenceNumber = 0;
5198 let notificationSquenceNumber = 0;
5199 let unknownResponseSquenceNumber = 0;
5200 const version = '2.0';
5201 let starRequestHandler = undefined;
5202 const requestHandlers = Object.create(null);
5203 let starNotificationHandler = undefined;
5204 const notificationHandlers = Object.create(null);
5205 const progressHandlers = new Map();
5207 let messageQueue = new linkedMap_1.LinkedMap();
5208 let responsePromises = Object.create(null);
5209 let requestTokens = Object.create(null);
5210 let trace = Trace.Off;
5211 let traceFormat = TraceFormat.Text;
5213 let state = ConnectionState.New;
5214 const errorEmitter = new events_1.Emitter();
5215 const closeEmitter = new events_1.Emitter();
5216 const unhandledNotificationEmitter = new events_1.Emitter();
5217 const unhandledProgressEmitter = new events_1.Emitter();
5218 const disposeEmitter = new events_1.Emitter();
5219 const cancellationStrategy = (options && options.cancellationStrategy) ? options.cancellationStrategy : CancellationStrategy.Message;
5220 function createRequestQueueKey(id) {
5221 return 'req-' + id.toString();
5223 function createResponseQueueKey(id) {
5225 return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
5228 return 'res-' + id.toString();
5231 function createNotificationQueueKey() {
5232 return 'not-' + (++notificationSquenceNumber).toString();
5234 function addMessageToQueue(queue, message) {
5235 if (messages_1.isRequestMessage(message)) {
5236 queue.set(createRequestQueueKey(message.id), message);
5238 else if (messages_1.isResponseMessage(message)) {
5239 queue.set(createResponseQueueKey(message.id), message);
5242 queue.set(createNotificationQueueKey(), message);
5245 function cancelUndispatched(_message) {
5248 function isListening() {
5249 return state === ConnectionState.Listening;
5251 function isClosed() {
5252 return state === ConnectionState.Closed;
5254 function isDisposed() {
5255 return state === ConnectionState.Disposed;
5257 function closeHandler() {
5258 if (state === ConnectionState.New || state === ConnectionState.Listening) {
5259 state = ConnectionState.Closed;
5260 closeEmitter.fire(undefined);
5262 // If the connection is disposed don't sent close events.
5264 function readErrorHandler(error) {
5265 errorEmitter.fire([error, undefined, undefined]);
5267 function writeErrorHandler(data) {
5268 errorEmitter.fire(data);
5270 messageReader.onClose(closeHandler);
5271 messageReader.onError(readErrorHandler);
5272 messageWriter.onClose(closeHandler);
5273 messageWriter.onError(writeErrorHandler);
5274 function triggerMessageQueue() {
5275 if (timer || messageQueue.size === 0) {
5278 timer = ral_1.default().timer.setImmediate(() => {
5280 processMessageQueue();
5283 function processMessageQueue() {
5284 if (messageQueue.size === 0) {
5287 const message = messageQueue.shift();
5289 if (messages_1.isRequestMessage(message)) {
5290 handleRequest(message);
5292 else if (messages_1.isNotificationMessage(message)) {
5293 handleNotification(message);
5295 else if (messages_1.isResponseMessage(message)) {
5296 handleResponse(message);
5299 handleInvalidMessage(message);
5303 triggerMessageQueue();
5306 const callback = (message) => {
5308 // We have received a cancellation message. Check if the message is still in the queue
5309 // and cancel it if allowed to do so.
5310 if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
5311 const key = createRequestQueueKey(message.params.id);
5312 const toCancel = messageQueue.get(key);
5313 if (messages_1.isRequestMessage(toCancel)) {
5314 const strategy = options === null || options === void 0 ? void 0 : options.connectionStrategy;
5315 const response = (strategy && strategy.cancelUndispatched) ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
5316 if (response && (response.error !== undefined || response.result !== undefined)) {
5317 messageQueue.delete(key);
5318 response.id = toCancel.id;
5319 traceSendingResponse(response, message.method, Date.now());
5320 messageWriter.write(response);
5325 addMessageToQueue(messageQueue, message);
5328 triggerMessageQueue();
5331 function handleRequest(requestMessage) {
5333 // we return here silently since we fired an event when the
5334 // connection got disposed.
5337 function reply(resultOrError, method, startTime) {
5340 id: requestMessage.id
5342 if (resultOrError instanceof messages_1.ResponseError) {
5343 message.error = resultOrError.toJson();
5346 message.result = resultOrError === undefined ? null : resultOrError;
5348 traceSendingResponse(message, method, startTime);
5349 messageWriter.write(message);
5351 function replyError(error, method, startTime) {
5354 id: requestMessage.id,
5355 error: error.toJson()
5357 traceSendingResponse(message, method, startTime);
5358 messageWriter.write(message);
5360 function replySuccess(result, method, startTime) {
5361 // The JSON RPC defines that a response must either have a result or an error
5362 // So we can't treat undefined as a valid response result.
5363 if (result === undefined) {
5368 id: requestMessage.id,
5371 traceSendingResponse(message, method, startTime);
5372 messageWriter.write(message);
5374 traceReceivedRequest(requestMessage);
5375 const element = requestHandlers[requestMessage.method];
5379 type = element.type;
5380 requestHandler = element.handler;
5382 const startTime = Date.now();
5383 if (requestHandler || starRequestHandler) {
5384 const tokenKey = String(requestMessage.id);
5385 const cancellationSource = cancellationStrategy.receiver.createCancellationTokenSource(tokenKey);
5386 requestTokens[tokenKey] = cancellationSource;
5389 if (requestMessage.params === undefined || (type !== undefined && type.numberOfParams === 0)) {
5390 handlerResult = requestHandler
5391 ? requestHandler(cancellationSource.token)
5392 : starRequestHandler(requestMessage.method, cancellationSource.token);
5394 else if (Is.array(requestMessage.params) && (type === undefined || type.numberOfParams > 1)) {
5395 handlerResult = requestHandler
5396 ? requestHandler(...requestMessage.params, cancellationSource.token)
5397 : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
5400 handlerResult = requestHandler
5401 ? requestHandler(requestMessage.params, cancellationSource.token)
5402 : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
5404 const promise = handlerResult;
5405 if (!handlerResult) {
5406 delete requestTokens[tokenKey];
5407 replySuccess(handlerResult, requestMessage.method, startTime);
5409 else if (promise.then) {
5410 promise.then((resultOrError) => {
5411 delete requestTokens[tokenKey];
5412 reply(resultOrError, requestMessage.method, startTime);
5414 delete requestTokens[tokenKey];
5415 if (error instanceof messages_1.ResponseError) {
5416 replyError(error, requestMessage.method, startTime);
5418 else if (error && Is.string(error.message)) {
5419 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
5422 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
5427 delete requestTokens[tokenKey];
5428 reply(handlerResult, requestMessage.method, startTime);
5432 delete requestTokens[tokenKey];
5433 if (error instanceof messages_1.ResponseError) {
5434 reply(error, requestMessage.method, startTime);
5436 else if (error && Is.string(error.message)) {
5437 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
5440 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
5445 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
5448 function handleResponse(responseMessage) {
5450 // See handle request.
5453 if (responseMessage.id === null) {
5454 if (responseMessage.error) {
5455 logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
5458 logger.error(`Received response message without id. No further error information provided.`);
5462 const key = String(responseMessage.id);
5463 const responsePromise = responsePromises[key];
5464 traceReceivedResponse(responseMessage, responsePromise);
5465 if (responsePromise) {
5466 delete responsePromises[key];
5468 if (responseMessage.error) {
5469 const error = responseMessage.error;
5470 responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
5472 else if (responseMessage.result !== undefined) {
5473 responsePromise.resolve(responseMessage.result);
5476 throw new Error('Should never happen.');
5480 if (error.message) {
5481 logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
5484 logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
5490 function handleNotification(message) {
5492 // See handle request.
5495 let type = undefined;
5496 let notificationHandler;
5497 if (message.method === CancelNotification.type.method) {
5498 notificationHandler = (params) => {
5499 const id = params.id;
5500 const source = requestTokens[String(id)];
5507 const element = notificationHandlers[message.method];
5509 notificationHandler = element.handler;
5510 type = element.type;
5513 if (notificationHandler || starNotificationHandler) {
5515 traceReceivedNotification(message);
5516 if (message.params === undefined || (type !== undefined && type.numberOfParams === 0)) {
5517 notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
5519 else if (Is.array(message.params) && (type === undefined || type.numberOfParams > 1)) {
5520 notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
5523 notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
5527 if (error.message) {
5528 logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
5531 logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
5536 unhandledNotificationEmitter.fire(message);
5539 function handleInvalidMessage(message) {
5541 logger.error('Received empty message.');
5544 logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
5545 // Test whether we find an id to reject the promise
5546 const responseMessage = message;
5547 if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
5548 const key = String(responseMessage.id);
5549 const responseHandler = responsePromises[key];
5550 if (responseHandler) {
5551 responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
5555 function traceSendingRequest(message) {
5556 if (trace === Trace.Off || !tracer) {
5559 if (traceFormat === TraceFormat.Text) {
5560 let data = undefined;
5561 if (trace === Trace.Verbose && message.params) {
5562 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
5564 tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
5567 logLSPMessage('send-request', message);
5570 function traceSendingNotification(message) {
5571 if (trace === Trace.Off || !tracer) {
5574 if (traceFormat === TraceFormat.Text) {
5575 let data = undefined;
5576 if (trace === Trace.Verbose) {
5577 if (message.params) {
5578 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
5581 data = 'No parameters provided.\n\n';
5584 tracer.log(`Sending notification '${message.method}'.`, data);
5587 logLSPMessage('send-notification', message);
5590 function traceSendingResponse(message, method, startTime) {
5591 if (trace === Trace.Off || !tracer) {
5594 if (traceFormat === TraceFormat.Text) {
5595 let data = undefined;
5596 if (trace === Trace.Verbose) {
5597 if (message.error && message.error.data) {
5598 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
5601 if (message.result) {
5602 data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
5604 else if (message.error === undefined) {
5605 data = 'No result returned.\n\n';
5609 tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
5612 logLSPMessage('send-response', message);
5615 function traceReceivedRequest(message) {
5616 if (trace === Trace.Off || !tracer) {
5619 if (traceFormat === TraceFormat.Text) {
5620 let data = undefined;
5621 if (trace === Trace.Verbose && message.params) {
5622 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
5624 tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
5627 logLSPMessage('receive-request', message);
5630 function traceReceivedNotification(message) {
5631 if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
5634 if (traceFormat === TraceFormat.Text) {
5635 let data = undefined;
5636 if (trace === Trace.Verbose) {
5637 if (message.params) {
5638 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
5641 data = 'No parameters provided.\n\n';
5644 tracer.log(`Received notification '${message.method}'.`, data);
5647 logLSPMessage('receive-notification', message);
5650 function traceReceivedResponse(message, responsePromise) {
5651 if (trace === Trace.Off || !tracer) {
5654 if (traceFormat === TraceFormat.Text) {
5655 let data = undefined;
5656 if (trace === Trace.Verbose) {
5657 if (message.error && message.error.data) {
5658 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
5661 if (message.result) {
5662 data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
5664 else if (message.error === undefined) {
5665 data = 'No result returned.\n\n';
5669 if (responsePromise) {
5670 const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
5671 tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
5674 tracer.log(`Received response ${message.id} without active response promise.`, data);
5678 logLSPMessage('receive-response', message);
5681 function logLSPMessage(type, message) {
5682 if (!tracer || trace === Trace.Off) {
5685 const lspMessage = {
5689 timestamp: Date.now()
5691 tracer.log(lspMessage);
5693 function throwIfClosedOrDisposed() {
5695 throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
5698 throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
5701 function throwIfListening() {
5702 if (isListening()) {
5703 throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
5706 function throwIfNotListening() {
5707 if (!isListening()) {
5708 throw new Error('Call listen() first.');
5711 function undefinedToNull(param) {
5712 if (param === undefined) {
5719 function computeMessageParams(type, params) {
5721 const numberOfParams = type.numberOfParams;
5722 switch (numberOfParams) {
5727 result = undefinedToNull(params[0]);
5731 for (let i = 0; i < params.length && i < numberOfParams; i++) {
5732 result.push(undefinedToNull(params[i]));
5734 if (params.length < numberOfParams) {
5735 for (let i = params.length; i < numberOfParams; i++) {
5743 const connection = {
5744 sendNotification: (type, ...params) => {
5745 throwIfClosedOrDisposed();
5748 if (Is.string(type)) {
5750 switch (params.length) {
5752 messageParams = null;
5755 messageParams = params[0];
5758 messageParams = params;
5763 method = type.method;
5764 messageParams = computeMessageParams(type, params);
5766 const notificationMessage = {
5769 params: messageParams
5771 traceSendingNotification(notificationMessage);
5772 messageWriter.write(notificationMessage);
5774 onNotification: (type, handler) => {
5775 throwIfClosedOrDisposed();
5776 if (Is.func(type)) {
5777 starNotificationHandler = type;
5780 if (Is.string(type)) {
5781 notificationHandlers[type] = { type: undefined, handler };
5784 notificationHandlers[type.method] = { type, handler };
5788 onProgress: (_type, token, handler) => {
5789 if (progressHandlers.has(token)) {
5790 throw new Error(`Progress handler for token ${token} already registered`);
5792 progressHandlers.set(token, handler);
5795 progressHandlers.delete(token);
5799 sendProgress: (_type, token, value) => {
5800 connection.sendNotification(ProgressNotification.type, { token, value });
5802 onUnhandledProgress: unhandledProgressEmitter.event,
5803 sendRequest: (type, ...params) => {
5804 throwIfClosedOrDisposed();
5805 throwIfNotListening();
5808 let token = undefined;
5809 if (Is.string(type)) {
5811 switch (params.length) {
5813 messageParams = null;
5816 // The cancellation token is optional so it can also be undefined.
5817 if (cancellation_1.CancellationToken.is(params[0])) {
5818 messageParams = null;
5822 messageParams = undefinedToNull(params[0]);
5826 const last = params.length - 1;
5827 if (cancellation_1.CancellationToken.is(params[last])) {
5828 token = params[last];
5829 if (params.length === 2) {
5830 messageParams = undefinedToNull(params[0]);
5833 messageParams = params.slice(0, last).map(value => undefinedToNull(value));
5837 messageParams = params.map(value => undefinedToNull(value));
5843 method = type.method;
5844 messageParams = computeMessageParams(type, params);
5845 const numberOfParams = type.numberOfParams;
5846 token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
5848 const id = sequenceNumber++;
5851 disposable = token.onCancellationRequested(() => {
5852 cancellationStrategy.sender.sendCancellation(connection, id);
5855 const result = new Promise((resolve, reject) => {
5856 const requestMessage = {
5860 params: messageParams
5862 const resolveWithCleanup = (r) => {
5864 cancellationStrategy.sender.cleanup(id);
5865 disposable === null || disposable === void 0 ? void 0 : disposable.dispose();
5867 const rejectWithCleanup = (r) => {
5869 cancellationStrategy.sender.cleanup(id);
5870 disposable === null || disposable === void 0 ? void 0 : disposable.dispose();
5872 let responsePromise = { method: method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup };
5873 traceSendingRequest(requestMessage);
5875 messageWriter.write(requestMessage);
5878 // Writing the message failed. So we need to reject the promise.
5879 responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
5880 responsePromise = null;
5882 if (responsePromise) {
5883 responsePromises[String(id)] = responsePromise;
5888 onRequest: (type, handler) => {
5889 throwIfClosedOrDisposed();
5890 if (Is.func(type)) {
5891 starRequestHandler = type;
5894 if (Is.string(type)) {
5895 requestHandlers[type] = { type: undefined, handler };
5898 requestHandlers[type.method] = { type, handler };
5902 trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
5903 let _sendNotification = false;
5904 let _traceFormat = TraceFormat.Text;
5905 if (sendNotificationOrTraceOptions !== undefined) {
5906 if (Is.boolean(sendNotificationOrTraceOptions)) {
5907 _sendNotification = sendNotificationOrTraceOptions;
5910 _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
5911 _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
5915 traceFormat = _traceFormat;
5916 if (trace === Trace.Off) {
5922 if (_sendNotification && !isClosed() && !isDisposed()) {
5923 connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
5926 onError: errorEmitter.event,
5927 onClose: closeEmitter.event,
5928 onUnhandledNotification: unhandledNotificationEmitter.event,
5929 onDispose: disposeEmitter.event,
5934 state = ConnectionState.Disposed;
5935 disposeEmitter.fire(undefined);
5936 const error = new Error('Connection got disposed.');
5937 Object.keys(responsePromises).forEach((key) => {
5938 responsePromises[key].reject(error);
5940 responsePromises = Object.create(null);
5941 requestTokens = Object.create(null);
5942 messageQueue = new linkedMap_1.LinkedMap();
5943 // Test for backwards compatibility
5944 if (Is.func(messageWriter.dispose)) {
5945 messageWriter.dispose();
5947 if (Is.func(messageReader.dispose)) {
5948 messageReader.dispose();
5952 throwIfClosedOrDisposed();
5954 state = ConnectionState.Listening;
5955 messageReader.listen(callback);
5958 // eslint-disable-next-line no-console
5959 ral_1.default().console.log('inspect');
5962 connection.onNotification(LogTraceNotification.type, (params) => {
5963 if (trace === Trace.Off || !tracer) {
5966 tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
5968 connection.onNotification(ProgressNotification.type, (params) => {
5969 const handler = progressHandlers.get(params.token);
5971 handler(params.value);
5974 unhandledProgressEmitter.fire(params);
5979 exports.createMessageConnection = createMessageConnection;
5980 //# sourceMappingURL=connection.js.map
5984 /***/ (function(module, exports, __webpack_require__) {
5988 /*---------------------------------------------------------------------------------------------
5989 * Copyright (c) Microsoft Corporation. All rights reserved.
5990 * Licensed under the MIT License. See License.txt in the project root for license information.
5991 *--------------------------------------------------------------------------------------------*/
5992 Object.defineProperty(exports, "__esModule", { value: true });
5997 Touch.AsOld = Touch.First;
5999 Touch.AsNew = Touch.Last;
6000 })(Touch = exports.Touch || (exports.Touch = {}));
6003 this[Symbol.toStringTag] = 'LinkedMap';
6004 this._map = new Map();
6005 this._head = undefined;
6006 this._tail = undefined;
6012 this._head = undefined;
6013 this._tail = undefined;
6018 return !this._head && !this._tail;
6025 return (_a = this._head) === null || _a === void 0 ? void 0 : _a.value;
6029 return (_a = this._tail) === null || _a === void 0 ? void 0 : _a.value;
6032 return this._map.has(key);
6034 get(key, touch = Touch.None) {
6035 const item = this._map.get(key);
6039 if (touch !== Touch.None) {
6040 this.touch(item, touch);
6044 set(key, value, touch = Touch.None) {
6045 let item = this._map.get(key);
6048 if (touch !== Touch.None) {
6049 this.touch(item, touch);
6053 item = { key, value, next: undefined, previous: undefined };
6056 this.addItemLast(item);
6059 this.addItemFirst(item);
6062 this.addItemLast(item);
6065 this.addItemLast(item);
6068 this._map.set(key, item);
6074 return !!this.remove(key);
6077 const item = this._map.get(key);
6081 this._map.delete(key);
6082 this.removeItem(item);
6087 if (!this._head && !this._tail) {
6090 if (!this._head || !this._tail) {
6091 throw new Error('Invalid list');
6093 const item = this._head;
6094 this._map.delete(item.key);
6095 this.removeItem(item);
6099 forEach(callbackfn, thisArg) {
6100 const state = this._state;
6101 let current = this._head;
6104 callbackfn.bind(thisArg)(current.value, current.key, this);
6107 callbackfn(current.value, current.key, this);
6109 if (this._state !== state) {
6110 throw new Error(`LinkedMap got modified during iteration.`);
6112 current = current.next;
6117 const state = this._state;
6118 let current = this._head;
6120 [Symbol.iterator]() {
6124 if (map._state !== state) {
6125 throw new Error(`LinkedMap got modified during iteration.`);
6128 const result = { value: current.key, done: false };
6129 current = current.next;
6133 return { value: undefined, done: true };
6141 const state = this._state;
6142 let current = this._head;
6144 [Symbol.iterator]() {
6148 if (map._state !== state) {
6149 throw new Error(`LinkedMap got modified during iteration.`);
6152 const result = { value: current.value, done: false };
6153 current = current.next;
6157 return { value: undefined, done: true };
6165 const state = this._state;
6166 let current = this._head;
6168 [Symbol.iterator]() {
6172 if (map._state !== state) {
6173 throw new Error(`LinkedMap got modified during iteration.`);
6176 const result = { value: [current.key, current.value], done: false };
6177 current = current.next;
6181 return { value: undefined, done: true };
6187 [Symbol.iterator]() {
6188 return this.entries();
6191 if (newSize >= this.size) {
6194 if (newSize === 0) {
6198 let current = this._head;
6199 let currentSize = this.size;
6200 while (current && currentSize > newSize) {
6201 this._map.delete(current.key);
6202 current = current.next;
6205 this._head = current;
6206 this._size = currentSize;
6208 current.previous = undefined;
6212 addItemFirst(item) {
6213 // First time Insert
6214 if (!this._head && !this._tail) {
6217 else if (!this._head) {
6218 throw new Error('Invalid list');
6221 item.next = this._head;
6222 this._head.previous = item;
6228 // First time Insert
6229 if (!this._head && !this._tail) {
6232 else if (!this._tail) {
6233 throw new Error('Invalid list');
6236 item.previous = this._tail;
6237 this._tail.next = item;
6243 if (item === this._head && item === this._tail) {
6244 this._head = undefined;
6245 this._tail = undefined;
6247 else if (item === this._head) {
6248 // This can only happend if size === 1 which is handle
6249 // by the case above.
6251 throw new Error('Invalid list');
6253 item.next.previous = undefined;
6254 this._head = item.next;
6256 else if (item === this._tail) {
6257 // This can only happend if size === 1 which is handle
6258 // by the case above.
6259 if (!item.previous) {
6260 throw new Error('Invalid list');
6262 item.previous.next = undefined;
6263 this._tail = item.previous;
6266 const next = item.next;
6267 const previous = item.previous;
6268 if (!next || !previous) {
6269 throw new Error('Invalid list');
6271 next.previous = previous;
6272 previous.next = next;
6274 item.next = undefined;
6275 item.previous = undefined;
6278 touch(item, touch) {
6279 if (!this._head || !this._tail) {
6280 throw new Error('Invalid list');
6282 if ((touch !== Touch.First && touch !== Touch.Last)) {
6285 if (touch === Touch.First) {
6286 if (item === this._head) {
6289 const next = item.next;
6290 const previous = item.previous;
6292 if (item === this._tail) {
6293 // previous must be defined since item was not head but is tail
6294 // So there are more than on item in the map
6295 previous.next = undefined;
6296 this._tail = previous;
6299 // Both next and previous are not undefined since item was neither head nor tail.
6300 next.previous = previous;
6301 previous.next = next;
6303 // Insert the node at head
6304 item.previous = undefined;
6305 item.next = this._head;
6306 this._head.previous = item;
6310 else if (touch === Touch.Last) {
6311 if (item === this._tail) {
6314 const next = item.next;
6315 const previous = item.previous;
6317 if (item === this._head) {
6318 // next must be defined since item was not tail but is head
6319 // So there are more than on item in the map
6320 next.previous = undefined;
6324 // Both next and previous are not undefined since item was neither head nor tail.
6325 next.previous = previous;
6326 previous.next = next;
6328 item.next = undefined;
6329 item.previous = this._tail;
6330 this._tail.next = item;
6337 this.forEach((value, key) => {
6338 data.push([key, value]);
6344 for (const [key, value] of data) {
6345 this.set(key, value);
6349 exports.LinkedMap = LinkedMap;
6350 class LRUCache extends LinkedMap {
6351 constructor(limit, ratio = 1) {
6353 this._limit = limit;
6354 this._ratio = Math.min(Math.max(0, ratio), 1);
6360 this._limit = limit;
6367 this._ratio = Math.min(Math.max(0, ratio), 1);
6370 get(key, touch = Touch.AsNew) {
6371 return super.get(key, touch);
6374 return super.get(key, Touch.None);
6377 super.set(key, value, Touch.Last);
6382 if (this.size > this._limit) {
6383 this.trimOld(Math.round(this._limit * this._ratio));
6387 exports.LRUCache = LRUCache;
6388 //# sourceMappingURL=linkedMap.js.map
6392 /***/ (function(module, exports, __webpack_require__) {
6396 /* --------------------------------------------------------------------------------------------
6397 * Copyright (c) Microsoft Corporation. All rights reserved.
6398 * Licensed under the MIT License. See License.txt in the project root for license information.
6399 * ------------------------------------------------------------------------------------------ */
6400 function __export(m) {
6401 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
6403 Object.defineProperty(exports, "__esModule", { value: true });
6404 __export(__webpack_require__(46));
6405 __export(__webpack_require__(61));
6406 __export(__webpack_require__(62));
6407 __export(__webpack_require__(63));
6408 var connection_1 = __webpack_require__(75);
6409 exports.createProtocolConnection = connection_1.createProtocolConnection;
6410 const st = __webpack_require__(76);
6412 (function (Proposed) {
6413 Proposed.SemanticTokenTypes = st.SemanticTokenTypes;
6414 Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers;
6415 Proposed.SemanticTokens = st.SemanticTokens;
6416 let SemanticTokensRequest;
6417 (function (SemanticTokensRequest) {
6418 SemanticTokensRequest.method = st.SemanticTokensRequest.method;
6419 SemanticTokensRequest.type = st.SemanticTokensRequest.type;
6420 })(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {}));
6421 let SemanticTokensEditsRequest;
6422 (function (SemanticTokensEditsRequest) {
6423 SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method;
6424 SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type;
6425 })(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {}));
6426 let SemanticTokensRangeRequest;
6427 (function (SemanticTokensRangeRequest) {
6428 SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method;
6429 SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type;
6430 })(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {}));
6431 })(Proposed = exports.Proposed || (exports.Proposed = {}));
6432 //# sourceMappingURL=api.js.map
6436 /***/ (function(module, __webpack_exports__, __webpack_require__) {
6439 __webpack_require__.r(__webpack_exports__);
6440 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
6441 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
6442 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
6443 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
6444 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
6445 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
6446 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
6447 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
6448 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
6449 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
6450 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
6451 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
6452 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticCode", function() { return DiagnosticCode; });
6453 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
6454 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
6455 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
6456 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
6457 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
6458 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
6459 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
6460 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
6461 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
6462 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
6463 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
6464 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
6465 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
6466 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
6467 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
6468 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
6469 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemTag", function() { return CompletionItemTag; });
6470 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertReplaceEdit", function() { return InsertReplaceEdit; });
6471 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
6472 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
6473 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
6474 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
6475 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
6476 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
6477 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
6478 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
6479 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
6480 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolTag", function() { return SymbolTag; });
6481 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
6482 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
6483 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
6484 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
6485 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
6486 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
6487 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
6488 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
6489 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
6490 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
6491 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
6492 /* --------------------------------------------------------------------------------------------
6493 * Copyright (c) Microsoft Corporation. All rights reserved.
6494 * Licensed under the MIT License. See License.txt in the project root for license information.
6495 * ------------------------------------------------------------------------------------------ */
6498 * The Position namespace provides helper functions to work with
6499 * [Position](#Position) literals.
6502 (function (Position) {
6504 * Creates a new Position literal from the given line and character.
6505 * @param line The position's line.
6506 * @param character The position's character.
6508 function create(line, character) {
6509 return { line: line, character: character };
6511 Position.create = create;
6513 * Checks whether the given liternal conforms to the [Position](#Position) interface.
6515 function is(value) {
6516 var candidate = value;
6517 return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
6520 })(Position || (Position = {}));
6522 * The Range namespace provides helper functions to work with
6523 * [Range](#Range) literals.
6527 function create(one, two, three, four) {
6528 if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
6529 return { start: Position.create(one, two), end: Position.create(three, four) };
6531 else if (Position.is(one) && Position.is(two)) {
6532 return { start: one, end: two };
6535 throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
6538 Range.create = create;
6540 * Checks whether the given literal conforms to the [Range](#Range) interface.
6542 function is(value) {
6543 var candidate = value;
6544 return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
6547 })(Range || (Range = {}));
6549 * The Location namespace provides helper functions to work with
6550 * [Location](#Location) literals.
6553 (function (Location) {
6555 * Creates a Location literal.
6556 * @param uri The location's uri.
6557 * @param range The location's range.
6559 function create(uri, range) {
6560 return { uri: uri, range: range };
6562 Location.create = create;
6564 * Checks whether the given literal conforms to the [Location](#Location) interface.
6566 function is(value) {
6567 var candidate = value;
6568 return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
6571 })(Location || (Location = {}));
6573 * The LocationLink namespace provides helper functions to work with
6574 * [LocationLink](#LocationLink) literals.
6577 (function (LocationLink) {
6579 * Creates a LocationLink literal.
6580 * @param targetUri The definition's uri.
6581 * @param targetRange The full range of the definition.
6582 * @param targetSelectionRange The span of the symbol definition at the target.
6583 * @param originSelectionRange The span of the symbol being defined in the originating source file.
6585 function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
6586 return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
6588 LocationLink.create = create;
6590 * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
6592 function is(value) {
6593 var candidate = value;
6594 return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
6595 && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
6596 && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
6598 LocationLink.is = is;
6599 })(LocationLink || (LocationLink = {}));
6601 * The Color namespace provides helper functions to work with
6602 * [Color](#Color) literals.
6607 * Creates a new Color literal.
6609 function create(red, green, blue, alpha) {
6617 Color.create = create;
6619 * Checks whether the given literal conforms to the [Color](#Color) interface.
6621 function is(value) {
6622 var candidate = value;
6623 return Is.number(candidate.red)
6624 && Is.number(candidate.green)
6625 && Is.number(candidate.blue)
6626 && Is.number(candidate.alpha);
6629 })(Color || (Color = {}));
6631 * The ColorInformation namespace provides helper functions to work with
6632 * [ColorInformation](#ColorInformation) literals.
6634 var ColorInformation;
6635 (function (ColorInformation) {
6637 * Creates a new ColorInformation literal.
6639 function create(range, color) {
6645 ColorInformation.create = create;
6647 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
6649 function is(value) {
6650 var candidate = value;
6651 return Range.is(candidate.range) && Color.is(candidate.color);
6653 ColorInformation.is = is;
6654 })(ColorInformation || (ColorInformation = {}));
6656 * The Color namespace provides helper functions to work with
6657 * [ColorPresentation](#ColorPresentation) literals.
6659 var ColorPresentation;
6660 (function (ColorPresentation) {
6662 * Creates a new ColorInformation literal.
6664 function create(label, textEdit, additionalTextEdits) {
6668 additionalTextEdits: additionalTextEdits,
6671 ColorPresentation.create = create;
6673 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
6675 function is(value) {
6676 var candidate = value;
6677 return Is.string(candidate.label)
6678 && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
6679 && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
6681 ColorPresentation.is = is;
6682 })(ColorPresentation || (ColorPresentation = {}));
6684 * Enum of known range kinds
6686 var FoldingRangeKind;
6687 (function (FoldingRangeKind) {
6689 * Folding range for a comment
6691 FoldingRangeKind["Comment"] = "comment";
6693 * Folding range for a imports or includes
6695 FoldingRangeKind["Imports"] = "imports";
6697 * Folding range for a region (e.g. `#region`)
6699 FoldingRangeKind["Region"] = "region";
6700 })(FoldingRangeKind || (FoldingRangeKind = {}));
6702 * The folding range namespace provides helper functions to work with
6703 * [FoldingRange](#FoldingRange) literals.
6706 (function (FoldingRange) {
6708 * Creates a new FoldingRange literal.
6710 function create(startLine, endLine, startCharacter, endCharacter, kind) {
6712 startLine: startLine,
6715 if (Is.defined(startCharacter)) {
6716 result.startCharacter = startCharacter;
6718 if (Is.defined(endCharacter)) {
6719 result.endCharacter = endCharacter;
6721 if (Is.defined(kind)) {
6726 FoldingRange.create = create;
6728 * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
6730 function is(value) {
6731 var candidate = value;
6732 return Is.number(candidate.startLine) && Is.number(candidate.startLine)
6733 && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
6734 && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
6735 && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
6737 FoldingRange.is = is;
6738 })(FoldingRange || (FoldingRange = {}));
6740 * The DiagnosticRelatedInformation namespace provides helper functions to work with
6741 * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
6743 var DiagnosticRelatedInformation;
6744 (function (DiagnosticRelatedInformation) {
6746 * Creates a new DiagnosticRelatedInformation literal.
6748 function create(location, message) {
6754 DiagnosticRelatedInformation.create = create;
6756 * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
6758 function is(value) {
6759 var candidate = value;
6760 return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
6762 DiagnosticRelatedInformation.is = is;
6763 })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
6765 * The diagnostic's severity.
6767 var DiagnosticSeverity;
6768 (function (DiagnosticSeverity) {
6772 DiagnosticSeverity.Error = 1;
6774 * Reports a warning.
6776 DiagnosticSeverity.Warning = 2;
6778 * Reports an information.
6780 DiagnosticSeverity.Information = 3;
6784 DiagnosticSeverity.Hint = 4;
6785 })(DiagnosticSeverity || (DiagnosticSeverity = {}));
6787 * The diagnostic tags.
6792 (function (DiagnosticTag) {
6794 * Unused or unnecessary code.
6796 * Clients are allowed to render diagnostics with this tag faded out instead of having
6797 * an error squiggle.
6799 DiagnosticTag.Unnecessary = 1;
6801 * Deprecated or obsolete code.
6803 * Clients are allowed to rendered diagnostics with this tag strike through.
6805 DiagnosticTag.Deprecated = 2;
6806 })(DiagnosticTag || (DiagnosticTag = {}));
6808 * The DiagnosticCode namespace provides functions to deal with complex diagnostic codes.
6810 * @since 3.16.0 - Proposed state
6813 (function (DiagnosticCode) {
6815 * Checks whether the given liternal conforms to the [DiagnosticCode](#DiagnosticCode) interface.
6817 function is(value) {
6818 var candidate = value;
6819 return candidate !== undefined && candidate !== null && (Is.number(candidate.value) || Is.string(candidate.value)) && Is.string(candidate.target);
6821 DiagnosticCode.is = is;
6822 })(DiagnosticCode || (DiagnosticCode = {}));
6824 * The Diagnostic namespace provides helper functions to work with
6825 * [Diagnostic](#Diagnostic) literals.
6828 (function (Diagnostic) {
6830 * Creates a new Diagnostic literal.
6832 function create(range, message, severity, code, source, relatedInformation) {
6833 var result = { range: range, message: message };
6834 if (Is.defined(severity)) {
6835 result.severity = severity;
6837 if (Is.defined(code)) {
6840 if (Is.defined(source)) {
6841 result.source = source;
6843 if (Is.defined(relatedInformation)) {
6844 result.relatedInformation = relatedInformation;
6848 Diagnostic.create = create;
6850 * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
6852 function is(value) {
6853 var candidate = value;
6854 return Is.defined(candidate)
6855 && Range.is(candidate.range)
6856 && Is.string(candidate.message)
6857 && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
6858 && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
6859 && (Is.string(candidate.source) || Is.undefined(candidate.source))
6860 && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
6863 })(Diagnostic || (Diagnostic = {}));
6865 * The Command namespace provides helper functions to work with
6866 * [Command](#Command) literals.
6869 (function (Command) {
6871 * Creates a new Command literal.
6873 function create(title, command) {
6875 for (var _i = 2; _i < arguments.length; _i++) {
6876 args[_i - 2] = arguments[_i];
6878 var result = { title: title, command: command };
6879 if (Is.defined(args) && args.length > 0) {
6880 result.arguments = args;
6884 Command.create = create;
6886 * Checks whether the given literal conforms to the [Command](#Command) interface.
6888 function is(value) {
6889 var candidate = value;
6890 return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
6893 })(Command || (Command = {}));
6895 * The TextEdit namespace provides helper function to create replace,
6896 * insert and delete edits more easily.
6899 (function (TextEdit) {
6901 * Creates a replace text edit.
6902 * @param range The range of text to be replaced.
6903 * @param newText The new text.
6905 function replace(range, newText) {
6906 return { range: range, newText: newText };
6908 TextEdit.replace = replace;
6910 * Creates a insert text edit.
6911 * @param position The position to insert the text at.
6912 * @param newText The text to be inserted.
6914 function insert(position, newText) {
6915 return { range: { start: position, end: position }, newText: newText };
6917 TextEdit.insert = insert;
6919 * Creates a delete text edit.
6920 * @param range The range of text to be deleted.
6922 function del(range) {
6923 return { range: range, newText: '' };
6926 function is(value) {
6927 var candidate = value;
6928 return Is.objectLiteral(candidate)
6929 && Is.string(candidate.newText)
6930 && Range.is(candidate.range);
6933 })(TextEdit || (TextEdit = {}));
6935 * The TextDocumentEdit namespace provides helper function to create
6936 * an edit that manipulates a text document.
6938 var TextDocumentEdit;
6939 (function (TextDocumentEdit) {
6941 * Creates a new `TextDocumentEdit`
6943 function create(textDocument, edits) {
6944 return { textDocument: textDocument, edits: edits };
6946 TextDocumentEdit.create = create;
6947 function is(value) {
6948 var candidate = value;
6949 return Is.defined(candidate)
6950 && VersionedTextDocumentIdentifier.is(candidate.textDocument)
6951 && Array.isArray(candidate.edits);
6953 TextDocumentEdit.is = is;
6954 })(TextDocumentEdit || (TextDocumentEdit = {}));
6956 (function (CreateFile) {
6957 function create(uri, options) {
6962 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
6963 result.options = options;
6967 CreateFile.create = create;
6968 function is(value) {
6969 var candidate = value;
6970 return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
6971 (candidate.options === void 0 ||
6972 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
6975 })(CreateFile || (CreateFile = {}));
6977 (function (RenameFile) {
6978 function create(oldUri, newUri, options) {
6984 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
6985 result.options = options;
6989 RenameFile.create = create;
6990 function is(value) {
6991 var candidate = value;
6992 return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
6993 (candidate.options === void 0 ||
6994 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
6997 })(RenameFile || (RenameFile = {}));
6999 (function (DeleteFile) {
7000 function create(uri, options) {
7005 if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
7006 result.options = options;
7010 DeleteFile.create = create;
7011 function is(value) {
7012 var candidate = value;
7013 return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
7014 (candidate.options === void 0 ||
7015 ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
7018 })(DeleteFile || (DeleteFile = {}));
7020 (function (WorkspaceEdit) {
7021 function is(value) {
7022 var candidate = value;
7024 (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
7025 (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
7026 if (Is.string(change.kind)) {
7027 return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
7030 return TextDocumentEdit.is(change);
7034 WorkspaceEdit.is = is;
7035 })(WorkspaceEdit || (WorkspaceEdit = {}));
7036 var TextEditChangeImpl = /** @class */ (function () {
7037 function TextEditChangeImpl(edits) {
7040 TextEditChangeImpl.prototype.insert = function (position, newText) {
7041 this.edits.push(TextEdit.insert(position, newText));
7043 TextEditChangeImpl.prototype.replace = function (range, newText) {
7044 this.edits.push(TextEdit.replace(range, newText));
7046 TextEditChangeImpl.prototype.delete = function (range) {
7047 this.edits.push(TextEdit.del(range));
7049 TextEditChangeImpl.prototype.add = function (edit) {
7050 this.edits.push(edit);
7052 TextEditChangeImpl.prototype.all = function () {
7055 TextEditChangeImpl.prototype.clear = function () {
7056 this.edits.splice(0, this.edits.length);
7058 return TextEditChangeImpl;
7061 * A workspace change helps constructing changes to a workspace.
7063 var WorkspaceChange = /** @class */ (function () {
7064 function WorkspaceChange(workspaceEdit) {
7066 this._textEditChanges = Object.create(null);
7067 if (workspaceEdit) {
7068 this._workspaceEdit = workspaceEdit;
7069 if (workspaceEdit.documentChanges) {
7070 workspaceEdit.documentChanges.forEach(function (change) {
7071 if (TextDocumentEdit.is(change)) {
7072 var textEditChange = new TextEditChangeImpl(change.edits);
7073 _this._textEditChanges[change.textDocument.uri] = textEditChange;
7077 else if (workspaceEdit.changes) {
7078 Object.keys(workspaceEdit.changes).forEach(function (key) {
7079 var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
7080 _this._textEditChanges[key] = textEditChange;
7085 Object.defineProperty(WorkspaceChange.prototype, "edit", {
7087 * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
7088 * use to be returned from a workspace edit operation like rename.
7091 if (this._workspaceEdit === undefined) {
7092 return { documentChanges: [] };
7094 return this._workspaceEdit;
7099 WorkspaceChange.prototype.getTextEditChange = function (key) {
7100 if (VersionedTextDocumentIdentifier.is(key)) {
7101 if (!this._workspaceEdit) {
7102 this._workspaceEdit = {
7106 if (!this._workspaceEdit.documentChanges) {
7107 throw new Error('Workspace edit is not configured for document changes.');
7109 var textDocument = key;
7110 var result = this._textEditChanges[textDocument.uri];
7113 var textDocumentEdit = {
7114 textDocument: textDocument,
7117 this._workspaceEdit.documentChanges.push(textDocumentEdit);
7118 result = new TextEditChangeImpl(edits);
7119 this._textEditChanges[textDocument.uri] = result;
7124 if (!this._workspaceEdit) {
7125 this._workspaceEdit = {
7126 changes: Object.create(null)
7129 if (!this._workspaceEdit.changes) {
7130 throw new Error('Workspace edit is not configured for normal text edit changes.');
7132 var result = this._textEditChanges[key];
7135 this._workspaceEdit.changes[key] = edits;
7136 result = new TextEditChangeImpl(edits);
7137 this._textEditChanges[key] = result;
7142 WorkspaceChange.prototype.createFile = function (uri, options) {
7143 this.checkDocumentChanges();
7144 this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
7146 WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
7147 this.checkDocumentChanges();
7148 this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
7150 WorkspaceChange.prototype.deleteFile = function (uri, options) {
7151 this.checkDocumentChanges();
7152 this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
7154 WorkspaceChange.prototype.checkDocumentChanges = function () {
7155 if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
7156 throw new Error('Workspace edit is not configured for document changes.');
7159 return WorkspaceChange;
7163 * The TextDocumentIdentifier namespace provides helper functions to work with
7164 * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
7166 var TextDocumentIdentifier;
7167 (function (TextDocumentIdentifier) {
7169 * Creates a new TextDocumentIdentifier literal.
7170 * @param uri The document's uri.
7172 function create(uri) {
7173 return { uri: uri };
7175 TextDocumentIdentifier.create = create;
7177 * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
7179 function is(value) {
7180 var candidate = value;
7181 return Is.defined(candidate) && Is.string(candidate.uri);
7183 TextDocumentIdentifier.is = is;
7184 })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
7186 * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
7187 * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
7189 var VersionedTextDocumentIdentifier;
7190 (function (VersionedTextDocumentIdentifier) {
7192 * Creates a new VersionedTextDocumentIdentifier literal.
7193 * @param uri The document's uri.
7194 * @param uri The document's text.
7196 function create(uri, version) {
7197 return { uri: uri, version: version };
7199 VersionedTextDocumentIdentifier.create = create;
7201 * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
7203 function is(value) {
7204 var candidate = value;
7205 return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
7207 VersionedTextDocumentIdentifier.is = is;
7208 })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
7210 * The TextDocumentItem namespace provides helper functions to work with
7211 * [TextDocumentItem](#TextDocumentItem) literals.
7213 var TextDocumentItem;
7214 (function (TextDocumentItem) {
7216 * Creates a new TextDocumentItem literal.
7217 * @param uri The document's uri.
7218 * @param languageId The document's language identifier.
7219 * @param version The document's version number.
7220 * @param text The document's text.
7222 function create(uri, languageId, version, text) {
7223 return { uri: uri, languageId: languageId, version: version, text: text };
7225 TextDocumentItem.create = create;
7227 * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
7229 function is(value) {
7230 var candidate = value;
7231 return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
7233 TextDocumentItem.is = is;
7234 })(TextDocumentItem || (TextDocumentItem = {}));
7236 * Describes the content type that a client supports in various
7237 * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
7239 * Please note that `MarkupKinds` must not start with a `$`. This kinds
7240 * are reserved for internal usage.
7243 (function (MarkupKind) {
7245 * Plain text is supported as a content format
7247 MarkupKind.PlainText = 'plaintext';
7249 * Markdown is supported as a content format
7251 MarkupKind.Markdown = 'markdown';
7252 })(MarkupKind || (MarkupKind = {}));
7253 (function (MarkupKind) {
7255 * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
7257 function is(value) {
7258 var candidate = value;
7259 return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
7262 })(MarkupKind || (MarkupKind = {}));
7264 (function (MarkupContent) {
7266 * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
7268 function is(value) {
7269 var candidate = value;
7270 return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
7272 MarkupContent.is = is;
7273 })(MarkupContent || (MarkupContent = {}));
7275 * The kind of a completion entry.
7277 var CompletionItemKind;
7278 (function (CompletionItemKind) {
7279 CompletionItemKind.Text = 1;
7280 CompletionItemKind.Method = 2;
7281 CompletionItemKind.Function = 3;
7282 CompletionItemKind.Constructor = 4;
7283 CompletionItemKind.Field = 5;
7284 CompletionItemKind.Variable = 6;
7285 CompletionItemKind.Class = 7;
7286 CompletionItemKind.Interface = 8;
7287 CompletionItemKind.Module = 9;
7288 CompletionItemKind.Property = 10;
7289 CompletionItemKind.Unit = 11;
7290 CompletionItemKind.Value = 12;
7291 CompletionItemKind.Enum = 13;
7292 CompletionItemKind.Keyword = 14;
7293 CompletionItemKind.Snippet = 15;
7294 CompletionItemKind.Color = 16;
7295 CompletionItemKind.File = 17;
7296 CompletionItemKind.Reference = 18;
7297 CompletionItemKind.Folder = 19;
7298 CompletionItemKind.EnumMember = 20;
7299 CompletionItemKind.Constant = 21;
7300 CompletionItemKind.Struct = 22;
7301 CompletionItemKind.Event = 23;
7302 CompletionItemKind.Operator = 24;
7303 CompletionItemKind.TypeParameter = 25;
7304 })(CompletionItemKind || (CompletionItemKind = {}));
7306 * Defines whether the insert text in a completion item should be interpreted as
7307 * plain text or a snippet.
7309 var InsertTextFormat;
7310 (function (InsertTextFormat) {
7312 * The primary text to be inserted is treated as a plain string.
7314 InsertTextFormat.PlainText = 1;
7316 * The primary text to be inserted is treated as a snippet.
7318 * A snippet can define tab stops and placeholders with `$1`, `$2`
7319 * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
7320 * the end of the snippet. Placeholders with equal identifiers are linked,
7321 * that is typing in one will update others too.
7323 * See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax
7325 InsertTextFormat.Snippet = 2;
7326 })(InsertTextFormat || (InsertTextFormat = {}));
7328 * Completion item tags are extra annotations that tweak the rendering of a completion
7333 var CompletionItemTag;
7334 (function (CompletionItemTag) {
7336 * Render a completion as obsolete, usually using a strike-out.
7338 CompletionItemTag.Deprecated = 1;
7339 })(CompletionItemTag || (CompletionItemTag = {}));
7341 * The InsertReplaceEdit namespace provides functions to deal with insert / replace edits.
7343 * @since 3.16.0 - Proposed state
7345 var InsertReplaceEdit;
7346 (function (InsertReplaceEdit) {
7348 * Creates a new insert / replace edit
7350 function create(newText, insert, replace) {
7351 return { newText: newText, insert: insert, replace: replace };
7353 InsertReplaceEdit.create = create;
7355 * Checks whether the given liternal conforms to the [InsertReplaceEdit](#InsertReplaceEdit) interface.
7357 function is(value) {
7358 var candidate = value;
7359 return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace);
7361 InsertReplaceEdit.is = is;
7362 })(InsertReplaceEdit || (InsertReplaceEdit = {}));
7364 * The CompletionItem namespace provides functions to deal with
7368 (function (CompletionItem) {
7370 * Create a completion item and seed it with a label.
7371 * @param label The completion item's label
7373 function create(label) {
7374 return { label: label };
7376 CompletionItem.create = create;
7377 })(CompletionItem || (CompletionItem = {}));
7379 * The CompletionList namespace provides functions to deal with
7383 (function (CompletionList) {
7385 * Creates a new completion list.
7387 * @param items The completion items.
7388 * @param isIncomplete The list is not complete.
7390 function create(items, isIncomplete) {
7391 return { items: items ? items : [], isIncomplete: !!isIncomplete };
7393 CompletionList.create = create;
7394 })(CompletionList || (CompletionList = {}));
7396 (function (MarkedString) {
7398 * Creates a marked string from plain text.
7400 * @param plainText The plain text.
7402 function fromPlainText(plainText) {
7403 return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
7405 MarkedString.fromPlainText = fromPlainText;
7407 * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
7409 function is(value) {
7410 var candidate = value;
7411 return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
7413 MarkedString.is = is;
7414 })(MarkedString || (MarkedString = {}));
7418 * Checks whether the given value conforms to the [Hover](#Hover) interface.
7420 function is(value) {
7421 var candidate = value;
7422 return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
7423 MarkedString.is(candidate.contents) ||
7424 Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
7427 })(Hover || (Hover = {}));
7429 * The ParameterInformation namespace provides helper functions to work with
7430 * [ParameterInformation](#ParameterInformation) literals.
7432 var ParameterInformation;
7433 (function (ParameterInformation) {
7435 * Creates a new parameter information literal.
7437 * @param label A label string.
7438 * @param documentation A doc string.
7440 function create(label, documentation) {
7441 return documentation ? { label: label, documentation: documentation } : { label: label };
7443 ParameterInformation.create = create;
7444 })(ParameterInformation || (ParameterInformation = {}));
7446 * The SignatureInformation namespace provides helper functions to work with
7447 * [SignatureInformation](#SignatureInformation) literals.
7449 var SignatureInformation;
7450 (function (SignatureInformation) {
7451 function create(label, documentation) {
7452 var parameters = [];
7453 for (var _i = 2; _i < arguments.length; _i++) {
7454 parameters[_i - 2] = arguments[_i];
7456 var result = { label: label };
7457 if (Is.defined(documentation)) {
7458 result.documentation = documentation;
7460 if (Is.defined(parameters)) {
7461 result.parameters = parameters;
7464 result.parameters = [];
7468 SignatureInformation.create = create;
7469 })(SignatureInformation || (SignatureInformation = {}));
7471 * A document highlight kind.
7473 var DocumentHighlightKind;
7474 (function (DocumentHighlightKind) {
7476 * A textual occurrence.
7478 DocumentHighlightKind.Text = 1;
7480 * Read-access of a symbol, like reading a variable.
7482 DocumentHighlightKind.Read = 2;
7484 * Write-access of a symbol, like writing to a variable.
7486 DocumentHighlightKind.Write = 3;
7487 })(DocumentHighlightKind || (DocumentHighlightKind = {}));
7489 * DocumentHighlight namespace to provide helper functions to work with
7490 * [DocumentHighlight](#DocumentHighlight) literals.
7492 var DocumentHighlight;
7493 (function (DocumentHighlight) {
7495 * Create a DocumentHighlight object.
7496 * @param range The range the highlight applies to.
7498 function create(range, kind) {
7499 var result = { range: range };
7500 if (Is.number(kind)) {
7505 DocumentHighlight.create = create;
7506 })(DocumentHighlight || (DocumentHighlight = {}));
7511 (function (SymbolKind) {
7512 SymbolKind.File = 1;
7513 SymbolKind.Module = 2;
7514 SymbolKind.Namespace = 3;
7515 SymbolKind.Package = 4;
7516 SymbolKind.Class = 5;
7517 SymbolKind.Method = 6;
7518 SymbolKind.Property = 7;
7519 SymbolKind.Field = 8;
7520 SymbolKind.Constructor = 9;
7521 SymbolKind.Enum = 10;
7522 SymbolKind.Interface = 11;
7523 SymbolKind.Function = 12;
7524 SymbolKind.Variable = 13;
7525 SymbolKind.Constant = 14;
7526 SymbolKind.String = 15;
7527 SymbolKind.Number = 16;
7528 SymbolKind.Boolean = 17;
7529 SymbolKind.Array = 18;
7530 SymbolKind.Object = 19;
7531 SymbolKind.Key = 20;
7532 SymbolKind.Null = 21;
7533 SymbolKind.EnumMember = 22;
7534 SymbolKind.Struct = 23;
7535 SymbolKind.Event = 24;
7536 SymbolKind.Operator = 25;
7537 SymbolKind.TypeParameter = 26;
7538 })(SymbolKind || (SymbolKind = {}));
7540 * Symbol tags are extra annotations that tweak the rendering of a symbol.
7544 (function (SymbolTag) {
7546 * Render a symbol as obsolete, usually using a strike-out.
7548 SymbolTag.Deprecated = 1;
7549 })(SymbolTag || (SymbolTag = {}));
7550 var SymbolInformation;
7551 (function (SymbolInformation) {
7553 * Creates a new symbol information literal.
7555 * @param name The name of the symbol.
7556 * @param kind The kind of the symbol.
7557 * @param range The range of the location of the symbol.
7558 * @param uri The resource of the location of symbol, defaults to the current document.
7559 * @param containerName The name of the symbol containing the symbol.
7561 function create(name, kind, range, uri, containerName) {
7565 location: { uri: uri, range: range }
7567 if (containerName) {
7568 result.containerName = containerName;
7572 SymbolInformation.create = create;
7573 })(SymbolInformation || (SymbolInformation = {}));
7575 (function (DocumentSymbol) {
7577 * Creates a new symbol information literal.
7579 * @param name The name of the symbol.
7580 * @param detail The detail of the symbol.
7581 * @param kind The kind of the symbol.
7582 * @param range The range of the symbol.
7583 * @param selectionRange The selectionRange of the symbol.
7584 * @param children Children of the symbol.
7586 function create(name, detail, kind, range, selectionRange, children) {
7592 selectionRange: selectionRange
7594 if (children !== void 0) {
7595 result.children = children;
7599 DocumentSymbol.create = create;
7601 * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
7603 function is(value) {
7604 var candidate = value;
7606 Is.string(candidate.name) && Is.number(candidate.kind) &&
7607 Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
7608 (candidate.detail === void 0 || Is.string(candidate.detail)) &&
7609 (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
7610 (candidate.children === void 0 || Array.isArray(candidate.children)) &&
7611 (candidate.tags === void 0 || Array.isArray(candidate.tags));
7613 DocumentSymbol.is = is;
7614 })(DocumentSymbol || (DocumentSymbol = {}));
7616 * A set of predefined code action kinds
7619 (function (CodeActionKind) {
7623 CodeActionKind.Empty = '';
7625 * Base kind for quickfix actions: 'quickfix'
7627 CodeActionKind.QuickFix = 'quickfix';
7629 * Base kind for refactoring actions: 'refactor'
7631 CodeActionKind.Refactor = 'refactor';
7633 * Base kind for refactoring extraction actions: 'refactor.extract'
7635 * Example extract actions:
7638 * - Extract function
7639 * - Extract variable
7640 * - Extract interface from class
7643 CodeActionKind.RefactorExtract = 'refactor.extract';
7645 * Base kind for refactoring inline actions: 'refactor.inline'
7647 * Example inline actions:
7654 CodeActionKind.RefactorInline = 'refactor.inline';
7656 * Base kind for refactoring rewrite actions: 'refactor.rewrite'
7658 * Example rewrite actions:
7660 * - Convert JavaScript function to class
7661 * - Add or remove parameter
7662 * - Encapsulate field
7663 * - Make method static
7664 * - Move method to base class
7667 CodeActionKind.RefactorRewrite = 'refactor.rewrite';
7669 * Base kind for source actions: `source`
7671 * Source code actions apply to the entire file.
7673 CodeActionKind.Source = 'source';
7675 * Base kind for an organize imports source action: `source.organizeImports`
7677 CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
7679 * Base kind for auto-fix source actions: `source.fixAll`.
7681 * Fix all actions automatically fix errors that have a clear fix that do not require user input.
7682 * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
7686 CodeActionKind.SourceFixAll = 'source.fixAll';
7687 })(CodeActionKind || (CodeActionKind = {}));
7689 * The CodeActionContext namespace provides helper functions to work with
7690 * [CodeActionContext](#CodeActionContext) literals.
7692 var CodeActionContext;
7693 (function (CodeActionContext) {
7695 * Creates a new CodeActionContext literal.
7697 function create(diagnostics, only) {
7698 var result = { diagnostics: diagnostics };
7699 if (only !== void 0 && only !== null) {
7704 CodeActionContext.create = create;
7706 * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
7708 function is(value) {
7709 var candidate = value;
7710 return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
7712 CodeActionContext.is = is;
7713 })(CodeActionContext || (CodeActionContext = {}));
7715 (function (CodeAction) {
7716 function create(title, commandOrEdit, kind) {
7717 var result = { title: title };
7718 if (Command.is(commandOrEdit)) {
7719 result.command = commandOrEdit;
7722 result.edit = commandOrEdit;
7724 if (kind !== void 0) {
7729 CodeAction.create = create;
7730 function is(value) {
7731 var candidate = value;
7732 return candidate && Is.string(candidate.title) &&
7733 (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
7734 (candidate.kind === void 0 || Is.string(candidate.kind)) &&
7735 (candidate.edit !== void 0 || candidate.command !== void 0) &&
7736 (candidate.command === void 0 || Command.is(candidate.command)) &&
7737 (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&
7738 (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
7741 })(CodeAction || (CodeAction = {}));
7743 * The CodeLens namespace provides helper functions to work with
7744 * [CodeLens](#CodeLens) literals.
7747 (function (CodeLens) {
7749 * Creates a new CodeLens literal.
7751 function create(range, data) {
7752 var result = { range: range };
7753 if (Is.defined(data)) {
7758 CodeLens.create = create;
7760 * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
7762 function is(value) {
7763 var candidate = value;
7764 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
7767 })(CodeLens || (CodeLens = {}));
7769 * The FormattingOptions namespace provides helper functions to work with
7770 * [FormattingOptions](#FormattingOptions) literals.
7772 var FormattingOptions;
7773 (function (FormattingOptions) {
7775 * Creates a new FormattingOptions literal.
7777 function create(tabSize, insertSpaces) {
7778 return { tabSize: tabSize, insertSpaces: insertSpaces };
7780 FormattingOptions.create = create;
7782 * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
7784 function is(value) {
7785 var candidate = value;
7786 return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
7788 FormattingOptions.is = is;
7789 })(FormattingOptions || (FormattingOptions = {}));
7791 * The DocumentLink namespace provides helper functions to work with
7792 * [DocumentLink](#DocumentLink) literals.
7795 (function (DocumentLink) {
7797 * Creates a new DocumentLink literal.
7799 function create(range, target, data) {
7800 return { range: range, target: target, data: data };
7802 DocumentLink.create = create;
7804 * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
7806 function is(value) {
7807 var candidate = value;
7808 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
7810 DocumentLink.is = is;
7811 })(DocumentLink || (DocumentLink = {}));
7813 * The SelectionRange namespace provides helper function to work with
7814 * SelectionRange literals.
7817 (function (SelectionRange) {
7819 * Creates a new SelectionRange
7820 * @param range the range.
7821 * @param parent an optional parent.
7823 function create(range, parent) {
7824 return { range: range, parent: parent };
7826 SelectionRange.create = create;
7827 function is(value) {
7828 var candidate = value;
7829 return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
7831 SelectionRange.is = is;
7832 })(SelectionRange || (SelectionRange = {}));
7833 var EOL = ['\n', '\r\n', '\r'];
7835 * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
7838 (function (TextDocument) {
7840 * Creates a new ITextDocument literal from the given uri and content.
7841 * @param uri The document's uri.
7842 * @param languageId The document's language Id.
7843 * @param content The document's content.
7845 function create(uri, languageId, version, content) {
7846 return new FullTextDocument(uri, languageId, version, content);
7848 TextDocument.create = create;
7850 * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
7852 function is(value) {
7853 var candidate = value;
7854 return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
7855 && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
7857 TextDocument.is = is;
7858 function applyEdits(document, edits) {
7859 var text = document.getText();
7860 var sortedEdits = mergeSort(edits, function (a, b) {
7861 var diff = a.range.start.line - b.range.start.line;
7863 return a.range.start.character - b.range.start.character;
7867 var lastModifiedOffset = text.length;
7868 for (var i = sortedEdits.length - 1; i >= 0; i--) {
7869 var e = sortedEdits[i];
7870 var startOffset = document.offsetAt(e.range.start);
7871 var endOffset = document.offsetAt(e.range.end);
7872 if (endOffset <= lastModifiedOffset) {
7873 text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
7876 throw new Error('Overlapping edit');
7878 lastModifiedOffset = startOffset;
7882 TextDocument.applyEdits = applyEdits;
7883 function mergeSort(data, compare) {
7884 if (data.length <= 1) {
7888 var p = (data.length / 2) | 0;
7889 var left = data.slice(0, p);
7890 var right = data.slice(p);
7891 mergeSort(left, compare);
7892 mergeSort(right, compare);
7896 while (leftIdx < left.length && rightIdx < right.length) {
7897 var ret = compare(left[leftIdx], right[rightIdx]);
7899 // smaller_equal -> take left to preserve order
7900 data[i++] = left[leftIdx++];
7903 // greater -> take right
7904 data[i++] = right[rightIdx++];
7907 while (leftIdx < left.length) {
7908 data[i++] = left[leftIdx++];
7910 while (rightIdx < right.length) {
7911 data[i++] = right[rightIdx++];
7915 })(TextDocument || (TextDocument = {}));
7916 var FullTextDocument = /** @class */ (function () {
7917 function FullTextDocument(uri, languageId, version, content) {
7919 this._languageId = languageId;
7920 this._version = version;
7921 this._content = content;
7922 this._lineOffsets = undefined;
7924 Object.defineProperty(FullTextDocument.prototype, "uri", {
7931 Object.defineProperty(FullTextDocument.prototype, "languageId", {
7933 return this._languageId;
7938 Object.defineProperty(FullTextDocument.prototype, "version", {
7940 return this._version;
7945 FullTextDocument.prototype.getText = function (range) {
7947 var start = this.offsetAt(range.start);
7948 var end = this.offsetAt(range.end);
7949 return this._content.substring(start, end);
7951 return this._content;
7953 FullTextDocument.prototype.update = function (event, version) {
7954 this._content = event.text;
7955 this._version = version;
7956 this._lineOffsets = undefined;
7958 FullTextDocument.prototype.getLineOffsets = function () {
7959 if (this._lineOffsets === undefined) {
7960 var lineOffsets = [];
7961 var text = this._content;
7962 var isLineStart = true;
7963 for (var i = 0; i < text.length; i++) {
7965 lineOffsets.push(i);
7966 isLineStart = false;
7968 var ch = text.charAt(i);
7969 isLineStart = (ch === '\r' || ch === '\n');
7970 if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
7974 if (isLineStart && text.length > 0) {
7975 lineOffsets.push(text.length);
7977 this._lineOffsets = lineOffsets;
7979 return this._lineOffsets;
7981 FullTextDocument.prototype.positionAt = function (offset) {
7982 offset = Math.max(Math.min(offset, this._content.length), 0);
7983 var lineOffsets = this.getLineOffsets();
7984 var low = 0, high = lineOffsets.length;
7986 return Position.create(0, offset);
7988 while (low < high) {
7989 var mid = Math.floor((low + high) / 2);
7990 if (lineOffsets[mid] > offset) {
7997 // low is the least x for which the line offset is larger than the current offset
7998 // or array.length if no line offset is larger than the current offset
8000 return Position.create(line, offset - lineOffsets[line]);
8002 FullTextDocument.prototype.offsetAt = function (position) {
8003 var lineOffsets = this.getLineOffsets();
8004 if (position.line >= lineOffsets.length) {
8005 return this._content.length;
8007 else if (position.line < 0) {
8010 var lineOffset = lineOffsets[position.line];
8011 var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
8012 return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
8014 Object.defineProperty(FullTextDocument.prototype, "lineCount", {
8016 return this.getLineOffsets().length;
8021 return FullTextDocument;
8025 var toString = Object.prototype.toString;
8026 function defined(value) {
8027 return typeof value !== 'undefined';
8029 Is.defined = defined;
8030 function undefined(value) {
8031 return typeof value === 'undefined';
8033 Is.undefined = undefined;
8034 function boolean(value) {
8035 return value === true || value === false;
8037 Is.boolean = boolean;
8038 function string(value) {
8039 return toString.call(value) === '[object String]';
8042 function number(value) {
8043 return toString.call(value) === '[object Number]';
8046 function func(value) {
8047 return toString.call(value) === '[object Function]';
8050 function objectLiteral(value) {
8051 // Strictly speaking class instances pass this check as well. Since the LSP
8052 // doesn't use classes we ignore this for now. If we do we need to add something
8053 // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
8054 return value !== null && typeof value === 'object';
8056 Is.objectLiteral = objectLiteral;
8057 function typedArray(value, check) {
8058 return Array.isArray(value) && value.every(check);
8060 Is.typedArray = typedArray;
8061 })(Is || (Is = {}));
8066 /***/ (function(module, exports, __webpack_require__) {
8070 /* --------------------------------------------------------------------------------------------
8071 * Copyright (c) Microsoft Corporation. All rights reserved.
8072 * Licensed under the MIT License. See License.txt in the project root for license information.
8073 * ------------------------------------------------------------------------------------------ */
8074 Object.defineProperty(exports, "__esModule", { value: true });
8075 const vscode_jsonrpc_1 = __webpack_require__(46);
8076 class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
8077 constructor(method) {
8081 exports.ProtocolRequestType0 = ProtocolRequestType0;
8082 class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
8083 constructor(method) {
8087 exports.ProtocolRequestType = ProtocolRequestType;
8088 class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
8089 constructor(method) {
8093 exports.ProtocolNotificationType = ProtocolNotificationType;
8094 class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
8095 constructor(method) {
8099 exports.ProtocolNotificationType0 = ProtocolNotificationType0;
8100 //# sourceMappingURL=messages.js.map
8104 /***/ (function(module, exports, __webpack_require__) {
8108 /* --------------------------------------------------------------------------------------------
8109 * Copyright (c) Microsoft Corporation. All rights reserved.
8110 * Licensed under the MIT License. See License.txt in the project root for license information.
8111 * ------------------------------------------------------------------------------------------ */
8112 Object.defineProperty(exports, "__esModule", { value: true });
8113 const Is = __webpack_require__(64);
8114 const vscode_jsonrpc_1 = __webpack_require__(46);
8115 const messages_1 = __webpack_require__(62);
8116 const protocol_implementation_1 = __webpack_require__(65);
8117 exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
8118 const protocol_typeDefinition_1 = __webpack_require__(66);
8119 exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
8120 const protocol_workspaceFolders_1 = __webpack_require__(67);
8121 exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
8122 exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
8123 const protocol_configuration_1 = __webpack_require__(68);
8124 exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
8125 const protocol_colorProvider_1 = __webpack_require__(69);
8126 exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
8127 exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
8128 const protocol_foldingRange_1 = __webpack_require__(70);
8129 exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
8130 const protocol_declaration_1 = __webpack_require__(71);
8131 exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
8132 const protocol_selectionRange_1 = __webpack_require__(72);
8133 exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;
8134 const protocol_progress_1 = __webpack_require__(73);
8135 exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;
8136 exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;
8137 exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;
8138 const protocol_callHierarchy_1 = __webpack_require__(74);
8139 exports.CallHierarchyIncomingCallsRequest = protocol_callHierarchy_1.CallHierarchyIncomingCallsRequest;
8140 exports.CallHierarchyOutgoingCallsRequest = protocol_callHierarchy_1.CallHierarchyOutgoingCallsRequest;
8141 exports.CallHierarchyPrepareRequest = protocol_callHierarchy_1.CallHierarchyPrepareRequest;
8142 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
8143 let __noDynamicImport;
8145 * The DocumentFilter namespace provides helper functions to work with
8146 * [DocumentFilter](#DocumentFilter) literals.
8149 (function (DocumentFilter) {
8150 function is(value) {
8151 const candidate = value;
8152 return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
8154 DocumentFilter.is = is;
8155 })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));
8157 * The DocumentSelector namespace provides helper functions to work with
8158 * [DocumentSelector](#DocumentSelector)s.
8160 var DocumentSelector;
8161 (function (DocumentSelector) {
8162 function is(value) {
8163 if (!Array.isArray(value)) {
8166 for (let elem of value) {
8167 if (!Is.string(elem) && !DocumentFilter.is(elem)) {
8173 DocumentSelector.is = is;
8174 })(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));
8176 * The `client/registerCapability` request is sent from the server to the client to register a new capability
8177 * handler on the client side.
8179 var RegistrationRequest;
8180 (function (RegistrationRequest) {
8181 RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability');
8182 })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
8184 * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
8185 * handler on the client side.
8187 var UnregistrationRequest;
8188 (function (UnregistrationRequest) {
8189 UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability');
8190 })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
8191 var ResourceOperationKind;
8192 (function (ResourceOperationKind) {
8194 * Supports creating new files and folders.
8196 ResourceOperationKind.Create = 'create';
8198 * Supports renaming existing files and folders.
8200 ResourceOperationKind.Rename = 'rename';
8202 * Supports deleting existing files and folders.
8204 ResourceOperationKind.Delete = 'delete';
8205 })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
8206 var FailureHandlingKind;
8207 (function (FailureHandlingKind) {
8209 * Applying the workspace change is simply aborted if one of the changes provided
8210 * fails. All operations executed before the failing operation stay executed.
8212 FailureHandlingKind.Abort = 'abort';
8214 * All operations are executed transactional. That means they either all
8215 * succeed or no changes at all are applied to the workspace.
8217 FailureHandlingKind.Transactional = 'transactional';
8219 * If the workspace edit contains only textual file changes they are executed transactional.
8220 * If resource changes (create, rename or delete file) are part of the change the failure
8221 * handling startegy is abort.
8223 FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
8225 * The client tries to undo the operations already executed. But there is no
8226 * guarantee that this is succeeding.
8228 FailureHandlingKind.Undo = 'undo';
8229 })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
8231 * The StaticRegistrationOptions namespace provides helper functions to work with
8232 * [StaticRegistrationOptions](#StaticRegistrationOptions) literals.
8234 var StaticRegistrationOptions;
8235 (function (StaticRegistrationOptions) {
8236 function hasId(value) {
8237 const candidate = value;
8238 return candidate && Is.string(candidate.id) && candidate.id.length > 0;
8240 StaticRegistrationOptions.hasId = hasId;
8241 })(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));
8243 * The TextDocumentRegistrationOptions namespace provides helper functions to work with
8244 * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals.
8246 var TextDocumentRegistrationOptions;
8247 (function (TextDocumentRegistrationOptions) {
8248 function is(value) {
8249 const candidate = value;
8250 return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
8252 TextDocumentRegistrationOptions.is = is;
8253 })(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));
8255 * The WorkDoneProgressOptions namespace provides helper functions to work with
8256 * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals.
8258 var WorkDoneProgressOptions;
8259 (function (WorkDoneProgressOptions) {
8260 function is(value) {
8261 const candidate = value;
8262 return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));
8264 WorkDoneProgressOptions.is = is;
8265 function hasWorkDoneProgress(value) {
8266 const candidate = value;
8267 return candidate && Is.boolean(candidate.workDoneProgress);
8269 WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;
8270 })(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));
8272 * The initialize request is sent from the client to the server.
8273 * It is sent once as the request after starting up the server.
8274 * The requests parameter is of type [InitializeParams](#InitializeParams)
8275 * the response if of type [InitializeResult](#InitializeResult) of a Thenable that
8278 var InitializeRequest;
8279 (function (InitializeRequest) {
8280 InitializeRequest.type = new messages_1.ProtocolRequestType('initialize');
8281 })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
8283 * Known error codes for an `InitializeError`;
8285 var InitializeError;
8286 (function (InitializeError) {
8288 * If the protocol version provided by the client can't be handled by the server.
8289 * @deprecated This initialize error got replaced by client capabilities. There is
8290 * no version handshake in version 3.0x
8292 InitializeError.unknownProtocolVersion = 1;
8293 })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));
8295 * The intialized notification is sent from the client to the
8296 * server after the client is fully initialized and the server
8297 * is allowed to send requests from the server to the client.
8299 var InitializedNotification;
8300 (function (InitializedNotification) {
8301 InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized');
8302 })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
8303 //---- Shutdown Method ----
8305 * A shutdown request is sent from the client to the server.
8306 * It is sent once when the client decides to shutdown the
8307 * server. The only notification that is sent after a shutdown request
8308 * is the exit event.
8310 var ShutdownRequest;
8311 (function (ShutdownRequest) {
8312 ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown');
8313 })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
8314 //---- Exit Notification ----
8316 * The exit event is sent from the client to the server to
8317 * ask the server to exit its process.
8319 var ExitNotification;
8320 (function (ExitNotification) {
8321 ExitNotification.type = new messages_1.ProtocolNotificationType0('exit');
8322 })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
8324 * The configuration change notification is sent from the client to the server
8325 * when the client's configuration has changed. The notification contains
8326 * the changed configuration as defined by the language client.
8328 var DidChangeConfigurationNotification;
8329 (function (DidChangeConfigurationNotification) {
8330 DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration');
8331 })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
8332 //---- Message show and log notifications ----
8337 (function (MessageType) {
8341 MessageType.Error = 1;
8343 * A warning message.
8345 MessageType.Warning = 2;
8347 * An information message.
8349 MessageType.Info = 3;
8353 MessageType.Log = 4;
8354 })(MessageType = exports.MessageType || (exports.MessageType = {}));
8356 * The show message notification is sent from a server to a client to ask
8357 * the client to display a particular message in the user interface.
8359 var ShowMessageNotification;
8360 (function (ShowMessageNotification) {
8361 ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage');
8362 })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
8364 * The show message request is sent from the server to the client to show a message
8365 * and a set of options actions to the user.
8367 var ShowMessageRequest;
8368 (function (ShowMessageRequest) {
8369 ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest');
8370 })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
8372 * The log message notification is sent from the server to the client to ask
8373 * the client to log a particular message.
8375 var LogMessageNotification;
8376 (function (LogMessageNotification) {
8377 LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage');
8378 })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
8379 //---- Telemetry notification
8381 * The telemetry event notification is sent from the server to the client to ask
8382 * the client to log telemetry data.
8384 var TelemetryEventNotification;
8385 (function (TelemetryEventNotification) {
8386 TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event');
8387 })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
8389 * Defines how the host (editor) should sync
8390 * document changes to the language server.
8392 var TextDocumentSyncKind;
8393 (function (TextDocumentSyncKind) {
8395 * Documents should not be synced at all.
8397 TextDocumentSyncKind.None = 0;
8399 * Documents are synced by always sending the full content
8402 TextDocumentSyncKind.Full = 1;
8404 * Documents are synced by sending the full content on open.
8405 * After that only incremental updates to the document are
8408 TextDocumentSyncKind.Incremental = 2;
8409 })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
8411 * The document open notification is sent from the client to the server to signal
8412 * newly opened text documents. The document's truth is now managed by the client
8413 * and the server must not try to read the document's truth using the document's
8414 * uri. Open in this sense means it is managed by the client. It doesn't necessarily
8415 * mean that its content is presented in an editor. An open notification must not
8416 * be sent more than once without a corresponding close notification send before.
8417 * This means open and close notification must be balanced and the max open count
8420 var DidOpenTextDocumentNotification;
8421 (function (DidOpenTextDocumentNotification) {
8422 DidOpenTextDocumentNotification.method = 'textDocument/didOpen';
8423 DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);
8424 })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
8426 * The document change notification is sent from the client to the server to signal
8427 * changes to a text document.
8429 var DidChangeTextDocumentNotification;
8430 (function (DidChangeTextDocumentNotification) {
8431 DidChangeTextDocumentNotification.method = 'textDocument/didChange';
8432 DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);
8433 })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
8435 * The document close notification is sent from the client to the server when
8436 * the document got closed in the client. The document's truth now exists where
8437 * the document's uri points to (e.g. if the document's uri is a file uri the
8438 * truth now exists on disk). As with the open notification the close notification
8439 * is about managing the document's content. Receiving a close notification
8440 * doesn't mean that the document was open in an editor before. A close
8441 * notification requires a previous open notification to be sent.
8443 var DidCloseTextDocumentNotification;
8444 (function (DidCloseTextDocumentNotification) {
8445 DidCloseTextDocumentNotification.method = 'textDocument/didClose';
8446 DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);
8447 })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
8449 * The document save notification is sent from the client to the server when
8450 * the document got saved in the client.
8452 var DidSaveTextDocumentNotification;
8453 (function (DidSaveTextDocumentNotification) {
8454 DidSaveTextDocumentNotification.method = 'textDocument/didSave';
8455 DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);
8456 })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
8458 * Represents reasons why a text document is saved.
8460 var TextDocumentSaveReason;
8461 (function (TextDocumentSaveReason) {
8463 * Manually triggered, e.g. by the user pressing save, by starting debugging,
8464 * or by an API call.
8466 TextDocumentSaveReason.Manual = 1;
8468 * Automatic after a delay.
8470 TextDocumentSaveReason.AfterDelay = 2;
8472 * When the editor lost focus.
8474 TextDocumentSaveReason.FocusOut = 3;
8475 })(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));
8477 * A document will save notification is sent from the client to the server before
8478 * the document is actually saved.
8480 var WillSaveTextDocumentNotification;
8481 (function (WillSaveTextDocumentNotification) {
8482 WillSaveTextDocumentNotification.method = 'textDocument/willSave';
8483 WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);
8484 })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
8486 * A document will save request is sent from the client to the server before
8487 * the document is actually saved. The request can return an array of TextEdits
8488 * which will be applied to the text document before it is saved. Please note that
8489 * clients might drop results if computing the text edits took too long or if a
8490 * server constantly fails on this request. This is done to keep the save fast and
8493 var WillSaveTextDocumentWaitUntilRequest;
8494 (function (WillSaveTextDocumentWaitUntilRequest) {
8495 WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';
8496 WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);
8497 })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
8499 * The watched files notification is sent from the client to the server when
8500 * the client detects changes to file watched by the language client.
8502 var DidChangeWatchedFilesNotification;
8503 (function (DidChangeWatchedFilesNotification) {
8504 DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles');
8505 })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
8507 * The file event type
8510 (function (FileChangeType) {
8512 * The file got created.
8514 FileChangeType.Created = 1;
8516 * The file got changed.
8518 FileChangeType.Changed = 2;
8520 * The file got deleted.
8522 FileChangeType.Deleted = 3;
8523 })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
8525 (function (WatchKind) {
8527 * Interested in create events.
8529 WatchKind.Create = 1;
8531 * Interested in change events
8533 WatchKind.Change = 2;
8535 * Interested in delete events
8537 WatchKind.Delete = 4;
8538 })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
8540 * Diagnostics notification are sent from the server to the client to signal
8541 * results of validation runs.
8543 var PublishDiagnosticsNotification;
8544 (function (PublishDiagnosticsNotification) {
8545 PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics');
8546 })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
8548 * How a completion was triggered
8550 var CompletionTriggerKind;
8551 (function (CompletionTriggerKind) {
8553 * Completion was triggered by typing an identifier (24x7 code
8554 * complete), manual invocation (e.g Ctrl+Space) or via API.
8556 CompletionTriggerKind.Invoked = 1;
8558 * Completion was triggered by a trigger character specified by
8559 * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
8561 CompletionTriggerKind.TriggerCharacter = 2;
8563 * Completion was re-triggered as current completion list is incomplete
8565 CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
8566 })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
8568 * Request to request completion at a given text document position. The request's
8569 * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response
8570 * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)
8571 * or a Thenable that resolves to such.
8573 * The request can delay the computation of the [`detail`](#CompletionItem.detail)
8574 * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`
8575 * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
8576 * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
8578 var CompletionRequest;
8579 (function (CompletionRequest) {
8580 CompletionRequest.method = 'textDocument/completion';
8581 CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);
8582 /** @deprecated Use CompletionRequest.type */
8583 CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
8584 })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
8586 * Request to resolve additional information for a given completion item.The request's
8587 * parameter is of type [CompletionItem](#CompletionItem) the response
8588 * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.
8590 var CompletionResolveRequest;
8591 (function (CompletionResolveRequest) {
8592 CompletionResolveRequest.method = 'completionItem/resolve';
8593 CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);
8594 })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
8596 * Request to request hover information at a given text document position. The request's
8597 * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of
8598 * type [Hover](#Hover) or a Thenable that resolves to such.
8601 (function (HoverRequest) {
8602 HoverRequest.method = 'textDocument/hover';
8603 HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);
8604 })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
8606 * How a signature help was triggered.
8610 var SignatureHelpTriggerKind;
8611 (function (SignatureHelpTriggerKind) {
8613 * Signature help was invoked manually by the user or by a command.
8615 SignatureHelpTriggerKind.Invoked = 1;
8617 * Signature help was triggered by a trigger character.
8619 SignatureHelpTriggerKind.TriggerCharacter = 2;
8621 * Signature help was triggered by the cursor moving or by the document content changing.
8623 SignatureHelpTriggerKind.ContentChange = 3;
8624 })(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));
8625 var SignatureHelpRequest;
8626 (function (SignatureHelpRequest) {
8627 SignatureHelpRequest.method = 'textDocument/signatureHelp';
8628 SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);
8629 })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
8631 * A request to resolve the definition location of a symbol at a given text
8632 * document position. The request's parameter is of type [TextDocumentPosition]
8633 * (#TextDocumentPosition) the response is of either type [Definition](#Definition)
8634 * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves
8637 var DefinitionRequest;
8638 (function (DefinitionRequest) {
8639 DefinitionRequest.method = 'textDocument/definition';
8640 DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);
8641 /** @deprecated Use DefinitionRequest.type */
8642 DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
8643 })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
8645 * A request to resolve project-wide references for the symbol denoted
8646 * by the given text document position. The request's parameter is of
8647 * type [ReferenceParams](#ReferenceParams) the response is of type
8648 * [Location[]](#Location) or a Thenable that resolves to such.
8650 var ReferencesRequest;
8651 (function (ReferencesRequest) {
8652 ReferencesRequest.method = 'textDocument/references';
8653 ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);
8654 /** @deprecated Use ReferencesRequest.type */
8655 ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType();
8656 })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
8658 * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given
8659 * text document position. The request's parameter is of type [TextDocumentPosition]
8660 * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
8661 * (#DocumentHighlight) or a Thenable that resolves to such.
8663 var DocumentHighlightRequest;
8664 (function (DocumentHighlightRequest) {
8665 DocumentHighlightRequest.method = 'textDocument/documentHighlight';
8666 DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);
8667 /** @deprecated Use DocumentHighlightRequest.type */
8668 DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType();
8669 })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
8671 * A request to list all symbols found in a given text document. The request's
8672 * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the
8673 * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable
8674 * that resolves to such.
8676 var DocumentSymbolRequest;
8677 (function (DocumentSymbolRequest) {
8678 DocumentSymbolRequest.method = 'textDocument/documentSymbol';
8679 DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);
8680 /** @deprecated Use DocumentSymbolRequest.type */
8681 DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
8682 })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
8684 * A request to provide commands for the given text document and range.
8686 var CodeActionRequest;
8687 (function (CodeActionRequest) {
8688 CodeActionRequest.method = 'textDocument/codeAction';
8689 CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);
8690 /** @deprecated Use CodeActionRequest.type */
8691 CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
8692 })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
8694 * A request to list project-wide symbols matching the query string given
8695 * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is
8696 * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that
8699 var WorkspaceSymbolRequest;
8700 (function (WorkspaceSymbolRequest) {
8701 WorkspaceSymbolRequest.method = 'workspace/symbol';
8702 WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);
8703 /** @deprecated Use WorkspaceSymbolRequest.type */
8704 WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
8705 })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
8707 * A request to provide code lens for the given text document.
8709 var CodeLensRequest;
8710 (function (CodeLensRequest) {
8711 CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens');
8712 /** @deprecated Use CodeLensRequest.type */
8713 CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType();
8714 })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
8716 * A request to resolve a command for a given code lens.
8718 var CodeLensResolveRequest;
8719 (function (CodeLensResolveRequest) {
8720 CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve');
8721 })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
8723 * A request to provide document links
8725 var DocumentLinkRequest;
8726 (function (DocumentLinkRequest) {
8727 DocumentLinkRequest.method = 'textDocument/documentLink';
8728 DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);
8729 /** @deprecated Use DocumentLinkRequest.type */
8730 DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType();
8731 })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
8733 * Request to resolve additional information for a given document link. The request's
8734 * parameter is of type [DocumentLink](#DocumentLink) the response
8735 * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.
8737 var DocumentLinkResolveRequest;
8738 (function (DocumentLinkResolveRequest) {
8739 DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve');
8740 })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
8742 * A request to to format a whole document.
8744 var DocumentFormattingRequest;
8745 (function (DocumentFormattingRequest) {
8746 DocumentFormattingRequest.method = 'textDocument/formatting';
8747 DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);
8748 })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
8750 * A request to to format a range in a document.
8752 var DocumentRangeFormattingRequest;
8753 (function (DocumentRangeFormattingRequest) {
8754 DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';
8755 DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);
8756 })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
8758 * A request to format a document on type.
8760 var DocumentOnTypeFormattingRequest;
8761 (function (DocumentOnTypeFormattingRequest) {
8762 DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';
8763 DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);
8764 })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
8766 * A request to rename a symbol.
8769 (function (RenameRequest) {
8770 RenameRequest.method = 'textDocument/rename';
8771 RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);
8772 })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
8774 * A request to test and perform the setup necessary for a rename.
8776 var PrepareRenameRequest;
8777 (function (PrepareRenameRequest) {
8778 PrepareRenameRequest.method = 'textDocument/prepareRename';
8779 PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);
8780 })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
8782 * A request send from the client to the server to execute a command. The request might return
8783 * a workspace edit which the client will apply to the workspace.
8785 var ExecuteCommandRequest;
8786 (function (ExecuteCommandRequest) {
8787 ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand');
8788 })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
8790 * A request sent from the server to the client to modified certain resources.
8792 var ApplyWorkspaceEditRequest;
8793 (function (ApplyWorkspaceEditRequest) {
8794 ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');
8795 })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
8796 //# sourceMappingURL=protocol.js.map
8800 /***/ (function(module, exports, __webpack_require__) {
8803 /* --------------------------------------------------------------------------------------------
8804 * Copyright (c) Microsoft Corporation. All rights reserved.
8805 * Licensed under the MIT License. See License.txt in the project root for license information.
8806 * ------------------------------------------------------------------------------------------ */
8808 Object.defineProperty(exports, "__esModule", { value: true });
8809 function boolean(value) {
8810 return value === true || value === false;
8812 exports.boolean = boolean;
8813 function string(value) {
8814 return typeof value === 'string' || value instanceof String;
8816 exports.string = string;
8817 function number(value) {
8818 return typeof value === 'number' || value instanceof Number;
8820 exports.number = number;
8821 function error(value) {
8822 return value instanceof Error;
8824 exports.error = error;
8825 function func(value) {
8826 return typeof value === 'function';
8828 exports.func = func;
8829 function array(value) {
8830 return Array.isArray(value);
8832 exports.array = array;
8833 function stringArray(value) {
8834 return array(value) && value.every(elem => string(elem));
8836 exports.stringArray = stringArray;
8837 function typedArray(value, check) {
8838 return Array.isArray(value) && value.every(check);
8840 exports.typedArray = typedArray;
8841 function objectLiteral(value) {
8842 // Strictly speaking class instances pass this check as well. Since the LSP
8843 // doesn't use classes we ignore this for now. If we do we need to add something
8844 // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
8845 return value !== null && typeof value === 'object';
8847 exports.objectLiteral = objectLiteral;
8848 //# sourceMappingURL=is.js.map
8852 /***/ (function(module, exports, __webpack_require__) {
8856 /* --------------------------------------------------------------------------------------------
8857 * Copyright (c) Microsoft Corporation. All rights reserved.
8858 * Licensed under the MIT License. See License.txt in the project root for license information.
8859 * ------------------------------------------------------------------------------------------ */
8860 Object.defineProperty(exports, "__esModule", { value: true });
8861 const vscode_jsonrpc_1 = __webpack_require__(46);
8862 const messages_1 = __webpack_require__(62);
8863 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
8864 let __noDynamicImport;
8866 * A request to resolve the implementation locations of a symbol at a given text
8867 * document position. The request's parameter is of type [TextDocumentPositioParams]
8868 * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
8869 * Thenable that resolves to such.
8871 var ImplementationRequest;
8872 (function (ImplementationRequest) {
8873 ImplementationRequest.method = 'textDocument/implementation';
8874 ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);
8875 /** @deprecated Use ImplementationRequest.type */
8876 ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
8877 })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
8878 //# sourceMappingURL=protocol.implementation.js.map
8882 /***/ (function(module, exports, __webpack_require__) {
8886 /* --------------------------------------------------------------------------------------------
8887 * Copyright (c) Microsoft Corporation. All rights reserved.
8888 * Licensed under the MIT License. See License.txt in the project root for license information.
8889 * ------------------------------------------------------------------------------------------ */
8890 Object.defineProperty(exports, "__esModule", { value: true });
8891 const vscode_jsonrpc_1 = __webpack_require__(46);
8892 const messages_1 = __webpack_require__(62);
8893 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
8894 let __noDynamicImport;
8896 * A request to resolve the type definition locations of a symbol at a given text
8897 * document position. The request's parameter is of type [TextDocumentPositioParams]
8898 * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
8899 * Thenable that resolves to such.
8901 var TypeDefinitionRequest;
8902 (function (TypeDefinitionRequest) {
8903 TypeDefinitionRequest.method = 'textDocument/typeDefinition';
8904 TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);
8905 /** @deprecated Use TypeDefinitionRequest.type */
8906 TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
8907 })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
8908 //# sourceMappingURL=protocol.typeDefinition.js.map
8912 /***/ (function(module, exports, __webpack_require__) {
8916 /* --------------------------------------------------------------------------------------------
8917 * Copyright (c) Microsoft Corporation. All rights reserved.
8918 * Licensed under the MIT License. See License.txt in the project root for license information.
8919 * ------------------------------------------------------------------------------------------ */
8920 Object.defineProperty(exports, "__esModule", { value: true });
8921 const messages_1 = __webpack_require__(62);
8923 * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
8925 var WorkspaceFoldersRequest;
8926 (function (WorkspaceFoldersRequest) {
8927 WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders');
8928 })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
8930 * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
8931 * folder configuration changes.
8933 var DidChangeWorkspaceFoldersNotification;
8934 (function (DidChangeWorkspaceFoldersNotification) {
8935 DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders');
8936 })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
8937 //# sourceMappingURL=protocol.workspaceFolders.js.map
8941 /***/ (function(module, exports, __webpack_require__) {
8945 /* --------------------------------------------------------------------------------------------
8946 * Copyright (c) Microsoft Corporation. All rights reserved.
8947 * Licensed under the MIT License. See License.txt in the project root for license information.
8948 * ------------------------------------------------------------------------------------------ */
8949 Object.defineProperty(exports, "__esModule", { value: true });
8950 const messages_1 = __webpack_require__(62);
8952 * The 'workspace/configuration' request is sent from the server to the client to fetch a certain
8953 * configuration setting.
8955 * This pull model replaces the old push model were the client signaled configuration change via an
8956 * event. If the server still needs to react to configuration changes (since the server caches the
8957 * result of `workspace/configuration` requests) the server should register for an empty configuration
8958 * change event and empty the cache if such an event is received.
8960 var ConfigurationRequest;
8961 (function (ConfigurationRequest) {
8962 ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration');
8963 })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
8964 //# sourceMappingURL=protocol.configuration.js.map
8968 /***/ (function(module, exports, __webpack_require__) {
8972 /* --------------------------------------------------------------------------------------------
8973 * Copyright (c) Microsoft Corporation. All rights reserved.
8974 * Licensed under the MIT License. See License.txt in the project root for license information.
8975 * ------------------------------------------------------------------------------------------ */
8976 Object.defineProperty(exports, "__esModule", { value: true });
8977 const vscode_jsonrpc_1 = __webpack_require__(46);
8978 const messages_1 = __webpack_require__(62);
8980 * A request to list all color symbols found in a given text document. The request's
8981 * parameter is of type [DocumentColorParams](#DocumentColorParams) the
8982 * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
8983 * that resolves to such.
8985 var DocumentColorRequest;
8986 (function (DocumentColorRequest) {
8987 DocumentColorRequest.method = 'textDocument/documentColor';
8988 DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);
8989 /** @deprecated Use DocumentColorRequest.type */
8990 DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType();
8991 })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
8993 * A request to list all presentation for a color. The request's
8994 * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the
8995 * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
8996 * that resolves to such.
8998 var ColorPresentationRequest;
8999 (function (ColorPresentationRequest) {
9000 ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation');
9001 })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
9002 //# sourceMappingURL=protocol.colorProvider.js.map
9006 /***/ (function(module, exports, __webpack_require__) {
9010 /*---------------------------------------------------------------------------------------------
9011 * Copyright (c) Microsoft Corporation. All rights reserved.
9012 * Licensed under the MIT License. See License.txt in the project root for license information.
9013 *--------------------------------------------------------------------------------------------*/
9014 Object.defineProperty(exports, "__esModule", { value: true });
9015 const vscode_jsonrpc_1 = __webpack_require__(46);
9016 const messages_1 = __webpack_require__(62);
9018 * Enum of known range kinds
9020 var FoldingRangeKind;
9021 (function (FoldingRangeKind) {
9023 * Folding range for a comment
9025 FoldingRangeKind["Comment"] = "comment";
9027 * Folding range for a imports or includes
9029 FoldingRangeKind["Imports"] = "imports";
9031 * Folding range for a region (e.g. `#region`)
9033 FoldingRangeKind["Region"] = "region";
9034 })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
9036 * A request to provide folding ranges in a document. The request's
9037 * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the
9038 * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable
9039 * that resolves to such.
9041 var FoldingRangeRequest;
9042 (function (FoldingRangeRequest) {
9043 FoldingRangeRequest.method = 'textDocument/foldingRange';
9044 FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);
9045 /** @deprecated Use FoldingRangeRequest.type */
9046 FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
9047 })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
9048 //# sourceMappingURL=protocol.foldingRange.js.map
9052 /***/ (function(module, exports, __webpack_require__) {
9056 /* --------------------------------------------------------------------------------------------
9057 * Copyright (c) Microsoft Corporation. All rights reserved.
9058 * Licensed under the MIT License. See License.txt in the project root for license information.
9059 * ------------------------------------------------------------------------------------------ */
9060 Object.defineProperty(exports, "__esModule", { value: true });
9061 const vscode_jsonrpc_1 = __webpack_require__(46);
9062 const messages_1 = __webpack_require__(62);
9063 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
9064 let __noDynamicImport;
9066 * A request to resolve the type definition locations of a symbol at a given text
9067 * document position. The request's parameter is of type [TextDocumentPositioParams]
9068 * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)
9069 * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves
9072 var DeclarationRequest;
9073 (function (DeclarationRequest) {
9074 DeclarationRequest.method = 'textDocument/declaration';
9075 DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);
9076 /** @deprecated Use DeclarationRequest.type */
9077 DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
9078 })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
9079 //# sourceMappingURL=protocol.declaration.js.map
9083 /***/ (function(module, exports, __webpack_require__) {
9087 /*---------------------------------------------------------------------------------------------
9088 * Copyright (c) Microsoft Corporation. All rights reserved.
9089 * Licensed under the MIT License. See License.txt in the project root for license information.
9090 *--------------------------------------------------------------------------------------------*/
9091 Object.defineProperty(exports, "__esModule", { value: true });
9092 const vscode_jsonrpc_1 = __webpack_require__(46);
9093 const messages_1 = __webpack_require__(62);
9095 * A request to provide selection ranges in a document. The request's
9096 * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the
9097 * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable
9098 * that resolves to such.
9100 var SelectionRangeRequest;
9101 (function (SelectionRangeRequest) {
9102 SelectionRangeRequest.method = 'textDocument/selectionRange';
9103 SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);
9104 /** @deprecated Use SelectionRangeRequest.type */
9105 SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
9106 })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
9107 //# sourceMappingURL=protocol.selectionRange.js.map
9111 /***/ (function(module, exports, __webpack_require__) {
9115 /* --------------------------------------------------------------------------------------------
9116 * Copyright (c) Microsoft Corporation. All rights reserved.
9117 * Licensed under the MIT License. See License.txt in the project root for license information.
9118 * ------------------------------------------------------------------------------------------ */
9119 Object.defineProperty(exports, "__esModule", { value: true });
9120 const vscode_jsonrpc_1 = __webpack_require__(46);
9121 const messages_1 = __webpack_require__(62);
9122 var WorkDoneProgress;
9123 (function (WorkDoneProgress) {
9124 WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();
9125 })(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));
9127 * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
9128 * reporting from the server.
9130 var WorkDoneProgressCreateRequest;
9131 (function (WorkDoneProgressCreateRequest) {
9132 WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create');
9133 })(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));
9135 * The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress
9136 * initiated on the server side.
9138 var WorkDoneProgressCancelNotification;
9139 (function (WorkDoneProgressCancelNotification) {
9140 WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel');
9141 })(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));
9142 //# sourceMappingURL=protocol.progress.js.map
9146 /***/ (function(module, exports, __webpack_require__) {
9150 /* --------------------------------------------------------------------------------------------
9151 * Copyright (c) TypeFox and others. All rights reserved.
9152 * Licensed under the MIT License. See License.txt in the project root for license information.
9153 * ------------------------------------------------------------------------------------------ */
9154 Object.defineProperty(exports, "__esModule", { value: true });
9155 const messages_1 = __webpack_require__(62);
9157 * A request to result a `CallHierarchyItem` in a document at a given position.
9158 * Can be used as an input to a incoming or outgoing call hierarchy.
9162 var CallHierarchyPrepareRequest;
9163 (function (CallHierarchyPrepareRequest) {
9164 CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';
9165 CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);
9166 })(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));
9168 * A request to resolve the incoming calls for a given `CallHierarchyItem`.
9172 var CallHierarchyIncomingCallsRequest;
9173 (function (CallHierarchyIncomingCallsRequest) {
9174 CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';
9175 CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);
9176 })(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));
9178 * A request to resolve the outgoing calls for a given `CallHierarchyItem`.
9182 var CallHierarchyOutgoingCallsRequest;
9183 (function (CallHierarchyOutgoingCallsRequest) {
9184 CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';
9185 CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);
9186 })(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));
9187 //# sourceMappingURL=protocol.callHierarchy.js.map
9191 /***/ (function(module, exports, __webpack_require__) {
9195 /* --------------------------------------------------------------------------------------------
9196 * Copyright (c) Microsoft Corporation. All rights reserved.
9197 * Licensed under the MIT License. See License.txt in the project root for license information.
9198 * ------------------------------------------------------------------------------------------ */
9199 Object.defineProperty(exports, "__esModule", { value: true });
9200 const vscode_jsonrpc_1 = __webpack_require__(46);
9201 function createProtocolConnection(input, output, logger, options) {
9202 if (vscode_jsonrpc_1.ConnectionStrategy.is(options)) {
9203 options = { connectionStrategy: options };
9205 return vscode_jsonrpc_1.createMessageConnection(input, output, logger, options);
9207 exports.createProtocolConnection = createProtocolConnection;
9208 //# sourceMappingURL=connection.js.map
9212 /***/ (function(module, exports, __webpack_require__) {
9216 /* --------------------------------------------------------------------------------------------
9217 * Copyright (c) Microsoft Corporation. All rights reserved.
9218 * Licensed under the MIT License. See License.txt in the project root for license information.
9219 * ------------------------------------------------------------------------------------------ */
9220 Object.defineProperty(exports, "__esModule", { value: true });
9221 const messages_1 = __webpack_require__(62);
9223 * A set of predefined token types. This set is not fixed
9224 * an clients can specify additional token types via the
9225 * corresponding client capabilities.
9227 * @since 3.16.0 - Proposed state
9229 var SemanticTokenTypes;
9230 (function (SemanticTokenTypes) {
9231 SemanticTokenTypes["namespace"] = "namespace";
9232 SemanticTokenTypes["type"] = "type";
9233 SemanticTokenTypes["class"] = "class";
9234 SemanticTokenTypes["enum"] = "enum";
9235 SemanticTokenTypes["interface"] = "interface";
9236 SemanticTokenTypes["struct"] = "struct";
9237 SemanticTokenTypes["typeParameter"] = "typeParameter";
9238 SemanticTokenTypes["parameter"] = "parameter";
9239 SemanticTokenTypes["variable"] = "variable";
9240 SemanticTokenTypes["property"] = "property";
9241 SemanticTokenTypes["enumMember"] = "enumMember";
9242 SemanticTokenTypes["event"] = "event";
9243 SemanticTokenTypes["function"] = "function";
9244 SemanticTokenTypes["member"] = "member";
9245 SemanticTokenTypes["macro"] = "macro";
9246 SemanticTokenTypes["keyword"] = "keyword";
9247 SemanticTokenTypes["modifier"] = "modifier";
9248 SemanticTokenTypes["comment"] = "comment";
9249 SemanticTokenTypes["string"] = "string";
9250 SemanticTokenTypes["number"] = "number";
9251 SemanticTokenTypes["regexp"] = "regexp";
9252 SemanticTokenTypes["operator"] = "operator";
9253 })(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {}));
9255 * A set of predefined token modifiers. This set is not fixed
9256 * an clients can specify additional token types via the
9257 * corresponding client capabilities.
9259 * @since 3.16.0 - Proposed state
9261 var SemanticTokenModifiers;
9262 (function (SemanticTokenModifiers) {
9263 SemanticTokenModifiers["declaration"] = "declaration";
9264 SemanticTokenModifiers["definition"] = "definition";
9265 SemanticTokenModifiers["readonly"] = "readonly";
9266 SemanticTokenModifiers["static"] = "static";
9267 SemanticTokenModifiers["deprecated"] = "deprecated";
9268 SemanticTokenModifiers["abstract"] = "abstract";
9269 SemanticTokenModifiers["async"] = "async";
9270 SemanticTokenModifiers["modification"] = "modification";
9271 SemanticTokenModifiers["documentation"] = "documentation";
9272 SemanticTokenModifiers["defaultLibrary"] = "defaultLibrary";
9273 })(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {}));
9275 * @since 3.16.0 - Proposed state
9278 (function (SemanticTokens) {
9279 function is(value) {
9280 const candidate = value;
9281 return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&
9282 Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');
9284 SemanticTokens.is = is;
9285 })(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {}));
9287 * @since 3.16.0 - Proposed state
9289 var SemanticTokensRequest;
9290 (function (SemanticTokensRequest) {
9291 SemanticTokensRequest.method = 'textDocument/semanticTokens';
9292 SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);
9293 })(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));
9295 * @since 3.16.0 - Proposed state
9297 var SemanticTokensEditsRequest;
9298 (function (SemanticTokensEditsRequest) {
9299 SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits';
9300 SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method);
9301 })(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {}));
9303 * @since 3.16.0 - Proposed state
9305 var SemanticTokensRangeRequest;
9306 (function (SemanticTokensRangeRequest) {
9307 SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';
9308 SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);
9309 })(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));
9310 //# sourceMappingURL=protocol.semanticTokens.proposed.js.map
9314 /***/ (function(module, exports, __webpack_require__) {
9318 /*---------------------------------------------------------------------------------------------
9319 * Copyright (c) Microsoft Corporation. All rights reserved.
9320 * Licensed under the MIT License. See License.txt in the project root for license information.
9321 *--------------------------------------------------------------------------------------------*/
9322 Object.defineProperty(exports, "__esModule", { value: true });
9324 constructor(_value) {
9325 this._value = _value;
9332 return this.asHex() === other.asHex();
9335 class V4UUID extends ValueUUID {
9338 V4UUID._randomHex(),
9339 V4UUID._randomHex(),
9340 V4UUID._randomHex(),
9341 V4UUID._randomHex(),
9342 V4UUID._randomHex(),
9343 V4UUID._randomHex(),
9344 V4UUID._randomHex(),
9345 V4UUID._randomHex(),
9347 V4UUID._randomHex(),
9348 V4UUID._randomHex(),
9349 V4UUID._randomHex(),
9350 V4UUID._randomHex(),
9353 V4UUID._randomHex(),
9354 V4UUID._randomHex(),
9355 V4UUID._randomHex(),
9357 V4UUID._oneOf(V4UUID._timeHighBits),
9358 V4UUID._randomHex(),
9359 V4UUID._randomHex(),
9360 V4UUID._randomHex(),
9362 V4UUID._randomHex(),
9363 V4UUID._randomHex(),
9364 V4UUID._randomHex(),
9365 V4UUID._randomHex(),
9366 V4UUID._randomHex(),
9367 V4UUID._randomHex(),
9368 V4UUID._randomHex(),
9369 V4UUID._randomHex(),
9370 V4UUID._randomHex(),
9371 V4UUID._randomHex(),
9372 V4UUID._randomHex(),
9373 V4UUID._randomHex(),
9376 static _oneOf(array) {
9377 return array[Math.floor(array.length * Math.random())];
9379 static _randomHex() {
9380 return V4UUID._oneOf(V4UUID._chars);
9383 V4UUID._chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
9384 V4UUID._timeHighBits = ['8', '9', 'a', 'b'];
9386 * An empty UUID that contains only zeros.
9388 exports.empty = new ValueUUID('00000000-0000-0000-0000-000000000000');
9390 return new V4UUID();
9393 const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9394 function isUUID(value) {
9395 return _UUIDPattern.test(value);
9397 exports.isUUID = isUUID;
9399 * Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
9400 * @param value A uuid string.
9402 function parse(value) {
9403 if (!isUUID(value)) {
9404 throw new Error('invalid uuid');
9406 return new ValueUUID(value);
9408 exports.parse = parse;
9409 function generateUuid() {
9410 return v4().asHex();
9412 exports.generateUuid = generateUuid;
9413 //# sourceMappingURL=uuid.js.map
9417 /***/ (function(module, exports, __webpack_require__) {
9421 /* --------------------------------------------------------------------------------------------
9422 * Copyright (c) Microsoft Corporation. All rights reserved.
9423 * Licensed under the MIT License. See License.txt in the project root for license information.
9424 * ------------------------------------------------------------------------------------------ */
9425 Object.defineProperty(exports, "__esModule", { value: true });
9426 const vscode_languageserver_protocol_1 = __webpack_require__(44);
9427 const uuid_1 = __webpack_require__(77);
9428 class WorkDoneProgressReporterImpl {
9429 constructor(_connection, _token) {
9430 this._connection = _connection;
9431 this._token = _token;
9432 WorkDoneProgressReporterImpl.Instances.set(this._token, this);
9434 begin(title, percentage, message, cancellable) {
9442 this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, param);
9444 report(arg0, arg1) {
9448 if (typeof arg0 === 'number') {
9449 param.percentage = arg0;
9450 if (arg1 !== undefined) {
9451 param.message = arg1;
9455 param.message = arg0;
9457 this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, param);
9460 WorkDoneProgressReporterImpl.Instances.delete(this._token);
9461 this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, { kind: 'end' });
9464 WorkDoneProgressReporterImpl.Instances = new Map();
9465 class WorkDoneProgressServerReporterImpl extends WorkDoneProgressReporterImpl {
9466 constructor(connection, token) {
9467 super(connection, token);
9468 this._source = new vscode_languageserver_protocol_1.CancellationTokenSource();
9471 return this._source.token;
9474 this._source.dispose();
9478 this._source.cancel();
9481 class NullProgressReporter {
9491 class NullProgressServerReporter extends NullProgressReporter {
9494 this._source = new vscode_languageserver_protocol_1.CancellationTokenSource();
9497 return this._source.token;
9500 this._source.dispose();
9503 this._source.cancel();
9506 function attachWorkDone(connection, params) {
9507 if (params === undefined || params.workDoneToken === undefined) {
9508 return new NullProgressReporter();
9510 const token = params.workDoneToken;
9511 delete params.workDoneToken;
9512 return new WorkDoneProgressReporterImpl(connection, token);
9514 exports.attachWorkDone = attachWorkDone;
9515 exports.ProgressFeature = (Base) => {
9516 return class extends Base {
9519 this._progressSupported = false;
9521 initialize(capabilities) {
9523 if (((_a = capabilities === null || capabilities === void 0 ? void 0 : capabilities.window) === null || _a === void 0 ? void 0 : _a.workDoneProgress) === true) {
9524 this._progressSupported = true;
9525 this.connection.onNotification(vscode_languageserver_protocol_1.WorkDoneProgressCancelNotification.type, (params) => {
9526 let progress = WorkDoneProgressReporterImpl.Instances.get(params.token);
9527 if (progress instanceof WorkDoneProgressServerReporterImpl || progress instanceof NullProgressServerReporter) {
9533 attachWorkDoneProgress(token) {
9534 if (token === undefined) {
9535 return new NullProgressReporter();
9538 return new WorkDoneProgressReporterImpl(this.connection, token);
9541 createWorkDoneProgress() {
9542 if (this._progressSupported) {
9543 const token = uuid_1.generateUuid();
9544 return this.connection.sendRequest(vscode_languageserver_protocol_1.WorkDoneProgressCreateRequest.type, { token }).then(() => {
9545 const result = new WorkDoneProgressServerReporterImpl(this.connection, token);
9550 return Promise.resolve(new NullProgressServerReporter());
9556 (function (ResultProgress) {
9557 ResultProgress.type = new vscode_languageserver_protocol_1.ProgressType();
9558 })(ResultProgress || (ResultProgress = {}));
9559 class ResultProgressReporterImpl {
9560 constructor(_connection, _token) {
9561 this._connection = _connection;
9562 this._token = _token;
9565 this._connection.sendProgress(ResultProgress.type, this._token, data);
9568 function attachPartialResult(connection, params) {
9569 if (params === undefined || params.partialResultToken === undefined) {
9572 const token = params.partialResultToken;
9573 delete params.partialResultToken;
9574 return new ResultProgressReporterImpl(connection, token);
9576 exports.attachPartialResult = attachPartialResult;
9577 //# sourceMappingURL=progress.js.map
9581 /***/ (function(module, exports, __webpack_require__) {
9584 /* --------------------------------------------------------------------------------------------
9585 * Copyright (c) Microsoft Corporation. All rights reserved.
9586 * Licensed under the MIT License. See License.txt in the project root for license information.
9587 * ------------------------------------------------------------------------------------------ */
9589 Object.defineProperty(exports, "__esModule", { value: true });
9590 const vscode_languageserver_protocol_1 = __webpack_require__(44);
9591 const Is = __webpack_require__(42);
9592 exports.ConfigurationFeature = (Base) => {
9593 return class extends Base {
9594 getConfiguration(arg) {
9596 return this._getConfiguration({});
9598 else if (Is.string(arg)) {
9599 return this._getConfiguration({ section: arg });
9602 return this._getConfiguration(arg);
9605 _getConfiguration(arg) {
9607 items: Array.isArray(arg) ? arg : [arg]
9609 return this.connection.sendRequest(vscode_languageserver_protocol_1.ConfigurationRequest.type, params).then((result) => {
9610 return Array.isArray(arg) ? result : result[0];
9615 //# sourceMappingURL=configuration.js.map
9619 /***/ (function(module, exports, __webpack_require__) {
9622 /* --------------------------------------------------------------------------------------------
9623 * Copyright (c) Microsoft Corporation. All rights reserved.
9624 * Licensed under the MIT License. See License.txt in the project root for license information.
9625 * ------------------------------------------------------------------------------------------ */
9627 Object.defineProperty(exports, "__esModule", { value: true });
9628 const vscode_languageserver_protocol_1 = __webpack_require__(44);
9629 exports.WorkspaceFoldersFeature = (Base) => {
9630 return class extends Base {
9631 initialize(capabilities) {
9632 let workspaceCapabilities = capabilities.workspace;
9633 if (workspaceCapabilities && workspaceCapabilities.workspaceFolders) {
9634 this._onDidChangeWorkspaceFolders = new vscode_languageserver_protocol_1.Emitter();
9635 this.connection.onNotification(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type, (params) => {
9636 this._onDidChangeWorkspaceFolders.fire(params.event);
9640 getWorkspaceFolders() {
9641 return this.connection.sendRequest(vscode_languageserver_protocol_1.WorkspaceFoldersRequest.type);
9643 get onDidChangeWorkspaceFolders() {
9644 if (!this._onDidChangeWorkspaceFolders) {
9645 throw new Error('Client doesn\'t support sending workspace folder change events.');
9647 if (!this._unregistration) {
9648 this._unregistration = this.connection.client.register(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type);
9650 return this._onDidChangeWorkspaceFolders.event;
9654 //# sourceMappingURL=workspaceFolders.js.map
9658 /***/ (function(module, exports, __webpack_require__) {
9661 /* --------------------------------------------------------------------------------------------
9662 * Copyright (c) Microsoft Corporation. All rights reserved.
9663 * Licensed under the MIT License. See License.txt in the project root for license information.
9664 * ------------------------------------------------------------------------------------------ */
9666 Object.defineProperty(exports, "__esModule", { value: true });
9667 const vscode_languageserver_protocol_1 = __webpack_require__(44);
9668 exports.CallHierarchyFeature = (Base) => {
9669 return class extends Base {
9670 get callHierarchy() {
9672 onPrepare: (handler) => {
9673 this.connection.onRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, (params, cancel) => {
9674 return handler(params, cancel, this.attachWorkDoneProgress(params), undefined);
9677 onIncomingCalls: (handler) => {
9678 const type = vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type;
9679 this.connection.onRequest(type, (params, cancel) => {
9680 return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
9683 onOutgoingCalls: (handler) => {
9684 const type = vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type;
9685 this.connection.onRequest(type, (params, cancel) => {
9686 return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
9693 //# sourceMappingURL=callHierarchy.js.map
9697 /***/ (function(module, exports, __webpack_require__) {
9700 /* WEBPACK VAR INJECTION */(function(__filename) {
9701 /* --------------------------------------------------------------------------------------------
9702 * Copyright (c) Microsoft Corporation. All rights reserved.
9703 * Licensed under the MIT License. See License.txt in the project root for license information.
9704 * ------------------------------------------------------------------------------------------ */
9705 Object.defineProperty(exports, "__esModule", { value: true });
9706 const url = __webpack_require__(83);
9707 const path = __webpack_require__(1);
9708 const fs = __webpack_require__(2);
9709 const child_process_1 = __webpack_require__(84);
9711 * @deprecated Use the `vscode-uri` npm module which provides a more
9712 * complete implementation of handling VS Code URIs.
9714 function uriToFilePath(uri) {
9715 let parsed = url.parse(uri);
9716 if (parsed.protocol !== 'file:' || !parsed.path) {
9719 let segments = parsed.path.split('/');
9720 for (var i = 0, len = segments.length; i < len; i++) {
9721 segments[i] = decodeURIComponent(segments[i]);
9723 if (process.platform === 'win32' && segments.length > 1) {
9724 let first = segments[0];
9725 let second = segments[1];
9726 // Do we have a drive letter and we started with a / which is the
9727 // case if the first segement is empty (see split above)
9728 if (first.length === 0 && second.length > 1 && second[1] === ':') {
9729 // Remove first slash
9733 return path.normalize(segments.join('/'));
9735 exports.uriToFilePath = uriToFilePath;
9736 function isWindows() {
9737 return process.platform === 'win32';
9739 function resolve(moduleName, nodePath, cwd, tracer) {
9740 const nodePathKey = 'NODE_PATH';
9743 'p.on(\'message\',function(m){',
9747 'else if(m.c===\'rs\'){',
9749 'var r=require.resolve(m.a);',
9750 'p.send({c:\'r\',s:true,r:r});',
9753 'p.send({c:\'r\',s:false});',
9758 return new Promise((resolve, reject) => {
9759 let env = process.env;
9760 let newEnv = Object.create(null);
9761 Object.keys(env).forEach(key => newEnv[key] = env[key]);
9762 if (nodePath && fs.existsSync(nodePath) /* see issue 545 */) {
9763 if (newEnv[nodePathKey]) {
9764 newEnv[nodePathKey] = nodePath + path.delimiter + newEnv[nodePathKey];
9767 newEnv[nodePathKey] = nodePath;
9770 tracer(`NODE_PATH value is: ${newEnv[nodePathKey]}`);
9773 newEnv['ELECTRON_RUN_AS_NODE'] = '1';
9775 let cp = child_process_1.fork('', [], {
9778 execArgv: ['-e', app]
9780 if (cp.pid === void 0) {
9781 reject(new Error(`Starting process to resolve node module ${moduleName} failed`));
9784 cp.on('error', (error) => {
9787 cp.on('message', (message) => {
9788 if (message.c === 'r') {
9789 cp.send({ c: 'e' });
9794 reject(new Error(`Failed to resolve module: ${moduleName}`));
9809 exports.resolve = resolve;
9811 * Resolve the global npm package path.
9812 * @deprecated Since this depends on the used package manager and their version the best is that servers
9813 * implement this themselves since they know best what kind of package managers to support.
9814 * @param tracer the tracer to use
9816 function resolveGlobalNodePath(tracer) {
9817 let npmCommand = 'npm';
9818 const env = Object.create(null);
9819 Object.keys(process.env).forEach(key => env[key] = process.env[key]);
9820 env['NO_UPDATE_NOTIFIER'] = 'true';
9826 npmCommand = 'npm.cmd';
9827 options.shell = true;
9829 let handler = () => { };
9831 process.on('SIGPIPE', handler);
9832 let stdout = child_process_1.spawnSync(npmCommand, ['config', 'get', 'prefix'], options).stdout;
9835 tracer(`'npm config get prefix' didn't return a value.`);
9839 let prefix = stdout.trim();
9841 tracer(`'npm config get prefix' value is: ${prefix}`);
9843 if (prefix.length > 0) {
9845 return path.join(prefix, 'node_modules');
9848 return path.join(prefix, 'lib', 'node_modules');
9857 process.removeListener('SIGPIPE', handler);
9860 exports.resolveGlobalNodePath = resolveGlobalNodePath;
9862 * Resolve the global yarn pakage path.
9863 * @deprecated Since this depends on the used package manager and their version the best is that servers
9864 * implement this themselves since they know best what kind of package managers to support.
9865 * @param tracer the tracer to use
9867 function resolveGlobalYarnPath(tracer) {
9868 let yarnCommand = 'yarn';
9873 yarnCommand = 'yarn.cmd';
9874 options.shell = true;
9876 let handler = () => { };
9878 process.on('SIGPIPE', handler);
9879 let results = child_process_1.spawnSync(yarnCommand, ['global', 'dir', '--json'], options);
9880 let stdout = results.stdout;
9883 tracer(`'yarn global dir' didn't return a value.`);
9884 if (results.stderr) {
9885 tracer(results.stderr);
9890 let lines = stdout.trim().split(/\r?\n/);
9891 for (let line of lines) {
9893 let yarn = JSON.parse(line);
9894 if (yarn.type === 'log') {
9895 return path.join(yarn.data, 'node_modules');
9899 // Do nothing. Ignore the line
9908 process.removeListener('SIGPIPE', handler);
9911 exports.resolveGlobalYarnPath = resolveGlobalYarnPath;
9913 (function (FileSystem) {
9914 let _isCaseSensitive = undefined;
9915 function isCaseSensitive() {
9916 if (_isCaseSensitive !== void 0) {
9917 return _isCaseSensitive;
9919 if (process.platform === 'win32') {
9920 _isCaseSensitive = false;
9923 // convert current file name to upper case / lower case and check if file exists
9924 // (guards against cases when name is already all uppercase or lowercase)
9925 _isCaseSensitive = !fs.existsSync(__filename.toUpperCase()) || !fs.existsSync(__filename.toLowerCase());
9927 return _isCaseSensitive;
9929 FileSystem.isCaseSensitive = isCaseSensitive;
9930 function isParent(parent, child) {
9931 if (isCaseSensitive()) {
9932 return path.normalize(child).indexOf(path.normalize(parent)) === 0;
9935 return path.normalize(child).toLowerCase().indexOf(path.normalize(parent).toLowerCase()) === 0;
9938 FileSystem.isParent = isParent;
9939 })(FileSystem = exports.FileSystem || (exports.FileSystem = {}));
9940 function resolveModulePath(workspaceRoot, moduleName, nodePath, tracer) {
9942 if (!path.isAbsolute(nodePath)) {
9943 nodePath = path.join(workspaceRoot, nodePath);
9945 return resolve(moduleName, nodePath, nodePath, tracer).then((value) => {
9946 if (FileSystem.isParent(nodePath, value)) {
9950 return Promise.reject(new Error(`Failed to load ${moduleName} from node path location.`));
9952 }).then(undefined, (_error) => {
9953 return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer);
9957 return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer);
9960 exports.resolveModulePath = resolveModulePath;
9961 //# sourceMappingURL=files.js.map
9962 /* WEBPACK VAR INJECTION */}.call(this, "/index.js"))
9966 /***/ (function(module, exports) {
9968 module.exports = require("url");
9972 /***/ (function(module, exports) {
9974 module.exports = require("child_process");
9978 /***/ (function(module, exports, __webpack_require__) {
9981 /* --------------------------------------------------------------------------------------------
9982 * Copyright (c) Microsoft Corporation. All rights reserved.
9983 * Licensed under the MIT License. See License.txt in the project root for license information.
9984 * ----------------------------------------------------------------------------------------- */
9987 module.exports = __webpack_require__(44);
9991 /***/ (function(module, exports, __webpack_require__) {
9995 /* --------------------------------------------------------------------------------------------
9996 * Copyright (c) Microsoft Corporation. All rights reserved.
9997 * Licensed under the MIT License. See License.txt in the project root for license information.
9998 * ------------------------------------------------------------------------------------------ */
9999 function __export(m) {
10000 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
10002 Object.defineProperty(exports, "__esModule", { value: true });
10003 const st = __webpack_require__(87);
10004 __export(__webpack_require__(44));
10005 __export(__webpack_require__(43));
10006 var ProposedFeatures;
10007 (function (ProposedFeatures) {
10008 ProposedFeatures.all = {
10009 __brand: 'features',
10010 languages: st.SemanticTokensFeature
10012 ProposedFeatures.SemanticTokensBuilder = st.SemanticTokensBuilder;
10013 })(ProposedFeatures = exports.ProposedFeatures || (exports.ProposedFeatures = {}));
10014 //# sourceMappingURL=api.js.map
10018 /***/ (function(module, exports, __webpack_require__) {
10022 /* --------------------------------------------------------------------------------------------
10023 * Copyright (c) Microsoft Corporation. All rights reserved.
10024 * Licensed under the MIT License. See License.txt in the project root for license information.
10025 * ------------------------------------------------------------------------------------------ */
10026 Object.defineProperty(exports, "__esModule", { value: true });
10027 const vscode_languageserver_protocol_1 = __webpack_require__(44);
10028 exports.SemanticTokensFeature = (Base) => {
10029 return class extends Base {
10030 get semanticTokens() {
10033 const type = vscode_languageserver_protocol_1.Proposed.SemanticTokensRequest.type;
10034 this.connection.onRequest(type, (params, cancel) => {
10035 return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
10038 onEdits: (handler) => {
10039 const type = vscode_languageserver_protocol_1.Proposed.SemanticTokensEditsRequest.type;
10040 this.connection.onRequest(type, (params, cancel) => {
10041 return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
10044 onRange: (handler) => {
10045 const type = vscode_languageserver_protocol_1.Proposed.SemanticTokensRangeRequest.type;
10046 this.connection.onRequest(type, (params, cancel) => {
10047 return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
10054 class SemanticTokensBuilder {
10056 this._prevData = undefined;
10060 this._id = Date.now();
10061 this._prevLine = 0;
10062 this._prevChar = 0;
10066 push(line, char, length, tokenType, tokenModifiers) {
10067 let pushLine = line;
10068 let pushChar = char;
10069 if (this._dataLen > 0) {
10070 pushLine -= this._prevLine;
10071 if (pushLine === 0) {
10072 pushChar -= this._prevChar;
10075 this._data[this._dataLen++] = pushLine;
10076 this._data[this._dataLen++] = pushChar;
10077 this._data[this._dataLen++] = length;
10078 this._data[this._dataLen++] = tokenType;
10079 this._data[this._dataLen++] = tokenModifiers;
10080 this._prevLine = line;
10081 this._prevChar = char;
10084 return this._id.toString();
10086 previousResult(id) {
10087 if (this.id === id) {
10088 this._prevData = this._data;
10093 this._prevData = undefined;
10100 return this._prevData !== undefined;
10103 if (this._prevData !== undefined) {
10104 const prevDataLength = this._prevData.length;
10105 const dataLength = this._data.length;
10106 let startIndex = 0;
10107 while (startIndex < dataLength && startIndex < prevDataLength && this._prevData[startIndex] === this._data[startIndex]) {
10110 if (startIndex < dataLength && startIndex < prevDataLength) {
10113 while (endIndex < dataLength && endIndex < prevDataLength && this._prevData[prevDataLength - 1 - endIndex] === this._data[dataLength - 1 - endIndex]) {
10116 const newData = this._data.slice(startIndex, dataLength - endIndex);
10120 { start: startIndex, deleteCount: prevDataLength - endIndex - startIndex, data: newData }
10125 else if (startIndex < dataLength) {
10126 return { resultId: this.id, edits: [
10127 { start: startIndex, deleteCount: 0, data: this._data.slice(startIndex) }
10130 else if (startIndex < prevDataLength) {
10131 return { resultId: this.id, edits: [
10132 { start: startIndex, deleteCount: prevDataLength - startIndex }
10136 return { resultId: this.id, edits: [] };
10140 return this.build();
10144 exports.SemanticTokensBuilder = SemanticTokensBuilder;
10145 //# sourceMappingURL=semanticTokens.proposed.js.map
10149 /***/ (function(module, exports, __webpack_require__) {
10153 /*---------------------------------------------------------------------------------------------
10154 * Copyright (c) Microsoft Corporation. All rights reserved.
10155 * Licensed under the MIT License. See License.txt in the project root for license information.
10156 *--------------------------------------------------------------------------------------------*/
10157 Object.defineProperty(exports, "__esModule", { value: true });
10158 exports.runSafe = exports.runSafeAsync = exports.formatError = void 0;
10159 const vscode_languageserver_1 = __webpack_require__(41);
10160 function formatError(message, err) {
10161 if (err instanceof Error) {
10163 return `${message}: ${error.message}\n${error.stack}`;
10165 else if (typeof err === 'string') {
10166 return `${message}: ${err}`;
10169 return `${message}: ${err.toString()}`;
10173 exports.formatError = formatError;
10174 function runSafeAsync(func, errorVal, errorMessage, token) {
10175 return new Promise((resolve) => {
10176 setImmediate(() => {
10177 if (token.isCancellationRequested) {
10178 resolve(cancelValue());
10180 return func().then(result => {
10181 if (token.isCancellationRequested) {
10182 resolve(cancelValue());
10189 console.error(formatError(errorMessage, e));
10195 exports.runSafeAsync = runSafeAsync;
10196 function runSafe(func, errorVal, errorMessage, token) {
10197 return new Promise((resolve) => {
10198 setImmediate(() => {
10199 if (token.isCancellationRequested) {
10200 resolve(cancelValue());
10204 let result = func();
10205 if (token.isCancellationRequested) {
10206 resolve(cancelValue());
10214 console.error(formatError(errorMessage, e));
10221 exports.runSafe = runSafe;
10222 function cancelValue() {
10223 console.log('cancelled');
10224 return new vscode_languageserver_1.ResponseError(vscode_languageserver_1.ErrorCodes.RequestCancelled, 'Request cancelled');
10230 /***/ (function(module, exports, __webpack_require__) {
10234 /*---------------------------------------------------------------------------------------------
10235 * Copyright (c) Microsoft Corporation. All rights reserved.
10236 * Licensed under the MIT License. See License.txt in the project root for license information.
10237 *--------------------------------------------------------------------------------------------*/
10238 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
10239 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10240 return new (P || (P = Promise))(function (resolve, reject) {
10241 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10242 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
10243 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10244 step((generator = generator.apply(thisArg, _arguments || [])).next());
10247 Object.defineProperty(exports, "__esModule", { value: true });
10248 exports.startServer = void 0;
10249 const vscode_languageserver_1 = __webpack_require__(41);
10250 const runner_1 = __webpack_require__(88);
10251 const vscode_json_languageservice_1 = __webpack_require__(90);
10252 const languageModelCache_1 = __webpack_require__(113);
10253 const requests_1 = __webpack_require__(114);
10254 var SchemaAssociationNotification;
10255 (function (SchemaAssociationNotification) {
10256 SchemaAssociationNotification.type = new vscode_languageserver_1.NotificationType('json/schemaAssociations');
10257 })(SchemaAssociationNotification || (SchemaAssociationNotification = {}));
10258 var VSCodeContentRequest;
10259 (function (VSCodeContentRequest) {
10260 VSCodeContentRequest.type = new vscode_languageserver_1.RequestType('vscode/content');
10261 })(VSCodeContentRequest || (VSCodeContentRequest = {}));
10262 var SchemaContentChangeNotification;
10263 (function (SchemaContentChangeNotification) {
10264 SchemaContentChangeNotification.type = new vscode_languageserver_1.NotificationType('json/schemaContent');
10265 })(SchemaContentChangeNotification || (SchemaContentChangeNotification = {}));
10266 var ResultLimitReachedNotification;
10267 (function (ResultLimitReachedNotification) {
10268 ResultLimitReachedNotification.type = new vscode_languageserver_1.NotificationType('json/resultLimitReached');
10269 })(ResultLimitReachedNotification || (ResultLimitReachedNotification = {}));
10270 var ForceValidateRequest;
10271 (function (ForceValidateRequest) {
10272 ForceValidateRequest.type = new vscode_languageserver_1.RequestType('json/validate');
10273 })(ForceValidateRequest || (ForceValidateRequest = {}));
10274 const workspaceContext = {
10275 resolveRelativePath: (relativePath, resource) => {
10276 const base = resource.substr(0, resource.lastIndexOf('/') + 1);
10277 return requests_1.resolvePath(base, relativePath);
10280 function startServer(connection, runtime) {
10281 function getSchemaRequestService(handledSchemas = ['https', 'http', 'file']) {
10282 const builtInHandlers = {};
10283 for (let protocol of handledSchemas) {
10284 if (protocol === 'file') {
10285 builtInHandlers[protocol] = runtime.file;
10287 else if (protocol === 'http' || protocol === 'https') {
10288 builtInHandlers[protocol] = runtime.http;
10292 const protocol = uri.substr(0, uri.indexOf(':'));
10293 const builtInHandler = builtInHandlers[protocol];
10294 if (builtInHandler) {
10295 return builtInHandler.getContent(uri);
10297 return connection.sendRequest(VSCodeContentRequest.type, uri).then(responseText => {
10298 return responseText;
10300 return Promise.reject(error.message);
10304 // create the JSON language service
10305 let languageService = vscode_json_languageservice_1.getLanguageService({
10308 clientCapabilities: vscode_json_languageservice_1.ClientCapabilities.LATEST
10310 // Create a text document manager.
10311 const documents = new vscode_languageserver_1.TextDocuments(vscode_json_languageservice_1.TextDocument);
10312 // Make the text document manager listen on the connection
10313 // for open, change and close text document events
10314 documents.listen(connection);
10315 let clientSnippetSupport = false;
10316 let dynamicFormatterRegistration = false;
10317 let hierarchicalDocumentSymbolSupport = false;
10318 let foldingRangeLimitDefault = Number.MAX_VALUE;
10319 let foldingRangeLimit = Number.MAX_VALUE;
10320 let resultLimit = Number.MAX_VALUE;
10321 let formatterMaxNumberOfEdits = Number.MAX_VALUE;
10322 // After the server has started the client sends an initialize request. The server receives
10323 // in the passed params the rootPath of the workspace plus the client capabilities.
10324 connection.onInitialize((params) => {
10325 var _a, _b, _c, _d, _e;
10326 const handledProtocols = (_a = params.initializationOptions) === null || _a === void 0 ? void 0 : _a.handledSchemaProtocols;
10327 languageService = vscode_json_languageservice_1.getLanguageService({
10328 schemaRequestService: getSchemaRequestService(handledProtocols),
10331 clientCapabilities: params.capabilities
10333 function getClientCapability(name, def) {
10334 const keys = name.split('.');
10335 let c = params.capabilities;
10336 for (let i = 0; c && i < keys.length; i++) {
10337 if (!c.hasOwnProperty(keys[i])) {
10344 clientSnippetSupport = getClientCapability('textDocument.completion.completionItem.snippetSupport', false);
10345 dynamicFormatterRegistration = getClientCapability('textDocument.rangeFormatting.dynamicRegistration', false) && (typeof ((_b = params.initializationOptions) === null || _b === void 0 ? void 0 : _b.provideFormatter) !== 'boolean');
10346 foldingRangeLimitDefault = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE);
10347 hierarchicalDocumentSymbolSupport = getClientCapability('textDocument.documentSymbol.hierarchicalDocumentSymbolSupport', false);
10348 formatterMaxNumberOfEdits = ((_e = (_d = (_c = params.initializationOptions) === null || _c === void 0 ? void 0 : _c.customCapabilities) === null || _d === void 0 ? void 0 : _d.rangeFormatting) === null || _e === void 0 ? void 0 : _e.editLimit) || Number.MAX_VALUE;
10349 const capabilities = {
10350 textDocumentSync: vscode_languageserver_1.TextDocumentSyncKind.Incremental,
10351 completionProvider: clientSnippetSupport ? {
10352 resolveProvider: false,
10353 triggerCharacters: ['"', ':']
10355 hoverProvider: true,
10356 documentSymbolProvider: true,
10357 documentRangeFormattingProvider: params.initializationOptions.provideFormatter === true,
10359 foldingRangeProvider: true,
10360 selectionRangeProvider: true,
10361 definitionProvider: true
10363 return { capabilities };
10365 const limitExceededWarnings = function () {
10366 const pendingWarnings = {};
10369 const warning = pendingWarnings[uri];
10370 if (warning && warning.timeout) {
10371 clearTimeout(warning.timeout);
10372 delete pendingWarnings[uri];
10375 onResultLimitExceeded(uri, resultLimit, name) {
10377 let warning = pendingWarnings[uri];
10379 if (!warning.timeout) {
10383 warning.features[name] = name;
10384 warning.timeout.refresh();
10387 warning = { features: { [name]: name } };
10388 warning.timeout = setTimeout(() => {
10389 connection.sendNotification(ResultLimitReachedNotification.type, `${requests_1.basename(uri)}: For performance reasons, ${Object.keys(warning.features).join(' and ')} have been limited to ${resultLimit} items.`);
10390 warning.timeout = undefined;
10392 pendingWarnings[uri] = warning;
10398 let jsonConfigurationSettings = undefined;
10399 let schemaAssociations = undefined;
10400 let formatterRegistration = null;
10401 // The settings have changed. Is send on server activation as well.
10402 connection.onDidChangeConfiguration((change) => {
10403 let settings = change.settings;
10404 if (runtime.configureHttpRequests) {
10405 runtime.configureHttpRequests(settings.http && settings.http.proxy, settings.http && settings.http.proxyStrictSSL);
10407 jsonConfigurationSettings = settings.json && settings.json.schemas;
10408 updateConfiguration();
10409 foldingRangeLimit = Math.trunc(Math.max(settings.json && settings.json.resultLimit || foldingRangeLimitDefault, 0));
10410 resultLimit = Math.trunc(Math.max(settings.json && settings.json.resultLimit || Number.MAX_VALUE, 0));
10411 // dynamically enable & disable the formatter
10412 if (dynamicFormatterRegistration) {
10413 const enableFormatter = settings && settings.json && settings.json.format && settings.json.format.enable;
10414 if (enableFormatter) {
10415 if (!formatterRegistration) {
10416 formatterRegistration = connection.client.register(vscode_languageserver_1.DocumentRangeFormattingRequest.type, { documentSelector: [{ language: 'json' }, { language: 'jsonc' }] });
10419 else if (formatterRegistration) {
10420 formatterRegistration.then(r => r.dispose());
10421 formatterRegistration = null;
10425 // The jsonValidation extension configuration has changed
10426 connection.onNotification(SchemaAssociationNotification.type, associations => {
10427 schemaAssociations = associations;
10428 updateConfiguration();
10430 // A schema has changed
10431 connection.onNotification(SchemaContentChangeNotification.type, uri => {
10432 languageService.resetSchema(uri);
10434 // Retry schema validation on all open documents
10435 connection.onRequest(ForceValidateRequest.type, uri => {
10436 return new Promise(resolve => {
10437 const document = documents.get(uri);
10439 updateConfiguration();
10440 validateTextDocument(document, diagnostics => {
10441 resolve(diagnostics);
10449 function updateConfiguration() {
10450 const languageSettings = {
10452 allowComments: true,
10453 schemas: new Array()
10455 if (schemaAssociations) {
10456 if (Array.isArray(schemaAssociations)) {
10457 Array.prototype.push.apply(languageSettings.schemas, schemaAssociations);
10460 for (const pattern in schemaAssociations) {
10461 const association = schemaAssociations[pattern];
10462 if (Array.isArray(association)) {
10463 association.forEach(uri => {
10464 languageSettings.schemas.push({ uri, fileMatch: [pattern] });
10470 if (jsonConfigurationSettings) {
10471 jsonConfigurationSettings.forEach((schema, index) => {
10472 let uri = schema.url;
10473 if (!uri && schema.schema) {
10474 uri = schema.schema.id || `vscode://schemas/custom/${index}`;
10477 languageSettings.schemas.push({ uri, fileMatch: schema.fileMatch, schema: schema.schema });
10481 languageService.configure(languageSettings);
10482 // Revalidate any open text documents
10483 documents.all().forEach(triggerValidation);
10485 // The content of a text document has changed. This event is emitted
10486 // when the text document first opened or when its content has changed.
10487 documents.onDidChangeContent((change) => {
10488 limitExceededWarnings.cancel(change.document.uri);
10489 triggerValidation(change.document);
10491 // a document has closed: clear all diagnostics
10492 documents.onDidClose(event => {
10493 limitExceededWarnings.cancel(event.document.uri);
10494 cleanPendingValidation(event.document);
10495 connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] });
10497 const pendingValidationRequests = {};
10498 const validationDelayMs = 300;
10499 function cleanPendingValidation(textDocument) {
10500 const request = pendingValidationRequests[textDocument.uri];
10502 clearTimeout(request);
10503 delete pendingValidationRequests[textDocument.uri];
10506 function triggerValidation(textDocument) {
10507 cleanPendingValidation(textDocument);
10508 pendingValidationRequests[textDocument.uri] = setTimeout(() => {
10509 delete pendingValidationRequests[textDocument.uri];
10510 validateTextDocument(textDocument);
10511 }, validationDelayMs);
10513 function validateTextDocument(textDocument, callback) {
10514 const respond = (diagnostics) => {
10515 connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
10517 callback(diagnostics);
10520 if (textDocument.getText().length === 0) {
10521 respond([]); // ignore empty documents
10524 const jsonDocument = getJSONDocument(textDocument);
10525 const version = textDocument.version;
10526 const documentSettings = textDocument.languageId === 'jsonc' ? { comments: 'ignore', trailingCommas: 'warning' } : { comments: 'error', trailingCommas: 'error' };
10527 languageService.doValidation(textDocument, jsonDocument, documentSettings).then(diagnostics => {
10528 setImmediate(() => {
10529 const currDocument = documents.get(textDocument.uri);
10530 if (currDocument && currDocument.version === version) {
10531 respond(diagnostics); // Send the computed diagnostics to VSCode.
10535 connection.console.error(runner_1.formatError(`Error while validating ${textDocument.uri}`, error));
10538 connection.onDidChangeWatchedFiles((change) => {
10539 // Monitored files have changed in VSCode
10540 let hasChanges = false;
10541 change.changes.forEach(c => {
10542 if (languageService.resetSchema(c.uri)) {
10547 documents.all().forEach(triggerValidation);
10550 const jsonDocuments = languageModelCache_1.getLanguageModelCache(10, 60, document => languageService.parseJSONDocument(document));
10551 documents.onDidClose(e => {
10552 jsonDocuments.onDocumentRemoved(e.document);
10554 connection.onShutdown(() => {
10555 jsonDocuments.dispose();
10557 function getJSONDocument(document) {
10558 return jsonDocuments.get(document);
10560 connection.onCompletion((textDocumentPosition, token) => {
10561 return runner_1.runSafeAsync(() => __awaiter(this, void 0, void 0, function* () {
10562 const document = documents.get(textDocumentPosition.textDocument.uri);
10564 const jsonDocument = getJSONDocument(document);
10565 return languageService.doComplete(document, textDocumentPosition.position, jsonDocument);
10568 }), null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`, token);
10570 connection.onHover((textDocumentPositionParams, token) => {
10571 return runner_1.runSafeAsync(() => __awaiter(this, void 0, void 0, function* () {
10572 const document = documents.get(textDocumentPositionParams.textDocument.uri);
10574 const jsonDocument = getJSONDocument(document);
10575 return languageService.doHover(document, textDocumentPositionParams.position, jsonDocument);
10578 }), null, `Error while computing hover for ${textDocumentPositionParams.textDocument.uri}`, token);
10580 connection.onDocumentSymbol((documentSymbolParams, token) => {
10581 return runner_1.runSafe(() => {
10582 const document = documents.get(documentSymbolParams.textDocument.uri);
10584 const jsonDocument = getJSONDocument(document);
10585 const onResultLimitExceeded = limitExceededWarnings.onResultLimitExceeded(document.uri, resultLimit, 'document symbols');
10586 if (hierarchicalDocumentSymbolSupport) {
10587 return languageService.findDocumentSymbols2(document, jsonDocument, { resultLimit, onResultLimitExceeded });
10590 return languageService.findDocumentSymbols(document, jsonDocument, { resultLimit, onResultLimitExceeded });
10594 }, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, token);
10596 connection.onDocumentRangeFormatting((formatParams, token) => {
10597 return runner_1.runSafe(() => {
10598 const document = documents.get(formatParams.textDocument.uri);
10600 const edits = languageService.format(document, formatParams.range, formatParams.options);
10601 if (edits.length > formatterMaxNumberOfEdits) {
10602 const newText = vscode_json_languageservice_1.TextDocument.applyEdits(document, edits);
10603 return [vscode_languageserver_1.TextEdit.replace(vscode_json_languageservice_1.Range.create(vscode_json_languageservice_1.Position.create(0, 0), document.positionAt(document.getText().length)), newText)];
10608 }, [], `Error while formatting range for ${formatParams.textDocument.uri}`, token);
10610 connection.onDocumentColor((params, token) => {
10611 return runner_1.runSafeAsync(() => __awaiter(this, void 0, void 0, function* () {
10612 const document = documents.get(params.textDocument.uri);
10614 const onResultLimitExceeded = limitExceededWarnings.onResultLimitExceeded(document.uri, resultLimit, 'document colors');
10615 const jsonDocument = getJSONDocument(document);
10616 return languageService.findDocumentColors(document, jsonDocument, { resultLimit, onResultLimitExceeded });
10619 }), [], `Error while computing document colors for ${params.textDocument.uri}`, token);
10621 connection.onColorPresentation((params, token) => {
10622 return runner_1.runSafe(() => {
10623 const document = documents.get(params.textDocument.uri);
10625 const jsonDocument = getJSONDocument(document);
10626 return languageService.getColorPresentations(document, jsonDocument, params.color, params.range);
10629 }, [], `Error while computing color presentations for ${params.textDocument.uri}`, token);
10631 connection.onFoldingRanges((params, token) => {
10632 return runner_1.runSafe(() => {
10633 const document = documents.get(params.textDocument.uri);
10635 const onRangeLimitExceeded = limitExceededWarnings.onResultLimitExceeded(document.uri, foldingRangeLimit, 'folding ranges');
10636 return languageService.getFoldingRanges(document, { rangeLimit: foldingRangeLimit, onRangeLimitExceeded });
10639 }, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token);
10641 connection.onSelectionRanges((params, token) => {
10642 return runner_1.runSafe(() => {
10643 const document = documents.get(params.textDocument.uri);
10645 const jsonDocument = getJSONDocument(document);
10646 return languageService.getSelectionRanges(document, params.positions, jsonDocument);
10649 }, [], `Error while computing selection ranges for ${params.textDocument.uri}`, token);
10651 connection.onDefinition((params, token) => {
10652 return runner_1.runSafeAsync(() => __awaiter(this, void 0, void 0, function* () {
10653 const document = documents.get(params.textDocument.uri);
10655 const jsonDocument = getJSONDocument(document);
10656 return languageService.findDefinition(document, params.position, jsonDocument);
10659 }), [], `Error while computing definitions for ${params.textDocument.uri}`, token);
10661 // Listen on the connection
10662 connection.listen();
10664 exports.startServer = startServer;
10669 /***/ (function(module, __webpack_exports__, __webpack_require__) {
10672 __webpack_require__.r(__webpack_exports__);
10673 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLanguageService", function() { return getLanguageService; });
10674 /* harmony import */ var _services_jsonCompletion__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(91);
10675 /* harmony import */ var _services_jsonHover__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(104);
10676 /* harmony import */ var _services_jsonValidation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(105);
10677 /* harmony import */ var _services_jsonDocumentSymbols__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(107);
10678 /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(92);
10679 /* harmony import */ var _services_configuration__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(109);
10680 /* harmony import */ var _services_jsonSchemaService__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(106);
10681 /* harmony import */ var _services_jsonFolding__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(110);
10682 /* harmony import */ var _services_jsonSelectionRanges__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(111);
10683 /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(93);
10684 /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(99);
10685 /* harmony import */ var _services_jsonDefinition__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(112);
10686 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["TextDocument"]; });
10688 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["Range"]; });
10690 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["TextEdit"]; });
10692 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["Color"]; });
10694 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["ColorInformation"]; });
10696 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["ColorPresentation"]; });
10698 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["FoldingRange"]; });
10700 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["FoldingRangeKind"]; });
10702 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["SelectionRange"]; });
10704 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["Diagnostic"]; });
10706 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["DiagnosticSeverity"]; });
10708 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["CompletionItem"]; });
10710 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["CompletionItemKind"]; });
10712 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["CompletionList"]; });
10714 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["Position"]; });
10716 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["InsertTextFormat"]; });
10718 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["MarkupContent"]; });
10720 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["MarkupKind"]; });
10722 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["SymbolInformation"]; });
10724 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["SymbolKind"]; });
10726 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["DocumentSymbol"]; });
10728 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["Location"]; });
10730 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["Hover"]; });
10732 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["MarkedString"]; });
10734 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["FormattingOptions"]; });
10736 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ErrorCode", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["ErrorCode"]; });
10738 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClientCapabilities", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["ClientCapabilities"]; });
10740 /*---------------------------------------------------------------------------------------------
10741 * Copyright (c) Microsoft Corporation. All rights reserved.
10742 * Licensed under the MIT License. See License.txt in the project root for license information.
10743 *--------------------------------------------------------------------------------------------*/
10757 function getLanguageService(params) {
10758 var promise = params.promiseConstructor || Promise;
10759 var jsonSchemaService = new _services_jsonSchemaService__WEBPACK_IMPORTED_MODULE_6__["JSONSchemaService"](params.schemaRequestService, params.workspaceContext, promise);
10760 jsonSchemaService.setSchemaContributions(_services_configuration__WEBPACK_IMPORTED_MODULE_5__["schemaContributions"]);
10761 var jsonCompletion = new _services_jsonCompletion__WEBPACK_IMPORTED_MODULE_0__["JSONCompletion"](jsonSchemaService, params.contributions, promise, params.clientCapabilities);
10762 var jsonHover = new _services_jsonHover__WEBPACK_IMPORTED_MODULE_1__["JSONHover"](jsonSchemaService, params.contributions, promise);
10763 var jsonDocumentSymbols = new _services_jsonDocumentSymbols__WEBPACK_IMPORTED_MODULE_3__["JSONDocumentSymbols"](jsonSchemaService);
10764 var jsonValidation = new _services_jsonValidation__WEBPACK_IMPORTED_MODULE_2__["JSONValidation"](jsonSchemaService, promise);
10766 configure: function (settings) {
10767 jsonSchemaService.clearExternalSchemas();
10768 if (settings.schemas) {
10769 settings.schemas.forEach(function (settings) {
10770 jsonSchemaService.registerExternalSchema(settings.uri, settings.fileMatch, settings.schema);
10773 jsonValidation.configure(settings);
10775 resetSchema: function (uri) { return jsonSchemaService.onResourceChange(uri); },
10776 doValidation: jsonValidation.doValidation.bind(jsonValidation),
10777 parseJSONDocument: function (document) { return Object(_parser_jsonParser__WEBPACK_IMPORTED_MODULE_4__["parse"])(document, { collectComments: true }); },
10778 newJSONDocument: function (root, diagnostics) { return Object(_parser_jsonParser__WEBPACK_IMPORTED_MODULE_4__["newJSONDocument"])(root, diagnostics); },
10779 getMatchingSchemas: jsonSchemaService.getMatchingSchemas.bind(jsonSchemaService),
10780 doResolve: jsonCompletion.doResolve.bind(jsonCompletion),
10781 doComplete: jsonCompletion.doComplete.bind(jsonCompletion),
10782 findDocumentSymbols: jsonDocumentSymbols.findDocumentSymbols.bind(jsonDocumentSymbols),
10783 findDocumentSymbols2: jsonDocumentSymbols.findDocumentSymbols2.bind(jsonDocumentSymbols),
10784 findColorSymbols: function (d, s) { return jsonDocumentSymbols.findDocumentColors(d, s).then(function (s) { return s.map(function (s) { return s.range; }); }); },
10785 findDocumentColors: jsonDocumentSymbols.findDocumentColors.bind(jsonDocumentSymbols),
10786 getColorPresentations: jsonDocumentSymbols.getColorPresentations.bind(jsonDocumentSymbols),
10787 doHover: jsonHover.doHover.bind(jsonHover),
10788 getFoldingRanges: _services_jsonFolding__WEBPACK_IMPORTED_MODULE_7__["getFoldingRanges"],
10789 getSelectionRanges: _services_jsonSelectionRanges__WEBPACK_IMPORTED_MODULE_8__["getSelectionRanges"],
10790 findDefinition: _services_jsonDefinition__WEBPACK_IMPORTED_MODULE_11__["findDefinition"],
10791 format: function (d, r, o) {
10792 var range = undefined;
10794 var offset = d.offsetAt(r.start);
10795 var length = d.offsetAt(r.end) - offset;
10796 range = { offset: offset, length: length };
10798 var options = { tabSize: o ? o.tabSize : 4, insertSpaces: o ? o.insertSpaces : true, eol: '\n' };
10799 return Object(jsonc_parser__WEBPACK_IMPORTED_MODULE_9__["format"])(d.getText(), range, options).map(function (e) {
10800 return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["TextEdit"].replace(_jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_10__["Range"].create(d.positionAt(e.offset), d.positionAt(e.offset + e.length)), e.content);
10809 /***/ (function(module, __webpack_exports__, __webpack_require__) {
10812 __webpack_require__.r(__webpack_exports__);
10813 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONCompletion", function() { return JSONCompletion; });
10814 /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(92);
10815 /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(93);
10816 /* harmony import */ var _utils_json__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(102);
10817 /* harmony import */ var _utils_strings__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(103);
10818 /* harmony import */ var _utils_objects__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(98);
10819 /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(99);
10820 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(101);
10821 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_6__);
10822 /*---------------------------------------------------------------------------------------------
10823 * Copyright (c) Microsoft Corporation. All rights reserved.
10824 * Licensed under the MIT License. See License.txt in the project root for license information.
10825 *--------------------------------------------------------------------------------------------*/
10833 var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_6__["loadMessageBundle"]();
10834 var valueCommitCharacters = [',', '}', ']'];
10835 var propertyCommitCharacters = [':'];
10836 var JSONCompletion = /** @class */ (function () {
10837 function JSONCompletion(schemaService, contributions, promiseConstructor, clientCapabilities) {
10838 if (contributions === void 0) { contributions = []; }
10839 if (promiseConstructor === void 0) { promiseConstructor = Promise; }
10840 if (clientCapabilities === void 0) { clientCapabilities = {}; }
10841 this.schemaService = schemaService;
10842 this.contributions = contributions;
10843 this.promiseConstructor = promiseConstructor;
10844 this.clientCapabilities = clientCapabilities;
10846 JSONCompletion.prototype.doResolve = function (item) {
10847 for (var i = this.contributions.length - 1; i >= 0; i--) {
10848 var resolveCompletion = this.contributions[i].resolveCompletion;
10849 if (resolveCompletion) {
10850 var resolver = resolveCompletion(item);
10856 return this.promiseConstructor.resolve(item);
10858 JSONCompletion.prototype.doComplete = function (document, position, doc) {
10862 isIncomplete: false
10864 var text = document.getText();
10865 var offset = document.offsetAt(position);
10866 var node = doc.getNodeFromOffset(offset, true);
10867 if (this.isInComment(document, node ? node.offset : 0, offset)) {
10868 return Promise.resolve(result);
10870 if (node && (offset === node.offset + node.length) && offset > 0) {
10871 var ch = text[offset - 1];
10872 if (node.type === 'object' && ch === '}' || node.type === 'array' && ch === ']') {
10874 node = node.parent;
10877 var currentWord = this.getCurrentWord(document, offset);
10878 var overwriteRange;
10879 if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
10880 overwriteRange = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["Range"].create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
10883 var overwriteStart = offset - currentWord.length;
10884 if (overwriteStart > 0 && text[overwriteStart - 1] === '"') {
10887 overwriteRange = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["Range"].create(document.positionAt(overwriteStart), position);
10889 var supportsCommitCharacters = false; //this.doesSupportsCommitCharacters(); disabled for now, waiting for new API: https://github.com/microsoft/vscode/issues/42544
10892 add: function (suggestion) {
10893 var label = suggestion.label;
10894 var existing = proposed[label];
10896 label = label.replace(/[\n]/g, '↵');
10897 if (label.length > 60) {
10898 var shortendedLabel = label.substr(0, 57).trim() + '...';
10899 if (!proposed[shortendedLabel]) {
10900 label = shortendedLabel;
10903 if (overwriteRange && suggestion.insertText !== undefined) {
10904 suggestion.textEdit = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["TextEdit"].replace(overwriteRange, suggestion.insertText);
10906 if (supportsCommitCharacters) {
10907 suggestion.commitCharacters = suggestion.kind === _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property ? propertyCommitCharacters : valueCommitCharacters;
10909 suggestion.label = label;
10910 proposed[label] = suggestion;
10911 result.items.push(suggestion);
10913 else if (!existing.documentation) {
10914 existing.documentation = suggestion.documentation;
10917 setAsIncomplete: function () {
10918 result.isIncomplete = true;
10920 error: function (message) {
10921 console.error(message);
10923 log: function (message) {
10924 console.log(message);
10926 getNumberOfProposals: function () {
10927 return result.items.length;
10930 return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
10931 var collectionPromises = [];
10932 var addValue = true;
10933 var currentKey = '';
10934 var currentProperty = undefined;
10936 if (node.type === 'string') {
10937 var parent = node.parent;
10938 if (parent && parent.type === 'property' && parent.keyNode === node) {
10939 addValue = !parent.valueNode;
10940 currentProperty = parent;
10941 currentKey = text.substr(node.offset + 1, node.length - 2);
10943 node = parent.parent;
10948 // proposals for properties
10949 if (node && node.type === 'object') {
10950 // don't suggest keys when the cursor is just before the opening curly brace
10951 if (node.offset === offset) {
10954 // don't suggest properties that are already present
10955 var properties = node.properties;
10956 properties.forEach(function (p) {
10957 if (!currentProperty || currentProperty !== p) {
10958 proposed[p.keyNode.value] = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["CompletionItem"].create('__');
10961 var separatorAfter_1 = '';
10963 separatorAfter_1 = _this.evaluateSeparatorAfter(document, document.offsetAt(overwriteRange.end));
10966 // property proposals with schema
10967 _this.getPropertyCompletions(schema, doc, node, addValue, separatorAfter_1, collector);
10970 // property proposals without schema
10971 _this.getSchemaLessPropertyCompletions(doc, node, currentKey, collector);
10973 var location_1 = _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodePath"](node);
10974 _this.contributions.forEach(function (contribution) {
10975 var collectPromise = contribution.collectPropertyCompletions(document.uri, location_1, currentWord, addValue, separatorAfter_1 === '', collector);
10976 if (collectPromise) {
10977 collectionPromises.push(collectPromise);
10980 if ((!schema && currentWord.length > 0 && text.charAt(offset - currentWord.length - 1) !== '"')) {
10982 kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property,
10983 label: _this.getLabelForValue(currentWord),
10984 insertText: _this.getInsertTextForProperty(currentWord, undefined, false, separatorAfter_1),
10985 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet, documentation: '',
10987 collector.setAsIncomplete();
10990 // proposals for values
10993 // value proposals with schema
10994 _this.getValueCompletions(schema, doc, node, offset, document, collector, types);
10997 // value proposals without schema
10998 _this.getSchemaLessValueCompletions(doc, node, offset, document, collector);
11000 if (_this.contributions.length > 0) {
11001 _this.getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises);
11003 return _this.promiseConstructor.all(collectionPromises).then(function () {
11004 if (collector.getNumberOfProposals() === 0) {
11005 var offsetForSeparator = offset;
11006 if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
11007 offsetForSeparator = node.offset + node.length;
11009 var separatorAfter = _this.evaluateSeparatorAfter(document, offsetForSeparator);
11010 _this.addFillerValueCompletions(types, separatorAfter, collector);
11016 JSONCompletion.prototype.getPropertyCompletions = function (schema, doc, node, addValue, separatorAfter, collector) {
11018 var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
11019 matchingSchemas.forEach(function (s) {
11020 if (s.node === node && !s.inverted) {
11021 var schemaProperties_1 = s.schema.properties;
11022 if (schemaProperties_1) {
11023 Object.keys(schemaProperties_1).forEach(function (key) {
11024 var propertySchema = schemaProperties_1[key];
11025 if (typeof propertySchema === 'object' && !propertySchema.deprecationMessage && !propertySchema.doNotSuggest) {
11027 kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property,
11029 insertText: _this.getInsertTextForProperty(key, propertySchema, addValue, separatorAfter),
11030 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
11031 filterText: _this.getFilterTextForValue(key),
11032 documentation: _this.fromMarkup(propertySchema.markdownDescription) || propertySchema.description || '',
11034 if (propertySchema.suggestSortText !== undefined) {
11035 proposal.sortText = propertySchema.suggestSortText;
11037 if (proposal.insertText && Object(_utils_strings__WEBPACK_IMPORTED_MODULE_3__["endsWith"])(proposal.insertText, "$1" + separatorAfter)) {
11038 proposal.command = {
11040 command: 'editor.action.triggerSuggest'
11043 collector.add(proposal);
11047 var schemaPropertyNames_1 = s.schema.propertyNames;
11048 if (typeof schemaPropertyNames_1 === 'object' && !schemaPropertyNames_1.deprecationMessage && !schemaPropertyNames_1.doNotSuggest) {
11049 var propertyNameCompletionItem = function (name, enumDescription) {
11050 if (enumDescription === void 0) { enumDescription = undefined; }
11052 kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property,
11054 insertText: _this.getInsertTextForProperty(name, undefined, addValue, separatorAfter),
11055 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
11056 filterText: _this.getFilterTextForValue(name),
11057 documentation: enumDescription || _this.fromMarkup(schemaPropertyNames_1.markdownDescription) || schemaPropertyNames_1.description || '',
11059 if (schemaPropertyNames_1.suggestSortText !== undefined) {
11060 proposal.sortText = schemaPropertyNames_1.suggestSortText;
11062 if (proposal.insertText && Object(_utils_strings__WEBPACK_IMPORTED_MODULE_3__["endsWith"])(proposal.insertText, "$1" + separatorAfter)) {
11063 proposal.command = {
11065 command: 'editor.action.triggerSuggest'
11068 collector.add(proposal);
11070 if (schemaPropertyNames_1.enum) {
11071 for (var i = 0; i < schemaPropertyNames_1.enum.length; i++) {
11072 var enumDescription = undefined;
11073 if (schemaPropertyNames_1.markdownEnumDescriptions && i < schemaPropertyNames_1.markdownEnumDescriptions.length) {
11074 enumDescription = _this.fromMarkup(schemaPropertyNames_1.markdownEnumDescriptions[i]);
11076 else if (schemaPropertyNames_1.enumDescriptions && i < schemaPropertyNames_1.enumDescriptions.length) {
11077 enumDescription = schemaPropertyNames_1.enumDescriptions[i];
11079 propertyNameCompletionItem(schemaPropertyNames_1.enum[i], enumDescription);
11082 if (schemaPropertyNames_1.const) {
11083 propertyNameCompletionItem(schemaPropertyNames_1.const);
11089 JSONCompletion.prototype.getSchemaLessPropertyCompletions = function (doc, node, currentKey, collector) {
11091 var collectCompletionsForSimilarObject = function (obj) {
11092 obj.properties.forEach(function (p) {
11093 var key = p.keyNode.value;
11095 kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property,
11097 insertText: _this.getInsertTextForValue(key, ''),
11098 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
11099 filterText: _this.getFilterTextForValue(key),
11105 if (node.parent.type === 'property') {
11106 // if the object is a property value, check the tree for other objects that hang under a property of the same name
11107 var parentKey_1 = node.parent.keyNode.value;
11108 doc.visit(function (n) {
11109 if (n.type === 'property' && n !== node.parent && n.keyNode.value === parentKey_1 && n.valueNode && n.valueNode.type === 'object') {
11110 collectCompletionsForSimilarObject(n.valueNode);
11115 else if (node.parent.type === 'array') {
11116 // if the object is in an array, use all other array elements as similar objects
11117 node.parent.items.forEach(function (n) {
11118 if (n.type === 'object' && n !== node) {
11119 collectCompletionsForSimilarObject(n);
11124 else if (node.type === 'object') {
11126 kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property,
11128 insertText: this.getInsertTextForProperty('$schema', undefined, true, ''),
11129 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet, documentation: '',
11130 filterText: this.getFilterTextForValue("$schema")
11134 JSONCompletion.prototype.getSchemaLessValueCompletions = function (doc, node, offset, document, collector) {
11136 var offsetForSeparator = offset;
11137 if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
11138 offsetForSeparator = node.offset + node.length;
11139 node = node.parent;
11143 kind: this.getSuggestionKind('object'),
11144 label: 'Empty object',
11145 insertText: this.getInsertTextForValue({}, ''),
11146 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
11150 kind: this.getSuggestionKind('array'),
11151 label: 'Empty array',
11152 insertText: this.getInsertTextForValue([], ''),
11153 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
11158 var separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
11159 var collectSuggestionsForValues = function (value) {
11160 if (value.parent && !_parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["contains"](value.parent, offset, true)) {
11162 kind: _this.getSuggestionKind(value.type),
11163 label: _this.getLabelTextForMatchingNode(value, document),
11164 insertText: _this.getInsertTextForMatchingNode(value, document, separatorAfter),
11165 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet, documentation: ''
11168 if (value.type === 'boolean') {
11169 _this.addBooleanValueCompletion(!value.value, separatorAfter, collector);
11172 if (node.type === 'property') {
11173 if (offset > (node.colonOffset || 0)) {
11174 var valueNode = node.valueNode;
11175 if (valueNode && (offset > (valueNode.offset + valueNode.length) || valueNode.type === 'object' || valueNode.type === 'array')) {
11178 // suggest values at the same key
11179 var parentKey_2 = node.keyNode.value;
11180 doc.visit(function (n) {
11181 if (n.type === 'property' && n.keyNode.value === parentKey_2 && n.valueNode) {
11182 collectSuggestionsForValues(n.valueNode);
11186 if (parentKey_2 === '$schema' && node.parent && !node.parent.parent) {
11187 this.addDollarSchemaCompletions(separatorAfter, collector);
11191 if (node.type === 'array') {
11192 if (node.parent && node.parent.type === 'property') {
11193 // suggest items of an array at the same key
11194 var parentKey_3 = node.parent.keyNode.value;
11195 doc.visit(function (n) {
11196 if (n.type === 'property' && n.keyNode.value === parentKey_3 && n.valueNode && n.valueNode.type === 'array') {
11197 n.valueNode.items.forEach(collectSuggestionsForValues);
11203 // suggest items in the same array
11204 node.items.forEach(collectSuggestionsForValues);
11208 JSONCompletion.prototype.getValueCompletions = function (schema, doc, node, offset, document, collector, types) {
11209 var offsetForSeparator = offset;
11210 var parentKey = undefined;
11211 var valueNode = undefined;
11212 if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
11213 offsetForSeparator = node.offset + node.length;
11215 node = node.parent;
11218 this.addSchemaValueCompletions(schema.schema, '', collector, types);
11221 if ((node.type === 'property') && offset > (node.colonOffset || 0)) {
11222 var valueNode_1 = node.valueNode;
11223 if (valueNode_1 && offset > (valueNode_1.offset + valueNode_1.length)) {
11224 return; // we are past the value node
11226 parentKey = node.keyNode.value;
11227 node = node.parent;
11229 if (node && (parentKey !== undefined || node.type === 'array')) {
11230 var separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
11231 var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset, valueNode);
11232 for (var _i = 0, matchingSchemas_1 = matchingSchemas; _i < matchingSchemas_1.length; _i++) {
11233 var s = matchingSchemas_1[_i];
11234 if (s.node === node && !s.inverted && s.schema) {
11235 if (node.type === 'array' && s.schema.items) {
11236 if (Array.isArray(s.schema.items)) {
11237 var index = this.findItemAtOffset(node, document, offset);
11238 if (index < s.schema.items.length) {
11239 this.addSchemaValueCompletions(s.schema.items[index], separatorAfter, collector, types);
11243 this.addSchemaValueCompletions(s.schema.items, separatorAfter, collector, types);
11246 if (parentKey !== undefined) {
11247 var propertyMatched = false;
11248 if (s.schema.properties) {
11249 var propertySchema = s.schema.properties[parentKey];
11250 if (propertySchema) {
11251 propertyMatched = true;
11252 this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);
11255 if (s.schema.patternProperties && !propertyMatched) {
11256 for (var _a = 0, _b = Object.keys(s.schema.patternProperties); _a < _b.length; _a++) {
11257 var pattern = _b[_a];
11258 var regex = new RegExp(pattern);
11259 if (regex.test(parentKey)) {
11260 propertyMatched = true;
11261 var propertySchema = s.schema.patternProperties[pattern];
11262 this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);
11266 if (s.schema.additionalProperties && !propertyMatched) {
11267 var propertySchema = s.schema.additionalProperties;
11268 this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);
11273 if (parentKey === '$schema' && !node.parent) {
11274 this.addDollarSchemaCompletions(separatorAfter, collector);
11276 if (types['boolean']) {
11277 this.addBooleanValueCompletion(true, separatorAfter, collector);
11278 this.addBooleanValueCompletion(false, separatorAfter, collector);
11280 if (types['null']) {
11281 this.addNullValueCompletion(separatorAfter, collector);
11285 JSONCompletion.prototype.getContributedValueCompletions = function (doc, node, offset, document, collector, collectionPromises) {
11287 this.contributions.forEach(function (contribution) {
11288 var collectPromise = contribution.collectDefaultCompletions(document.uri, collector);
11289 if (collectPromise) {
11290 collectionPromises.push(collectPromise);
11295 if (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null') {
11296 node = node.parent;
11298 if (node && (node.type === 'property') && offset > (node.colonOffset || 0)) {
11299 var parentKey_4 = node.keyNode.value;
11300 var valueNode = node.valueNode;
11301 if ((!valueNode || offset <= (valueNode.offset + valueNode.length)) && node.parent) {
11302 var location_2 = _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodePath"](node.parent);
11303 this.contributions.forEach(function (contribution) {
11304 var collectPromise = contribution.collectValueCompletions(document.uri, location_2, parentKey_4, collector);
11305 if (collectPromise) {
11306 collectionPromises.push(collectPromise);
11313 JSONCompletion.prototype.addSchemaValueCompletions = function (schema, separatorAfter, collector, types) {
11315 if (typeof schema === 'object') {
11316 this.addEnumValueCompletions(schema, separatorAfter, collector);
11317 this.addDefaultValueCompletions(schema, separatorAfter, collector);
11318 this.collectTypes(schema, types);
11319 if (Array.isArray(schema.allOf)) {
11320 schema.allOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
11322 if (Array.isArray(schema.anyOf)) {
11323 schema.anyOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
11325 if (Array.isArray(schema.oneOf)) {
11326 schema.oneOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
11330 JSONCompletion.prototype.addDefaultValueCompletions = function (schema, separatorAfter, collector, arrayDepth) {
11332 if (arrayDepth === void 0) { arrayDepth = 0; }
11333 var hasProposals = false;
11334 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(schema.default)) {
11335 var type = schema.type;
11336 var value = schema.default;
11337 for (var i = arrayDepth; i > 0; i--) {
11342 kind: this.getSuggestionKind(type),
11343 label: this.getLabelForValue(value),
11344 insertText: this.getInsertTextForValue(value, separatorAfter),
11345 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
11346 detail: localize('json.suggest.default', 'Default value')
11348 hasProposals = true;
11350 if (Array.isArray(schema.examples)) {
11351 schema.examples.forEach(function (example) {
11352 var type = schema.type;
11353 var value = example;
11354 for (var i = arrayDepth; i > 0; i--) {
11359 kind: _this.getSuggestionKind(type),
11360 label: _this.getLabelForValue(value),
11361 insertText: _this.getInsertTextForValue(value, separatorAfter),
11362 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet
11364 hasProposals = true;
11367 if (Array.isArray(schema.defaultSnippets)) {
11368 schema.defaultSnippets.forEach(function (s) {
11369 var type = schema.type;
11370 var value = s.body;
11371 var label = s.label;
11374 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(value)) {
11375 var type_1 = schema.type;
11376 for (var i = arrayDepth; i > 0; i--) {
11380 insertText = _this.getInsertTextForSnippetValue(value, separatorAfter);
11381 filterText = _this.getFilterTextForSnippetValue(value);
11382 label = label || _this.getLabelForSnippetValue(value);
11384 else if (typeof s.bodyText === 'string') {
11385 var prefix = '', suffix = '', indent = '';
11386 for (var i = arrayDepth; i > 0; i--) {
11387 prefix = prefix + indent + '[\n';
11388 suffix = suffix + '\n' + indent + ']';
11392 insertText = prefix + indent + s.bodyText.split('\n').join('\n' + indent) + suffix + separatorAfter;
11393 label = label || insertText,
11394 filterText = insertText.replace(/[\n]/g, ''); // remove new lines
11400 kind: _this.getSuggestionKind(type),
11402 documentation: _this.fromMarkup(s.markdownDescription) || s.description,
11403 insertText: insertText,
11404 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
11405 filterText: filterText
11407 hasProposals = true;
11410 if (!hasProposals && typeof schema.items === 'object' && !Array.isArray(schema.items) && arrayDepth < 5 /* beware of recursion */) {
11411 this.addDefaultValueCompletions(schema.items, separatorAfter, collector, arrayDepth + 1);
11414 JSONCompletion.prototype.addEnumValueCompletions = function (schema, separatorAfter, collector) {
11415 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(schema.const)) {
11417 kind: this.getSuggestionKind(schema.type),
11418 label: this.getLabelForValue(schema.const),
11419 insertText: this.getInsertTextForValue(schema.const, separatorAfter),
11420 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
11421 documentation: this.fromMarkup(schema.markdownDescription) || schema.description
11424 if (Array.isArray(schema.enum)) {
11425 for (var i = 0, length = schema.enum.length; i < length; i++) {
11426 var enm = schema.enum[i];
11427 var documentation = this.fromMarkup(schema.markdownDescription) || schema.description;
11428 if (schema.markdownEnumDescriptions && i < schema.markdownEnumDescriptions.length && this.doesSupportMarkdown()) {
11429 documentation = this.fromMarkup(schema.markdownEnumDescriptions[i]);
11431 else if (schema.enumDescriptions && i < schema.enumDescriptions.length) {
11432 documentation = schema.enumDescriptions[i];
11435 kind: this.getSuggestionKind(schema.type),
11436 label: this.getLabelForValue(enm),
11437 insertText: this.getInsertTextForValue(enm, separatorAfter),
11438 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
11439 documentation: documentation
11444 JSONCompletion.prototype.collectTypes = function (schema, types) {
11445 if (Array.isArray(schema.enum) || Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(schema.const)) {
11448 var type = schema.type;
11449 if (Array.isArray(type)) {
11450 type.forEach(function (t) { return types[t] = true; });
11453 types[type] = true;
11456 JSONCompletion.prototype.addFillerValueCompletions = function (types, separatorAfter, collector) {
11457 if (types['object']) {
11459 kind: this.getSuggestionKind('object'),
11461 insertText: this.getInsertTextForGuessedValue({}, separatorAfter),
11462 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
11463 detail: localize('defaults.object', 'New object'),
11467 if (types['array']) {
11469 kind: this.getSuggestionKind('array'),
11471 insertText: this.getInsertTextForGuessedValue([], separatorAfter),
11472 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
11473 detail: localize('defaults.array', 'New array'),
11478 JSONCompletion.prototype.addBooleanValueCompletion = function (value, separatorAfter, collector) {
11480 kind: this.getSuggestionKind('boolean'),
11481 label: value ? 'true' : 'false',
11482 insertText: this.getInsertTextForValue(value, separatorAfter),
11483 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
11487 JSONCompletion.prototype.addNullValueCompletion = function (separatorAfter, collector) {
11489 kind: this.getSuggestionKind('null'),
11491 insertText: 'null' + separatorAfter,
11492 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
11496 JSONCompletion.prototype.addDollarSchemaCompletions = function (separatorAfter, collector) {
11498 var schemaIds = this.schemaService.getRegisteredSchemaIds(function (schema) { return schema === 'http' || schema === 'https'; });
11499 schemaIds.forEach(function (schemaId) { return collector.add({
11500 kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Module,
11501 label: _this.getLabelForValue(schemaId),
11502 filterText: _this.getFilterTextForValue(schemaId),
11503 insertText: _this.getInsertTextForValue(schemaId, separatorAfter),
11504 insertTextFormat: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet, documentation: ''
11507 JSONCompletion.prototype.getLabelForValue = function (value) {
11508 return JSON.stringify(value);
11510 JSONCompletion.prototype.getFilterTextForValue = function (value) {
11511 return JSON.stringify(value);
11513 JSONCompletion.prototype.getFilterTextForSnippetValue = function (value) {
11514 return JSON.stringify(value).replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
11516 JSONCompletion.prototype.getLabelForSnippetValue = function (value) {
11517 var label = JSON.stringify(value);
11518 return label.replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
11520 JSONCompletion.prototype.getInsertTextForPlainText = function (text) {
11521 return text.replace(/[\\\$\}]/g, '\\$&'); // escape $, \ and }
11523 JSONCompletion.prototype.getInsertTextForValue = function (value, separatorAfter) {
11524 var text = JSON.stringify(value, null, '\t');
11525 if (text === '{}') {
11526 return '{$1}' + separatorAfter;
11528 else if (text === '[]') {
11529 return '[$1]' + separatorAfter;
11531 return this.getInsertTextForPlainText(text + separatorAfter);
11533 JSONCompletion.prototype.getInsertTextForSnippetValue = function (value, separatorAfter) {
11534 var replacer = function (value) {
11535 if (typeof value === 'string') {
11536 if (value[0] === '^') {
11537 return value.substr(1);
11540 return JSON.stringify(value);
11542 return Object(_utils_json__WEBPACK_IMPORTED_MODULE_2__["stringifyObject"])(value, '', replacer) + separatorAfter;
11544 JSONCompletion.prototype.getInsertTextForGuessedValue = function (value, separatorAfter) {
11545 switch (typeof value) {
11547 if (value === null) {
11548 return '${1:null}' + separatorAfter;
11550 return this.getInsertTextForValue(value, separatorAfter);
11552 var snippetValue = JSON.stringify(value);
11553 snippetValue = snippetValue.substr(1, snippetValue.length - 2); // remove quotes
11554 snippetValue = this.getInsertTextForPlainText(snippetValue); // escape \ and }
11555 return '"${1:' + snippetValue + '}"' + separatorAfter;
11558 return '${1:' + JSON.stringify(value) + '}' + separatorAfter;
11560 return this.getInsertTextForValue(value, separatorAfter);
11562 JSONCompletion.prototype.getSuggestionKind = function (type) {
11563 if (Array.isArray(type)) {
11565 type = array.length > 0 ? array[0] : undefined;
11568 return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Value;
11571 case 'string': return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Value;
11572 case 'object': return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Module;
11573 case 'property': return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property;
11574 default: return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Value;
11577 JSONCompletion.prototype.getLabelTextForMatchingNode = function (node, document) {
11578 switch (node.type) {
11584 var content = document.getText().substr(node.offset, node.length);
11588 JSONCompletion.prototype.getInsertTextForMatchingNode = function (node, document, separatorAfter) {
11589 switch (node.type) {
11591 return this.getInsertTextForValue([], separatorAfter);
11593 return this.getInsertTextForValue({}, separatorAfter);
11595 var content = document.getText().substr(node.offset, node.length) + separatorAfter;
11596 return this.getInsertTextForPlainText(content);
11599 JSONCompletion.prototype.getInsertTextForProperty = function (key, propertySchema, addValue, separatorAfter) {
11600 var propertyText = this.getInsertTextForValue(key, '');
11602 return propertyText;
11604 var resultText = propertyText + ': ';
11606 var nValueProposals = 0;
11607 if (propertySchema) {
11608 if (Array.isArray(propertySchema.defaultSnippets)) {
11609 if (propertySchema.defaultSnippets.length === 1) {
11610 var body = propertySchema.defaultSnippets[0].body;
11611 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(body)) {
11612 value = this.getInsertTextForSnippetValue(body, '');
11615 nValueProposals += propertySchema.defaultSnippets.length;
11617 if (propertySchema.enum) {
11618 if (!value && propertySchema.enum.length === 1) {
11619 value = this.getInsertTextForGuessedValue(propertySchema.enum[0], '');
11621 nValueProposals += propertySchema.enum.length;
11623 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(propertySchema.default)) {
11625 value = this.getInsertTextForGuessedValue(propertySchema.default, '');
11629 if (Array.isArray(propertySchema.examples) && propertySchema.examples.length) {
11631 value = this.getInsertTextForGuessedValue(propertySchema.examples[0], '');
11633 nValueProposals += propertySchema.examples.length;
11635 if (nValueProposals === 0) {
11636 var type = Array.isArray(propertySchema.type) ? propertySchema.type[0] : propertySchema.type;
11638 if (propertySchema.properties) {
11641 else if (propertySchema.items) {
11663 value = '${1:null}';
11666 return propertyText;
11670 if (!value || nValueProposals > 1) {
11673 return resultText + value + separatorAfter;
11675 JSONCompletion.prototype.getCurrentWord = function (document, offset) {
11676 var i = offset - 1;
11677 var text = document.getText();
11678 while (i >= 0 && ' \t\n\r\v":{[,]}'.indexOf(text.charAt(i)) === -1) {
11681 return text.substring(i + 1, offset);
11683 JSONCompletion.prototype.evaluateSeparatorAfter = function (document, offset) {
11684 var scanner = jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"](document.getText(), true);
11685 scanner.setPosition(offset);
11686 var token = scanner.scan();
11688 case 5 /* CommaToken */:
11689 case 2 /* CloseBraceToken */:
11690 case 4 /* CloseBracketToken */:
11697 JSONCompletion.prototype.findItemAtOffset = function (node, document, offset) {
11698 var scanner = jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"](document.getText(), true);
11699 var children = node.items;
11700 for (var i = children.length - 1; i >= 0; i--) {
11701 var child = children[i];
11702 if (offset > child.offset + child.length) {
11703 scanner.setPosition(child.offset + child.length);
11704 var token = scanner.scan();
11705 if (token === 5 /* CommaToken */ && offset >= scanner.getTokenOffset() + scanner.getTokenLength()) {
11710 else if (offset >= child.offset) {
11716 JSONCompletion.prototype.isInComment = function (document, start, offset) {
11717 var scanner = jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"](document.getText(), false);
11718 scanner.setPosition(start);
11719 var token = scanner.scan();
11720 while (token !== 17 /* EOF */ && (scanner.getTokenOffset() + scanner.getTokenLength() < offset)) {
11721 token = scanner.scan();
11723 return (token === 12 /* LineCommentTrivia */ || token === 13 /* BlockCommentTrivia */) && scanner.getTokenOffset() <= offset;
11725 JSONCompletion.prototype.fromMarkup = function (markupString) {
11726 if (markupString && this.doesSupportMarkdown()) {
11728 kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["MarkupKind"].Markdown,
11729 value: markupString
11734 JSONCompletion.prototype.doesSupportMarkdown = function () {
11735 if (!Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(this.supportsMarkdown)) {
11736 var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
11737 this.supportsMarkdown = completion && completion.completionItem && Array.isArray(completion.completionItem.documentationFormat) && completion.completionItem.documentationFormat.indexOf(_jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_5__["MarkupKind"].Markdown) !== -1;
11739 return this.supportsMarkdown;
11741 JSONCompletion.prototype.doesSupportsCommitCharacters = function () {
11742 if (!Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(this.supportsCommitCharacters)) {
11743 var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
11744 this.supportsCommitCharacters = completion && completion.completionItem && !!completion.completionItem.commitCharactersSupport;
11746 return this.supportsCommitCharacters;
11748 return JSONCompletion;
11755 /***/ (function(module, __webpack_exports__, __webpack_require__) {
11758 __webpack_require__.r(__webpack_exports__);
11759 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ASTNodeImpl", function() { return ASTNodeImpl; });
11760 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NullASTNodeImpl", function() { return NullASTNodeImpl; });
11761 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BooleanASTNodeImpl", function() { return BooleanASTNodeImpl; });
11762 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrayASTNodeImpl", function() { return ArrayASTNodeImpl; });
11763 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NumberASTNodeImpl", function() { return NumberASTNodeImpl; });
11764 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringASTNodeImpl", function() { return StringASTNodeImpl; });
11765 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PropertyASTNodeImpl", function() { return PropertyASTNodeImpl; });
11766 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObjectASTNodeImpl", function() { return ObjectASTNodeImpl; });
11767 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asSchema", function() { return asSchema; });
11768 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EnumMatch", function() { return EnumMatch; });
11769 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ValidationResult", function() { return ValidationResult; });
11770 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "newJSONDocument", function() { return newJSONDocument; });
11771 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; });
11772 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; });
11773 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return contains; });
11774 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONDocument", function() { return JSONDocument; });
11775 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
11776 /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(93);
11777 /* harmony import */ var _utils_objects__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(98);
11778 /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(99);
11779 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(101);
11780 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_3__);
11781 /*---------------------------------------------------------------------------------------------
11782 * Copyright (c) Microsoft Corporation. All rights reserved.
11783 * Licensed under the MIT License. See License.txt in the project root for license information.
11784 *--------------------------------------------------------------------------------------------*/
11785 var __extends = (undefined && undefined.__extends) || (function () {
11786 var extendStatics = function (d, b) {
11787 extendStatics = Object.setPrototypeOf ||
11788 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11789 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11790 return extendStatics(d, b);
11792 return function (d, b) {
11793 extendStatics(d, b);
11794 function __() { this.constructor = d; }
11795 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11802 var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_3__["loadMessageBundle"]();
11804 'color-hex': { errorMessage: localize('colorHexFormatWarning', 'Invalid color format. Use #RGB, #RGBA, #RRGGBB or #RRGGBBAA.'), pattern: /^#([0-9A-Fa-f]{3,4}|([0-9A-Fa-f]{2}){3,4})$/ },
11805 'date-time': { errorMessage: localize('dateTimeFormatWarning', 'String is not a RFC3339 date-time.'), pattern: /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))$/i },
11806 'date': { errorMessage: localize('dateFormatWarning', 'String is not a RFC3339 date.'), pattern: /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/i },
11807 'time': { errorMessage: localize('timeFormatWarning', 'String is not a RFC3339 time.'), pattern: /^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))$/i },
11808 'email': { errorMessage: localize('emailFormatWarning', 'String is not an e-mail address.'), pattern: /^(([^<>()\[\]\\.,;:\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,}))$/ }
11810 var ASTNodeImpl = /** @class */ (function () {
11811 function ASTNodeImpl(parent, offset, length) {
11812 if (length === void 0) { length = 0; }
11813 this.offset = offset;
11814 this.length = length;
11815 this.parent = parent;
11817 Object.defineProperty(ASTNodeImpl.prototype, "children", {
11824 ASTNodeImpl.prototype.toString = function () {
11825 return 'type: ' + this.type + ' (' + this.offset + '/' + this.length + ')' + (this.parent ? ' parent: {' + this.parent.toString() + '}' : '');
11827 return ASTNodeImpl;
11830 var NullASTNodeImpl = /** @class */ (function (_super) {
11831 __extends(NullASTNodeImpl, _super);
11832 function NullASTNodeImpl(parent, offset) {
11833 var _this = _super.call(this, parent, offset) || this;
11834 _this.type = 'null';
11835 _this.value = null;
11838 return NullASTNodeImpl;
11841 var BooleanASTNodeImpl = /** @class */ (function (_super) {
11842 __extends(BooleanASTNodeImpl, _super);
11843 function BooleanASTNodeImpl(parent, boolValue, offset) {
11844 var _this = _super.call(this, parent, offset) || this;
11845 _this.type = 'boolean';
11846 _this.value = boolValue;
11849 return BooleanASTNodeImpl;
11852 var ArrayASTNodeImpl = /** @class */ (function (_super) {
11853 __extends(ArrayASTNodeImpl, _super);
11854 function ArrayASTNodeImpl(parent, offset) {
11855 var _this = _super.call(this, parent, offset) || this;
11856 _this.type = 'array';
11860 Object.defineProperty(ArrayASTNodeImpl.prototype, "children", {
11867 return ArrayASTNodeImpl;
11870 var NumberASTNodeImpl = /** @class */ (function (_super) {
11871 __extends(NumberASTNodeImpl, _super);
11872 function NumberASTNodeImpl(parent, offset) {
11873 var _this = _super.call(this, parent, offset) || this;
11874 _this.type = 'number';
11875 _this.isInteger = true;
11876 _this.value = Number.NaN;
11879 return NumberASTNodeImpl;
11882 var StringASTNodeImpl = /** @class */ (function (_super) {
11883 __extends(StringASTNodeImpl, _super);
11884 function StringASTNodeImpl(parent, offset, length) {
11885 var _this = _super.call(this, parent, offset, length) || this;
11886 _this.type = 'string';
11890 return StringASTNodeImpl;
11893 var PropertyASTNodeImpl = /** @class */ (function (_super) {
11894 __extends(PropertyASTNodeImpl, _super);
11895 function PropertyASTNodeImpl(parent, offset, keyNode) {
11896 var _this = _super.call(this, parent, offset) || this;
11897 _this.type = 'property';
11898 _this.colonOffset = -1;
11899 _this.keyNode = keyNode;
11902 Object.defineProperty(PropertyASTNodeImpl.prototype, "children", {
11904 return this.valueNode ? [this.keyNode, this.valueNode] : [this.keyNode];
11909 return PropertyASTNodeImpl;
11912 var ObjectASTNodeImpl = /** @class */ (function (_super) {
11913 __extends(ObjectASTNodeImpl, _super);
11914 function ObjectASTNodeImpl(parent, offset) {
11915 var _this = _super.call(this, parent, offset) || this;
11916 _this.type = 'object';
11917 _this.properties = [];
11920 Object.defineProperty(ObjectASTNodeImpl.prototype, "children", {
11922 return this.properties;
11927 return ObjectASTNodeImpl;
11930 function asSchema(schema) {
11931 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(schema)) {
11932 return schema ? {} : { "not": {} };
11937 (function (EnumMatch) {
11938 EnumMatch[EnumMatch["Key"] = 0] = "Key";
11939 EnumMatch[EnumMatch["Enum"] = 1] = "Enum";
11940 })(EnumMatch || (EnumMatch = {}));
11941 var SchemaCollector = /** @class */ (function () {
11942 function SchemaCollector(focusOffset, exclude) {
11943 if (focusOffset === void 0) { focusOffset = -1; }
11944 this.focusOffset = focusOffset;
11945 this.exclude = exclude;
11948 SchemaCollector.prototype.add = function (schema) {
11949 this.schemas.push(schema);
11951 SchemaCollector.prototype.merge = function (other) {
11952 Array.prototype.push.apply(this.schemas, other.schemas);
11954 SchemaCollector.prototype.include = function (node) {
11955 return (this.focusOffset === -1 || contains(node, this.focusOffset)) && (node !== this.exclude);
11957 SchemaCollector.prototype.newSub = function () {
11958 return new SchemaCollector(-1, this.exclude);
11960 return SchemaCollector;
11962 var NoOpSchemaCollector = /** @class */ (function () {
11963 function NoOpSchemaCollector() {
11965 Object.defineProperty(NoOpSchemaCollector.prototype, "schemas", {
11966 get: function () { return []; },
11970 NoOpSchemaCollector.prototype.add = function (schema) { };
11971 NoOpSchemaCollector.prototype.merge = function (other) { };
11972 NoOpSchemaCollector.prototype.include = function (node) { return true; };
11973 NoOpSchemaCollector.prototype.newSub = function () { return this; };
11974 NoOpSchemaCollector.instance = new NoOpSchemaCollector();
11975 return NoOpSchemaCollector;
11977 var ValidationResult = /** @class */ (function () {
11978 function ValidationResult() {
11979 this.problems = [];
11980 this.propertiesMatches = 0;
11981 this.propertiesValueMatches = 0;
11982 this.primaryValueMatches = 0;
11983 this.enumValueMatch = false;
11984 this.enumValues = undefined;
11986 ValidationResult.prototype.hasProblems = function () {
11987 return !!this.problems.length;
11989 ValidationResult.prototype.mergeAll = function (validationResults) {
11990 for (var _i = 0, validationResults_1 = validationResults; _i < validationResults_1.length; _i++) {
11991 var validationResult = validationResults_1[_i];
11992 this.merge(validationResult);
11995 ValidationResult.prototype.merge = function (validationResult) {
11996 this.problems = this.problems.concat(validationResult.problems);
11998 ValidationResult.prototype.mergeEnumValues = function (validationResult) {
11999 if (!this.enumValueMatch && !validationResult.enumValueMatch && this.enumValues && validationResult.enumValues) {
12000 this.enumValues = this.enumValues.concat(validationResult.enumValues);
12001 for (var _i = 0, _a = this.problems; _i < _a.length; _i++) {
12002 var error = _a[_i];
12003 if (error.code === _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].EnumValueMismatch) {
12004 error.message = localize('enumWarning', 'Value is not accepted. Valid values: {0}.', this.enumValues.map(function (v) { return JSON.stringify(v); }).join(', '));
12009 ValidationResult.prototype.mergePropertyMatch = function (propertyValidationResult) {
12010 this.merge(propertyValidationResult);
12011 this.propertiesMatches++;
12012 if (propertyValidationResult.enumValueMatch || !propertyValidationResult.hasProblems() && propertyValidationResult.propertiesMatches) {
12013 this.propertiesValueMatches++;
12015 if (propertyValidationResult.enumValueMatch && propertyValidationResult.enumValues && propertyValidationResult.enumValues.length === 1) {
12016 this.primaryValueMatches++;
12019 ValidationResult.prototype.compare = function (other) {
12020 var hasProblems = this.hasProblems();
12021 if (hasProblems !== other.hasProblems()) {
12022 return hasProblems ? -1 : 1;
12024 if (this.enumValueMatch !== other.enumValueMatch) {
12025 return other.enumValueMatch ? -1 : 1;
12027 if (this.primaryValueMatches !== other.primaryValueMatches) {
12028 return this.primaryValueMatches - other.primaryValueMatches;
12030 if (this.propertiesValueMatches !== other.propertiesValueMatches) {
12031 return this.propertiesValueMatches - other.propertiesValueMatches;
12033 return this.propertiesMatches - other.propertiesMatches;
12035 return ValidationResult;
12038 function newJSONDocument(root, diagnostics) {
12039 if (diagnostics === void 0) { diagnostics = []; }
12040 return new JSONDocument(root, diagnostics, []);
12042 function getNodeValue(node) {
12043 return jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](node);
12045 function getNodePath(node) {
12046 return jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["getNodePath"](node);
12048 function contains(node, offset, includeRightBound) {
12049 if (includeRightBound === void 0) { includeRightBound = false; }
12050 return offset >= node.offset && offset < (node.offset + node.length) || includeRightBound && offset === (node.offset + node.length);
12052 var JSONDocument = /** @class */ (function () {
12053 function JSONDocument(root, syntaxErrors, comments) {
12054 if (syntaxErrors === void 0) { syntaxErrors = []; }
12055 if (comments === void 0) { comments = []; }
12057 this.syntaxErrors = syntaxErrors;
12058 this.comments = comments;
12060 JSONDocument.prototype.getNodeFromOffset = function (offset, includeRightBound) {
12061 if (includeRightBound === void 0) { includeRightBound = false; }
12063 return jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["findNodeAtOffset"](this.root, offset, includeRightBound);
12067 JSONDocument.prototype.visit = function (visitor) {
12069 var doVisit_1 = function (node) {
12070 var ctn = visitor(node);
12071 var children = node.children;
12072 if (Array.isArray(children)) {
12073 for (var i = 0; i < children.length && ctn; i++) {
12074 ctn = doVisit_1(children[i]);
12079 doVisit_1(this.root);
12082 JSONDocument.prototype.validate = function (textDocument, schema) {
12083 if (this.root && schema) {
12084 var validationResult = new ValidationResult();
12085 validate(this.root, schema, validationResult, NoOpSchemaCollector.instance);
12086 return validationResult.problems.map(function (p) {
12087 var range = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["Range"].create(textDocument.positionAt(p.location.offset), textDocument.positionAt(p.location.offset + p.location.length));
12088 return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["Diagnostic"].create(range, p.message, p.severity, p.code);
12093 JSONDocument.prototype.getMatchingSchemas = function (schema, focusOffset, exclude) {
12094 if (focusOffset === void 0) { focusOffset = -1; }
12095 var matchingSchemas = new SchemaCollector(focusOffset, exclude);
12096 if (this.root && schema) {
12097 validate(this.root, schema, new ValidationResult(), matchingSchemas);
12099 return matchingSchemas.schemas;
12101 return JSONDocument;
12104 function validate(n, schema, validationResult, matchingSchemas) {
12105 if (!n || !matchingSchemas.include(n)) {
12109 switch (node.type) {
12111 _validateObjectNode(node, schema, validationResult, matchingSchemas);
12114 _validateArrayNode(node, schema, validationResult, matchingSchemas);
12117 _validateStringNode(node, schema, validationResult, matchingSchemas);
12120 _validateNumberNode(node, schema, validationResult, matchingSchemas);
12123 return validate(node.valueNode, schema, validationResult, matchingSchemas);
12126 matchingSchemas.add({ node: node, schema: schema });
12127 function _validateNode() {
12128 function matchesType(type) {
12129 return node.type === type || (type === 'integer' && node.type === 'number' && node.isInteger);
12131 if (Array.isArray(schema.type)) {
12132 if (!schema.type.some(matchesType)) {
12133 validationResult.problems.push({
12134 location: { offset: node.offset, length: node.length },
12135 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12136 message: schema.errorMessage || localize('typeArrayMismatchWarning', 'Incorrect type. Expected one of {0}.', schema.type.join(', '))
12140 else if (schema.type) {
12141 if (!matchesType(schema.type)) {
12142 validationResult.problems.push({
12143 location: { offset: node.offset, length: node.length },
12144 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12145 message: schema.errorMessage || localize('typeMismatchWarning', 'Incorrect type. Expected "{0}".', schema.type)
12149 if (Array.isArray(schema.allOf)) {
12150 for (var _i = 0, _a = schema.allOf; _i < _a.length; _i++) {
12151 var subSchemaRef = _a[_i];
12152 validate(node, asSchema(subSchemaRef), validationResult, matchingSchemas);
12155 var notSchema = asSchema(schema.not);
12157 var subValidationResult = new ValidationResult();
12158 var subMatchingSchemas = matchingSchemas.newSub();
12159 validate(node, notSchema, subValidationResult, subMatchingSchemas);
12160 if (!subValidationResult.hasProblems()) {
12161 validationResult.problems.push({
12162 location: { offset: node.offset, length: node.length },
12163 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12164 message: localize('notSchemaWarning', "Matches a schema that is not allowed.")
12167 for (var _b = 0, _c = subMatchingSchemas.schemas; _b < _c.length; _b++) {
12169 ms.inverted = !ms.inverted;
12170 matchingSchemas.add(ms);
12173 var testAlternatives = function (alternatives, maxOneMatch) {
12175 // remember the best match that is used for error messages
12176 var bestMatch = undefined;
12177 for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
12178 var subSchemaRef = alternatives_1[_i];
12179 var subSchema = asSchema(subSchemaRef);
12180 var subValidationResult = new ValidationResult();
12181 var subMatchingSchemas = matchingSchemas.newSub();
12182 validate(node, subSchema, subValidationResult, subMatchingSchemas);
12183 if (!subValidationResult.hasProblems()) {
12184 matches.push(subSchema);
12187 bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
12190 if (!maxOneMatch && !subValidationResult.hasProblems() && !bestMatch.validationResult.hasProblems()) {
12191 // no errors, both are equally good matches
12192 bestMatch.matchingSchemas.merge(subMatchingSchemas);
12193 bestMatch.validationResult.propertiesMatches += subValidationResult.propertiesMatches;
12194 bestMatch.validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
12197 var compareResult = subValidationResult.compare(bestMatch.validationResult);
12198 if (compareResult > 0) {
12199 // our node is the best matching so far
12200 bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
12202 else if (compareResult === 0) {
12203 // there's already a best matching but we are as good
12204 bestMatch.matchingSchemas.merge(subMatchingSchemas);
12205 bestMatch.validationResult.mergeEnumValues(subValidationResult);
12210 if (matches.length > 1 && maxOneMatch) {
12211 validationResult.problems.push({
12212 location: { offset: node.offset, length: 1 },
12213 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12214 message: localize('oneOfWarning', "Matches multiple schemas when only one must validate.")
12218 validationResult.merge(bestMatch.validationResult);
12219 validationResult.propertiesMatches += bestMatch.validationResult.propertiesMatches;
12220 validationResult.propertiesValueMatches += bestMatch.validationResult.propertiesValueMatches;
12221 matchingSchemas.merge(bestMatch.matchingSchemas);
12223 return matches.length;
12225 if (Array.isArray(schema.anyOf)) {
12226 testAlternatives(schema.anyOf, false);
12228 if (Array.isArray(schema.oneOf)) {
12229 testAlternatives(schema.oneOf, true);
12231 var testBranch = function (schema) {
12232 var subValidationResult = new ValidationResult();
12233 var subMatchingSchemas = matchingSchemas.newSub();
12234 validate(node, asSchema(schema), subValidationResult, subMatchingSchemas);
12235 validationResult.merge(subValidationResult);
12236 validationResult.propertiesMatches += subValidationResult.propertiesMatches;
12237 validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
12238 matchingSchemas.merge(subMatchingSchemas);
12240 var testCondition = function (ifSchema, thenSchema, elseSchema) {
12241 var subSchema = asSchema(ifSchema);
12242 var subValidationResult = new ValidationResult();
12243 var subMatchingSchemas = matchingSchemas.newSub();
12244 validate(node, subSchema, subValidationResult, subMatchingSchemas);
12245 matchingSchemas.merge(subMatchingSchemas);
12246 if (!subValidationResult.hasProblems()) {
12248 testBranch(thenSchema);
12251 else if (elseSchema) {
12252 testBranch(elseSchema);
12255 var ifSchema = asSchema(schema.if);
12257 testCondition(ifSchema, asSchema(schema.then), asSchema(schema.else));
12259 if (Array.isArray(schema.enum)) {
12260 var val = getNodeValue(node);
12261 var enumValueMatch = false;
12262 for (var _d = 0, _e = schema.enum; _d < _e.length; _d++) {
12264 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["equals"])(val, e)) {
12265 enumValueMatch = true;
12269 validationResult.enumValues = schema.enum;
12270 validationResult.enumValueMatch = enumValueMatch;
12271 if (!enumValueMatch) {
12272 validationResult.problems.push({
12273 location: { offset: node.offset, length: node.length },
12274 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12275 code: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].EnumValueMismatch,
12276 message: schema.errorMessage || localize('enumWarning', 'Value is not accepted. Valid values: {0}.', schema.enum.map(function (v) { return JSON.stringify(v); }).join(', '))
12280 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isDefined"])(schema.const)) {
12281 var val = getNodeValue(node);
12282 if (!Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["equals"])(val, schema.const)) {
12283 validationResult.problems.push({
12284 location: { offset: node.offset, length: node.length },
12285 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12286 code: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].EnumValueMismatch,
12287 message: schema.errorMessage || localize('constWarning', 'Value must be {0}.', JSON.stringify(schema.const))
12289 validationResult.enumValueMatch = false;
12292 validationResult.enumValueMatch = true;
12294 validationResult.enumValues = [schema.const];
12296 if (schema.deprecationMessage && node.parent) {
12297 validationResult.problems.push({
12298 location: { offset: node.parent.offset, length: node.parent.length },
12299 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12300 message: schema.deprecationMessage
12304 function _validateNumberNode(node, schema, validationResult, matchingSchemas) {
12305 var val = node.value;
12306 function normalizeFloats(float) {
12308 var parts = /^(-?\d+)(?:\.(\d+))?(?:e([-+]\d+))?$/.exec(float.toString());
12310 value: Number(parts[1] + (parts[2] || '')),
12311 multiplier: (((_a = parts[2]) === null || _a === void 0 ? void 0 : _a.length) || 0) - (parseInt(parts[3]) || 0)
12315 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.multipleOf)) {
12316 var remainder = -1;
12317 if (Number.isInteger(schema.multipleOf)) {
12318 remainder = val % schema.multipleOf;
12321 var normMultipleOf = normalizeFloats(schema.multipleOf);
12322 var normValue = normalizeFloats(val);
12323 if (normMultipleOf && normValue) {
12324 var multiplier = Math.pow(10, Math.abs(normValue.multiplier - normMultipleOf.multiplier));
12325 if (normValue.multiplier < normMultipleOf.multiplier) {
12326 normValue.value *= multiplier;
12329 normMultipleOf.value *= multiplier;
12331 remainder = normValue.value % normMultipleOf.value;
12334 if (remainder !== 0) {
12335 validationResult.problems.push({
12336 location: { offset: node.offset, length: node.length },
12337 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12338 message: localize('multipleOfWarning', 'Value is not divisible by {0}.', schema.multipleOf)
12342 function getExclusiveLimit(limit, exclusive) {
12343 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(exclusive)) {
12346 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(exclusive) && exclusive) {
12351 function getLimit(limit, exclusive) {
12352 if (!Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(exclusive) || !exclusive) {
12357 var exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum);
12358 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(exclusiveMinimum) && val <= exclusiveMinimum) {
12359 validationResult.problems.push({
12360 location: { offset: node.offset, length: node.length },
12361 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12362 message: localize('exclusiveMinimumWarning', 'Value is below the exclusive minimum of {0}.', exclusiveMinimum)
12365 var exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum);
12366 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(exclusiveMaximum) && val >= exclusiveMaximum) {
12367 validationResult.problems.push({
12368 location: { offset: node.offset, length: node.length },
12369 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12370 message: localize('exclusiveMaximumWarning', 'Value is above the exclusive maximum of {0}.', exclusiveMaximum)
12373 var minimum = getLimit(schema.minimum, schema.exclusiveMinimum);
12374 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(minimum) && val < minimum) {
12375 validationResult.problems.push({
12376 location: { offset: node.offset, length: node.length },
12377 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12378 message: localize('minimumWarning', 'Value is below the minimum of {0}.', minimum)
12381 var maximum = getLimit(schema.maximum, schema.exclusiveMaximum);
12382 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(maximum) && val > maximum) {
12383 validationResult.problems.push({
12384 location: { offset: node.offset, length: node.length },
12385 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12386 message: localize('maximumWarning', 'Value is above the maximum of {0}.', maximum)
12390 function _validateStringNode(node, schema, validationResult, matchingSchemas) {
12391 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.minLength) && node.value.length < schema.minLength) {
12392 validationResult.problems.push({
12393 location: { offset: node.offset, length: node.length },
12394 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12395 message: localize('minLengthWarning', 'String is shorter than the minimum length of {0}.', schema.minLength)
12398 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.maxLength) && node.value.length > schema.maxLength) {
12399 validationResult.problems.push({
12400 location: { offset: node.offset, length: node.length },
12401 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12402 message: localize('maxLengthWarning', 'String is longer than the maximum length of {0}.', schema.maxLength)
12405 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isString"])(schema.pattern)) {
12406 var regex = new RegExp(schema.pattern);
12407 if (!regex.test(node.value)) {
12408 validationResult.problems.push({
12409 location: { offset: node.offset, length: node.length },
12410 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12411 message: schema.patternErrorMessage || schema.errorMessage || localize('patternWarning', 'String does not match the pattern of "{0}".', schema.pattern)
12415 if (schema.format) {
12416 switch (schema.format) {
12418 case 'uri-reference':
12420 var errorMessage = void 0;
12422 errorMessage = localize('uriEmpty', 'URI expected.');
12425 var match = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(node.value);
12427 errorMessage = localize('uriMissing', 'URI is expected.');
12429 else if (!match[2] && schema.format === 'uri') {
12430 errorMessage = localize('uriSchemeMissing', 'URI with a scheme is expected.');
12433 if (errorMessage) {
12434 validationResult.problems.push({
12435 location: { offset: node.offset, length: node.length },
12436 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12437 message: schema.patternErrorMessage || schema.errorMessage || localize('uriFormatWarning', 'String is not a URI: {0}', errorMessage)
12447 var format = formats[schema.format];
12448 if (!node.value || !format.pattern.exec(node.value)) {
12449 validationResult.problems.push({
12450 location: { offset: node.offset, length: node.length },
12451 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12452 message: schema.patternErrorMessage || schema.errorMessage || format.errorMessage
12459 function _validateArrayNode(node, schema, validationResult, matchingSchemas) {
12460 if (Array.isArray(schema.items)) {
12461 var subSchemas = schema.items;
12462 for (var index = 0; index < subSchemas.length; index++) {
12463 var subSchemaRef = subSchemas[index];
12464 var subSchema = asSchema(subSchemaRef);
12465 var itemValidationResult = new ValidationResult();
12466 var item = node.items[index];
12468 validate(item, subSchema, itemValidationResult, matchingSchemas);
12469 validationResult.mergePropertyMatch(itemValidationResult);
12471 else if (node.items.length >= subSchemas.length) {
12472 validationResult.propertiesValueMatches++;
12475 if (node.items.length > subSchemas.length) {
12476 if (typeof schema.additionalItems === 'object') {
12477 for (var i = subSchemas.length; i < node.items.length; i++) {
12478 var itemValidationResult = new ValidationResult();
12479 validate(node.items[i], schema.additionalItems, itemValidationResult, matchingSchemas);
12480 validationResult.mergePropertyMatch(itemValidationResult);
12483 else if (schema.additionalItems === false) {
12484 validationResult.problems.push({
12485 location: { offset: node.offset, length: node.length },
12486 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12487 message: localize('additionalItemsWarning', 'Array has too many items according to schema. Expected {0} or fewer.', subSchemas.length)
12493 var itemSchema = asSchema(schema.items);
12495 for (var _i = 0, _a = node.items; _i < _a.length; _i++) {
12497 var itemValidationResult = new ValidationResult();
12498 validate(item, itemSchema, itemValidationResult, matchingSchemas);
12499 validationResult.mergePropertyMatch(itemValidationResult);
12503 var containsSchema = asSchema(schema.contains);
12504 if (containsSchema) {
12505 var doesContain = node.items.some(function (item) {
12506 var itemValidationResult = new ValidationResult();
12507 validate(item, containsSchema, itemValidationResult, NoOpSchemaCollector.instance);
12508 return !itemValidationResult.hasProblems();
12510 if (!doesContain) {
12511 validationResult.problems.push({
12512 location: { offset: node.offset, length: node.length },
12513 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12514 message: schema.errorMessage || localize('requiredItemMissingWarning', 'Array does not contain required item.')
12518 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.minItems) && node.items.length < schema.minItems) {
12519 validationResult.problems.push({
12520 location: { offset: node.offset, length: node.length },
12521 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12522 message: localize('minItemsWarning', 'Array has too few items. Expected {0} or more.', schema.minItems)
12525 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.maxItems) && node.items.length > schema.maxItems) {
12526 validationResult.problems.push({
12527 location: { offset: node.offset, length: node.length },
12528 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12529 message: localize('maxItemsWarning', 'Array has too many items. Expected {0} or fewer.', schema.maxItems)
12532 if (schema.uniqueItems === true) {
12533 var values_1 = getNodeValue(node);
12534 var duplicates = values_1.some(function (value, index) {
12535 return index !== values_1.lastIndexOf(value);
12538 validationResult.problems.push({
12539 location: { offset: node.offset, length: node.length },
12540 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12541 message: localize('uniqueItemsWarning', 'Array has duplicate items.')
12546 function _validateObjectNode(node, schema, validationResult, matchingSchemas) {
12547 var seenKeys = Object.create(null);
12548 var unprocessedProperties = [];
12549 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
12550 var propertyNode = _a[_i];
12551 var key = propertyNode.keyNode.value;
12552 seenKeys[key] = propertyNode.valueNode;
12553 unprocessedProperties.push(key);
12555 if (Array.isArray(schema.required)) {
12556 for (var _b = 0, _c = schema.required; _b < _c.length; _b++) {
12557 var propertyName = _c[_b];
12558 if (!seenKeys[propertyName]) {
12559 var keyNode = node.parent && node.parent.type === 'property' && node.parent.keyNode;
12560 var location = keyNode ? { offset: keyNode.offset, length: keyNode.length } : { offset: node.offset, length: 1 };
12561 validationResult.problems.push({
12562 location: location,
12563 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12564 message: localize('MissingRequiredPropWarning', 'Missing property "{0}".', propertyName)
12569 var propertyProcessed = function (prop) {
12570 var index = unprocessedProperties.indexOf(prop);
12571 while (index >= 0) {
12572 unprocessedProperties.splice(index, 1);
12573 index = unprocessedProperties.indexOf(prop);
12576 if (schema.properties) {
12577 for (var _d = 0, _e = Object.keys(schema.properties); _d < _e.length; _d++) {
12578 var propertyName = _e[_d];
12579 propertyProcessed(propertyName);
12580 var propertySchema = schema.properties[propertyName];
12581 var child = seenKeys[propertyName];
12583 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(propertySchema)) {
12584 if (!propertySchema) {
12585 var propertyNode = child.parent;
12586 validationResult.problems.push({
12587 location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
12588 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12589 message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
12593 validationResult.propertiesMatches++;
12594 validationResult.propertiesValueMatches++;
12598 var propertyValidationResult = new ValidationResult();
12599 validate(child, propertySchema, propertyValidationResult, matchingSchemas);
12600 validationResult.mergePropertyMatch(propertyValidationResult);
12605 if (schema.patternProperties) {
12606 for (var _f = 0, _g = Object.keys(schema.patternProperties); _f < _g.length; _f++) {
12607 var propertyPattern = _g[_f];
12608 var regex = new RegExp(propertyPattern);
12609 for (var _h = 0, _j = unprocessedProperties.slice(0); _h < _j.length; _h++) {
12610 var propertyName = _j[_h];
12611 if (regex.test(propertyName)) {
12612 propertyProcessed(propertyName);
12613 var child = seenKeys[propertyName];
12615 var propertySchema = schema.patternProperties[propertyPattern];
12616 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(propertySchema)) {
12617 if (!propertySchema) {
12618 var propertyNode = child.parent;
12619 validationResult.problems.push({
12620 location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
12621 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12622 message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
12626 validationResult.propertiesMatches++;
12627 validationResult.propertiesValueMatches++;
12631 var propertyValidationResult = new ValidationResult();
12632 validate(child, propertySchema, propertyValidationResult, matchingSchemas);
12633 validationResult.mergePropertyMatch(propertyValidationResult);
12640 if (typeof schema.additionalProperties === 'object') {
12641 for (var _k = 0, unprocessedProperties_1 = unprocessedProperties; _k < unprocessedProperties_1.length; _k++) {
12642 var propertyName = unprocessedProperties_1[_k];
12643 var child = seenKeys[propertyName];
12645 var propertyValidationResult = new ValidationResult();
12646 validate(child, schema.additionalProperties, propertyValidationResult, matchingSchemas);
12647 validationResult.mergePropertyMatch(propertyValidationResult);
12651 else if (schema.additionalProperties === false) {
12652 if (unprocessedProperties.length > 0) {
12653 for (var _l = 0, unprocessedProperties_2 = unprocessedProperties; _l < unprocessedProperties_2.length; _l++) {
12654 var propertyName = unprocessedProperties_2[_l];
12655 var child = seenKeys[propertyName];
12657 var propertyNode = child.parent;
12658 validationResult.problems.push({
12659 location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
12660 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12661 message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
12667 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.maxProperties)) {
12668 if (node.properties.length > schema.maxProperties) {
12669 validationResult.problems.push({
12670 location: { offset: node.offset, length: node.length },
12671 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12672 message: localize('MaxPropWarning', 'Object has more properties than limit of {0}.', schema.maxProperties)
12676 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.minProperties)) {
12677 if (node.properties.length < schema.minProperties) {
12678 validationResult.problems.push({
12679 location: { offset: node.offset, length: node.length },
12680 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12681 message: localize('MinPropWarning', 'Object has fewer properties than the required number of {0}', schema.minProperties)
12685 if (schema.dependencies) {
12686 for (var _m = 0, _o = Object.keys(schema.dependencies); _m < _o.length; _m++) {
12688 var prop = seenKeys[key];
12690 var propertyDep = schema.dependencies[key];
12691 if (Array.isArray(propertyDep)) {
12692 for (var _p = 0, propertyDep_1 = propertyDep; _p < propertyDep_1.length; _p++) {
12693 var requiredProp = propertyDep_1[_p];
12694 if (!seenKeys[requiredProp]) {
12695 validationResult.problems.push({
12696 location: { offset: node.offset, length: node.length },
12697 severity: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning,
12698 message: localize('RequiredDependentPropWarning', 'Object is missing property {0} required by property {1}.', requiredProp, key)
12702 validationResult.propertiesValueMatches++;
12707 var propertySchema = asSchema(propertyDep);
12708 if (propertySchema) {
12709 var propertyValidationResult = new ValidationResult();
12710 validate(node, propertySchema, propertyValidationResult, matchingSchemas);
12711 validationResult.mergePropertyMatch(propertyValidationResult);
12717 var propertyNames = asSchema(schema.propertyNames);
12718 if (propertyNames) {
12719 for (var _q = 0, _r = node.properties; _q < _r.length; _q++) {
12721 var key = f.keyNode;
12723 validate(key, propertyNames, validationResult, NoOpSchemaCollector.instance);
12729 function parse(textDocument, config) {
12731 var lastProblemOffset = -1;
12732 var text = textDocument.getText();
12733 var scanner = jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["createScanner"](text, false);
12734 var commentRanges = config && config.collectComments ? [] : undefined;
12735 function _scanNext() {
12737 var token_1 = scanner.scan();
12740 case 12 /* LineCommentTrivia */:
12741 case 13 /* BlockCommentTrivia */:
12742 if (Array.isArray(commentRanges)) {
12743 commentRanges.push(_jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["Range"].create(textDocument.positionAt(scanner.getTokenOffset()), textDocument.positionAt(scanner.getTokenOffset() + scanner.getTokenLength())));
12746 case 15 /* Trivia */:
12747 case 14 /* LineBreakTrivia */:
12754 function _accept(token) {
12755 if (scanner.getToken() === token) {
12761 function _errorAtRange(message, code, startOffset, endOffset, severity) {
12762 if (severity === void 0) { severity = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Error; }
12763 if (problems.length === 0 || startOffset !== lastProblemOffset) {
12764 var range = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["Range"].create(textDocument.positionAt(startOffset), textDocument.positionAt(endOffset));
12765 problems.push(_jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["Diagnostic"].create(range, message, severity, code, textDocument.languageId));
12766 lastProblemOffset = startOffset;
12769 function _error(message, code, node, skipUntilAfter, skipUntil) {
12770 if (node === void 0) { node = undefined; }
12771 if (skipUntilAfter === void 0) { skipUntilAfter = []; }
12772 if (skipUntil === void 0) { skipUntil = []; }
12773 var start = scanner.getTokenOffset();
12774 var end = scanner.getTokenOffset() + scanner.getTokenLength();
12775 if (start === end && start > 0) {
12777 while (start > 0 && /\s/.test(text.charAt(start))) {
12782 _errorAtRange(message, code, start, end);
12784 _finalize(node, false);
12786 if (skipUntilAfter.length + skipUntil.length > 0) {
12787 var token_2 = scanner.getToken();
12788 while (token_2 !== 17 /* EOF */) {
12789 if (skipUntilAfter.indexOf(token_2) !== -1) {
12793 else if (skipUntil.indexOf(token_2) !== -1) {
12796 token_2 = _scanNext();
12801 function _checkScanError() {
12802 switch (scanner.getTokenError()) {
12803 case 4 /* InvalidUnicode */:
12804 _error(localize('InvalidUnicode', 'Invalid unicode sequence in string.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].InvalidUnicode);
12806 case 5 /* InvalidEscapeCharacter */:
12807 _error(localize('InvalidEscapeCharacter', 'Invalid escape character in string.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].InvalidEscapeCharacter);
12809 case 3 /* UnexpectedEndOfNumber */:
12810 _error(localize('UnexpectedEndOfNumber', 'Unexpected end of number.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].UnexpectedEndOfNumber);
12812 case 1 /* UnexpectedEndOfComment */:
12813 _error(localize('UnexpectedEndOfComment', 'Unexpected end of comment.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].UnexpectedEndOfComment);
12815 case 2 /* UnexpectedEndOfString */:
12816 _error(localize('UnexpectedEndOfString', 'Unexpected end of string.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].UnexpectedEndOfString);
12818 case 6 /* InvalidCharacter */:
12819 _error(localize('InvalidCharacter', 'Invalid characters in string. Control characters must be escaped.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].InvalidCharacter);
12824 function _finalize(node, scanNext) {
12825 node.length = scanner.getTokenOffset() + scanner.getTokenLength() - node.offset;
12831 function _parseArray(parent) {
12832 if (scanner.getToken() !== 3 /* OpenBracketToken */) {
12835 var node = new ArrayASTNodeImpl(parent, scanner.getTokenOffset());
12836 _scanNext(); // consume OpenBracketToken
12838 var needsComma = false;
12839 while (scanner.getToken() !== 4 /* CloseBracketToken */ && scanner.getToken() !== 17 /* EOF */) {
12840 if (scanner.getToken() === 5 /* CommaToken */) {
12842 _error(localize('ValueExpected', 'Value expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].ValueExpected);
12844 var commaOffset = scanner.getTokenOffset();
12845 _scanNext(); // consume comma
12846 if (scanner.getToken() === 4 /* CloseBracketToken */) {
12848 _errorAtRange(localize('TrailingComma', 'Trailing comma'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].TrailingComma, commaOffset, commaOffset + 1);
12853 else if (needsComma) {
12854 _error(localize('ExpectedComma', 'Expected comma'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommaExpected);
12856 var item = _parseValue(node);
12858 _error(localize('PropertyExpected', 'Value expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].ValueExpected, undefined, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
12861 node.items.push(item);
12865 if (scanner.getToken() !== 4 /* CloseBracketToken */) {
12866 return _error(localize('ExpectedCloseBracket', 'Expected comma or closing bracket'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommaOrCloseBacketExpected, node);
12868 return _finalize(node, true);
12870 var keyPlaceholder = new StringASTNodeImpl(undefined, 0, 0);
12871 function _parseProperty(parent, keysSeen) {
12872 var node = new PropertyASTNodeImpl(parent, scanner.getTokenOffset(), keyPlaceholder);
12873 var key = _parseString(node);
12875 if (scanner.getToken() === 16 /* Unknown */) {
12876 // give a more helpful error message
12877 _error(localize('DoubleQuotesExpected', 'Property keys must be doublequoted'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined);
12878 var keyNode = new StringASTNodeImpl(node, scanner.getTokenOffset(), scanner.getTokenLength());
12879 keyNode.value = scanner.getTokenValue();
12881 _scanNext(); // consume Unknown
12887 node.keyNode = key;
12888 var seen = keysSeen[key.value];
12890 _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].DuplicateKey, node.keyNode.offset, node.keyNode.offset + node.keyNode.length, _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning);
12891 if (typeof seen === 'object') {
12892 _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].DuplicateKey, seen.keyNode.offset, seen.keyNode.offset + seen.keyNode.length, _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["DiagnosticSeverity"].Warning);
12894 keysSeen[key.value] = true; // if the same key is duplicate again, avoid duplicate error reporting
12897 keysSeen[key.value] = node;
12899 if (scanner.getToken() === 6 /* ColonToken */) {
12900 node.colonOffset = scanner.getTokenOffset();
12901 _scanNext(); // consume ColonToken
12904 _error(localize('ColonExpected', 'Colon expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].ColonExpected);
12905 if (scanner.getToken() === 10 /* StringLiteral */ && textDocument.positionAt(key.offset + key.length).line < textDocument.positionAt(scanner.getTokenOffset()).line) {
12906 node.length = key.length;
12910 var value = _parseValue(node);
12912 return _error(localize('ValueExpected', 'Value expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].ValueExpected, node, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
12914 node.valueNode = value;
12915 node.length = value.offset + value.length - node.offset;
12918 function _parseObject(parent) {
12919 if (scanner.getToken() !== 1 /* OpenBraceToken */) {
12922 var node = new ObjectASTNodeImpl(parent, scanner.getTokenOffset());
12923 var keysSeen = Object.create(null);
12924 _scanNext(); // consume OpenBraceToken
12925 var needsComma = false;
12926 while (scanner.getToken() !== 2 /* CloseBraceToken */ && scanner.getToken() !== 17 /* EOF */) {
12927 if (scanner.getToken() === 5 /* CommaToken */) {
12929 _error(localize('PropertyExpected', 'Property expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].PropertyExpected);
12931 var commaOffset = scanner.getTokenOffset();
12932 _scanNext(); // consume comma
12933 if (scanner.getToken() === 2 /* CloseBraceToken */) {
12935 _errorAtRange(localize('TrailingComma', 'Trailing comma'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].TrailingComma, commaOffset, commaOffset + 1);
12940 else if (needsComma) {
12941 _error(localize('ExpectedComma', 'Expected comma'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommaExpected);
12943 var property = _parseProperty(node, keysSeen);
12945 _error(localize('PropertyExpected', 'Property expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].PropertyExpected, undefined, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
12948 node.properties.push(property);
12952 if (scanner.getToken() !== 2 /* CloseBraceToken */) {
12953 return _error(localize('ExpectedCloseBrace', 'Expected comma or closing brace'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommaOrCloseBraceExpected, node);
12955 return _finalize(node, true);
12957 function _parseString(parent) {
12958 if (scanner.getToken() !== 10 /* StringLiteral */) {
12961 var node = new StringASTNodeImpl(parent, scanner.getTokenOffset());
12962 node.value = scanner.getTokenValue();
12963 return _finalize(node, true);
12965 function _parseNumber(parent) {
12966 if (scanner.getToken() !== 11 /* NumericLiteral */) {
12969 var node = new NumberASTNodeImpl(parent, scanner.getTokenOffset());
12970 if (scanner.getTokenError() === 0 /* None */) {
12971 var tokenValue = scanner.getTokenValue();
12973 var numberValue = JSON.parse(tokenValue);
12974 if (!Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(numberValue)) {
12975 return _error(localize('InvalidNumberFormat', 'Invalid number format.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined, node);
12977 node.value = numberValue;
12980 return _error(localize('InvalidNumberFormat', 'Invalid number format.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined, node);
12982 node.isInteger = tokenValue.indexOf('.') === -1;
12984 return _finalize(node, true);
12986 function _parseLiteral(parent) {
12988 switch (scanner.getToken()) {
12989 case 7 /* NullKeyword */:
12990 return _finalize(new NullASTNodeImpl(parent, scanner.getTokenOffset()), true);
12991 case 8 /* TrueKeyword */:
12992 return _finalize(new BooleanASTNodeImpl(parent, true, scanner.getTokenOffset()), true);
12993 case 9 /* FalseKeyword */:
12994 return _finalize(new BooleanASTNodeImpl(parent, false, scanner.getTokenOffset()), true);
12999 function _parseValue(parent) {
13000 return _parseArray(parent) || _parseObject(parent) || _parseString(parent) || _parseNumber(parent) || _parseLiteral(parent);
13002 var _root = undefined;
13003 var token = _scanNext();
13004 if (token !== 17 /* EOF */) {
13005 _root = _parseValue(_root);
13007 _error(localize('Invalid symbol', 'Expected a JSON object, array or literal.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined);
13009 else if (scanner.getToken() !== 17 /* EOF */) {
13010 _error(localize('End of file expected', 'End of file expected.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined);
13013 return new JSONDocument(_root, problems, commentRanges);
13019 /***/ (function(module, __webpack_exports__, __webpack_require__) {
13022 __webpack_require__.r(__webpack_exports__);
13023 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createScanner", function() { return createScanner; });
13024 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocation", function() { return getLocation; });
13025 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
13026 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTree", function() { return parseTree; });
13027 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtLocation", function() { return findNodeAtLocation; });
13028 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtOffset", function() { return findNodeAtOffset; });
13029 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; });
13030 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; });
13031 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "visit", function() { return visit; });
13032 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripComments", function() { return stripComments; });
13033 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "printParseErrorCode", function() { return printParseErrorCode; });
13034 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; });
13035 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "modify", function() { return modify; });
13036 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEdits", function() { return applyEdits; });
13037 /* harmony import */ var _impl_format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(94);
13038 /* harmony import */ var _impl_edit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(96);
13039 /* harmony import */ var _impl_scanner__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(95);
13040 /* harmony import */ var _impl_parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(97);
13041 /*---------------------------------------------------------------------------------------------
13042 * Copyright (c) Microsoft Corporation. All rights reserved.
13043 * Licensed under the MIT License. See License.txt in the project root for license information.
13044 *--------------------------------------------------------------------------------------------*/
13051 * Creates a JSON scanner on the given text.
13052 * If ignoreTrivia is set, whitespaces or comments are ignored.
13054 var createScanner = _impl_scanner__WEBPACK_IMPORTED_MODULE_2__["createScanner"];
13056 * 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.
13058 var getLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getLocation"];
13060 * 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.
13061 * Therefore, always check the errors list to find out if the input was valid.
13063 var parse = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["parse"];
13065 * 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.
13067 var parseTree = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["parseTree"];
13069 * Finds the node at the given path in a JSON DOM.
13071 var findNodeAtLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["findNodeAtLocation"];
13073 * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
13075 var findNodeAtOffset = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["findNodeAtOffset"];
13077 * Gets the JSON path of the given JSON DOM node
13079 var getNodePath = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getNodePath"];
13081 * Evaluates the JavaScript object of the given JSON DOM node
13083 var getNodeValue = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getNodeValue"];
13085 * Parses the given text and invokes the visitor functions for each object, array and literal reached.
13087 var visit = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["visit"];
13089 * Takes JSON with JavaScript-style comments and remove
13090 * them. Optionally replaces every none-newline character
13091 * of comments with a replaceCharacter
13093 var stripComments = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["stripComments"];
13094 function printParseErrorCode(code) {
13096 case 1 /* InvalidSymbol */: return 'InvalidSymbol';
13097 case 2 /* InvalidNumberFormat */: return 'InvalidNumberFormat';
13098 case 3 /* PropertyNameExpected */: return 'PropertyNameExpected';
13099 case 4 /* ValueExpected */: return 'ValueExpected';
13100 case 5 /* ColonExpected */: return 'ColonExpected';
13101 case 6 /* CommaExpected */: return 'CommaExpected';
13102 case 7 /* CloseBraceExpected */: return 'CloseBraceExpected';
13103 case 8 /* CloseBracketExpected */: return 'CloseBracketExpected';
13104 case 9 /* EndOfFileExpected */: return 'EndOfFileExpected';
13105 case 10 /* InvalidCommentToken */: return 'InvalidCommentToken';
13106 case 11 /* UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';
13107 case 12 /* UnexpectedEndOfString */: return 'UnexpectedEndOfString';
13108 case 13 /* UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';
13109 case 14 /* InvalidUnicode */: return 'InvalidUnicode';
13110 case 15 /* InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';
13111 case 16 /* InvalidCharacter */: return 'InvalidCharacter';
13113 return '<unknown ParseErrorCode>';
13116 * Computes the edits needed to format a JSON document.
13118 * @param documentText The input text
13119 * @param range The range to format or `undefined` to format the full content
13120 * @param options The formatting options
13121 * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
13122 * 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
13123 * text in the original document. However, multiple edits can have
13124 * 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.
13125 * To apply edits to an input, you can use `applyEdits`.
13127 function format(documentText, range, options) {
13128 return _impl_format__WEBPACK_IMPORTED_MODULE_0__["format"](documentText, range, options);
13131 * Computes the edits needed to modify a value in the JSON document.
13133 * @param documentText The input text
13134 * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
13135 * If the path points to an non-existing property or item, it will be created.
13136 * @param value The new value for the specified property or item. If the value is undefined,
13137 * the property or item will be removed.
13138 * @param options Options
13139 * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
13140 * 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
13141 * text in the original document. However, multiple edits can have
13142 * 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.
13143 * To apply edits to an input, you can use `applyEdits`.
13145 function modify(text, path, value, options) {
13146 return _impl_edit__WEBPACK_IMPORTED_MODULE_1__["setProperty"](text, path, value, options);
13149 * Applies edits to a input string.
13151 function applyEdits(text, edits) {
13152 for (var i = edits.length - 1; i >= 0; i--) {
13153 text = _impl_edit__WEBPACK_IMPORTED_MODULE_1__["applyEdit"](text, edits[i]);
13161 /***/ (function(module, __webpack_exports__, __webpack_require__) {
13164 __webpack_require__.r(__webpack_exports__);
13165 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; });
13166 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isEOL", function() { return isEOL; });
13167 /* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(95);
13168 /*---------------------------------------------------------------------------------------------
13169 * Copyright (c) Microsoft Corporation. All rights reserved.
13170 * Licensed under the MIT License. See License.txt in the project root for license information.
13171 *--------------------------------------------------------------------------------------------*/
13174 function format(documentText, range, options) {
13175 var initialIndentLevel;
13177 var formatTextStart;
13181 rangeStart = range.offset;
13182 rangeEnd = rangeStart + range.length;
13183 formatTextStart = rangeStart;
13184 while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
13187 var endOffset = rangeEnd;
13188 while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
13191 formatText = documentText.substring(formatTextStart, endOffset);
13192 initialIndentLevel = computeIndentLevel(formatText, options);
13195 formatText = documentText;
13196 initialIndentLevel = 0;
13197 formatTextStart = 0;
13199 rangeEnd = documentText.length;
13201 var eol = getEOL(options, documentText);
13202 var lineBreak = false;
13203 var indentLevel = 0;
13205 if (options.insertSpaces) {
13206 indentValue = repeat(' ', options.tabSize || 4);
13209 indentValue = '\t';
13211 var scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(formatText, false);
13212 var hasError = false;
13213 function newLineAndIndent() {
13214 return eol + repeat(indentValue, initialIndentLevel + indentLevel);
13216 function scanNext() {
13217 var token = scanner.scan();
13219 while (token === 15 /* Trivia */ || token === 14 /* LineBreakTrivia */) {
13220 lineBreak = lineBreak || (token === 14 /* LineBreakTrivia */);
13221 token = scanner.scan();
13223 hasError = token === 16 /* Unknown */ || scanner.getTokenError() !== 0 /* None */;
13226 var editOperations = [];
13227 function addEdit(text, startOffset, endOffset) {
13228 if (!hasError && startOffset < rangeEnd && endOffset > rangeStart && documentText.substring(startOffset, endOffset) !== text) {
13229 editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
13232 var firstToken = scanNext();
13233 if (firstToken !== 17 /* EOF */) {
13234 var firstTokenStart = scanner.getTokenOffset() + formatTextStart;
13235 var initialIndent = repeat(indentValue, initialIndentLevel);
13236 addEdit(initialIndent, formatTextStart, firstTokenStart);
13238 while (firstToken !== 17 /* EOF */) {
13239 var firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
13240 var secondToken = scanNext();
13241 var replaceContent = '';
13242 while (!lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
13243 // comments on the same line: keep them on the same line, but ignore them otherwise
13244 var commentTokenStart = scanner.getTokenOffset() + formatTextStart;
13245 addEdit(' ', firstTokenEnd, commentTokenStart);
13246 firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
13247 replaceContent = secondToken === 12 /* LineCommentTrivia */ ? newLineAndIndent() : '';
13248 secondToken = scanNext();
13250 if (secondToken === 2 /* CloseBraceToken */) {
13251 if (firstToken !== 1 /* OpenBraceToken */) {
13253 replaceContent = newLineAndIndent();
13256 else if (secondToken === 4 /* CloseBracketToken */) {
13257 if (firstToken !== 3 /* OpenBracketToken */) {
13259 replaceContent = newLineAndIndent();
13263 switch (firstToken) {
13264 case 3 /* OpenBracketToken */:
13265 case 1 /* OpenBraceToken */:
13267 replaceContent = newLineAndIndent();
13269 case 5 /* CommaToken */:
13270 case 12 /* LineCommentTrivia */:
13271 replaceContent = newLineAndIndent();
13273 case 13 /* BlockCommentTrivia */:
13275 replaceContent = newLineAndIndent();
13278 // symbol following comment on the same line: keep on same line, separate with ' '
13279 replaceContent = ' ';
13282 case 6 /* ColonToken */:
13283 replaceContent = ' ';
13285 case 10 /* StringLiteral */:
13286 if (secondToken === 6 /* ColonToken */) {
13287 replaceContent = '';
13291 case 7 /* NullKeyword */:
13292 case 8 /* TrueKeyword */:
13293 case 9 /* FalseKeyword */:
13294 case 11 /* NumericLiteral */:
13295 case 2 /* CloseBraceToken */:
13296 case 4 /* CloseBracketToken */:
13297 if (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */) {
13298 replaceContent = ' ';
13300 else if (secondToken !== 5 /* CommaToken */ && secondToken !== 17 /* EOF */) {
13304 case 16 /* Unknown */:
13308 if (lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
13309 replaceContent = newLineAndIndent();
13312 var secondTokenStart = scanner.getTokenOffset() + formatTextStart;
13313 addEdit(replaceContent, firstTokenEnd, secondTokenStart);
13314 firstToken = secondToken;
13316 return editOperations;
13318 function repeat(s, count) {
13320 for (var i = 0; i < count; i++) {
13325 function computeIndentLevel(content, options) {
13328 var tabSize = options.tabSize || 4;
13329 while (i < content.length) {
13330 var ch = content.charAt(i);
13334 else if (ch === '\t') {
13342 return Math.floor(nChars / tabSize);
13344 function getEOL(options, text) {
13345 for (var i = 0; i < text.length; i++) {
13346 var ch = text.charAt(i);
13348 if (i + 1 < text.length && text.charAt(i + 1) === '\n') {
13353 else if (ch === '\n') {
13357 return (options && options.eol) || '\n';
13359 function isEOL(text, offset) {
13360 return '\r\n'.indexOf(text.charAt(offset)) !== -1;
13366 /***/ (function(module, __webpack_exports__, __webpack_require__) {
13369 __webpack_require__.r(__webpack_exports__);
13370 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createScanner", function() { return createScanner; });
13371 /*---------------------------------------------------------------------------------------------
13372 * Copyright (c) Microsoft Corporation. All rights reserved.
13373 * Licensed under the MIT License. See License.txt in the project root for license information.
13374 *--------------------------------------------------------------------------------------------*/
13377 * Creates a JSON scanner on the given text.
13378 * If ignoreTrivia is set, whitespaces or comments are ignored.
13380 function createScanner(text, ignoreTrivia) {
13381 if (ignoreTrivia === void 0) { ignoreTrivia = false; }
13382 var len = text.length;
13383 var pos = 0, value = '', tokenOffset = 0, token = 16 /* Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* None */;
13384 function scanHexDigits(count, exact) {
13387 while (digits < count || !exact) {
13388 var ch = text.charCodeAt(pos);
13389 if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
13390 value = value * 16 + ch - 48 /* _0 */;
13392 else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
13393 value = value * 16 + ch - 65 /* A */ + 10;
13395 else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
13396 value = value * 16 + ch - 97 /* a */ + 10;
13404 if (digits < count) {
13409 function setPosition(newPosition) {
13413 token = 16 /* Unknown */;
13414 scanError = 0 /* None */;
13416 function scanNumber() {
13418 if (text.charCodeAt(pos) === 48 /* _0 */) {
13423 while (pos < text.length && isDigit(text.charCodeAt(pos))) {
13427 if (pos < text.length && text.charCodeAt(pos) === 46 /* dot */) {
13429 if (pos < text.length && isDigit(text.charCodeAt(pos))) {
13431 while (pos < text.length && isDigit(text.charCodeAt(pos))) {
13436 scanError = 3 /* UnexpectedEndOfNumber */;
13437 return text.substring(start, pos);
13441 if (pos < text.length && (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */)) {
13443 if (pos < text.length && text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) {
13446 if (pos < text.length && isDigit(text.charCodeAt(pos))) {
13448 while (pos < text.length && isDigit(text.charCodeAt(pos))) {
13454 scanError = 3 /* UnexpectedEndOfNumber */;
13457 return text.substring(start, end);
13459 function scanString() {
13460 var result = '', start = pos;
13463 result += text.substring(start, pos);
13464 scanError = 2 /* UnexpectedEndOfString */;
13467 var ch = text.charCodeAt(pos);
13468 if (ch === 34 /* doubleQuote */) {
13469 result += text.substring(start, pos);
13473 if (ch === 92 /* backslash */) {
13474 result += text.substring(start, pos);
13477 scanError = 2 /* UnexpectedEndOfString */;
13480 var ch2 = text.charCodeAt(pos++);
13482 case 34 /* doubleQuote */:
13485 case 92 /* backslash */:
13488 case 47 /* slash */:
13507 var ch3 = scanHexDigits(4, true);
13509 result += String.fromCharCode(ch3);
13512 scanError = 4 /* InvalidUnicode */;
13516 scanError = 5 /* InvalidEscapeCharacter */;
13521 if (ch >= 0 && ch <= 0x1f) {
13522 if (isLineBreak(ch)) {
13523 result += text.substring(start, pos);
13524 scanError = 2 /* UnexpectedEndOfString */;
13528 scanError = 6 /* InvalidCharacter */;
13529 // mark as error but continue with string
13536 function scanNext() {
13538 scanError = 0 /* None */;
13540 lineStartOffset = lineNumber;
13541 prevTokenLineStartOffset = tokenLineStartOffset;
13545 return token = 17 /* EOF */;
13547 var code = text.charCodeAt(pos);
13548 // trivia: whitespace
13549 if (isWhiteSpace(code)) {
13552 value += String.fromCharCode(code);
13553 code = text.charCodeAt(pos);
13554 } while (isWhiteSpace(code));
13555 return token = 15 /* Trivia */;
13557 // trivia: newlines
13558 if (isLineBreak(code)) {
13560 value += String.fromCharCode(code);
13561 if (code === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
13566 tokenLineStartOffset = pos;
13567 return token = 14 /* LineBreakTrivia */;
13571 case 123 /* openBrace */:
13573 return token = 1 /* OpenBraceToken */;
13574 case 125 /* closeBrace */:
13576 return token = 2 /* CloseBraceToken */;
13577 case 91 /* openBracket */:
13579 return token = 3 /* OpenBracketToken */;
13580 case 93 /* closeBracket */:
13582 return token = 4 /* CloseBracketToken */;
13583 case 58 /* colon */:
13585 return token = 6 /* ColonToken */;
13586 case 44 /* comma */:
13588 return token = 5 /* CommaToken */;
13590 case 34 /* doubleQuote */:
13592 value = scanString();
13593 return token = 10 /* StringLiteral */;
13595 case 47 /* slash */:
13596 var start = pos - 1;
13597 // Single-line comment
13598 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
13600 while (pos < len) {
13601 if (isLineBreak(text.charCodeAt(pos))) {
13606 value = text.substring(start, pos);
13607 return token = 12 /* LineCommentTrivia */;
13609 // Multi-line comment
13610 if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
13612 var safeLength = len - 1; // For lookahead.
13613 var commentClosed = false;
13614 while (pos < safeLength) {
13615 var ch = text.charCodeAt(pos);
13616 if (ch === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
13618 commentClosed = true;
13622 if (isLineBreak(ch)) {
13623 if (ch === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
13627 tokenLineStartOffset = pos;
13630 if (!commentClosed) {
13632 scanError = 1 /* UnexpectedEndOfComment */;
13634 value = text.substring(start, pos);
13635 return token = 13 /* BlockCommentTrivia */;
13637 // just a single slash
13638 value += String.fromCharCode(code);
13640 return token = 16 /* Unknown */;
13642 case 45 /* minus */:
13643 value += String.fromCharCode(code);
13645 if (pos === len || !isDigit(text.charCodeAt(pos))) {
13646 return token = 16 /* Unknown */;
13648 // found a minus, followed by a number so
13649 // we fall through to proceed with scanning
13661 value += scanNumber();
13662 return token = 11 /* NumericLiteral */;
13663 // literals and unknown symbols
13665 // is a literal? Read the full word.
13666 while (pos < len && isUnknownContentCharacter(code)) {
13668 code = text.charCodeAt(pos);
13670 if (tokenOffset !== pos) {
13671 value = text.substring(tokenOffset, pos);
13672 // keywords: true, false, null
13674 case 'true': return token = 8 /* TrueKeyword */;
13675 case 'false': return token = 9 /* FalseKeyword */;
13676 case 'null': return token = 7 /* NullKeyword */;
13678 return token = 16 /* Unknown */;
13681 value += String.fromCharCode(code);
13683 return token = 16 /* Unknown */;
13686 function isUnknownContentCharacter(code) {
13687 if (isWhiteSpace(code) || isLineBreak(code)) {
13691 case 125 /* closeBrace */:
13692 case 93 /* closeBracket */:
13693 case 123 /* openBrace */:
13694 case 91 /* openBracket */:
13695 case 34 /* doubleQuote */:
13696 case 58 /* colon */:
13697 case 44 /* comma */:
13698 case 47 /* slash */:
13703 function scanNextNonTrivia() {
13706 result = scanNext();
13707 } while (result >= 12 /* LineCommentTrivia */ && result <= 15 /* Trivia */);
13711 setPosition: setPosition,
13712 getPosition: function () { return pos; },
13713 scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
13714 getToken: function () { return token; },
13715 getTokenValue: function () { return value; },
13716 getTokenOffset: function () { return tokenOffset; },
13717 getTokenLength: function () { return pos - tokenOffset; },
13718 getTokenStartLine: function () { return lineStartOffset; },
13719 getTokenStartCharacter: function () { return tokenOffset - prevTokenLineStartOffset; },
13720 getTokenError: function () { return scanError; },
13723 function isWhiteSpace(ch) {
13724 return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ ||
13725 ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
13726 ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */;
13728 function isLineBreak(ch) {
13729 return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */;
13731 function isDigit(ch) {
13732 return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
13738 /***/ (function(module, __webpack_exports__, __webpack_require__) {
13741 __webpack_require__.r(__webpack_exports__);
13742 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeProperty", function() { return removeProperty; });
13743 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setProperty", function() { return setProperty; });
13744 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEdit", function() { return applyEdit; });
13745 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isWS", function() { return isWS; });
13746 /* harmony import */ var _format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(94);
13747 /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(97);
13748 /*---------------------------------------------------------------------------------------------
13749 * Copyright (c) Microsoft Corporation. All rights reserved.
13750 * Licensed under the MIT License. See License.txt in the project root for license information.
13751 *--------------------------------------------------------------------------------------------*/
13755 function removeProperty(text, path, options) {
13756 return setProperty(text, path, void 0, options);
13758 function setProperty(text, originalPath, value, options) {
13760 var path = originalPath.slice();
13762 var root = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["parseTree"])(text, errors);
13763 var parent = void 0;
13764 var lastSegment = void 0;
13765 while (path.length > 0) {
13766 lastSegment = path.pop();
13767 parent = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["findNodeAtLocation"])(root, path);
13768 if (parent === void 0 && value !== void 0) {
13769 if (typeof lastSegment === 'string') {
13770 value = (_a = {}, _a[lastSegment] = value, _a);
13782 if (value === void 0) { // delete
13783 throw new Error('Can not delete in empty document');
13785 return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);
13787 else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {
13788 var existing = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["findNodeAtLocation"])(parent, [lastSegment]);
13789 if (existing !== void 0) {
13790 if (value === void 0) { // delete
13791 if (!existing.parent) {
13792 throw new Error('Malformed AST');
13794 var propertyIndex = parent.children.indexOf(existing.parent);
13795 var removeBegin = void 0;
13796 var removeEnd = existing.parent.offset + existing.parent.length;
13797 if (propertyIndex > 0) {
13798 // remove the comma of the previous node
13799 var previous = parent.children[propertyIndex - 1];
13800 removeBegin = previous.offset + previous.length;
13803 removeBegin = parent.offset + 1;
13804 if (parent.children.length > 1) {
13805 // remove the comma of the next node
13806 var next = parent.children[1];
13807 removeEnd = next.offset;
13810 return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options);
13813 // set value of existing property
13814 return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);
13818 if (value === void 0) { // delete
13819 return []; // property does not exist, nothing to do
13821 var newProperty = JSON.stringify(lastSegment) + ": " + JSON.stringify(value);
13822 var index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(function (p) { return p.children[0].value; })) : parent.children.length;
13825 var previous = parent.children[index - 1];
13826 edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
13828 else if (parent.children.length === 0) {
13829 edit = { offset: parent.offset + 1, length: 0, content: newProperty };
13832 edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };
13834 return withFormatting(text, edit, options);
13837 else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {
13838 var insertIndex = lastSegment;
13839 if (insertIndex === -1) {
13841 var newProperty = "" + JSON.stringify(value);
13843 if (parent.children.length === 0) {
13844 edit = { offset: parent.offset + 1, length: 0, content: newProperty };
13847 var previous = parent.children[parent.children.length - 1];
13848 edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
13850 return withFormatting(text, edit, options);
13852 else if (value === void 0 && parent.children.length >= 0) {
13854 var removalIndex = lastSegment;
13855 var toRemove = parent.children[removalIndex];
13857 if (parent.children.length === 1) {
13859 edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };
13861 else if (parent.children.length - 1 === removalIndex) {
13863 var previous = parent.children[removalIndex - 1];
13864 var offset = previous.offset + previous.length;
13865 var parentEndOffset = parent.offset + parent.length;
13866 edit = { offset: offset, length: parentEndOffset - 2 - offset, content: '' };
13869 edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };
13871 return withFormatting(text, edit, options);
13873 else if (value !== void 0) {
13875 var newProperty = "" + JSON.stringify(value);
13876 if (!options.isArrayInsertion && parent.children.length > lastSegment) {
13877 var toModify = parent.children[lastSegment];
13878 edit = { offset: toModify.offset, length: toModify.length, content: newProperty };
13880 else if (parent.children.length === 0 || lastSegment === 0) {
13881 edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' };
13884 var index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
13885 var previous = parent.children[index - 1];
13886 edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
13888 return withFormatting(text, edit, options);
13891 throw new Error("Can not " + (value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')) + " Array index " + insertIndex + " as length is not sufficient");
13895 throw new Error("Can not add " + (typeof lastSegment !== 'number' ? 'index' : 'property') + " to parent of type " + parent.type);
13898 function withFormatting(text, edit, options) {
13899 if (!options.formattingOptions) {
13903 var newText = applyEdit(text, edit);
13904 // format the new text
13905 var begin = edit.offset;
13906 var end = edit.offset + edit.content.length;
13907 if (edit.length === 0 || edit.content.length === 0) { // insert or remove
13908 while (begin > 0 && !Object(_format__WEBPACK_IMPORTED_MODULE_0__["isEOL"])(newText, begin - 1)) {
13911 while (end < newText.length && !Object(_format__WEBPACK_IMPORTED_MODULE_0__["isEOL"])(newText, end)) {
13915 var edits = Object(_format__WEBPACK_IMPORTED_MODULE_0__["format"])(newText, { offset: begin, length: end - begin }, options.formattingOptions);
13916 // apply the formatting edits and track the begin and end offsets of the changes
13917 for (var i = edits.length - 1; i >= 0; i--) {
13918 var edit_1 = edits[i];
13919 newText = applyEdit(newText, edit_1);
13920 begin = Math.min(begin, edit_1.offset);
13921 end = Math.max(end, edit_1.offset + edit_1.length);
13922 end += edit_1.content.length - edit_1.length;
13924 // create a single edit with all changes
13925 var editLength = text.length - (newText.length - end) - begin;
13926 return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
13928 function applyEdit(text, edit) {
13929 return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
13931 function isWS(text, offset) {
13932 return '\r\n \t'.indexOf(text.charAt(offset)) !== -1;
13938 /***/ (function(module, __webpack_exports__, __webpack_require__) {
13941 __webpack_require__.r(__webpack_exports__);
13942 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocation", function() { return getLocation; });
13943 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
13944 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTree", function() { return parseTree; });
13945 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtLocation", function() { return findNodeAtLocation; });
13946 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; });
13947 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; });
13948 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return contains; });
13949 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtOffset", function() { return findNodeAtOffset; });
13950 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "visit", function() { return visit; });
13951 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripComments", function() { return stripComments; });
13952 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeType", function() { return getNodeType; });
13953 /* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(95);
13954 /*---------------------------------------------------------------------------------------------
13955 * Copyright (c) Microsoft Corporation. All rights reserved.
13956 * Licensed under the MIT License. See License.txt in the project root for license information.
13957 *--------------------------------------------------------------------------------------------*/
13961 (function (ParseOptions) {
13962 ParseOptions.DEFAULT = {
13963 allowTrailingComma: false
13965 })(ParseOptions || (ParseOptions = {}));
13967 * 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.
13969 function getLocation(text, position) {
13970 var segments = []; // strings or numbers
13971 var earlyReturnException = new Object();
13972 var previousNode = undefined;
13973 var previousNodeInst = {
13980 var isAtPropertyKey = false;
13981 function setPreviousNode(value, offset, length, type) {
13982 previousNodeInst.value = value;
13983 previousNodeInst.offset = offset;
13984 previousNodeInst.length = length;
13985 previousNodeInst.type = type;
13986 previousNodeInst.colonOffset = undefined;
13987 previousNode = previousNodeInst;
13991 onObjectBegin: function (offset, length) {
13992 if (position <= offset) {
13993 throw earlyReturnException;
13995 previousNode = undefined;
13996 isAtPropertyKey = position > offset;
13997 segments.push(''); // push a placeholder (will be replaced)
13999 onObjectProperty: function (name, offset, length) {
14000 if (position < offset) {
14001 throw earlyReturnException;
14003 setPreviousNode(name, offset, length, 'property');
14004 segments[segments.length - 1] = name;
14005 if (position <= offset + length) {
14006 throw earlyReturnException;
14009 onObjectEnd: function (offset, length) {
14010 if (position <= offset) {
14011 throw earlyReturnException;
14013 previousNode = undefined;
14016 onArrayBegin: function (offset, length) {
14017 if (position <= offset) {
14018 throw earlyReturnException;
14020 previousNode = undefined;
14023 onArrayEnd: function (offset, length) {
14024 if (position <= offset) {
14025 throw earlyReturnException;
14027 previousNode = undefined;
14030 onLiteralValue: function (value, offset, length) {
14031 if (position < offset) {
14032 throw earlyReturnException;
14034 setPreviousNode(value, offset, length, getNodeType(value));
14035 if (position <= offset + length) {
14036 throw earlyReturnException;
14039 onSeparator: function (sep, offset, length) {
14040 if (position <= offset) {
14041 throw earlyReturnException;
14043 if (sep === ':' && previousNode && previousNode.type === 'property') {
14044 previousNode.colonOffset = offset;
14045 isAtPropertyKey = false;
14046 previousNode = undefined;
14048 else if (sep === ',') {
14049 var last = segments[segments.length - 1];
14050 if (typeof last === 'number') {
14051 segments[segments.length - 1] = last + 1;
14054 isAtPropertyKey = true;
14055 segments[segments.length - 1] = '';
14057 previousNode = undefined;
14063 if (e !== earlyReturnException) {
14069 previousNode: previousNode,
14070 isAtPropertyKey: isAtPropertyKey,
14071 matches: function (pattern) {
14073 for (var i = 0; k < pattern.length && i < segments.length; i++) {
14074 if (pattern[k] === segments[i] || pattern[k] === '*') {
14077 else if (pattern[k] !== '**') {
14081 return k === pattern.length;
14086 * 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.
14087 * Therefore always check the errors list to find out if the input was valid.
14089 function parse(text, errors, options) {
14090 if (errors === void 0) { errors = []; }
14091 if (options === void 0) { options = ParseOptions.DEFAULT; }
14092 var currentProperty = null;
14093 var currentParent = [];
14094 var previousParents = [];
14095 function onValue(value) {
14096 if (Array.isArray(currentParent)) {
14097 currentParent.push(value);
14099 else if (currentProperty !== null) {
14100 currentParent[currentProperty] = value;
14104 onObjectBegin: function () {
14107 previousParents.push(currentParent);
14108 currentParent = object;
14109 currentProperty = null;
14111 onObjectProperty: function (name) {
14112 currentProperty = name;
14114 onObjectEnd: function () {
14115 currentParent = previousParents.pop();
14117 onArrayBegin: function () {
14120 previousParents.push(currentParent);
14121 currentParent = array;
14122 currentProperty = null;
14124 onArrayEnd: function () {
14125 currentParent = previousParents.pop();
14127 onLiteralValue: onValue,
14128 onError: function (error, offset, length) {
14129 errors.push({ error: error, offset: offset, length: length });
14132 visit(text, visitor, options);
14133 return currentParent[0];
14136 * 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.
14138 function parseTree(text, errors, options) {
14139 if (errors === void 0) { errors = []; }
14140 if (options === void 0) { options = ParseOptions.DEFAULT; }
14141 var currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root
14142 function ensurePropertyComplete(endOffset) {
14143 if (currentParent.type === 'property') {
14144 currentParent.length = endOffset - currentParent.offset;
14145 currentParent = currentParent.parent;
14148 function onValue(valueNode) {
14149 currentParent.children.push(valueNode);
14153 onObjectBegin: function (offset) {
14154 currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });
14156 onObjectProperty: function (name, offset, length) {
14157 currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });
14158 currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });
14160 onObjectEnd: function (offset, length) {
14161 ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete
14162 currentParent.length = offset + length - currentParent.offset;
14163 currentParent = currentParent.parent;
14164 ensurePropertyComplete(offset + length);
14166 onArrayBegin: function (offset, length) {
14167 currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });
14169 onArrayEnd: function (offset, length) {
14170 currentParent.length = offset + length - currentParent.offset;
14171 currentParent = currentParent.parent;
14172 ensurePropertyComplete(offset + length);
14174 onLiteralValue: function (value, offset, length) {
14175 onValue({ type: getNodeType(value), offset: offset, length: length, parent: currentParent, value: value });
14176 ensurePropertyComplete(offset + length);
14178 onSeparator: function (sep, offset, length) {
14179 if (currentParent.type === 'property') {
14181 currentParent.colonOffset = offset;
14183 else if (sep === ',') {
14184 ensurePropertyComplete(offset);
14188 onError: function (error, offset, length) {
14189 errors.push({ error: error, offset: offset, length: length });
14192 visit(text, visitor, options);
14193 var result = currentParent.children[0];
14195 delete result.parent;
14200 * Finds the node at the given path in a JSON DOM.
14202 function findNodeAtLocation(root, path) {
14207 for (var _i = 0, path_1 = path; _i < path_1.length; _i++) {
14208 var segment = path_1[_i];
14209 if (typeof segment === 'string') {
14210 if (node.type !== 'object' || !Array.isArray(node.children)) {
14214 for (var _a = 0, _b = node.children; _a < _b.length; _a++) {
14215 var propertyNode = _b[_a];
14216 if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) {
14217 node = propertyNode.children[1];
14227 var index = segment;
14228 if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
14231 node = node.children[index];
14237 * Gets the JSON path of the given JSON DOM node
14239 function getNodePath(node) {
14240 if (!node.parent || !node.parent.children) {
14243 var path = getNodePath(node.parent);
14244 if (node.parent.type === 'property') {
14245 var key = node.parent.children[0].value;
14248 else if (node.parent.type === 'array') {
14249 var index = node.parent.children.indexOf(node);
14250 if (index !== -1) {
14257 * Evaluates the JavaScript object of the given JSON DOM node
14259 function getNodeValue(node) {
14260 switch (node.type) {
14262 return node.children.map(getNodeValue);
14264 var obj = Object.create(null);
14265 for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
14267 var valueNode = prop.children[1];
14269 obj[prop.children[0].value] = getNodeValue(valueNode);
14282 function contains(node, offset, includeRightBound) {
14283 if (includeRightBound === void 0) { includeRightBound = false; }
14284 return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));
14287 * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
14289 function findNodeAtOffset(node, offset, includeRightBound) {
14290 if (includeRightBound === void 0) { includeRightBound = false; }
14291 if (contains(node, offset, includeRightBound)) {
14292 var children = node.children;
14293 if (Array.isArray(children)) {
14294 for (var i = 0; i < children.length && children[i].offset <= offset; i++) {
14295 var item = findNodeAtOffset(children[i], offset, includeRightBound);
14306 * Parses the given text and invokes the visitor functions for each object, array and literal reached.
14308 function visit(text, visitor, options) {
14309 if (options === void 0) { options = ParseOptions.DEFAULT; }
14310 var _scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(text, false);
14311 function toNoArgVisit(visitFunction) {
14312 return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
14314 function toOneArgVisit(visitFunction) {
14315 return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
14317 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);
14318 var disallowComments = options && options.disallowComments;
14319 var allowTrailingComma = options && options.allowTrailingComma;
14320 function scanNext() {
14322 var token = _scanner.scan();
14323 switch (_scanner.getTokenError()) {
14324 case 4 /* InvalidUnicode */:
14325 handleError(14 /* InvalidUnicode */);
14327 case 5 /* InvalidEscapeCharacter */:
14328 handleError(15 /* InvalidEscapeCharacter */);
14330 case 3 /* UnexpectedEndOfNumber */:
14331 handleError(13 /* UnexpectedEndOfNumber */);
14333 case 1 /* UnexpectedEndOfComment */:
14334 if (!disallowComments) {
14335 handleError(11 /* UnexpectedEndOfComment */);
14338 case 2 /* UnexpectedEndOfString */:
14339 handleError(12 /* UnexpectedEndOfString */);
14341 case 6 /* InvalidCharacter */:
14342 handleError(16 /* InvalidCharacter */);
14346 case 12 /* LineCommentTrivia */:
14347 case 13 /* BlockCommentTrivia */:
14348 if (disallowComments) {
14349 handleError(10 /* InvalidCommentToken */);
14355 case 16 /* Unknown */:
14356 handleError(1 /* InvalidSymbol */);
14358 case 15 /* Trivia */:
14359 case 14 /* LineBreakTrivia */:
14366 function handleError(error, skipUntilAfter, skipUntil) {
14367 if (skipUntilAfter === void 0) { skipUntilAfter = []; }
14368 if (skipUntil === void 0) { skipUntil = []; }
14370 if (skipUntilAfter.length + skipUntil.length > 0) {
14371 var token = _scanner.getToken();
14372 while (token !== 17 /* EOF */) {
14373 if (skipUntilAfter.indexOf(token) !== -1) {
14377 else if (skipUntil.indexOf(token) !== -1) {
14380 token = scanNext();
14384 function parseString(isValue) {
14385 var value = _scanner.getTokenValue();
14387 onLiteralValue(value);
14390 onObjectProperty(value);
14395 function parseLiteral() {
14396 switch (_scanner.getToken()) {
14397 case 11 /* NumericLiteral */:
14400 value = JSON.parse(_scanner.getTokenValue());
14401 if (typeof value !== 'number') {
14402 handleError(2 /* InvalidNumberFormat */);
14407 handleError(2 /* InvalidNumberFormat */);
14409 onLiteralValue(value);
14411 case 7 /* NullKeyword */:
14412 onLiteralValue(null);
14414 case 8 /* TrueKeyword */:
14415 onLiteralValue(true);
14417 case 9 /* FalseKeyword */:
14418 onLiteralValue(false);
14426 function parseProperty() {
14427 if (_scanner.getToken() !== 10 /* StringLiteral */) {
14428 handleError(3 /* PropertyNameExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
14431 parseString(false);
14432 if (_scanner.getToken() === 6 /* ColonToken */) {
14434 scanNext(); // consume colon
14435 if (!parseValue()) {
14436 handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
14440 handleError(5 /* ColonExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
14444 function parseObject() {
14446 scanNext(); // consume open brace
14447 var needsComma = false;
14448 while (_scanner.getToken() !== 2 /* CloseBraceToken */ && _scanner.getToken() !== 17 /* EOF */) {
14449 if (_scanner.getToken() === 5 /* CommaToken */) {
14451 handleError(4 /* ValueExpected */, [], []);
14454 scanNext(); // consume comma
14455 if (_scanner.getToken() === 2 /* CloseBraceToken */ && allowTrailingComma) {
14459 else if (needsComma) {
14460 handleError(6 /* CommaExpected */, [], []);
14462 if (!parseProperty()) {
14463 handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
14468 if (_scanner.getToken() !== 2 /* CloseBraceToken */) {
14469 handleError(7 /* CloseBraceExpected */, [2 /* CloseBraceToken */], []);
14472 scanNext(); // consume close brace
14476 function parseArray() {
14478 scanNext(); // consume open bracket
14479 var needsComma = false;
14480 while (_scanner.getToken() !== 4 /* CloseBracketToken */ && _scanner.getToken() !== 17 /* EOF */) {
14481 if (_scanner.getToken() === 5 /* CommaToken */) {
14483 handleError(4 /* ValueExpected */, [], []);
14486 scanNext(); // consume comma
14487 if (_scanner.getToken() === 4 /* CloseBracketToken */ && allowTrailingComma) {
14491 else if (needsComma) {
14492 handleError(6 /* CommaExpected */, [], []);
14494 if (!parseValue()) {
14495 handleError(4 /* ValueExpected */, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
14500 if (_scanner.getToken() !== 4 /* CloseBracketToken */) {
14501 handleError(8 /* CloseBracketExpected */, [4 /* CloseBracketToken */], []);
14504 scanNext(); // consume close bracket
14508 function parseValue() {
14509 switch (_scanner.getToken()) {
14510 case 3 /* OpenBracketToken */:
14511 return parseArray();
14512 case 1 /* OpenBraceToken */:
14513 return parseObject();
14514 case 10 /* StringLiteral */:
14515 return parseString(true);
14517 return parseLiteral();
14521 if (_scanner.getToken() === 17 /* EOF */) {
14522 if (options.allowEmptyContent) {
14525 handleError(4 /* ValueExpected */, [], []);
14528 if (!parseValue()) {
14529 handleError(4 /* ValueExpected */, [], []);
14532 if (_scanner.getToken() !== 17 /* EOF */) {
14533 handleError(9 /* EndOfFileExpected */, [], []);
14538 * Takes JSON with JavaScript-style comments and remove
14539 * them. Optionally replaces every none-newline character
14540 * of comments with a replaceCharacter
14542 function stripComments(text, replaceCh) {
14543 var _scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(text), parts = [], kind, offset = 0, pos;
14545 pos = _scanner.getPosition();
14546 kind = _scanner.scan();
14548 case 12 /* LineCommentTrivia */:
14549 case 13 /* BlockCommentTrivia */:
14551 if (offset !== pos) {
14552 parts.push(text.substring(offset, pos));
14554 if (replaceCh !== undefined) {
14555 parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh));
14557 offset = _scanner.getPosition();
14560 } while (kind !== 17 /* EOF */);
14561 return parts.join('');
14563 function getNodeType(value) {
14564 switch (typeof value) {
14565 case 'boolean': return 'boolean';
14566 case 'number': return 'number';
14567 case 'string': return 'string';
14572 else if (Array.isArray(value)) {
14577 default: return 'null';
14584 /***/ (function(module, __webpack_exports__, __webpack_require__) {
14587 __webpack_require__.r(__webpack_exports__);
14588 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "equals", function() { return equals; });
14589 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNumber", function() { return isNumber; });
14590 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDefined", function() { return isDefined; });
14591 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBoolean", function() { return isBoolean; });
14592 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isString", function() { return isString; });
14593 /*---------------------------------------------------------------------------------------------
14594 * Copyright (c) Microsoft Corporation. All rights reserved.
14595 * Licensed under the MIT License. See License.txt in the project root for license information.
14596 *--------------------------------------------------------------------------------------------*/
14597 function equals(one, other) {
14598 if (one === other) {
14601 if (one === null || one === undefined || other === null || other === undefined) {
14604 if (typeof one !== typeof other) {
14607 if (typeof one !== 'object') {
14610 if ((Array.isArray(one)) !== (Array.isArray(other))) {
14614 if (Array.isArray(one)) {
14615 if (one.length !== other.length) {
14618 for (i = 0; i < one.length; i++) {
14619 if (!equals(one[i], other[i])) {
14630 var otherKeys = [];
14631 for (key in other) {
14632 otherKeys.push(key);
14635 if (!equals(oneKeys, otherKeys)) {
14638 for (i = 0; i < oneKeys.length; i++) {
14639 if (!equals(one[oneKeys[i]], other[oneKeys[i]])) {
14646 function isNumber(val) {
14647 return typeof val === 'number';
14649 function isDefined(val) {
14650 return typeof val !== 'undefined';
14652 function isBoolean(val) {
14653 return typeof val === 'boolean';
14655 function isString(val) {
14656 return typeof val === 'string';
14662 /***/ (function(module, __webpack_exports__, __webpack_require__) {
14665 __webpack_require__.r(__webpack_exports__);
14666 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorCode", function() { return ErrorCode; });
14667 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClientCapabilities", function() { return ClientCapabilities; });
14668 /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(18);
14669 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Range"]; });
14671 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["TextEdit"]; });
14673 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Color"]; });
14675 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["ColorInformation"]; });
14677 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["ColorPresentation"]; });
14679 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["FoldingRange"]; });
14681 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["FoldingRangeKind"]; });
14683 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["SelectionRange"]; });
14685 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Diagnostic"]; });
14687 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["DiagnosticSeverity"]; });
14689 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["CompletionItem"]; });
14691 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["CompletionItemKind"]; });
14693 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["CompletionList"]; });
14695 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Position"]; });
14697 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["InsertTextFormat"]; });
14699 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["MarkupContent"]; });
14701 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["MarkupKind"]; });
14703 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["SymbolInformation"]; });
14705 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["SymbolKind"]; });
14707 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["DocumentSymbol"]; });
14709 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Location"]; });
14711 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Hover"]; });
14713 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["MarkedString"]; });
14715 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["FormattingOptions"]; });
14717 /* harmony import */ var vscode_languageserver_textdocument__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(100);
14718 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return vscode_languageserver_textdocument__WEBPACK_IMPORTED_MODULE_1__["TextDocument"]; });
14720 /*---------------------------------------------------------------------------------------------
14721 * Copyright (c) Microsoft Corporation. All rights reserved.
14722 * Licensed under the MIT License. See License.txt in the project root for license information.
14723 *--------------------------------------------------------------------------------------------*/
14728 * Error codes used by diagnostics
14731 (function (ErrorCode) {
14732 ErrorCode[ErrorCode["Undefined"] = 0] = "Undefined";
14733 ErrorCode[ErrorCode["EnumValueMismatch"] = 1] = "EnumValueMismatch";
14734 ErrorCode[ErrorCode["UnexpectedEndOfComment"] = 257] = "UnexpectedEndOfComment";
14735 ErrorCode[ErrorCode["UnexpectedEndOfString"] = 258] = "UnexpectedEndOfString";
14736 ErrorCode[ErrorCode["UnexpectedEndOfNumber"] = 259] = "UnexpectedEndOfNumber";
14737 ErrorCode[ErrorCode["InvalidUnicode"] = 260] = "InvalidUnicode";
14738 ErrorCode[ErrorCode["InvalidEscapeCharacter"] = 261] = "InvalidEscapeCharacter";
14739 ErrorCode[ErrorCode["InvalidCharacter"] = 262] = "InvalidCharacter";
14740 ErrorCode[ErrorCode["PropertyExpected"] = 513] = "PropertyExpected";
14741 ErrorCode[ErrorCode["CommaExpected"] = 514] = "CommaExpected";
14742 ErrorCode[ErrorCode["ColonExpected"] = 515] = "ColonExpected";
14743 ErrorCode[ErrorCode["ValueExpected"] = 516] = "ValueExpected";
14744 ErrorCode[ErrorCode["CommaOrCloseBacketExpected"] = 517] = "CommaOrCloseBacketExpected";
14745 ErrorCode[ErrorCode["CommaOrCloseBraceExpected"] = 518] = "CommaOrCloseBraceExpected";
14746 ErrorCode[ErrorCode["TrailingComma"] = 519] = "TrailingComma";
14747 ErrorCode[ErrorCode["DuplicateKey"] = 520] = "DuplicateKey";
14748 ErrorCode[ErrorCode["CommentNotPermitted"] = 521] = "CommentNotPermitted";
14749 ErrorCode[ErrorCode["SchemaResolveError"] = 768] = "SchemaResolveError";
14750 })(ErrorCode || (ErrorCode = {}));
14751 var ClientCapabilities;
14752 (function (ClientCapabilities) {
14753 ClientCapabilities.LATEST = {
14757 documentationFormat: [vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["MarkupKind"].Markdown, vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["MarkupKind"].PlainText],
14758 commitCharactersSupport: true
14763 })(ClientCapabilities || (ClientCapabilities = {}));
14768 /***/ (function(module, __webpack_exports__, __webpack_require__) {
14771 __webpack_require__.r(__webpack_exports__);
14772 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
14773 /* --------------------------------------------------------------------------------------------
14774 * Copyright (c) Microsoft Corporation. All rights reserved.
14775 * Licensed under the MIT License. See License.txt in the project root for license information.
14776 * ------------------------------------------------------------------------------------------ */
14778 var FullTextDocument = /** @class */ (function () {
14779 function FullTextDocument(uri, languageId, version, content) {
14781 this._languageId = languageId;
14782 this._version = version;
14783 this._content = content;
14784 this._lineOffsets = undefined;
14786 Object.defineProperty(FullTextDocument.prototype, "uri", {
14793 Object.defineProperty(FullTextDocument.prototype, "languageId", {
14795 return this._languageId;
14800 Object.defineProperty(FullTextDocument.prototype, "version", {
14802 return this._version;
14807 FullTextDocument.prototype.getText = function (range) {
14809 var start = this.offsetAt(range.start);
14810 var end = this.offsetAt(range.end);
14811 return this._content.substring(start, end);
14813 return this._content;
14815 FullTextDocument.prototype.update = function (changes, version) {
14816 for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) {
14817 var change = changes_1[_i];
14818 if (FullTextDocument.isIncremental(change)) {
14819 // makes sure start is before end
14820 var range = getWellformedRange(change.range);
14822 var startOffset = this.offsetAt(range.start);
14823 var endOffset = this.offsetAt(range.end);
14824 this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length);
14825 // update the offsets
14826 var startLine = Math.max(range.start.line, 0);
14827 var endLine = Math.max(range.end.line, 0);
14828 var lineOffsets = this._lineOffsets;
14829 var addedLineOffsets = computeLineOffsets(change.text, false, startOffset);
14830 if (endLine - startLine === addedLineOffsets.length) {
14831 for (var i = 0, len = addedLineOffsets.length; i < len; i++) {
14832 lineOffsets[i + startLine + 1] = addedLineOffsets[i];
14836 if (addedLineOffsets.length < 10000) {
14837 lineOffsets.splice.apply(lineOffsets, [startLine + 1, endLine - startLine].concat(addedLineOffsets));
14839 else { // avoid too many arguments for splice
14840 this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1));
14843 var diff = change.text.length - (endOffset - startOffset);
14845 for (var i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) {
14846 lineOffsets[i] = lineOffsets[i] + diff;
14850 else if (FullTextDocument.isFull(change)) {
14851 this._content = change.text;
14852 this._lineOffsets = undefined;
14855 throw new Error('Unknown change event received');
14858 this._version = version;
14860 FullTextDocument.prototype.getLineOffsets = function () {
14861 if (this._lineOffsets === undefined) {
14862 this._lineOffsets = computeLineOffsets(this._content, true);
14864 return this._lineOffsets;
14866 FullTextDocument.prototype.positionAt = function (offset) {
14867 offset = Math.max(Math.min(offset, this._content.length), 0);
14868 var lineOffsets = this.getLineOffsets();
14869 var low = 0, high = lineOffsets.length;
14871 return { line: 0, character: offset };
14873 while (low < high) {
14874 var mid = Math.floor((low + high) / 2);
14875 if (lineOffsets[mid] > offset) {
14882 // low is the least x for which the line offset is larger than the current offset
14883 // or array.length if no line offset is larger than the current offset
14884 var line = low - 1;
14885 return { line: line, character: offset - lineOffsets[line] };
14887 FullTextDocument.prototype.offsetAt = function (position) {
14888 var lineOffsets = this.getLineOffsets();
14889 if (position.line >= lineOffsets.length) {
14890 return this._content.length;
14892 else if (position.line < 0) {
14895 var lineOffset = lineOffsets[position.line];
14896 var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
14897 return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
14899 Object.defineProperty(FullTextDocument.prototype, "lineCount", {
14901 return this.getLineOffsets().length;
14906 FullTextDocument.isIncremental = function (event) {
14907 var candidate = event;
14908 return candidate !== undefined && candidate !== null &&
14909 typeof candidate.text === 'string' && candidate.range !== undefined &&
14910 (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number');
14912 FullTextDocument.isFull = function (event) {
14913 var candidate = event;
14914 return candidate !== undefined && candidate !== null &&
14915 typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined;
14917 return FullTextDocument;
14920 (function (TextDocument) {
14922 * Creates a new text document.
14924 * @param uri The document's uri.
14925 * @param languageId The document's language Id.
14926 * @param version The document's initial version number.
14927 * @param content The document's content.
14929 function create(uri, languageId, version, content) {
14930 return new FullTextDocument(uri, languageId, version, content);
14932 TextDocument.create = create;
14934 * Updates a TextDocument by modifing its content.
14936 * @param document the document to update. Only documents created by TextDocument.create are valid inputs.
14937 * @param changes the changes to apply to the document.
14938 * @returns The updated TextDocument. Note: That's the same document instance passed in as first parameter.
14941 function update(document, changes, version) {
14942 if (document instanceof FullTextDocument) {
14943 document.update(changes, version);
14947 throw new Error('TextDocument.update: document must be created by TextDocument.create');
14950 TextDocument.update = update;
14951 function applyEdits(document, edits) {
14952 var text = document.getText();
14953 var sortedEdits = mergeSort(edits.map(getWellformedEdit), function (a, b) {
14954 var diff = a.range.start.line - b.range.start.line;
14956 return a.range.start.character - b.range.start.character;
14960 var lastModifiedOffset = 0;
14962 for (var _i = 0, sortedEdits_1 = sortedEdits; _i < sortedEdits_1.length; _i++) {
14963 var e = sortedEdits_1[_i];
14964 var startOffset = document.offsetAt(e.range.start);
14965 if (startOffset < lastModifiedOffset) {
14966 throw new Error('Overlapping edit');
14968 else if (startOffset > lastModifiedOffset) {
14969 spans.push(text.substring(lastModifiedOffset, startOffset));
14971 if (e.newText.length) {
14972 spans.push(e.newText);
14974 lastModifiedOffset = document.offsetAt(e.range.end);
14976 spans.push(text.substr(lastModifiedOffset));
14977 return spans.join('');
14979 TextDocument.applyEdits = applyEdits;
14980 })(TextDocument || (TextDocument = {}));
14981 function mergeSort(data, compare) {
14982 if (data.length <= 1) {
14986 var p = (data.length / 2) | 0;
14987 var left = data.slice(0, p);
14988 var right = data.slice(p);
14989 mergeSort(left, compare);
14990 mergeSort(right, compare);
14994 while (leftIdx < left.length && rightIdx < right.length) {
14995 var ret = compare(left[leftIdx], right[rightIdx]);
14997 // smaller_equal -> take left to preserve order
14998 data[i++] = left[leftIdx++];
15001 // greater -> take right
15002 data[i++] = right[rightIdx++];
15005 while (leftIdx < left.length) {
15006 data[i++] = left[leftIdx++];
15008 while (rightIdx < right.length) {
15009 data[i++] = right[rightIdx++];
15013 function computeLineOffsets(text, isAtLineStart, textOffset) {
15014 if (textOffset === void 0) { textOffset = 0; }
15015 var result = isAtLineStart ? [textOffset] : [];
15016 for (var i = 0; i < text.length; i++) {
15017 var ch = text.charCodeAt(i);
15018 if (ch === 13 /* CarriageReturn */ || ch === 10 /* LineFeed */) {
15019 if (ch === 13 /* CarriageReturn */ && i + 1 < text.length && text.charCodeAt(i + 1) === 10 /* LineFeed */) {
15022 result.push(textOffset + i + 1);
15027 function getWellformedRange(range) {
15028 var start = range.start;
15029 var end = range.end;
15030 if (start.line > end.line || (start.line === end.line && start.character > end.character)) {
15031 return { start: end, end: start };
15035 function getWellformedEdit(textEdit) {
15036 var range = getWellformedRange(textEdit.range);
15037 if (range !== textEdit.range) {
15038 return { newText: textEdit.newText, range: range };
15046 /***/ (function(module, exports, __webpack_require__) {
15049 /* --------------------------------------------------------------------------------------------
\r
15050 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
15051 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
15052 * ------------------------------------------------------------------------------------------ */
\r
15054 Object.defineProperty(exports, "__esModule", { value: true });
\r
15055 var path = __webpack_require__(1);
\r
15056 var fs = __webpack_require__(2);
\r
15057 var toString = Object.prototype.toString;
\r
15058 function isDefined(value) {
\r
15059 return typeof value !== 'undefined';
\r
15061 function isNumber(value) {
\r
15062 return toString.call(value) === '[object Number]';
\r
15064 function isString(value) {
\r
15065 return toString.call(value) === '[object String]';
\r
15067 function isBoolean(value) {
\r
15068 return value === true || value === false;
\r
15070 function readJsonFileSync(filename) {
\r
15071 return JSON.parse(fs.readFileSync(filename, 'utf8'));
\r
15073 var MessageFormat;
\r
15074 (function (MessageFormat) {
\r
15075 MessageFormat["file"] = "file";
\r
15076 MessageFormat["bundle"] = "bundle";
\r
15077 MessageFormat["both"] = "both";
\r
15078 })(MessageFormat = exports.MessageFormat || (exports.MessageFormat = {}));
\r
15079 var BundleFormat;
\r
15080 (function (BundleFormat) {
\r
15081 // the nls.bundle format
\r
15082 BundleFormat["standalone"] = "standalone";
\r
15083 BundleFormat["languagePack"] = "languagePack";
\r
15084 })(BundleFormat = exports.BundleFormat || (exports.BundleFormat = {}));
\r
15085 var LocalizeInfo;
\r
15086 (function (LocalizeInfo) {
\r
15087 function is(value) {
\r
15088 var candidate = value;
\r
15089 return candidate && isDefined(candidate.key) && isDefined(candidate.comment);
\r
15091 LocalizeInfo.is = is;
\r
15092 })(LocalizeInfo || (LocalizeInfo = {}));
\r
15093 var resolvedLanguage;
\r
15094 var resolvedBundles;
\r
15097 function initializeSettings() {
\r
15098 options = { locale: undefined, language: undefined, languagePackSupport: false, cacheLanguageResolution: true, messageFormat: MessageFormat.bundle };
\r
15099 if (isString(process.env.VSCODE_NLS_CONFIG)) {
\r
15101 var vscodeOptions_1 = JSON.parse(process.env.VSCODE_NLS_CONFIG);
\r
15102 var language = void 0;
\r
15103 var locale = void 0;
\r
15104 if (vscodeOptions_1.availableLanguages) {
\r
15105 var value = vscodeOptions_1.availableLanguages['*'];
\r
15106 if (isString(value)) {
\r
15107 language = value;
\r
15110 if (isString(vscodeOptions_1.locale)) {
\r
15111 options.locale = vscodeOptions_1.locale.toLowerCase();
\r
15113 if (language === undefined) {
\r
15114 options.language = options.locale;
\r
15116 else if (language !== 'en') {
\r
15117 options.language = language;
\r
15119 if (isBoolean(vscodeOptions_1._languagePackSupport)) {
\r
15120 options.languagePackSupport = vscodeOptions_1._languagePackSupport;
\r
15122 if (isString(vscodeOptions_1._cacheRoot)) {
\r
15123 options.cacheRoot = vscodeOptions_1._cacheRoot;
\r
15125 if (isString(vscodeOptions_1._languagePackId)) {
\r
15126 options.languagePackId = vscodeOptions_1._languagePackId;
\r
15128 if (isString(vscodeOptions_1._translationsConfigFile)) {
\r
15129 options.translationsConfigFile = vscodeOptions_1._translationsConfigFile;
\r
15131 options.translationsConfig = readJsonFileSync(options.translationsConfigFile);
\r
15134 // We can't read the translation config file. Mark the cache as corrupted.
\r
15135 if (vscodeOptions_1._corruptedFile) {
\r
15136 var dirname = path.dirname(vscodeOptions_1._corruptedFile);
\r
15137 fs.exists(dirname, function (exists) {
\r
15139 fs.writeFile(vscodeOptions_1._corruptedFile, 'corrupted', 'utf8', function (err) {
\r
15140 console.error(err);
\r
15152 isPseudo = options.locale === 'pseudo';
\r
15153 resolvedLanguage = undefined;
\r
15154 resolvedBundles = Object.create(null);
\r
15156 initializeSettings();
\r
15157 function supportsLanguagePack() {
\r
15158 return options.languagePackSupport === true && options.cacheRoot !== undefined && options.languagePackId !== undefined && options.translationsConfigFile !== undefined
\r
15159 && options.translationsConfig !== undefined;
\r
15161 function format(message, args) {
\r
15164 // FF3B and FF3D is the Unicode zenkaku representation for [ and ]
\r
15165 message = '\uFF3B' + message.replace(/[aouei]/g, '$&$&') + '\uFF3D';
\r
15167 if (args.length === 0) {
\r
15168 result = message;
\r
15171 result = message.replace(/\{(\d+)\}/g, function (match, rest) {
\r
15172 var index = rest[0];
\r
15173 var arg = args[index];
\r
15174 var replacement = match;
\r
15175 if (typeof arg === 'string') {
\r
15176 replacement = arg;
\r
15178 else if (typeof arg === 'number' || typeof arg === 'boolean' || arg === void 0 || arg === null) {
\r
15179 replacement = String(arg);
\r
15181 return replacement;
\r
15186 function createScopedLocalizeFunction(messages) {
\r
15187 return function (key, message) {
\r
15189 for (var _i = 2; _i < arguments.length; _i++) {
\r
15190 args[_i - 2] = arguments[_i];
\r
15192 if (isNumber(key)) {
\r
15193 if (key >= messages.length) {
\r
15194 console.error("Broken localize call found. Index out of bounds. Stacktrace is\n: " + new Error('').stack);
\r
15197 return format(messages[key], args);
\r
15200 if (isString(message)) {
\r
15201 console.warn("Message " + message + " didn't get externalized correctly.");
\r
15202 return format(message, args);
\r
15205 console.error("Broken localize call found. Stacktrace is\n: " + new Error('').stack);
\r
15210 function localize(key, message) {
\r
15212 for (var _i = 2; _i < arguments.length; _i++) {
\r
15213 args[_i - 2] = arguments[_i];
\r
15215 return format(message, args);
\r
15217 function resolveLanguage(file) {
\r
15218 var resolvedLanguage;
\r
15219 if (options.cacheLanguageResolution && resolvedLanguage) {
\r
15220 resolvedLanguage = resolvedLanguage;
\r
15223 if (isPseudo || !options.language) {
\r
15224 resolvedLanguage = '.nls.json';
\r
15227 var locale = options.language;
\r
15229 var candidate = '.nls.' + locale + '.json';
\r
15230 if (fs.existsSync(file + candidate)) {
\r
15231 resolvedLanguage = candidate;
\r
15235 var index = locale.lastIndexOf('-');
\r
15237 locale = locale.substring(0, index);
\r
15240 resolvedLanguage = '.nls.json';
\r
15246 if (options.cacheLanguageResolution) {
\r
15247 resolvedLanguage = resolvedLanguage;
\r
15250 return file + resolvedLanguage;
\r
15252 function findInTheBoxBundle(root) {
\r
15253 var language = options.language;
\r
15254 while (language) {
\r
15255 var candidate = path.join(root, "nls.bundle." + language + ".json");
\r
15256 if (fs.existsSync(candidate)) {
\r
15257 return candidate;
\r
15260 var index = language.lastIndexOf('-');
\r
15262 language = language.substring(0, index);
\r
15265 language = undefined;
\r
15269 // Test if we can reslove the default bundle.
\r
15270 if (language === undefined) {
\r
15271 var candidate = path.join(root, 'nls.bundle.json');
\r
15272 if (fs.existsSync(candidate)) {
\r
15273 return candidate;
\r
15276 return undefined;
\r
15278 function mkdir(directory) {
\r
15280 fs.mkdirSync(directory);
\r
15283 if (err.code === 'EEXIST') {
\r
15286 else if (err.code === 'ENOENT') {
\r
15287 var parent = path.dirname(directory);
\r
15288 if (parent !== directory) {
\r
15290 fs.mkdirSync(directory);
\r
15298 function createDefaultNlsBundle(folder) {
\r
15299 var metaData = readJsonFileSync(path.join(folder, 'nls.metadata.json'));
\r
15300 var result = Object.create(null);
\r
15301 for (var module_1 in metaData) {
\r
15302 var entry = metaData[module_1];
\r
15303 result[module_1] = entry.messages;
\r
15307 function createNLSBundle(header, metaDataPath) {
\r
15308 var languagePackLocation = options.translationsConfig[header.id];
\r
15309 if (!languagePackLocation) {
\r
15310 return undefined;
\r
15312 var languagePack = readJsonFileSync(languagePackLocation).contents;
\r
15313 var metaData = readJsonFileSync(path.join(metaDataPath, 'nls.metadata.json'));
\r
15314 var result = Object.create(null);
\r
15315 for (var module_2 in metaData) {
\r
15316 var entry = metaData[module_2];
\r
15317 var translations = languagePack[header.outDir + "/" + module_2];
\r
15318 if (translations) {
\r
15319 var resultMessages = [];
\r
15320 for (var i = 0; i < entry.keys.length; i++) {
\r
15321 var messageKey = entry.keys[i];
\r
15322 var key = isString(messageKey) ? messageKey : messageKey.key;
\r
15323 var translatedMessage = translations[key];
\r
15324 if (translatedMessage === undefined) {
\r
15325 translatedMessage = entry.messages[i];
\r
15327 resultMessages.push(translatedMessage);
\r
15329 result[module_2] = resultMessages;
\r
15332 result[module_2] = entry.messages;
\r
15337 function touch(file) {
\r
15338 var d = new Date();
\r
15339 fs.utimes(file, d, d, function () {
\r
15340 // Do nothing. Ignore
\r
15343 function cacheBundle(key, bundle) {
\r
15344 resolvedBundles[key] = bundle;
\r
15347 function loadNlsBundleOrCreateFromI18n(header, bundlePath) {
\r
15349 var bundle = path.join(options.cacheRoot, header.id + "-" + header.hash + ".json");
\r
15350 var useMemoryOnly = false;
\r
15351 var writeBundle = false;
\r
15353 result = JSON.parse(fs.readFileSync(bundle, { encoding: 'utf8', flag: 'r' }));
\r
15358 if (err.code === 'ENOENT') {
\r
15359 writeBundle = true;
\r
15361 else if (err instanceof SyntaxError) {
\r
15362 // We have a syntax error. So no valid JSON. Use
\r
15363 console.log("Syntax error parsing message bundle: " + err.message + ".");
\r
15364 fs.unlink(bundle, function (err) {
\r
15366 console.error("Deleting corrupted bundle " + bundle + " failed.");
\r
15369 useMemoryOnly = true;
\r
15375 result = createNLSBundle(header, bundlePath);
\r
15376 if (!result || useMemoryOnly) {
\r
15379 if (writeBundle) {
\r
15381 fs.writeFileSync(bundle, JSON.stringify(result), { encoding: 'utf8', flag: 'wx' });
\r
15384 if (err.code === 'EEXIST') {
\r
15392 function loadDefaultNlsBundle(bundlePath) {
\r
15394 return createDefaultNlsBundle(bundlePath);
\r
15397 console.log("Generating default bundle from meta data failed.", err);
\r
15398 return undefined;
\r
15401 function loadNlsBundle(header, bundlePath) {
\r
15403 // Core decided to use a language pack. Do the same in the extension
\r
15404 if (supportsLanguagePack()) {
\r
15406 result = loadNlsBundleOrCreateFromI18n(header, bundlePath);
\r
15409 console.log("Load or create bundle failed ", err);
\r
15413 // No language pack found, but core is running in language pack mode
\r
15414 // Don't try to use old in the box bundles since the might be stale
\r
15415 // Fall right back to the default bundle.
\r
15416 if (options.languagePackSupport) {
\r
15417 return loadDefaultNlsBundle(bundlePath);
\r
15419 var candidate = findInTheBoxBundle(bundlePath);
\r
15422 return readJsonFileSync(candidate);
\r
15425 console.log("Loading in the box message bundle failed.", err);
\r
15428 result = loadDefaultNlsBundle(bundlePath);
\r
15432 function tryFindMetaDataHeaderFile(file) {
\r
15434 var dirname = path.dirname(file);
\r
15436 result = path.join(dirname, 'nls.metadata.header.json');
\r
15437 if (fs.existsSync(result)) {
\r
15440 var parent = path.dirname(dirname);
\r
15441 if (parent === dirname) {
\r
15442 result = undefined;
\r
15446 dirname = parent;
\r
15451 function loadMessageBundle(file) {
\r
15453 // No file. We are in dev mode. Return the default
\r
15454 // localize function.
\r
15457 // Remove extension since we load json files.
\r
15458 var ext = path.extname(file);
\r
15460 file = file.substr(0, file.length - ext.length);
\r
15462 if (options.messageFormat === MessageFormat.both || options.messageFormat === MessageFormat.bundle) {
\r
15463 var headerFile = tryFindMetaDataHeaderFile(file);
\r
15464 if (headerFile) {
\r
15465 var bundlePath = path.dirname(headerFile);
\r
15466 var bundle = resolvedBundles[bundlePath];
\r
15467 if (bundle === undefined) {
\r
15469 var header = JSON.parse(fs.readFileSync(headerFile, 'utf8'));
\r
15471 var nlsBundle = loadNlsBundle(header, bundlePath);
\r
15472 bundle = cacheBundle(bundlePath, nlsBundle ? { header: header, nlsBundle: nlsBundle } : null);
\r
15475 console.error('Failed to load nls bundle', err);
\r
15476 bundle = cacheBundle(bundlePath, null);
\r
15480 console.error('Failed to read header file', err);
\r
15481 bundle = cacheBundle(bundlePath, null);
\r
15485 var module_3 = file.substr(bundlePath.length + 1).replace(/\\/g, '/');
\r
15486 var messages = bundle.nlsBundle[module_3];
\r
15487 if (messages === undefined) {
\r
15488 console.error("Messages for file " + file + " not found. See console for details.");
\r
15489 return function () {
\r
15490 return 'Messages not found.';
\r
15493 return createScopedLocalizeFunction(messages);
\r
15497 if (options.messageFormat === MessageFormat.both || options.messageFormat === MessageFormat.file) {
\r
15498 // Try to load a single file bundle
\r
15500 var json = readJsonFileSync(resolveLanguage(file));
\r
15501 if (Array.isArray(json)) {
\r
15502 return createScopedLocalizeFunction(json);
\r
15505 if (isDefined(json.messages) && isDefined(json.keys)) {
\r
15506 return createScopedLocalizeFunction(json.messages);
\r
15509 console.error("String bundle '" + file + "' uses an unsupported format.");
\r
15510 return function () {
\r
15511 return 'File bundle has unsupported format. See console for details';
\r
15517 if (err.code !== 'ENOENT') {
\r
15518 console.error('Failed to load single file bundle', err);
\r
15522 console.error("Failed to load message bundle for file " + file);
\r
15523 return function () {
\r
15524 return 'Failed to load message bundle. See console for details.';
\r
15527 exports.loadMessageBundle = loadMessageBundle;
\r
15528 function config(opts) {
\r
15530 if (isString(opts.locale)) {
\r
15531 options.locale = opts.locale.toLowerCase();
\r
15532 options.language = options.locale;
\r
15533 resolvedLanguage = undefined;
\r
15534 resolvedBundles = Object.create(null);
\r
15536 if (opts.messageFormat !== undefined) {
\r
15537 options.messageFormat = opts.messageFormat;
\r
15539 if (opts.bundleFormat === BundleFormat.standalone && options.languagePackSupport === true) {
\r
15540 options.languagePackSupport = false;
\r
15543 isPseudo = options.locale === 'pseudo';
\r
15544 return loadMessageBundle;
\r
15546 exports.config = config;
\r
15547 //# sourceMappingURL=main.js.map
15551 /***/ (function(module, __webpack_exports__, __webpack_require__) {
15554 __webpack_require__.r(__webpack_exports__);
15555 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stringifyObject", function() { return stringifyObject; });
15556 /*---------------------------------------------------------------------------------------------
15557 * Copyright (c) Microsoft Corporation. All rights reserved.
15558 * Licensed under the MIT License. See License.txt in the project root for license information.
15559 *--------------------------------------------------------------------------------------------*/
15560 function stringifyObject(obj, indent, stringifyLiteral) {
15561 if (obj !== null && typeof obj === 'object') {
15562 var newIndent = indent + '\t';
15563 if (Array.isArray(obj)) {
15564 if (obj.length === 0) {
15567 var result = '[\n';
15568 for (var i = 0; i < obj.length; i++) {
15569 result += newIndent + stringifyObject(obj[i], newIndent, stringifyLiteral);
15570 if (i < obj.length - 1) {
15575 result += indent + ']';
15579 var keys = Object.keys(obj);
15580 if (keys.length === 0) {
15583 var result = '{\n';
15584 for (var i = 0; i < keys.length; i++) {
15586 result += newIndent + JSON.stringify(key) + ': ' + stringifyObject(obj[key], newIndent, stringifyLiteral);
15587 if (i < keys.length - 1) {
15592 result += indent + '}';
15596 return stringifyLiteral(obj);
15602 /***/ (function(module, __webpack_exports__, __webpack_require__) {
15605 __webpack_require__.r(__webpack_exports__);
15606 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startsWith", function() { return startsWith; });
15607 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "endsWith", function() { return endsWith; });
15608 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertSimple2RegExpPattern", function() { return convertSimple2RegExpPattern; });
15609 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "repeat", function() { return repeat; });
15610 /*---------------------------------------------------------------------------------------------
15611 * Copyright (c) Microsoft Corporation. All rights reserved.
15612 * Licensed under the MIT License. See License.txt in the project root for license information.
15613 *--------------------------------------------------------------------------------------------*/
15614 function startsWith(haystack, needle) {
15615 if (haystack.length < needle.length) {
15618 for (var i = 0; i < needle.length; i++) {
15619 if (haystack[i] !== needle[i]) {
15626 * Determines if haystack ends with needle.
15628 function endsWith(haystack, needle) {
15629 var diff = haystack.length - needle.length;
15631 return haystack.lastIndexOf(needle) === diff;
15633 else if (diff === 0) {
15634 return haystack === needle;
15640 function convertSimple2RegExpPattern(pattern) {
15641 return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*');
15643 function repeat(value, count) {
15645 while (count > 0) {
15646 if ((count & 1) === 1) {
15650 count = count >>> 1;
15658 /***/ (function(module, __webpack_exports__, __webpack_require__) {
15661 __webpack_require__.r(__webpack_exports__);
15662 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONHover", function() { return JSONHover; });
15663 /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(92);
15664 /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(99);
15665 /*---------------------------------------------------------------------------------------------
15666 * Copyright (c) Microsoft Corporation. All rights reserved.
15667 * Licensed under the MIT License. See License.txt in the project root for license information.
15668 *--------------------------------------------------------------------------------------------*/
15671 var JSONHover = /** @class */ (function () {
15672 function JSONHover(schemaService, contributions, promiseConstructor) {
15673 if (contributions === void 0) { contributions = []; }
15674 this.schemaService = schemaService;
15675 this.contributions = contributions;
15676 this.promise = promiseConstructor || Promise;
15678 JSONHover.prototype.doHover = function (document, position, doc) {
15679 var offset = document.offsetAt(position);
15680 var node = doc.getNodeFromOffset(offset);
15681 if (!node || (node.type === 'object' || node.type === 'array') && offset > node.offset + 1 && offset < node.offset + node.length - 1) {
15682 return this.promise.resolve(null);
15684 var hoverRangeNode = node;
15685 // use the property description when hovering over an object key
15686 if (node.type === 'string') {
15687 var parent = node.parent;
15688 if (parent && parent.type === 'property' && parent.keyNode === node) {
15689 node = parent.valueNode;
15691 return this.promise.resolve(null);
15695 var hoverRange = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["Range"].create(document.positionAt(hoverRangeNode.offset), document.positionAt(hoverRangeNode.offset + hoverRangeNode.length));
15696 var createHover = function (contents) {
15698 contents: contents,
15703 var location = _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodePath"](node);
15704 for (var i = this.contributions.length - 1; i >= 0; i--) {
15705 var contribution = this.contributions[i];
15706 var promise = contribution.getInfoContribution(document.uri, location);
15708 return promise.then(function (htmlContent) { return createHover(htmlContent); });
15711 return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
15712 if (schema && node) {
15713 var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
15714 var title_1 = undefined;
15715 var markdownDescription_1 = undefined;
15716 var markdownEnumValueDescription_1 = undefined, enumValue_1 = undefined;
15717 matchingSchemas.every(function (s) {
15718 if (s.node === node && !s.inverted && s.schema) {
15719 title_1 = title_1 || s.schema.title;
15720 markdownDescription_1 = markdownDescription_1 || s.schema.markdownDescription || toMarkdown(s.schema.description);
15721 if (s.schema.enum) {
15722 var idx = s.schema.enum.indexOf(_parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](node));
15723 if (s.schema.markdownEnumDescriptions) {
15724 markdownEnumValueDescription_1 = s.schema.markdownEnumDescriptions[idx];
15726 else if (s.schema.enumDescriptions) {
15727 markdownEnumValueDescription_1 = toMarkdown(s.schema.enumDescriptions[idx]);
15729 if (markdownEnumValueDescription_1) {
15730 enumValue_1 = s.schema.enum[idx];
15731 if (typeof enumValue_1 !== 'string') {
15732 enumValue_1 = JSON.stringify(enumValue_1);
15741 result = toMarkdown(title_1);
15743 if (markdownDescription_1) {
15744 if (result.length > 0) {
15747 result += markdownDescription_1;
15749 if (markdownEnumValueDescription_1) {
15750 if (result.length > 0) {
15753 result += "`" + toMarkdownCodeBlock(enumValue_1) + "`: " + markdownEnumValueDescription_1;
15755 return createHover([result]);
15763 function toMarkdown(plain) {
15765 var res = plain.replace(/([^\n\r])(\r?\n)([^\n\r])/gm, '$1\n\n$3'); // single new lines to \n\n (Markdown paragraph)
15766 return res.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
15770 function toMarkdownCodeBlock(content) {
15771 // see https://daringfireball.net/projects/markdown/syntax#precode
15772 if (content.indexOf('`') !== -1) {
15773 return '`` ' + content + ' ``';
15781 /***/ (function(module, __webpack_exports__, __webpack_require__) {
15784 __webpack_require__.r(__webpack_exports__);
15785 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONValidation", function() { return JSONValidation; });
15786 /* harmony import */ var _jsonSchemaService__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(106);
15787 /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(99);
15788 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(101);
15789 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_2__);
15790 /* harmony import */ var _utils_objects__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(98);
15791 /*---------------------------------------------------------------------------------------------
15792 * Copyright (c) Microsoft Corporation. All rights reserved.
15793 * Licensed under the MIT License. See License.txt in the project root for license information.
15794 *--------------------------------------------------------------------------------------------*/
15799 var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_2__["loadMessageBundle"]();
15800 var JSONValidation = /** @class */ (function () {
15801 function JSONValidation(jsonSchemaService, promiseConstructor) {
15802 this.jsonSchemaService = jsonSchemaService;
15803 this.promise = promiseConstructor;
15804 this.validationEnabled = true;
15806 JSONValidation.prototype.configure = function (raw) {
15808 this.validationEnabled = raw.validate;
15809 this.commentSeverity = raw.allowComments ? undefined : _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Error;
15812 JSONValidation.prototype.doValidation = function (textDocument, jsonDocument, documentSettings, schema) {
15814 if (!this.validationEnabled) {
15815 return this.promise.resolve([]);
15817 var diagnostics = [];
15819 var addProblem = function (problem) {
15820 // remove duplicated messages
15821 var signature = problem.range.start.line + ' ' + problem.range.start.character + ' ' + problem.message;
15822 if (!added[signature]) {
15823 added[signature] = true;
15824 diagnostics.push(problem);
15827 var getDiagnostics = function (schema) {
15828 var trailingCommaSeverity = documentSettings ? toDiagnosticSeverity(documentSettings.trailingCommas) : _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Error;
15829 var commentSeverity = documentSettings ? toDiagnosticSeverity(documentSettings.comments) : _this.commentSeverity;
15831 if (schema.errors.length && jsonDocument.root) {
15832 var astRoot = jsonDocument.root;
15833 var property = astRoot.type === 'object' ? astRoot.properties[0] : undefined;
15834 if (property && property.keyNode.value === '$schema') {
15835 var node = property.valueNode || property;
15836 var range = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["Range"].create(textDocument.positionAt(node.offset), textDocument.positionAt(node.offset + node.length));
15837 addProblem(_jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["Diagnostic"].create(range, schema.errors[0], _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Warning, _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["ErrorCode"].SchemaResolveError));
15840 var range = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["Range"].create(textDocument.positionAt(astRoot.offset), textDocument.positionAt(astRoot.offset + 1));
15841 addProblem(_jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["Diagnostic"].create(range, schema.errors[0], _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Warning, _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["ErrorCode"].SchemaResolveError));
15845 var semanticErrors = jsonDocument.validate(textDocument, schema.schema);
15846 if (semanticErrors) {
15847 semanticErrors.forEach(addProblem);
15850 if (schemaAllowsComments(schema.schema)) {
15851 commentSeverity = undefined;
15853 if (schemaAllowsTrailingCommas(schema.schema)) {
15854 trailingCommaSeverity = undefined;
15857 for (var _i = 0, _a = jsonDocument.syntaxErrors; _i < _a.length; _i++) {
15859 if (p.code === _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["ErrorCode"].TrailingComma) {
15860 if (typeof trailingCommaSeverity !== 'number') {
15863 p.severity = trailingCommaSeverity;
15867 if (typeof commentSeverity === 'number') {
15868 var message_1 = localize('InvalidCommentToken', 'Comments are not permitted in JSON.');
15869 jsonDocument.comments.forEach(function (c) {
15870 addProblem(_jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["Diagnostic"].create(c, message_1, commentSeverity, _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["ErrorCode"].CommentNotPermitted));
15873 return diagnostics;
15876 var id = schema.id || ('schemaservice://untitled/' + idCounter++);
15877 return this.jsonSchemaService.resolveSchemaContent(new _jsonSchemaService__WEBPACK_IMPORTED_MODULE_0__["UnresolvedSchema"](schema), id, {}).then(function (resolvedSchema) {
15878 return getDiagnostics(resolvedSchema);
15881 return this.jsonSchemaService.getSchemaForResource(textDocument.uri, jsonDocument).then(function (schema) {
15882 return getDiagnostics(schema);
15885 return JSONValidation;
15889 function schemaAllowsComments(schemaRef) {
15890 if (schemaRef && typeof schemaRef === 'object') {
15891 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_3__["isBoolean"])(schemaRef.allowComments)) {
15892 return schemaRef.allowComments;
15894 if (schemaRef.allOf) {
15895 for (var _i = 0, _a = schemaRef.allOf; _i < _a.length; _i++) {
15896 var schema = _a[_i];
15897 var allow = schemaAllowsComments(schema);
15898 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_3__["isBoolean"])(allow)) {
15906 function schemaAllowsTrailingCommas(schemaRef) {
15907 if (schemaRef && typeof schemaRef === 'object') {
15908 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_3__["isBoolean"])(schemaRef.allowTrailingCommas)) {
15909 return schemaRef.allowTrailingCommas;
15911 var deprSchemaRef = schemaRef;
15912 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_3__["isBoolean"])(deprSchemaRef['allowsTrailingCommas'])) { // deprecated
15913 return deprSchemaRef['allowsTrailingCommas'];
15915 if (schemaRef.allOf) {
15916 for (var _i = 0, _a = schemaRef.allOf; _i < _a.length; _i++) {
15917 var schema = _a[_i];
15918 var allow = schemaAllowsTrailingCommas(schema);
15919 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_3__["isBoolean"])(allow)) {
15927 function toDiagnosticSeverity(severityLevel) {
15928 switch (severityLevel) {
15929 case 'error': return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Error;
15930 case 'warning': return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Warning;
15931 case 'ignore': return undefined;
15939 /***/ (function(module, __webpack_exports__, __webpack_require__) {
15942 __webpack_require__.r(__webpack_exports__);
15943 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnresolvedSchema", function() { return UnresolvedSchema; });
15944 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ResolvedSchema", function() { return ResolvedSchema; });
15945 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONSchemaService", function() { return JSONSchemaService; });
15946 /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(93);
15947 /* harmony import */ var vscode_uri__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35);
15948 /* harmony import */ var _utils_strings__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(103);
15949 /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(92);
15950 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(101);
15951 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_4__);
15952 /*---------------------------------------------------------------------------------------------
15953 * Copyright (c) Microsoft Corporation. All rights reserved.
15954 * Licensed under the MIT License. See License.txt in the project root for license information.
15955 *--------------------------------------------------------------------------------------------*/
15961 var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_4__["loadMessageBundle"]();
15962 var FilePatternAssociation = /** @class */ (function () {
15963 function FilePatternAssociation(pattern, uris) {
15964 this.patternRegExps = [];
15965 this.isInclude = [];
15967 for (var _i = 0, pattern_1 = pattern; _i < pattern_1.length; _i++) {
15968 var p = pattern_1[_i];
15969 var include = p[0] !== '!';
15971 p = p.substring(1);
15973 this.patternRegExps.push(new RegExp(_utils_strings__WEBPACK_IMPORTED_MODULE_2__["convertSimple2RegExpPattern"](p) + '$'));
15974 this.isInclude.push(include);
15980 this.patternRegExps.length = 0;
15981 this.isInclude.length = 0;
15985 FilePatternAssociation.prototype.matchesPattern = function (fileName) {
15987 for (var i = 0; i < this.patternRegExps.length; i++) {
15988 var regExp = this.patternRegExps[i];
15989 if (regExp.test(fileName)) {
15990 match = this.isInclude[i];
15995 FilePatternAssociation.prototype.getURIs = function () {
15998 return FilePatternAssociation;
16000 var SchemaHandle = /** @class */ (function () {
16001 function SchemaHandle(service, url, unresolvedSchemaContent) {
16002 this.service = service;
16004 this.dependencies = {};
16005 if (unresolvedSchemaContent) {
16006 this.unresolvedSchema = this.service.promise.resolve(new UnresolvedSchema(unresolvedSchemaContent));
16009 SchemaHandle.prototype.getUnresolvedSchema = function () {
16010 if (!this.unresolvedSchema) {
16011 this.unresolvedSchema = this.service.loadSchema(this.url);
16013 return this.unresolvedSchema;
16015 SchemaHandle.prototype.getResolvedSchema = function () {
16017 if (!this.resolvedSchema) {
16018 this.resolvedSchema = this.getUnresolvedSchema().then(function (unresolved) {
16019 return _this.service.resolveSchemaContent(unresolved, _this.url, _this.dependencies);
16022 return this.resolvedSchema;
16024 SchemaHandle.prototype.clearSchema = function () {
16025 this.resolvedSchema = undefined;
16026 this.unresolvedSchema = undefined;
16027 this.dependencies = {};
16029 return SchemaHandle;
16031 var UnresolvedSchema = /** @class */ (function () {
16032 function UnresolvedSchema(schema, errors) {
16033 if (errors === void 0) { errors = []; }
16034 this.schema = schema;
16035 this.errors = errors;
16037 return UnresolvedSchema;
16040 var ResolvedSchema = /** @class */ (function () {
16041 function ResolvedSchema(schema, errors) {
16042 if (errors === void 0) { errors = []; }
16043 this.schema = schema;
16044 this.errors = errors;
16046 ResolvedSchema.prototype.getSection = function (path) {
16047 var schemaRef = this.getSectionRecursive(path, this.schema);
16049 return _parser_jsonParser__WEBPACK_IMPORTED_MODULE_3__["asSchema"](schemaRef);
16053 ResolvedSchema.prototype.getSectionRecursive = function (path, schema) {
16054 if (!schema || typeof schema === 'boolean' || path.length === 0) {
16057 var next = path.shift();
16058 if (schema.properties && typeof schema.properties[next]) {
16059 return this.getSectionRecursive(path, schema.properties[next]);
16061 else if (schema.patternProperties) {
16062 for (var _i = 0, _a = Object.keys(schema.patternProperties); _i < _a.length; _i++) {
16063 var pattern = _a[_i];
16064 var regex = new RegExp(pattern);
16065 if (regex.test(next)) {
16066 return this.getSectionRecursive(path, schema.patternProperties[pattern]);
16070 else if (typeof schema.additionalProperties === 'object') {
16071 return this.getSectionRecursive(path, schema.additionalProperties);
16073 else if (next.match('[0-9]+')) {
16074 if (Array.isArray(schema.items)) {
16075 var index = parseInt(next, 10);
16076 if (!isNaN(index) && schema.items[index]) {
16077 return this.getSectionRecursive(path, schema.items[index]);
16080 else if (schema.items) {
16081 return this.getSectionRecursive(path, schema.items);
16086 return ResolvedSchema;
16089 var JSONSchemaService = /** @class */ (function () {
16090 function JSONSchemaService(requestService, contextService, promiseConstructor) {
16091 this.contextService = contextService;
16092 this.requestService = requestService;
16093 this.promiseConstructor = promiseConstructor || Promise;
16094 this.callOnDispose = [];
16095 this.contributionSchemas = {};
16096 this.contributionAssociations = [];
16097 this.schemasById = {};
16098 this.filePatternAssociations = [];
16099 this.registeredSchemasIds = {};
16101 JSONSchemaService.prototype.getRegisteredSchemaIds = function (filter) {
16102 return Object.keys(this.registeredSchemasIds).filter(function (id) {
16103 var scheme = vscode_uri__WEBPACK_IMPORTED_MODULE_1__["URI"].parse(id).scheme;
16104 return scheme !== 'schemaservice' && (!filter || filter(scheme));
16107 Object.defineProperty(JSONSchemaService.prototype, "promise", {
16109 return this.promiseConstructor;
16114 JSONSchemaService.prototype.dispose = function () {
16115 while (this.callOnDispose.length > 0) {
16116 this.callOnDispose.pop()();
16119 JSONSchemaService.prototype.onResourceChange = function (uri) {
16121 var hasChanges = false;
16122 uri = normalizeId(uri);
16123 var toWalk = [uri];
16124 var all = Object.keys(this.schemasById).map(function (key) { return _this.schemasById[key]; });
16125 while (toWalk.length) {
16126 var curr = toWalk.pop();
16127 for (var i = 0; i < all.length; i++) {
16128 var handle = all[i];
16129 if (handle && (handle.url === curr || handle.dependencies[curr])) {
16130 if (handle.url !== curr) {
16131 toWalk.push(handle.url);
16133 handle.clearSchema();
16134 all[i] = undefined;
16141 JSONSchemaService.prototype.setSchemaContributions = function (schemaContributions) {
16142 if (schemaContributions.schemas) {
16143 var schemas = schemaContributions.schemas;
16144 for (var id in schemas) {
16145 var normalizedId = normalizeId(id);
16146 this.contributionSchemas[normalizedId] = this.addSchemaHandle(normalizedId, schemas[id]);
16149 if (Array.isArray(schemaContributions.schemaAssociations)) {
16150 var schemaAssociations = schemaContributions.schemaAssociations;
16151 for (var _i = 0, schemaAssociations_1 = schemaAssociations; _i < schemaAssociations_1.length; _i++) {
16152 var schemaAssociation = schemaAssociations_1[_i];
16153 var uris = schemaAssociation.uris.map(normalizeId);
16154 var association = this.addFilePatternAssociation(schemaAssociation.pattern, uris);
16155 this.contributionAssociations.push(association);
16159 JSONSchemaService.prototype.addSchemaHandle = function (id, unresolvedSchemaContent) {
16160 var schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent);
16161 this.schemasById[id] = schemaHandle;
16162 return schemaHandle;
16164 JSONSchemaService.prototype.getOrAddSchemaHandle = function (id, unresolvedSchemaContent) {
16165 return this.schemasById[id] || this.addSchemaHandle(id, unresolvedSchemaContent);
16167 JSONSchemaService.prototype.addFilePatternAssociation = function (pattern, uris) {
16168 var fpa = new FilePatternAssociation(pattern, uris);
16169 this.filePatternAssociations.push(fpa);
16172 JSONSchemaService.prototype.registerExternalSchema = function (uri, filePatterns, unresolvedSchemaContent) {
16173 var id = normalizeId(uri);
16174 this.registeredSchemasIds[id] = true;
16175 this.cachedSchemaForResource = undefined;
16176 if (filePatterns) {
16177 this.addFilePatternAssociation(filePatterns, [uri]);
16179 return unresolvedSchemaContent ? this.addSchemaHandle(id, unresolvedSchemaContent) : this.getOrAddSchemaHandle(id);
16181 JSONSchemaService.prototype.clearExternalSchemas = function () {
16182 this.schemasById = {};
16183 this.filePatternAssociations = [];
16184 this.registeredSchemasIds = {};
16185 this.cachedSchemaForResource = undefined;
16186 for (var id in this.contributionSchemas) {
16187 this.schemasById[id] = this.contributionSchemas[id];
16188 this.registeredSchemasIds[id] = true;
16190 for (var _i = 0, _a = this.contributionAssociations; _i < _a.length; _i++) {
16191 var contributionAssociation = _a[_i];
16192 this.filePatternAssociations.push(contributionAssociation);
16195 JSONSchemaService.prototype.getResolvedSchema = function (schemaId) {
16196 var id = normalizeId(schemaId);
16197 var schemaHandle = this.schemasById[id];
16198 if (schemaHandle) {
16199 return schemaHandle.getResolvedSchema();
16201 return this.promise.resolve(undefined);
16203 JSONSchemaService.prototype.loadSchema = function (url) {
16204 if (!this.requestService) {
16205 var errorMessage = localize('json.schema.norequestservice', 'Unable to load schema from \'{0}\'. No schema request service available', toDisplayString(url));
16206 return this.promise.resolve(new UnresolvedSchema({}, [errorMessage]));
16208 return this.requestService(url).then(function (content) {
16210 var errorMessage = localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': No content.', toDisplayString(url));
16211 return new UnresolvedSchema({}, [errorMessage]);
16213 var schemaContent = {};
16214 var jsonErrors = [];
16215 schemaContent = jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["parse"](content, jsonErrors);
16216 var errors = jsonErrors.length ? [localize('json.schema.invalidFormat', 'Unable to parse content from \'{0}\': Parse error at offset {1}.', toDisplayString(url), jsonErrors[0].offset)] : [];
16217 return new UnresolvedSchema(schemaContent, errors);
16218 }, function (error) {
16219 var errorMessage = error.toString();
16220 var errorSplit = error.toString().split('Error: ');
16221 if (errorSplit.length > 1) {
16222 // more concise error message, URL and context are attached by caller anyways
16223 errorMessage = errorSplit[1];
16225 if (_utils_strings__WEBPACK_IMPORTED_MODULE_2__["endsWith"](errorMessage, '.')) {
16226 errorMessage = errorMessage.substr(0, errorMessage.length - 1);
16228 return new UnresolvedSchema({}, [localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': {1}.', toDisplayString(url), errorMessage)]);
16231 JSONSchemaService.prototype.resolveSchemaContent = function (schemaToResolve, schemaURL, dependencies) {
16233 var resolveErrors = schemaToResolve.errors.slice(0);
16234 var schema = schemaToResolve.schema;
16235 if (schema.$schema) {
16236 var id = normalizeId(schema.$schema);
16237 if (id === 'http://json-schema.org/draft-03/schema') {
16238 return this.promise.resolve(new ResolvedSchema({}, [localize('json.schema.draft03.notsupported', "Draft-03 schemas are not supported.")]));
16240 else if (id === 'https://json-schema.org/draft/2019-09/schema') {
16241 resolveErrors.push(localize('json.schema.draft201909.notsupported', "Draft 2019-09 schemas are not yet fully supported."));
16244 var contextService = this.contextService;
16245 var findSection = function (schema, path) {
16249 var current = schema;
16250 if (path[0] === '/') {
16251 path = path.substr(1);
16253 path.split('/').some(function (part) {
16254 current = current[part];
16259 var merge = function (target, sourceRoot, sourceURI, refSegment) {
16260 var path = refSegment ? decodeURIComponent(refSegment) : undefined;
16261 var section = findSection(sourceRoot, path);
16263 for (var key in section) {
16264 if (section.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
16265 target[key] = section[key];
16270 resolveErrors.push(localize('json.schema.invalidref', '$ref \'{0}\' in \'{1}\' can not be resolved.', path, sourceURI));
16273 var resolveExternalLink = function (node, uri, refSegment, parentSchemaURL, parentSchemaDependencies) {
16274 if (contextService && !/^\w+:\/\/.*/.test(uri)) {
16275 uri = contextService.resolveRelativePath(uri, parentSchemaURL);
16277 uri = normalizeId(uri);
16278 var referencedHandle = _this.getOrAddSchemaHandle(uri);
16279 return referencedHandle.getUnresolvedSchema().then(function (unresolvedSchema) {
16280 parentSchemaDependencies[uri] = true;
16281 if (unresolvedSchema.errors.length) {
16282 var loc = refSegment ? uri + '#' + refSegment : uri;
16283 resolveErrors.push(localize('json.schema.problemloadingref', 'Problems loading reference \'{0}\': {1}', loc, unresolvedSchema.errors[0]));
16285 merge(node, unresolvedSchema.schema, uri, refSegment);
16286 return resolveRefs(node, unresolvedSchema.schema, uri, referencedHandle.dependencies);
16289 var resolveRefs = function (node, parentSchema, parentSchemaURL, parentSchemaDependencies) {
16290 if (!node || typeof node !== 'object') {
16291 return Promise.resolve(null);
16293 var toWalk = [node];
16295 var openPromises = [];
16296 var collectEntries = function () {
16298 for (var _i = 0; _i < arguments.length; _i++) {
16299 entries[_i] = arguments[_i];
16301 for (var _a = 0, entries_1 = entries; _a < entries_1.length; _a++) {
16302 var entry = entries_1[_a];
16303 if (typeof entry === 'object') {
16304 toWalk.push(entry);
16308 var collectMapEntries = function () {
16310 for (var _i = 0; _i < arguments.length; _i++) {
16311 maps[_i] = arguments[_i];
16313 for (var _a = 0, maps_1 = maps; _a < maps_1.length; _a++) {
16314 var map = maps_1[_a];
16315 if (typeof map === 'object') {
16316 for (var k in map) {
16318 var entry = map[key];
16319 if (typeof entry === 'object') {
16320 toWalk.push(entry);
16326 var collectArrayEntries = function () {
16328 for (var _i = 0; _i < arguments.length; _i++) {
16329 arrays[_i] = arguments[_i];
16331 for (var _a = 0, arrays_1 = arrays; _a < arrays_1.length; _a++) {
16332 var array = arrays_1[_a];
16333 if (Array.isArray(array)) {
16334 for (var _b = 0, array_1 = array; _b < array_1.length; _b++) {
16335 var entry = array_1[_b];
16336 if (typeof entry === 'object') {
16337 toWalk.push(entry);
16343 var handleRef = function (next) {
16345 while (next.$ref) {
16346 var ref = next.$ref;
16347 var segments = ref.split('#', 2);
16349 if (segments[0].length > 0) {
16350 openPromises.push(resolveExternalLink(next, segments[0], segments[1], parentSchemaURL, parentSchemaDependencies));
16354 if (seenRefs.indexOf(ref) === -1) {
16355 merge(next, parentSchema, parentSchemaURL, segments[1]); // can set next.$ref again, use seenRefs to avoid circle
16356 seenRefs.push(ref);
16360 collectEntries(next.items, next.additionalItems, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else);
16361 collectMapEntries(next.definitions, next.properties, next.patternProperties, next.dependencies);
16362 collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.items);
16364 while (toWalk.length) {
16365 var next = toWalk.pop();
16366 if (seen.indexOf(next) >= 0) {
16372 return _this.promise.all(openPromises);
16374 return resolveRefs(schema, schema, schemaURL, dependencies).then(function (_) { return new ResolvedSchema(schema, resolveErrors); });
16376 JSONSchemaService.prototype.getSchemaForResource = function (resource, document) {
16377 // first use $schema if present
16378 if (document && document.root && document.root.type === 'object') {
16379 var schemaProperties = document.root.properties.filter(function (p) { return (p.keyNode.value === '$schema') && p.valueNode && p.valueNode.type === 'string'; });
16380 if (schemaProperties.length > 0) {
16381 var valueNode = schemaProperties[0].valueNode;
16382 if (valueNode && valueNode.type === 'string') {
16383 var schemeId = _parser_jsonParser__WEBPACK_IMPORTED_MODULE_3__["getNodeValue"](valueNode);
16384 if (schemeId && _utils_strings__WEBPACK_IMPORTED_MODULE_2__["startsWith"](schemeId, '.') && this.contextService) {
16385 schemeId = this.contextService.resolveRelativePath(schemeId, resource);
16388 var id = normalizeId(schemeId);
16389 return this.getOrAddSchemaHandle(id).getResolvedSchema();
16394 if (this.cachedSchemaForResource && this.cachedSchemaForResource.resource === resource) {
16395 return this.cachedSchemaForResource.resolvedSchema;
16397 var seen = Object.create(null);
16399 for (var _i = 0, _a = this.filePatternAssociations; _i < _a.length; _i++) {
16400 var entry = _a[_i];
16401 if (entry.matchesPattern(resource)) {
16402 for (var _b = 0, _c = entry.getURIs(); _b < _c.length; _b++) {
16403 var schemaId = _c[_b];
16404 if (!seen[schemaId]) {
16405 schemas.push(schemaId);
16406 seen[schemaId] = true;
16411 var resolvedSchema = schemas.length > 0 ? this.createCombinedSchema(resource, schemas).getResolvedSchema() : this.promise.resolve(undefined);
16412 this.cachedSchemaForResource = { resource: resource, resolvedSchema: resolvedSchema };
16413 return resolvedSchema;
16415 JSONSchemaService.prototype.createCombinedSchema = function (resource, schemaIds) {
16416 if (schemaIds.length === 1) {
16417 return this.getOrAddSchemaHandle(schemaIds[0]);
16420 var combinedSchemaId = 'schemaservice://combinedSchema/' + encodeURIComponent(resource);
16421 var combinedSchema = {
16422 allOf: schemaIds.map(function (schemaId) { return ({ $ref: schemaId }); })
16424 return this.addSchemaHandle(combinedSchemaId, combinedSchema);
16427 JSONSchemaService.prototype.getMatchingSchemas = function (document, jsonDocument, schema) {
16429 var id = schema.id || ('schemaservice://untitled/matchingSchemas/' + idCounter++);
16430 return this.resolveSchemaContent(new UnresolvedSchema(schema), id, {}).then(function (resolvedSchema) {
16431 return jsonDocument.getMatchingSchemas(resolvedSchema.schema).filter(function (s) { return !s.inverted; });
16434 return this.getSchemaForResource(document.uri, jsonDocument).then(function (schema) {
16436 return jsonDocument.getMatchingSchemas(schema.schema).filter(function (s) { return !s.inverted; });
16441 return JSONSchemaService;
16445 function normalizeId(id) {
16446 // remove trailing '#', normalize drive capitalization
16448 return vscode_uri__WEBPACK_IMPORTED_MODULE_1__["URI"].parse(id).toString();
16454 function toDisplayString(url) {
16456 var uri = vscode_uri__WEBPACK_IMPORTED_MODULE_1__["URI"].parse(url);
16457 if (uri.scheme === 'file') {
16470 /***/ (function(module, __webpack_exports__, __webpack_require__) {
16473 __webpack_require__.r(__webpack_exports__);
16474 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONDocumentSymbols", function() { return JSONDocumentSymbols; });
16475 /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(92);
16476 /* harmony import */ var _utils_strings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(103);
16477 /* harmony import */ var _utils_colors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(108);
16478 /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(99);
16479 /*---------------------------------------------------------------------------------------------
16480 * Copyright (c) Microsoft Corporation. All rights reserved.
16481 * Licensed under the MIT License. See License.txt in the project root for license information.
16482 *--------------------------------------------------------------------------------------------*/
16487 var JSONDocumentSymbols = /** @class */ (function () {
16488 function JSONDocumentSymbols(schemaService) {
16489 this.schemaService = schemaService;
16491 JSONDocumentSymbols.prototype.findDocumentSymbols = function (document, doc, context) {
16493 if (context === void 0) { context = { resultLimit: Number.MAX_VALUE }; }
16494 var root = doc.root;
16498 var limit = context.resultLimit || Number.MAX_VALUE;
16499 // special handling for key bindings
16500 var resourceString = document.uri;
16501 if ((resourceString === 'vscode://defaultsettings/keybindings.json') || _utils_strings__WEBPACK_IMPORTED_MODULE_1__["endsWith"](resourceString.toLowerCase(), '/user/keybindings.json')) {
16502 if (root.type === 'array') {
16504 for (var _i = 0, _a = root.items; _i < _a.length; _i++) {
16506 if (item.type === 'object') {
16507 for (var _b = 0, _c = item.properties; _b < _c.length; _b++) {
16508 var property = _c[_b];
16509 if (property.keyNode.value === 'key' && property.valueNode) {
16510 var location = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_3__["Location"].create(document.uri, getRange(document, item));
16511 result_1.push({ name: _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](property.valueNode), kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Function, location: location });
16514 if (context && context.onResultLimitExceeded) {
16515 context.onResultLimitExceeded(resourceString);
16527 { node: root, containerName: '' }
16529 var nextToVisit = 0;
16530 var limitExceeded = false;
16532 var collectOutlineEntries = function (node, containerName) {
16533 if (node.type === 'array') {
16534 node.items.forEach(function (node) {
16536 toVisit.push({ node: node, containerName: containerName });
16540 else if (node.type === 'object') {
16541 node.properties.forEach(function (property) {
16542 var valueNode = property.valueNode;
16546 var location = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_3__["Location"].create(document.uri, getRange(document, property));
16547 var childContainerName = containerName ? containerName + '.' + property.keyNode.value : property.keyNode.value;
16548 result.push({ name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), location: location, containerName: containerName });
16549 toVisit.push({ node: valueNode, containerName: childContainerName });
16552 limitExceeded = true;
16558 // breath first traversal
16559 while (nextToVisit < toVisit.length) {
16560 var next = toVisit[nextToVisit++];
16561 collectOutlineEntries(next.node, next.containerName);
16563 if (limitExceeded && context && context.onResultLimitExceeded) {
16564 context.onResultLimitExceeded(resourceString);
16568 JSONDocumentSymbols.prototype.findDocumentSymbols2 = function (document, doc, context) {
16570 if (context === void 0) { context = { resultLimit: Number.MAX_VALUE }; }
16571 var root = doc.root;
16575 var limit = context.resultLimit || Number.MAX_VALUE;
16576 // special handling for key bindings
16577 var resourceString = document.uri;
16578 if ((resourceString === 'vscode://defaultsettings/keybindings.json') || _utils_strings__WEBPACK_IMPORTED_MODULE_1__["endsWith"](resourceString.toLowerCase(), '/user/keybindings.json')) {
16579 if (root.type === 'array') {
16581 for (var _i = 0, _a = root.items; _i < _a.length; _i++) {
16583 if (item.type === 'object') {
16584 for (var _b = 0, _c = item.properties; _b < _c.length; _b++) {
16585 var property = _c[_b];
16586 if (property.keyNode.value === 'key' && property.valueNode) {
16587 var range = getRange(document, item);
16588 var selectionRange = getRange(document, property.keyNode);
16589 result_2.push({ name: _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](property.valueNode), kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Function, range: range, selectionRange: selectionRange });
16592 if (context && context.onResultLimitExceeded) {
16593 context.onResultLimitExceeded(resourceString);
16606 { node: root, result: result }
16608 var nextToVisit = 0;
16609 var limitExceeded = false;
16610 var collectOutlineEntries = function (node, result) {
16611 if (node.type === 'array') {
16612 node.items.forEach(function (node, index) {
16616 var range = getRange(document, node);
16617 var selectionRange = range;
16618 var name = String(index);
16619 var symbol = { name: name, kind: _this.getSymbolKind(node.type), range: range, selectionRange: selectionRange, children: [] };
16620 result.push(symbol);
16621 toVisit.push({ result: symbol.children, node: node });
16624 limitExceeded = true;
16629 else if (node.type === 'object') {
16630 node.properties.forEach(function (property) {
16631 var valueNode = property.valueNode;
16635 var range = getRange(document, property);
16636 var selectionRange = getRange(document, property.keyNode);
16637 var symbol = { name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), range: range, selectionRange: selectionRange, children: [] };
16638 result.push(symbol);
16639 toVisit.push({ result: symbol.children, node: valueNode });
16642 limitExceeded = true;
16648 // breath first traversal
16649 while (nextToVisit < toVisit.length) {
16650 var next = toVisit[nextToVisit++];
16651 collectOutlineEntries(next.node, next.result);
16653 if (limitExceeded && context && context.onResultLimitExceeded) {
16654 context.onResultLimitExceeded(resourceString);
16658 JSONDocumentSymbols.prototype.getSymbolKind = function (nodeType) {
16659 switch (nodeType) {
16661 return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Module;
16663 return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].String;
16665 return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Number;
16667 return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Array;
16669 return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Boolean;
16671 return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Variable;
16674 JSONDocumentSymbols.prototype.getKeyLabel = function (property) {
16675 var name = property.keyNode.value;
16677 name = name.replace(/[\n]/g, '↵');
16679 if (name && name.trim()) {
16682 return "\"" + name + "\"";
16684 JSONDocumentSymbols.prototype.findDocumentColors = function (document, doc, context) {
16685 return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
16688 var limit = context && typeof context.resultLimit === 'number' ? context.resultLimit : Number.MAX_VALUE;
16689 var matchingSchemas = doc.getMatchingSchemas(schema.schema);
16690 var visitedNode = {};
16691 for (var _i = 0, matchingSchemas_1 = matchingSchemas; _i < matchingSchemas_1.length; _i++) {
16692 var s = matchingSchemas_1[_i];
16693 if (!s.inverted && s.schema && (s.schema.format === 'color' || s.schema.format === 'color-hex') && s.node && s.node.type === 'string') {
16694 var nodeId = String(s.node.offset);
16695 if (!visitedNode[nodeId]) {
16696 var color = Object(_utils_colors__WEBPACK_IMPORTED_MODULE_2__["colorFromHex"])(_parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](s.node));
16698 var range = getRange(document, s.node);
16699 result.push({ color: color, range: range });
16701 visitedNode[nodeId] = true;
16704 if (context && context.onResultLimitExceeded) {
16705 context.onResultLimitExceeded(document.uri);
16716 JSONDocumentSymbols.prototype.getColorPresentations = function (document, doc, color, range) {
16718 var red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255);
16719 function toTwoDigitHex(n) {
16720 var r = n.toString(16);
16721 return r.length !== 2 ? '0' + r : r;
16724 if (color.alpha === 1) {
16725 label = "#" + toTwoDigitHex(red256) + toTwoDigitHex(green256) + toTwoDigitHex(blue256);
16728 label = "#" + toTwoDigitHex(red256) + toTwoDigitHex(green256) + toTwoDigitHex(blue256) + toTwoDigitHex(Math.round(color.alpha * 255));
16730 result.push({ label: label, textEdit: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_3__["TextEdit"].replace(range, JSON.stringify(label)) });
16733 return JSONDocumentSymbols;
16736 function getRange(document, node) {
16737 return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_3__["Range"].create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
16743 /***/ (function(module, __webpack_exports__, __webpack_require__) {
16746 __webpack_require__.r(__webpack_exports__);
16747 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hexDigit", function() { return hexDigit; });
16748 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "colorFromHex", function() { return colorFromHex; });
16749 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "colorFrom256RGB", function() { return colorFrom256RGB; });
16750 /*---------------------------------------------------------------------------------------------
16751 * Copyright (c) Microsoft Corporation. All rights reserved.
16752 * Licensed under the MIT License. See License.txt in the project root for license information.
16753 *--------------------------------------------------------------------------------------------*/
16759 function hexDigit(charCode) {
16760 if (charCode < Digit0) {
16763 if (charCode <= Digit9) {
16764 return charCode - Digit0;
16766 if (charCode < a) {
16767 charCode += (a - A);
16769 if (charCode >= a && charCode <= f) {
16770 return charCode - a + 10;
16774 function colorFromHex(text) {
16775 if (text[0] !== '#') {
16778 switch (text.length) {
16781 red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0,
16782 green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0,
16783 blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0,
16788 red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0,
16789 green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0,
16790 blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0,
16791 alpha: (hexDigit(text.charCodeAt(4)) * 0x11) / 255.0,
16795 red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0,
16796 green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0,
16797 blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0,
16802 red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0,
16803 green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0,
16804 blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0,
16805 alpha: (hexDigit(text.charCodeAt(7)) * 0x10 + hexDigit(text.charCodeAt(8))) / 255.0
16810 function colorFrom256RGB(red, green, blue, alpha) {
16811 if (alpha === void 0) { alpha = 1.0; }
16814 green: green / 255.0,
16815 blue: blue / 255.0,
16823 /***/ (function(module, __webpack_exports__, __webpack_require__) {
16826 __webpack_require__.r(__webpack_exports__);
16827 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "schemaContributions", function() { return schemaContributions; });
16828 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(101);
16829 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_0__);
16830 /*---------------------------------------------------------------------------------------------
16831 * Copyright (c) Microsoft Corporation. All rights reserved.
16832 * Licensed under the MIT License. See License.txt in the project root for license information.
16833 *--------------------------------------------------------------------------------------------*/
16835 var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_0__["loadMessageBundle"]();
16836 var schemaContributions = {
16837 schemaAssociations: [],
16839 // refer to the latest schema
16840 'http://json-schema.org/schema#': {
16841 $ref: 'http://json-schema.org/draft-07/schema#'
16843 // bundle the schema-schema to include (localized) descriptions
16844 'http://json-schema.org/draft-04/schema#': {
16845 'title': localize('schema.json', 'Describes a JSON file using a schema. See json-schema.org for more info.'),
16846 '$schema': 'http://json-schema.org/draft-04/schema#',
16855 'positiveInteger': {
16859 'positiveIntegerDefault0': {
16862 '$ref': '#/definitions/positiveInteger'
16887 'uniqueItems': true
16910 'exclusiveMinimum': true
16915 'exclusiveMaximum': {
16922 'exclusiveMinimum': {
16929 '$ref': '#/definitions/positiveInteger'
16936 '$ref': '#/definitions/positiveIntegerDefault0'
16944 'additionalItems': {
16961 '$ref': '#/definitions/schemaArray'
16969 '$ref': '#/definitions/positiveInteger'
16976 '$ref': '#/definitions/positiveIntegerDefault0'
16987 '$ref': '#/definitions/positiveInteger'
16994 '$ref': '#/definitions/positiveIntegerDefault0'
17001 '$ref': '#/definitions/stringArray'
17005 'additionalProperties': {
17018 'additionalProperties': {
17025 'additionalProperties': {
17030 'patternProperties': {
17032 'additionalProperties': {
17039 'additionalProperties': {
17045 '$ref': '#/definitions/stringArray'
17053 'uniqueItems': true
17058 '$ref': '#/definitions/simpleTypes'
17063 '$ref': '#/definitions/simpleTypes'
17066 'uniqueItems': true
17092 '$ref': '#/definitions/schemaArray'
17099 '$ref': '#/definitions/schemaArray'
17106 '$ref': '#/definitions/schemaArray'
17119 'exclusiveMaximum': [
17122 'exclusiveMinimum': [
17128 'http://json-schema.org/draft-07/schema#': {
17129 'title': localize('schema.json', 'Describes a JSON file using a schema. See json-schema.org for more info.'),
17134 'items': { '$ref': '#' }
17136 'nonNegativeInteger': {
17140 'nonNegativeIntegerDefault0': {
17142 { '$ref': '#/definitions/nonNegativeInteger' },
17159 'items': { 'type': 'string' },
17160 'uniqueItems': true,
17164 'type': ['object', 'boolean'],
17168 'format': 'uri-reference'
17176 'format': 'uri-reference'
17198 'exclusiveMinimum': 0
17203 'exclusiveMaximum': {
17209 'exclusiveMinimum': {
17212 'maxLength': { '$ref': '#/definitions/nonNegativeInteger' },
17213 'minLength': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
17218 'additionalItems': { '$ref': '#' },
17222 { '$ref': '#/definitions/schemaArray' }
17226 'maxItems': { '$ref': '#/definitions/nonNegativeInteger' },
17227 'minItems': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
17232 'contains': { '$ref': '#' },
17233 'maxProperties': { '$ref': '#/definitions/nonNegativeInteger' },
17234 'minProperties': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
17235 'required': { '$ref': '#/definitions/stringArray' },
17236 'additionalProperties': { '$ref': '#' },
17239 'additionalProperties': { '$ref': '#' },
17244 'additionalProperties': { '$ref': '#' },
17247 'patternProperties': {
17249 'additionalProperties': { '$ref': '#' },
17250 'propertyNames': { 'format': 'regex' },
17255 'additionalProperties': {
17258 { '$ref': '#/definitions/stringArray' }
17262 'propertyNames': { '$ref': '#' },
17268 'uniqueItems': true
17272 { '$ref': '#/definitions/simpleTypes' },
17275 'items': { '$ref': '#/definitions/simpleTypes' },
17277 'uniqueItems': true
17281 'format': { 'type': 'string' },
17282 'contentMediaType': { 'type': 'string' },
17283 'contentEncoding': { 'type': 'string' },
17284 'if': { '$ref': '#' },
17285 'then': { '$ref': '#' },
17286 'else': { '$ref': '#' },
17287 'allOf': { '$ref': '#/definitions/schemaArray' },
17288 'anyOf': { '$ref': '#/definitions/schemaArray' },
17289 'oneOf': { '$ref': '#/definitions/schemaArray' },
17290 'not': { '$ref': '#' }
17296 var descriptions = {
17297 id: localize('schema.json.id', "A unique identifier for the schema."),
17298 $schema: localize('schema.json.$schema', "The schema to verify this document against."),
17299 title: localize('schema.json.title', "A descriptive title of the element."),
17300 description: localize('schema.json.description', "A long description of the element. Used in hover menus and suggestions."),
17301 default: localize('schema.json.default', "A default value. Used by suggestions."),
17302 multipleOf: localize('schema.json.multipleOf', "A number that should cleanly divide the current value (i.e. have no remainder)."),
17303 maximum: localize('schema.json.maximum', "The maximum numerical value, inclusive by default."),
17304 exclusiveMaximum: localize('schema.json.exclusiveMaximum', "Makes the maximum property exclusive."),
17305 minimum: localize('schema.json.minimum', "The minimum numerical value, inclusive by default."),
17306 exclusiveMinimum: localize('schema.json.exclusiveMininum', "Makes the minimum property exclusive."),
17307 maxLength: localize('schema.json.maxLength', "The maximum length of a string."),
17308 minLength: localize('schema.json.minLength', "The minimum length of a string."),
17309 pattern: localize('schema.json.pattern', "A regular expression to match the string against. It is not implicitly anchored."),
17310 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."),
17311 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."),
17312 maxItems: localize('schema.json.maxItems', "The maximum number of items that can be inside an array. Inclusive."),
17313 minItems: localize('schema.json.minItems', "The minimum number of items that can be inside an array. Inclusive."),
17314 uniqueItems: localize('schema.json.uniqueItems', "If all of the items in the array must be unique. Defaults to false."),
17315 maxProperties: localize('schema.json.maxProperties', "The maximum number of properties an object can have. Inclusive."),
17316 minProperties: localize('schema.json.minProperties', "The minimum number of properties an object can have. Inclusive."),
17317 required: localize('schema.json.required', "An array of strings that lists the names of all properties required on this object."),
17318 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."),
17319 definitions: localize('schema.json.definitions', "Not used for validation. Place subschemas here that you wish to reference inline with $ref."),
17320 properties: localize('schema.json.properties', "A map of property names to schemas for each property."),
17321 patternProperties: localize('schema.json.patternProperties', "A map of regular expressions on property names to schemas for matching properties."),
17322 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."),
17323 enum: localize('schema.json.enum', "The set of literal values that are valid."),
17324 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."),
17325 format: localize('schema.json.format', "Describes the format expected for the value."),
17326 allOf: localize('schema.json.allOf', "An array of schemas, all of which must match."),
17327 anyOf: localize('schema.json.anyOf', "An array of schemas, where at least one must match."),
17328 oneOf: localize('schema.json.oneOf', "An array of schemas, exactly one of which must match."),
17329 not: localize('schema.json.not', "A schema which must not match."),
17330 $id: localize('schema.json.$id', "A unique identifier for the schema."),
17331 $ref: localize('schema.json.$ref', "Reference a definition hosted on any location."),
17332 $comment: localize('schema.json.$comment', "Comments from schema authors to readers or maintainers of the schema."),
17333 readOnly: localize('schema.json.readOnly', "Indicates that the value of the instance is managed exclusively by the owning authority."),
17334 examples: localize('schema.json.examples', "Sample JSON values associated with a particular schema, for the purpose of illustrating usage."),
17335 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."),
17336 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."),
17337 const: localize('schema.json.const', "An instance validates successfully against this keyword if its value is equal to the value of the keyword."),
17338 contentMediaType: localize('schema.json.contentMediaType', "Describes the media type of a string property."),
17339 contentEncoding: localize('schema.json.contentEncoding', "Describes the content encoding of a string property."),
17340 if: localize('schema.json.if', "The validation outcome of the \"if\" subschema controls which of the \"then\" or \"else\" keywords are evaluated."),
17341 then: localize('schema.json.then', "The \"if\" subschema is used for validation when the \"if\" subschema succeeds."),
17342 else: localize('schema.json.else', "The \"else\" subschema is used for validation when the \"if\" subschema fails.")
17344 for (var schemaName in schemaContributions.schemas) {
17345 var schema = schemaContributions.schemas[schemaName];
17346 for (var property in schema.properties) {
17347 var propertyObject = schema.properties[property];
17348 if (typeof propertyObject === 'boolean') {
17349 propertyObject = schema.properties[property] = {};
17351 var description = descriptions[property];
17353 propertyObject['description'] = description;
17356 console.log(property + ": localize('schema.json." + property + "', \"\")");
17364 /***/ (function(module, __webpack_exports__, __webpack_require__) {
17367 __webpack_require__.r(__webpack_exports__);
17368 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFoldingRanges", function() { return getFoldingRanges; });
17369 /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(93);
17370 /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(99);
17371 /*---------------------------------------------------------------------------------------------
17372 * Copyright (c) Microsoft Corporation. All rights reserved.
17373 * Licensed under the MIT License. See License.txt in the project root for license information.
17374 *--------------------------------------------------------------------------------------------*/
17377 function getFoldingRanges(document, context) {
17379 var nestingLevels = [];
17381 var prevStart = -1;
17382 var scanner = Object(jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(document.getText(), false);
17383 var token = scanner.scan();
17384 function addRange(range) {
17385 ranges.push(range);
17386 nestingLevels.push(stack.length);
17388 while (token !== 17 /* EOF */) {
17390 case 1 /* OpenBraceToken */:
17391 case 3 /* OpenBracketToken */: {
17392 var startLine = document.positionAt(scanner.getTokenOffset()).line;
17393 var range = { startLine: startLine, endLine: startLine, kind: token === 1 /* OpenBraceToken */ ? 'object' : 'array' };
17397 case 2 /* CloseBraceToken */:
17398 case 4 /* CloseBracketToken */: {
17399 var kind = token === 2 /* CloseBraceToken */ ? 'object' : 'array';
17400 if (stack.length > 0 && stack[stack.length - 1].kind === kind) {
17401 var range = stack.pop();
17402 var line = document.positionAt(scanner.getTokenOffset()).line;
17403 if (range && line > range.startLine + 1 && prevStart !== range.startLine) {
17404 range.endLine = line - 1;
17406 prevStart = range.startLine;
17411 case 13 /* BlockCommentTrivia */: {
17412 var startLine = document.positionAt(scanner.getTokenOffset()).line;
17413 var endLine = document.positionAt(scanner.getTokenOffset() + scanner.getTokenLength()).line;
17414 if (scanner.getTokenError() === 1 /* UnexpectedEndOfComment */ && startLine + 1 < document.lineCount) {
17415 scanner.setPosition(document.offsetAt(_jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["Position"].create(startLine + 1, 0)));
17418 if (startLine < endLine) {
17419 addRange({ startLine: startLine, endLine: endLine, kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["FoldingRangeKind"].Comment });
17420 prevStart = startLine;
17425 case 12 /* LineCommentTrivia */: {
17426 var text = document.getText().substr(scanner.getTokenOffset(), scanner.getTokenLength());
17427 var m = text.match(/^\/\/\s*#(region\b)|(endregion\b)/);
17429 var line = document.positionAt(scanner.getTokenOffset()).line;
17430 if (m[1]) { // start pattern match
17431 var range = { startLine: line, endLine: line, kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["FoldingRangeKind"].Region };
17435 var i = stack.length - 1;
17436 while (i >= 0 && stack[i].kind !== _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_1__["FoldingRangeKind"].Region) {
17440 var range = stack[i];
17442 if (line > range.startLine && prevStart !== range.startLine) {
17443 range.endLine = line;
17445 prevStart = range.startLine;
17453 token = scanner.scan();
17455 var rangeLimit = context && context.rangeLimit;
17456 if (typeof rangeLimit !== 'number' || ranges.length <= rangeLimit) {
17459 if (context && context.onRangeLimitExceeded) {
17460 context.onRangeLimitExceeded(document.uri);
17463 for (var _i = 0, nestingLevels_1 = nestingLevels; _i < nestingLevels_1.length; _i++) {
17464 var level = nestingLevels_1[_i];
17466 counts[level] = (counts[level] || 0) + 1;
17471 for (var i = 0; i < counts.length; i++) {
17474 if (n + entries > rangeLimit) {
17482 for (var i = 0; i < ranges.length; i++) {
17483 var level = nestingLevels[i];
17484 if (typeof level === 'number') {
17485 if (level < maxLevel || (level === maxLevel && entries++ < rangeLimit)) {
17486 result.push(ranges[i]);
17496 /***/ (function(module, __webpack_exports__, __webpack_require__) {
17499 __webpack_require__.r(__webpack_exports__);
17500 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSelectionRanges", function() { return getSelectionRanges; });
17501 /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(99);
17502 /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(93);
17503 /*---------------------------------------------------------------------------------------------
17504 * Copyright (c) Microsoft Corporation. All rights reserved.
17505 * Licensed under the MIT License. See License.txt in the project root for license information.
17506 *--------------------------------------------------------------------------------------------*/
17509 function getSelectionRanges(document, positions, doc) {
17510 function getSelectionRange(position) {
17511 var offset = document.offsetAt(position);
17512 var node = doc.getNodeFromOffset(offset, true);
17515 switch (node.type) {
17519 // range without ", [ or {
17520 var cStart = node.offset + 1, cEnd = node.offset + node.length - 1;
17521 if (cStart < cEnd && offset >= cStart && offset <= cEnd) {
17522 result.push(newRange(cStart, cEnd));
17524 result.push(newRange(node.offset, node.offset + node.length));
17530 result.push(newRange(node.offset, node.offset + node.length));
17533 if (node.type === 'property' || node.parent && node.parent.type === 'array') {
17534 var afterCommaOffset = getOffsetAfterNextToken(node.offset + node.length, 5 /* CommaToken */);
17535 if (afterCommaOffset !== -1) {
17536 result.push(newRange(node.offset, afterCommaOffset));
17539 node = node.parent;
17541 var current = undefined;
17542 for (var index = result.length - 1; index >= 0; index--) {
17543 current = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_0__["SelectionRange"].create(result[index], current);
17546 current = _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_0__["SelectionRange"].create(_jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_0__["Range"].create(position, position));
17550 function newRange(start, end) {
17551 return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_0__["Range"].create(document.positionAt(start), document.positionAt(end));
17553 var scanner = Object(jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"])(document.getText(), true);
17554 function getOffsetAfterNextToken(offset, expectedToken) {
17555 scanner.setPosition(offset);
17556 var token = scanner.scan();
17557 if (token === expectedToken) {
17558 return scanner.getTokenOffset() + scanner.getTokenLength();
17562 return positions.map(getSelectionRange);
17568 /***/ (function(module, __webpack_exports__, __webpack_require__) {
17571 __webpack_require__.r(__webpack_exports__);
17572 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findDefinition", function() { return findDefinition; });
17573 /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(99);
17574 /*---------------------------------------------------------------------------------------------
17575 * Copyright (c) Microsoft Corporation. All rights reserved.
17576 * Licensed under the MIT License. See License.txt in the project root for license information.
17577 *--------------------------------------------------------------------------------------------*/
17579 function findDefinition(document, position, doc) {
17580 var offset = document.offsetAt(position);
17581 var node = doc.getNodeFromOffset(offset, true);
17582 if (!node || !isRef(node)) {
17583 return Promise.resolve([]);
17585 var propertyNode = node.parent;
17586 var valueNode = propertyNode.valueNode;
17587 var path = valueNode.value;
17588 var targetNode = findTargetNode(doc, path);
17590 return Promise.resolve([]);
17593 targetUri: document.uri,
17594 originSelectionRange: createRange(document, valueNode),
17595 targetRange: createRange(document, targetNode),
17596 targetSelectionRange: createRange(document, targetNode)
17598 return Promise.resolve([definition]);
17600 function createRange(document, node) {
17601 return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_0__["Range"].create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
17603 function isRef(node) {
17604 return node.type === 'string' &&
17606 node.parent.type === 'property' &&
17607 node.parent.valueNode === node &&
17608 node.parent.keyNode.value === "$ref" ||
17611 function findTargetNode(doc, path) {
17612 var tokens = parseJSONPointer(path);
17616 return findNode(tokens, doc.root);
17618 function findNode(pointer, node) {
17622 if (pointer.length === 0) {
17625 var token = pointer.shift();
17626 if (node && node.type === 'object') {
17627 var propertyNode = node.properties.find(function (propertyNode) { return propertyNode.keyNode.value === token; });
17628 if (!propertyNode) {
17631 return findNode(pointer, propertyNode.valueNode);
17633 else if (node && node.type === 'array') {
17634 if (token.match(/^(0|[1-9][0-9]*)$/)) {
17635 var index = Number.parseInt(token);
17636 var arrayItem = node.items[index];
17640 return findNode(pointer, arrayItem);
17645 function parseJSONPointer(path) {
17646 if (path === "#") {
17649 if (path[0] !== '#' || path[1] !== '/') {
17652 return path.substring(2).split(/\//).map(unescape);
17654 function unescape(str) {
17655 return str.replace(/~1/g, '/').replace(/~0/g, '~');
17661 /***/ (function(module, exports, __webpack_require__) {
17665 /*---------------------------------------------------------------------------------------------
17666 * Copyright (c) Microsoft Corporation. All rights reserved.
17667 * Licensed under the MIT License. See License.txt in the project root for license information.
17668 *--------------------------------------------------------------------------------------------*/
17669 Object.defineProperty(exports, "__esModule", { value: true });
17670 exports.getLanguageModelCache = void 0;
17671 function getLanguageModelCache(maxEntries, cleanupIntervalTimeInSec, parse) {
17672 let languageModels = {};
17674 let cleanupInterval = undefined;
17675 if (cleanupIntervalTimeInSec > 0) {
17676 cleanupInterval = setInterval(() => {
17677 let cutoffTime = Date.now() - cleanupIntervalTimeInSec * 1000;
17678 let uris = Object.keys(languageModels);
17679 for (let uri of uris) {
17680 let languageModelInfo = languageModels[uri];
17681 if (languageModelInfo.cTime < cutoffTime) {
17682 delete languageModels[uri];
17686 }, cleanupIntervalTimeInSec * 1000);
17690 let version = document.version;
17691 let languageId = document.languageId;
17692 let languageModelInfo = languageModels[document.uri];
17693 if (languageModelInfo && languageModelInfo.version === version && languageModelInfo.languageId === languageId) {
17694 languageModelInfo.cTime = Date.now();
17695 return languageModelInfo.languageModel;
17697 let languageModel = parse(document);
17698 languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now() };
17699 if (!languageModelInfo) {
17702 if (nModels === maxEntries) {
17703 let oldestTime = Number.MAX_VALUE;
17704 let oldestUri = null;
17705 for (let uri in languageModels) {
17706 let languageModelInfo = languageModels[uri];
17707 if (languageModelInfo.cTime < oldestTime) {
17709 oldestTime = languageModelInfo.cTime;
17713 delete languageModels[oldestUri];
17717 return languageModel;
17719 onDocumentRemoved(document) {
17720 let uri = document.uri;
17721 if (languageModels[uri]) {
17722 delete languageModels[uri];
17727 if (typeof cleanupInterval !== 'undefined') {
17728 clearInterval(cleanupInterval);
17729 cleanupInterval = undefined;
17730 languageModels = {};
17736 exports.getLanguageModelCache = getLanguageModelCache;
17741 /***/ (function(module, exports, __webpack_require__) {
17745 /*---------------------------------------------------------------------------------------------
17746 * Copyright (c) Microsoft Corporation. All rights reserved.
17747 * Licensed under the MIT License. See License.txt in the project root for license information.
17748 *--------------------------------------------------------------------------------------------*/
17749 Object.defineProperty(exports, "__esModule", { value: true });
17750 exports.joinPath = exports.normalizePath = exports.resolvePath = exports.isAbsolutePath = exports.extname = exports.basename = exports.dirname = exports.getScheme = void 0;
17751 const vscode_uri_1 = __webpack_require__(35);
17752 function getScheme(uri) {
17753 return uri.substr(0, uri.indexOf(':'));
17755 exports.getScheme = getScheme;
17756 function dirname(uri) {
17757 const lastIndexOfSlash = uri.lastIndexOf('/');
17758 return lastIndexOfSlash !== -1 ? uri.substr(0, lastIndexOfSlash) : '';
17760 exports.dirname = dirname;
17761 function basename(uri) {
17762 const lastIndexOfSlash = uri.lastIndexOf('/');
17763 return uri.substr(lastIndexOfSlash + 1);
17765 exports.basename = basename;
17766 const Slash = '/'.charCodeAt(0);
17767 const Dot = '.'.charCodeAt(0);
17768 function extname(uri) {
17769 for (let i = uri.length - 1; i >= 0; i--) {
17770 const ch = uri.charCodeAt(i);
17772 if (i > 0 && uri.charCodeAt(i - 1) !== Slash) {
17773 return uri.substr(i);
17779 else if (ch === Slash) {
17785 exports.extname = extname;
17786 function isAbsolutePath(path) {
17787 return path.charCodeAt(0) === Slash;
17789 exports.isAbsolutePath = isAbsolutePath;
17790 function resolvePath(uriString, path) {
17791 if (isAbsolutePath(path)) {
17792 const uri = vscode_uri_1.URI.parse(uriString);
17793 const parts = path.split('/');
17794 return uri.with({ path: normalizePath(parts) }).toString();
17796 return joinPath(uriString, path);
17798 exports.resolvePath = resolvePath;
17799 function normalizePath(parts) {
17800 const newParts = [];
17801 for (const part of parts) {
17802 if (part.length === 0 || part.length === 1 && part.charCodeAt(0) === Dot) {
17805 else if (part.length === 2 && part.charCodeAt(0) === Dot && part.charCodeAt(1) === Dot) {
17809 newParts.push(part);
17812 if (parts.length > 1 && parts[parts.length - 1].length === 0) {
17815 let res = newParts.join('/');
17816 if (parts[0].length === 0) {
17821 exports.normalizePath = normalizePath;
17822 function joinPath(uriString, ...paths) {
17823 const uri = vscode_uri_1.URI.parse(uriString);
17824 const parts = uri.path.split('/');
17825 for (let path of paths) {
17826 parts.push(...path.split('/'));
17828 return uri.with({ path: normalizePath(parts) }).toString();
17830 exports.joinPath = joinPath;
17835 /***/ (function(module, exports, __webpack_require__) {
17838 /*---------------------------------------------------------------------------------------------
17839 * Copyright (c) Microsoft Corporation. All rights reserved.
17840 * Licensed under the MIT License. See License.txt in the project root for license information.
17841 *--------------------------------------------------------------------------------------------*/
17843 Object.defineProperty(exports, "__esModule", { value: true });
17844 var url_1 = __webpack_require__(83);
17845 var https = __webpack_require__(116);
17846 var http = __webpack_require__(117);
17847 var HttpProxyAgent = __webpack_require__(118);
17848 var HttpsProxyAgent = __webpack_require__(134);
17849 var zlib = __webpack_require__(141);
17850 var nls = __webpack_require__(101);
17851 if (process.env.VSCODE_NLS_CONFIG) {
17852 var VSCODE_NLS_CONFIG = process.env.VSCODE_NLS_CONFIG;
17853 nls.config(JSON.parse(VSCODE_NLS_CONFIG));
17855 var localize = nls.loadMessageBundle();
17856 var proxyUrl = null;
17857 var strictSSL = true;
17858 function configure(_proxyUrl, _strictSSL) {
17859 proxyUrl = _proxyUrl;
17860 strictSSL = _strictSSL;
17862 exports.configure = configure;
17863 function xhr(options) {
17864 var agent = getProxyAgent(options.url, { proxyUrl: proxyUrl, strictSSL: strictSSL });
17865 options = assign({}, options);
17866 options = assign(options, { agent: agent, strictSSL: strictSSL });
17867 if (typeof options.followRedirects !== 'number') {
17868 options.followRedirects = 5;
17870 return request(options).then(function (result) { return new Promise(function (c, e) {
17871 var res = result.res;
17872 var readable = res;
17873 var encoding = res.headers && res.headers['content-encoding'];
17874 var isCompleted = false;
17875 if (encoding === 'gzip') {
17876 var gunzip = zlib.createGunzip();
17880 else if (encoding === 'deflate') {
17881 var inflate = zlib.createInflate();
17883 readable = inflate;
17886 readable.on('data', function (c) { return data.push(c); });
17887 readable.on('end', function () {
17891 isCompleted = true;
17892 if (options.followRedirects > 0 && (res.statusCode >= 300 && res.statusCode <= 303 || res.statusCode === 307)) {
17893 var location = res.headers['location'];
17896 type: options.type, url: location, user: options.user, password: options.password, responseType: options.responseType, headers: options.headers,
17897 timeout: options.timeout, followRedirects: options.followRedirects - 1, data: options.data
17899 xhr(newOptions).then(c, e);
17904 responseText: data.join(''),
17905 status: res.statusCode,
17906 headers: res.headers || {}
17908 if ((res.statusCode >= 200 && res.statusCode < 300) || res.statusCode === 1223) {
17915 readable.on('error', function (err) {
17917 responseText: localize('error', 'Unable to access {0}. Error: {1}', options.url, err.message),
17919 headers: undefined,
17921 isCompleted = true;
17924 }); }, function (err) {
17927 message = localize('error.cannot.connect.proxy', 'Unable to connect to {0} through a proxy . Error: {1}', options.url, err.message);
17930 message = localize('error.cannot.connect', 'Unable to connect to {0}. Error: {1}', options.url, err.message);
17932 return Promise.reject({
17933 responseText: message,
17939 function assign(destination) {
17941 for (var _i = 1; _i < arguments.length; _i++) {
17942 sources[_i - 1] = arguments[_i];
17944 sources.forEach(function (source) { return Object.keys(source).forEach(function (key) { return destination[key] = source[key]; }); });
17945 return destination;
17947 function request(options) {
17949 return new Promise(function (c, e) {
17950 var endpoint = url_1.parse(options.url);
17952 hostname: endpoint.hostname,
17953 port: endpoint.port ? parseInt(endpoint.port) : (endpoint.protocol === 'https:' ? 443 : 80),
17954 path: endpoint.path,
17955 method: options.type || 'GET',
17956 headers: options.headers,
17957 agent: options.agent,
17958 rejectUnauthorized: (typeof options.strictSSL === 'boolean') ? options.strictSSL : true
17960 if (options.user && options.password) {
17961 opts.auth = options.user + ':' + options.password;
17963 var handler = function (res) {
17964 if (res.statusCode >= 300 && res.statusCode < 400 && options.followRedirects && options.followRedirects > 0 && res.headers['location']) {
17965 c(request(assign({}, options, {
17966 url: res.headers['location'],
17967 followRedirects: options.followRedirects - 1
17971 c({ req: req, res: res });
17974 if (endpoint.protocol === 'https:') {
17975 req = https.request(opts, handler);
17978 req = http.request(opts, handler);
17980 req.on('error', e);
17981 if (options.timeout) {
17982 req.setTimeout(options.timeout);
17984 if (options.data) {
17985 req.write(options.data);
17990 function getErrorStatusDescription(status) {
17991 if (status < 400) {
17995 case 400: return localize('status.400', 'Bad request. The request cannot be fulfilled due to bad syntax.');
17996 case 401: return localize('status.401', 'Unauthorized. The server is refusing to respond.');
17997 case 403: return localize('status.403', 'Forbidden. The server is refusing to respond.');
17998 case 404: return localize('status.404', 'Not Found. The requested location could not be found.');
17999 case 405: return localize('status.405', 'Method not allowed. A request was made using a request method not supported by that location.');
18000 case 406: return localize('status.406', 'Not Acceptable. The server can only generate a response that is not accepted by the client.');
18001 case 407: return localize('status.407', 'Proxy Authentication Required. The client must first authenticate itself with the proxy.');
18002 case 408: return localize('status.408', 'Request Timeout. The server timed out waiting for the request.');
18003 case 409: return localize('status.409', 'Conflict. The request could not be completed because of a conflict in the request.');
18004 case 410: return localize('status.410', 'Gone. The requested page is no longer available.');
18005 case 411: return localize('status.411', 'Length Required. The "Content-Length" is not defined.');
18006 case 412: return localize('status.412', 'Precondition Failed. The precondition given in the request evaluated to false by the server.');
18007 case 413: return localize('status.413', 'Request Entity Too Large. The server will not accept the request, because the request entity is too large.');
18008 case 414: return localize('status.414', 'Request-URI Too Long. The server will not accept the request, because the URL is too long.');
18009 case 415: return localize('status.415', 'Unsupported Media Type. The server will not accept the request, because the media type is not supported.');
18010 case 500: return localize('status.500', 'Internal Server Error.');
18011 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.');
18012 case 503: return localize('status.503', 'Service Unavailable. The server is currently unavailable (overloaded or down).');
18013 default: return localize('status.416', 'HTTP status code {0}', status);
18016 exports.getErrorStatusDescription = getErrorStatusDescription;
18018 function getSystemProxyURI(requestURL) {
18019 if (requestURL.protocol === 'http:') {
18020 return process.env.HTTP_PROXY || process.env.http_proxy || null;
18022 else if (requestURL.protocol === 'https:') {
18023 return process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null;
18027 function getProxyAgent(rawRequestURL, options) {
18028 if (options === void 0) { options = {}; }
18029 var requestURL = url_1.parse(rawRequestURL);
18030 var proxyURL = options.proxyUrl || getSystemProxyURI(requestURL);
18034 var proxyEndpoint = url_1.parse(proxyURL);
18035 if (!/^https?:$/.test(proxyEndpoint.protocol)) {
18039 host: proxyEndpoint.hostname,
18040 port: Number(proxyEndpoint.port),
18041 auth: proxyEndpoint.auth,
18042 rejectUnauthorized: (typeof options.strictSSL === 'boolean') ? options.strictSSL : true
18044 return requestURL.protocol === 'http:' ? new HttpProxyAgent(opts) : new HttpsProxyAgent(opts);
18050 /***/ (function(module, exports) {
18052 module.exports = require("https");
18056 /***/ (function(module, exports) {
18058 module.exports = require("http");
18062 /***/ (function(module, exports, __webpack_require__) {
18066 * Module dependencies.
18069 var net = __webpack_require__(16);
18070 var tls = __webpack_require__(119);
18071 var url = __webpack_require__(83);
18072 var Agent = __webpack_require__(120);
18073 var inherits = __webpack_require__(3).inherits;
18074 var debug = __webpack_require__(126)('http-proxy-agent');
18080 module.exports = HttpProxyAgent;
18083 * The `HttpProxyAgent` implements an HTTP Agent subclass that connects to the
18084 * specified "HTTP proxy server" in order to proxy HTTP requests.
18089 function HttpProxyAgent (opts) {
18090 if (!(this instanceof HttpProxyAgent)) return new HttpProxyAgent(opts);
18091 if ('string' == typeof opts) opts = url.parse(opts);
18092 if (!opts) throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');
18093 debug('creating new HttpProxyAgent instance: %o', opts);
18094 Agent.call(this, opts);
18096 var proxy = Object.assign({}, opts);
18098 // if `true`, then connect to the proxy server over TLS. defaults to `false`.
18099 this.secureProxy = proxy.protocol ? /^https:?$/i.test(proxy.protocol) : false;
18101 // prefer `hostname` over `host`, and set the `port` if needed
18102 proxy.host = proxy.hostname || proxy.host;
18103 proxy.port = +proxy.port || (this.secureProxy ? 443 : 80);
18105 if (proxy.host && proxy.path) {
18106 // if both a `host` and `path` are specified then it's most likely the
18107 // result of a `url.parse()` call... we need to remove the `path` portion so
18108 // that `net.connect()` doesn't attempt to open that as a unix socket file.
18110 delete proxy.pathname;
18113 this.proxy = proxy;
18115 inherits(HttpProxyAgent, Agent);
18118 * Called when the node-core HTTP client library is creating a new HTTP request.
18123 HttpProxyAgent.prototype.callback = function connect (req, opts, fn) {
18124 var proxy = this.proxy;
18126 // change the `http.ClientRequest` instance's "path" field
18127 // to the absolute path of the URL that will be requested
18128 var parsed = url.parse(req.path);
18129 if (null == parsed.protocol) parsed.protocol = 'http:';
18130 if (null == parsed.hostname) parsed.hostname = opts.hostname || opts.host;
18131 if (null == parsed.port) parsed.port = opts.port;
18132 if (parsed.port == 80) {
18133 // if port is 80, then we can remove the port so that the
18134 // ":80" portion is not on the produced URL
18135 delete parsed.port;
18137 var absolute = url.format(parsed);
18138 req.path = absolute;
18140 // inject the `Proxy-Authorization` header if necessary
18143 'Proxy-Authorization',
18144 'Basic ' + Buffer.from(proxy.auth).toString('base64')
18148 // create a socket connection to the proxy server
18150 if (this.secureProxy) {
18151 socket = tls.connect(proxy);
18153 socket = net.connect(proxy);
18156 // at this point, the http ClientRequest's internal `_header` field might have
18157 // already been set. If this is the case then we'll need to re-generate the
18158 // string since we just changed the `req.path`
18160 debug('regenerating stored HTTP header string for request');
18161 req._header = null;
18162 req._implicitHeader();
18163 if (req.output && req.output.length > 0) {
18164 debug('patching connection write() output buffer with updated header');
18165 // the _header has already been queued to be written to the socket
18166 var first = req.output[0];
18167 var endOfHeaders = first.indexOf('\r\n\r\n') + 4;
18168 req.output[0] = req._header + first.substring(endOfHeaders);
18169 debug('output buffer: %o', req.output);
18179 /***/ (function(module, exports) {
18181 module.exports = require("tls");
18185 /***/ (function(module, exports, __webpack_require__) {
18189 __webpack_require__(121);
18190 const inherits = __webpack_require__(3).inherits;
18191 const promisify = __webpack_require__(122);
18192 const EventEmitter = __webpack_require__(125).EventEmitter;
18194 module.exports = Agent;
18196 function isAgent(v) {
18197 return v && typeof v.addRequest === 'function';
18201 * Base `http.Agent` implementation.
18202 * No pooling/keep-alive is implemented by default.
18204 * @param {Function} callback
18207 function Agent(callback, _opts) {
18208 if (!(this instanceof Agent)) {
18209 return new Agent(callback, _opts);
18212 EventEmitter.call(this);
18214 // The callback gets promisified if it has 3 parameters
18215 // (i.e. it has a callback function) lazily
18216 this._promisifiedCallback = false;
18219 if ('function' === typeof callback) {
18220 this.callback = callback;
18221 } else if (callback) {
18225 // timeout for the socket to be returned from the callback
18226 this.timeout = (opts && opts.timeout) || null;
18228 this.options = opts;
18230 inherits(Agent, EventEmitter);
18233 * Override this function in your subclass!
18235 Agent.prototype.callback = function callback(req, opts) {
18237 '"agent-base" has no default implementation, you must subclass and override `callback()`'
18242 * Called by node-core's "_http_client.js" module when creating
18243 * a new HTTP request with this Agent instance.
18247 Agent.prototype.addRequest = function addRequest(req, _opts) {
18248 const ownOpts = Object.assign({}, _opts);
18250 // Set default `host` for HTTP to localhost
18251 if (null == ownOpts.host) {
18252 ownOpts.host = 'localhost';
18255 // Set default `port` for HTTP if none was explicitly specified
18256 if (null == ownOpts.port) {
18257 ownOpts.port = ownOpts.secureEndpoint ? 443 : 80;
18260 const opts = Object.assign({}, this.options, ownOpts);
18262 if (opts.host && opts.path) {
18263 // If both a `host` and `path` are specified then it's most likely the
18264 // result of a `url.parse()` call... we need to remove the `path` portion so
18265 // that `net.connect()` doesn't attempt to open that as a unix socket file.
18270 delete opts.hostname;
18271 delete opts._defaultAgent;
18272 delete opts.defaultPort;
18273 delete opts.createConnection;
18275 // Hint to use "Connection: close"
18276 // XXX: non-documented `http` module API :(
18278 req.shouldKeepAlive = false;
18280 // Create the `stream.Duplex` instance
18282 let timedOut = false;
18283 const timeoutMs = this.timeout;
18284 const freeSocket = this.freeSocket;
18286 function onerror(err) {
18287 if (req._hadError) return;
18288 req.emit('error', err);
18289 // For Safety. Some additional errors might fire later on
18290 // and we need to make sure we don't double-fire the error event.
18291 req._hadError = true;
18294 function ontimeout() {
18297 const err = new Error(
18298 'A "socket" was not created for HTTP request before ' + timeoutMs + 'ms'
18300 err.code = 'ETIMEOUT';
18304 function callbackError(err) {
18305 if (timedOut) return;
18306 if (timeout != null) {
18307 clearTimeout(timeout);
18313 function onsocket(socket) {
18314 if (timedOut) return;
18315 if (timeout != null) {
18316 clearTimeout(timeout);
18319 if (isAgent(socket)) {
18320 // `socket` is actually an http.Agent instance, so relinquish
18321 // responsibility for this `req` to the Agent from here on
18322 socket.addRequest(req, opts);
18323 } else if (socket) {
18324 function onfree() {
18325 freeSocket(socket, opts);
18327 socket.on('free', onfree);
18328 req.onSocket(socket);
18330 const err = new Error(
18331 'no Duplex stream was returned to agent-base for `' + req.method + ' ' + req.path + '`'
18337 if (!this._promisifiedCallback && this.callback.length >= 3) {
18338 // Legacy callback function - convert to a Promise
18339 this.callback = promisify(this.callback, this);
18340 this._promisifiedCallback = true;
18343 if (timeoutMs > 0) {
18344 timeout = setTimeout(ontimeout, timeoutMs);
18348 Promise.resolve(this.callback(req, opts)).then(onsocket, callbackError);
18350 Promise.reject(err).catch(callbackError);
18354 Agent.prototype.freeSocket = function freeSocket(socket, opts) {
18355 // TODO reuse sockets
18362 /***/ (function(module, exports, __webpack_require__) {
18366 const url = __webpack_require__(83);
18367 const https = __webpack_require__(116);
18370 * This currently needs to be applied to all Node.js versions
18371 * in order to determine if the `req` is an HTTP or HTTPS request.
18373 * There is currently no PR attempting to move this property upstream.
18375 const patchMarker = "__agent_base_https_request_patched__";
18376 if (!https.request[patchMarker]) {
18377 https.request = (function(request) {
18378 return function(_options, cb) {
18380 if (typeof _options === 'string') {
18381 options = url.parse(_options);
18383 options = Object.assign({}, _options);
18385 if (null == options.port) {
18386 options.port = 443;
18388 options.secureEndpoint = true;
18389 return request.call(https, options, cb);
18392 https.request[patchMarker] = true;
18396 * This is needed for Node.js >= 9.0.0 to make sure `https.get()` uses the
18397 * patched `https.request()`.
18399 * Ref: https://github.com/nodejs/node/commit/5118f31
18401 https.get = function (_url, _options, cb) {
18403 if (typeof _url === 'string' && _options && typeof _options !== 'function') {
18404 options = Object.assign({}, url.parse(_url), _options);
18405 } else if (!_options && !cb) {
18412 const req = https.request(options, cb);
18420 /***/ (function(module, exports, __webpack_require__) {
18425 /* global module, require */
18426 module.exports = function () {
18430 // Get a promise object. This may be native, or it may be polyfilled
18432 var ES6Promise = __webpack_require__(123);
18435 * thatLooksLikeAPromiseToMe()
18437 * Duck-types a promise.
18439 * @param {object} o
18440 * @return {bool} True if this resembles a promise
18442 function thatLooksLikeAPromiseToMe(o) {
18443 return o && typeof o.then === "function" && typeof o.catch === "function";
18449 * Transforms callback-based function -- func(arg1, arg2 .. argN, callback) -- into
18450 * an ES6-compatible Promise. Promisify provides a default callback of the form (error, result)
18451 * and rejects when `error` is truthy. You can also supply settings object as the second argument.
18453 * @param {function} original - The function to promisify
18454 * @param {object} settings - Settings object
18455 * @param {object} settings.thisArg - A `this` context to use. If not set, assume `settings` _is_ `thisArg`
18456 * @param {bool} settings.multiArgs - Should multiple arguments be returned as an array?
18457 * @return {function} A promisified version of `original`
18459 return function promisify(original, settings) {
18461 return function () {
18462 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
18463 args[_key] = arguments[_key];
18466 var returnMultipleArguments = settings && settings.multiArgs;
18468 var target = void 0;
18469 if (settings && settings.thisArg) {
18470 target = settings.thisArg;
18471 } else if (settings) {
18475 // Return the promisified function
18476 return new ES6Promise(function (resolve, reject) {
18478 // Append the callback bound to the context
18479 args.push(function callback(err) {
18482 return reject(err);
18485 for (var _len2 = arguments.length, values = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
18486 values[_key2 - 1] = arguments[_key2];
18489 if (false === !!returnMultipleArguments) {
18490 return resolve(values[0]);
18496 // Call the function
18497 var response = original.apply(target, args);
18499 // If it looks like original already returns a promise,
18500 // then just resolve with that promise. Hopefully, the callback function we added will just be ignored.
18501 if (thatLooksLikeAPromiseToMe(response)) {
18511 /***/ (function(module, exports, __webpack_require__) {
18516 /* global self, window, module, global, require */
18517 module.exports = function () {
18521 var globalObject = void 0;
18523 function isFunction(x) {
18524 return typeof x === "function";
18527 // Seek the global object
18528 if (global !== undefined) {
18529 globalObject = global;
18530 } else if (window !== undefined && window.document) {
18531 globalObject = window;
18533 globalObject = self;
18536 // Test for any native promise implementation, and if that
18537 // implementation appears to conform to the specificaton.
18538 // This code mostly nicked from the es6-promise module polyfill
18539 // and then fooled with.
18540 var hasPromiseSupport = function () {
18542 // No promise object at all, and it's a non-starter
18543 if (!globalObject.hasOwnProperty("Promise")) {
18547 // There is a Promise object. Does it conform to the spec?
18548 var P = globalObject.Promise;
18550 // Some of these methods are missing from
18551 // Firefox/Chrome experimental implementations
18552 if (!P.hasOwnProperty("resolve") || !P.hasOwnProperty("reject")) {
18556 if (!P.hasOwnProperty("all") || !P.hasOwnProperty("race")) {
18560 // Older version of the spec had a resolver object
18561 // as the arg rather than a function
18562 return function () {
18564 var resolve = void 0;
18566 var p = new globalObject.Promise(function (r) {
18571 return isFunction(resolve);
18578 // Export the native Promise implementation if it
18579 // looks like it matches the spec
18580 if (hasPromiseSupport) {
18581 return globalObject.Promise;
18584 // Otherwise, return the es6-promise polyfill by @jaffathecake.
18585 return __webpack_require__(124).Promise;
18590 /***/ (function(module, exports, __webpack_require__) {
18593 * @overview es6-promise - a tiny implementation of Promises/A+.
18594 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
18595 * @license Licensed under MIT license
18596 * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
18597 * @version v4.2.8+1e68dce6
18600 (function (global, factory) {
18601 true ? module.exports = factory() :
18603 }(this, (function () { 'use strict';
18605 function objectOrFunction(x) {
18606 var type = typeof x;
18607 return x !== null && (type === 'object' || type === 'function');
18610 function isFunction(x) {
18611 return typeof x === 'function';
18616 var _isArray = void 0;
18617 if (Array.isArray) {
18618 _isArray = Array.isArray;
18620 _isArray = function (x) {
18621 return Object.prototype.toString.call(x) === '[object Array]';
18625 var isArray = _isArray;
18628 var vertxNext = void 0;
18629 var customSchedulerFn = void 0;
18631 var asap = function asap(callback, arg) {
18632 queue[len] = callback;
18633 queue[len + 1] = arg;
18636 // If len is 2, that means that we need to schedule an async flush.
18637 // If additional callbacks are queued before the queue is flushed, they
18638 // will be processed by this flush that we are scheduling.
18639 if (customSchedulerFn) {
18640 customSchedulerFn(flush);
18647 function setScheduler(scheduleFn) {
18648 customSchedulerFn = scheduleFn;
18651 function setAsap(asapFn) {
18655 var browserWindow = typeof window !== 'undefined' ? window : undefined;
18656 var browserGlobal = browserWindow || {};
18657 var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
18658 var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
18660 // test for web worker but not in IE10
18661 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
18664 function useNextTick() {
18665 // node version 0.10.x displays a deprecation warning when nextTick is used recursively
18666 // see https://github.com/cujojs/when/issues/410 for details
18667 return function () {
18668 return process.nextTick(flush);
18673 function useVertxTimer() {
18674 if (typeof vertxNext !== 'undefined') {
18675 return function () {
18680 return useSetTimeout();
18683 function useMutationObserver() {
18684 var iterations = 0;
18685 var observer = new BrowserMutationObserver(flush);
18686 var node = document.createTextNode('');
18687 observer.observe(node, { characterData: true });
18689 return function () {
18690 node.data = iterations = ++iterations % 2;
18695 function useMessageChannel() {
18696 var channel = new MessageChannel();
18697 channel.port1.onmessage = flush;
18698 return function () {
18699 return channel.port2.postMessage(0);
18703 function useSetTimeout() {
18704 // Store setTimeout reference so es6-promise will be unaffected by
18705 // other code modifying setTimeout (like sinon.useFakeTimers())
18706 var globalSetTimeout = setTimeout;
18707 return function () {
18708 return globalSetTimeout(flush, 1);
18712 var queue = new Array(1000);
18714 for (var i = 0; i < len; i += 2) {
18715 var callback = queue[i];
18716 var arg = queue[i + 1];
18720 queue[i] = undefined;
18721 queue[i + 1] = undefined;
18727 function attemptVertx() {
18729 var vertx = Function('return this')().require('vertx');
18730 vertxNext = vertx.runOnLoop || vertx.runOnContext;
18731 return useVertxTimer();
18733 return useSetTimeout();
18737 var scheduleFlush = void 0;
18738 // Decide what async method to use to triggering processing of queued callbacks:
18740 scheduleFlush = useNextTick();
18741 } else if (BrowserMutationObserver) {
18742 scheduleFlush = useMutationObserver();
18743 } else if (isWorker) {
18744 scheduleFlush = useMessageChannel();
18745 } else if (browserWindow === undefined && "function" === 'function') {
18746 scheduleFlush = attemptVertx();
18748 scheduleFlush = useSetTimeout();
18751 function then(onFulfillment, onRejection) {
18754 var child = new this.constructor(noop);
18756 if (child[PROMISE_ID] === undefined) {
18757 makePromise(child);
18760 var _state = parent._state;
18764 var callback = arguments[_state - 1];
18766 return invokeCallback(_state, child, callback, parent._result);
18769 subscribe(parent, child, onFulfillment, onRejection);
18776 `Promise.resolve` returns a promise that will become resolved with the
18777 passed `value`. It is shorthand for the following:
18780 let promise = new Promise(function(resolve, reject){
18784 promise.then(function(value){
18789 Instead of writing the above, your code now simply becomes the following:
18792 let promise = Promise.resolve(1);
18794 promise.then(function(value){
18801 @param {Any} value value that the returned promise will be resolved with
18802 Useful for tooling.
18803 @return {Promise} a promise that will become fulfilled with the given
18806 function resolve$1(object) {
18807 /*jshint validthis:true */
18808 var Constructor = this;
18810 if (object && typeof object === 'object' && object.constructor === Constructor) {
18814 var promise = new Constructor(noop);
18815 resolve(promise, object);
18819 var PROMISE_ID = Math.random().toString(36).substring(2);
18823 var PENDING = void 0;
18827 function selfFulfillment() {
18828 return new TypeError("You cannot resolve a promise with itself");
18831 function cannotReturnOwn() {
18832 return new TypeError('A promises callback cannot return that same promise.');
18835 function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
18837 then$$1.call(value, fulfillmentHandler, rejectionHandler);
18843 function handleForeignThenable(promise, thenable, then$$1) {
18844 asap(function (promise) {
18845 var sealed = false;
18846 var error = tryThen(then$$1, thenable, function (value) {
18851 if (thenable !== value) {
18852 resolve(promise, value);
18854 fulfill(promise, value);
18856 }, function (reason) {
18862 reject(promise, reason);
18863 }, 'Settle: ' + (promise._label || ' unknown promise'));
18865 if (!sealed && error) {
18867 reject(promise, error);
18872 function handleOwnThenable(promise, thenable) {
18873 if (thenable._state === FULFILLED) {
18874 fulfill(promise, thenable._result);
18875 } else if (thenable._state === REJECTED) {
18876 reject(promise, thenable._result);
18878 subscribe(thenable, undefined, function (value) {
18879 return resolve(promise, value);
18880 }, function (reason) {
18881 return reject(promise, reason);
18886 function handleMaybeThenable(promise, maybeThenable, then$$1) {
18887 if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
18888 handleOwnThenable(promise, maybeThenable);
18890 if (then$$1 === undefined) {
18891 fulfill(promise, maybeThenable);
18892 } else if (isFunction(then$$1)) {
18893 handleForeignThenable(promise, maybeThenable, then$$1);
18895 fulfill(promise, maybeThenable);
18900 function resolve(promise, value) {
18901 if (promise === value) {
18902 reject(promise, selfFulfillment());
18903 } else if (objectOrFunction(value)) {
18904 var then$$1 = void 0;
18906 then$$1 = value.then;
18908 reject(promise, error);
18911 handleMaybeThenable(promise, value, then$$1);
18913 fulfill(promise, value);
18917 function publishRejection(promise) {
18918 if (promise._onerror) {
18919 promise._onerror(promise._result);
18925 function fulfill(promise, value) {
18926 if (promise._state !== PENDING) {
18930 promise._result = value;
18931 promise._state = FULFILLED;
18933 if (promise._subscribers.length !== 0) {
18934 asap(publish, promise);
18938 function reject(promise, reason) {
18939 if (promise._state !== PENDING) {
18942 promise._state = REJECTED;
18943 promise._result = reason;
18945 asap(publishRejection, promise);
18948 function subscribe(parent, child, onFulfillment, onRejection) {
18949 var _subscribers = parent._subscribers;
18950 var length = _subscribers.length;
18953 parent._onerror = null;
18955 _subscribers[length] = child;
18956 _subscribers[length + FULFILLED] = onFulfillment;
18957 _subscribers[length + REJECTED] = onRejection;
18959 if (length === 0 && parent._state) {
18960 asap(publish, parent);
18964 function publish(promise) {
18965 var subscribers = promise._subscribers;
18966 var settled = promise._state;
18968 if (subscribers.length === 0) {
18972 var child = void 0,
18974 detail = promise._result;
18976 for (var i = 0; i < subscribers.length; i += 3) {
18977 child = subscribers[i];
18978 callback = subscribers[i + settled];
18981 invokeCallback(settled, child, callback, detail);
18987 promise._subscribers.length = 0;
18990 function invokeCallback(settled, promise, callback, detail) {
18991 var hasCallback = isFunction(callback),
18998 value = callback(detail);
19004 if (promise === value) {
19005 reject(promise, cannotReturnOwn());
19012 if (promise._state !== PENDING) {
19014 } else if (hasCallback && succeeded) {
19015 resolve(promise, value);
19016 } else if (succeeded === false) {
19017 reject(promise, error);
19018 } else if (settled === FULFILLED) {
19019 fulfill(promise, value);
19020 } else if (settled === REJECTED) {
19021 reject(promise, value);
19025 function initializePromise(promise, resolver) {
19027 resolver(function resolvePromise(value) {
19028 resolve(promise, value);
19029 }, function rejectPromise(reason) {
19030 reject(promise, reason);
19033 reject(promise, e);
19038 function nextId() {
19042 function makePromise(promise) {
19043 promise[PROMISE_ID] = id++;
19044 promise._state = undefined;
19045 promise._result = undefined;
19046 promise._subscribers = [];
19049 function validationError() {
19050 return new Error('Array Methods must be provided an Array');
19053 var Enumerator = function () {
19054 function Enumerator(Constructor, input) {
19055 this._instanceConstructor = Constructor;
19056 this.promise = new Constructor(noop);
19058 if (!this.promise[PROMISE_ID]) {
19059 makePromise(this.promise);
19062 if (isArray(input)) {
19063 this.length = input.length;
19064 this._remaining = input.length;
19066 this._result = new Array(this.length);
19068 if (this.length === 0) {
19069 fulfill(this.promise, this._result);
19071 this.length = this.length || 0;
19072 this._enumerate(input);
19073 if (this._remaining === 0) {
19074 fulfill(this.promise, this._result);
19078 reject(this.promise, validationError());
19082 Enumerator.prototype._enumerate = function _enumerate(input) {
19083 for (var i = 0; this._state === PENDING && i < input.length; i++) {
19084 this._eachEntry(input[i], i);
19088 Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
19089 var c = this._instanceConstructor;
19090 var resolve$$1 = c.resolve;
19093 if (resolve$$1 === resolve$1) {
19094 var _then = void 0;
19095 var error = void 0;
19096 var didError = false;
19098 _then = entry.then;
19104 if (_then === then && entry._state !== PENDING) {
19105 this._settledAt(entry._state, i, entry._result);
19106 } else if (typeof _then !== 'function') {
19108 this._result[i] = entry;
19109 } else if (c === Promise$1) {
19110 var promise = new c(noop);
19112 reject(promise, error);
19114 handleMaybeThenable(promise, entry, _then);
19116 this._willSettleAt(promise, i);
19118 this._willSettleAt(new c(function (resolve$$1) {
19119 return resolve$$1(entry);
19123 this._willSettleAt(resolve$$1(entry), i);
19127 Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
19128 var promise = this.promise;
19131 if (promise._state === PENDING) {
19134 if (state === REJECTED) {
19135 reject(promise, value);
19137 this._result[i] = value;
19141 if (this._remaining === 0) {
19142 fulfill(promise, this._result);
19146 Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
19147 var enumerator = this;
19149 subscribe(promise, undefined, function (value) {
19150 return enumerator._settledAt(FULFILLED, i, value);
19151 }, function (reason) {
19152 return enumerator._settledAt(REJECTED, i, reason);
19160 `Promise.all` accepts an array of promises, and returns a new promise which
19161 is fulfilled with an array of fulfillment values for the passed promises, or
19162 rejected with the reason of the first passed promise to be rejected. It casts all
19163 elements of the passed iterable to promises as it runs this algorithm.
19168 let promise1 = resolve(1);
19169 let promise2 = resolve(2);
19170 let promise3 = resolve(3);
19171 let promises = [ promise1, promise2, promise3 ];
19173 Promise.all(promises).then(function(array){
19174 // The array here would be [ 1, 2, 3 ];
19178 If any of the `promises` given to `all` are rejected, the first promise
19179 that is rejected will be given as an argument to the returned promises's
19180 rejection handler. For example:
19185 let promise1 = resolve(1);
19186 let promise2 = reject(new Error("2"));
19187 let promise3 = reject(new Error("3"));
19188 let promises = [ promise1, promise2, promise3 ];
19190 Promise.all(promises).then(function(array){
19191 // Code here never runs because there are rejected promises!
19192 }, function(error) {
19193 // error.message === "2"
19199 @param {Array} entries array of promises
19200 @param {String} label optional string for labeling the promise.
19201 Useful for tooling.
19202 @return {Promise} promise that is fulfilled when all `promises` have been
19203 fulfilled, or rejected if any of them become rejected.
19206 function all(entries) {
19207 return new Enumerator(this, entries).promise;
19211 `Promise.race` returns a new promise which is settled in the same way as the
19212 first passed promise to settle.
19217 let promise1 = new Promise(function(resolve, reject){
19218 setTimeout(function(){
19219 resolve('promise 1');
19223 let promise2 = new Promise(function(resolve, reject){
19224 setTimeout(function(){
19225 resolve('promise 2');
19229 Promise.race([promise1, promise2]).then(function(result){
19230 // result === 'promise 2' because it was resolved before promise1
19235 `Promise.race` is deterministic in that only the state of the first
19236 settled promise matters. For example, even if other promises given to the
19237 `promises` array argument are resolved, but the first settled promise has
19238 become rejected before the other promises became fulfilled, the returned
19239 promise will become rejected:
19242 let promise1 = new Promise(function(resolve, reject){
19243 setTimeout(function(){
19244 resolve('promise 1');
19248 let promise2 = new Promise(function(resolve, reject){
19249 setTimeout(function(){
19250 reject(new Error('promise 2'));
19254 Promise.race([promise1, promise2]).then(function(result){
19255 // Code here never runs
19256 }, function(reason){
19257 // reason.message === 'promise 2' because promise 2 became rejected before
19258 // promise 1 became fulfilled
19262 An example real-world use case is implementing timeouts:
19265 Promise.race([ajax('foo.json'), timeout(5000)])
19270 @param {Array} promises array of promises to observe
19271 Useful for tooling.
19272 @return {Promise} a promise which settles in the same way as the first passed
19275 function race(entries) {
19276 /*jshint validthis:true */
19277 var Constructor = this;
19279 if (!isArray(entries)) {
19280 return new Constructor(function (_, reject) {
19281 return reject(new TypeError('You must pass an array to race.'));
19284 return new Constructor(function (resolve, reject) {
19285 var length = entries.length;
19286 for (var i = 0; i < length; i++) {
19287 Constructor.resolve(entries[i]).then(resolve, reject);
19294 `Promise.reject` returns a promise rejected with the passed `reason`.
19295 It is shorthand for the following:
19298 let promise = new Promise(function(resolve, reject){
19299 reject(new Error('WHOOPS'));
19302 promise.then(function(value){
19303 // Code here doesn't run because the promise is rejected!
19304 }, function(reason){
19305 // reason.message === 'WHOOPS'
19309 Instead of writing the above, your code now simply becomes the following:
19312 let promise = Promise.reject(new Error('WHOOPS'));
19314 promise.then(function(value){
19315 // Code here doesn't run because the promise is rejected!
19316 }, function(reason){
19317 // reason.message === 'WHOOPS'
19323 @param {Any} reason value that the returned promise will be rejected with.
19324 Useful for tooling.
19325 @return {Promise} a promise rejected with the given `reason`.
19327 function reject$1(reason) {
19328 /*jshint validthis:true */
19329 var Constructor = this;
19330 var promise = new Constructor(noop);
19331 reject(promise, reason);
19335 function needsResolver() {
19336 throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
19339 function needsNew() {
19340 throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
19344 Promise objects represent the eventual result of an asynchronous operation. The
19345 primary way of interacting with a promise is through its `then` method, which
19346 registers callbacks to receive either a promise's eventual value or the reason
19347 why the promise cannot be fulfilled.
19352 - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
19353 - `thenable` is an object or function that defines a `then` method.
19354 - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
19355 - `exception` is a value that is thrown using the throw statement.
19356 - `reason` is a value that indicates why a promise was rejected.
19357 - `settled` the final resting state of a promise, fulfilled or rejected.
19359 A promise can be in one of three states: pending, fulfilled, or rejected.
19361 Promises that are fulfilled have a fulfillment value and are in the fulfilled
19362 state. Promises that are rejected have a rejection reason and are in the
19363 rejected state. A fulfillment value is never a thenable.
19365 Promises can also be said to *resolve* a value. If this value is also a
19366 promise, then the original promise's settled state will match the value's
19367 settled state. So a promise that *resolves* a promise that rejects will
19368 itself reject, and a promise that *resolves* a promise that fulfills will
19376 let promise = new Promise(function(resolve, reject) {
19384 promise.then(function(value) {
19386 }, function(reason) {
19394 Promises shine when abstracting away asynchronous interactions such as
19398 function getJSON(url) {
19399 return new Promise(function(resolve, reject){
19400 let xhr = new XMLHttpRequest();
19402 xhr.open('GET', url);
19403 xhr.onreadystatechange = handler;
19404 xhr.responseType = 'json';
19405 xhr.setRequestHeader('Accept', 'application/json');
19408 function handler() {
19409 if (this.readyState === this.DONE) {
19410 if (this.status === 200) {
19411 resolve(this.response);
19413 reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
19420 getJSON('/posts.json').then(function(json) {
19422 }, function(reason) {
19427 Unlike callbacks, promises are great composable primitives.
19432 getJSON('/comments')
19433 ]).then(function(values){
19434 values[0] // => postsJSON
19435 values[1] // => commentsJSON
19442 @param {Function} resolver
19443 Useful for tooling.
19447 var Promise$1 = function () {
19448 function Promise(resolver) {
19449 this[PROMISE_ID] = nextId();
19450 this._result = this._state = undefined;
19451 this._subscribers = [];
19453 if (noop !== resolver) {
19454 typeof resolver !== 'function' && needsResolver();
19455 this instanceof Promise ? initializePromise(this, resolver) : needsNew();
19460 The primary way of interacting with a promise is through its `then` method,
19461 which registers callbacks to receive either a promise's eventual value or the
19462 reason why the promise cannot be fulfilled.
19464 findUser().then(function(user){
19465 // user is available
19466 }, function(reason){
19467 // user is unavailable, and you are given the reason why
19472 The return value of `then` is itself a promise. This second, 'downstream'
19473 promise is resolved with the return value of the first promise's fulfillment
19474 or rejection handler, or rejected if the handler throws an exception.
19476 findUser().then(function (user) {
19478 }, function (reason) {
19479 return 'default name';
19480 }).then(function (userName) {
19481 // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
19482 // will be `'default name'`
19484 findUser().then(function (user) {
19485 throw new Error('Found user, but still unhappy');
19486 }, function (reason) {
19487 throw new Error('`findUser` rejected and we're unhappy');
19488 }).then(function (value) {
19490 }, function (reason) {
19491 // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
19492 // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
19495 If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
19497 findUser().then(function (user) {
19498 throw new PedagogicalException('Upstream error');
19499 }).then(function (value) {
19501 }).then(function (value) {
19503 }, function (reason) {
19504 // The `PedgagocialException` is propagated all the way down to here
19509 Sometimes the value you want to propagate to a downstream promise can only be
19510 retrieved asynchronously. This can be achieved by returning a promise in the
19511 fulfillment or rejection handler. The downstream promise will then be pending
19512 until the returned promise is settled. This is called *assimilation*.
19514 findUser().then(function (user) {
19515 return findCommentsByAuthor(user);
19516 }).then(function (comments) {
19517 // The user's comments are now available
19520 If the assimliated promise rejects, then the downstream promise will also reject.
19522 findUser().then(function (user) {
19523 return findCommentsByAuthor(user);
19524 }).then(function (comments) {
19525 // If `findCommentsByAuthor` fulfills, we'll have the value here
19526 }, function (reason) {
19527 // If `findCommentsByAuthor` rejects, we'll have the reason here
19532 Synchronous Example
19536 result = findResult();
19544 findResult(function(result, err){
19554 findResult().then(function(result){
19556 }, function(reason){
19562 Synchronous Example
19566 author = findAuthor();
19567 books = findBooksByAuthor(author);
19575 function foundBooks(books) {
19577 function failure(reason) {
19579 findAuthor(function(author, err){
19585 findBoooksByAuthor(author, function(books, err) {
19606 then(findBooksByAuthor).
19607 then(function(books){
19609 }).catch(function(reason){
19610 // something went wrong
19614 @param {Function} onFulfilled
19615 @param {Function} onRejected
19616 Useful for tooling.
19621 `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
19622 as the catch block of a try/catch statement.
19624 function findAuthor(){
19625 throw new Error('couldn't find that author');
19631 // something went wrong
19633 // async with promises
19634 findAuthor().catch(function(reason){
19635 // something went wrong
19639 @param {Function} onRejection
19640 Useful for tooling.
19645 Promise.prototype.catch = function _catch(onRejection) {
19646 return this.then(null, onRejection);
19650 `finally` will be invoked regardless of the promise's fate just as native
19651 try/catch/finally behaves
19653 Synchronous example:
19657 if (Math.random() > 0.5) {
19660 return new Author();
19664 return findAuthor(); // succeed or fail
19666 return findOtherAuther();
19669 // doesn't affect the return value
19673 Asynchronous example:
19676 findAuthor().catch(function(reason){
19677 return findOtherAuther();
19678 }).finally(function(){
19679 // author was either found, or not
19684 @param {Function} callback
19689 Promise.prototype.finally = function _finally(callback) {
19690 var promise = this;
19691 var constructor = promise.constructor;
19693 if (isFunction(callback)) {
19694 return promise.then(function (value) {
19695 return constructor.resolve(callback()).then(function () {
19698 }, function (reason) {
19699 return constructor.resolve(callback()).then(function () {
19705 return promise.then(callback, callback);
19711 Promise$1.prototype.then = then;
19712 Promise$1.all = all;
19713 Promise$1.race = race;
19714 Promise$1.resolve = resolve$1;
19715 Promise$1.reject = reject$1;
19716 Promise$1._setScheduler = setScheduler;
19717 Promise$1._setAsap = setAsap;
19718 Promise$1._asap = asap;
19721 function polyfill() {
19722 var local = void 0;
19724 if (typeof global !== 'undefined') {
19726 } else if (typeof self !== 'undefined') {
19730 local = Function('return this')();
19732 throw new Error('polyfill failed because global object is unavailable in this environment');
19736 var P = local.Promise;
19739 var promiseToString = null;
19741 promiseToString = Object.prototype.toString.call(P.resolve());
19743 // silently ignored
19746 if (promiseToString === '[object Promise]' && !P.cast) {
19751 local.Promise = Promise$1;
19754 // Strange compat..
19755 Promise$1.polyfill = polyfill;
19756 Promise$1.Promise = Promise$1;
19764 //# sourceMappingURL=es6-promise.map
19769 /***/ (function(module, exports) {
19771 module.exports = require("events");
19775 /***/ (function(module, exports, __webpack_require__) {
19778 * Detect Electron renderer process, which is node, but we should
19779 * treat as a browser.
19782 if (typeof process === 'undefined' || process.type === 'renderer') {
19783 module.exports = __webpack_require__(127);
19785 module.exports = __webpack_require__(130);
19791 /***/ (function(module, exports, __webpack_require__) {
19794 * This is the web browser implementation of `debug()`.
19796 * Expose `debug()` as the module.
19799 exports = module.exports = __webpack_require__(128);
19801 exports.formatArgs = formatArgs;
19802 exports.save = save;
19803 exports.load = load;
19804 exports.useColors = useColors;
19805 exports.storage = 'undefined' != typeof chrome
19806 && 'undefined' != typeof chrome.storage
19807 ? chrome.storage.local
19815 '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC',
19816 '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF',
19817 '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC',
19818 '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF',
19819 '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC',
19820 '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033',
19821 '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366',
19822 '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933',
19823 '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC',
19824 '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF',
19825 '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'
19829 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
19830 * and the Firebug extension (any Firefox version) are known
19831 * to support "%c" CSS customizations.
19833 * TODO: add a `localStorage` variable to explicitly enable/disable colors
19836 function useColors() {
19837 // NB: In an Electron preload script, document will be defined but not fully
19838 // initialized. Since we know we're in Chrome, we'll just detect this case
19840 if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
19844 // Internet Explorer and Edge do not support colors.
19845 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
19849 // is webkit? http://stackoverflow.com/a/16459606/376773
19850 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
19851 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
19852 // is firebug? http://stackoverflow.com/a/398120/376773
19853 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
19854 // is firefox >= v31?
19855 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
19856 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
19857 // double check webkit in userAgent just in case we are in a worker
19858 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
19862 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
19865 exports.formatters.j = function(v) {
19867 return JSON.stringify(v);
19869 return '[UnexpectedJSONParseError]: ' + err.message;
19875 * Colorize log arguments if enabled.
19880 function formatArgs(args) {
19881 var useColors = this.useColors;
19883 args[0] = (useColors ? '%c' : '')
19885 + (useColors ? ' %c' : ' ')
19887 + (useColors ? '%c ' : ' ')
19888 + '+' + exports.humanize(this.diff);
19890 if (!useColors) return;
19892 var c = 'color: ' + this.color;
19893 args.splice(1, 0, c, 'color: inherit')
19895 // the final "%c" is somewhat tricky, because there could be other
19896 // arguments passed either before or after the %c, so we need to
19897 // figure out the correct index to insert the CSS into
19900 args[0].replace(/%[a-zA-Z%]/g, function(match) {
19901 if ('%%' === match) return;
19903 if ('%c' === match) {
19904 // we only are interested in the *last* %c
19905 // (the user may have provided their own)
19910 args.splice(lastC, 0, c);
19914 * Invokes `console.log()` when available.
19915 * No-op when `console.log` is not a "function".
19921 // this hackery is required for IE8/9, where
19922 // the `console.log` function doesn't have 'apply'
19923 return 'object' === typeof console
19925 && Function.prototype.apply.call(console.log, console, arguments);
19929 * Save `namespaces`.
19931 * @param {String} namespaces
19935 function save(namespaces) {
19937 if (null == namespaces) {
19938 exports.storage.removeItem('debug');
19940 exports.storage.debug = namespaces;
19946 * Load `namespaces`.
19948 * @return {String} returns the previously persisted debug modes
19955 r = exports.storage.debug;
19958 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
19959 if (!r && typeof process !== 'undefined' && 'env' in process) {
19960 r = process.env.DEBUG;
19967 * Enable namespaces listed in `localStorage.debug` initially.
19970 exports.enable(load());
19973 * Localstorage attempts to return the localstorage.
19975 * This is necessary because safari throws
19976 * when a user disables cookies/localstorage
19977 * and you attempt to access it.
19979 * @return {LocalStorage}
19983 function localstorage() {
19985 return window.localStorage;
19992 /***/ (function(module, exports, __webpack_require__) {
19996 * This is the common logic for both the Node.js and web browser
19997 * implementations of `debug()`.
19999 * Expose `debug()` as the module.
20002 exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
20003 exports.coerce = coerce;
20004 exports.disable = disable;
20005 exports.enable = enable;
20006 exports.enabled = enabled;
20007 exports.humanize = __webpack_require__(129);
20010 * Active `debug` instances.
20012 exports.instances = [];
20015 * The currently active debug mode names, and names to skip.
20018 exports.names = [];
20019 exports.skips = [];
20022 * Map of special "%n" handling functions, for the debug "format" argument.
20024 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
20027 exports.formatters = {};
20031 * @param {String} namespace
20036 function selectColor(namespace) {
20039 for (i in namespace) {
20040 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
20041 hash |= 0; // Convert to 32bit integer
20044 return exports.colors[Math.abs(hash) % exports.colors.length];
20048 * Create a debugger with the given `namespace`.
20050 * @param {String} namespace
20051 * @return {Function}
20055 function createDebug(namespace) {
20061 if (!debug.enabled) return;
20065 // set `diff` timestamp
20066 var curr = +new Date();
20067 var ms = curr - (prevTime || curr);
20069 self.prev = prevTime;
20073 // turn the `arguments` into a proper Array
20074 var args = new Array(arguments.length);
20075 for (var i = 0; i < args.length; i++) {
20076 args[i] = arguments[i];
20079 args[0] = exports.coerce(args[0]);
20081 if ('string' !== typeof args[0]) {
20082 // anything else let's inspect with %O
20083 args.unshift('%O');
20086 // apply any `formatters` transformations
20088 args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
20089 // if we encounter an escaped % then don't increase the array index
20090 if (match === '%%') return match;
20092 var formatter = exports.formatters[format];
20093 if ('function' === typeof formatter) {
20094 var val = args[index];
20095 match = formatter.call(self, val);
20097 // now we need to remove `args[index]` since it's inlined in the `format`
20098 args.splice(index, 1);
20104 // apply env-specific formatting (colors, etc.)
20105 exports.formatArgs.call(self, args);
20107 var logFn = debug.log || exports.log || console.log.bind(console);
20108 logFn.apply(self, args);
20111 debug.namespace = namespace;
20112 debug.enabled = exports.enabled(namespace);
20113 debug.useColors = exports.useColors();
20114 debug.color = selectColor(namespace);
20115 debug.destroy = destroy;
20117 // env-specific initialization logic for debug instances
20118 if ('function' === typeof exports.init) {
20119 exports.init(debug);
20122 exports.instances.push(debug);
20127 function destroy () {
20128 var index = exports.instances.indexOf(this);
20129 if (index !== -1) {
20130 exports.instances.splice(index, 1);
20138 * Enables a debug mode by namespaces. This can include modes
20139 * separated by a colon and wildcards.
20141 * @param {String} namespaces
20145 function enable(namespaces) {
20146 exports.save(namespaces);
20148 exports.names = [];
20149 exports.skips = [];
20152 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
20153 var len = split.length;
20155 for (i = 0; i < len; i++) {
20156 if (!split[i]) continue; // ignore empty strings
20157 namespaces = split[i].replace(/\*/g, '.*?');
20158 if (namespaces[0] === '-') {
20159 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
20161 exports.names.push(new RegExp('^' + namespaces + '$'));
20165 for (i = 0; i < exports.instances.length; i++) {
20166 var instance = exports.instances[i];
20167 instance.enabled = exports.enabled(instance.namespace);
20172 * Disable debug output.
20177 function disable() {
20178 exports.enable('');
20182 * Returns true if the given mode name is enabled, false otherwise.
20184 * @param {String} name
20185 * @return {Boolean}
20189 function enabled(name) {
20190 if (name[name.length - 1] === '*') {
20194 for (i = 0, len = exports.skips.length; i < len; i++) {
20195 if (exports.skips[i].test(name)) {
20199 for (i = 0, len = exports.names.length; i < len; i++) {
20200 if (exports.names[i].test(name)) {
20210 * @param {Mixed} val
20215 function coerce(val) {
20216 if (val instanceof Error) return val.stack || val.message;
20223 /***/ (function(module, exports) {
20233 var y = d * 365.25;
20236 * Parse or format the given `val`.
20240 * - `long` verbose formatting [false]
20242 * @param {String|Number} val
20243 * @param {Object} [options]
20244 * @throws {Error} throw an error if val is not a non-empty string or a number
20245 * @return {String|Number}
20249 module.exports = function(val, options) {
20250 options = options || {};
20251 var type = typeof val;
20252 if (type === 'string' && val.length > 0) {
20254 } else if (type === 'number' && isNaN(val) === false) {
20255 return options.long ? fmtLong(val) : fmtShort(val);
20258 'val is not a non-empty string or a valid number. val=' +
20259 JSON.stringify(val)
20264 * Parse the given `str` and return milliseconds.
20266 * @param {String} str
20271 function parse(str) {
20273 if (str.length > 100) {
20276 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
20282 var n = parseFloat(match[1]);
20283 var type = (match[2] || 'ms').toLowerCase();
20313 case 'milliseconds':
20314 case 'millisecond':
20325 * Short format for `ms`.
20327 * @param {Number} ms
20332 function fmtShort(ms) {
20334 return Math.round(ms / d) + 'd';
20337 return Math.round(ms / h) + 'h';
20340 return Math.round(ms / m) + 'm';
20343 return Math.round(ms / s) + 's';
20349 * Long format for `ms`.
20351 * @param {Number} ms
20356 function fmtLong(ms) {
20357 return plural(ms, d, 'day') ||
20358 plural(ms, h, 'hour') ||
20359 plural(ms, m, 'minute') ||
20360 plural(ms, s, 'second') ||
20365 * Pluralization helper.
20368 function plural(ms, n, name) {
20372 if (ms < n * 1.5) {
20373 return Math.floor(ms / n) + ' ' + name;
20375 return Math.ceil(ms / n) + ' ' + name + 's';
20381 /***/ (function(module, exports, __webpack_require__) {
20384 * Module dependencies.
20387 var tty = __webpack_require__(131);
20388 var util = __webpack_require__(3);
20391 * This is the Node.js implementation of `debug()`.
20393 * Expose `debug()` as the module.
20396 exports = module.exports = __webpack_require__(128);
20397 exports.init = init;
20399 exports.formatArgs = formatArgs;
20400 exports.save = save;
20401 exports.load = load;
20402 exports.useColors = useColors;
20408 exports.colors = [ 6, 2, 3, 4, 5, 1 ];
20411 var supportsColor = __webpack_require__(132);
20412 if (supportsColor && supportsColor.level >= 2) {
20414 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68,
20415 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134,
20416 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171,
20417 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204,
20418 205, 206, 207, 208, 209, 214, 215, 220, 221
20422 // swallow - we only care if `supports-color` is available; it doesn't have to be.
20426 * Build up the default `inspectOpts` object from the environment variables.
20428 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
20431 exports.inspectOpts = Object.keys(process.env).filter(function (key) {
20432 return /^debug_/i.test(key);
20433 }).reduce(function (obj, key) {
20438 .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
20440 // coerce string value into JS value
20441 var val = process.env[key];
20442 if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
20443 else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
20444 else if (val === 'null') val = null;
20445 else val = Number(val);
20452 * Is stdout a TTY? Colored output is enabled when `true`.
20455 function useColors() {
20456 return 'colors' in exports.inspectOpts
20457 ? Boolean(exports.inspectOpts.colors)
20458 : tty.isatty(process.stderr.fd);
20462 * Map %o to `util.inspect()`, all on a single line.
20465 exports.formatters.o = function(v) {
20466 this.inspectOpts.colors = this.useColors;
20467 return util.inspect(v, this.inspectOpts)
20468 .split('\n').map(function(str) {
20474 * Map %o to `util.inspect()`, allowing multiple lines if needed.
20477 exports.formatters.O = function(v) {
20478 this.inspectOpts.colors = this.useColors;
20479 return util.inspect(v, this.inspectOpts);
20483 * Adds ANSI color escape codes if enabled.
20488 function formatArgs(args) {
20489 var name = this.namespace;
20490 var useColors = this.useColors;
20493 var c = this.color;
20494 var colorCode = '\u001b[3' + (c < 8 ? c : '8;5;' + c);
20495 var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m';
20497 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
20498 args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
20500 args[0] = getDate() + name + ' ' + args[0];
20504 function getDate() {
20505 if (exports.inspectOpts.hideDate) {
20508 return new Date().toISOString() + ' ';
20513 * Invokes `util.format()` with the specified arguments and writes to stderr.
20517 return process.stderr.write(util.format.apply(util, arguments) + '\n');
20521 * Save `namespaces`.
20523 * @param {String} namespaces
20527 function save(namespaces) {
20528 if (null == namespaces) {
20529 // If you set a process.env field to null or undefined, it gets cast to the
20530 // string 'null' or 'undefined'. Just delete instead.
20531 delete process.env.DEBUG;
20533 process.env.DEBUG = namespaces;
20538 * Load `namespaces`.
20540 * @return {String} returns the previously persisted debug modes
20545 return process.env.DEBUG;
20549 * Init logic for `debug` instances.
20551 * Create a new `inspectOpts` object in case `useColors` is set
20552 * differently for a particular `debug` instance.
20555 function init (debug) {
20556 debug.inspectOpts = {};
20558 var keys = Object.keys(exports.inspectOpts);
20559 for (var i = 0; i < keys.length; i++) {
20560 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
20565 * Enable namespaces listed in `process.env.DEBUG` initially.
20568 exports.enable(load());
20573 /***/ (function(module, exports) {
20575 module.exports = require("tty");
20579 /***/ (function(module, exports, __webpack_require__) {
20583 const os = __webpack_require__(14);
20584 const hasFlag = __webpack_require__(133);
20586 const {env} = process;
20589 if (hasFlag('no-color') ||
20590 hasFlag('no-colors') ||
20591 hasFlag('color=false') ||
20592 hasFlag('color=never')) {
20594 } else if (hasFlag('color') ||
20595 hasFlag('colors') ||
20596 hasFlag('color=true') ||
20597 hasFlag('color=always')) {
20600 if ('FORCE_COLOR' in env) {
20601 if (env.FORCE_COLOR === true || env.FORCE_COLOR === 'true') {
20603 } else if (env.FORCE_COLOR === false || env.FORCE_COLOR === 'false') {
20606 forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
20610 function translateLevel(level) {
20618 has256: level >= 2,
20623 function supportsColor(stream) {
20624 if (forceColor === 0) {
20628 if (hasFlag('color=16m') ||
20629 hasFlag('color=full') ||
20630 hasFlag('color=truecolor')) {
20634 if (hasFlag('color=256')) {
20638 if (stream && !stream.isTTY && forceColor === undefined) {
20642 const min = forceColor || 0;
20644 if (env.TERM === 'dumb') {
20648 if (process.platform === 'win32') {
20649 // Node.js 7.5.0 is the first version of Node.js to include a patch to
20650 // libuv that enables 256 color output on Windows. Anything earlier and it
20651 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
20652 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
20653 // release that supports 256 colors. Windows 10 build 14931 is the first release
20654 // that supports 16m/TrueColor.
20655 const osRelease = os.release().split('.');
20657 Number(process.versions.node.split('.')[0]) >= 8 &&
20658 Number(osRelease[0]) >= 10 &&
20659 Number(osRelease[2]) >= 10586
20661 return Number(osRelease[2]) >= 14931 ? 3 : 2;
20668 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
20675 if ('TEAMCITY_VERSION' in env) {
20676 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
20679 if (env.COLORTERM === 'truecolor') {
20683 if ('TERM_PROGRAM' in env) {
20684 const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
20686 switch (env.TERM_PROGRAM) {
20688 return version >= 3 ? 3 : 2;
20689 case 'Apple_Terminal':
20695 if (/-256(color)?$/i.test(env.TERM)) {
20699 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
20703 if ('COLORTERM' in env) {
20710 function getSupportLevel(stream) {
20711 const level = supportsColor(stream);
20712 return translateLevel(level);
20716 supportsColor: getSupportLevel,
20717 stdout: getSupportLevel(process.stdout),
20718 stderr: getSupportLevel(process.stderr)
20724 /***/ (function(module, exports, __webpack_require__) {
20728 module.exports = (flag, argv) => {
20729 argv = argv || process.argv;
20730 const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
20731 const pos = argv.indexOf(prefix + flag);
20732 const terminatorPos = argv.indexOf('--');
20733 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
20739 /***/ (function(module, exports, __webpack_require__) {
20742 * Module dependencies.
20745 var net = __webpack_require__(16);
20746 var tls = __webpack_require__(119);
20747 var url = __webpack_require__(83);
20748 var assert = __webpack_require__(135);
20749 var Agent = __webpack_require__(120);
20750 var inherits = __webpack_require__(3).inherits;
20751 var debug = __webpack_require__(136)('https-proxy-agent');
20757 module.exports = HttpsProxyAgent;
20760 * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to the
20761 * specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
20766 function HttpsProxyAgent(opts) {
20767 if (!(this instanceof HttpsProxyAgent)) return new HttpsProxyAgent(opts);
20768 if ('string' == typeof opts) opts = url.parse(opts);
20771 'an HTTP(S) proxy server `host` and `port` must be specified!'
20773 debug('creating new HttpsProxyAgent instance: %o', opts);
20774 Agent.call(this, opts);
20776 var proxy = Object.assign({}, opts);
20778 // if `true`, then connect to the proxy server over TLS. defaults to `false`.
20779 this.secureProxy = proxy.protocol
20780 ? /^https:?$/i.test(proxy.protocol)
20783 // prefer `hostname` over `host`, and set the `port` if needed
20784 proxy.host = proxy.hostname || proxy.host;
20785 proxy.port = +proxy.port || (this.secureProxy ? 443 : 80);
20787 // ALPN is supported by Node.js >= v5.
20788 // attempt to negotiate http/1.1 for proxy servers that support http/2
20789 if (this.secureProxy && !('ALPNProtocols' in proxy)) {
20790 proxy.ALPNProtocols = ['http 1.1'];
20793 if (proxy.host && proxy.path) {
20794 // if both a `host` and `path` are specified then it's most likely the
20795 // result of a `url.parse()` call... we need to remove the `path` portion so
20796 // that `net.connect()` doesn't attempt to open that as a unix socket file.
20798 delete proxy.pathname;
20801 this.proxy = proxy;
20802 this.defaultPort = 443;
20804 inherits(HttpsProxyAgent, Agent);
20807 * Called when the node-core HTTP client library is creating a new HTTP request.
20812 HttpsProxyAgent.prototype.callback = function connect(req, opts, fn) {
20813 var proxy = this.proxy;
20815 // create a socket connection to the proxy server
20817 if (this.secureProxy) {
20818 socket = tls.connect(proxy);
20820 socket = net.connect(proxy);
20823 // we need to buffer any HTTP traffic that happens with the proxy before we get
20824 // the CONNECT response, so that if the response is anything other than an "200"
20825 // response code, then we can re-play the "data" events on the socket once the
20826 // HTTP parser is hooked up...
20828 var buffersLength = 0;
20831 var b = socket.read();
20833 else socket.once('readable', read);
20836 function cleanup() {
20837 socket.removeListener('end', onend);
20838 socket.removeListener('error', onerror);
20839 socket.removeListener('close', onclose);
20840 socket.removeListener('readable', read);
20843 function onclose(err) {
20844 debug('onclose had error %o', err);
20851 function onerror(err) {
20856 function ondata(b) {
20858 buffersLength += b.length;
20859 var buffered = Buffer.concat(buffers, buffersLength);
20860 var str = buffered.toString('ascii');
20862 if (!~str.indexOf('\r\n\r\n')) {
20864 debug('have not received end of HTTP headers yet...');
20869 var firstLine = str.substring(0, str.indexOf('\r\n'));
20870 var statusCode = +firstLine.split(' ')[1];
20871 debug('got proxy server response: %o', firstLine);
20873 if (200 == statusCode) {
20874 // 200 Connected status code!
20877 // nullify the buffered data since we won't be needing it
20878 buffers = buffered = null;
20880 if (opts.secureEndpoint) {
20881 // since the proxy is connecting to an SSL server, we have
20882 // to upgrade this socket connection to an SSL connection
20884 'upgrading proxy-connected socket to TLS connection: %o',
20887 opts.socket = socket;
20888 opts.servername = opts.servername || opts.host;
20890 opts.hostname = null;
20892 sock = tls.connect(opts);
20896 req.once('socket', resume);
20899 // some other status code that's not 200... need to re-play the HTTP header
20900 // "data" events onto the socket once the HTTP machinery is attached so
20901 // that the node core `http` can parse and handle the error status code
20904 // the original socket is closed, and a new closed socket is
20905 // returned instead, so that the proxy doesn't get the HTTP request
20906 // written to it (which may contain `Authorization` headers or other
20907 // sensitive data).
20909 // See: https://hackerone.com/reports/541502
20911 socket = new net.Socket();
20912 socket.readable = true;
20915 // save a reference to the concat'd Buffer for the `onsocket` callback
20916 buffers = buffered;
20918 // need to wait for the "socket" event to re-play the "data" events
20919 req.once('socket', onsocket);
20925 function onsocket(socket) {
20926 debug('replaying proxy buffer for failed request');
20927 assert(socket.listenerCount('data') > 0);
20929 // replay the "buffers" Buffer onto the `socket`, since at this point
20930 // the HTTP module machinery has been hooked up for the user
20931 socket.push(buffers);
20933 // nullify the cached Buffer instance
20937 socket.on('error', onerror);
20938 socket.on('close', onclose);
20939 socket.on('end', onend);
20943 var hostname = opts.host + ':' + opts.port;
20944 var msg = 'CONNECT ' + hostname + ' HTTP/1.1\r\n';
20946 var headers = Object.assign({}, proxy.headers);
20948 headers['Proxy-Authorization'] =
20949 'Basic ' + Buffer.from(proxy.auth).toString('base64');
20952 // the Host header should only include the port
20953 // number when it is a non-standard port
20954 var host = opts.host;
20955 if (!isDefaultPort(opts.port, opts.secureEndpoint)) {
20956 host += ':' + opts.port;
20958 headers['Host'] = host;
20960 headers['Connection'] = 'close';
20961 Object.keys(headers).forEach(function(name) {
20962 msg += name + ': ' + headers[name] + '\r\n';
20965 socket.write(msg + '\r\n');
20969 * Resumes a socket.
20971 * @param {(net.Socket|tls.Socket)} socket The socket to resume
20975 function resume(socket) {
20979 function isDefaultPort(port, secure) {
20980 return Boolean((!secure && port === 80) || (secure && port === 443));
20986 /***/ (function(module, exports) {
20988 module.exports = require("assert");
20992 /***/ (function(module, exports, __webpack_require__) {
20998 * Detect Electron renderer / nwjs process, which is node, but we should
20999 * treat as a browser.
21001 if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
21002 module.exports = __webpack_require__(137);
21004 module.exports = __webpack_require__(140);
21011 /***/ (function(module, exports, __webpack_require__) {
21016 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); }
21018 /* eslint-env browser */
21021 * This is the web browser implementation of `debug()`.
21024 exports.formatArgs = formatArgs;
21025 exports.save = save;
21026 exports.load = load;
21027 exports.useColors = useColors;
21028 exports.storage = localstorage();
21033 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'];
21035 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
21036 * and the Firebug extension (any Firefox version) are known
21037 * to support "%c" CSS customizations.
21039 * TODO: add a `localStorage` variable to explicitly enable/disable colors
21041 // eslint-disable-next-line complexity
21043 function useColors() {
21044 // NB: In an Electron preload script, document will be defined but not fully
21045 // initialized. Since we know we're in Chrome, we'll just detect this case
21047 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
21049 } // Internet Explorer and Edge do not support colors.
21052 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
21054 } // Is webkit? http://stackoverflow.com/a/16459606/376773
21055 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
21058 return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
21059 typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
21060 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
21061 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
21062 typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
21065 * Colorize log arguments if enabled.
21071 function formatArgs(args) {
21072 args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
21074 if (!this.useColors) {
21078 var c = 'color: ' + this.color;
21079 args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
21080 // arguments passed either before or after the %c, so we need to
21081 // figure out the correct index to insert the CSS into
21085 args[0].replace(/%[a-zA-Z%]/g, function (match) {
21086 if (match === '%%') {
21092 if (match === '%c') {
21093 // We only are interested in the *last* %c
21094 // (the user may have provided their own)
21098 args.splice(lastC, 0, c);
21101 * Invokes `console.log()` when available.
21102 * No-op when `console.log` is not a "function".
21111 // This hackery is required for IE8/9, where
21112 // the `console.log` function doesn't have 'apply'
21113 return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
21116 * Save `namespaces`.
21118 * @param {String} namespaces
21123 function save(namespaces) {
21126 exports.storage.setItem('debug', namespaces);
21128 exports.storage.removeItem('debug');
21130 } catch (error) {// Swallow
21131 // XXX (@Qix-) should we be logging these?
21135 * Load `namespaces`.
21137 * @return {String} returns the previously persisted debug modes
21146 r = exports.storage.getItem('debug');
21147 } catch (error) {} // Swallow
21148 // XXX (@Qix-) should we be logging these?
21149 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
21152 if (!r && typeof process !== 'undefined' && 'env' in process) {
21153 r = process.env.DEBUG;
21159 * Localstorage attempts to return the localstorage.
21161 * This is necessary because safari throws
21162 * when a user disables cookies/localstorage
21163 * and you attempt to access it.
21165 * @return {LocalStorage}
21170 function localstorage() {
21172 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
21173 // The Browser also has localStorage in the global context.
21174 return localStorage;
21175 } catch (error) {// Swallow
21176 // XXX (@Qix-) should we be logging these?
21180 module.exports = __webpack_require__(138)(exports);
21181 var formatters = module.exports.formatters;
21183 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
21186 formatters.j = function (v) {
21188 return JSON.stringify(v);
21190 return '[UnexpectedJSONParseError]: ' + error.message;
21198 /***/ (function(module, exports, __webpack_require__) {
21204 * This is the common logic for both the Node.js and web browser
21205 * implementations of `debug()`.
21207 function setup(env) {
21208 createDebug.debug = createDebug;
21209 createDebug.default = createDebug;
21210 createDebug.coerce = coerce;
21211 createDebug.disable = disable;
21212 createDebug.enable = enable;
21213 createDebug.enabled = enabled;
21214 createDebug.humanize = __webpack_require__(139);
21215 Object.keys(env).forEach(function (key) {
21216 createDebug[key] = env[key];
21219 * Active `debug` instances.
21222 createDebug.instances = [];
21224 * The currently active debug mode names, and names to skip.
21227 createDebug.names = [];
21228 createDebug.skips = [];
21230 * Map of special "%n" handling functions, for the debug "format" argument.
21232 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
21235 createDebug.formatters = {};
21237 * Selects a color for a debug namespace
21238 * @param {String} namespace The namespace string for the for the debug instance to be colored
21239 * @return {Number|String} An ANSI color code for the given namespace
21243 function selectColor(namespace) {
21246 for (var i = 0; i < namespace.length; i++) {
21247 hash = (hash << 5) - hash + namespace.charCodeAt(i);
21248 hash |= 0; // Convert to 32bit integer
21251 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
21254 createDebug.selectColor = selectColor;
21256 * Create a debugger with the given `namespace`.
21258 * @param {String} namespace
21259 * @return {Function}
21263 function createDebug(namespace) {
21268 if (!debug.enabled) {
21272 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
21273 args[_key] = arguments[_key];
21276 var self = debug; // Set `diff` timestamp
21278 var curr = Number(new Date());
21279 var ms = curr - (prevTime || curr);
21281 self.prev = prevTime;
21284 args[0] = createDebug.coerce(args[0]);
21286 if (typeof args[0] !== 'string') {
21287 // Anything else let's inspect with %O
21288 args.unshift('%O');
21289 } // Apply any `formatters` transformations
21293 args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
21294 // If we encounter an escaped % then don't increase the array index
21295 if (match === '%%') {
21300 var formatter = createDebug.formatters[format];
21302 if (typeof formatter === 'function') {
21303 var val = args[index];
21304 match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
21306 args.splice(index, 1);
21311 }); // Apply env-specific formatting (colors, etc.)
21313 createDebug.formatArgs.call(self, args);
21314 var logFn = self.log || createDebug.log;
21315 logFn.apply(self, args);
21318 debug.namespace = namespace;
21319 debug.enabled = createDebug.enabled(namespace);
21320 debug.useColors = createDebug.useColors();
21321 debug.color = selectColor(namespace);
21322 debug.destroy = destroy;
21323 debug.extend = extend; // Debug.formatArgs = formatArgs;
21324 // debug.rawLog = rawLog;
21325 // env-specific initialization logic for debug instances
21327 if (typeof createDebug.init === 'function') {
21328 createDebug.init(debug);
21331 createDebug.instances.push(debug);
21335 function destroy() {
21336 var index = createDebug.instances.indexOf(this);
21338 if (index !== -1) {
21339 createDebug.instances.splice(index, 1);
21346 function extend(namespace, delimiter) {
21347 return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
21350 * Enables a debug mode by namespaces. This can include modes
21351 * separated by a colon and wildcards.
21353 * @param {String} namespaces
21358 function enable(namespaces) {
21359 createDebug.save(namespaces);
21360 createDebug.names = [];
21361 createDebug.skips = [];
21363 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
21364 var len = split.length;
21366 for (i = 0; i < len; i++) {
21368 // ignore empty strings
21372 namespaces = split[i].replace(/\*/g, '.*?');
21374 if (namespaces[0] === '-') {
21375 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
21377 createDebug.names.push(new RegExp('^' + namespaces + '$'));
21381 for (i = 0; i < createDebug.instances.length; i++) {
21382 var instance = createDebug.instances[i];
21383 instance.enabled = createDebug.enabled(instance.namespace);
21387 * Disable debug output.
21393 function disable() {
21394 createDebug.enable('');
21397 * Returns true if the given mode name is enabled, false otherwise.
21399 * @param {String} name
21400 * @return {Boolean}
21405 function enabled(name) {
21406 if (name[name.length - 1] === '*') {
21413 for (i = 0, len = createDebug.skips.length; i < len; i++) {
21414 if (createDebug.skips[i].test(name)) {
21419 for (i = 0, len = createDebug.names.length; i < len; i++) {
21420 if (createDebug.names[i].test(name)) {
21430 * @param {Mixed} val
21436 function coerce(val) {
21437 if (val instanceof Error) {
21438 return val.stack || val.message;
21444 createDebug.enable(createDebug.load());
21445 return createDebug;
21448 module.exports = setup;
21454 /***/ (function(module, exports) {
21465 var y = d * 365.25;
21468 * Parse or format the given `val`.
21472 * - `long` verbose formatting [false]
21474 * @param {String|Number} val
21475 * @param {Object} [options]
21476 * @throws {Error} throw an error if val is not a non-empty string or a number
21477 * @return {String|Number}
21481 module.exports = function(val, options) {
21482 options = options || {};
21483 var type = typeof val;
21484 if (type === 'string' && val.length > 0) {
21486 } else if (type === 'number' && isFinite(val)) {
21487 return options.long ? fmtLong(val) : fmtShort(val);
21490 'val is not a non-empty string or a valid number. val=' +
21491 JSON.stringify(val)
21496 * Parse the given `str` and return milliseconds.
21498 * @param {String} str
21503 function parse(str) {
21505 if (str.length > 100) {
21508 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(
21514 var n = parseFloat(match[1]);
21515 var type = (match[2] || 'ms').toLowerCase();
21549 case 'milliseconds':
21550 case 'millisecond':
21561 * Short format for `ms`.
21563 * @param {Number} ms
21568 function fmtShort(ms) {
21569 var msAbs = Math.abs(ms);
21571 return Math.round(ms / d) + 'd';
21574 return Math.round(ms / h) + 'h';
21577 return Math.round(ms / m) + 'm';
21580 return Math.round(ms / s) + 's';
21586 * Long format for `ms`.
21588 * @param {Number} ms
21593 function fmtLong(ms) {
21594 var msAbs = Math.abs(ms);
21596 return plural(ms, msAbs, d, 'day');
21599 return plural(ms, msAbs, h, 'hour');
21602 return plural(ms, msAbs, m, 'minute');
21605 return plural(ms, msAbs, s, 'second');
21611 * Pluralization helper.
21614 function plural(ms, msAbs, n, name) {
21615 var isPlural = msAbs >= n * 1.5;
21616 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
21622 /***/ (function(module, exports, __webpack_require__) {
21628 * Module dependencies.
21630 var tty = __webpack_require__(131);
21632 var util = __webpack_require__(3);
21634 * This is the Node.js implementation of `debug()`.
21638 exports.init = init;
21640 exports.formatArgs = formatArgs;
21641 exports.save = save;
21642 exports.load = load;
21643 exports.useColors = useColors;
21648 exports.colors = [6, 2, 3, 4, 5, 1];
21651 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
21652 // eslint-disable-next-line import/no-extraneous-dependencies
21653 var supportsColor = __webpack_require__(132);
21655 if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
21656 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];
21658 } catch (error) {} // Swallow - we only care if `supports-color` is available; it doesn't have to be.
21661 * Build up the default `inspectOpts` object from the environment variables.
21663 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
21667 exports.inspectOpts = Object.keys(process.env).filter(function (key) {
21668 return /^debug_/i.test(key);
21669 }).reduce(function (obj, key) {
21671 var prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, function (_, k) {
21672 return k.toUpperCase();
21673 }); // Coerce string value into JS value
21675 var val = process.env[key];
21677 if (/^(yes|on|true|enabled)$/i.test(val)) {
21679 } else if (/^(no|off|false|disabled)$/i.test(val)) {
21681 } else if (val === 'null') {
21691 * Is stdout a TTY? Colored output is enabled when `true`.
21694 function useColors() {
21695 return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd);
21698 * Adds ANSI color escape codes if enabled.
21704 function formatArgs(args) {
21705 var name = this.namespace,
21706 useColors = this.useColors;
21709 var c = this.color;
21710 var colorCode = "\x1B[3" + (c < 8 ? c : '8;5;' + c);
21711 var prefix = " ".concat(colorCode, ";1m").concat(name, " \x1B[0m");
21712 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
21713 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + "\x1B[0m");
21715 args[0] = getDate() + name + ' ' + args[0];
21719 function getDate() {
21720 if (exports.inspectOpts.hideDate) {
21724 return new Date().toISOString() + ' ';
21727 * Invokes `util.format()` with the specified arguments and writes to stderr.
21732 return process.stderr.write(util.format.apply(util, arguments) + '\n');
21735 * Save `namespaces`.
21737 * @param {String} namespaces
21742 function save(namespaces) {
21744 process.env.DEBUG = namespaces;
21746 // If you set a process.env field to null or undefined, it gets cast to the
21747 // string 'null' or 'undefined'. Just delete instead.
21748 delete process.env.DEBUG;
21752 * Load `namespaces`.
21754 * @return {String} returns the previously persisted debug modes
21760 return process.env.DEBUG;
21763 * Init logic for `debug` instances.
21765 * Create a new `inspectOpts` object in case `useColors` is set
21766 * differently for a particular `debug` instance.
21770 function init(debug) {
21771 debug.inspectOpts = {};
21772 var keys = Object.keys(exports.inspectOpts);
21774 for (var i = 0; i < keys.length; i++) {
21775 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
21779 module.exports = __webpack_require__(138)(exports);
21780 var formatters = module.exports.formatters;
21782 * Map %o to `util.inspect()`, all on a single line.
21785 formatters.o = function (v) {
21786 this.inspectOpts.colors = this.useColors;
21787 return util.inspect(v, this.inspectOpts).replace(/\s*\n\s*/g, ' ');
21790 * Map %O to `util.inspect()`, allowing multiple lines if needed.
21794 formatters.O = function (v) {
21795 this.inspectOpts.colors = this.useColors;
21796 return util.inspect(v, this.inspectOpts);
21803 /***/ (function(module, exports) {
21805 module.exports = require("zlib");