"use strict";
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

require("core-js/modules/es.array.slice.js");

require("core-js/modules/es.function.name.js");

require("core-js/modules/es.array.from.js");

require("core-js/modules/es.string.iterator.js");

require("core-js/modules/es.symbol.js");

require("core-js/modules/es.symbol.description.js");

require("core-js/modules/es.symbol.iterator.js");

require("core-js/modules/es.array.iterator.js");

require("core-js/modules/web.dom-collections.iterator.js");

require("regenerator-runtime/runtime.js");

require("core-js/modules/es.object.to-string.js");

require("core-js/modules/es.regexp.to-string.js");

require("core-js/modules/es.promise.js");

require("core-js/modules/es.number.constructor.js");

require("core-js/modules/es.regexp.exec.js");

require("core-js/modules/es.string.split.js");

require("core-js/modules/es.math.trunc.js");

require("core-js/modules/web.dom-collections.for-each.js");

require("core-js/modules/es.array.sort.js");

require("core-js/modules/es.array.concat.js");

require("core-js/modules/es.string.replace.js");

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.startServer = startServer;

var vscode_languageserver_1 = require("vscode-languageserver");

var runner_1 = require("./utils/runner");

var validation_1 = require("./utils/validation");

var vscode_json_languageservice_1 = require("vscode-json-languageservice");

var languageModelCache_1 = require("./languageModelCache");

var vscode_uri_1 = require("vscode-uri");

var l10n = require("@vscode/l10n");

var SchemaAssociationNotification;

(function (SchemaAssociationNotification) {
  SchemaAssociationNotification.type = new vscode_languageserver_1.NotificationType('json/schemaAssociations');
})(SchemaAssociationNotification || (SchemaAssociationNotification = {}));

var VSCodeContentRequest;

(function (VSCodeContentRequest) {
  VSCodeContentRequest.type = new vscode_languageserver_1.RequestType('vscode/content');
})(VSCodeContentRequest || (VSCodeContentRequest = {}));

var SchemaContentChangeNotification;

(function (SchemaContentChangeNotification) {
  SchemaContentChangeNotification.type = new vscode_languageserver_1.NotificationType('json/schemaContent');
})(SchemaContentChangeNotification || (SchemaContentChangeNotification = {}));

var ForceValidateRequest;

(function (ForceValidateRequest) {
  ForceValidateRequest.type = new vscode_languageserver_1.RequestType('json/validate');
})(ForceValidateRequest || (ForceValidateRequest = {}));

var LanguageStatusRequest;

(function (LanguageStatusRequest) {
  LanguageStatusRequest.type = new vscode_languageserver_1.RequestType('json/languageStatus');
})(LanguageStatusRequest || (LanguageStatusRequest = {}));

var DocumentSortingRequest;

(function (DocumentSortingRequest) {
  DocumentSortingRequest.type = new vscode_languageserver_1.RequestType('json/sort');
})(DocumentSortingRequest || (DocumentSortingRequest = {}));

var workspaceContext = {
  resolveRelativePath: function resolveRelativePath(relativePath, resource) {
    var base = resource.substring(0, resource.lastIndexOf('/') + 1);
    return vscode_uri_1.Utils.resolvePath(vscode_uri_1.URI.parse(base), relativePath).toString();
  }
};

