"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.symbol.js");

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

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

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("regenerator-runtime/runtime.js");

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

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

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

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

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

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

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

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

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

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

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

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; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

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); }); }; }

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

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

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

var vscode_css_languageservice_1 = require("vscode-css-languageservice");

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

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

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

var documentContext_1 = require("./utils/documentContext");

var customData_1 = require("./customData");

var requests_1 = require("./requests");

var CustomDataChangedNotification;

(function (CustomDataChangedNotification) {
  CustomDataChangedNotification.type = new vscode_languageserver_1.NotificationType('css/customDataChanged');
})(CustomDataChangedNotification || (CustomDataChangedNotification = {}));

function startServer(connection, runtime) {
  // Create a text document manager.
  var documents = new vscode_languageserver_1.TextDocuments(vscode_css_languageservice_1.TextDocument); // Make the text document manager listen on the connection
  // for open, change and close text document events

  documents.listen(connection);
  var stylesheets = (0, languageModelCache_1.getLanguageModelCache)(10, 60, function (document) {
    return getLanguageService(document).parseStylesheet(document);
  });
  documents.onDidClose(function (e) {
    stylesheets.onDocumentRemoved(e.document);
  });
  connection.onShutdown(function () {
    stylesheets.dispose();
  });
  var scopedSettingsSupport = false;
  var foldingRangeLimit = Number.MAX_VALUE;
  var workspaceFolders;
  var formatterMaxNumberOfEdits = Number.MAX_VALUE;
  var dataProvidersReady = Promise.resolve();
  var diagnosticsSupport;
  var languageServices = {};

  var notReady = function notReady() {
    return Promise.reject('Not Ready');
  };

  var requestService = {
    getContent: notReady,
    stat: notReady,
    readDirectory: notReady
  }; // 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 || {};
    workspaceFolders = params.workspaceFolders;

    if (!Array.isArray(workspaceFolders)) {
      workspaceFolders = [];

      if (params.rootPath) {
        workspaceFolders.push({
          name: '',
          uri: vscode_uri_1.URI.file(params.rootPath).toString(true)
        });
      }
    }

    requestService = (0, requests_1.getRequestService)((initializationOptions === null || initializationOptions === void 0 ? void 0 : initializationOptions.handledSchemas) || ['file'], connection, runtime);

    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;
    }

    var snippetSupport = !!getClientCapability('textDocument.completion.completionItem.snippetSupport', false);
    scopedSettingsSupport = !!getClientCapability('workspace.configuration', false);
    foldingRangeLimit = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE);
    formatterMaxNumberOfEdits = (initializationOptions === null || initializationOptions === void 0 ? void 0 : (_initializationOption = initializationOptions.customCapabilities) === null || _initializationOption === void 0 ? void 0 : (_initializationOption2 = _initializationOption.rangeFormatting) === null || _initializationOption2 === void 0 ? void 0 : _initializationOption2.editLimit) || Number.MAX_VALUE;
    languageServices.css = (0, vscode_css_languageservice_1.getCSSLanguageService)({
      fileSystemProvider: requestService,
      clientCapabilities: params.capabilities
    });
    languageServices.scss = (0, vscode_css_languageservice_1.getSCSSLanguageService)({
      fileSystemProvider: requestService,
      clientCapabilities: params.capabilities
    });
    languageServices.less = (0, vscode_css_languageservice_1.getLESSLanguageService)({
      fileSystemProvider: requestService,
      clientCapabilities: params.capabilities
    });
    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: snippetSupport ? {
        resolveProvider: false,
        triggerCharacters: ['/', '-', ':']
      } : undefined,
      hoverProvider: true,
      documentSymbolProvider: true,
      referencesProvider: true,
      definitionProvider: true,
      documentHighlightProvider: true,
      documentLinkProvider: {
        resolveProvider: false
      },
      codeActionProvider: true,
      renameProvider: true,
      colorProvider: {},
      foldingRangeProvider: true,
      selectionRangeProvider: true,
      diagnosticProvider: {
        documentSelector: null,
        interFileDependencies: false,
        workspaceDiagnostics: false
      },
      documentRangeFormattingProvider: (initializationOptions === null || initializationOptions === void 0 ? void 0 : initializationOptions.provideFormatter) === true,
      documentFormattingProvider: (initializationOptions === null || initializationOptions === void 0 ? void 0 : initializationOptions.provideFormatter) === true
    };
    return {
      capabilities: capabilities
    };
  });

  function getLanguageService(document) {
    var service = languageServices[document.languageId];

    if (!service) {
      connection.console.log('Document type is ' + document.languageId + ', using css instead.');
      service = languageServices['css'];
    }

    return service;
  }

  var documentSettings = {}; // remove document settings on close

  documents.onDidClose(function (e) {
    delete documentSettings[e.document.uri];
  });

  function getDocumentSettings(textDocument) {
    if (scopedSettingsSupport) {
      var promise = documentSettings[textDocument.uri];

      if (!promise) {
        var configRequestParam = {
          items: [{
            scopeUri: textDocument.uri,
            section: textDocument.languageId
          }]
        };
        promise = connection.sendRequest(vscode_languageserver_1.ConfigurationRequest.type, configRequestParam).then(function (s) {
          return s[0];
        });
        documentSettings[textDocument.uri] = promise;
      }

      return promise;
    }

    return Promise.resolve(undefined);
  } // The settings have changed. Is send on server activation as well.


  connection.onDidChangeConfiguration(function (change) {
    updateConfiguration(change.settings);
  });

  function updateConfiguration(settings) {
    var _diagnosticsSupport;

    for (var languageId in languageServices) {
      languageServices[languageId].configure(settings[languageId]);
    } // reset all document settings


    documentSettings = {};
    (_diagnosticsSupport = diagnosticsSupport) === null || _diagnosticsSupport === void 0 ? void 0 : _diagnosticsSupport.requestRefresh();
  }

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

  function _validateTextDocument() {
    _validateTextDocument = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee15(textDocument) {
      var settingsPromise, _yield$Promise$all5, _yield$Promise$all6, settings, stylesheet;

      return regeneratorRuntime.wrap(function _callee15$(_context15) {
        while (1) {
          switch (_context15.prev = _context15.next) {
            case 0:
              settingsPromise = getDocumentSettings(textDocument);
              _context15.next = 3;
              return Promise.all([settingsPromise, dataProvidersReady]);

            case 3:
              _yield$Promise$all5 = _context15.sent;
              _yield$Promise$all6 = _slicedToArray(_yield$Promise$all5, 1);
              settings = _yield$Promise$all6[0];
              stylesheet = stylesheets.get(textDocument);
              return _context15.abrupt("return", getLanguageService(textDocument).doValidation(textDocument, stylesheet, settings));

            case 8:
            case "end":
              return _context15.stop();
          }
        }
      }, _callee15);
    }));
    return _validateTextDocument.apply(this, arguments);
  }

  function updateDataProviders(dataPaths) {
    dataProvidersReady = (0, customData_1.fetchDataProviders)(dataPaths, requestService).then(function (customDataProviders) {
      for (var lang in languageServices) {
        languageServices[lang].setDataProviders(true, customDataProviders);
      }
    });
  }

  connection.onCompletion(function (textDocumentPosition, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var document, _yield$Promise$all, _yield$Promise$all2, settings, styleSheet, documentContext;

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

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

              _context.next = 4;
              return Promise.all([getDocumentSettings(document), dataProvidersReady]);

            case 4:
              _yield$Promise$all = _context.sent;
              _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 1);
              settings = _yield$Promise$all2[0];
              styleSheet = stylesheets.get(document);
              documentContext = (0, documentContext_1.getDocumentContext)(document.uri, workspaceFolders);
              return _context.abrupt("return", getLanguageService(document).doComplete2(document, textDocumentPosition.position, styleSheet, documentContext, settings === null || settings === void 0 ? void 0 : settings.completion));

            case 10:
              return _context.abrupt("return", null);

            case 11:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    })), null, "Error while computing completions for ".concat(textDocumentPosition.textDocument.uri), token);
  });
  connection.onHover(function (textDocumentPosition, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var document, _yield$Promise$all3, _yield$Promise$all4, settings, styleSheet;

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

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

              _context2.next = 4;
              return Promise.all([getDocumentSettings(document), dataProvidersReady]);

            case 4:
              _yield$Promise$all3 = _context2.sent;
              _yield$Promise$all4 = _slicedToArray(_yield$Promise$all3, 1);
              settings = _yield$Promise$all4[0];
              styleSheet = stylesheets.get(document);
              return _context2.abrupt("return", getLanguageService(document).doHover(document, textDocumentPosition.position, styleSheet, settings === null || settings === void 0 ? void 0 : settings.hover));

            case 9:
              return _context2.abrupt("return", null);

            case 10:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    })), null, "Error while computing hover for ".concat(textDocumentPosition.textDocument.uri), token);
  });
  connection.onDocumentSymbol(function (documentSymbolParams, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var document, stylesheet;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              document = documents.get(documentSymbolParams.textDocument.uri);

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

              _context3.next = 4;
              return dataProvidersReady;

            case 4:
              stylesheet = stylesheets.get(document);
              return _context3.abrupt("return", getLanguageService(document).findDocumentSymbols2(document, stylesheet));

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

            case 7:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    })), [], "Error while computing document symbols for ".concat(documentSymbolParams.textDocument.uri), token);
  });
  connection.onDefinition(function (documentDefinitionParams, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
      var document, stylesheet;
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              document = documents.get(documentDefinitionParams.textDocument.uri);

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

              _context4.next = 4;
              return dataProvidersReady;

            case 4:
              stylesheet = stylesheets.get(document);
              return _context4.abrupt("return", getLanguageService(document).findDefinition(document, documentDefinitionParams.position, stylesheet));

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

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

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

              _context5.next = 4;
              return dataProvidersReady;

            case 4:
              stylesheet = stylesheets.get(document);
              return _context5.abrupt("return", getLanguageService(document).findDocumentHighlights(document, documentHighlightParams.position, stylesheet));

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

            case 7:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5);
    })), [], "Error while computing document highlights for ".concat(documentHighlightParams.textDocument.uri), token);
  });
  connection.onDocumentLinks( /*#__PURE__*/function () {
    var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(documentLinkParams, token) {
      return regeneratorRuntime.wrap(function _callee7$(_context7) {
        while (1) {
          switch (_context7.prev = _context7.next) {
            case 0:
              return _context7.abrupt("return", (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6() {
                var document, documentContext, stylesheet;
                return regeneratorRuntime.wrap(function _callee6$(_context6) {
                  while (1) {
                    switch (_context6.prev = _context6.next) {
                      case 0:
                        document = documents.get(documentLinkParams.textDocument.uri);

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

                        _context6.next = 4;
                        return dataProvidersReady;

                      case 4:
                        documentContext = (0, documentContext_1.getDocumentContext)(document.uri, workspaceFolders);
                        stylesheet = stylesheets.get(document);
                        return _context6.abrupt("return", getLanguageService(document).findDocumentLinks2(document, stylesheet, documentContext));

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

                      case 8:
                      case "end":
                        return _context6.stop();
                    }
                  }
                }, _callee6);
              })), [], "Error while computing document links for ".concat(documentLinkParams.textDocument.uri), token));

            case 1:
            case "end":
              return _context7.stop();
          }
        }
      }, _callee7);
    }));

    return function (_x2, _x3) {
      return _ref6.apply(this, arguments);
    };
  }());
  connection.onReferences(function (referenceParams, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8() {
      var document, stylesheet;
      return regeneratorRuntime.wrap(function _callee8$(_context8) {
        while (1) {
          switch (_context8.prev = _context8.next) {
            case 0:
              document = documents.get(referenceParams.textDocument.uri);

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

              _context8.next = 4;
              return dataProvidersReady;

            case 4:
              stylesheet = stylesheets.get(document);
              return _context8.abrupt("return", getLanguageService(document).findReferences(document, referenceParams.position, stylesheet));

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

            case 7:
            case "end":
              return _context8.stop();
          }
        }
      }, _callee8);
    })), [], "Error while computing references for ".concat(referenceParams.textDocument.uri), token);
  });
  connection.onCodeAction(function (codeActionParams, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9() {
      var document, stylesheet;
      return regeneratorRuntime.wrap(function _callee9$(_context9) {
        while (1) {
          switch (_context9.prev = _context9.next) {
            case 0:
              document = documents.get(codeActionParams.textDocument.uri);

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

              _context9.next = 4;
              return dataProvidersReady;

            case 4:
              stylesheet = stylesheets.get(document);
              return _context9.abrupt("return", getLanguageService(document).doCodeActions(document, codeActionParams.range, codeActionParams.context, stylesheet));

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

            case 7:
            case "end":
              return _context9.stop();
          }
        }
      }, _callee9);
    })), [], "Error while computing code actions for ".concat(codeActionParams.textDocument.uri), token);
  });
  connection.onDocumentColor(function (params, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee10() {
      var document, stylesheet;
      return regeneratorRuntime.wrap(function _callee10$(_context10) {
        while (1) {
          switch (_context10.prev = _context10.next) {
            case 0:
              document = documents.get(params.textDocument.uri);

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

              _context10.next = 4;
              return dataProvidersReady;

            case 4:
              stylesheet = stylesheets.get(document);
              return _context10.abrupt("return", getLanguageService(document).findDocumentColors(document, stylesheet));

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

            case 7:
            case "end":
              return _context10.stop();
          }
        }
      }, _callee10);
    })), [], "Error while computing document colors for ".concat(params.textDocument.uri), token);
  });
  connection.onColorPresentation(function (params, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee11() {
      var document, stylesheet;
      return regeneratorRuntime.wrap(function _callee11$(_context11) {
        while (1) {
          switch (_context11.prev = _context11.next) {
            case 0:
              document = documents.get(params.textDocument.uri);

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

              _context11.next = 4;
              return dataProvidersReady;

            case 4:
              stylesheet = stylesheets.get(document);
              return _context11.abrupt("return", getLanguageService(document).getColorPresentations(document, stylesheet, params.color, params.range));

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

            case 7:
            case "end":
              return _context11.stop();
          }
        }
      }, _callee11);
    })), [], "Error while computing color presentations for ".concat(params.textDocument.uri), token);
  });
  connection.onRenameRequest(function (renameParameters, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee12() {
      var document, stylesheet;
      return regeneratorRuntime.wrap(function _callee12$(_context12) {
        while (1) {
          switch (_context12.prev = _context12.next) {
            case 0:
              document = documents.get(renameParameters.textDocument.uri);

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

              _context12.next = 4;
              return dataProvidersReady;

            case 4:
              stylesheet = stylesheets.get(document);
              return _context12.abrupt("return", getLanguageService(document).doRename(document, renameParameters.position, renameParameters.newName, stylesheet));

            case 6:
              return _context12.abrupt("return", null);

            case 7:
            case "end":
              return _context12.stop();
          }
        }
      }, _callee12);
    })), null, "Error while computing renames for ".concat(renameParameters.textDocument.uri), token);
  });
  connection.onFoldingRanges(function (params, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee13() {
      var document;
      return regeneratorRuntime.wrap(function _callee13$(_context13) {
        while (1) {
          switch (_context13.prev = _context13.next) {
            case 0:
              document = documents.get(params.textDocument.uri);

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

              _context13.next = 4;
              return dataProvidersReady;

            case 4:
              return _context13.abrupt("return", getLanguageService(document).getFoldingRanges(document, {
                rangeLimit: foldingRangeLimit
              }));

            case 5:
              return _context13.abrupt("return", null);

            case 6:
            case "end":
              return _context13.stop();
          }
        }
      }, _callee13);
    })), null, "Error while computing folding ranges for ".concat(params.textDocument.uri), token);
  });
  connection.onSelectionRanges(function (params, token) {
    return (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee14() {
      var document, positions, stylesheet;
      return regeneratorRuntime.wrap(function _callee14$(_context14) {
        while (1) {
          switch (_context14.prev = _context14.next) {
            case 0:
              document = documents.get(params.textDocument.uri);
              positions = params.positions;

              if (!document) {
                _context14.next = 7;
                break;
              }

              _context14.next = 5;
              return dataProvidersReady;

            case 5:
              stylesheet = stylesheets.get(document);
              return _context14.abrupt("return", getLanguageService(document).getSelectionRanges(document, positions, stylesheet));

            case 7:
              return _context14.abrupt("return", []);

            case 8:
            case "end":
              return _context14.stop();
          }
        }
      }, _callee14);
    })), [], "Error while computing selection ranges for ".concat(params.textDocument.uri), token);
  });

  function onFormat(_x4, _x5, _x6) {
    return _onFormat.apply(this, arguments);
  }

  function _onFormat() {
    _onFormat = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee16(textDocument, range, options) {
      var document, edits, newText;
      return regeneratorRuntime.wrap(function _callee16$(_context16) {
        while (1) {
          switch (_context16.prev = _context16.next) {
            case 0:
              document = documents.get(textDocument.uri);

              if (!document) {
                _context16.next = 7;
                break;
              }

              edits = getLanguageService(document).format(document, range !== null && range !== void 0 ? range : getFullRange(document), options);

              if (!(edits.length > formatterMaxNumberOfEdits)) {
                _context16.next = 6;
                break;
              }

              newText = vscode_css_languageservice_1.TextDocument.applyEdits(document, edits);
              return _context16.abrupt("return", [vscode_languageserver_1.TextEdit.replace(getFullRange(document), newText)]);

            case 6:
              return _context16.abrupt("return", edits);

            case 7:
              return _context16.abrupt("return", []);

            case 8:
            case "end":
              return _context16.stop();
          }
        }
      }, _callee16);
    }));
    return _onFormat.apply(this, arguments);
  }

  connection.onDocumentRangeFormatting(function (formatParams, token) {
    return (0, runner_1.runSafeAsync)(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.runSafeAsync)(runtime, function () {
      return onFormat(formatParams.textDocument, undefined, formatParams.options);
    }, [], "Error while formatting ".concat(formatParams.textDocument.uri), token);
  });
  connection.onNotification(CustomDataChangedNotification.type, updateDataProviders); // Listen on the connection

  connection.listen();
}

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