function startServer(connection, runtime) {
  function getSchemaRequestService() {
    var handledSchemas = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['https', 'http', 'file'];
    var builtInHandlers = {};

    var _iterator = _createForOfIteratorHelper(handledSchemas),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var protocol = _step.value;

        if (protocol === 'file') {
          builtInHandlers[protocol] = runtime.file;
        } else if (protocol === 'http' || protocol === 'https') {
          builtInHandlers[protocol] = runtime.http;
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    return function (uri) {
      var protocol = uri.substr(0, uri.indexOf(':'));
      var builtInHandler = builtInHandlers[protocol];

      if (builtInHandler) {
        return builtInHandler.getContent(uri);
      }

      return connection.sendRequest(VSCodeContentRequest.type, uri).then(function (responseText) {
        return responseText;
      }, function (error) {
        return Promise.reject(error.message);
      });
    };
  } // create the JSON language service


  var languageService = (0, vscode_json_languageservice_1.getLanguageService)({
    workspaceContext: workspaceContext,
    contributions: [],
    clientCapabilities: vscode_json_languageservice_1.ClientCapabilities.LATEST
  }); // Create a text document manager.

  var documents = new vscode_languageserver_1.TextDocuments(vscode_json_languageservice_1.TextDocument); // Make the text document manager listen on the connection
  // for open, change and close text document events

  documents.listen(connection);
  var clientSnippetSupport = false;
  var dynamicFormatterRegistration = false;
  var hierarchicalDocumentSymbolSupport = false;
  var foldingRangeLimitDefault = Number.MAX_VALUE;
  var resultLimit = Number.MAX_VALUE;
  var jsonFoldingRangeLimit = Number.MAX_VALUE;
  var jsoncFoldingRangeLimit = Number.MAX_VALUE;
  var jsonColorDecoratorLimit = Number.MAX_VALUE;
  var jsoncColorDecoratorLimit = Number.MAX_VALUE;
  var formatterMaxNumberOfEdits = Number.MAX_VALUE;
  var diagnosticsSupport; // After the server has started the client sends an initialize request. The server receives
  // in the passed params the rootPath of the workspace plus the client capabilities.

  connection.onInitialize(function (params) {
    var _initializationOption, _initializationOption2;

    var initializationOptions = params.initializationOptions || {};
    var handledProtocols = initializationOptions === null || initializationOptions === void 0 ? void 0 : initializationOptions.handledSchemaProtocols;
    languageService = (0, vscode_json_languageservice_1.getLanguageService)({
      schemaRequestService: getSchemaRequestService(handledProtocols),
      workspaceContext: workspaceContext,
      contributions: [],
      clientCapabilities: params.capabilities
    });

    function getClientCapability(name, def) {
      var keys = name.split('.');
      var c = params.capabilities;

      for (var i = 0; c && i < keys.length; i++) {
        if (!c.hasOwnProperty(keys[i])) {
          return def;
        }

        c = c[keys[i]];
      }

      return c;
    }

    clientSnippetSupport = getClientCapability('textDocument.completion.completionItem.snippetSupport', false);
    dynamicFormatterRegistration = getClientCapability('textDocument.rangeFormatting.dynamicRegistration', false) && typeof initializationOptions.provideFormatter !== 'boolean';
    foldingRangeLimitDefault = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE);
    hierarchicalDocumentSymbolSupport = getClientCapability('textDocument.documentSymbol.hierarchicalDocumentSymbolSupport', false);
    formatterMaxNumberOfEdits = ((_initializationOption = initializationOptions.customCapabilities) === null || _initializationOption === void 0 ? void 0 : (_initializationOption2 = _initializationOption.rangeFormatting) === null || _initializationOption2 === void 0 ? void 0 : _initializationOption2.editLimit) || Number.MAX_VALUE;
    var supportsDiagnosticPull = getClientCapability('textDocument.diagnostic', undefined);

    if (supportsDiagnosticPull === undefined) {
      diagnosticsSupport = (0, validation_1.registerDiagnosticsPushSupport)(documents, connection, runtime, validateTextDocument);
    } else {
      diagnosticsSupport = (0, validation_1.registerDiagnosticsPullSupport)(documents, connection, runtime, validateTextDocument);
    }

    var capabilities = {
      textDocumentSync: vscode_languageserver_1.TextDocumentSyncKind.Incremental,
      completionProvider: clientSnippetSupport ? {
        resolveProvider: false,
        // turn off resolving as the current language service doesn't do anything on resolve. Also fixes #91747
        triggerCharacters: ['"', ':']
      } : undefined,
      hoverProvider: true,
      documentSymbolProvider: true,
      documentRangeFormattingProvider: initializationOptions.provideFormatter === true,
      documentFormattingProvider: initializationOptions.provideFormatter === true,
      colorProvider: {},
      foldingRangeProvider: true,
      selectionRangeProvider: true,
      documentLinkProvider: {},
      diagnosticProvider: {
        documentSelector: null,
        interFileDependencies: false,
        workspaceDiagnostics: false
      },
      codeActionProvider: true
    };
    return {
      capabilities: capabilities
    };
  });
  var jsonConfigurationSettings = undefined;
  var schemaAssociations = undefined;
  var formatterRegistrations = null;
  var validateEnabled = true;
  var keepLinesEnabled = false; // The settings have changed. Is sent on server activation as well.

  connection.onDidChangeConfiguration(function (change) {
    var _runtime$configureHtt, _settings$http, _settings$http2, _settings$json, _settings$json2, _settings$json2$valid, _settings$json3, _settings$json3$keepL, _settings$json4, _settings$json5, _settings$json6, _settings$json7, _settings$json8;

    var settings = change.settings;
    (_runtime$configureHtt = runtime.configureHttpRequests) === null || _runtime$configureHtt === void 0 ? void 0 : _runtime$configureHtt.call(runtime, settings === null || settings === void 0 ? void 0 : (_settings$http = settings.http) === null || _settings$http === void 0 ? void 0 : _settings$http.proxy, !!((_settings$http2 = settings.http) !== null && _settings$http2 !== void 0 && _settings$http2.proxyStrictSSL));
    jsonConfigurationSettings = (_settings$json = settings.json) === null || _settings$json === void 0 ? void 0 : _settings$json.schemas;
    validateEnabled = !!((_settings$json2 = settings.json) !== null && _settings$json2 !== void 0 && (_settings$json2$valid = _settings$json2.validate) !== null && _settings$json2$valid !== void 0 && _settings$json2$valid.enable);
    keepLinesEnabled = ((_settings$json3 = settings.json) === null || _settings$json3 === void 0 ? void 0 : (_settings$json3$keepL = _settings$json3.keepLines) === null || _settings$json3$keepL === void 0 ? void 0 : _settings$json3$keepL.enable) || false;
    updateConfiguration();

    var sanitizeLimitSetting = function sanitizeLimitSetting(settingValue) {
      return Math.trunc(Math.max(settingValue, 0));
    };

    resultLimit = sanitizeLimitSetting(((_settings$json4 = settings.json) === null || _settings$json4 === void 0 ? void 0 : _settings$json4.resultLimit) || Number.MAX_VALUE);
    jsonFoldingRangeLimit = sanitizeLimitSetting(((_settings$json5 = settings.json) === null || _settings$json5 === void 0 ? void 0 : _settings$json5.jsonFoldingLimit) || foldingRangeLimitDefault);
    jsoncFoldingRangeLimit = sanitizeLimitSetting(((_settings$json6 = settings.json) === null || _settings$json6 === void 0 ? void 0 : _settings$json6.jsoncFoldingLimit) || foldingRangeLimitDefault);
    jsonColorDecoratorLimit = sanitizeLimitSetting(((_settings$json7 = settings.json) === null || _settings$json7 === void 0 ? void 0 : _settings$json7.jsonColorDecoratorLimit) || Number.MAX_VALUE);
    jsoncColorDecoratorLimit = sanitizeLimitSetting(((_settings$json8 = settings.json) === null || _settings$json8 === void 0 ? void 0 : _settings$json8.jsoncColorDecoratorLimit) || Number.MAX_VALUE); // dynamically enable & disable the formatter

    if (dynamicFormatterRegistration) {
      var _settings$json9, _settings$json9$forma;

      var enableFormatter = (_settings$json9 = settings.json) === null || _settings$json9 === void 0 ? void 0 : (_settings$json9$forma = _settings$json9.format) === null || _settings$json9$forma === void 0 ? void 0 : _settings$json9$forma.enable;

      if (enableFormatter) {
        if (!formatterRegistrations) {
          var documentSelector = [{
            language: 'json'
          }, {
            language: 'jsonc'
          }];
          formatterRegistrations = [connection.client.register(vscode_languageserver_1.DocumentRangeFormattingRequest.type, {
            documentSelector: documentSelector
          }), connection.client.register(vscode_languageserver_1.DocumentFormattingRequest.type, {
            documentSelector: documentSelector
          })];
        }
      } else if (formatterRegistrations) {
        formatterRegistrations.forEach(function (p) {
          return p.then(function (r) {
            return r.dispose();
          });
        });
        formatterRegistrations = null;
      }
    }
  }); // The jsonValidation extension configuration has changed

  connection.onNotification(SchemaAssociationNotification.type, function (associations) {
    schemaAssociations = associations;
    updateConfiguration();
  }); // A schema has changed

  connection.onNotification(SchemaContentChangeNotification.type, function (uriOrUris) {
    var needsRevalidation = false;

    if (Array.isArray(uriOrUris)) {
      var _iterator2 = _createForOfIteratorHelper(uriOrUris),
          _step2;

      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var uri = _step2.value;

          if (languageService.resetSchema(uri)) {
            needsRevalidation = true;
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
    } else {
      needsRevalidation = languageService.resetSchema(uriOrUris);
    }

    if (needsRevalidation) {
      var _diagnosticsSupport;

      (_diagnosticsSupport = diagnosticsSupport) === null || _diagnosticsSupport === void 0 ? void 0 : _diagnosticsSupport.requestRefresh();
    }
  }); // Retry schema validation on all open documents

  connection.onRequest(ForceValidateRequest.type, /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(uri) {
      var document;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              document = documents.get(uri);

              if (!document) {
                _context.next = 6;
                break;
              }

              updateConfiguration();
              _context.next = 5;
              return validateTextDocument(document);

            case 5:
              return _context.abrupt("return", _context.sent);

            case 6:
              return _context.abrupt("return", []);

            case 7:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function (_x) {
      return _ref.apply(this, arguments);
    };
  }());
  connection.onRequest(LanguageStatusRequest.type, /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(uri) {
      var document, jsonDocument;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              document = documents.get(uri);

              if (!document) {
                _context2.next = 6;
                break;
              }

              jsonDocument = getJSONDocument(document);
              return _context2.abrupt("return", languageService.getLanguageStatus(document, jsonDocument));

            case 6:
              return _context2.abrupt("return", {
                schemas: []
              });

            case 7:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));

    return function (_x2) {
      return _ref2.apply(this, arguments);
    };
  }());
  connection.onRequest(DocumentSortingRequest.type, /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(params) {
      var uri, options, document;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              uri = params.uri;
              options = params.options;
              document = documents.get(uri);

              if (!document) {
                _context3.next = 5;
                break;
              }

              return _context3.abrupt("return", languageService.sort(document, options));

            case 5:
              return _context3.abrupt("return", []);

            case 6:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));

    return function (_x3) {
      return _ref3.apply(this, arguments);
    };
  }());

  function updateConfiguration() {
    var _diagnosticsSupport2;

    var languageSettings = {
      validate: validateEnabled,
      allowComments: true,
      schemas: new Array()
    };

    if (schemaAssociations) {
      if (Array.isArray(schemaAssociations)) {
        Array.prototype.push.apply(languageSettings.schemas, schemaAssociations);
      } else {
        var _loop = function _loop(pattern) {
          var association = schemaAssociations[pattern];

          if (Array.isArray(association)) {
            association.forEach(function (uri) {
              languageSettings.schemas.push({
                uri: uri,
                fileMatch: [pattern]
              });
            });
          }
        };

        for (var pattern in schemaAssociations) {
          _loop(pattern);
        }
      }
    }

    if (jsonConfigurationSettings) {
      jsonConfigurationSettings.forEach(function (schema, index) {
        var uri = schema.url;

        if (!uri && schema.schema) {
          uri = schema.schema.id || "vscode://schemas/custom/".concat(index);
        }

        if (uri) {
          languageSettings.schemas.push({
            uri: uri,
            fileMatch: schema.fileMatch,
            schema: schema.schema,
            folderUri: schema.folderUri
          });
        }
      });
    }

    languageService.configure(languageSettings);
    (_diagnosticsSupport2 = diagnosticsSupport) === null || _diagnosticsSupport2 === void 0 ? void 0 : _diagnosticsSupport2.requestRefresh();
  }

  function validateTextDocument(_x4) {
    return _validateTextDocument.apply(this, arguments);
  }

  function _validateTextDocument() {
    _validateTextDocument = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9(textDocument) {
      var jsonDocument, documentSettings;
      return regeneratorRuntime.wrap(function _callee9$(_context9) {
        while (1) {
          switch (_context9.prev = _context9.next) {
            case 0:
              if (!(textDocument.getText().length === 0)) {
                _context9.next = 2;
                break;
              }

              return _context9.abrupt("return", []);

            case 2:
              jsonDocument = getJSONDocument(textDocument);
              documentSettings = textDocument.languageId === 'jsonc' ? {
                comments: 'ignore',
                trailingCommas: 'warning'
              } : {
                comments: 'error',
                trailingCommas: 'error'
              };
              _context9.next = 6;
              return languageService.doValidation(textDocument, jsonDocument, documentSettings);

            case 6:
              return _context9.abrupt("return", _context9.sent);

            case 7:
            case "end":
              return _context9.stop();
          }
        }
      }, _callee9);
    }));
    return _validateTextDocument.apply(this, arguments);
  }

  connection.onDidChangeWatchedFiles(function (change) {
    // Monitored files have changed in VSCode
    var hasChanges = false;
    change.changes.forEach(function (c) {
      if (languageService.resetSchema(c.uri)) {
        hasChanges = true;
      }
    });

    if (hasChanges) {
      var _diagnosticsSupport3;

      (_diagnosticsSupport3 = diagnosticsSupport) === null || _diagnosticsSupport3 === void 0 ? void 0 : _diagnosticsSupport3.requestRefresh();
    }
  });
  var jsonDocuments = (0, languageModelCache_1.getLanguageModelCache)(10, 60, function (document) {
    return languageService.parseJSONDocument(document);
  });
  documents.onDidClose(function (e) {
    jsonDocuments.onDocumentRemoved(e.document);
  });
  connection.onShutdown(function () {
    jsonDocuments.dispose();
  });

  function getJSONDocument(document) {
    return jsonDocuments.get(document);
  }

  connection.onCompletion(function (textDocumentPosition, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
      var document, jsonDocument;
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              document = documents.get(textDocumentPosition.textDocument.uri);

              if (!document) {
                _context4.next = 4;
                break;
              }

              jsonDocument = getJSONDocument(document);
              return _context4.abrupt("return", languageService.doComplete(document, textDocumentPosition.position, jsonDocument));

            case 4:
              return _context4.abrupt("return", null);

            case 5:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4);
    })), null, "Error while computing completions for ".concat(textDocumentPosition.textDocument.uri), token);
  });
  connection.onHover(function (textDocumentPositionParams, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() {
      var document, jsonDocument;
      return regeneratorRuntime.wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              document = documents.get(textDocumentPositionParams.textDocument.uri);

              if (!document) {
                _context5.next = 4;
                break;
              }

              jsonDocument = getJSONDocument(document);
              return _context5.abrupt("return", languageService.doHover(document, textDocumentPositionParams.position, jsonDocument));

            case 4:
              return _context5.abrupt("return", null);

            case 5:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5);
    })), null, "Error while computing hover for ".concat(textDocumentPositionParams.textDocument.uri), token);
  });
  connection.onDocumentSymbol(function (documentSymbolParams, token) {
    return (0, runner_1.runSafe)(runtime, function () {
      var document = documents.get(documentSymbolParams.textDocument.uri);

      if (document) {
        var jsonDocument = getJSONDocument(document);

        if (hierarchicalDocumentSymbolSupport) {
          return languageService.findDocumentSymbols2(document, jsonDocument, {
            resultLimit: resultLimit
          });
        } else {
          return languageService.findDocumentSymbols(document, jsonDocument, {
            resultLimit: resultLimit
          });
        }
      }

      return [];
    }, [], "Error while computing document symbols for ".concat(documentSymbolParams.textDocument.uri), token);
  });
  connection.onCodeAction(function (codeActionParams, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6() {
      var document, sortCodeAction;
      return regeneratorRuntime.wrap(function _callee6$(_context6) {
        while (1) {
          switch (_context6.prev = _context6.next) {
            case 0:
              document = documents.get(codeActionParams.textDocument.uri);

              if (!document) {
                _context6.next = 5;
                break;
              }

              sortCodeAction = vscode_languageserver_1.CodeAction.create('Sort JSON', vscode_languageserver_1.CodeActionKind.Source.concat('.sort', '.json'));
              sortCodeAction.command = {
                command: 'json.sort',
                title: l10n.t('Sort JSON')
              };
              return _context6.abrupt("return", [sortCodeAction]);

            case 5:
              return _context6.abrupt("return", []);

            case 6:
            case "end":
              return _context6.stop();
          }
        }
      }, _callee6);
    })), [], "Error while computing code actions for ".concat(codeActionParams.textDocument.uri), token);
  });

  function onFormat(textDocument, range, options) {
    options.keepLines = keepLinesEnabled;
    var document = documents.get(textDocument.uri);

    if (document) {
      var edits = languageService.format(document, range !== null && range !== void 0 ? range : getFullRange(document), options);

      if (edits.length > formatterMaxNumberOfEdits) {
        var newText = vscode_json_languageservice_1.TextDocument.applyEdits(document, edits);
        return [vscode_languageserver_1.TextEdit.replace(getFullRange(document), newText)];
      }

      return edits;
    }

    return [];
  }

  connection.onDocumentRangeFormatting(function (formatParams, token) {
    return (0, runner_1.runSafe)(runtime, function () {
      return onFormat(formatParams.textDocument, formatParams.range, formatParams.options);
    }, [], "Error while formatting range for ".concat(formatParams.textDocument.uri), token);
  });
  connection.onDocumentFormatting(function (formatParams, token) {
    return (0, runner_1.runSafe)(runtime, function () {
      return onFormat(formatParams.textDocument, undefined, formatParams.options);
    }, [], "Error while formatting ".concat(formatParams.textDocument.uri), token);
  });
  connection.onDocumentColor(function (params, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7() {
      var document, jsonDocument, _resultLimit;

      return regeneratorRuntime.wrap(function _callee7$(_context7) {
        while (1) {
          switch (_context7.prev = _context7.next) {
            case 0:
              document = documents.get(params.textDocument.uri);

              if (!document) {
                _context7.next = 5;
                break;
              }

              jsonDocument = getJSONDocument(document);
              _resultLimit = document.languageId === 'jsonc' ? jsoncColorDecoratorLimit : jsonColorDecoratorLimit;
              return _context7.abrupt("return", languageService.findDocumentColors(document, jsonDocument, {
                resultLimit: _resultLimit
              }));

            case 5:
              return _context7.abrupt("return", []);

            case 6:
            case "end":
              return _context7.stop();
          }
        }
      }, _callee7);
    })), [], "Error while computing document colors for ".concat(params.textDocument.uri), token);
  });
  connection.onColorPresentation(function (params, token) {
    return (0, runner_1.runSafe)(runtime, function () {
      var document = documents.get(params.textDocument.uri);

      if (document) {
        var jsonDocument = getJSONDocument(document);
        return languageService.getColorPresentations(document, jsonDocument, params.color, params.range);
      }

      return [];
    }, [], "Error while computing color presentations for ".concat(params.textDocument.uri), token);
  });
  connection.onFoldingRanges(function (params, token) {
    return (0, runner_1.runSafe)(runtime, function () {
      var document = documents.get(params.textDocument.uri);

      if (document) {
        var rangeLimit = document.languageId === 'jsonc' ? jsoncFoldingRangeLimit : jsonFoldingRangeLimit;
        return languageService.getFoldingRanges(document, {
          rangeLimit: rangeLimit
        });
      }

      return null;
    }, null, "Error while computing folding ranges for ".concat(params.textDocument.uri), token);
  });
  connection.onSelectionRanges(function (params, token) {
    return (0, runner_1.runSafe)(runtime, function () {
      var document = documents.get(params.textDocument.uri);

      if (document) {
        var jsonDocument = getJSONDocument(document);
        return languageService.getSelectionRanges(document, params.positions, jsonDocument);
      }

      return [];
    }, [], "Error while computing selection ranges for ".concat(params.textDocument.uri), token);
  });
  connection.onDocumentLinks(function (params, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8() {
      var document, jsonDocument;
      return regeneratorRuntime.wrap(function _callee8$(_context8) {
        while (1) {
          switch (_context8.prev = _context8.next) {
            case 0:
              document = documents.get(params.textDocument.uri);

              if (!document) {
                _context8.next = 4;
                break;
              }

              jsonDocument = getJSONDocument(document);
              return _context8.abrupt("return", languageService.findLinks(document, jsonDocument));

            case 4:
              return _context8.abrupt("return", []);

            case 5:
            case "end":
              return _context8.stop();
          }
        }
      }, _callee8);
    })), [], "Error while computing links for ".concat(params.textDocument.uri), token);
  }); // Listen on the connection

  connection.listen();
}

function getFullRange(document) {
  return vscode_json_languageservice_1.Range.create(vscode_json_languageservice_1.Position.create(0, 0), document.positionAt(document.getText().length));
}