X-Git-Url: https://git.josue.xyz/?p=dotfiles%2F.git;a=blobdiff_plain;f=.config%2Fcoc%2Fextensions%2Fnode_modules%2Fcoc-tsserver%2Flib%2Findex.js;h=872689f313629f8556d5af62dc74c31ba2485fc6;hp=7235f7ff32a3b41fc48c2c33c80fb7d480f69f3b;hb=4d07c77cf4d78cab8639e13ddc3c22495e585b0b;hpb=b3950616b54221c40a7dab9099bda675007e5b6e diff --git a/.config/coc/extensions/node_modules/coc-tsserver/lib/index.js b/.config/coc/extensions/node_modules/coc-tsserver/lib/index.js index 7235f7ff..872689f3 100644 --- a/.config/coc/extensions/node_modules/coc-tsserver/lib/index.js +++ b/.config/coc/extensions/node_modules/coc-tsserver/lib/index.js @@ -90,15 +90,6 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -106,29 +97,28 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.activate = void 0; const coc_nvim_1 = __webpack_require__(1); const server_1 = __importDefault(__webpack_require__(2)); -const commands_1 = __webpack_require__(140); -const organizeImports_1 = __webpack_require__(114); -const plugins_1 = __webpack_require__(141); -function activate(context) { - return __awaiter(this, void 0, void 0, function* () { - let { subscriptions } = context; - const config = coc_nvim_1.workspace.getConfiguration().get('tsserver', {}); - if (!config.enable) - return; - const pluginManager = new plugins_1.PluginManager(); - const service = new server_1.default(pluginManager); +const commands_1 = __webpack_require__(141); +const organizeImports_1 = __webpack_require__(112); +const plugins_1 = __webpack_require__(142); +async function activate(context) { + let { subscriptions, logger } = context; + const config = coc_nvim_1.workspace.getConfiguration().get('tsserver', {}); + if (!config.enable) + return; + const pluginManager = new plugins_1.PluginManager(); + const service = new server_1.default(pluginManager); + function registCommand(cmd) { + let { id, execute } = cmd; + subscriptions.push(coc_nvim_1.commands.registerCommand(id, execute, cmd)); + } + registCommand(new commands_1.ConfigurePluginCommand(pluginManager)); + registCommand(new commands_1.AutoFixCommand(service)); + registCommand(new commands_1.ReloadProjectsCommand(service)); + registCommand(new commands_1.OpenTsServerLogCommand(service)); + registCommand(new commands_1.TypeScriptGoToProjectConfigCommand(service)); + registCommand(new organizeImports_1.OrganizeImportsCommand(service)); + service.start().then(() => { subscriptions.push(coc_nvim_1.services.regist(service)); - yield service.start(); - function registCommand(cmd) { - let { id, execute } = cmd; - subscriptions.push(coc_nvim_1.commands.registerCommand(id, execute, cmd)); - } - registCommand(new commands_1.AutoFixCommand(service.clientHost)); - registCommand(new commands_1.ReloadProjectsCommand(service.clientHost)); - registCommand(new commands_1.OpenTsServerLogCommand(service.clientHost)); - registCommand(new commands_1.TypeScriptGoToProjectConfigCommand(service.clientHost)); - registCommand(new organizeImports_1.OrganizeImportsCommand(service.clientHost.serviceClient)); - registCommand(new commands_1.ConfigurePluginCommand(pluginManager)); registCommand(coc_nvim_1.commands.register({ id: 'tsserver.restart', execute: () => { @@ -140,12 +130,14 @@ function activate(context) { }); } })); - return { - configurePlugin: (pluginId, configuration) => { - pluginManager.setConfiguration(pluginId, configuration); - } - }; + }, e => { + logger.error(`Error on service start:`, e); }); + return { + configurePlugin: (pluginId, configuration) => { + pluginManager.setConfiguration(pluginId, configuration); + } + }; } exports.activate = activate; @@ -162,15 +154,6 @@ module.exports = require("coc.nvim"); "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -178,7 +161,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); const coc_nvim_1 = __webpack_require__(1); const vscode_languageserver_protocol_1 = __webpack_require__(3); const typescriptServiceClientHost_1 = __importDefault(__webpack_require__(33)); -const languageDescription_1 = __webpack_require__(115); +const languageDescription_1 = __webpack_require__(140); class TsserverService { constructor(pluginManager) { this.pluginManager = pluginManager; @@ -198,20 +181,26 @@ class TsserverService { this.selector = this.descriptions.reduce((arr, c) => { return arr.concat(c.modeIds); }, []); - coc_nvim_1.workspace.onDidOpenTextDocument(doc => { - this.ensureConfigurationForDocument(doc); - }, null, this.disposables); } get config() { return coc_nvim_1.workspace.getConfiguration('tsserver'); } - ensureConfigurationForDocument(document) { - let uri = coc_nvim_1.Uri.parse(document.uri); - let language = this.clientHost.findLanguage(uri); - if (!language) - return; - language.fileConfigurationManager.ensureConfigurationForDocument(document).catch(_e => { - // noop + /** + * Get running client host. + */ + getClientHost() { + if (this.state == coc_nvim_1.ServiceStat.Running) + return Promise.resolve(this.clientHost); + this.start(); + return new Promise((resolve, reject) => { + let timer = setTimeout(() => { + reject(new Error(`Server not started after 5s`)); + }, 5000); + let disposable = this.onServiceReady(() => { + clearTimeout(timer); + disposable.dispose(); + resolve(this.clientHost); + }); }); } start() { @@ -230,7 +219,6 @@ class TsserverService { } }); this._onDidServiceReady.fire(void 0); - this.ensureConfiguration(); if (!started) { started = true; resolve(); @@ -238,33 +226,22 @@ class TsserverService { }); }); } - ensureConfiguration() { - if (!this.clientHost) - return; - for (let doc of coc_nvim_1.workspace.documents) { - this.ensureConfigurationForDocument(doc.textDocument); - } - } dispose() { coc_nvim_1.disposeAll(this.disposables); } - restart() { - return __awaiter(this, void 0, void 0, function* () { - if (!this.clientHost) - return; - let client = this.clientHost.serviceClient; - yield client.restartTsServer(); - }); + async restart() { + if (!this.clientHost) + return; + let client = this.clientHost.serviceClient; + await client.restartTsServer(); } - stop() { - return __awaiter(this, void 0, void 0, function* () { - if (!this.clientHost) - return; - this.clientHost.reset(); - let client = this.clientHost.serviceClient; - yield client.stop(); + async stop() { + if (!this.clientHost) return; - }); + this.clientHost.reset(); + let client = this.clientHost.serviceClient; + await client.stop(); + return; } } exports.default = TsserverService; @@ -5527,7 +5504,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -5543,9 +5520,13 @@ const coc_nvim_1 = __webpack_require__(1); const vscode_languageserver_protocol_1 = __webpack_require__(3); const languageProvider_1 = __importDefault(__webpack_require__(34)); const PConst = __importStar(__webpack_require__(39)); -const typescriptServiceClient_1 = __importDefault(__webpack_require__(117)); +const fileConfigurationManager_1 = __importDefault(__webpack_require__(113)); +const typescriptServiceClient_1 = __importDefault(__webpack_require__(114)); const typeConverters = __importStar(__webpack_require__(37)); -const typingsStatus_1 = __importStar(__webpack_require__(139)); +const typingsStatus_1 = __importStar(__webpack_require__(137)); +const arrays_1 = __webpack_require__(91); +const watchBuild_1 = __importDefault(__webpack_require__(138)); +const workspaceSymbols_1 = __importDefault(__webpack_require__(139)); // Style check diagnostics that can be reported as warnings const styleCheckDiagnostics = [ 6133, @@ -5557,7 +5538,6 @@ const styleCheckDiagnostics = [ ]; class TypeScriptServiceClientHost { constructor(descriptions, pluginManager) { - this.languages = []; this.languagePerId = new Map(); this.disposables = []; this.reportStyleCheckAsWarnings = true; @@ -5577,11 +5557,17 @@ class TypeScriptServiceClientHost { const packageFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/package.json'); packageFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables); packageFileWatcher.onDidChange(handleProjectChange, this, this.disposables); - this.client = new typescriptServiceClient_1.default(pluginManager); + const allModeIds = this.getAllModeIds(descriptions, pluginManager); + this.client = new typescriptServiceClient_1.default(pluginManager, allModeIds); this.disposables.push(this.client); this.client.onDiagnosticsReceived(({ kind, resource, diagnostics }) => { - this.diagnosticsReceived(kind, resource, diagnostics); + this.diagnosticsReceived(kind, resource, diagnostics).catch(e => { + console.error(e); + }); }, null, this.disposables); + // features + this.disposables.push(new watchBuild_1.default(this.client)); + this.disposables.push(coc_nvim_1.languages.registerWorkspaceSymbolProvider(new workspaceSymbols_1.default(this.client, allModeIds))); this.client.onConfigDiagnosticsReceived(diag => { let { body } = diag; if (body) { @@ -5609,12 +5595,39 @@ class TypeScriptServiceClientHost { }, null, this.disposables); this.typingsStatus = new typingsStatus_1.default(this.client); this.ataProgressReporter = new typingsStatus_1.AtaProgressReporter(this.client); + this.fileConfigurationManager = new fileConfigurationManager_1.default(this.client); for (const description of descriptions) { // tslint:disable-line - const manager = new languageProvider_1.default(this.client, description, this.typingsStatus); - this.languages.push(manager); - this.disposables.push(manager); + const manager = new languageProvider_1.default(this.client, this.fileConfigurationManager, description, this.typingsStatus); this.languagePerId.set(description.id, manager); } + const languageIds = new Set(); + for (const plugin of pluginManager.plugins) { + if (plugin.configNamespace && plugin.languages.length) { + this.registerExtensionLanguageProvider({ + id: plugin.configNamespace, + modeIds: Array.from(plugin.languages), + diagnosticSource: 'ts-plugin', + diagnosticLanguage: 1 /* TypeScript */, + diagnosticOwner: 'typescript', + isExternal: true + }); + } + else { + for (const language of plugin.languages) { + languageIds.add(language); + } + } + } + if (languageIds.size) { + this.registerExtensionLanguageProvider({ + id: 'typescript-plugins', + modeIds: Array.from(languageIds.values()), + diagnosticSource: 'ts-plugin', + diagnosticLanguage: 1 /* TypeScript */, + diagnosticOwner: 'typescript', + isExternal: true + }); + } this.client.ensureServiceStarted(); this.client.onTsServerStarted(() => { this.triggerAllDiagnostics(); @@ -5622,20 +5635,28 @@ class TypeScriptServiceClientHost { coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables); this.configurationChanged(); } + registerExtensionLanguageProvider(description) { + const manager = new languageProvider_1.default(this.client, this.fileConfigurationManager, description, this.typingsStatus); + this.languagePerId.set(description.id, manager); + } dispose() { coc_nvim_1.disposeAll(this.disposables); + for (let language of this.languagePerId.values()) { + language.dispose(); + } + this.languagePerId.clear(); + this.fileConfigurationManager.dispose(); this.typingsStatus.dispose(); this.ataProgressReporter.dispose(); } reset() { - for (let lang of this.languages) { - lang.fileConfigurationManager.reset(); - } + this.fileConfigurationManager.reset(); } get serviceClient() { return this.client; } reloadProjects() { + this.client.diagnosticsManager.reInitialize(); this.client.execute('reloadProjects', null, vscode_languageserver_protocol_1.CancellationToken.None); this.triggerAllDiagnostics(); } @@ -5647,24 +5668,32 @@ class TypeScriptServiceClientHost { const config = coc_nvim_1.workspace.getConfiguration('tsserver'); this.reportStyleCheckAsWarnings = config.get('reportStyleChecksAsWarnings', true); } - findLanguage(resource) { + async findLanguage(uri) { try { - return this.languages.find(language => language.handles(resource)); + let doc = await coc_nvim_1.workspace.loadFile(uri); + if (!doc) + return undefined; + let languages = Array.from(this.languagePerId.values()); + return languages.find(language => language.handles(uri, doc.textDocument)); } catch (_a) { - return null; + return undefined; } } - handles(uri) { - return this.findLanguage(coc_nvim_1.Uri.parse(uri)) != null; + async handles(doc) { + let languages = Array.from(this.languagePerId.values()); + let idx = languages.findIndex(language => language.handles(doc.uri, doc)); + if (idx != -1) + return true; + return this.client.bufferSyncSupport.handles(doc.uri); } triggerAllDiagnostics() { for (const language of this.languagePerId.values()) { language.triggerAllDiagnostics(); } } - diagnosticsReceived(kind, resource, diagnostics) { - const language = this.findLanguage(resource); + async diagnosticsReceived(kind, resource, diagnostics) { + const language = await this.findLanguage(resource.toString()); if (language) { language.diagnosticsReceived(kind, resource, this.createMarkerDatas(diagnostics)); } @@ -5718,6 +5747,13 @@ class TypeScriptServiceClientHost { isStyleCheckDiagnostic(code) { return code ? styleCheckDiagnostics.indexOf(code) !== -1 : false; } + getAllModeIds(descriptions, pluginManager) { + const allModeIds = arrays_1.flatten([ + ...descriptions.map(x => x.modeIds), + ...pluginManager.plugins.map(x => x.languages) + ]); + return allModeIds; + } } exports.default = TypeScriptServiceClientHost; @@ -5728,15 +5764,6 @@ exports.default = TypeScriptServiceClientHost; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -5745,53 +5772,49 @@ Object.defineProperty(exports, "__esModule", { value: true }); * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -const vscode_languageserver_protocol_1 = __webpack_require__(3); const coc_nvim_1 = __webpack_require__(1); +const path_1 = __importDefault(__webpack_require__(13)); +const vscode_languageserver_protocol_1 = __webpack_require__(3); const baseCodeLensProvider_1 = __webpack_require__(35); const completionItemProvider_1 = __importDefault(__webpack_require__(38)); const definitionProvider_1 = __importDefault(__webpack_require__(88)); const directiveCommentCompletions_1 = __importDefault(__webpack_require__(89)); const documentHighlight_1 = __importDefault(__webpack_require__(90)); const documentSymbol_1 = __importDefault(__webpack_require__(92)); -const fileConfigurationManager_1 = __importDefault(__webpack_require__(93)); -const folding_1 = __importDefault(__webpack_require__(94)); -const formatting_1 = __importDefault(__webpack_require__(95)); -const hover_1 = __importDefault(__webpack_require__(96)); -const implementationsCodeLens_1 = __importDefault(__webpack_require__(97)); +const folding_1 = __importDefault(__webpack_require__(93)); +const formatting_1 = __importDefault(__webpack_require__(94)); +const hover_1 = __importDefault(__webpack_require__(95)); +const implementationsCodeLens_1 = __importDefault(__webpack_require__(96)); +const importFix_1 = __importDefault(__webpack_require__(97)); +const moduleInstall_1 = __importDefault(__webpack_require__(99)); // import TagCompletionProvider from './features/tagCompletion' -const quickfix_1 = __importDefault(__webpack_require__(98)); -const importFix_1 = __importDefault(__webpack_require__(99)); -const refactor_1 = __importDefault(__webpack_require__(101)); -const references_1 = __importDefault(__webpack_require__(102)); -const referencesCodeLens_1 = __importDefault(__webpack_require__(103)); -const rename_1 = __importDefault(__webpack_require__(104)); -const signatureHelp_1 = __importDefault(__webpack_require__(105)); -const updatePathOnRename_1 = __importDefault(__webpack_require__(106)); -const watchBuild_1 = __importDefault(__webpack_require__(108)); -const workspaceSymbols_1 = __importDefault(__webpack_require__(109)); -const smartSelect_1 = __importDefault(__webpack_require__(110)); -const moduleInstall_1 = __importDefault(__webpack_require__(111)); +const quickfix_1 = __importDefault(__webpack_require__(103)); +const refactor_1 = __importDefault(__webpack_require__(104)); +const references_1 = __importDefault(__webpack_require__(105)); +const referencesCodeLens_1 = __importDefault(__webpack_require__(106)); +const rename_1 = __importDefault(__webpack_require__(107)); +const signatureHelp_1 = __importDefault(__webpack_require__(108)); +const smartSelect_1 = __importDefault(__webpack_require__(109)); +const updatePathOnRename_1 = __importDefault(__webpack_require__(110)); +const organizeImports_1 = __webpack_require__(112); const api_1 = __importDefault(__webpack_require__(40)); -const organizeImports_1 = __webpack_require__(114); const suggestionSetting = 'suggestionActions.enabled'; class LanguageProvider { - constructor(client, description, typingsStatus) { + constructor(client, fileConfigurationManager, description, typingsStatus) { this.client = client; + this.fileConfigurationManager = fileConfigurationManager; this.description = description; + this.typingsStatus = typingsStatus; this.disposables = []; - this.fileConfigurationManager = new fileConfigurationManager_1.default(client); coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables); this.configurationChanged(); let initialized = false; - client.onTsServerStarted(() => __awaiter(this, void 0, void 0, function* () { + client.onTsServerStarted(async () => { if (!initialized) { initialized = true; this.registerProviders(client, typingsStatus); } - else { - this.client.diagnosticsManager.reInitialize(); - } - })); + }); } configurationChanged() { const config = coc_nvim_1.workspace.getConfiguration(this.id, null); @@ -5800,64 +5823,59 @@ class LanguageProvider { dispose() { coc_nvim_1.disposeAll(this.disposables); } + _register(disposable) { + this.disposables.push(disposable); + } registerProviders(client, typingsStatus) { let languageIds = this.description.modeIds; - this.disposables.push(coc_nvim_1.languages.registerCompletionItemProvider(`tsserver-${this.description.id}`, 'TSC', languageIds, new completionItemProvider_1.default(client, typingsStatus, this.fileConfigurationManager, this.description.id), completionItemProvider_1.default.triggerCharacters)); + let clientId = `tsserver-${this.description.id}`; + this._register(coc_nvim_1.languages.registerCompletionItemProvider(clientId, 'TSC', languageIds, new completionItemProvider_1.default(client, typingsStatus, this.fileConfigurationManager, this.description.id), completionItemProvider_1.default.triggerCharacters)); if (this.client.apiVersion.gte(api_1.default.v230)) { - this.disposables.push(coc_nvim_1.languages.registerCompletionItemProvider(`${this.description.id}-directive`, 'TSC', languageIds, new directiveCommentCompletions_1.default(client), ['@'])); + this._register(coc_nvim_1.languages.registerCompletionItemProvider(`${this.description.id}-directive`, 'TSC', languageIds, new directiveCommentCompletions_1.default(client), ['@'])); } let definitionProvider = new definitionProvider_1.default(client); - this.disposables.push(coc_nvim_1.languages.registerDefinitionProvider(languageIds, definitionProvider)); - this.disposables.push(coc_nvim_1.languages.registerTypeDefinitionProvider(languageIds, definitionProvider)); - this.disposables.push(coc_nvim_1.languages.registerImplementationProvider(languageIds, definitionProvider)); - this.disposables.push(coc_nvim_1.languages.registerReferencesProvider(languageIds, new references_1.default(client))); - this.disposables.push(coc_nvim_1.languages.registerHoverProvider(languageIds, new hover_1.default(client))); - this.disposables.push(coc_nvim_1.languages.registerDocumentHighlightProvider(languageIds, new documentHighlight_1.default(this.client))); - this.disposables.push(coc_nvim_1.languages.registerSignatureHelpProvider(languageIds, new signatureHelp_1.default(client), ['(', ',', '<', ')'])); - this.disposables.push(coc_nvim_1.languages.registerDocumentSymbolProvider(languageIds, new documentSymbol_1.default(client))); - this.disposables.push(coc_nvim_1.languages.registerWorkspaceSymbolProvider(languageIds, new workspaceSymbols_1.default(client, languageIds))); - this.disposables.push(coc_nvim_1.languages.registerRenameProvider(languageIds, new rename_1.default(client))); + this._register(coc_nvim_1.languages.registerDefinitionProvider(languageIds, definitionProvider)); + this._register(coc_nvim_1.languages.registerTypeDefinitionProvider(languageIds, definitionProvider)); + this._register(coc_nvim_1.languages.registerImplementationProvider(languageIds, definitionProvider)); + this._register(coc_nvim_1.languages.registerReferencesProvider(languageIds, new references_1.default(client))); + this._register(coc_nvim_1.languages.registerHoverProvider(languageIds, new hover_1.default(client))); + this._register(coc_nvim_1.languages.registerDocumentHighlightProvider(languageIds, new documentHighlight_1.default(this.client))); + this._register(coc_nvim_1.languages.registerSignatureHelpProvider(languageIds, new signatureHelp_1.default(client), ['(', ',', '<', ')'])); + this._register(coc_nvim_1.languages.registerDocumentSymbolProvider(languageIds, new documentSymbol_1.default(client))); + this._register(coc_nvim_1.languages.registerRenameProvider(languageIds, new rename_1.default(client, this.fileConfigurationManager))); let formatProvider = new formatting_1.default(client, this.fileConfigurationManager); - this.disposables.push(coc_nvim_1.languages.registerDocumentFormatProvider(languageIds, formatProvider)); - this.disposables.push(coc_nvim_1.languages.registerDocumentRangeFormatProvider(languageIds, formatProvider)); - this.disposables.push(coc_nvim_1.languages.registerOnTypeFormattingEditProvider(languageIds, formatProvider, [';', '}', '\n', String.fromCharCode(27)])); - // this.disposables.push( - // new ProjectError(client, commandManager) - // ) - if (this.client.apiVersion.gte(api_1.default.v280)) { - this.disposables.push(coc_nvim_1.languages.registerFoldingRangeProvider(languageIds, new folding_1.default(this.client))); - this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new organizeImports_1.OrganizeImportsCodeActionProvider(this.client, this.fileConfigurationManager), `tsserver-${this.description.id}`, [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports])); - } + this._register(coc_nvim_1.languages.registerDocumentFormatProvider(languageIds, formatProvider)); + this._register(coc_nvim_1.languages.registerDocumentRangeFormatProvider(languageIds, formatProvider)); + this._register(coc_nvim_1.languages.registerOnTypeFormattingEditProvider(languageIds, formatProvider, [';', '}', '\n', String.fromCharCode(27)])); + this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new moduleInstall_1.default(client), 'tsserver')); let { fileConfigurationManager } = this; let conf = fileConfigurationManager.getLanguageConfiguration(this.id); - if (this.client.apiVersion.gte(api_1.default.v290) - && conf.get('updateImportsOnFileMove.enable')) { - this.disposables.push(new updatePathOnRename_1.default(client, this.fileConfigurationManager, this.id)); + if (['javascript', 'typescript'].includes(this.id)) { + if (this.client.apiVersion.gte(api_1.default.v290) && conf.get('updateImportsOnFileMove.enable')) { + this._register(new updatePathOnRename_1.default(client, this.fileConfigurationManager, this.id)); + } + } + if (this.client.apiVersion.gte(api_1.default.v280)) { + this._register(coc_nvim_1.languages.registerFoldingRangeProvider(languageIds, new folding_1.default(this.client))); + this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new organizeImports_1.OrganizeImportsCodeActionProvider(this.client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports])); } if (this.client.apiVersion.gte(api_1.default.v240)) { - this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new refactor_1.default(client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.Refactor])); + this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new refactor_1.default(client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.Refactor])); } - this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new moduleInstall_1.default(client), 'tsserver')); - this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new quickfix_1.default(client), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix])); - this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new importFix_1.default(this.client.bufferSyncSupport), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix])); + this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new quickfix_1.default(client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix])); + this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new importFix_1.default(this.client.bufferSyncSupport), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix])); let cachedResponse = new baseCodeLensProvider_1.CachedNavTreeResponse(); - if (this.client.apiVersion.gte(api_1.default.v206) - && conf.get('referencesCodeLens.enable')) { - this.disposables.push(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new referencesCodeLens_1.default(client, cachedResponse))); + if (this.client.apiVersion.gte(api_1.default.v206) && conf.get('referencesCodeLens.enable')) { + this._register(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new referencesCodeLens_1.default(client, cachedResponse))); } - if (this.client.apiVersion.gte(api_1.default.v220) - && conf.get('implementationsCodeLens.enable')) { - this.disposables.push(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new implementationsCodeLens_1.default(client, cachedResponse))); + if (this.client.apiVersion.gte(api_1.default.v220) && conf.get('implementationsCodeLens.enable')) { + this._register(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new implementationsCodeLens_1.default(client, cachedResponse))); } if (this.client.apiVersion.gte(api_1.default.v350)) { - this.disposables.push(coc_nvim_1.languages.registerSelectionRangeProvider(languageIds, new smartSelect_1.default(this.client))); - } - if (this.description.id == 'typescript') { - // this.client.apiVersion - this.disposables.push(new watchBuild_1.default(coc_nvim_1.commands, this.client)); + this._register(coc_nvim_1.languages.registerSelectionRangeProvider(languageIds, new smartSelect_1.default(this.client))); } // if (this.client.apiVersion.gte(API.v300)) { - // this.disposables.push( + // this._register( // languages.registerCompletionItemProvider( // `tsserver-${this.description.id}-tag`, // 'TSC', @@ -5868,23 +5886,12 @@ class LanguageProvider { // ) // } } - handles(resource) { - let { modeIds, configFile } = this.description; - if (resource.toString().endsWith(configFile)) { - return true; - } - let doc = coc_nvim_1.workspace.getDocument(resource.toString()); - if (doc && modeIds.indexOf(doc.filetype) !== -1) { - return true; - } - let str = resource.toString(); - if (this.id === 'typescript' && /\.ts(x)?$/.test(str)) { - return true; - } - if (this.id === 'javascript' && /\.js(x)?$/.test(str)) { + handles(resource, doc) { + if (doc && this.description.modeIds.indexOf(doc.languageId) >= 0) { return true; } - return false; + const base = path_1.default.basename(coc_nvim_1.Uri.parse(resource).fsPath); + return !!base && (!!this.description.configFilePattern && this.description.configFilePattern.test(base)); } get id() { return this.description.id; @@ -5896,9 +5903,6 @@ class LanguageProvider { this.client.bufferSyncSupport.requestAllDiagnostics(); } diagnosticsReceived(diagnosticsKind, file, diagnostics) { - if (!this.client.bufferSyncSupport.shouldValidate(file.toString())) { - return; - } const config = coc_nvim_1.workspace.getConfiguration(this.id, file.toString()); const reportUnnecessary = config.get('showUnused', true); this.client.diagnosticsManager.diagnosticsReceived(diagnosticsKind, file.toString(), diagnostics.filter(diag => { @@ -5936,19 +5940,10 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", { value: true }); exports.TypeScriptBaseCodeLensProvider = exports.CachedNavTreeResponse = void 0; /*--------------------------------------------------------------------------------------------- @@ -5990,33 +5985,31 @@ class TypeScriptBaseCodeLensProvider { get onDidChangeCodeLenses() { return this.onDidChangeCodeLensesEmitter.event; } - provideCodeLenses(document, token) { - return __awaiter(this, void 0, void 0, function* () { - const filepath = this.client.toPath(document.uri); - if (!filepath) { + async provideCodeLenses(document, token) { + const filepath = this.client.toPath(document.uri); + if (!filepath) { + return []; + } + try { + const response = await this.cachedResponse.execute(document, () => this.client.execute('navtree', { file: filepath }, token)); + if (!response) { return []; } - try { - const response = yield this.cachedResponse.execute(document, () => this.client.execute('navtree', { file: filepath }, token)); - if (!response) { - return []; - } - const tree = response.body; - const referenceableSpans = []; - if (tree && tree.childItems) { - tree.childItems.forEach(item => this.walkNavTree(document, item, null, referenceableSpans)); - } - return referenceableSpans.map(range => { - return { - range, - data: { uri: document.uri } - }; - }); - } - catch (_a) { - return []; + const tree = response.body; + const referenceableSpans = []; + if (tree && tree.childItems) { + tree.childItems.forEach(item => this.walkNavTree(document, item, null, referenceableSpans)); } - }); + return referenceableSpans.map(range => { + return { + range, + data: { uri: document.uri } + }; + }); + } + catch (_a) { + return []; + } } walkNavTree(document, item, parent, results) { if (!item) { @@ -6186,19 +6179,10 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -6222,22 +6206,20 @@ class ApplyCompletionCodeActionCommand { this.id = ApplyCompletionCodeActionCommand.ID; } // apply code action on complete - execute(codeActions) { - return __awaiter(this, void 0, void 0, function* () { - if (codeActions.length === 0) { - return; - } - if (codeActions.length === 1) { - yield codeAction_1.applyCodeAction(this.client, codeActions[0]); - return; - } - const idx = yield coc_nvim_1.workspace.showQuickpick(codeActions.map(o => o.description), 'Select code action to apply'); - if (idx < 0) - return; - const action = codeActions[idx]; - yield codeAction_1.applyCodeAction(this.client, action); + async execute(codeActions) { + if (codeActions.length === 0) { return; - }); + } + if (codeActions.length === 1) { + await codeAction_1.applyCodeAction(this.client, codeActions[0]); + return; + } + const idx = await coc_nvim_1.workspace.showQuickpick(codeActions.map(o => o.description), 'Select code action to apply'); + if (idx < 0) + return; + const action = codeActions[idx]; + await codeAction_1.applyCodeAction(this.client, action); + return; } } ApplyCompletionCodeActionCommand.ID = '_typescript.applyCompletionCodeAction'; @@ -6265,89 +6247,88 @@ class TypeScriptCompletionItemProvider { * @param {string} triggerCharacter * @returns {Promise} */ - provideCompletionItems(document, position, token, context) { - return __awaiter(this, void 0, void 0, function* () { - if (this.typingsStatus.isAcquiringTypings) { - return Promise.resolve({ - isIncomplete: true, - items: [{ - label: 'Acquiring typings...', - detail: 'Acquiring typings definitions for IntelliSense.' - }] - }); - } - let { uri } = document; - const file = this.client.toPath(document.uri); - if (!file) - return null; - let preText = document.getText({ - start: { line: position.line, character: 0 }, - end: position + async provideCompletionItems(document, position, token, context) { + if (this.typingsStatus.isAcquiringTypings) { + return Promise.resolve({ + isIncomplete: true, + items: [{ + label: 'Acquiring typings...', + detail: 'Acquiring typings definitions for IntelliSense.' + }] }); - let { triggerCharacter, option } = context; - if (!this.shouldTrigger(triggerCharacter, preText, option)) { - return null; - } - const { completeOption } = this; - const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { includeExternalModuleExports: completeOption.autoImports, includeInsertTextCompletions: true, triggerCharacter: this.getTsTriggerCharacter(context), includeAutomaticOptionalChainCompletions: completeOption.includeAutomaticOptionalChainCompletions }); - let entries; - let dotAccessorContext; - let isNewIdentifierLocation = true; - let isMemberCompletion = false; - let isIncomplete = false; - const isInValidCommitCharacterContext = this.isInValidCommitCharacterContext(document, position); - if (this.client.apiVersion.gte(api_1.default.v300)) { - try { - const response = yield this.client.interruptGetErr(() => this.client.execute('completionInfo', args, token)); - if (response.type !== 'response' || !response.body) { - return null; - } - isNewIdentifierLocation = response.body.isNewIdentifierLocation; - isMemberCompletion = response.body.isMemberCompletion; - if (isMemberCompletion) { - const dotMatch = preText.slice(0, position.character).match(/\??\.\s*$/) || undefined; - if (dotMatch) { - const range = vscode_languageserver_protocol_1.Range.create({ - line: position.line, - character: position.character - dotMatch.length - }, position); - const text = document.getText(range); - dotAccessorContext = { range, text }; - } - } - isIncomplete = response.metadata && response.metadata.isIncomplete; - entries = response.body.entries; + } + let { uri } = document; + const file = this.client.toPath(document.uri); + if (!file) + return null; + let preText = document.getText({ + start: { line: position.line, character: 0 }, + end: position + }); + let { triggerCharacter, option } = context; + if (!this.shouldTrigger(triggerCharacter, preText, option)) { + return null; + } + await this.client.interruptGetErr(() => this.fileConfigurationManager.ensureConfigurationForDocument(document, token)); + const { completeOption } = this; + const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { includeExternalModuleExports: completeOption.autoImports, includeInsertTextCompletions: true, triggerCharacter: this.getTsTriggerCharacter(context), includeAutomaticOptionalChainCompletions: completeOption.includeAutomaticOptionalChainCompletions }); + let entries; + let dotAccessorContext; + let isNewIdentifierLocation = true; + let isMemberCompletion = false; + let isIncomplete = false; + const isInValidCommitCharacterContext = this.isInValidCommitCharacterContext(document, position); + if (this.client.apiVersion.gte(api_1.default.v300)) { + try { + const response = await this.client.interruptGetErr(() => this.client.execute('completionInfo', args, token)); + if (response.type !== 'response' || !response.body) { + return null; } - catch (e) { - if (e.message == 'No content available.') { - return null; + isNewIdentifierLocation = response.body.isNewIdentifierLocation; + isMemberCompletion = response.body.isMemberCompletion; + if (isMemberCompletion) { + const dotMatch = preText.slice(0, position.character).match(/\??\.\s*$/) || undefined; + if (dotMatch) { + const range = vscode_languageserver_protocol_1.Range.create({ + line: position.line, + character: position.character - dotMatch.length + }, position); + const text = document.getText(range); + dotAccessorContext = { range, text }; } - throw e; } + isIncomplete = response.metadata && response.metadata.isIncomplete; + entries = response.body.entries; } - else { - const response = yield this.client.interruptGetErr(() => this.client.execute('completions', args, token)); - if (response.type !== 'response' || !response.body) { + catch (e) { + if (e.message == 'No content available.') { return null; } - entries = response.body; + throw e; } - const completionItems = []; - for (const element of entries) { - if (shouldExcludeCompletionEntry(element, completeOption)) { - continue; - } - const item = completionItem_1.convertCompletionEntry(element, uri, position, { - isNewIdentifierLocation, - isMemberCompletion, - enableCallCompletions: completeOption.completeFunctionCalls, - isInValidCommitCharacterContext, - dotAccessorContext, - }); - completionItems.push(item); + } + else { + const response = await this.client.interruptGetErr(() => this.client.execute('completions', args, token)); + if (response.type !== 'response' || !response.body) { + return null; } - return { isIncomplete, items: completionItems }; - }); + entries = response.body; + } + const completionItems = []; + for (const element of entries) { + if (shouldExcludeCompletionEntry(element, completeOption)) { + continue; + } + const item = completionItem_1.convertCompletionEntry(element, uri, position, { + isNewIdentifierLocation, + isMemberCompletion, + enableCallCompletions: completeOption.completeFunctionCalls, + isInValidCommitCharacterContext, + dotAccessorContext, + }); + completionItems.push(item); + } + return { isIncomplete, items: completionItems }; } getTsTriggerCharacter(context) { // return context.triggerCharacter as Proto.CompletionsTriggerCharacter @@ -6374,53 +6355,47 @@ class TypeScriptCompletionItemProvider { * @param {CancellationToken} token * @returns {Promise} */ - resolveCompletionItem(item, token) { - return __awaiter(this, void 0, void 0, function* () { - if (item == null) - return undefined; - let { uri, position, source } = item.data; - const filepath = this.client.toPath(uri); - if (!filepath) - return undefined; - let document = coc_nvim_1.workspace.getDocument(uri); - if (!document) - return undefined; - const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(filepath, position)), { entryNames: [ - source - ? { name: item.label, source } - : item.label - ] }); - let response; - try { - response = yield this.client.interruptGetErr(() => this.client.execute('completionEntryDetails', args, token)); - } - catch (_a) { - return item; - } - if (response.type !== 'response' || !response.body) { - return item; - } - const details = response.body; - if (!details || !details.length || !details[0]) { - return item; - } - const detail = details[0]; - if (!item.detail && detail.displayParts.length) { - item.detail = Previewer.plain(detail.displayParts); - } - item.documentation = this.getDocumentation(detail); - const { command, additionalTextEdits } = this.getCodeActions(detail, filepath); - if (command) - item.command = command; - item.additionalTextEdits = additionalTextEdits; - if (detail && item.insertTextFormat == vscode_languageserver_protocol_1.InsertTextFormat.Snippet) { - const shouldCompleteFunction = yield this.isValidFunctionCompletionContext(filepath, position, token); - if (shouldCompleteFunction) { - this.createSnippetOfFunctionCall(item, detail); - } - } + async resolveCompletionItem(item, token) { + if (item == null) + return undefined; + let { uri, position, source, name } = item.data; + const filepath = this.client.toPath(uri); + if (!filepath) + return undefined; + let document = coc_nvim_1.workspace.getDocument(uri); + if (!document) + return undefined; + const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(filepath, position)), { entryNames: [source ? { name, source } : name] }); + let response; + try { + response = await this.client.interruptGetErr(() => this.client.execute('completionEntryDetails', args, token)); + } + catch (_a) { return item; - }); + } + if (response.type !== 'response' || !response.body || !response.body.length) { + return item; + } + const details = response.body; + if (!details || !details.length || !details[0]) { + return item; + } + const detail = details[0]; + if (!item.detail && detail.displayParts.length) { + item.detail = Previewer.plain(detail.displayParts); + } + item.documentation = this.getDocumentation(detail); + const { command, additionalTextEdits } = this.getCodeActions(detail, filepath); + if (command) + item.command = command; + item.additionalTextEdits = additionalTextEdits; + if (detail && item.insertTextFormat == vscode_languageserver_protocol_1.InsertTextFormat.Snippet) { + const shouldCompleteFunction = await this.isValidFunctionCompletionContext(filepath, position, token); + if (shouldCompleteFunction) { + this.createSnippetOfFunctionCall(item, detail); + } + } + return item; } getCodeActions(detail, filepath) { if (!detail.codeActions || !detail.codeActions.length) { @@ -6521,31 +6496,29 @@ class TypeScriptCompletionItemProvider { snippet.appendTabstop(0); item.insertText = snippet.value; } - isValidFunctionCompletionContext(filepath, position, token) { - return __awaiter(this, void 0, void 0, function* () { - // Workaround for https://github.com/Microsoft/TypeScript/issues/12677 - // Don't complete function calls inside of destructive assigments or imports - try { - const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position); - const response = yield this.client.execute('quickinfo', args, token); - if (response.type !== 'response') { - return true; - } - const { body } = response; - switch (body && body.kind) { - case 'var': - case 'let': - case 'const': - case 'alias': - return false; - default: - return true; - } - } - catch (e) { + async isValidFunctionCompletionContext(filepath, position, token) { + // Workaround for https://github.com/Microsoft/TypeScript/issues/12677 + // Don't complete function calls inside of destructive assigments or imports + try { + const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position); + const response = await this.client.execute('quickinfo', args, token); + if (response.type !== 'response') { return true; } - }); + const { body } = response; + switch (body && body.kind) { + case 'var': + case 'let': + case 'const': + case 'alias': + return false; + default: + return true; + } + } + catch (e) { + return true; + } } isInValidCommitCharacterContext(document, position) { if (this.client.apiVersion.lt(api_1.default.v320)) { @@ -6681,7 +6654,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -6748,6 +6721,8 @@ API.v350 = API.fromSimpleString('3.5.0'); API.v380 = API.fromSimpleString('3.8.0'); API.v381 = API.fromSimpleString('3.8.1'); API.v390 = API.fromSimpleString('3.9.0'); +API.v400 = API.fromSimpleString('4.0.0'); +API.v401 = API.fromSimpleString('4.0.1'); /***/ }), @@ -8872,19 +8847,10 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", { value: true }); exports.applyCodeActionCommands = exports.applyCodeAction = exports.getEditForCodeAction = void 0; /*--------------------------------------------------------------------------------------------- @@ -8900,31 +8866,27 @@ function getEditForCodeAction(client, action) { : undefined; } exports.getEditForCodeAction = getEditForCodeAction; -function applyCodeAction(client, action) { - return __awaiter(this, void 0, void 0, function* () { - const workspaceEdit = getEditForCodeAction(client, action); - if (workspaceEdit) { - if (!(yield coc_nvim_1.workspace.applyEdit(workspaceEdit))) { - return false; - } +async function applyCodeAction(client, action) { + const workspaceEdit = getEditForCodeAction(client, action); + if (workspaceEdit) { + if (!(await coc_nvim_1.workspace.applyEdit(workspaceEdit))) { + return false; } - return applyCodeActionCommands(client, action); - }); + } + return applyCodeActionCommands(client, action); } exports.applyCodeAction = applyCodeAction; -function applyCodeActionCommands(client, action) { - return __awaiter(this, void 0, void 0, function* () { - // make sure there is command - if (action.commands && action.commands.length) { - for (const command of action.commands) { - const response = yield client.execute('applyCodeActionCommand', { command }, vscode_languageserver_protocol_1.CancellationToken.None); - if (!response || response.type != 'response' || !response.body) { - return false; - } +async function applyCodeActionCommands(client, action) { + // make sure there is command + if (action.commands && action.commands.length) { + for (const command of action.commands) { + const response = await client.execute('applyCodeActionCommand', { command }, vscode_languageserver_protocol_1.CancellationToken.None); + if (!response || response.type != 'response' || !response.body) { + return false; } } - return true; - }); + } + return true; } exports.applyCodeActionCommands = applyCodeActionCommands; @@ -8950,7 +8912,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -9029,6 +8991,7 @@ function convertCompletionEntry(tsEntry, uri, position, context) { data: { uri, position, + name: tsEntry.name, source: tsEntry.source || '' } }; @@ -9133,7 +9096,9 @@ function getParameterListParts(displayParts) { const next = displayParts[i + 1]; // Skip optional parameters const nameIsFollowedByOptionalIndicator = next && next.text === '?'; - if (!nameIsFollowedByOptionalIndicator) { + // Skip this parameter + const nameIsThis = part.text === 'this'; + if (!nameIsFollowedByOptionalIndicator && !nameIsThis) { parts.push(part); } hasOptionalParameters = hasOptionalParameters || nameIsFollowedByOptionalIndicator; @@ -9338,41 +9303,30 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", { value: true }); const typeConverters = __importStar(__webpack_require__(37)); class TypeScriptDefinitionProvider { constructor(client) { this.client = client; } - getSymbolLocations(definitionType, document, position, token) { - return __awaiter(this, void 0, void 0, function* () { - const filepath = this.client.toPath(document.uri); - if (!filepath) { - return undefined; - } - const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position); - try { - const response = yield this.client.execute(definitionType, args, token); - const locations = (response.type == 'response' && response.body) || []; - return locations.map(location => typeConverters.Location.fromTextSpan(this.client.toResource(location.file), location)); - } - catch (_a) { - return []; - } - }); + async getSymbolLocations(definitionType, document, position, token) { + const filepath = this.client.toPath(document.uri); + if (!filepath) { + return undefined; + } + const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position); + try { + const response = await this.client.execute(definitionType, args, token); + const locations = (response.type == 'response' && response.body) || []; + return locations.map(location => typeConverters.Location.fromTextSpan(this.client.toResource(location.file), location)); + } + catch (_a) { + return []; + } } provideDefinition(document, position, token) { return this.getSymbolLocations('definition', document, position, token); @@ -9489,19 +9443,10 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", { value: true }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. @@ -9514,25 +9459,23 @@ class TypeScriptDocumentHighlightProvider { constructor(client) { this.client = client; } - provideDocumentHighlights(resource, position, token) { - return __awaiter(this, void 0, void 0, function* () { - const file = this.client.toPath(resource.uri); - if (!file) - return []; - const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { filesToSearch: [file] }); - try { - const response = yield this.client.execute('documentHighlights', args, token); - if (response.type !== 'response' || !response.body) { - return []; - } - return arrays_1.flatten(response.body - .filter(highlight => highlight.file === file) - .map(convertDocumentHighlight)); - } - catch (_e) { + async provideDocumentHighlights(resource, position, token) { + const file = this.client.toPath(resource.uri); + if (!file) + return []; + const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { filesToSearch: [file] }); + try { + const response = await this.client.execute('documentHighlights', args, token); + if (response.type !== 'response' || !response.body) { return []; } - }); + return arrays_1.flatten(response.body + .filter(highlight => highlight.file === file) + .map(convertDocumentHighlight)); + } + catch (_e) { + return []; + } } } exports.default = TypeScriptDocumentHighlightProvider; @@ -9597,19 +9540,10 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", { value: true }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. @@ -9656,31 +9590,29 @@ class TypeScriptDocumentSymbolProvider { constructor(client) { this.client = client; } - provideDocumentSymbols(resource, token) { - return __awaiter(this, void 0, void 0, function* () { - const filepath = this.client.toPath(resource.uri); - if (!filepath) - return []; - const args = { - file: filepath - }; - try { - const response = yield this.client.execute('navtree', args, token); - if (response.type == 'response' && response.body) { - // The root represents the file. Ignore this when showing in the UI - const tree = response.body; - if (tree.childItems) { - const result = new Array(); - tree.childItems.forEach(item => TypeScriptDocumentSymbolProvider.convertNavTree(result, item)); - return result; - } + async provideDocumentSymbols(resource, token) { + const filepath = this.client.toPath(resource.uri); + if (!filepath) + return []; + const args = { + file: filepath + }; + try { + const response = await this.client.execute('navtree', args, token); + if (response.type == 'response' && response.body) { + // The root represents the file. Ignore this when showing in the UI + const tree = response.body; + if (tree.childItems) { + const result = new Array(); + tree.childItems.forEach(item => TypeScriptDocumentSymbolProvider.convertNavTree(result, item)); + return result; } - return []; } - catch (e) { - return []; - } - }); + return []; + } + catch (e) { + return []; + } } static convertNavTree(bucket, item) { let shouldInclude = TypeScriptDocumentSymbolProvider.shouldInclueEntry(item); @@ -9735,180 +9667,6 @@ function containsRange(range, otherRange) { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -const coc_nvim_1 = __webpack_require__(1); -const vscode_languageserver_protocol_1 = __webpack_require__(3); -const api_1 = __importDefault(__webpack_require__(40)); -function objAreEqual(a, b) { - let keys = Object.keys(a); - for (let i = 0; i < keys.length; i++) { // tslint:disable-line - let key = keys[i]; - if (a[key] !== b[key]) { - return false; - } - } - return true; -} -class FileConfigurationManager { - constructor(client) { - this.client = client; - this.cachedMap = new Map(); - } - ensureConfigurationOptions(document, insertSpaces, tabSize) { - return __awaiter(this, void 0, void 0, function* () { - const file = this.client.toPath(document.uri); - let options = { - tabSize, - insertSpaces - }; - let cachedOption = this.cachedMap.get(document.uri); - const currentOptions = this.getFileOptions(options, document); - if (cachedOption - && objAreEqual(cachedOption.formatOptions, currentOptions.formatOptions) - && objAreEqual(cachedOption.preferences, currentOptions.preferences)) - return; - this.cachedMap.set(document.uri, currentOptions); - const args = Object.assign({ file }, currentOptions); - yield this.client.execute('configure', args, vscode_languageserver_protocol_1.CancellationToken.None); - }); - } - ensureConfigurationForDocument(document) { - return __awaiter(this, void 0, void 0, function* () { - let opts = yield coc_nvim_1.workspace.getFormatOptions(document.uri); - return this.ensureConfigurationOptions(document, opts.insertSpaces, opts.tabSize); - }); - } - reset() { - this.cachedMap.clear(); - } - getLanguageConfiguration(languageId) { - return coc_nvim_1.workspace.getConfiguration(languageId); - } - isTypeScriptDocument(languageId) { - return languageId.startsWith('typescript'); - } - formatEnabled(document) { - let { languageId, uri } = document; - let language = languageId.startsWith('typescript') ? 'typescript' : 'javascript'; - const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri); - return config.get('enabled'); - } - enableJavascript() { - const config = coc_nvim_1.workspace.getConfiguration('tsserver'); - return !!config.get('enableJavascript'); - } - getFileOptions(options, document) { - const lang = this.isTypeScriptDocument(document.languageId) ? 'typescript' : 'javascript'; - return { - formatOptions: this.getFormatOptions(options, lang, document.uri), - preferences: this.getPreferences(lang, document.uri) - }; - } - getFormatOptions(options, language, uri) { - const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri); - return { - tabSize: options.tabSize, - indentSize: options.tabSize, - convertTabsToSpaces: options.insertSpaces, - // We can use \n here since the editor normalizes later on to its line endings. - newLineCharacter: '\n', - insertSpaceAfterCommaDelimiter: config.get('insertSpaceAfterCommaDelimiter'), - insertSpaceAfterConstructor: config.get('insertSpaceAfterConstructor'), - insertSpaceAfterSemicolonInForStatements: config.get('insertSpaceAfterSemicolonInForStatements'), - insertSpaceBeforeAndAfterBinaryOperators: config.get('insertSpaceBeforeAndAfterBinaryOperators'), - insertSpaceAfterKeywordsInControlFlowStatements: config.get('insertSpaceAfterKeywordsInControlFlowStatements'), - insertSpaceAfterFunctionKeywordForAnonymousFunctions: config.get('insertSpaceAfterFunctionKeywordForAnonymousFunctions'), - insertSpaceBeforeFunctionParenthesis: config.get('insertSpaceBeforeFunctionParenthesis'), - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis'), - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets'), - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces'), - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces'), - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces'), - insertSpaceAfterTypeAssertion: config.get('insertSpaceAfterTypeAssertion'), - placeOpenBraceOnNewLineForFunctions: config.get('placeOpenBraceOnNewLineForFunctions'), - placeOpenBraceOnNewLineForControlBlocks: config.get('placeOpenBraceOnNewLineForControlBlocks'), - semicolons: config.get('semicolons', undefined) - }; - } - getCompleteOptions(languageId) { - const lang = this.isTypeScriptDocument(languageId) ? 'typescript' : 'javascript'; - const config = coc_nvim_1.workspace.getConfiguration(`${lang}.suggest`); - return { - enabled: config.get('enabled', true), - names: config.get('names', true), - paths: config.get('paths', true), - completeFunctionCalls: config.get('completeFunctionCalls', true), - autoImports: config.get('autoImports', true), - includeAutomaticOptionalChainCompletions: config.get('includeAutomaticOptionalChainCompletions', true) - }; - } - getPreferences(language, uri) { - if (this.client.apiVersion.lt(api_1.default.v290)) { - return {}; - } - const config = coc_nvim_1.workspace.getConfiguration(`${language}.preferences`, uri); - // getImportModuleSpecifierEndingPreference available on ts 2.9.0 - const preferences = { - quotePreference: this.getQuoteStyle(config), - importModuleSpecifierPreference: getImportModuleSpecifier(config), - importModuleSpecifierEnding: getImportModuleSpecifierEndingPreference(config), - allowTextChangesInNewFiles: uri.startsWith('file:'), - allowRenameOfImportPath: true, - providePrefixAndSuffixTextForRename: true, - }; - return preferences; - } - getQuoteStyle(config) { - let quoteStyle = config.get('quoteStyle', 'auto'); - if (this.client.apiVersion.gte(api_1.default.v333) || quoteStyle != 'auto') - return quoteStyle; - return 'single'; - } -} -exports.default = FileConfigurationManager; -function getImportModuleSpecifier(config) { - let val = config.get('importModuleSpecifier'); - switch (val) { - case 'relative': - return 'relative'; - case 'non-relative': - return 'non-relative'; - default: - return 'auto'; - } -} -function getImportModuleSpecifierEndingPreference(config) { - switch (config.get('importModuleSpecifierEnding')) { - case 'minimal': return 'minimal'; - case 'index': return 'index'; - case 'js': return 'js'; - default: return 'auto'; - } -} - - -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. @@ -9928,19 +9686,10 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", { value: true }); const vscode_languageserver_types_1 = __webpack_require__(18); const coc_nvim_1 = __webpack_require__(1); @@ -9949,25 +9698,23 @@ class TypeScriptFoldingProvider { constructor(client) { this.client = client; } - provideFoldingRanges(document, _context, token) { - return __awaiter(this, void 0, void 0, function* () { - const file = this.client.toPath(document.uri); - if (!file) { - return; - } - const args = { file }; - const res = yield this.client.execute('getOutliningSpans', args, token); - if (res.type != 'response') { - return; - } - const { body } = res; - if (!body) { - return; - } - return body - .map(span => this.convertOutliningSpan(span, document)) - .filter(foldingRange => !!foldingRange); - }); + async provideFoldingRanges(document, _context, token) { + const file = this.client.toPath(document.uri); + if (!file) { + return; + } + const args = { file }; + const res = await this.client.execute('getOutliningSpans', args, token); + if (res.type != 'response') { + return; + } + const { body } = res; + if (!body) { + return; + } + return body + .map(span => this.convertOutliningSpan(span, document)) + .filter(foldingRange => !!foldingRange); } convertOutliningSpan(span, document) { const range = typeConverters.Range.fromTextSpan(span.textSpan); @@ -9999,7 +9746,7 @@ exports.default = TypeScriptFoldingProvider; /***/ }), -/* 95 */ +/* 94 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -10019,19 +9766,10 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", { value: true }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. @@ -10047,115 +9785,107 @@ class TypeScriptFormattingProvider { enabled(document) { return this.formattingOptionsManager.formatEnabled(document); } - doFormat(document, options, args, token) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.enabled(document)) - return []; - yield this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize); - try { - const response = yield this.client.execute('format', args, token); - if (response.type == 'response' && response.body) { - let edits = response.body.map(typeConverters.TextEdit.fromCodeEdit); - return edits; - } - } - catch (_a) { - // noop - } + async doFormat(document, options, args, token) { + if (!this.enabled(document)) return []; - }); + await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token); + try { + const response = await this.client.execute('format', args, token); + if (response.type == 'response' && response.body) { + let edits = response.body.map(typeConverters.TextEdit.fromCodeEdit); + return edits; + } + } + catch (_a) { + // noop + } + return []; } - provideDocumentRangeFormattingEdits(document, range, options, token) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.enabled(document)) - return []; - const filepath = this.client.toPath(document.uri); - if (!filepath) - return []; - const args = { - file: filepath, - line: range.start.line + 1, - offset: range.start.character + 1, - endLine: range.end.line + 1, - endOffset: range.end.character + 1 - }; - return this.doFormat(document, options, args, token); - }); + async provideDocumentRangeFormattingEdits(document, range, options, token) { + if (!this.enabled(document)) + return []; + const filepath = this.client.toPath(document.uri); + if (!filepath) + return []; + const args = { + file: filepath, + line: range.start.line + 1, + offset: range.start.character + 1, + endLine: range.end.line + 1, + endOffset: range.end.character + 1 + }; + return this.doFormat(document, options, args, token); } - provideDocumentFormattingEdits(document, options, token) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.enabled(document)) - return []; - const filepath = this.client.toPath(document.uri); - if (!filepath) - return []; - const args = { - file: filepath, - line: 1, - offset: 1, - endLine: document.lineCount + 1, - endOffset: 1 - }; - return this.doFormat(document, options, args, token); - }); + async provideDocumentFormattingEdits(document, options, token) { + if (!this.enabled(document)) + return []; + const filepath = this.client.toPath(document.uri); + if (!filepath) + return []; + const args = { + file: filepath, + line: 1, + offset: 1, + endLine: document.lineCount + 1, + endOffset: 1 + }; + return this.doFormat(document, options, args, token); } - provideOnTypeFormattingEdits(document, position, ch, options, token) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.enabled(document)) - return []; - if (!this.client.configuration.formatOnType) - return []; - const file = this.client.toPath(document.uri); - if (!file) + async provideOnTypeFormattingEdits(document, position, ch, options, token) { + if (!this.enabled(document)) + return []; + if (!this.client.configuration.formatOnType) + return []; + const file = this.client.toPath(document.uri); + if (!file) + return []; + await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token); + const doc = coc_nvim_1.workspace.getDocument(document.uri); + const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { key: ch }); + try { + const res = await this.client.execute('formatonkey', args, token); + if (res.type != 'response') { return []; - yield this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize); - const doc = coc_nvim_1.workspace.getDocument(document.uri); - const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { key: ch }); - try { - const res = yield this.client.execute('formatonkey', args, token); - if (res.type != 'response') { - return []; - } - const { body } = res; - const edits = body; - const result = []; - if (!edits) { - return result; - } - for (const edit of edits) { - const textEdit = typeConverters.TextEdit.fromCodeEdit(edit); - const range = textEdit.range; - // Work around for https://github.com/Microsoft/TypeScript/issues/6700. - // Check if we have an edit at the beginning of the line which only removes white spaces and leaves - // an empty line. Drop those edits - if (range.start.character === 0 && - range.start.line === range.end.line && - textEdit.newText === '') { - const lText = doc.getline(range.start.line); - // If the edit leaves something on the line keep the edit (note that the end character is exclusive). - // Keep it also if it removes something else than whitespace - if (lText.trim().length > 0 || lText.length > range.end.character) { - result.push(textEdit); - } - } - else { + } + const { body } = res; + const edits = body; + const result = []; + if (!edits) { + return result; + } + for (const edit of edits) { + const textEdit = typeConverters.TextEdit.fromCodeEdit(edit); + const range = textEdit.range; + // Work around for https://github.com/Microsoft/TypeScript/issues/6700. + // Check if we have an edit at the beginning of the line which only removes white spaces and leaves + // an empty line. Drop those edits + if (range.start.character === 0 && + range.start.line === range.end.line && + textEdit.newText === '') { + const lText = doc.getline(range.start.line); + // If the edit leaves something on the line keep the edit (note that the end character is exclusive). + // Keep it also if it removes something else than whitespace + if (lText.trim().length > 0 || lText.length > range.end.character) { result.push(textEdit); } } - return result; - } - catch (_a) { - // noop + else { + result.push(textEdit); + } } - return []; - }); + return result; + } + catch (_a) { + // noop + } + return []; } } exports.default = TypeScriptFormattingProvider; /***/ }), -/* 96 */ +/* 95 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -10175,19 +9905,10 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", { value: true }); const previewer_1 = __webpack_require__(86); const typeConverters = __importStar(__webpack_require__(37)); @@ -10195,28 +9916,26 @@ class TypeScriptHoverProvider { constructor(client) { this.client = client; } - provideHover(document, position, token) { - return __awaiter(this, void 0, void 0, function* () { - const filepath = this.client.toPath(document.uri); - if (!filepath) { - return undefined; - } - const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position); - try { - const response = yield this.client.interruptGetErr(() => this.client.execute('quickinfo', args, token)); - if (response && response.type == 'response' && response.body) { - const data = response.body; - return { - contents: TypeScriptHoverProvider.getContents(data), - range: typeConverters.Range.fromTextSpan(data) - }; - } - } - catch (e) { - // noop - } + async provideHover(document, position, token) { + const filepath = this.client.toPath(document.uri); + if (!filepath) { return undefined; - }); + } + const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position); + try { + const response = await this.client.interruptGetErr(() => this.client.execute('quickinfo', args, token)); + if (response && response.type == 'response' && response.body) { + const data = response.body; + return { + contents: TypeScriptHoverProvider.getContents(data), + range: typeConverters.Range.fromTextSpan(data) + }; + } + } + catch (e) { + // noop + } + return undefined; } static getContents(data) { const parts = []; @@ -10232,7 +9951,7 @@ exports.default = TypeScriptHoverProvider; /***/ }), -/* 97 */ +/* 96 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -10252,63 +9971,52 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", { value: true }); const PConst = __importStar(__webpack_require__(39)); const typeConverters = __importStar(__webpack_require__(37)); const baseCodeLensProvider_1 = __webpack_require__(35); class TypeScriptImplementationsCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider { - resolveCodeLens(codeLens, token) { - return __awaiter(this, void 0, void 0, function* () { - let { uri } = codeLens.data; - let filepath = this.client.toPath(uri); - const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start); - try { - const response = yield this.client.execute('implementation', args, token, true); - if (response && response.type == 'response' && response.body) { - const locations = response.body - .map(reference => { - return { - uri: this.client.toResource(reference.file), - range: { - start: typeConverters.Position.fromLocation(reference.start), - end: { - line: reference.start.line, - character: 0 - } + async resolveCodeLens(codeLens, token) { + let { uri } = codeLens.data; + let filepath = this.client.toPath(uri); + const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start); + try { + const response = await this.client.execute('implementation', args, token, { lowPriority: true }); + if (response && response.type == 'response' && response.body) { + const locations = response.body + .map(reference => { + return { + uri: this.client.toResource(reference.file), + range: { + start: typeConverters.Position.fromLocation(reference.start), + end: { + line: reference.start.line, + character: 0 } - }; - }) - // Exclude original from implementations - .filter(location => !(location.uri.toString() === uri && - location.range.start.line === codeLens.range.start.line && - location.range.start.character === - codeLens.range.start.character)); - codeLens.command = this.getCommand(locations, codeLens); - return codeLens; - } - } - catch (_a) { - // noop + } + }; + }) + // Exclude original from implementations + .filter(location => !(location.uri.toString() === uri && + location.range.start.line === codeLens.range.start.line && + location.range.start.character === + codeLens.range.start.character)); + codeLens.command = this.getCommand(locations, codeLens); + return codeLens; } - codeLens.command = { - title: '0 implementations', - command: '' - }; - return codeLens; - }); + } + catch (_a) { + // noop + } + codeLens.command = { + title: '0 implementations', + command: '' + }; + return codeLens; } getCommand(locations, codeLens) { let { uri } = codeLens.data; @@ -10341,12 +10049,304 @@ class TypeScriptImplementationsCodeLensProvider extends baseCodeLensProvider_1.T exports.default = TypeScriptImplementationsCodeLensProvider; +/***/ }), +/* 97 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const coc_nvim_1 = __webpack_require__(1); +const vscode_languageserver_protocol_1 = __webpack_require__(3); +const helper_1 = __webpack_require__(98); +class ImportFixProvider { + constructor(bufferSyncSupport) { + this.bufferSyncSupport = bufferSyncSupport; + } + async provideCodeActions(document, _range, context, _token) { + if (this.bufferSyncSupport.hasPendingDiagnostics(document.uri)) { + return []; + } + let diagnostics = context.diagnostics.filter(d => d.code == 2304); + if (!diagnostics.length) + return []; + let edits = []; + let names = []; + let doc = coc_nvim_1.workspace.getDocument(document.uri); + let command; + for (const diagnostic of diagnostics) { + let { range } = diagnostic; + let line = doc.getline(range.start.line); + let name = line.slice(range.start.character, range.end.character); + if (names.indexOf(name) !== -1) + continue; + if (helper_1.nodeModules.indexOf(name) !== -1) { + names.push(name); + edits.push({ + range: vscode_languageserver_protocol_1.Range.create(0, 0, 0, 0), + newText: `import ${name} from '${name}'\n` + }); + command = 'tsserver.organizeImports'; + } + } + let edit = { + changes: { + [document.uri]: edits + } + }; + let cmd = null; + if (command) + cmd = { + title: `fix import`, + command: 'tsserver.organizeImports' + }; + return [{ + title: `Add import ${names.join(', ')}`, + edit, + command: cmd + }]; + } +} +exports.default = ImportFixProvider; + + /***/ }), /* 98 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.nodeModules = void 0; +exports.nodeModules = [ + 'assert', + 'cluster', + 'crypto', + 'dns', + 'domain', + 'events', + 'fs', + 'http', + 'http2', + 'https', + 'inspector', + 'net', + 'os', + 'path', + 'punycode', + 'querystring', + 'readline', + 'repl', + 'stream', + 'string_decoder', + 'tls', + 'tty', + 'url', + 'util', + 'v8', + 'vm', + 'zlib', + 'perf_hooks' +]; + + +/***/ }), +/* 99 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const coc_nvim_1 = __webpack_require__(1); +const vscode_languageserver_protocol_1 = __webpack_require__(3); +const modules_1 = __webpack_require__(100); +class InstallModuleCommand { + constructor() { + this.id = InstallModuleCommand.ID; + } + async execute(uri, name) { + await modules_1.installModules(uri, [name]); + } +} +InstallModuleCommand.ID = '_tsserver.installModule'; +class InstallModuleProvider { + constructor(client) { + this.client = client; + coc_nvim_1.commands.register(new InstallModuleCommand(), true); + } + async provideCodeActions(document, _range, context, _token) { + const uri = coc_nvim_1.Uri.parse(document.uri); + if (uri.scheme != 'file') + return null; + let { diagnostics } = context; + let diags = diagnostics.filter(s => s.code == 2307); + let names = diags.map(o => { + let ms = o.message.match(/module\s'(.+)'/); + return ms ? ms[1] : null; + }); + names = names.filter(s => s != null); + if (!names.length) + return null; + let actions = []; + for (let name of names) { + let title = `install ${name}`; + let command = { + title: `install ${name}`, + command: InstallModuleCommand.ID, + arguments: [document.uri, name] + }; + let codeAction = vscode_languageserver_protocol_1.CodeAction.create(title, command, vscode_languageserver_protocol_1.CodeActionKind.QuickFix); + actions.push(codeAction); + } + return actions; + } +} +exports.default = InstallModuleProvider; + + +/***/ }), +/* 100 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.installModules = exports.distinct = exports.moduleExists = exports.runCommand = void 0; +const child_process_1 = __webpack_require__(101); +const coc_nvim_1 = __webpack_require__(1); +const fs_1 = __importDefault(__webpack_require__(102)); +const path_1 = __importDefault(__webpack_require__(13)); +function runCommand(cmd, cwd, timeout) { + return new Promise((resolve, reject) => { + let timer; + if (timeout) { + timer = setTimeout(() => { + reject(new Error(`timeout after ${timeout}s`)); + }, timeout * 1000); + } + child_process_1.exec(cmd, { cwd }, (err, stdout) => { + if (timer) + clearTimeout(timer); + if (err) { + reject(new Error(`exited with ${err.code}`)); + return; + } + resolve(stdout); + }); + }); +} +exports.runCommand = runCommand; +async function getManager() { + let res = await coc_nvim_1.workspace.findUp(['yarn.lock', 'package-lock.json']); + if (!res) + return 'yarn'; + return res.endsWith('yarn.lock') ? 'yarn' : 'npm'; +} +async function getRoot() { + let res = await coc_nvim_1.workspace.findUp(['package.json']); + if (!res) + return null; + return path_1.default.dirname(res); +} +async function moduleExists(name) { + try { + let content = await runCommand(`npm info ${name} --json`, process.cwd()); + if (!content) + return false; + let obj = JSON.parse(content); + if (obj.error != null) + return false; + return true; + } + catch (e) { + return false; + } + return false; +} +exports.moduleExists = moduleExists; +/** + * Removes duplicates from the given array. The optional keyFn allows to specify + * how elements are checked for equalness by returning a unique string for each. + */ +function distinct(array, keyFn) { + if (!keyFn) { + return array.filter((element, position) => { + return array.indexOf(element) === position; + }); + } + const seen = Object.create(null); + return array.filter(elem => { + const key = keyFn(elem); + if (seen[key]) { + return false; + } + seen[key] = true; + return true; + }); +} +exports.distinct = distinct; +async function installModules(uri, names) { + names = distinct(names); + let workspaceFolder = coc_nvim_1.workspace.getWorkspaceFolder(uri); + let root = workspaceFolder ? coc_nvim_1.Uri.parse(workspaceFolder.uri).fsPath : undefined; + if (!root || !fs_1.default.existsSync(path_1.default.join(root, 'package.json'))) { + coc_nvim_1.workspace.showMessage(`package.json not found from workspaceFolder: ${root}`, 'error'); + return; + } + let arr = names.concat(names.map(s => `@types/${s}`)); + let statusItem = coc_nvim_1.workspace.createStatusBarItem(99, { progress: true }); + statusItem.text = `Checking module ${arr.join(' ')}`; + statusItem.show(); + let exists = await Promise.all(arr.map(name => { + return moduleExists(name).then(exists => { + return exists ? name : null; + }); + })); + let manager = await getManager(); + exists = exists.filter(s => s != null); + if (!exists.length) + return; + let devs = exists.filter(s => s.startsWith('@types')); + let deps = exists.filter(s => devs.indexOf(s) == -1); + statusItem.text = `Installing ${exists.join(' ')}`; + try { + let cmd = manager == 'npm' ? `npm i ${deps.join(' ')}` : `yarn add ${deps.join(' ')}`; + await runCommand(cmd, root); + cmd = manager == 'npm' ? `npm i ${deps.join(' ')} --save-dev` : `yarn add ${deps.join(' ')} --save-dev`; + await runCommand(cmd, root); + } + catch (e) { + statusItem.dispose(); + coc_nvim_1.workspace.showMessage(`Install error ${e.message}`, 'error'); + return; + } + statusItem.dispose(); + coc_nvim_1.workspace.showMessage(`Installed: ${exists.join(' ')}`, 'more'); +} +exports.installModules = installModules; + + +/***/ }), +/* 101 */ +/***/ (function(module, exports) { + +module.exports = require("child_process"); + +/***/ }), +/* 102 */ +/***/ (function(module, exports) { + +module.exports = require("fs"); + +/***/ }), +/* 103 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); @@ -10362,19 +10362,10 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -10389,54 +10380,53 @@ const api_1 = __importDefault(__webpack_require__(40)); const codeAction_1 = __webpack_require__(84); const typeConverters = __importStar(__webpack_require__(37)); class ApplyCodeActionCommand { - constructor(client) { + constructor(client, formattingConfigurationManager) { this.client = client; + this.formattingConfigurationManager = formattingConfigurationManager; this.id = ApplyCodeActionCommand.ID; } - execute(action) { - return __awaiter(this, void 0, void 0, function* () { - return codeAction_1.applyCodeActionCommands(this.client, action); - }); + async execute(action) { + return codeAction_1.applyCodeActionCommands(this.client, action); } } ApplyCodeActionCommand.ID = '_typescript.applyCodeActionCommand'; class ApplyFixAllCodeAction { - constructor(client) { + constructor(client, formattingConfigurationManager) { this.client = client; + this.formattingConfigurationManager = formattingConfigurationManager; this.id = ApplyFixAllCodeAction.ID; } - execute(file, tsAction) { - return __awaiter(this, void 0, void 0, function* () { - if (!tsAction.fixId) { + async execute(document, file, tsAction) { + if (!tsAction.fixId) { + return; + } + await this.formattingConfigurationManager.ensureConfigurationForDocument(document, vscode_languageserver_protocol_1.CancellationToken.None); + const args = { + scope: { + type: 'file', + args: { file } + }, + fixId: tsAction.fixId + }; + try { + const res = await this.client.execute('getCombinedCodeFix', args, vscode_languageserver_protocol_1.CancellationToken.None); + if (res.type != 'response') { return; } - const args = { - scope: { - type: 'file', - args: { file } - }, - fixId: tsAction.fixId - }; - try { - const res = yield this.client.execute('getCombinedCodeFix', args, vscode_languageserver_protocol_1.CancellationToken.None); - if (res.type != 'response') { - return; - } - let { body } = res; - const edit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.changes); - yield coc_nvim_1.workspace.applyEdit(edit); - const token = vscode_languageserver_protocol_1.CancellationToken.None; - const { commands } = body; - if (commands && commands.length) { - for (const command of commands) { - yield this.client.execute('applyCodeActionCommand', { command }, token); - } + let { body } = res; + const edit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.changes); + await coc_nvim_1.workspace.applyEdit(edit); + const token = vscode_languageserver_protocol_1.CancellationToken.None; + const { commands } = body; + if (commands && commands.length) { + for (const command of commands) { + await this.client.execute('applyCodeActionCommand', { command }, token); } } - catch (_a) { - // noop - } - }); + } + catch (_a) { + // noop + } } } ApplyFixAllCodeAction.ID = '_typescript.applyFixAllCodeAction'; @@ -10466,12 +10456,10 @@ class SupportedCodeActionProvider { constructor(client) { this.client = client; } - getFixableDiagnosticsForContext(context) { - return __awaiter(this, void 0, void 0, function* () { - const supportedActions = yield this.supportedCodeActions; - const fixableDiagnostics = DiagnosticsSet.from(context.diagnostics.filter(diagnostic => supportedActions.has(+diagnostic.code))); - return Array.from(fixableDiagnostics.values); - }); + async getFixableDiagnosticsForContext(context) { + const supportedActions = await this.supportedCodeActions; + const fixableDiagnostics = DiagnosticsSet.from(context.diagnostics.filter(diagnostic => supportedActions.has(+diagnostic.code))); + return Array.from(fixableDiagnostics.values); } get supportedCodeActions() { if (!this._supportedCodeActions) { @@ -10490,58 +10478,51 @@ class SupportedCodeActionProvider { } } class TypeScriptQuickFixProvider { - constructor(client) { + constructor(client, formattingConfigurationManager) { this.client = client; - coc_nvim_1.commands.register(new ApplyCodeActionCommand(client)); - coc_nvim_1.commands.register(new ApplyFixAllCodeAction(client)); + this.formattingConfigurationManager = formattingConfigurationManager; + coc_nvim_1.commands.register(new ApplyCodeActionCommand(client, formattingConfigurationManager)); + coc_nvim_1.commands.register(new ApplyFixAllCodeAction(client, formattingConfigurationManager)); this.supportedCodeActionProvider = new SupportedCodeActionProvider(client); } - provideCodeActions(document, _range, context, token) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.client.apiVersion.gte(api_1.default.v213)) { - return []; - } - const file = this.client.toPath(document.uri); - if (!file) { - return []; - } - const fixableDiagnostics = yield this.supportedCodeActionProvider.getFixableDiagnosticsForContext(context); - if (!fixableDiagnostics.length) { - return []; - } - if (this.client.bufferSyncSupport.hasPendingDiagnostics(document.uri)) { - return []; - } + async provideCodeActions(document, _range, context, token) { + const file = this.client.toPath(document.uri); + if (!file) { + return []; + } + await this.formattingConfigurationManager.ensureConfigurationForDocument(document, token); + const fixableDiagnostics = await this.supportedCodeActionProvider.getFixableDiagnosticsForContext(context); + if (!fixableDiagnostics.length) { + return []; + } + if (this.client.bufferSyncSupport.hasPendingDiagnostics(document.uri)) { + return []; + } + const results = []; + for (const diagnostic of fixableDiagnostics) { + results.push(...(await this.getFixesForDiagnostic(document, file, diagnostic, token))); + } + return results; + } + async getFixesForDiagnostic(document, file, diagnostic, token) { + const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+diagnostic.code] }); + const codeFixesResponse = await this.client.execute('getCodeFixes', args, token); + if (codeFixesResponse.type != 'response') { + return []; + } + if (codeFixesResponse.body) { const results = []; - for (const diagnostic of fixableDiagnostics) { - results.push(...(yield this.getFixesForDiagnostic(document, file, diagnostic, token))); + for (const tsCodeFix of codeFixesResponse.body) { + results.push(...(await this.getAllFixesForTsCodeAction(document, file, diagnostic, tsCodeFix))); } return results; - }); - } - getFixesForDiagnostic(document, file, diagnostic, token) { - return __awaiter(this, void 0, void 0, function* () { - const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+diagnostic.code] }); - const codeFixesResponse = yield this.client.execute('getCodeFixes', args, token); - if (codeFixesResponse.type != 'response') { - return []; - } - if (codeFixesResponse.body) { - const results = []; - for (const tsCodeFix of codeFixesResponse.body) { - results.push(...(yield this.getAllFixesForTsCodeAction(document, file, diagnostic, tsCodeFix))); - } - return results; - } - return []; - }); + } + return []; } - getAllFixesForTsCodeAction(document, file, diagnostic, tsAction) { - return __awaiter(this, void 0, void 0, function* () { - const singleFix = this.getSingleFixForTsCodeAction(diagnostic, tsAction); - const fixAll = yield this.getFixAllForTsCodeAction(document, file, diagnostic, tsAction); - return fixAll ? [singleFix, fixAll] : [singleFix]; - }); + async getAllFixesForTsCodeAction(document, file, diagnostic, tsAction) { + const singleFix = this.getSingleFixForTsCodeAction(diagnostic, tsAction); + const fixAll = await this.getFixAllForTsCodeAction(document, file, diagnostic, tsAction); + return fixAll ? [singleFix, fixAll] : [singleFix]; } getSingleFixForTsCodeAction(diagnostic, tsAction) { const codeAction = { @@ -10550,7 +10531,7 @@ class TypeScriptQuickFixProvider { }; codeAction.edit = codeAction_1.getEditForCodeAction(this.client, tsAction); codeAction.diagnostics = [diagnostic]; - codeAction.isPrefered = true; + codeAction.isPreferred = true; if (tsAction.commands) { codeAction.command = { command: ApplyCodeActionCommand.ID, @@ -10560,148 +10541,34 @@ class TypeScriptQuickFixProvider { } return codeAction; } - getFixAllForTsCodeAction(document, file, diagnostic, tsAction) { - return __awaiter(this, void 0, void 0, function* () { - if (!tsAction.fixId || !this.client.apiVersion.gte(api_1.default.v270)) { - return undefined; - } - // Make sure there are multiple diagnostics of the same type in the file - if (!this.client.diagnosticsManager - .getDiagnostics(document.uri) - .some(x => x.code === diagnostic.code && x !== diagnostic)) { - return; - } - const action = { - title: tsAction.fixAllDescription || 'Fix all in file', - kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix - }; - action.diagnostics = [diagnostic]; - action.command = { - command: ApplyFixAllCodeAction.ID, - arguments: [file, tsAction], - title: '' - }; - return action; - }); + async getFixAllForTsCodeAction(document, file, diagnostic, tsAction) { + if (!tsAction.fixId || !this.client.apiVersion.gte(api_1.default.v270)) { + return undefined; + } + // Make sure there are multiple diagnostics of the same type in the file + if (!this.client.diagnosticsManager + .getDiagnostics(document.uri) + .some(x => x.code === diagnostic.code && x !== diagnostic)) { + return; + } + const action = { + title: tsAction.fixAllDescription || 'Fix all in file', + kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix + }; + action.diagnostics = [diagnostic]; + action.command = { + command: ApplyFixAllCodeAction.ID, + arguments: [document, file, tsAction], + title: '' + }; + return action; } } exports.default = TypeScriptQuickFixProvider; /***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const coc_nvim_1 = __webpack_require__(1); -const vscode_languageserver_protocol_1 = __webpack_require__(3); -const helper_1 = __webpack_require__(100); -class ImportFixProvider { - constructor(bufferSyncSupport) { - this.bufferSyncSupport = bufferSyncSupport; - } - provideCodeActions(document, _range, context, _token) { - return __awaiter(this, void 0, void 0, function* () { - if (this.bufferSyncSupport.hasPendingDiagnostics(document.uri)) { - return []; - } - let diagnostics = context.diagnostics.filter(d => d.code == 2304); - if (!diagnostics.length) - return []; - let edits = []; - let names = []; - let doc = coc_nvim_1.workspace.getDocument(document.uri); - let command; - for (const diagnostic of diagnostics) { - let { range } = diagnostic; - let line = doc.getline(range.start.line); - let name = line.slice(range.start.character, range.end.character); - if (names.indexOf(name) !== -1) - continue; - if (helper_1.nodeModules.indexOf(name) !== -1) { - names.push(name); - edits.push({ - range: vscode_languageserver_protocol_1.Range.create(0, 0, 0, 0), - newText: `import ${name} from '${name}'\n` - }); - command = 'tsserver.organizeImports'; - } - } - let edit = { - changes: { - [document.uri]: edits - } - }; - let cmd = null; - if (command) - cmd = { - title: `fix import`, - command: 'tsserver.organizeImports' - }; - return [{ - title: `Add import ${names.join(', ')}`, - edit, - command: cmd - }]; - }); - } -} -exports.default = ImportFixProvider; - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.nodeModules = void 0; -exports.nodeModules = [ - 'assert', - 'cluster', - 'crypto', - 'dns', - 'domain', - 'events', - 'fs', - 'http', - 'http2', - 'https', - 'inspector', - 'net', - 'os', - 'path', - 'punycode', - 'querystring', - 'readline', - 'repl', - 'stream', - 'string_decoder', - 'tls', - 'tty', - 'url', - 'util', - 'v8', - 'vm', - 'zlib', - 'perf_hooks' -]; - - -/***/ }), -/* 101 */ +/* 104 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -10721,19 +10588,10 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", { value: true }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. @@ -10747,34 +10605,30 @@ class ApplyRefactoringCommand { this.client = client; this.id = ApplyRefactoringCommand.ID; } - execute(document, file, refactor, action, range) { - return __awaiter(this, void 0, void 0, function* () { - const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, range)), { refactor, - action }); - const response = yield this.client.execute('getEditsForRefactor', args, vscode_languageserver_protocol_1.CancellationToken.None); - const body = response && response.body; - if (!body || !body.edits.length) { - return false; - } - const workspaceEdit = yield this.toWorkspaceEdit(body); - if (!(yield coc_nvim_1.workspace.applyEdit(workspaceEdit))) { - return false; - } - const renameLocation = body.renameLocation; - if (renameLocation) { - coc_nvim_1.commands.executeCommand('editor.action.rename', document.uri, typeConverters.Position.fromLocation(renameLocation)); - } - return true; - }); + async execute(document, file, refactor, action, range) { + const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, range)), { refactor, + action }); + const response = await this.client.execute('getEditsForRefactor', args, vscode_languageserver_protocol_1.CancellationToken.None); + const body = response && response.body; + if (!body || !body.edits.length) { + return false; + } + const workspaceEdit = await this.toWorkspaceEdit(body); + if (!(await coc_nvim_1.workspace.applyEdit(workspaceEdit))) { + return false; + } + const renameLocation = body.renameLocation; + if (renameLocation) { + coc_nvim_1.commands.executeCommand('editor.action.rename', document.uri, typeConverters.Position.fromLocation(renameLocation)); + } + return true; } - toWorkspaceEdit(body) { - return __awaiter(this, void 0, void 0, function* () { - for (const edit of body.edits) { - yield coc_nvim_1.workspace.createFile(edit.fileName, { ignoreIfExists: true }); - } - let workspaceEdit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.edits); - return workspaceEdit; - }); + async toWorkspaceEdit(body) { + for (const edit of body.edits) { + await coc_nvim_1.workspace.createFile(edit.fileName, { ignoreIfExists: true }); + } + let workspaceEdit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.edits); + return workspaceEdit; } } ApplyRefactoringCommand.ID = '_typescript.applyRefactoring'; @@ -10783,17 +10637,15 @@ class SelectRefactorCommand { this.doRefactoring = doRefactoring; this.id = SelectRefactorCommand.ID; } - execute(document, file, info, range) { - return __awaiter(this, void 0, void 0, function* () { - let { actions } = info; - const idx = actions.length == 1 ? 0 : yield coc_nvim_1.workspace.showQuickpick(actions.map(action => action.description || action.name)); - if (idx == -1) - return false; - let label = info.actions[idx].name; - if (!label) - return false; - return this.doRefactoring.execute(document, file, info.name, label, range); - }); + async execute(document, file, info, range) { + let { actions } = info; + const idx = actions.length == 1 ? 0 : await coc_nvim_1.workspace.showQuickpick(actions.map(action => action.description || action.name)); + if (idx == -1) + return false; + let label = info.actions[idx].name; + if (!label) + return false; + return this.doRefactoring.execute(document, file, info.name, label, range); } } SelectRefactorCommand.ID = '_typescript.selectRefactoring'; @@ -10804,34 +10656,35 @@ class TypeScriptRefactorProvider { const doRefactoringCommand = coc_nvim_1.commands.register(new ApplyRefactoringCommand(this.client)); coc_nvim_1.commands.register(new SelectRefactorCommand(doRefactoringCommand)); } - provideCodeActions(document, range, context, token) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.shouldTrigger(context)) { - return undefined; - } - const file = this.client.toPath(document.uri); - if (!file) - return undefined; - yield this.formattingOptionsManager.ensureConfigurationForDocument(document); - const args = typeConverters.Range.toFileRangeRequestArgs(file, range); - let response; - try { - response = yield this.client.interruptGetErr(() => { - return this.client.execute('getApplicableRefactors', args, token); - }); - if (!response || !response.body) { - return undefined; - } - } - catch (_a) { + async provideCodeActions(document, range, context, token) { + if (!this.shouldTrigger(context)) { + return undefined; + } + const file = this.client.toPath(document.uri); + if (!file) + return undefined; + await this.formattingOptionsManager.ensureConfigurationForDocument(document, token); + const args = typeConverters.Range.toFileRangeRequestArgs(file, range); + let response; + try { + response = await this.client.interruptGetErr(() => { + return this.client.execute('getApplicableRefactors', args, token); + }); + if (!response || !response.body) { return undefined; } - return this.convertApplicableRefactors(response.body, document, file, range); - }); + } + catch (_a) { + return undefined; + } + return this.convertApplicableRefactors(response.body, document, file, range, context.only && context.only.some(v => v.includes(vscode_languageserver_protocol_1.CodeActionKind.Refactor))); } - convertApplicableRefactors(body, document, file, rangeOrSelection) { + convertApplicableRefactors(body, document, file, rangeOrSelection, setPrefrred) { const actions = []; for (const info of body) { + // ignore not refactor that not applicable + if (info.notApplicableReason) + continue; if (!info.inlineable) { const codeAction = { title: info.description, @@ -10846,7 +10699,11 @@ class TypeScriptRefactorProvider { } else { for (const action of info.actions) { - actions.push(this.refactorActionToCodeAction(action, document, file, info, rangeOrSelection)); + let codeAction = this.refactorActionToCodeAction(action, document, file, info, rangeOrSelection); + if (setPrefrred) { + codeAction.isPreferred = TypeScriptRefactorProvider.isPreferred(action, info.actions); + } + actions.push(codeAction); } } } @@ -10866,7 +10723,7 @@ class TypeScriptRefactorProvider { } shouldTrigger(context) { if (context.only && - context.only.indexOf(vscode_languageserver_protocol_1.CodeActionKind.Refactor) == -1) { + context.only.every(o => !o.includes(vscode_languageserver_protocol_1.CodeActionKind.Refactor))) { return false; } return true; @@ -10883,6 +10740,32 @@ class TypeScriptRefactorProvider { } return vscode_languageserver_protocol_1.CodeActionKind.Refactor; } + static isPreferred(action, allActions) { + let kind = TypeScriptRefactorProvider.getKind(action); + if (TypeScriptRefactorProvider.extractConstantKind == kind) { + // Only mark the action with the lowest scope as preferred + const getScope = (name) => { + var _a; + const scope = (_a = name.match(/scope_(\d)/)) === null || _a === void 0 ? void 0 : _a[1]; + return scope ? +scope : undefined; + }; + const scope = getScope(action.name); + if (typeof scope !== 'number') { + return false; + } + return allActions + .filter(otherAtion => otherAtion !== action && otherAtion.name.startsWith('constant_')) + .every(otherAction => { + const otherScope = getScope(otherAction.name); + return typeof otherScope === 'number' ? scope < otherScope : true; + }); + } + let { name } = action; + if (name.startsWith('Extract to type alias') || name.startsWith('Extract to interface')) { + return true; + } + return false; + } } exports.default = TypeScriptRefactorProvider; TypeScriptRefactorProvider.extractFunctionKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.function'; @@ -10894,7 +10777,7 @@ TypeScriptRefactorProvider.metadata = { /***/ }), -/* 102 */ +/* 105 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -10914,58 +10797,47 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", { value: true }); const typeConverters = __importStar(__webpack_require__(37)); class TypeScriptReferences { constructor(client) { this.client = client; } - provideReferences(document, position, context, token) { - return __awaiter(this, void 0, void 0, function* () { - const filepath = this.client.toPath(document.uri); - if (!filepath) + async provideReferences(document, position, context, token) { + const filepath = this.client.toPath(document.uri); + if (!filepath) + return []; + const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position); + try { + const msg = await this.client.execute('references', args, token); + if (!msg || msg.type != 'response' || !msg.body) { return []; - const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position); - try { - const msg = yield this.client.execute('references', args, token); - if (!msg || msg.type != 'response' || !msg.body) { - return []; - } - const result = []; - for (const ref of msg.body.refs) { - if (!context.includeDeclaration && ref.isDefinition) { - continue; - } - const url = this.client.toResource(ref.file); - const location = typeConverters.Location.fromTextSpan(url, ref); - result.push(location); - } - return result; } - catch (_a) { - return []; + const result = []; + for (const ref of msg.body.refs) { + if (!context.includeDeclaration && ref.isDefinition) { + continue; + } + const url = this.client.toResource(ref.file); + const location = typeConverters.Location.fromTextSpan(url, ref); + result.push(location); } - }); + return result; + } + catch (_a) { + return []; + } } } exports.default = TypeScriptReferences; /***/ }), -/* 103 */ +/* 106 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -10985,7 +10857,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -10999,7 +10871,9 @@ class TypeScriptReferencesCodeLensProvider extends baseCodeLensProvider_1.TypeSc let filepath = this.client.toPath(uri); const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start); return this.client - .execute('references', args, token, true) + .execute('references', args, token, { + lowPriority: true + }) .then(response => { if (!response || response.type != 'response' || !response.body) { throw codeLens; @@ -11063,7 +10937,7 @@ exports.default = TypeScriptReferencesCodeLensProvider; /***/ }), -/* 104 */ +/* 107 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -11083,19 +10957,10 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -11109,62 +10974,58 @@ const path_1 = __importDefault(__webpack_require__(13)); const api_1 = __importDefault(__webpack_require__(40)); const typeConverters = __importStar(__webpack_require__(37)); class TypeScriptRenameProvider { - constructor(client) { + constructor(client, fileConfigurationManager) { this.client = client; + this.fileConfigurationManager = fileConfigurationManager; } - prepareRename(document, position, token) { - return __awaiter(this, void 0, void 0, function* () { - const response = yield this.execRename(document, position, token); - if (!response || response.type !== 'response' || !response.body) { - return null; - } - const renameInfo = response.body.info; - if (!renameInfo.canRename) { - return Promise.reject(new Error('Invalid location for rename.')); - } - if (this.client.apiVersion.gte(api_1.default.v310)) { - const triggerSpan = renameInfo.triggerSpan; - if (triggerSpan) { - const range = typeConverters.Range.fromTextSpan(triggerSpan); - return range; - } - } + async prepareRename(document, position, token) { + const response = await this.execRename(document, position, token); + if (!response || response.type !== 'response' || !response.body) { return null; - }); - } - provideRenameEdits(document, position, newName, token) { - return __awaiter(this, void 0, void 0, function* () { - const response = yield this.execRename(document, position, token); - if (!response || response.type !== 'response' || !response.body) { - return null; - } - const renameInfo = response.body.info; - if (!renameInfo.canRename) { - return Promise.reject(new Error('Invalid location for rename.')); + } + const renameInfo = response.body.info; + if (!renameInfo.canRename) { + return Promise.reject(new Error('Invalid location for rename.')); + } + if (this.client.apiVersion.gte(api_1.default.v310)) { + const triggerSpan = renameInfo.triggerSpan; + if (triggerSpan) { + const range = typeConverters.Range.fromTextSpan(triggerSpan); + return range; } - if (this.client.apiVersion.gte(api_1.default.v310)) { - if (renameInfo.fileToRename) { - const edits = yield this.renameFile(renameInfo.fileToRename, newName, token); - if (edits) { - return edits; - } - else { - return Promise.reject(new Error('An error occurred while renaming file')); - } + } + return null; + } + async provideRenameEdits(document, position, newName, token) { + const response = await this.execRename(document, position, token); + if (!response || response.type !== 'response' || !response.body) { + return null; + } + const renameInfo = response.body.info; + if (!renameInfo.canRename) { + return Promise.reject(new Error('Invalid location for rename.')); + } + if (this.client.apiVersion.gte(api_1.default.v310)) { + if (renameInfo.fileToRename) { + const edits = await this.renameFile(renameInfo.fileToRename, newName, token); + if (edits) { + return edits; + } + else { + return Promise.reject(new Error('An error occurred while renaming file')); } } - return this.toWorkspaceEdit(response.body.locs, newName); - }); + } + return this.toWorkspaceEdit(response.body.locs, newName); } - execRename(document, position, token) { - return __awaiter(this, void 0, void 0, function* () { - const file = this.client.toPath(document.uri); - if (!file) - return undefined; - const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { findInStrings: false, findInComments: false }); - return this.client.interruptGetErr(() => { - return this.client.execute('rename', args, token); - }); + async execRename(document, position, token) { + const file = this.client.toPath(document.uri); + if (!file) + return undefined; + const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { findInStrings: false, findInComments: false }); + await this.fileConfigurationManager.ensureConfigurationForDocument(document, token); + return this.client.interruptGetErr(() => { + return this.client.execute('rename', args, token); }); } toWorkspaceEdit(locations, newName) { @@ -11183,43 +11044,41 @@ class TypeScriptRenameProvider { } return { changes }; } - renameFile(fileToRename, newName, token) { - return __awaiter(this, void 0, void 0, function* () { - // Make sure we preserve file exension if none provided - if (!path_1.default.extname(newName)) { - newName += path_1.default.extname(fileToRename); - } - const dirname = path_1.default.dirname(fileToRename); - const newFilePath = path_1.default.join(dirname, newName); - const args = { - file: fileToRename, - oldFilePath: fileToRename, - newFilePath - }; - const response = yield this.client.execute('getEditsForFileRename', args, token); - if (response.type !== 'response' || !response.body) { - return undefined; + async renameFile(fileToRename, newName, token) { + // Make sure we preserve file exension if none provided + if (!path_1.default.extname(newName)) { + newName += path_1.default.extname(fileToRename); + } + const dirname = path_1.default.dirname(fileToRename); + const newFilePath = path_1.default.join(dirname, newName); + const args = { + file: fileToRename, + oldFilePath: fileToRename, + newFilePath + }; + const response = await this.client.execute('getEditsForFileRename', args, token); + if (response.type !== 'response' || !response.body) { + return undefined; + } + const edits = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, response.body); + edits.documentChanges = edits.documentChanges || []; + edits.documentChanges.push({ + kind: 'rename', + oldUri: coc_nvim_1.Uri.file(fileToRename).toString(), + newUri: coc_nvim_1.Uri.file(newFilePath).toString(), + options: { + overwrite: false, + ignoreIfExists: true } - const edits = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, response.body); - edits.documentChanges = edits.documentChanges || []; - edits.documentChanges.push({ - kind: 'rename', - oldUri: coc_nvim_1.Uri.file(fileToRename).toString(), - newUri: coc_nvim_1.Uri.file(newFilePath).toString(), - options: { - overwrite: false, - ignoreIfExists: true - } - }); - return edits; }); + return edits; } } exports.default = TypeScriptRenameProvider; /***/ }), -/* 105 */ +/* 108 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -11239,19 +11098,10 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", { value: true }); const Previewer = __importStar(__webpack_require__(86)); const typeConverters = __importStar(__webpack_require__(37)); @@ -11259,33 +11109,31 @@ class TypeScriptSignatureHelpProvider { constructor(client) { this.client = client; } - provideSignatureHelp(document, position, token) { - return __awaiter(this, void 0, void 0, function* () { - const filepath = this.client.toPath(document.uri); - if (!filepath) { - return undefined; - } - const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position); - let response; - try { - response = yield this.client.interruptGetErr(() => this.client.execute('signatureHelp', args, token)); - } - catch (e) { - return undefined; - } - if (response.type !== 'response' || !response.body) { - return undefined; - } - let info = response.body; - const result = { - activeSignature: info.selectedItemIndex, - activeParameter: this.getActiveParmeter(info), - signatures: info.items.map(signature => { - return this.convertSignature(signature); - }) - }; - return result; - }); + async provideSignatureHelp(document, position, token) { + const filepath = this.client.toPath(document.uri); + if (!filepath) { + return undefined; + } + const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position); + let response; + try { + response = await this.client.interruptGetErr(() => this.client.execute('signatureHelp', args, token)); + } + catch (e) { + return undefined; + } + if (response.type !== 'response' || !response.body) { + return undefined; + } + let info = response.body; + const result = { + activeSignature: info.selectedItemIndex, + activeParameter: this.getActiveParmeter(info), + signatures: info.items.map(signature => { + return this.convertSignature(signature); + }) + }; + return result; } getActiveParmeter(info) { const activeSignature = info.items[info.selectedItemIndex]; @@ -11316,11 +11164,15 @@ TypeScriptSignatureHelpProvider.triggerCharacters = ['(', ',', '<']; /***/ }), -/* 106 */ +/* 109 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); @@ -11336,18 +11188,65 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); +Object.defineProperty(exports, "__esModule", { value: true }); +const typeConverters = __importStar(__webpack_require__(37)); +class SmartSelection { + constructor(client) { + this.client = client; + } + async provideSelectionRanges(document, positions, token) { + const file = this.client.toPath(document.uri); + if (!file) { + return undefined; + } + const args = { + file, + locations: positions.map(typeConverters.Position.toLocation) + }; + const response = await this.client.execute('selectionRange', args, token); + if (response.type !== 'response' || !response.body) { + return undefined; + } + return response.body.map(SmartSelection.convertSelectionRange); + } + static convertSelectionRange(selectionRange) { + return { + range: typeConverters.Range.fromTextSpan(selectionRange.textSpan), + parent: selectionRange.parent ? SmartSelection.convertSelectionRange(selectionRange.parent) : undefined, + }; + } +} +exports.default = SmartSelection; + + +/***/ }), +/* 110 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; }; Object.defineProperty(exports, "__esModule", { value: true }); /*--------------------------------------------------------------------------------------------- @@ -11357,7 +11256,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); const vscode_languageserver_protocol_1 = __webpack_require__(3); const coc_nvim_1 = __webpack_require__(1); const typeConverters = __importStar(__webpack_require__(37)); -const mutex_1 = __webpack_require__(107); +const mutex_1 = __webpack_require__(111); function wait(ms) { return new Promise(resolve => { setTimeout(() => { @@ -11374,90 +11273,84 @@ class UpdateImportsOnFileRenameHandler { const watcher = coc_nvim_1.workspace.createFileSystemWatcher(glob); this.disposables.push(watcher); let mutex = new mutex_1.Mutex(); - watcher.onDidRename((e) => __awaiter(this, void 0, void 0, function* () { - let release = yield mutex.acquire(); + watcher.onDidRename(async (e) => { + let release = await mutex.acquire(); try { - yield this.doRename(e.oldUri, e.newUri); + await this.doRename(e.oldUri, e.newUri); release(); } catch (e) { this.client.logger.error('Error on rename:', e); release(); } - }), null, this.disposables); + }, null, this.disposables); } dispose() { coc_nvim_1.disposeAll(this.disposables); } - doRename(oldResource, newResource) { - return __awaiter(this, void 0, void 0, function* () { - if (oldResource.scheme !== 'file' || newResource.scheme !== 'file') { - return; - } - const targetFile = newResource.fsPath; - const oldFile = oldResource.fsPath; - const newUri = newResource.toString(); - let oldDocument = coc_nvim_1.workspace.getDocument(oldResource.toString()); - if (oldDocument) { - yield coc_nvim_1.workspace.nvim.command(`silent ${oldDocument.bufnr}bwipeout!`); - } - let document = coc_nvim_1.workspace.getDocument(newUri); - if (document) { - yield coc_nvim_1.workspace.nvim.command(`silent ${document.bufnr}bwipeout!`); - yield wait(30); - } - document = yield coc_nvim_1.workspace.loadFile(newUri); - if (!document) - return; - yield wait(50); - const edits = yield this.getEditsForFileRename(document.textDocument, oldFile, targetFile); - if (!edits) - return; - if (yield this.promptUser(newResource)) { - yield coc_nvim_1.workspace.applyEdit(edits); - } - }); + async doRename(oldResource, newResource) { + if (oldResource.scheme !== 'file' || newResource.scheme !== 'file') { + return; + } + const targetFile = newResource.fsPath; + const oldFile = oldResource.fsPath; + const newUri = newResource.toString(); + let oldDocument = coc_nvim_1.workspace.getDocument(oldResource.toString()); + if (oldDocument) { + await coc_nvim_1.workspace.nvim.command(`silent ${oldDocument.bufnr}bwipeout!`); + } + let document = coc_nvim_1.workspace.getDocument(newUri); + if (document) { + await coc_nvim_1.workspace.nvim.command(`silent ${document.bufnr}bwipeout!`); + await wait(30); + } + document = await coc_nvim_1.workspace.loadFile(newUri); + if (!document) + return; + await wait(50); + const edits = await this.getEditsForFileRename(document.textDocument, oldFile, targetFile); + if (!edits) + return; + if (await this.promptUser(newResource)) { + await coc_nvim_1.workspace.applyEdit(edits); + } } - promptUser(newResource) { - return __awaiter(this, void 0, void 0, function* () { - return yield coc_nvim_1.workspace.showPrompt(`Update imports for moved file: ${newResource.fsPath}?`); - }); + async promptUser(newResource) { + return await coc_nvim_1.workspace.showPrompt(`Update imports for moved file: ${newResource.fsPath}?`); } - getEditsForFileRename(document, oldFile, newFile) { - return __awaiter(this, void 0, void 0, function* () { - yield this.fileConfigurationManager.ensureConfigurationForDocument(document); - const response = yield this.client.interruptGetErr(() => { - const args = { - oldFilePath: oldFile, - newFilePath: newFile, - }; - return this.client.execute('getEditsForFileRename', args, vscode_languageserver_protocol_1.CancellationToken.None); - }); - if (!response || response.type != 'response' || !response.body) { - return; + async getEditsForFileRename(document, oldFile, newFile) { + await this.fileConfigurationManager.ensureConfigurationForDocument(document, vscode_languageserver_protocol_1.CancellationToken.None); + const response = await this.client.interruptGetErr(() => { + const args = { + oldFilePath: oldFile, + newFilePath: newFile, + }; + return this.client.execute('getEditsForFileRename', args, vscode_languageserver_protocol_1.CancellationToken.None); + }); + if (!response || response.type != 'response' || !response.body) { + return; + } + const edits = []; + for (const edit of response.body) { + // Workaround for https://github.com/Microsoft/vscode/issues/52675 + if (edit.fileName.match(/[\/\\]node_modules[\/\\]/gi)) { + continue; } - const edits = []; - for (const edit of response.body) { - // Workaround for https://github.com/Microsoft/vscode/issues/52675 - if (edit.fileName.match(/[\/\\]node_modules[\/\\]/gi)) { + for (const change of edit.textChanges) { + if (change.newText.match(/\/node_modules\//gi)) { continue; } - for (const change of edit.textChanges) { - if (change.newText.match(/\/node_modules\//gi)) { - continue; - } - } - edits.push(edit); } - return typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, edits); - }); + edits.push(edit); + } + return typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, edits); } } exports.default = UpdateImportsOnFileRenameHandler; /***/ }), -/* 107 */ +/* 111 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -11515,155 +11408,7 @@ exports.Mutex = Mutex; /***/ }), -/* 108 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const coc_nvim_1 = __webpack_require__(1); -const path_1 = __importDefault(__webpack_require__(13)); -const vscode_languageserver_protocol_1 = __webpack_require__(3); -const countRegex = /Found\s+(\d+)\s+error/; -const errorRegex = /^(.+)\((\d+),(\d+)\):\s(\w+)\sTS(\d+):\s*(.+)$/; -var TscStatus; -(function (TscStatus) { - TscStatus[TscStatus["INIT"] = 0] = "INIT"; - TscStatus[TscStatus["COMPILING"] = 1] = "COMPILING"; - TscStatus[TscStatus["RUNNING"] = 2] = "RUNNING"; - TscStatus[TscStatus["ERROR"] = 3] = "ERROR"; -})(TscStatus || (TscStatus = {})); -class WatchProject { - constructor(commandManager, client) { - this.client = client; - this.disposables = []; - this.statusItem = coc_nvim_1.workspace.createStatusBarItem(1, { progress: true }); - let task = this.task = coc_nvim_1.workspace.createTask('TSC'); - this.disposables.push(commandManager.registerCommand(WatchProject.id, () => __awaiter(this, void 0, void 0, function* () { - let opts = this.options = yield this.getOptions(); - yield this.start(opts); - }))); - task.onExit(code => { - if (code != 0) { - coc_nvim_1.workspace.showMessage(`TSC exit with code ${code}`, 'warning'); - } - this.onStop(); - }); - task.onStdout(lines => { - for (let line of lines) { - this.onLine(line); - } - }); - task.onStderr(lines => { - coc_nvim_1.workspace.showMessage(`TSC error: ` + lines.join('\n'), 'error'); - }); - this.disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => { - task.dispose(); - })); - this.check().catch(_e => { - // noop - }); - } - check() { - return __awaiter(this, void 0, void 0, function* () { - let running = yield this.task.running; - if (running) { - this.options = yield this.getOptions(); - this.statusItem.isProgress = false; - this.statusItem.text = '?'; - this.statusItem.show(); - } - else { - this.onStop(); - } - }); - } - start(options) { - return __awaiter(this, void 0, void 0, function* () { - yield this.task.start(options); - }); - } - onStop() { - this.statusItem.hide(); - } - onStart() { - this.statusItem.text = 'compiling'; - this.statusItem.isProgress = true; - this.statusItem.show(); - coc_nvim_1.workspace.nvim.call('setqflist', [[]], true); - } - onLine(line) { - if (countRegex.test(line)) { - let ms = line.match(countRegex); - this.statusItem.text = ms[1] == '0' ? '✓' : '✗'; - this.statusItem.isProgress = false; - } - else if (WatchProject.startTexts.findIndex(s => line.indexOf(s) !== -1) != -1) { - this.onStart(); - } - else { - let ms = line.match(errorRegex); - if (!ms) - return; - let fullpath = path_1.default.join(this.options.cwd, ms[1]); - let uri = coc_nvim_1.Uri.file(fullpath).toString(); - let doc = coc_nvim_1.workspace.getDocument(uri); - let bufnr = doc ? doc.bufnr : null; - let item = { - filename: fullpath, - lnum: Number(ms[2]), - col: Number(ms[3]), - text: `[tsc ${ms[5]}] ${ms[6]}`, - type: /error/i.test(ms[4]) ? 'E' : 'W' - }; - if (bufnr) - item.bufnr = bufnr; - coc_nvim_1.workspace.nvim.call('setqflist', [[item], 'a']); - } - } - getOptions() { - return __awaiter(this, void 0, void 0, function* () { - let { tscPath } = this.client; - if (!tscPath) { - coc_nvim_1.workspace.showMessage(`Local & global tsc not found`, 'error'); - return; - } - let find = yield coc_nvim_1.workspace.findUp(['tsconfig.json']); - if (!find) { - coc_nvim_1.workspace.showMessage('tsconfig.json not found!', 'error'); - return; - } - let root = path_1.default.dirname(find); - return { - cmd: tscPath, - args: ['-p', 'tsconfig.json', '--watch', 'true', '--pretty', 'false'], - cwd: root - }; - }); - } - dispose() { - coc_nvim_1.disposeAll(this.disposables); - } -} -exports.default = WatchProject; -WatchProject.id = 'tsserver.watchBuild'; -WatchProject.startTexts = ['Starting compilation in watch mode', 'Starting incremental compilation']; - - -/***/ }), -/* 109 */ +/* 112 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -11683,128 +11428,281 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.OrganizeImportsCodeActionProvider = exports.OrganizeImportsCommand = void 0; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -const vscode_languageserver_protocol_1 = __webpack_require__(3); const coc_nvim_1 = __webpack_require__(1); -const typeConverters = __importStar(__webpack_require__(37)); -const api_1 = __importDefault(__webpack_require__(40)); -function getSymbolKind(item) { - switch (item.kind) { - case 'method': - return vscode_languageserver_protocol_1.SymbolKind.Method; - case 'enum': - return vscode_languageserver_protocol_1.SymbolKind.Enum; - case 'function': - return vscode_languageserver_protocol_1.SymbolKind.Function; - case 'class': - return vscode_languageserver_protocol_1.SymbolKind.Class; - case 'interface': - return vscode_languageserver_protocol_1.SymbolKind.Interface; - case 'var': - return vscode_languageserver_protocol_1.SymbolKind.Variable; - default: - return vscode_languageserver_protocol_1.SymbolKind.Variable; - } -} -class TypeScriptWorkspaceSymbolProvider { - constructor(client, languageIds) { - this.client = client; - this.languageIds = languageIds; +const vscode_languageserver_protocol_1 = __webpack_require__(3); +const typeconverts = __importStar(__webpack_require__(37)); +class OrganizeImportsCommand { + constructor(service) { + this.service = service; + this.id = 'tsserver.organizeImports'; } - provideWorkspaceSymbols(search, token) { - return __awaiter(this, void 0, void 0, function* () { - let filepath; - if (this.searchAllOpenProjects) { - filepath = undefined; - } - else { - let uri = this.getUri(); - filepath = uri ? this.client.toPath(uri) : undefined; - if (!filepath && this.client.apiVersion.lt(api_1.default.v390)) { - return []; + async _execute(client, document) { + let file = client.toPath(document.uri); + const args = { + scope: { + type: 'file', + args: { + file } } - const args = { - file: filepath, - searchValue: search, - maxResultCount: 256, - }; - const response = yield this.client.execute('navto', args, token); - if (response.type !== 'response' || response.body == null) - return []; - const result = []; - for (const item of response.body) { - if (!item.containerName && item.kind === 'alias') { - continue; - } - const label = TypeScriptWorkspaceSymbolProvider.getLabel(item); - const range = { - start: typeConverters.Position.fromLocation(item.start), - end: typeConverters.Position.fromLocation(item.end), - }; - const symbolInfo = vscode_languageserver_protocol_1.SymbolInformation.create(label, getSymbolKind(item), range, this.client.toResource(item.file)); - result.push(symbolInfo); + }; + const response = await client.interruptGetErr(() => client.execute('organizeImports', args, vscode_languageserver_protocol_1.CancellationToken.None)); + if (!response || response.type != 'response' || !response.success) { + return; + } + const edit = typeconverts.WorkspaceEdit.fromFileCodeEdits(client, response.body); + let keys = Object.keys(edit.changes); + if (keys.length == 1) { + let doc = coc_nvim_1.workspace.getDocument(keys[0]); + if (doc) { + await doc.applyEdits(edit.changes[keys[0]]); + return; } - return result; - }); - } - static getLabel(item) { - let label = item.name; - if (item.kind === 'method' || item.kind === 'function') { - label += '()'; } - return label; + if (edit) + await coc_nvim_1.workspace.applyEdit(edit); } - getUri() { - // typescript wants to have a resource even when asking - // general questions so we check the active editor. If this - // doesn't match we take the first TS document. - const documents = coc_nvim_1.workspace.textDocuments; - for (const document of documents) { - if (this.languageIds.indexOf(document.languageId) >= 0) { - return document.uri; + async execute(document) { + let client = await this.service.getClientHost(); + if (!document) { + let doc = await coc_nvim_1.workspace.document; + if (!doc.attached) { + throw new Error(`Document not attached.`); } + if (client.serviceClient.modeIds.indexOf(doc.filetype) == -1) { + throw new Error(`filetype "${doc.filetype}" not supported by tsserver.`); + } + document = doc.textDocument; } - return undefined; + await this._execute(client.serviceClient, document); } - get searchAllOpenProjects() { - return this.client.apiVersion.gte(api_1.default.v390) - && coc_nvim_1.workspace.getConfiguration('typescript').get('workspaceSymbols.scope', 'allOpenProjects') === 'allOpenProjects'; +} +exports.OrganizeImportsCommand = OrganizeImportsCommand; +class OrganizeImportsCodeActionProvider { + // public static readonly minVersion = API.v280 + constructor(client, fileConfigManager) { + this.client = client; + this.fileConfigManager = fileConfigManager; + this.metadata = { + providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports] + }; + } + async provideCodeActions(document, _range, context, token) { + if (this.client.modeIds.indexOf(document.languageId) == -1) + return; + if (!context.only || !context.only.includes(vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports)) { + return []; + } + await this.fileConfigManager.ensureConfigurationForDocument(document, token); + const action = vscode_languageserver_protocol_1.CodeAction.create('Organize Imports', { + title: '', + command: 'tsserver.organizeImports', + arguments: [document] + }, vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports); + return [action]; } } -exports.default = TypeScriptWorkspaceSymbolProvider; +exports.OrganizeImportsCodeActionProvider = OrganizeImportsCodeActionProvider; /***/ }), -/* 110 */ +/* 113 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +const coc_nvim_1 = __webpack_require__(1); +const vscode_languageserver_protocol_1 = __webpack_require__(3); +const api_1 = __importDefault(__webpack_require__(40)); +function objAreEqual(a, b) { + let keys = Object.keys(a); + for (let i = 0; i < keys.length; i++) { // tslint:disable-line + let key = keys[i]; + if (a[key] !== b[key]) { + return false; + } + } + return true; +} +class FileConfigurationManager { + constructor(client) { + this.client = client; + this.cachedMap = new Map(); + this.disposables = []; + coc_nvim_1.workspace.onDidCloseTextDocument(textDocument => { + // When a document gets closed delete the cached formatting options. + // This is necessary since the tsserver now closed a project when its + // last file in it closes which drops the stored formatting options + // as well. + this.cachedMap.delete(textDocument.uri); + }, undefined, this.disposables); + } + async ensureConfigurationOptions(document, insertSpaces, tabSize, token) { + const file = this.client.toPath(document.uri); + let options = { + tabSize, + insertSpaces + }; + let cachedOption = this.cachedMap.get(document.uri); + const currentOptions = this.getFileOptions(options, document); + if (cachedOption + && objAreEqual(cachedOption.formatOptions, currentOptions.formatOptions) + && objAreEqual(cachedOption.preferences, currentOptions.preferences)) + return; + this.cachedMap.set(document.uri, currentOptions); + const args = Object.assign({ file }, currentOptions); + await this.client.execute('configure', args, vscode_languageserver_protocol_1.CancellationToken.None); + try { + const response = await this.client.execute('configure', args, token); + if (response.type !== 'response') { + this.cachedMap.delete(document.uri); + } + } + catch (_e) { + this.cachedMap.delete(document.uri); + } + } + async ensureConfigurationForDocument(document, token) { + let opts = await coc_nvim_1.workspace.getFormatOptions(document.uri); + return this.ensureConfigurationOptions(document, opts.insertSpaces, opts.tabSize, token); + } + reset() { + this.cachedMap.clear(); + } + getLanguageConfiguration(languageId) { + return coc_nvim_1.workspace.getConfiguration(languageId); + } + isTypeScriptDocument(languageId) { + return languageId.startsWith('typescript'); + } + formatEnabled(document) { + let { languageId, uri } = document; + let language = languageId.startsWith('typescript') ? 'typescript' : 'javascript'; + const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri); + return config.get('enabled'); + } + enableJavascript() { + const config = coc_nvim_1.workspace.getConfiguration('tsserver'); + return !!config.get('enableJavascript'); + } + getFileOptions(options, document) { + const lang = this.isTypeScriptDocument(document.languageId) ? 'typescript' : 'javascript'; + return { + formatOptions: this.getFormatOptions(options, lang, document.uri), + preferences: this.getPreferences(lang, document.uri) + }; + } + getFormatOptions(options, language, uri) { + const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri); + return { + tabSize: options.tabSize, + indentSize: options.tabSize, + convertTabsToSpaces: options.insertSpaces, + // We can use \n here since the editor normalizes later on to its line endings. + newLineCharacter: '\n', + insertSpaceAfterCommaDelimiter: config.get('insertSpaceAfterCommaDelimiter'), + insertSpaceAfterConstructor: config.get('insertSpaceAfterConstructor'), + insertSpaceAfterSemicolonInForStatements: config.get('insertSpaceAfterSemicolonInForStatements'), + insertSpaceBeforeAndAfterBinaryOperators: config.get('insertSpaceBeforeAndAfterBinaryOperators'), + insertSpaceAfterKeywordsInControlFlowStatements: config.get('insertSpaceAfterKeywordsInControlFlowStatements'), + insertSpaceAfterFunctionKeywordForAnonymousFunctions: config.get('insertSpaceAfterFunctionKeywordForAnonymousFunctions'), + insertSpaceBeforeFunctionParenthesis: config.get('insertSpaceBeforeFunctionParenthesis'), + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis'), + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets'), + insertSpaceAfterOpeningAndBeforeClosingEmptyBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingEmptyBraces'), + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces'), + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces'), + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces'), + insertSpaceAfterTypeAssertion: config.get('insertSpaceAfterTypeAssertion'), + placeOpenBraceOnNewLineForFunctions: config.get('placeOpenBraceOnNewLineForFunctions'), + placeOpenBraceOnNewLineForControlBlocks: config.get('placeOpenBraceOnNewLineForControlBlocks'), + semicolons: config.get('semicolons', undefined) + }; + } + getCompleteOptions(languageId) { + const lang = this.isTypeScriptDocument(languageId) ? 'typescript' : 'javascript'; + const config = coc_nvim_1.workspace.getConfiguration(`${lang}.suggest`); + return { + enabled: config.get('enabled', true), + names: config.get('names', true), + paths: config.get('paths', true), + completeFunctionCalls: config.get('completeFunctionCalls', true), + autoImports: config.get('autoImports', true), + includeAutomaticOptionalChainCompletions: config.get('includeAutomaticOptionalChainCompletions', true) + }; + } + getPreferences(language, uri) { + if (this.client.apiVersion.lt(api_1.default.v290)) { + return {}; + } + const config = coc_nvim_1.workspace.getConfiguration(`${language}.preferences`, uri); + // getImportModuleSpecifierEndingPreference available on ts 2.9.0 + const preferences = { + quotePreference: this.getQuoteStyle(config), + importModuleSpecifierPreference: getImportModuleSpecifier(config), + importModuleSpecifierEnding: getImportModuleSpecifierEndingPreference(config), + allowTextChangesInNewFiles: uri.startsWith('file:'), + allowRenameOfImportPath: true, + providePrefixAndSuffixTextForRename: config.get('renameShorthandProperties', true) === false ? false : config.get('useAliasesForRenames', true), + }; + return preferences; + } + getQuoteStyle(config) { + let quoteStyle = config.get('quoteStyle', 'auto'); + if (this.client.apiVersion.gte(api_1.default.v333) || quoteStyle != 'auto') + return quoteStyle; + return 'single'; + } + dispose() { + coc_nvim_1.disposeAll(this.disposables); + } +} +exports.default = FileConfigurationManager; +function getImportModuleSpecifier(config) { + let val = config.get('importModuleSpecifier'); + switch (val) { + case 'relative': + return 'relative'; + case 'non-relative': + return 'non-relative'; + default: + return 'auto'; + } +} +function getImportModuleSpecifierEndingPreference(config) { + switch (config.get('importModuleSpecifierEnding')) { + case 'minimal': return 'minimal'; + case 'index': return 'index'; + case 'js': return 'js'; + default: return 'auto'; + } +} + + +/***/ }), +/* 114 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); @@ -11820,1539 +11718,1791 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const typeConverters = __importStar(__webpack_require__(37)); -class SmartSelection { - constructor(client) { - this.client = client; - } - provideSelectionRanges(document, positions, token) { - return __awaiter(this, void 0, void 0, function* () { - const file = this.client.toPath(document.uri); - if (!file) { - return undefined; - } - const args = { - file, - locations: positions.map(typeConverters.Position.toLocation) - }; - const response = yield this.client.execute('selectionRange', args, token); - if (response.type !== 'response' || !response.body) { - return undefined; - } - return response.body.map(SmartSelection.convertSelectionRange); - }); - } - static convertSelectionRange(selectionRange) { - return { - range: typeConverters.Range.fromTextSpan(selectionRange.textSpan), - parent: selectionRange.parent ? SmartSelection.convertSelectionRange(selectionRange.parent) : undefined, - }; - } -} -exports.default = SmartSelection; - - -/***/ }), -/* 111 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const coc_nvim_1 = __webpack_require__(1); +const fs_1 = __importDefault(__webpack_require__(102)); +const os_1 = __importDefault(__webpack_require__(14)); +const path_1 = __importDefault(__webpack_require__(13)); const vscode_languageserver_protocol_1 = __webpack_require__(3); -const modules_1 = __webpack_require__(112); -class InstallModuleCommand { - constructor() { - this.id = InstallModuleCommand.ID; +const fileSchemes = __importStar(__webpack_require__(115)); +const callbackMap_1 = __webpack_require__(116); +const bufferSyncSupport_1 = __importDefault(__webpack_require__(118)); +const diagnostics_1 = __webpack_require__(122); +const fileConfigurationManager_1 = __importDefault(__webpack_require__(113)); +const requestQueue_1 = __webpack_require__(123); +const typescriptService_1 = __webpack_require__(117); +const api_1 = __importDefault(__webpack_require__(40)); +const configuration_1 = __webpack_require__(124); +const logger_1 = __importDefault(__webpack_require__(129)); +const process_1 = __webpack_require__(131); +const tracer_1 = __importDefault(__webpack_require__(132)); +const tsconfig_1 = __webpack_require__(133); +const versionProvider_1 = __webpack_require__(134); +const versionStatus_1 = __importDefault(__webpack_require__(135)); +const wireProtocol_1 = __webpack_require__(136); +class ForkedTsServerProcess { + constructor(childProcess) { + this.childProcess = childProcess; + this.toCancelOnResourceChange = new Set(); } - execute(uri, name) { - return __awaiter(this, void 0, void 0, function* () { - yield modules_1.installModules(uri, [name]); - }); + onError(cb) { + this.childProcess.on('error', cb); } -} -InstallModuleCommand.ID = '_tsserver.installModule'; -class InstallModuleProvider { - constructor(client) { - this.client = client; - coc_nvim_1.commands.register(new InstallModuleCommand(), true); + onExit(cb) { + this.childProcess.on('exit', cb); } - provideCodeActions(document, _range, context, _token) { - return __awaiter(this, void 0, void 0, function* () { - const uri = coc_nvim_1.Uri.parse(document.uri); - if (uri.scheme != 'file') - return null; - let { diagnostics } = context; - let diags = diagnostics.filter(s => s.code == 2307); - let names = diags.map(o => { - let ms = o.message.match(/module\s'(.+)'\./); - return ms ? ms[1] : null; - }); - names = names.filter(s => s != null); - if (!names.length) - return null; - let actions = []; - for (let name of names) { - let title = `install ${name}`; - let command = { - title: `install ${name}`, - command: InstallModuleCommand.ID, - arguments: [document.uri, name] - }; - let codeAction = vscode_languageserver_protocol_1.CodeAction.create(title, command); - actions.push(codeAction); - } - return actions; - }); + write(serverRequest) { + this.childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8'); + } + createReader(callback, onError) { + // tslint:disable-next-line:no-unused-expression + new wireProtocol_1.Reader(this.childProcess.stdout, callback, onError); + } + kill() { + this.childProcess.kill(); } } -exports.default = InstallModuleProvider; - - -/***/ }), -/* 112 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.installModules = exports.distinct = exports.moduleExists = exports.runCommand = void 0; -const child_process_1 = __webpack_require__(113); -const path_1 = __importDefault(__webpack_require__(13)); -const coc_nvim_1 = __webpack_require__(1); -function runCommand(cmd, cwd, timeout) { - return new Promise((resolve, reject) => { - let timer; - if (timeout) { - timer = setTimeout(() => { - reject(new Error(`timeout after ${timeout}s`)); - }, timeout * 1000); - } - child_process_1.exec(cmd, { cwd }, (err, stdout) => { - if (timer) - clearTimeout(timer); - if (err) { - reject(new Error(`exited with ${err.code}`)); - return; - } - resolve(stdout); +class TypeScriptServiceClient { + constructor(pluginManager, modeIds) { + this.pluginManager = pluginManager; + this.modeIds = modeIds; + this.state = coc_nvim_1.ServiceStat.Initial; + this.logger = new logger_1.default(); + this.tsServerLogFile = null; + this.cancellationPipeName = null; + this._callbacks = new callbackMap_1.CallbackMap(); + this._requestQueue = new requestQueue_1.RequestQueue(); + this._pendingResponses = new Set(); + this._onTsServerStarted = new vscode_languageserver_protocol_1.Emitter(); + this._onProjectLanguageServiceStateChanged = new vscode_languageserver_protocol_1.Emitter(); + this._onDidBeginInstallTypings = new vscode_languageserver_protocol_1.Emitter(); + this._onDidEndInstallTypings = new vscode_languageserver_protocol_1.Emitter(); + this._onTypesInstallerInitializationFailed = new vscode_languageserver_protocol_1.Emitter(); + this.disposables = []; + this.isRestarting = false; + this._onDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter(); + this._onConfigDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter(); + this._onResendModelsRequested = new vscode_languageserver_protocol_1.Emitter(); + this.pathSeparator = path_1.default.sep; + this.lastStart = Date.now(); + this.servicePromise = null; + this.lastError = null; + this.numberRestarts = 0; + this.fileConfigurationManager = new fileConfigurationManager_1.default(this); + this._configuration = configuration_1.TypeScriptServiceConfiguration.loadFromWorkspace(); + this.versionProvider = new versionProvider_1.TypeScriptVersionProvider(this._configuration); + this._apiVersion = api_1.default.defaultVersion; + this.tracer = new tracer_1.default(this.logger); + this.versionStatus = new versionStatus_1.default(this.normalizePath.bind(this), this.fileConfigurationManager.enableJavascript()); + pluginManager.onDidUpdateConfig(update => { + this.configurePlugin(update.pluginId, update.config); + }, null, this.disposables); + pluginManager.onDidChangePlugins(() => { + this.restartTsServer(); + }, null, this.disposables); + this.bufferSyncSupport = new bufferSyncSupport_1.default(this, modeIds); + this.onTsServerStarted(() => { + this.bufferSyncSupport.listen(); }); - }); -} -exports.runCommand = runCommand; -function getManager() { - return __awaiter(this, void 0, void 0, function* () { - let res = yield coc_nvim_1.workspace.findUp(['yarn.lock', 'package-lock.json']); - if (!res) - return 'yarn'; - return res.endsWith('yarn.lock') ? 'yarn' : 'npm'; - }); -} -function getRoot() { - return __awaiter(this, void 0, void 0, function* () { - let res = yield coc_nvim_1.workspace.findUp(['package.json']); - if (!res) - return null; - return path_1.default.dirname(res); - }); -} -function moduleExists(name) { - return __awaiter(this, void 0, void 0, function* () { - try { - let content = yield runCommand(`npm info ${name} --json`, process.cwd()); - if (!content) - return false; - let obj = JSON.parse(content); - if (obj.error != null) - return false; - return true; + this.diagnosticsManager = new diagnostics_1.DiagnosticsManager(); + this.bufferSyncSupport.onDelete(resource => { + this.cancelInflightRequestsForResource(resource); + this.diagnosticsManager.delete(resource); + }, null, this.disposables); + this.bufferSyncSupport.onWillChange(resource => { + this.cancelInflightRequestsForResource(resource); + }); + } + get onDiagnosticsReceived() { + return this._onDiagnosticsReceived.event; + } + get onConfigDiagnosticsReceived() { + return this._onConfigDiagnosticsReceived.event; + } + get onResendModelsRequested() { + return this._onResendModelsRequested.event; + } + get configuration() { + return this._configuration; + } + dispose() { + if (this.servicePromise) { + this.servicePromise + .then(childProcess => { + childProcess.kill(); + }) + .then(undefined, () => void 0); } - catch (e) { - return false; + this.bufferSyncSupport.dispose(); + this.logger.dispose(); + this._onTsServerStarted.dispose(); + this._onResendModelsRequested.dispose(); + this.versionStatus.dispose(); + } + info(message, data) { + this.logger.info(message, data); + } + error(message, data) { + this.logger.error(message, data); + } + restartTsServer() { + const start = () => { + this.servicePromise = this.startService(true); + return this.servicePromise; + }; + if (this.servicePromise) { + return Promise.resolve(this.servicePromise.then(childProcess => { + this.state = coc_nvim_1.ServiceStat.Stopping; + this.info('Killing TS Server'); + this.isRestarting = true; + childProcess.kill(); + this.servicePromise = null; + }).then(start)); } - return false; - }); -} -exports.moduleExists = moduleExists; -/** - * Removes duplicates from the given array. The optional keyFn allows to specify - * how elements are checked for equalness by returning a unique string for each. - */ -function distinct(array, keyFn) { - if (!keyFn) { - return array.filter((element, position) => { - return array.indexOf(element) === position; + else { + return Promise.resolve(start()); + } + } + stop() { + if (!this.servicePromise) + return; + return new Promise((resolve, reject) => { + this.servicePromise.then(childProcess => { + if (this.state == coc_nvim_1.ServiceStat.Running) { + this.info('Killing TS Server'); + childProcess.onExit(() => { + resolve(); + }); + childProcess.kill(); + this.servicePromise = null; + } + else { + resolve(); + } + }, reject); }); } - const seen = Object.create(null); - return array.filter(elem => { - const key = keyFn(elem); - if (seen[key]) { - return false; + get onTsServerStarted() { + return this._onTsServerStarted.event; + } + get onProjectLanguageServiceStateChanged() { + return this._onProjectLanguageServiceStateChanged.event; + } + get onDidBeginInstallTypings() { + return this._onDidBeginInstallTypings.event; + } + get onDidEndInstallTypings() { + return this._onDidEndInstallTypings.event; + } + get onTypesInstallerInitializationFailed() { + return this._onTypesInstallerInitializationFailed.event; + } + get apiVersion() { + return this._apiVersion; + } + get tscPath() { + return this._tscPath; + } + service() { + if (this.servicePromise) { + return this.servicePromise; } - seen[key] = true; - return true; - }); -} -exports.distinct = distinct; -function installModules(uri, names) { - return __awaiter(this, void 0, void 0, function* () { - names = distinct(names); - let root = yield getRoot(); - if (!root) { - coc_nvim_1.workspace.showMessage(`package.json not found from cwd: ${coc_nvim_1.workspace.cwd}`, 'error'); - return; + if (this.lastError) { + return Promise.reject(this.lastError); } - let arr = names.concat(names.map(s => `@types/${s}`)); - let statusItem = coc_nvim_1.workspace.createStatusBarItem(99, { progress: true }); - statusItem.text = `Checking module ${arr.join(' ')}`; - statusItem.show(); - let exists = yield Promise.all(arr.map(name => { - return moduleExists(name).then(exists => { - return exists ? name : null; + return this.startService().then(() => { + if (this.servicePromise) { + return this.servicePromise; + } + }); + } + ensureServiceStarted() { + if (!this.servicePromise) { + this.startService().catch(err => { + coc_nvim_1.workspace.showMessage(`TSServer start failed: ${err.message}`, 'error'); + this.error(`Service start failed: ${err.stack}`); }); - })); - let manager = yield getManager(); - exists = exists.filter(s => s != null); - if (!exists.length) - return; - let devs = exists.filter(s => s.startsWith('@types')); - let deps = exists.filter(s => devs.indexOf(s) == -1); - statusItem.text = `Installing ${exists.join(' ')}`; - try { - yield Promise.all([deps, devs].map((names, i) => { - let cmd = manager == 'npm' ? `npm i ${names.join(' ')}` : `yarn add ${names.join(' ')} --ignore-scripts --no-default-rc`; - if (i == 1) - cmd = cmd + ' --dev'; - return runCommand(cmd, root); - })); } - catch (e) { - statusItem.dispose(); - coc_nvim_1.workspace.showMessage(`Install error ${e.message}`, 'error'); + } + async startService(resendModels = false) { + const { ignoreLocalTsserver } = this.configuration; + let currentVersion; + if (!ignoreLocalTsserver) + currentVersion = this.versionProvider.getLocalVersion(); + if (!currentVersion || !fs_1.default.existsSync(currentVersion.tsServerPath)) { + currentVersion = this.versionProvider.getDefaultVersion(); + } + if (!currentVersion || !currentVersion.isValid) { + if (this.configuration.globalTsdk) { + coc_nvim_1.workspace.showMessage(`Can not find typescript module, in 'tsserver.tsdk': ${this.configuration.globalTsdk}`, 'error'); + } + else { + coc_nvim_1.workspace.showMessage(`Can not find typescript module, run ':CocInstall coc-tsserver' to fix it!`, 'error'); + } return; } - statusItem.dispose(); - coc_nvim_1.workspace.showMessage(`Installed: ${exists.join(' ')}`, 'more'); - }); -} -exports.installModules = installModules; - - -/***/ }), -/* 113 */ -/***/ (function(module, exports) { - -module.exports = require("child_process"); - -/***/ }), -/* 114 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OrganizeImportsCodeActionProvider = exports.OrganizeImportsCommand = void 0; -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -const coc_nvim_1 = __webpack_require__(1); -const vscode_languageserver_protocol_1 = __webpack_require__(3); -const languageDescription_1 = __webpack_require__(115); -const languageModeIds_1 = __webpack_require__(116); -const typeconverts = __importStar(__webpack_require__(37)); -class OrganizeImportsCommand { - constructor(client) { - this.client = client; - this.id = 'tsserver.organizeImports'; + this._apiVersion = currentVersion.version; + this._tscPath = currentVersion.tscPath; + this.versionStatus.onDidChangeTypeScriptVersion(currentVersion); + this.lastError = null; + const tsServerForkArgs = await this.getTsServerArgs(currentVersion); + const debugPort = this._configuration.debugPort; + const maxTsServerMemory = this._configuration.maxTsServerMemory; + const options = { + execArgv: [ + ...(debugPort ? [`--inspect=${debugPort}`] : []), + ...(maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : []), + ], + cwd: coc_nvim_1.workspace.root + }; + this.servicePromise = this.startProcess(currentVersion, tsServerForkArgs, options, resendModels); + return this.servicePromise; } - getTextEdits(document) { - return __awaiter(this, void 0, void 0, function* () { - let client = this.client; - let file = client.toPath(document.uri); - const args = { - scope: { - type: 'file', - args: { - file + startProcess(currentVersion, args, options, resendModels) { + this.state = coc_nvim_1.ServiceStat.Starting; + return new Promise((resolve, reject) => { + try { + process_1.fork(currentVersion.tsServerPath, args, options, this.logger, (err, childProcess) => { + if (err || !childProcess) { + this.state = coc_nvim_1.ServiceStat.StartFailed; + this.lastError = err; + this.error('Starting TSServer failed with error.', err.stack); + return; } - } - }; - const response = yield this.client.interruptGetErr(() => this.client.execute('organizeImports', args, vscode_languageserver_protocol_1.CancellationToken.None)); - if (!response || response.type != 'response' || !response.success) { - return; + this.state = coc_nvim_1.ServiceStat.Running; + this.info('Started TSServer', JSON.stringify(currentVersion, null, 2)); + const handle = new ForkedTsServerProcess(childProcess); + this.tsServerProcess = handle; + this.lastStart = Date.now(); + handle.onError((err) => { + this.lastError = err; + this.error('TSServer errored with error.', err); + this.error(`TSServer log file: ${this.tsServerLogFile || ''}`); + coc_nvim_1.workspace.showMessage(`TSServer errored with error. ${err.message}`, 'error'); + this.serviceExited(false); + }); + handle.onExit((code) => { + if (code == null) { + this.info('TSServer normal exit'); + } + else { + this.error(`TSServer exited with code: ${code}`); + } + this.info(`TSServer log file: ${this.tsServerLogFile || ''}`); + this.serviceExited(!this.isRestarting); + this.isRestarting = false; + }); + handle.createReader(msg => { + this.dispatchMessage(msg); + }, error => { + this.error('ReaderError', error); + }); + resolve(handle); + this.serviceStarted(resendModels); + this._onTsServerStarted.fire(currentVersion.version); + }); } - const edit = typeconverts.WorkspaceEdit.fromFileCodeEdits(client, response.body); - let desc = languageDescription_1.standardLanguageDescriptions.find(o => o.modeIds.indexOf(document.languageId) !== -1); - if (!desc) - return null; - return edit; - }); - } - execute(document) { - return __awaiter(this, void 0, void 0, function* () { - if (!document) { - let doc = yield coc_nvim_1.workspace.document; - if (languageModeIds_1.languageIds.indexOf(doc.filetype) == -1) - return; - document = doc.textDocument; + catch (e) { + reject(e); } - let edit = yield this.getTextEdits(document); - if (edit) - yield coc_nvim_1.workspace.applyEdit(edit); - return; }); } -} -exports.OrganizeImportsCommand = OrganizeImportsCommand; -class OrganizeImportsCodeActionProvider { - // public static readonly minVersion = API.v280 - constructor(client, fileConfigManager) { - this.client = client; - this.fileConfigManager = fileConfigManager; - this.metadata = { - providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports] + async openTsServerLogFile() { + const isRoot = process.getuid && process.getuid() == 0; + let echoErr = (msg) => { + coc_nvim_1.workspace.showMessage(msg, 'error'); }; - } - provideCodeActions(document, _range, context, _token) { - if (languageModeIds_1.languageIds.indexOf(document.languageId) == -1) - return; - if (!context.only || !context.only.includes(vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports)) { - return []; + if (isRoot) { + echoErr('Log disabled for root user.'); + return false; + } + if (!this.apiVersion.gte(api_1.default.v222)) { + echoErr('TS Server logging requires TS 2.2.2+'); + return false; + } + if (this._configuration.tsServerLogLevel === configuration_1.TsServerLogLevel.Off) { + echoErr(`TS Server logging is off. Change 'tsserver.log' in 'coc-settings.json' to enable`); + return false; + } + if (!this.tsServerLogFile) { + echoErr('TS Server has not started logging.'); + return false; + } + try { + await coc_nvim_1.workspace.nvim.command(`edit ${this.tsServerLogFile}`); + return true; + } + catch (_a) { + echoErr('Could not open TS Server log file'); + return false; } - const action = vscode_languageserver_protocol_1.CodeAction.create('Organize Imports', { - title: '', - command: 'tsserver.organizeImports', - arguments: [document] - }, vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports); - return [action]; - } -} -exports.OrganizeImportsCodeActionProvider = OrganizeImportsCodeActionProvider; - - -/***/ }), -/* 115 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.standardLanguageDescriptions = void 0; -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -const languageModeIds = __importStar(__webpack_require__(116)); -exports.standardLanguageDescriptions = [ - { - id: 'typescript', - diagnosticSource: 'ts', - diagnosticOwner: 'typescript', - modeIds: [languageModeIds.typescript, languageModeIds.typescriptreact, - languageModeIds.typescripttsx, languageModeIds.typescriptjsx], - diagnosticLanguage: 1 /* TypeScript */, - configFile: 'tsconfig.json' - }, - { - id: 'javascript', - diagnosticSource: 'ts', - diagnosticOwner: 'typescript', - modeIds: [languageModeIds.javascript, languageModeIds.javascriptreact], - diagnosticLanguage: 0 /* JavaScript */, - configFile: 'jsconfig.json' - } -]; - - -/***/ }), -/* 116 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.languageIds = exports.jsxTags = exports.javascriptjsx = exports.javascriptreact = exports.javascript = exports.typescriptjsx = exports.typescripttsx = exports.typescriptreact = exports.typescript = void 0; -exports.typescript = 'typescript'; -exports.typescriptreact = 'typescriptreact'; -exports.typescripttsx = 'typescript.tsx'; -exports.typescriptjsx = 'typescript.jsx'; -exports.javascript = 'javascript'; -exports.javascriptreact = 'javascriptreact'; -exports.javascriptjsx = 'javascript.jsx'; -exports.jsxTags = 'jsx-tags'; -exports.languageIds = [exports.typescript, exports.typescriptreact, exports.javascript, exports.javascriptreact, exports.javascriptjsx, exports.typescripttsx, exports.jsxTags]; - - -/***/ }), -/* 117 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const fs_1 = __importDefault(__webpack_require__(118)); -const os_1 = __importDefault(__webpack_require__(14)); -const path_1 = __importDefault(__webpack_require__(13)); -const vscode_languageserver_protocol_1 = __webpack_require__(3); -const which_1 = __importDefault(__webpack_require__(119)); -const coc_nvim_1 = __webpack_require__(1); -const fileConfigurationManager_1 = __importDefault(__webpack_require__(93)); -const typescriptService_1 = __webpack_require__(123); -const api_1 = __importDefault(__webpack_require__(40)); -const configuration_1 = __webpack_require__(124); -const logger_1 = __importDefault(__webpack_require__(125)); -const process_1 = __webpack_require__(127); -const tracer_1 = __importDefault(__webpack_require__(128)); -const tsconfig_1 = __webpack_require__(129); -const versionProvider_1 = __webpack_require__(130); -const versionStatus_1 = __importDefault(__webpack_require__(131)); -const wireProtocol_1 = __webpack_require__(132); -const callbackMap_1 = __webpack_require__(133); -const requestQueue_1 = __webpack_require__(134); -const bufferSyncSupport_1 = __importDefault(__webpack_require__(135)); -const diagnostics_1 = __webpack_require__(137); -class ForkedTsServerProcess { - constructor(childProcess) { - this.childProcess = childProcess; - } - onError(cb) { - this.childProcess.on('error', cb); - } - onExit(cb) { - this.childProcess.on('exit', cb); } - write(serverRequest) { - this.childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8'); + serviceStarted(resendModels) { + this.bufferSyncSupport.reset(); + const watchOptions = this.apiVersion.gte(api_1.default.v380) + ? this.configuration.watchOptions + : undefined; + const configureOptions = { + hostInfo: 'coc-nvim', + preferences: { + providePrefixAndSuffixTextForRename: true, + allowRenameOfImportPath: true, + }, + watchOptions + }; + this.executeWithoutWaitingForResponse('configure', configureOptions); // tslint:disable-line + this.setCompilerOptionsForInferredProjects(this._configuration); + if (resendModels) { + this._onResendModelsRequested.fire(void 0); + this.fileConfigurationManager.reset(); + this.diagnosticsManager.reInitialize(); + this.bufferSyncSupport.reinitialize(); + } + // Reconfigure any plugins + for (const [config, pluginName] of this.pluginManager.configurations()) { + this.configurePlugin(config, pluginName); + } } - createReader(callback, onError) { - // tslint:disable-next-line:no-unused-expression - new wireProtocol_1.Reader(this.childProcess.stdout, callback, onError); + setCompilerOptionsForInferredProjects(configuration) { + if (!this.apiVersion.gte(api_1.default.v206)) + return; + const args = { + options: this.getCompilerOptionsForInferredProjects(configuration) + }; + this.executeWithoutWaitingForResponse('compilerOptionsForInferredProjects', args); // tslint:disable-line } - kill() { - this.childProcess.kill(); + getCompilerOptionsForInferredProjects(configuration) { + return Object.assign(Object.assign({}, tsconfig_1.inferredProjectConfig(configuration)), { allowJs: true, allowSyntheticDefaultImports: true, allowNonTsExtensions: true }); } -} -class TypeScriptServiceClient { - constructor(pluginManager) { - this.pluginManager = pluginManager; - this.state = coc_nvim_1.ServiceStat.Initial; - this.logger = new logger_1.default(); + serviceExited(restart) { + this.state = coc_nvim_1.ServiceStat.Stopped; + this.servicePromise = null; this.tsServerLogFile = null; - this.cancellationPipeName = null; + this._callbacks.destroy('Service died.'); this._callbacks = new callbackMap_1.CallbackMap(); this._requestQueue = new requestQueue_1.RequestQueue(); this._pendingResponses = new Set(); - this._onTsServerStarted = new vscode_languageserver_protocol_1.Emitter(); - this._onProjectLanguageServiceStateChanged = new vscode_languageserver_protocol_1.Emitter(); - this._onDidBeginInstallTypings = new vscode_languageserver_protocol_1.Emitter(); - this._onDidEndInstallTypings = new vscode_languageserver_protocol_1.Emitter(); - this._onTypesInstallerInitializationFailed = new vscode_languageserver_protocol_1.Emitter(); - this.disposables = []; - this.isRestarting = false; - this._onDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter(); - this._onConfigDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter(); - this._onResendModelsRequested = new vscode_languageserver_protocol_1.Emitter(); - this.pathSeparator = path_1.default.sep; - this.lastStart = Date.now(); - this.servicePromise = null; - this.lastError = null; - this.numberRestarts = 0; - this.fileConfigurationManager = new fileConfigurationManager_1.default(this); - this._configuration = configuration_1.TypeScriptServiceConfiguration.loadFromWorkspace(); - this.versionProvider = new versionProvider_1.TypeScriptVersionProvider(this._configuration); - this._apiVersion = api_1.default.defaultVersion; - this.tracer = new tracer_1.default(this.logger); - this.versionStatus = new versionStatus_1.default(this.normalizePath.bind(this), this.fileConfigurationManager.enableJavascript()); - pluginManager.onDidUpdateConfig(update => { - this.configurePlugin(update.pluginId, update.config); - }, null, this.disposables); - pluginManager.onDidChangePlugins(() => { - this.restartTsServer(); - }, null, this.disposables); - this.bufferSyncSupport = new bufferSyncSupport_1.default(this); - this.onTsServerStarted(() => { - this.bufferSyncSupport.listen(); - }); - this.diagnosticsManager = new diagnostics_1.DiagnosticsManager(); - this.bufferSyncSupport.onDelete(resource => { - this.diagnosticsManager.delete(resource); - }, null, this.disposables); - } - get onDiagnosticsReceived() { - return this._onDiagnosticsReceived.event; + if (restart) { + const diff = Date.now() - this.lastStart; + this.numberRestarts++; + let startService = true; + if (this.numberRestarts > 5) { + this.numberRestarts = 0; + if (diff < 10 * 1000 /* 10 seconds */) { + this.lastStart = Date.now(); + startService = false; + coc_nvim_1.workspace.showMessage('The TypeScript language service died 5 times right after it got started.', 'error'); // tslint:disable-line + } + else if (diff < 60 * 1000 /* 1 Minutes */) { + this.lastStart = Date.now(); + coc_nvim_1.workspace.showMessage('The TypeScript language service died unexpectedly 5 times in the last 5 Minutes.', 'error'); // tslint:disable-line + } + } + if (startService) { + this.startService(true); // tslint:disable-line + } + } } - get onConfigDiagnosticsReceived() { - return this._onConfigDiagnosticsReceived.event; + toPath(uri) { + return this.normalizePath(coc_nvim_1.Uri.parse(uri)); } - get onResendModelsRequested() { - return this._onResendModelsRequested.event; + toOpenedFilePath(uri, options = {}) { + if (!this.bufferSyncSupport.ensureHasBuffer(uri)) { + if (!options.suppressAlertOnFailure) { + console.error(`Unexpected resource ${uri}`); + } + return undefined; + } + return this.toPath(uri); } - get configuration() { - return this._configuration; + toResource(filepath) { + if (this._apiVersion.gte(api_1.default.v213)) { + if (filepath.startsWith('untitled:')) { + let resource = coc_nvim_1.Uri.parse(filepath); + if (this.inMemoryResourcePrefix) { + const dirName = path_1.default.dirname(resource.path); + const fileName = path_1.default.basename(resource.path); + if (fileName.startsWith(this.inMemoryResourcePrefix)) { + resource = resource.with({ path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length)) }); + } + } + return resource.toString(); + } + } + return coc_nvim_1.Uri.file(filepath).toString(); } - dispose() { - if (this.servicePromise) { - this.servicePromise - .then(childProcess => { - childProcess.kill(); - }) - .then(undefined, () => void 0); + normalizePath(resource) { + if (fileSchemes.disabledSchemes.has(resource.scheme)) { + return undefined; + } + switch (resource.scheme) { + case fileSchemes.file: { + let result = resource.fsPath; + if (!result) + return undefined; + result = path_1.default.normalize(result); + // Both \ and / must be escaped in regular expressions + return result.replace(new RegExp('\\' + this.pathSeparator, 'g'), '/'); + } + default: { + return this.inMemoryResourcePrefix + resource.toString(true); + } } - this.bufferSyncSupport.dispose(); - coc_nvim_1.disposeAll(this.disposables); - this.logger.dispose(); - this._onTsServerStarted.dispose(); - this._onResendModelsRequested.dispose(); - this.versionStatus.dispose(); } - info(message, data) { - this.logger.info(message, data); + get inMemoryResourcePrefix() { + return this._apiVersion.gte(api_1.default.v270) ? '^' : ''; } - error(message, data) { - this.logger.error(message, data); + asUrl(filepath) { + if (this._apiVersion.gte(api_1.default.v213)) { + if (filepath.startsWith('untitled:')) { + let resource = coc_nvim_1.Uri.parse(filepath); + if (this.inMemoryResourcePrefix) { + const dirName = path_1.default.dirname(resource.path); + const fileName = path_1.default.basename(resource.path); + if (fileName.startsWith(this.inMemoryResourcePrefix)) { + resource = resource.with({ + path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length)) + }); + } + } + return resource; + } + } + return coc_nvim_1.Uri.file(filepath); } - restartTsServer() { - const start = () => { - this.servicePromise = this.startService(true); - return this.servicePromise; - }; - if (this.servicePromise) { - return Promise.resolve(this.servicePromise.then(childProcess => { - this.state = coc_nvim_1.ServiceStat.Stopping; - this.info('Killing TS Server'); - this.isRestarting = true; - childProcess.kill(); - this.servicePromise = null; - }).then(start)); + execute(command, args, token, config) { + var _a; + let execution; + if (config === null || config === void 0 ? void 0 : config.cancelOnResourceChange) { + const source = new vscode_languageserver_protocol_1.CancellationTokenSource(); + token.onCancellationRequested(() => source.cancel()); + const inFlight = { + resource: config.cancelOnResourceChange, + cancel: () => source.cancel(), + }; + (_a = this.tsServerProcess) === null || _a === void 0 ? void 0 : _a.toCancelOnResourceChange.add(inFlight); + execution = this.executeImpl(command, args, Object.assign({ isAsync: false, token: source.token, expectsResult: true }, config)).finally(() => { + var _a; + (_a = this.tsServerProcess) === null || _a === void 0 ? void 0 : _a.toCancelOnResourceChange.delete(inFlight); + source.dispose(); + }); } else { - return Promise.resolve(start()); + execution = this.executeImpl(command, args, Object.assign({ isAsync: false, token, expectsResult: true }, config)); } + if (config === null || config === void 0 ? void 0 : config.nonRecoverable) { + execution.catch(err => this.fatalError(command, err)); + } + return execution; } - stop() { - if (!this.servicePromise) - return; - return new Promise((resolve, reject) => { - this.servicePromise.then(childProcess => { - if (this.state == coc_nvim_1.ServiceStat.Running) { - this.info('Killing TS Server'); - childProcess.onExit(() => { - resolve(); - }); - childProcess.kill(); - this.servicePromise = null; - } - else { - resolve(); - } - }, reject); - }); - } - get onTsServerStarted() { - return this._onTsServerStarted.event; - } - get onProjectLanguageServiceStateChanged() { - return this._onProjectLanguageServiceStateChanged.event; - } - get onDidBeginInstallTypings() { - return this._onDidBeginInstallTypings.event; - } - get onDidEndInstallTypings() { - return this._onDidEndInstallTypings.event; - } - get onTypesInstallerInitializationFailed() { - return this._onTypesInstallerInitializationFailed.event; + fatalError(command, error) { + console.error(`A non-recoverable error occured while executing tsserver command: ${command}`); + if (this.state === coc_nvim_1.ServiceStat.Running) { + this.info('Killing TS Server by fatal error:', error); + this.service().then(service => { + service.kill(); + }); + } } - get apiVersion() { - return this._apiVersion; + executeAsync(command, args, token) { + return this.executeImpl(command, args, { + isAsync: true, + token, + expectsResult: true + }); } - get tscPath() { - return this._tscPath; + executeWithoutWaitingForResponse(command, args) { + this.executeImpl(command, args, { + isAsync: false, + token: undefined, + expectsResult: false + }); } - service() { - if (this.servicePromise) { - return this.servicePromise; + executeImpl(command, args, executeInfo) { + if (this.servicePromise == null) { + return Promise.resolve(undefined); } - if (this.lastError) { - return Promise.reject(this.lastError); + this.bufferSyncSupport.beforeCommand(command); + const request = this._requestQueue.createRequest(command, args); + const requestInfo = { + request, + expectsResponse: executeInfo.expectsResult, + isAsync: executeInfo.isAsync, + queueingType: getQueueingType(command, executeInfo.lowPriority) + }; + let result; + if (executeInfo.expectsResult) { + result = new Promise((resolve, reject) => { + this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync); + if (executeInfo.token) { + executeInfo.token.onCancellationRequested(() => { + this.tryCancelRequest(request.seq, command); + }); + } + }).catch((err) => { + throw err; + }); } - return this.startService().then(() => { - if (this.servicePromise) { - return this.servicePromise; + this._requestQueue.enqueue(requestInfo); + this.sendNextRequests(); + return result; + } + sendNextRequests() { + while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) { + const item = this._requestQueue.dequeue(); + if (item) { + this.sendRequest(item); } - }); + } } - ensureServiceStarted() { - if (!this.servicePromise) { - this.startService().catch(err => { - coc_nvim_1.workspace.showMessage(`TSServer start failed: ${err.message}`, 'error'); - this.error(`Service start failed: ${err.stack}`); - }); + sendRequest(requestItem) { + const serverRequest = requestItem.request; + this.tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length); + if (requestItem.expectsResponse && !requestItem.isAsync) { + this._pendingResponses.add(requestItem.request.seq); } + this.service().then(childProcess => { + try { + childProcess.write(serverRequest); + } + catch (err) { + const callback = this.fetchCallback(serverRequest.seq); + if (callback) { + callback.onError(err); + } + } + }); } - startService(resendModels = false) { - return __awaiter(this, void 0, void 0, function* () { - const { ignoreLocalTsserver } = this.configuration; - let currentVersion; - if (!ignoreLocalTsserver) - currentVersion = this.versionProvider.getLocalVersion(); - if (!currentVersion || !fs_1.default.existsSync(currentVersion.tsServerPath)) { - currentVersion = this.versionProvider.getDefaultVersion(); + tryCancelRequest(seq, command) { + try { + if (this._requestQueue.tryDeletePendingRequest(seq)) { + this.tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`); + return true; } - if (!currentVersion || !currentVersion.isValid) { - if (this.configuration.globalTsdk) { - coc_nvim_1.workspace.showMessage(`Can not find typescript module, in 'tsserver.tsdk': ${this.configuration.globalTsdk}`, 'error'); + if (this.cancellationPipeName) { + this.tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`); + try { + fs_1.default.writeFileSync(this.cancellationPipeName + seq, ''); } - else { - coc_nvim_1.workspace.showMessage(`Can not find typescript module, run ':CocInstall coc-tsserver' to fix it!`, 'error'); + catch (_a) { + // noop } - return; + return true; } - this._apiVersion = currentVersion.version; - this._tscPath = currentVersion.tscPath; - this.versionStatus.onDidChangeTypeScriptVersion(currentVersion); - this.lastError = null; - const tsServerForkArgs = yield this.getTsServerArgs(); - const debugPort = this._configuration.debugPort; - const maxTsServerMemory = this._configuration.maxTsServerMemory; - const options = { - execArgv: [ - ...(debugPort ? [`--inspect=${debugPort}`] : []), - ...(maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : []), - ], - cwd: coc_nvim_1.workspace.root - }; - this.servicePromise = this.startProcess(currentVersion, tsServerForkArgs, options, resendModels); - return this.servicePromise; - }); + this.tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`); + return false; + } + finally { + const callback = this.fetchCallback(seq); + if (callback) { + callback.onSuccess(new typescriptService_1.ServerResponse.Cancelled(`Cancelled request ${seq} - ${command}`)); + } + } } - startProcess(currentVersion, args, options, resendModels) { - this.state = coc_nvim_1.ServiceStat.Starting; - return new Promise((resolve, reject) => { - try { - process_1.fork(currentVersion.tsServerPath, args, options, this.logger, (err, childProcess) => { - if (err || !childProcess) { - this.state = coc_nvim_1.ServiceStat.StartFailed; - this.lastError = err; - this.error('Starting TSServer failed with error.', err.stack); - return; - } - this.state = coc_nvim_1.ServiceStat.Running; - this.info('Started TSServer', JSON.stringify(currentVersion, null, 2)); - const handle = new ForkedTsServerProcess(childProcess); - this.lastStart = Date.now(); - handle.onError((err) => { - this.lastError = err; - this.error('TSServer errored with error.', err); - this.error(`TSServer log file: ${this.tsServerLogFile || ''}`); - coc_nvim_1.workspace.showMessage(`TSServer errored with error. ${err.message}`, 'error'); - this.serviceExited(false); - }); - handle.onExit((code) => { - if (code == null) { - this.info('TSServer normal exit'); - } - else { - this.error(`TSServer exited with code: ${code}`); + fetchCallback(seq) { + const callback = this._callbacks.fetch(seq); + if (!callback) { + return undefined; + } + this._pendingResponses.delete(seq); + return callback; + } + dispatchMessage(message) { + try { + switch (message.type) { + case 'response': + this.dispatchResponse(message); + break; + case 'event': + const event = message; + if (event.event === 'requestCompleted') { + const seq = event.body.request_seq; + const p = this._callbacks.fetch(seq); + if (p) { + this.tracer.traceRequestCompleted('requestCompleted', seq, p.startTime); + p.onSuccess(undefined); } - this.info(`TSServer log file: ${this.tsServerLogFile || ''}`); - this.serviceExited(!this.isRestarting); - this.isRestarting = false; - }); - handle.createReader(msg => { - this.dispatchMessage(msg); - }, error => { - this.error('ReaderError', error); - }); - resolve(handle); - this.serviceStarted(resendModels); - this._onTsServerStarted.fire(currentVersion.version); - }); - } - catch (e) { - reject(e); + } + else { + this.tracer.traceEvent(event); + this.dispatchEvent(event); + } + break; + default: + throw new Error(`Unknown message type ${message.type} received`); } - }); + } + finally { + this.sendNextRequests(); + } } - openTsServerLogFile() { - return __awaiter(this, void 0, void 0, function* () { - const isRoot = process.getuid && process.getuid() == 0; - let echoErr = (msg) => { - coc_nvim_1.workspace.showMessage(msg, 'error'); - }; - if (isRoot) { - echoErr('Log disabled for root user.'); - return false; + dispatchResponse(response) { + const callback = this.fetchCallback(response.request_seq); + if (!callback) { + return; + } + this.tracer.traceResponse(response, callback.startTime); + if (response.success) { + callback.onSuccess(response); + } + else if (response.message === 'No content available.') { + // Special case where response itself is successful but there is not any data to return. + callback.onSuccess(typescriptService_1.ServerResponse.NoContent); + } + else { + callback.onError(new Error(response.message)); + } + } + dispatchEvent(event) { + switch (event.event) { + case 'syntaxDiag': + case 'semanticDiag': + case 'suggestionDiag': + const diagnosticEvent = event; + if (diagnosticEvent.body && diagnosticEvent.body.diagnostics) { + this._onDiagnosticsReceived.fire({ + kind: getDiagnosticsKind(event), + resource: this.asUrl(diagnosticEvent.body.file), + diagnostics: diagnosticEvent.body.diagnostics + }); + } + break; + case 'configFileDiag': + this._onConfigDiagnosticsReceived.fire(event); + break; + case 'projectLanguageServiceState': + if (event.body) { + this._onProjectLanguageServiceStateChanged.fire(event.body); + } + break; + case 'beginInstallTypes': + if (event.body) { + this._onDidBeginInstallTypings.fire(event.body); + } + break; + case 'endInstallTypes': + if (event.body) { + this._onDidEndInstallTypings.fire(event.body); + } + break; + case 'projectsUpdatedInBackground': + const body = event.body; + const resources = body.openFiles.map(coc_nvim_1.Uri.file); + this.bufferSyncSupport.getErr(resources); + break; + case 'typesInstallerInitializationFailed': + if (event.body) { + this._onTypesInstallerInitializationFailed.fire(event.body); + } + break; + case 'projectLoadingStart': + this.versionStatus.loading = true; + break; + case 'projectLoadingFinish': + this.versionStatus.loading = false; + break; + } + } + async getTsServerArgs(currentVersion) { + const args = []; + args.push('--allowLocalPluginLoads'); + if (this.apiVersion.gte(api_1.default.v250)) { + args.push('--useInferredProjectPerProjectRoot'); + } + else { + args.push('--useSingleInferredProject'); + } + if (this.apiVersion.gte(api_1.default.v206) && this._configuration.disableAutomaticTypeAcquisition) { + args.push('--disableAutomaticTypingAcquisition'); + } + if (this.apiVersion.gte(api_1.default.v222)) { + this.cancellationPipeName = process_1.getTempFile(`tscancellation-${process_1.makeRandomHexString(20)}`); + args.push('--cancellationPipeName', this.cancellationPipeName + '*'); + } + if (this.apiVersion.gte(api_1.default.v222)) { + const isRoot = process.getuid && process.getuid() == 0; + if (this._configuration.tsServerLogLevel !== configuration_1.TsServerLogLevel.Off && !isRoot) { + const logDir = process_1.getTempDirectory(); + if (logDir) { + this.tsServerLogFile = path_1.default.join(logDir, `tsserver.log`); + this.info('TSServer log file :', this.tsServerLogFile); + } + else { + this.tsServerLogFile = null; + this.error('Could not create TSServer log directory'); + } + if (this.tsServerLogFile) { + args.push('--logVerbosity', configuration_1.TsServerLogLevel.toString(this._configuration.tsServerLogLevel)); + args.push('--logFile', this.tsServerLogFile); + } } - if (!this.apiVersion.gte(api_1.default.v222)) { - echoErr('TS Server logging requires TS 2.2.2+'); - return false; + } + if (this.apiVersion.gte(api_1.default.v230)) { + const pluginNames = this.pluginManager.plugins.map(x => x.name); + let pluginPaths = this._configuration.tsServerPluginPaths; + pluginPaths = pluginPaths.reduce((p, c) => { + if (path_1.default.isAbsolute(c)) { + p.push(c); + } + else { + let roots = coc_nvim_1.workspace.workspaceFolders.map(o => coc_nvim_1.Uri.parse(o.uri).fsPath); + p.push(...roots.map(r => path_1.default.join(r, c))); + } + return p; + }, []); + if (pluginNames.length) { + const isUsingBundledTypeScriptVersion = currentVersion.path == this.versionProvider.bundledVersion.path; + args.push('--globalPlugins', pluginNames.join(',')); + for (const plugin of this.pluginManager.plugins) { + if (isUsingBundledTypeScriptVersion || plugin.enableForWorkspaceTypeScriptVersions) { + pluginPaths.push(plugin.path); + } + } } - if (this._configuration.tsServerLogLevel === configuration_1.TsServerLogLevel.Off) { - echoErr(`TS Server logging is off. Change 'tsserver.log' in 'coc-settings.json' to enable`); - return false; + if (pluginPaths.length) { + args.push('--pluginProbeLocations', pluginPaths.join(',')); } - if (!this.tsServerLogFile) { - echoErr('TS Server has not started logging.'); - return false; + } + if (this._configuration.locale) { + args.push('--locale', this._configuration.locale); + } + if (this._configuration.typingsCacheLocation) { + args.push('--globalTypingsCacheLocation', `"${this._configuration.typingsCacheLocation}"`); + } + if (this.apiVersion.gte(api_1.default.v234)) { + let { npmLocation } = this._configuration; + if (npmLocation) { + this.logger.info(`using npm from ${npmLocation}`); + args.push('--npmLocation', `"${npmLocation}"`); } - try { - yield coc_nvim_1.workspace.nvim.command(`edit ${this.tsServerLogFile}`); - return true; + } + if (this.apiVersion.gte(api_1.default.v291)) { + args.push('--noGetErrOnBackgroundUpdate'); + } + if (this.apiVersion.gte(api_1.default.v345)) { + args.push('--validateDefaultNpmLocation'); + } + return args; + } + getProjectRootPath(uri) { + let root = coc_nvim_1.workspace.cwd; + let u = coc_nvim_1.Uri.parse(uri); + if (u.scheme !== 'file') + return undefined; + let folder = coc_nvim_1.workspace.getWorkspaceFolder(uri); + if (folder) { + root = coc_nvim_1.Uri.parse(folder.uri).fsPath; + } + else { + let filepath = coc_nvim_1.Uri.parse(uri).fsPath; + if (!filepath.startsWith(root)) { + root = path_1.default.dirname(filepath); } - catch (_a) { - echoErr('Could not open TS Server log file'); - return false; + } + if (root == os_1.default.homedir()) + return undefined; + return root; + } + configurePlugin(pluginName, configuration) { + if (this.apiVersion.gte(api_1.default.v314)) { + if (!this.servicePromise) + return; + this.servicePromise.then(() => { + // tslint:disable-next-line: no-floating-promises + this.executeWithoutWaitingForResponse('configurePlugin', { pluginName, configuration }); + }); + } + } + interruptGetErr(f) { + return this.bufferSyncSupport.interuptGetErr(f); + } + cancelInflightRequestsForResource(resource) { + if (this.state !== coc_nvim_1.ServiceStat.Running || !this.tsServerProcess) { + return; + } + for (const request of this.tsServerProcess.toCancelOnResourceChange) { + if (request.resource.toString() === resource.toString()) { + request.cancel(); } - }); + } } - serviceStarted(resendModels) { - const watchOptions = this.apiVersion.gte(api_1.default.v380) - ? this.configuration.watchOptions - : undefined; - const configureOptions = { - hostInfo: 'coc-nvim', - preferences: { - providePrefixAndSuffixTextForRename: true, - allowRenameOfImportPath: true, - }, - watchOptions - }; - this.executeWithoutWaitingForResponse('configure', configureOptions); // tslint:disable-line - this.setCompilerOptionsForInferredProjects(this._configuration); - if (resendModels) { - this._onResendModelsRequested.fire(void 0); - this.diagnosticsManager.reInitialize(); - this.bufferSyncSupport.reinitialize(); +} +exports.default = TypeScriptServiceClient; +function getDiagnosticsKind(event) { + switch (event.event) { + case 'syntaxDiag': + return diagnostics_1.DiagnosticKind.Syntax; + case 'semanticDiag': + return diagnostics_1.DiagnosticKind.Semantic; + case 'suggestionDiag': + return diagnostics_1.DiagnosticKind.Suggestion; + } + throw new Error('Unknown dignostics kind'); +} +const fenceCommands = new Set(['change', 'close', 'open']); +function getQueueingType(command, lowPriority) { + if (fenceCommands.has(command)) { + return requestQueue_1.RequestQueueingType.Fence; + } + return lowPriority ? requestQueue_1.RequestQueueingType.LowPriority : requestQueue_1.RequestQueueingType.Normal; +} + + +/***/ }), +/* 115 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.disabledSchemes = exports.semanticSupportedSchemes = exports.walkThroughSnippet = exports.vsls = exports.git = exports.untitled = exports.file = void 0; +exports.file = 'file'; +exports.untitled = 'untitled'; +exports.git = 'git'; +/** Live share scheme */ +exports.vsls = 'vsls'; +exports.walkThroughSnippet = 'walkThroughSnippet'; +exports.semanticSupportedSchemes = [ + exports.file, + exports.untitled, + exports.walkThroughSnippet, +]; +/** + * File scheme for which JS/TS language feature should be disabled + */ +exports.disabledSchemes = new Set([ + exports.git, + exports.vsls +]); + + +/***/ }), +/* 116 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CallbackMap = void 0; +const typescriptService_1 = __webpack_require__(117); +class CallbackMap { + constructor() { + this._callbacks = new Map(); + this._asyncCallbacks = new Map(); + } + destroy(cause) { + const cancellation = new typescriptService_1.ServerResponse.Cancelled(cause); + for (const callback of this._callbacks.values()) { + callback.onSuccess(cancellation); } - // Reconfigure any plugins - for (const [config, pluginName] of this.pluginManager.configurations()) { - this.configurePlugin(config, pluginName); + this._callbacks.clear(); + for (const callback of this._asyncCallbacks.values()) { + callback.onSuccess(cancellation); } + this._asyncCallbacks.clear(); } - setCompilerOptionsForInferredProjects(configuration) { - if (!this.apiVersion.gte(api_1.default.v206)) - return; - const args = { - options: this.getCompilerOptionsForInferredProjects(configuration) - }; - this.executeWithoutWaitingForResponse('compilerOptionsForInferredProjects', args); // tslint:disable-line + add(seq, callback, isAsync) { + if (isAsync) { + this._asyncCallbacks.set(seq, callback); + } + else { + this._callbacks.set(seq, callback); + } } - getCompilerOptionsForInferredProjects(configuration) { - return Object.assign(Object.assign({}, tsconfig_1.inferredProjectConfig(configuration)), { allowJs: true, allowSyntheticDefaultImports: true, allowNonTsExtensions: true }); + fetch(seq) { + const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq); + this.delete(seq); + return callback; } - serviceExited(restart) { - this.state = coc_nvim_1.ServiceStat.Stopped; - this.servicePromise = null; - this.tsServerLogFile = null; - this._callbacks.destroy('Service died.'); - this._callbacks = new callbackMap_1.CallbackMap(); - this._requestQueue = new requestQueue_1.RequestQueue(); - this._pendingResponses = new Set(); - if (restart) { - const diff = Date.now() - this.lastStart; - this.numberRestarts++; - let startService = true; - if (this.numberRestarts > 5) { - this.numberRestarts = 0; - if (diff < 10 * 1000 /* 10 seconds */) { - this.lastStart = Date.now(); - startService = false; - coc_nvim_1.workspace.showMessage('The TypeScript language service died 5 times right after it got started.', 'error'); // tslint:disable-line - } - else if (diff < 60 * 1000 /* 1 Minutes */) { - this.lastStart = Date.now(); - coc_nvim_1.workspace.showMessage('The TypeScript language service died unexpectedly 5 times in the last 5 Minutes.', 'error'); // tslint:disable-line - } - } - if (startService) { - this.startService(true); // tslint:disable-line - } + delete(seq) { + if (!this._callbacks.delete(seq)) { + this._asyncCallbacks.delete(seq); } } - toPath(uri) { - return this.normalizePath(coc_nvim_1.Uri.parse(uri)); +} +exports.CallbackMap = CallbackMap; + + +/***/ }), +/* 117 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExectuionTarget = exports.ServerResponse = void 0; +var ServerResponse; +(function (ServerResponse) { + class Cancelled { + constructor(reason) { + this.reason = reason; + this.type = 'cancelled'; + } + } + ServerResponse.Cancelled = Cancelled; + // tslint:disable-next-line: new-parens + ServerResponse.NoContent = new class { + constructor() { + this.type = 'noContent'; + } + }; +})(ServerResponse = exports.ServerResponse || (exports.ServerResponse = {})); +var ExectuionTarget; +(function (ExectuionTarget) { + ExectuionTarget[ExectuionTarget["Semantic"] = 0] = "Semantic"; + ExectuionTarget[ExectuionTarget["Syntax"] = 1] = "Syntax"; +})(ExectuionTarget = exports.ExectuionTarget || (exports.ExectuionTarget = {})); + + +/***/ }), +/* 118 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +const coc_nvim_1 = __webpack_require__(1); +const vscode_languageserver_protocol_1 = __webpack_require__(3); +const api_1 = __importDefault(__webpack_require__(40)); +const async_1 = __webpack_require__(119); +const typeConverters = __importStar(__webpack_require__(37)); +const languageModeIds_1 = __webpack_require__(120); +const resourceMap_1 = __webpack_require__(121); +class CloseOperation { + constructor(args) { + this.args = args; + this.type = 0 /* Close */; } - toResource(filepath) { - if (this._apiVersion.gte(api_1.default.v213)) { - if (filepath.startsWith('untitled:')) { - let resource = coc_nvim_1.Uri.parse(filepath); - if (this.inMemoryResourcePrefix) { - const dirName = path_1.default.dirname(resource.path); - const fileName = path_1.default.basename(resource.path); - if (fileName.startsWith(this.inMemoryResourcePrefix)) { - resource = resource.with({ path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length)) }); - } - } - return resource.toString(); - } - } - return coc_nvim_1.Uri.file(filepath).toString(); +} +class OpenOperation { + constructor(args) { + this.args = args; + this.type = 1 /* Open */; } - normalizePath(resource) { - if (this._apiVersion.gte(api_1.default.v213)) { - if (resource.scheme == 'untitled') { - const dirName = path_1.default.dirname(resource.path); - const fileName = this.inMemoryResourcePrefix + path_1.default.basename(resource.path); - return resource - .with({ path: path_1.default.posix.join(dirName, fileName) }) - .toString(true); - } - } - const result = resource.fsPath; - if (!result) - return null; - // Both \ and / must be escaped in regular expressions - return result.replace(new RegExp('\\' + this.pathSeparator, 'g'), '/'); +} +class ChangeOperation { + constructor(args) { + this.args = args; + this.type = 2 /* Change */; } - get inMemoryResourcePrefix() { - return this._apiVersion.gte(api_1.default.v270) ? '^' : ''; +} +class SyncedBuffer { + constructor(document, filepath, client, synchronizer) { + this.document = document; + this.filepath = filepath; + this.client = client; + this.synchronizer = synchronizer; + this.state = 1 /* Initial */; } - asUrl(filepath) { - if (this._apiVersion.gte(api_1.default.v213)) { - if (filepath.startsWith('untitled:')) { - let resource = coc_nvim_1.Uri.parse(filepath); - if (this.inMemoryResourcePrefix) { - const dirName = path_1.default.dirname(resource.path); - const fileName = path_1.default.basename(resource.path); - if (fileName.startsWith(this.inMemoryResourcePrefix)) { - resource = resource.with({ - path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length)) - }); - } - } - return resource; + open() { + const args = { + file: this.filepath, + fileContent: this.document.getText(), + projectRootPath: this.client.getProjectRootPath(this.document.uri), + }; + const scriptKind = languageModeIds_1.mode2ScriptKind(this.document.languageId); + if (scriptKind) { + args.scriptKindName = scriptKind; + } + if (this.client.apiVersion.gte(api_1.default.v240)) { + // plugin managed. + const tsPluginsForDocument = this.client.pluginManager.plugins + .filter(x => x.languages.indexOf(this.document.languageId) >= 0); + if (tsPluginsForDocument.length) { + args.plugins = tsPluginsForDocument.map(plugin => plugin.name); } } - return coc_nvim_1.Uri.file(filepath); - } - execute(command, args, token, lowPriority) { - return this.executeImpl(command, args, { - isAsync: false, - token, - expectsResult: true, - lowPriority - }); + this.synchronizer.open(this.resource, args); + this.state = 2 /* Open */; } - executeAsync(command, args, token) { - return this.executeImpl(command, args, { - isAsync: true, - token, - expectsResult: true - }); + get resource() { + return this.document.uri; } - executeWithoutWaitingForResponse(command, args) { - this.executeImpl(command, args, { - isAsync: false, - token: undefined, - expectsResult: false - }); + get lineCount() { + return this.document.lineCount; } - executeImpl(command, args, executeInfo) { - if (this.servicePromise == null) { - return Promise.resolve(undefined); - } - this.bufferSyncSupport.beforeCommand(command); - const request = this._requestQueue.createRequest(command, args); - const requestInfo = { - request, - expectsResponse: executeInfo.expectsResult, - isAsync: executeInfo.isAsync, - queueingType: getQueueingType(command, executeInfo.lowPriority) - }; - let result; - if (executeInfo.expectsResult) { - result = new Promise((resolve, reject) => { - this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync); - if (executeInfo.token) { - executeInfo.token.onCancellationRequested(() => { - this.tryCancelRequest(request.seq, command); - }); - } - }).catch((err) => { - throw err; - }); + get kind() { + if (this.document.languageId.startsWith('javascript')) { + return 2 /* JavaScript */; } - this._requestQueue.enqueue(requestInfo); - this.sendNextRequests(); - return result; + return 1 /* TypeScript */; } - sendNextRequests() { - while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) { - const item = this._requestQueue.dequeue(); - if (item) { - this.sendRequest(item); - } + /** + * @return Was the buffer open? + */ + close() { + if (this.state !== 2 /* Open */) { + this.state = 2 /* Closed */; + return false; } + this.state = 2 /* Closed */; + return this.synchronizer.close(this.resource, this.filepath); } - sendRequest(requestItem) { - const serverRequest = requestItem.request; - this.tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length); - if (requestItem.expectsResponse && !requestItem.isAsync) { - this._pendingResponses.add(requestItem.request.seq); + onContentChanged(events) { + if (this.state !== 2 /* Open */) { + console.error(`Unexpected buffer state: ${this.state}`); } - this.service().then(childProcess => { - try { - childProcess.write(serverRequest); - } - catch (err) { - const callback = this.fetchCallback(serverRequest.seq); - if (callback) { - callback.onError(err); - } - } - }); + this.synchronizer.change(this.resource, this.filepath, events); } - tryCancelRequest(seq, command) { - try { - if (this._requestQueue.tryDeletePendingRequest(seq)) { - this.tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`); - return true; - } - if (this.cancellationPipeName) { - this.tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`); - try { - fs_1.default.writeFileSync(this.cancellationPipeName + seq, ''); - } - catch (_a) { - // noop - } - return true; - } - this.tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`); - return false; - } - finally { - const callback = this.fetchCallback(seq); - if (callback) { - callback.onSuccess(new typescriptService_1.ServerResponse.Cancelled(`Cancelled request ${seq} - ${command}`)); - } +} +class SyncedBufferMap extends resourceMap_1.ResourceMap { + getForPath(filePath) { + return this.get(coc_nvim_1.Uri.file(filePath).toString()); + } + get allBuffers() { + return this.values; + } +} +class PendingDiagnostics extends resourceMap_1.ResourceMap { + getOrderedFileSet() { + const orderedResources = Array.from(this.entries) + .sort((a, b) => a.value - b.value) + .map(entry => entry.uri); + const map = new resourceMap_1.ResourceMap(this._normalizePath); + for (const resource of orderedResources) { + map.set(resource, undefined); } + return map; } - fetchCallback(seq) { - const callback = this._callbacks.fetch(seq); - if (!callback) { - return undefined; +} +/** + * Manages synchronization of buffers with the TS server. + * + * If supported, batches together file changes. This allows the TS server to more efficiently process changes. + */ +class BufferSynchronizer { + constructor(client, pathNormalizer) { + this.client = client; + this._pending = new resourceMap_1.ResourceMap(pathNormalizer); + } + open(resource, args) { + if (this.supportsBatching) { + this.updatePending(resource, new OpenOperation(args)); + } + else { + this.client.executeWithoutWaitingForResponse('open', args); } - this._pendingResponses.delete(seq); - return callback; } - dispatchMessage(message) { - try { - switch (message.type) { - case 'response': - this.dispatchResponse(message); - break; - case 'event': - const event = message; - if (event.event === 'requestCompleted') { - const seq = event.body.request_seq; - const p = this._callbacks.fetch(seq); - if (p) { - this.tracer.traceRequestCompleted('requestCompleted', seq, p.startTime); - p.onSuccess(undefined); - } - } - else { - this.tracer.traceEvent(event); - this.dispatchEvent(event); - } - break; - default: - throw new Error(`Unknown message type ${message.type} received`); - } + /** + * @return Was the buffer open? + */ + close(resource, filepath) { + if (this.supportsBatching) { + return this.updatePending(resource, new CloseOperation(filepath)); } - finally { - this.sendNextRequests(); + else { + const args = { file: filepath }; + this.client.executeWithoutWaitingForResponse('close', args); + return true; } } - dispatchResponse(response) { - const callback = this.fetchCallback(response.request_seq); - if (!callback) { + change(resource, filepath, events) { + if (!events.length) { return; } - this.tracer.traceResponse(response, callback.startTime); - if (response.success) { - callback.onSuccess(response); - } - else if (response.message === 'No content available.') { - // Special case where response itself is successful but there is not any data to return. - callback.onSuccess(typescriptService_1.ServerResponse.NoContent); + if (this.supportsBatching) { + this.updatePending(resource, new ChangeOperation({ + fileName: filepath, + textChanges: events.map((change) => ({ + newText: change.text, + start: typeConverters.Position.toLocation(change.range.start), + end: typeConverters.Position.toLocation(change.range.end), + })).reverse(), + })); } else { - callback.onError(new Error(response.message)); + for (const { range, text } of events) { + const args = Object.assign({ insertString: text }, typeConverters.Range.toFormattingRequestArgs(filepath, range)); + this.client.executeWithoutWaitingForResponse('change', args); + } } } - dispatchEvent(event) { - switch (event.event) { - case 'syntaxDiag': - case 'semanticDiag': - case 'suggestionDiag': - const diagnosticEvent = event; - if (diagnosticEvent.body && diagnosticEvent.body.diagnostics) { - this._onDiagnosticsReceived.fire({ - kind: getDiagnosticsKind(event), - resource: this.asUrl(diagnosticEvent.body.file), - diagnostics: diagnosticEvent.body.diagnostics - }); - } - break; - case 'configFileDiag': - this._onConfigDiagnosticsReceived.fire(event); - break; - case 'projectLanguageServiceState': - if (event.body) { - this._onProjectLanguageServiceStateChanged.fire(event.body); - } - break; - case 'beginInstallTypes': - if (event.body) { - this._onDidBeginInstallTypings.fire(event.body); - } - break; - case 'endInstallTypes': - if (event.body) { - this._onDidEndInstallTypings.fire(event.body); - } - break; - case 'projectsUpdatedInBackground': - const body = event.body; - const resources = body.openFiles.map(coc_nvim_1.Uri.file); - this.bufferSyncSupport.getErr(resources); - break; - case 'typesInstallerInitializationFailed': - if (event.body) { - this._onTypesInstallerInitializationFailed.fire(event.body); - } - break; - case 'projectLoadingStart': - this.versionStatus.loading = true; - break; - case 'projectLoadingFinish': - this.versionStatus.loading = false; - break; + reset() { + this._pending.clear(); + } + beforeCommand(command) { + if (command === 'updateOpen') { + return; } + this.flush(); } - getTsServerArgs() { - return __awaiter(this, void 0, void 0, function* () { - const args = []; - args.push('--allowLocalPluginLoads'); - if (this.apiVersion.gte(api_1.default.v250)) { - args.push('--useInferredProjectPerProjectRoot'); - } - else { - args.push('--useSingleInferredProject'); - } - if (this.apiVersion.gte(api_1.default.v206) && this._configuration.disableAutomaticTypeAcquisition) { - args.push('--disableAutomaticTypingAcquisition'); - } - if (this.apiVersion.gte(api_1.default.v222)) { - this.cancellationPipeName = process_1.getTempFile(`tscancellation-${process_1.makeRandomHexString(20)}`); - args.push('--cancellationPipeName', this.cancellationPipeName + '*'); - } - if (this.apiVersion.gte(api_1.default.v222)) { - const isRoot = process.getuid && process.getuid() == 0; - if (this._configuration.tsServerLogLevel !== configuration_1.TsServerLogLevel.Off && !isRoot) { - const logDir = process_1.getTempDirectory(); - if (logDir) { - this.tsServerLogFile = path_1.default.join(logDir, `tsserver.log`); - this.info('TSServer log file :', this.tsServerLogFile); - } - else { - this.tsServerLogFile = null; - this.error('Could not create TSServer log directory'); - } - if (this.tsServerLogFile) { - args.push('--logVerbosity', configuration_1.TsServerLogLevel.toString(this._configuration.tsServerLogLevel)); - args.push('--logFile', this.tsServerLogFile); - } - } - } - if (this.apiVersion.gte(api_1.default.v230)) { - const pluginNames = this.pluginManager.plugins.map(x => x.name); - const pluginRoot = this._configuration.tsServerPluginRoot; - const pluginPaths = pluginRoot ? [pluginRoot] : []; - if (pluginNames.length) { - args.push('--globalPlugins', pluginNames.join(',')); - for (const plugin of this.pluginManager.plugins) { - pluginPaths.push(plugin.path); - } - } - if (pluginPaths.length) { - args.push('--pluginProbeLocations', pluginPaths.join(',')); - } - } - if (this._configuration.typingsCacheLocation) { - args.push('--globalTypingsCacheLocation', `"${this._configuration.typingsCacheLocation}"`); - } - if (this.apiVersion.gte(api_1.default.v234)) { - if (this._configuration.npmLocation) { - args.push('--npmLocation', `"${this._configuration.npmLocation}"`); - } - else { - try { - args.push('--npmLocation', `"${which_1.default.sync('npm')}"`); - } - catch (e) { } // tslint:disable-line + flush() { + if (!this.supportsBatching) { + // We've already eagerly synchronized + this._pending.clear(); + return; + } + if (this._pending.size > 0) { + const closedFiles = []; + const openFiles = []; + const changedFiles = []; + for (const change of this._pending.values) { + switch (change.type) { + case 2 /* Change */: + changedFiles.push(change.args); + break; + case 1 /* Open */: + openFiles.push(change.args); + break; + case 0 /* Close */: + closedFiles.push(change.args); + break; } } - if (this.apiVersion.gte(api_1.default.v291)) { - args.push('--noGetErrOnBackgroundUpdate'); - } - if (this.apiVersion.gte(api_1.default.v345)) { - args.push('--validateDefaultNpmLocation'); - } - return args; - }); + this.client.execute('updateOpen', { changedFiles, closedFiles, openFiles }, vscode_languageserver_protocol_1.CancellationToken.None, { nonRecoverable: true }); + this._pending.clear(); + } } - getProjectRootPath(uri) { - let root = coc_nvim_1.workspace.cwd; - let u = coc_nvim_1.Uri.parse(uri); - if (u.scheme == 'file') { - let folder = coc_nvim_1.workspace.getWorkspaceFolder(uri); - if (folder) { - root = coc_nvim_1.Uri.parse(folder.uri).fsPath; - } - else { - let filepath = coc_nvim_1.Uri.parse(uri).fsPath; - if (!filepath.startsWith(root)) { - root = path_1.default.dirname(filepath); + get supportsBatching() { + return this.client.apiVersion.gte(api_1.default.v340); + } + updatePending(resource, op) { + switch (op.type) { + case 0 /* Close */: + const existing = this._pending.get(resource); + switch (existing === null || existing === void 0 ? void 0 : existing.type) { + case 1 /* Open */: + this._pending.delete(resource); + return false; // Open then close. No need to do anything } - } + break; } - if (root == os_1.default.homedir()) - return null; - return root; + if (this._pending.has(resource)) { + // we saw this file before, make sure we flush before working with it again + this.flush(); + } + this._pending.set(resource, op); + return true; } - configurePlugin(pluginName, configuration) { - if (this.apiVersion.gte(api_1.default.v314)) { - if (!this.servicePromise) +} +class GetErrRequest { + constructor(client, uris, _token, onDone) { + this.uris = uris; + this._token = _token; + this._done = false; + let files = uris.map(uri => client.normalizePath(uri)); + const args = { + delay: 0, + files + }; + const done = () => { + if (this._done) { return; - this.servicePromise.then(() => { - // tslint:disable-next-line: no-floating-promises - this.executeWithoutWaitingForResponse('configurePlugin', { pluginName, configuration }); - }); - } + } + this._done = true; + onDone(); + }; + client.executeAsync('geterr', args, _token.token).then(done, done); } - interruptGetErr(f) { - return this.bufferSyncSupport.interuptGetErr(f); + static executeGetErrRequest(client, uris, onDone) { + const token = new vscode_languageserver_protocol_1.CancellationTokenSource(); + return new GetErrRequest(client, uris, token, onDone); } -} -exports.default = TypeScriptServiceClient; -function getDiagnosticsKind(event) { - switch (event.event) { - case 'syntaxDiag': - return diagnostics_1.DiagnosticKind.Syntax; - case 'semanticDiag': - return diagnostics_1.DiagnosticKind.Semantic; - case 'suggestionDiag': - return diagnostics_1.DiagnosticKind.Suggestion; + cancel() { + if (!this._done) { + this._token.cancel(); + } + this._token.dispose(); } - throw new Error('Unknown dignostics kind'); } -const fenceCommands = new Set(['change', 'close', 'open']); -function getQueueingType(command, lowPriority) { - if (fenceCommands.has(command)) { - return requestQueue_1.RequestQueueingType.Fence; +class BufferSyncSupport { + constructor(client, modeIds) { + this.disposables = []; + this._validateJavaScript = true; + this._validateTypeScript = true; + this.listening = false; + this._onDelete = new vscode_languageserver_protocol_1.Emitter(); + this.onDelete = this._onDelete.event; + this._onWillChange = new vscode_languageserver_protocol_1.Emitter(); + this.onWillChange = this._onWillChange.event; + this.client = client; + this.modeIds = new Set(modeIds); + this.diagnosticDelayer = new async_1.Delayer(300); + const pathNormalizer = (path) => this.client.toPath(path); + this.syncedBuffers = new SyncedBufferMap(pathNormalizer); + this.pendingDiagnostics = new PendingDiagnostics(pathNormalizer); + this.synchronizer = new BufferSynchronizer(client, pathNormalizer); + this.updateConfiguration(); + coc_nvim_1.workspace.onDidChangeConfiguration(this.updateConfiguration, this, this.disposables); } - return lowPriority ? requestQueue_1.RequestQueueingType.LowPriority : requestQueue_1.RequestQueueingType.Normal; -} - - -/***/ }), -/* 118 */ -/***/ (function(module, exports) { - -module.exports = require("fs"); - -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { - -const isWindows = process.platform === 'win32' || - process.env.OSTYPE === 'cygwin' || - process.env.OSTYPE === 'msys' - -const path = __webpack_require__(13) -const COLON = isWindows ? ';' : ':' -const isexe = __webpack_require__(120) - -const getNotFoundError = (cmd) => - Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) - -const getPathInfo = (cmd, opt) => { - const colon = opt.colon || COLON - - // If it has a slash, then we don't bother searching the pathenv. - // just check the file itself, and that's it. - const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] - : ( - [ - // windows always checks the cwd first - ...(isWindows ? [process.cwd()] : []), - ...(opt.path || process.env.PATH || - /* istanbul ignore next: very unusual */ '').split(colon), - ] - ) - const pathExtExe = isWindows - ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' - : '' - const pathExt = isWindows ? pathExtExe.split(colon) : [''] - - if (isWindows) { - if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') - pathExt.unshift('') - } - - return { - pathEnv, - pathExt, - pathExtExe, - } -} - -const which = (cmd, opt, cb) => { - if (typeof opt === 'function') { - cb = opt - opt = {} - } - if (!opt) - opt = {} - - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) - const found = [] - - const step = i => new Promise((resolve, reject) => { - if (i === pathEnv.length) - return opt.all && found.length ? resolve(found) - : reject(getNotFoundError(cmd)) - - const ppRaw = pathEnv[i] - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw - - const pCmd = path.join(pathPart, cmd) - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd - - resolve(subStep(p, i, 0)) - }) - - const subStep = (p, i, ii) => new Promise((resolve, reject) => { - if (ii === pathExt.length) - return resolve(step(i + 1)) - const ext = pathExt[ii] - isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { - if (!er && is) { - if (opt.all) - found.push(p + ext) - else - return resolve(p + ext) - } - return resolve(subStep(p, i, ii + 1)) - }) - }) - - return cb ? step(0).then(res => cb(null, res), cb) : step(0) -} - -const whichSync = (cmd, opt) => { - opt = opt || {} - - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) - const found = [] - - for (let i = 0; i < pathEnv.length; i ++) { - const ppRaw = pathEnv[i] - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw - - const pCmd = path.join(pathPart, cmd) - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd - - for (let j = 0; j < pathExt.length; j ++) { - const cur = p + pathExt[j] - try { - const is = isexe.sync(cur, { pathExt: pathExtExe }) - if (is) { - if (opt.all) - found.push(cur) - else - return cur + listen() { + if (this.listening) { + return; + } + this.listening = true; + coc_nvim_1.workspace.onDidOpenTextDocument(this.openTextDocument, this, this.disposables); + coc_nvim_1.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, this.disposables); + coc_nvim_1.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, this.disposables); + coc_nvim_1.workspace.textDocuments.forEach(this.openTextDocument, this); + } + handles(resource) { + return this.syncedBuffers.has(resource); + } + dispose() { + this.pendingDiagnostics.clear(); + coc_nvim_1.disposeAll(this.disposables); + this._onWillChange.dispose(); + this._onDelete.dispose(); + } + ensureHasBuffer(resource) { + if (this.syncedBuffers.has(resource)) { + return true; + } + const existingDocument = coc_nvim_1.workspace.textDocuments.find(doc => doc.uri.toString() === resource); + if (existingDocument) { + return this.openTextDocument(existingDocument); + } + return false; + } + toResource(filePath) { + const buffer = this.syncedBuffers.getForPath(filePath); + if (buffer) + return buffer.resource; + return coc_nvim_1.Uri.file(filePath).toString(); + } + reset() { + var _a; + (_a = this.pendingGetErr) === null || _a === void 0 ? void 0 : _a.cancel(); + this.pendingDiagnostics.clear(); + this.synchronizer.reset(); + } + reinitialize() { + this.reset(); + for (const buffer of this.syncedBuffers.allBuffers) { + buffer.open(); + } + } + openTextDocument(document) { + if (!this.modeIds.has(document.languageId)) { + // can't handle + return false; + } + const resource = document.uri; + const filepath = this.client.normalizePath(coc_nvim_1.Uri.parse(resource)); + if (!filepath) { + return false; + } + if (this.syncedBuffers.has(resource)) { + return true; + } + const syncedBuffer = new SyncedBuffer(document, filepath, this.client, this.synchronizer); + this.syncedBuffers.set(resource, syncedBuffer); + syncedBuffer.open(); + this.requestDiagnostic(syncedBuffer); + return true; + } + closeResource(resource) { + const syncedBuffer = this.syncedBuffers.get(resource); + if (!syncedBuffer) { + return; + } + this.pendingDiagnostics.delete(resource); + this.syncedBuffers.delete(resource); + const wasBufferOpen = syncedBuffer.close(); + this._onDelete.fire(resource); + if (wasBufferOpen) { + this.requestAllDiagnostics(); + } + } + onDidCloseTextDocument(document) { + this.closeResource(document.uri); + } + onDidChangeTextDocument(e) { + const syncedBuffer = this.syncedBuffers.get(e.textDocument.uri); + if (!syncedBuffer) { + return; + } + this._onWillChange.fire(syncedBuffer.resource); + syncedBuffer.onContentChanged(e.contentChanges); + const didTrigger = this.requestDiagnostic(syncedBuffer); + if (!didTrigger && this.pendingGetErr) { + // In this case we always want to re-trigger all diagnostics + this.pendingGetErr.cancel(); + this.pendingGetErr = undefined; + this.triggerDiagnostics(); + } + } + beforeCommand(command) { + this.synchronizer.beforeCommand(command); + } + interuptGetErr(f) { + if (!this.pendingGetErr) { + return f(); + } + this.pendingGetErr.cancel(); + this.pendingGetErr = undefined; + const result = f(); + this.triggerDiagnostics(); + return result; + } + getErr(resources) { + const handledResources = resources.filter(resource => { + let syncedBuffer = this.syncedBuffers.get(resource.toString()); + return syncedBuffer && this.shouldValidate(syncedBuffer); + }); + if (!handledResources.length) { + return; + } + for (const resource of handledResources) { + this.pendingDiagnostics.set(resource.toString(), Date.now()); + } + this.triggerDiagnostics(); + } + triggerDiagnostics(delay = 200) { + this.diagnosticDelayer.trigger(() => { + this.sendPendingDiagnostics(); + }, delay); + } + requestAllDiagnostics() { + for (const buffer of this.syncedBuffers.allBuffers) { + if (this.shouldValidate(buffer)) { + this.pendingDiagnostics.set(buffer.resource, Date.now()); + } + } + this.triggerDiagnostics(); + } + requestDiagnostic(buffer) { + if (!this.shouldValidate(buffer)) { + return false; + } + this.pendingDiagnostics.set(buffer.resource, Date.now()); + const delay = Math.min(Math.max(Math.ceil(buffer.lineCount / 20), 300), 800); + this.triggerDiagnostics(delay); + return true; + } + hasPendingDiagnostics(uri) { + return this.pendingDiagnostics.has(uri); + } + sendPendingDiagnostics() { + const orderedFileSet = this.pendingDiagnostics.getOrderedFileSet(); + if (this.pendingGetErr) { + this.pendingGetErr.cancel(); + for (const uri of this.pendingGetErr.uris) { + let resource = uri.toString(); + let syncedBuffer = this.syncedBuffers.get(resource); + if (syncedBuffer && this.shouldValidate(syncedBuffer)) { + orderedFileSet.set(resource, undefined); + } + else { + orderedFileSet.delete(resource); + } + } + this.pendingGetErr = undefined; + } + // Add all open TS buffers to the geterr request. They might be visible + for (const buffer of this.syncedBuffers.values) { + if (this.shouldValidate(buffer)) { + orderedFileSet.set(buffer.resource, undefined); + } + } + if (orderedFileSet.size) { + let uris = Array.from(orderedFileSet.uris).map(uri => coc_nvim_1.Uri.parse(uri)); + const getErr = this.pendingGetErr = GetErrRequest.executeGetErrRequest(this.client, uris, () => { + if (this.pendingGetErr === getErr) { + this.pendingGetErr = undefined; + } + }); + } + this.pendingDiagnostics.clear(); + } + updateConfiguration() { + const jsConfig = coc_nvim_1.workspace.getConfiguration('javascript', null); + const tsConfig = coc_nvim_1.workspace.getConfiguration('typescript', null); + this._validateJavaScript = jsConfig.get('validate.enable', true); + this._validateTypeScript = tsConfig.get('validate.enable', true); + } + shouldValidate(buffer) { + switch (buffer.kind) { + case 2 /* JavaScript */: + return this._validateJavaScript; + case 1 /* TypeScript */: + default: + return this._validateTypeScript; } - } catch (ex) {} } - } - - if (opt.all && found.length) - return found - - if (opt.nothrow) - return null - - throw getNotFoundError(cmd) } - -module.exports = which -which.sync = whichSync +exports.default = BufferSyncSupport; /***/ }), -/* 120 */ +/* 119 */ /***/ (function(module, exports, __webpack_require__) { -var fs = __webpack_require__(118) -var core -if (process.platform === 'win32' || global.TESTING_WINDOWS) { - core = __webpack_require__(121) -} else { - core = __webpack_require__(122) -} - -module.exports = isexe -isexe.sync = sync - -function isexe (path, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} - } +"use strict"; - if (!cb) { - if (typeof Promise !== 'function') { - throw new TypeError('callback not provided') +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Delayer = void 0; +class Delayer { + constructor(defaultDelay) { + this.defaultDelay = defaultDelay; + this.timeout = null; + this.completionPromise = null; + this.onSuccess = null; + this.task = null; } - - return new Promise(function (resolve, reject) { - isexe(path, options || {}, function (er, is) { - if (er) { - reject(er) - } else { - resolve(is) + trigger(task, delay = this.defaultDelay) { + this.task = task; + if (delay >= 0) { + this.cancelTimeout(); } - }) - }) - } - - core(path, options || {}, function (er, is) { - // ignore EACCES because that just means we aren't allowed to run it - if (er) { - if (er.code === 'EACCES' || options && options.ignoreErrors) { - er = null - is = false - } + if (!this.completionPromise) { + this.completionPromise = new Promise(resolve => { + this.onSuccess = resolve; + }).then(() => { + this.completionPromise = null; + this.onSuccess = null; + let result = this.task && this.task(); + this.task = null; + return result; + }); + } + if (delay >= 0 || this.timeout === null) { + this.timeout = setTimeout(() => { + this.timeout = null; + if (this.onSuccess) { + this.onSuccess(undefined); + } + }, delay >= 0 ? delay : this.defaultDelay); + } + return this.completionPromise; } - cb(er, is) - }) -} - -function sync (path, options) { - // my kingdom for a filtered catch - try { - return core.sync(path, options || {}) - } catch (er) { - if (options && options.ignoreErrors || er.code === 'EACCES') { - return false - } else { - throw er + cancelTimeout() { + if (this.timeout !== null) { + clearTimeout(this.timeout); + this.timeout = null; + } } - } } +exports.Delayer = Delayer; /***/ }), -/* 121 */ +/* 120 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = isexe -isexe.sync = sync - -var fs = __webpack_require__(118) - -function checkPathExt (path, options) { - var pathext = options.pathExt !== undefined ? - options.pathExt : process.env.PATHEXT - - if (!pathext) { - return true - } - - pathext = pathext.split(';') - if (pathext.indexOf('') !== -1) { - return true - } - for (var i = 0; i < pathext.length; i++) { - var p = pathext[i].toLowerCase() - if (p && path.substr(-p.length).toLowerCase() === p) { - return true - } - } - return false -} - -function checkStat (stat, path, options) { - if (!stat.isSymbolicLink() && !stat.isFile()) { - return false - } - return checkPathExt(path, options) -} - -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, path, options)) - }) -} +"use strict"; -function sync (path, options) { - return checkStat(fs.statSync(path), path, options) +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.mode2ScriptKind = exports.languageIds = exports.jsxTags = exports.javascriptjsx = exports.javascriptreact = exports.javascript = exports.typescriptjsx = exports.typescripttsx = exports.typescriptreact = exports.typescript = void 0; +exports.typescript = 'typescript'; +exports.typescriptreact = 'typescriptreact'; +exports.typescripttsx = 'typescript.tsx'; +exports.typescriptjsx = 'typescript.jsx'; +exports.javascript = 'javascript'; +exports.javascriptreact = 'javascriptreact'; +exports.javascriptjsx = 'javascript.jsx'; +exports.jsxTags = 'jsx-tags'; +exports.languageIds = [exports.typescript, exports.typescriptreact, exports.javascript, exports.javascriptreact, exports.javascriptjsx, exports.typescripttsx, exports.jsxTags]; +function mode2ScriptKind(mode) { + switch (mode) { + case exports.typescript: + return 'TS'; + case exports.typescripttsx: + return 'TSX'; + case exports.typescriptjsx: + return 'TSX'; + case exports.typescriptreact: + return 'TSX'; + case exports.javascript: + return 'JS'; + case exports.javascriptreact: + return 'JSX'; + } + return undefined; } +exports.mode2ScriptKind = mode2ScriptKind; /***/ }), -/* 122 */ +/* 121 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = isexe -isexe.sync = sync - -var fs = __webpack_require__(118) +"use strict"; -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, options)) - }) +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isWindowsPath = exports.ResourceMap = void 0; +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +const coc_nvim_1 = __webpack_require__(1); +function defaultPathNormalizer(resource) { + let u = coc_nvim_1.Uri.parse(resource); + if (u.scheme === 'file') { + return u.fsPath; + } + return resource.toString(); } - -function sync (path, options) { - return checkStat(fs.statSync(path), options) +/** + * Maps of file uris + * + * Attempts to handle correct mapping on both case sensitive and case in-sensitive + * file systems. + */ +class ResourceMap { + constructor(_normalizePath = defaultPathNormalizer) { + this._normalizePath = _normalizePath; + this._map = new Map(); + } + get size() { + return this._map.size; + } + get entries() { + return this._map.values(); + } + has(uri) { + const file = this.toKey(uri); + return !!file && this._map.has(file); + } + get(uri) { + const file = this.toKey(uri); + if (!file) + return undefined; + let entry = this._map.get(file); + return entry ? entry.value : undefined; + } + set(uri, value) { + const file = this.toKey(uri); + if (file) { + this._map.set(file, { uri, value }); + } + } + delete(uri) { + const file = this.toKey(uri); + if (file) { + this._map.delete(file); + } + } + get values() { + return Array.from(this._map.values()).map(x => x.value); + } + get uris() { + return Array.from(this._map.values()).map(x => x.uri); + } + clear() { + this._map.clear(); + } + toKey(uri) { + const key = this._normalizePath + ? this._normalizePath(uri) + : uri; + if (!key) { + return key; + } + return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key; + } + isCaseInsensitivePath(path) { + if (isWindowsPath(path)) { + return true; + } + return path[0] === '/' && this.onIsCaseInsenitiveFileSystem; + } + get onIsCaseInsenitiveFileSystem() { + if (process.platform === 'win32') { + return true; + } + if (process.platform === 'darwin') { + return true; + } + return false; + } } - -function checkStat (stat, options) { - return stat.isFile() && checkMode(stat, options) +exports.ResourceMap = ResourceMap; +function isWindowsPath(path) { + return /^[a-zA-Z]:\\/.test(path); } +exports.isWindowsPath = isWindowsPath; -function checkMode (stat, options) { - var mod = stat.mode - var uid = stat.uid - var gid = stat.gid - - var myUid = options.uid !== undefined ? - options.uid : process.getuid && process.getuid() - var myGid = options.gid !== undefined ? - options.gid : process.getgid && process.getgid() - var u = parseInt('100', 8) - var g = parseInt('010', 8) - var o = parseInt('001', 8) - var ug = u | g +/***/ }), +/* 122 */ +/***/ (function(module, exports, __webpack_require__) { - var ret = (mod & o) || - (mod & g) && gid === myGid || - (mod & u) && uid === myUid || - (mod & ug) && myUid === 0 +"use strict"; - return ret +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DiagnosticsManager = exports.DiagnosticKind = exports.DiagnosticSet = void 0; +const coc_nvim_1 = __webpack_require__(1); +const resourceMap_1 = __webpack_require__(121); +class DiagnosticSet { + constructor() { + this._map = new resourceMap_1.ResourceMap(); + } + set(uri, diagnostics) { + this._map.set(uri, diagnostics); + } + get(uri) { + return this._map.get(uri) || []; + } + clear() { + this._map = new resourceMap_1.ResourceMap(); + } +} +exports.DiagnosticSet = DiagnosticSet; +var DiagnosticKind; +(function (DiagnosticKind) { + DiagnosticKind[DiagnosticKind["Syntax"] = 0] = "Syntax"; + DiagnosticKind[DiagnosticKind["Semantic"] = 1] = "Semantic"; + DiagnosticKind[DiagnosticKind["Suggestion"] = 2] = "Suggestion"; +})(DiagnosticKind = exports.DiagnosticKind || (exports.DiagnosticKind = {})); +const allDiagnosticKinds = [ + DiagnosticKind.Syntax, + DiagnosticKind.Semantic, + DiagnosticKind.Suggestion +]; +class DiagnosticsManager { + constructor() { + this._diagnostics = new Map(); + this._pendingUpdates = new resourceMap_1.ResourceMap(); + this._enableJavascriptSuggestions = true; + this._enableTypescriptSuggestions = true; + this.updateDelay = 200; + for (const kind of allDiagnosticKinds) { + this._diagnostics.set(kind, new DiagnosticSet()); + } + this._currentDiagnostics = coc_nvim_1.languages.createDiagnosticCollection('tsserver'); + } + dispose() { + this._currentDiagnostics.dispose(); + for (const value of this._pendingUpdates.values) { + clearTimeout(value); + } + this._pendingUpdates = new resourceMap_1.ResourceMap(); + } + reInitialize() { + this._currentDiagnostics.clear(); + for (const diagnosticSet of this._diagnostics.values()) { + diagnosticSet.clear(); + } + } + setEnableSuggestions(languageId, value) { + let curr = languageId == 'javascript' ? this._enableJavascriptSuggestions : this._enableTypescriptSuggestions; + if (curr == value) { + return; + } + if (languageId == 'javascript') { + this._enableJavascriptSuggestions = value; + } + else { + this._enableTypescriptSuggestions = value; + } + } + diagnosticsReceived(kind, uri, diagnostics) { + const collection = this._diagnostics.get(kind); + if (!collection) + return; + let doc = coc_nvim_1.workspace.getDocument(uri); + if (doc) + uri = doc.uri; + if (diagnostics.length === 0) { + const existing = collection.get(uri); + if (existing.length === 0) { + // No need to update + return; + } + } + collection.set(uri, diagnostics); + this.scheduleDiagnosticsUpdate(uri); + } + configFileDiagnosticsReceived(uri, diagnostics) { + this._currentDiagnostics.set(uri, diagnostics); + } + delete(uri) { + this._currentDiagnostics.delete(uri); + } + getDiagnostics(uri) { + return this._currentDiagnostics.get(uri) || []; + return []; + } + scheduleDiagnosticsUpdate(uri) { + if (!this._pendingUpdates.has(uri)) { + this._pendingUpdates.set(uri, setTimeout(() => this.updateCurrentDiagnostics(uri), this.updateDelay)); + } + } + updateCurrentDiagnostics(uri) { + if (this._pendingUpdates.has(uri)) { + clearTimeout(this._pendingUpdates.get(uri)); + this._pendingUpdates.delete(uri); + } + const allDiagnostics = [ + ...this._diagnostics.get(DiagnosticKind.Syntax).get(uri), + ...this._diagnostics.get(DiagnosticKind.Semantic).get(uri), + ...this.getSuggestionDiagnostics(uri) + ]; + this._currentDiagnostics.set(uri, allDiagnostics); + } + getSuggestionDiagnostics(uri) { + const enabled = this.suggestionsEnabled(uri); + return this._diagnostics + .get(DiagnosticKind.Suggestion) + .get(uri) + .filter(x => { + if (!enabled) { + // Still show unused + return x.code == 6133; + } + return enabled; + }); + } + suggestionsEnabled(uri) { + let doc = coc_nvim_1.workspace.getDocument(uri); + if (!doc) + return false; + if (doc.filetype.startsWith('javascript')) { + return this._enableJavascriptSuggestions; + } + if (doc.filetype.startsWith('typescript')) { + return this._enableTypescriptSuggestions; + } + return true; + } } +exports.DiagnosticsManager = DiagnosticsManager; /***/ }), @@ -13361,24 +13511,76 @@ function checkMode (stat, options) { "use strict"; +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); -exports.ServerResponse = void 0; -var ServerResponse; -(function (ServerResponse) { - class Cancelled { - constructor(reason) { - this.reason = reason; - this.type = 'cancelled'; +exports.RequestQueue = exports.RequestQueueingType = void 0; +var RequestQueueingType; +(function (RequestQueueingType) { + /** + * Normal request that is executed in order. + */ + RequestQueueingType[RequestQueueingType["Normal"] = 1] = "Normal"; + /** + * Request that normal requests jump in front of in the queue. + */ + RequestQueueingType[RequestQueueingType["LowPriority"] = 2] = "LowPriority"; + /** + * A fence that blocks request reordering. + * + * Fences are not reordered. Unlike a normal request, a fence will never jump in front of a low priority request + * in the request queue. + */ + RequestQueueingType[RequestQueueingType["Fence"] = 3] = "Fence"; +})(RequestQueueingType = exports.RequestQueueingType || (exports.RequestQueueingType = {})); +class RequestQueue { + constructor() { + this.queue = []; + this.sequenceNumber = 0; + } + get length() { + return this.queue.length; + } + enqueue(item) { + if (item.queueingType === RequestQueueingType.Normal) { + let index = this.queue.length - 1; + while (index >= 0) { + if (this.queue[index].queueingType !== RequestQueueingType.LowPriority) { + break; + } + --index; + } + this.queue.splice(index + 1, 0, item); + } + else { + // Only normal priority requests can be reordered. All other requests just go to the end. + this.queue.push(item); } } - ServerResponse.Cancelled = Cancelled; - // tslint:disable-next-line: new-parens - ServerResponse.NoContent = new class { - constructor() { - this.type = 'noContent'; + dequeue() { + return this.queue.shift(); + } + tryDeletePendingRequest(seq) { + for (let i = 0; i < this.queue.length; i++) { + if (this.queue[i].request.seq === seq) { + this.queue.splice(i, 1); + return true; + } } - }; -})(ServerResponse = exports.ServerResponse || (exports.ServerResponse = {})); + return false; + } + createRequest(command, args) { + return { + seq: this.sequenceNumber++, + type: 'request', + command, + arguments: args + }; + } +} +exports.RequestQueue = RequestQueue; /***/ }), @@ -13393,7 +13595,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { Object.defineProperty(exports, "__esModule", { value: true }); exports.TypeScriptServiceConfiguration = exports.TsServerLogLevel = void 0; const coc_nvim_1 = __webpack_require__(1); -const which_1 = __importDefault(__webpack_require__(119)); +const which_1 = __importDefault(__webpack_require__(125)); var TsServerLogLevel; (function (TsServerLogLevel) { TsServerLogLevel[TsServerLogLevel["Off"] = 0] = "Off"; @@ -13457,8 +13659,8 @@ class TypeScriptServiceConfiguration { get typingsCacheLocation() { return this._configuration.get('typingsCacheLocation', ''); } - get tsServerPluginRoot() { - return this._configuration.get('tsServerPluginRoot', null); + get tsServerPluginPaths() { + return this._configuration.get('pluginPaths', []); } get checkJs() { return this._configuration.get('implicitProjectConfig.checkJs', false); @@ -13481,7 +13683,7 @@ class TypeScriptServiceConfiguration { get npmLocation() { let path = this._configuration.get('npm', ''); if (path) - return path; + return coc_nvim_1.workspace.expand(path); try { path = which_1.default.sync('npm'); } @@ -13501,1165 +13703,829 @@ exports.TypeScriptServiceConfiguration = TypeScriptServiceConfiguration; /* 125 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +const isWindows = process.platform === 'win32' || + process.env.OSTYPE === 'cygwin' || + process.env.OSTYPE === 'msys' -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const coc_nvim_1 = __webpack_require__(1); -const is = __importStar(__webpack_require__(126)); -class Logger { - get output() { - if (this._channel) { - return this._channel; - } - this._channel = coc_nvim_1.workspace.createOutputChannel('tsserver'); - return this._channel; - } - dispose() { - if (this._channel) { - this._channel.dispose(); - } - } - data2String(data) { - if (data instanceof Error) { - if (is.string(data.stack)) { - return data.stack; - } - return data.message; - } - if (is.boolean(data.success) && !data.success && is.string(data.message)) { - return data.message; - } - if (is.string(data)) { - return data; - } - return data.toString(); - } - info(message, data) { - this.logLevel('Info', message, data); - } - warn(message, data) { - this.logLevel('Warn', message, data); - } - error(message, data) { - // See https://github.com/Microsoft/TypeScript/issues/10496 - if (data && data.message === 'No content available.') { - return; - } - this.logLevel('Error', message, data); - } - logLevel(level, message, data) { - this.output.appendLine(`[${level} - ${new Date().toLocaleTimeString()}] ${message}`); - if (data) { - this.output.appendLine(this.data2String(data)); - } - } -} -exports.default = Logger; +const path = __webpack_require__(13) +const COLON = isWindows ? ';' : ':' +const isexe = __webpack_require__(126) +const getNotFoundError = (cmd) => + Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) -/***/ }), -/* 126 */ -/***/ (function(module, exports, __webpack_require__) { +const getPathInfo = (cmd, opt) => { + const colon = opt.colon || COLON -"use strict"; + // If it has a slash, then we don't bother searching the pathenv. + // just check the file itself, and that's it. + const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] + : ( + [ + // windows always checks the cwd first + ...(isWindows ? [process.cwd()] : []), + ...(opt.path || process.env.PATH || + /* istanbul ignore next: very unusual */ '').split(colon), + ] + ) + const pathExtExe = isWindows + ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' + : '' + const pathExt = isWindows ? pathExtExe.split(colon) : [''] -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.string = exports.boolean = exports.defined = void 0; -const toString = Object.prototype.toString; -function defined(value) { - return typeof value !== 'undefined'; -} -exports.defined = defined; -function boolean(value) { - return value === true || value === false; + if (isWindows) { + if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') + pathExt.unshift('') + } + + return { + pathEnv, + pathExt, + pathExtExe, + } } -exports.boolean = boolean; -function string(value) { - return toString.call(value) === '[object String]'; + +const which = (cmd, opt, cb) => { + if (typeof opt === 'function') { + cb = opt + opt = {} + } + if (!opt) + opt = {} + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) + const found = [] + + const step = i => new Promise((resolve, reject) => { + if (i === pathEnv.length) + return opt.all && found.length ? resolve(found) + : reject(getNotFoundError(cmd)) + + const ppRaw = pathEnv[i] + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw + + const pCmd = path.join(pathPart, cmd) + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd + + resolve(subStep(p, i, 0)) + }) + + const subStep = (p, i, ii) => new Promise((resolve, reject) => { + if (ii === pathExt.length) + return resolve(step(i + 1)) + const ext = pathExt[ii] + isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { + if (!er && is) { + if (opt.all) + found.push(p + ext) + else + return resolve(p + ext) + } + return resolve(subStep(p, i, ii + 1)) + }) + }) + + return cb ? step(0).then(res => cb(null, res), cb) : step(0) } -exports.string = string; +const whichSync = (cmd, opt) => { + opt = opt || {} + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) + const found = [] + + for (let i = 0; i < pathEnv.length; i ++) { + const ppRaw = pathEnv[i] + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw + + const pCmd = path.join(pathPart, cmd) + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd + + for (let j = 0; j < pathExt.length; j ++) { + const cur = p + pathExt[j] + try { + const is = isexe.sync(cur, { pathExt: pathExtExe }) + if (is) { + if (opt.all) + found.push(cur) + else + return cur + } + } catch (ex) {} + } + } -/***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { + if (opt.all && found.length) + return found -"use strict"; + if (opt.nothrow) + return null -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fork = exports.getTempFile = exports.getTempDirectory = exports.makeRandomHexString = void 0; -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -const child_process_1 = __importDefault(__webpack_require__(113)); -const net_1 = __importDefault(__webpack_require__(16)); -const os_1 = __importDefault(__webpack_require__(14)); -const path_1 = __importDefault(__webpack_require__(13)); -const fs_1 = __importDefault(__webpack_require__(118)); -function makeRandomHexString(length) { - let chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; - let result = ''; - for (let i = 0; i < length; i++) { - const idx = Math.floor(chars.length * Math.random()); - result += chars[idx]; - } - return result; -} -exports.makeRandomHexString = makeRandomHexString; -function getTempDirectory() { - let dir = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`); - if (!fs_1.default.existsSync(dir)) { - fs_1.default.mkdirSync(dir); - } - return dir; -} -exports.getTempDirectory = getTempDirectory; -function generatePipeName() { - return getPipeName(makeRandomHexString(40)); -} -function getPipeName(name) { - const fullName = 'coc-tsc-' + name; - if (process.platform === 'win32') { - return '\\\\.\\pipe\\' + fullName + '-sock'; - } - const tmpdir = getTempDirectory(); - // Mac/Unix: use socket file - return path_1.default.join(tmpdir, fullName + '.sock'); -} -function getTempFile(name) { - const fullName = 'coc-nvim-' + name; - return path_1.default.join(getTempDirectory(), fullName + '.sock'); -} -exports.getTempFile = getTempFile; -function generatePatchedEnv(env, stdInPipeName, stdOutPipeName, stdErrPipeName) { - const newEnv = Object.assign({}, env); - // Set the two unique pipe names and the electron flag as process env - newEnv['STDIN_PIPE_NAME'] = stdInPipeName; // tslint:disable-line - newEnv['STDOUT_PIPE_NAME'] = stdOutPipeName; // tslint:disable-line - newEnv['STDERR_PIPE_NAME'] = stdErrPipeName; // tslint:disable-line - newEnv['TSS_LOG'] = `-level verbose -file ${path_1.default.join(os_1.default.tmpdir(), 'coc-nvim-tsc.log')}`; // tslint:disable-line - // Ensure we always have a PATH set - newEnv['PATH'] = newEnv['PATH'] || process.env.PATH; // tslint:disable-line - return newEnv; -} -function fork(modulePath, args, options, logger, callback) { - let callbackCalled = false; - const resolve = (result) => { - if (callbackCalled) { - return; - } - callbackCalled = true; - callback(null, result); - }; - const reject = (err) => { - if (callbackCalled) { - return; - } - callbackCalled = true; - callback(err, null); - }; - // Generate three unique pipe names - const stdInPipeName = generatePipeName(); - const stdOutPipeName = generatePipeName(); - const stdErrPipeName = generatePipeName(); - const newEnv = generatePatchedEnv(process.env, stdInPipeName, stdOutPipeName, stdErrPipeName); - newEnv['NODE_PATH'] = path_1.default.join(modulePath, '..', '..', '..'); // tslint:disable-line - let childProcess; - // Begin listening to stderr pipe - let stdErrServer = net_1.default.createServer(stdErrStream => { - // From now on the childProcess.stderr is available for reading - childProcess.stderr = stdErrStream; - }); - stdErrServer.listen(stdErrPipeName); - // Begin listening to stdout pipe - let stdOutServer = net_1.default.createServer(stdOutStream => { - // The child process will write exactly one chunk with content `ready` when it has installed a listener to the stdin pipe - stdOutStream.once('data', (_chunk) => { - // The child process is sending me the `ready` chunk, time to connect to the stdin pipe - childProcess.stdin = net_1.default.connect(stdInPipeName); - // From now on the childProcess.stdout is available for reading - childProcess.stdout = stdOutStream; - resolve(childProcess); - }); - }); - stdOutServer.listen(stdOutPipeName); - let serverClosed = false; - const closeServer = () => { - if (serverClosed) { - return; - } - serverClosed = true; - stdOutServer.close(); - stdErrServer.close(); - }; - // Create the process - logger.info('Forking TSServer', `PATH: ${newEnv['PATH']} `); - const bootstrapperPath = path_1.default.resolve(__dirname, '../bin/tsserverForkStart'); - childProcess = child_process_1.default.fork(bootstrapperPath, [modulePath].concat(args), { - silent: true, - env: newEnv, - execArgv: options.execArgv - }); - childProcess.once('error', (err) => { - closeServer(); - reject(err); - }); - childProcess.once('exit', (err) => { - closeServer(); - reject(err); - }); + throw getNotFoundError(cmd) } -exports.fork = fork; + +module.exports = which +which.sync = whichSync /***/ }), -/* 128 */ +/* 126 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var fs = __webpack_require__(102) +var core +if (process.platform === 'win32' || global.TESTING_WINDOWS) { + core = __webpack_require__(127) +} else { + core = __webpack_require__(128) +} -Object.defineProperty(exports, "__esModule", { value: true }); -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -const coc_nvim_1 = __webpack_require__(1); -var Trace; -(function (Trace) { - Trace[Trace["Off"] = 0] = "Off"; - Trace[Trace["Messages"] = 1] = "Messages"; - Trace[Trace["Verbose"] = 2] = "Verbose"; -})(Trace || (Trace = {})); -(function (Trace) { - function fromString(value) { - value = value || ''; - value = value.toLowerCase(); - switch (value) { - case 'off': - return Trace.Off; - case 'messages': - return Trace.Messages; - case 'verbose': - return Trace.Verbose; - default: - return Trace.Off; - } - } - Trace.fromString = fromString; -})(Trace || (Trace = {})); -class Tracer { - constructor(logger) { - this.logger = logger; - this.trace = Tracer.readTrace(); - } - static readTrace() { - let result = Trace.fromString(coc_nvim_1.workspace.getConfiguration('tsserver').get('trace.server', 'off')); - if (result === Trace.Off && !!process.env.TSS_TRACE) { - result = Trace.Messages; - } - return result; - } - traceRequest(request, responseExpected, queueLength) { - if (this.trace === Trace.Off) - return; - let data; - if (this.trace === Trace.Verbose && request.arguments) { - data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`; - } - this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? 'yes' : 'no'}. Current queue length: ${queueLength}`, data); - } - traceResponse(response, startTime) { - if (this.trace === Trace.Off) { - return; - } - let data; - if (this.trace === Trace.Verbose && response.body) { - data = `Result: ${JSON.stringify(response.body, null, 4)}`; - } - this.logTrace(`Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? '. Message: ' + response.message : ''}`, data); - } - traceEvent(event) { - if (this.trace === Trace.Off) { - return; - } - let data; - if (this.trace === Trace.Verbose && event.body) { - data = `Data: ${JSON.stringify(event.body, null, 4)}`; - } - this.logTrace(`Event received: ${event.event} (${event.seq}).`, data); - } - logTrace(message, data) { - if (this.trace !== Trace.Off) { - this.logger.logLevel('Trace', message, data); - } +module.exports = isexe +isexe.sync = sync + +function isexe (path, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } + + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') } - traceRequestCompleted(command, request_seq, startTime) { - if (this.trace === Trace.Off) { - return; + + return new Promise(function (resolve, reject) { + isexe(path, options || {}, function (er, is) { + if (er) { + reject(er) + } else { + resolve(is) } - this.logTrace(`Async response received: ${command} (${request_seq}). Request took ${Date.now() - startTime} ms.`); + }) + }) + } + + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null + is = false + } } + cb(er, is) + }) +} + +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } } -exports.default = Tracer; /***/ }), -/* 129 */ +/* 127 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +module.exports = isexe +isexe.sync = sync -Object.defineProperty(exports, "__esModule", { value: true }); -exports.inferredProjectConfig = void 0; -function inferredProjectConfig(config) { - const base = { - module: 'commonjs', - target: 'es2016', - jsx: 'preserve' - }; - if (config.checkJs) { - base.checkJs = true; - } - if (config.experimentalDecorators) { - base.experimentalDecorators = true; +var fs = __webpack_require__(102) + +function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT + + if (!pathext) { + return true + } + + pathext = pathext.split(';') + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase() + if (p && path.substr(-p.length).toLowerCase() === p) { + return true } - return base; + } + return false +} + +function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) +} + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), path, options) } -exports.inferredProjectConfig = inferredProjectConfig; /***/ }), -/* 130 */ +/* 128 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = isexe +isexe.sync = sync + +var fs = __webpack_require__(102) + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), options) +} + +function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) +} + +function checkMode (stat, options) { + var mod = stat.mode + var uid = stat.uid + var gid = stat.gid + + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid() + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid() + + var u = parseInt('100', 8) + var g = parseInt('010', 8) + var o = parseInt('001', 8) + var ug = u | g + + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0 + + return ret +} + + +/***/ }), +/* 129 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TypeScriptVersionProvider = exports.TypeScriptVersion = void 0; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -const fs_1 = __importDefault(__webpack_require__(118)); -const path_1 = __importDefault(__webpack_require__(13)); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); const coc_nvim_1 = __webpack_require__(1); -const api_1 = __importDefault(__webpack_require__(40)); -const requireFunc = true ? require : undefined; -class TypeScriptVersion { - constructor(path, _pathLabel) { - this.path = path; - this._pathLabel = _pathLabel; - this._api = null; - } - get tscPath() { - return path_1.default.resolve(this.path, '../bin/tsc'); - } - get tsServerPath() { - return path_1.default.resolve(this.path, 'tsserver.js'); - } - get pathLabel() { - return typeof this._pathLabel === 'undefined' ? this.path : this._pathLabel; - } - get isValid() { - return this.version != null; - } - get version() { - if (this._api) - return this._api; - let api = this._api = this.getTypeScriptVersion(this.tsServerPath); - return api; - } - get versionString() { - const version = this.version; - return version ? version.versionString : null; - } - getTypeScriptVersion(serverPath) { - if (!fs_1.default.existsSync(serverPath)) { - return undefined; +const is = __importStar(__webpack_require__(130)); +class Logger { + get output() { + if (this._channel) { + return this._channel; } - const p = serverPath.split(path_1.default.sep); - if (p.length <= 2) { - return undefined; + this._channel = coc_nvim_1.workspace.createOutputChannel('tsserver'); + return this._channel; + } + dispose() { + if (this._channel) { + this._channel.dispose(); } - const p2 = p.slice(0, -2); - const modulePath = p2.join(path_1.default.sep); - let fileName = path_1.default.join(modulePath, 'package.json'); - if (!fs_1.default.existsSync(fileName)) { - // Special case for ts dev versions - if (path_1.default.basename(modulePath) === 'built') { - fileName = path_1.default.join(modulePath, '..', 'package.json'); + } + data2String(data) { + if (data instanceof Error) { + if (is.string(data.stack)) { + return data.stack; } + return data.message; } - if (!fs_1.default.existsSync(fileName)) { - return undefined; - } - const contents = fs_1.default.readFileSync(fileName).toString(); - let desc = null; - try { - desc = JSON.parse(contents); - } - catch (err) { - return undefined; - } - if (!desc || !desc.version) { - return undefined; + if (is.boolean(data.success) && !data.success && is.string(data.message)) { + return data.message; } - return desc.version ? api_1.default.fromVersionString(desc.version) : undefined; - } -} -exports.TypeScriptVersion = TypeScriptVersion; -const MODULE_FOLDERS = ['node_modules/typescript/lib', '.vscode/pnpify/typescript/lib']; -class TypeScriptVersionProvider { - constructor(configuration) { - this.configuration = configuration; - } - updateConfiguration(configuration) { - this.configuration = configuration; - } - getDefaultVersion() { - // tsdk from configuration - let { globalTsdk } = this.configuration; - if (globalTsdk) - return new TypeScriptVersion(globalTsdk); - return this.bundledVersion; - } - get globalVersion() { - let { globalTsdk } = this.configuration; - if (globalTsdk) - return new TypeScriptVersion(globalTsdk); - return undefined; - } - getLocalVersion() { - let folders = coc_nvim_1.workspace.workspaceFolders.map(f => coc_nvim_1.Uri.parse(f.uri).fsPath); - for (let p of folders) { - for (let folder of MODULE_FOLDERS) { - let libFolder = path_1.default.join(p, folder); - if (fs_1.default.existsSync(libFolder)) { - let version = new TypeScriptVersion(libFolder); - if (version.isValid) - return version; - } - } + if (is.string(data)) { + return data; } - return null; + return data.toString(); } - get bundledVersion() { - try { - const file = requireFunc.resolve('typescript'); - const bundledVersion = new TypeScriptVersion(path_1.default.dirname(file), ''); - return bundledVersion; + info(message, data) { + this.logLevel('Info', message, data); + } + warn(message, data) { + this.logLevel('Warn', message, data); + } + error(message, data) { + // See https://github.com/Microsoft/TypeScript/issues/10496 + if (data && data.message === 'No content available.') { + return; } - catch (e) { - coc_nvim_1.workspace.showMessage('Bundled typescript module not found', 'error'); - return null; + this.logLevel('Error', message, data); + } + logLevel(level, message, data) { + this.output.appendLine(`[${level} - ${new Date().toLocaleTimeString()}] ${message}`); + if (data) { + this.output.appendLine(this.data2String(data)); } } } -exports.TypeScriptVersionProvider = TypeScriptVersionProvider; +exports.default = Logger; /***/ }), -/* 131 */ +/* 130 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); -const coc_nvim_1 = __webpack_require__(1); -class VersionStatus { - constructor(_normalizePath, enableJavascript) { - this._normalizePath = _normalizePath; - this.enableJavascript = enableJavascript; - this._versionBarEntry = coc_nvim_1.workspace.createStatusBarItem(99); - this._onChangeEditorSub = coc_nvim_1.events.on('BufEnter', this.onBufEnter, this); - this._versionBarEntry.show(); - } - dispose() { - this._versionBarEntry.dispose(); - this._onChangeEditorSub.dispose(); - } - onDidChangeTypeScriptVersion(_version) { - this._versionBarEntry.text = `TSC`; - } - set loading(isLoading) { - this._versionBarEntry.isProgress = isLoading; - } - checkFiletype(filetype) { - if (filetype.startsWith('javascript') && this.enableJavascript) { - return true; - } - return filetype.startsWith('typescript'); - } - onBufEnter(bufnr) { - return __awaiter(this, void 0, void 0, function* () { - let filetype = yield coc_nvim_1.workspace.nvim.call('getbufvar', [bufnr, '&filetype', '']); - if (this.checkFiletype(filetype)) { - this._versionBarEntry.show(); - } - else { - this._versionBarEntry.hide(); - } - }); - } +exports.string = exports.boolean = exports.defined = void 0; +const toString = Object.prototype.toString; +function defined(value) { + return typeof value !== 'undefined'; } -exports.default = VersionStatus; +exports.defined = defined; +function boolean(value) { + return value === true || value === false; +} +exports.boolean = boolean; +function string(value) { + return toString.call(value) === '[object String]'; +} +exports.string = string; /***/ }), -/* 132 */ +/* 131 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", { value: true }); -exports.Reader = void 0; -const DefaultSize = 8192; -const ContentLength = 'Content-Length: '; -const ContentLengthSize = Buffer.byteLength(ContentLength, 'utf8'); -const Blank = Buffer.from(' ', 'utf8')[0]; -const BackslashR = Buffer.from('\r', 'utf8')[0]; -const BackslashN = Buffer.from('\n', 'utf8')[0]; -class ProtocolBuffer { - constructor() { - this.index = 0; - this.buffer = Buffer.allocUnsafe(DefaultSize); +exports.fork = exports.getTempFile = exports.getTempDirectory = exports.makeRandomHexString = void 0; +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +const child_process_1 = __importDefault(__webpack_require__(101)); +const net_1 = __importDefault(__webpack_require__(16)); +const os_1 = __importDefault(__webpack_require__(14)); +const path_1 = __importDefault(__webpack_require__(13)); +const fs_1 = __importDefault(__webpack_require__(102)); +function makeRandomHexString(length) { + let chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; + let result = ''; + for (let i = 0; i < length; i++) { + const idx = Math.floor(chars.length * Math.random()); + result += chars[idx]; } - append(data) { - let toAppend = null; - if (Buffer.isBuffer(data)) { - toAppend = data; - } - else { - toAppend = Buffer.from(data, 'utf8'); - } - if (this.buffer.length - this.index >= toAppend.length) { - toAppend.copy(this.buffer, this.index, 0, toAppend.length); - } - else { - let newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * - DefaultSize; - if (this.index === 0) { - this.buffer = Buffer.allocUnsafe(newSize); - toAppend.copy(this.buffer, 0, 0, toAppend.length); - } - else { - this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize); - } - } - this.index += toAppend.length; + return result; +} +exports.makeRandomHexString = makeRandomHexString; +function getTempDirectory() { + let dir = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`); + if (!fs_1.default.existsSync(dir)) { + fs_1.default.mkdirSync(dir); } - tryReadContentLength() { - let result = -1; - let current = 0; - // we are utf8 encoding... - while (current < this.index && - (this.buffer[current] === Blank || - this.buffer[current] === BackslashR || - this.buffer[current] === BackslashN)) { - current++; - } - if (this.index < current + ContentLengthSize) { - return result; - } - current += ContentLengthSize; - let start = current; - while (current < this.index && this.buffer[current] !== BackslashR) { - current++; - } - if (current + 3 >= this.index || - this.buffer[current + 1] !== BackslashN || - this.buffer[current + 2] !== BackslashR || - this.buffer[current + 3] !== BackslashN) { - return result; - } - let data = this.buffer.toString('utf8', start, current); - result = parseInt(data, 10); - this.buffer = this.buffer.slice(current + 4); - this.index = this.index - (current + 4); - return result; + return dir; +} +exports.getTempDirectory = getTempDirectory; +function generatePipeName() { + return getPipeName(makeRandomHexString(40)); +} +function getPipeName(name) { + const fullName = 'coc-tsc-' + name; + if (process.platform === 'win32') { + return '\\\\.\\pipe\\' + fullName + '-sock'; } - tryReadContent(length) { - if (this.index < length) { - return null; + const tmpdir = getTempDirectory(); + // Mac/Unix: use socket file + return path_1.default.join(tmpdir, fullName + '.sock'); +} +function getTempFile(name) { + const fullName = 'coc-nvim-' + name; + return path_1.default.join(getTempDirectory(), fullName + '.sock'); +} +exports.getTempFile = getTempFile; +function generatePatchedEnv(env, stdInPipeName, stdOutPipeName, stdErrPipeName) { + const newEnv = Object.assign({}, env); + // Set the two unique pipe names and the electron flag as process env + newEnv['STDIN_PIPE_NAME'] = stdInPipeName; // tslint:disable-line + newEnv['STDOUT_PIPE_NAME'] = stdOutPipeName; // tslint:disable-line + newEnv['STDERR_PIPE_NAME'] = stdErrPipeName; // tslint:disable-line + newEnv['TSS_LOG'] = `-level verbose -file ${path_1.default.join(os_1.default.tmpdir(), 'coc-nvim-tsc.log')}`; // tslint:disable-line + // Ensure we always have a PATH set + newEnv['PATH'] = newEnv['PATH'] || process.env.PATH; // tslint:disable-line + return newEnv; +} +function fork(modulePath, args, options, logger, callback) { + let callbackCalled = false; + const resolve = (result) => { + if (callbackCalled) { + return; } - let result = this.buffer.toString('utf8', 0, length); - let sourceStart = length; - while (sourceStart < this.index && - (this.buffer[sourceStart] === BackslashR || - this.buffer[sourceStart] === BackslashN)) { - sourceStart++; + callbackCalled = true; + callback(null, result); + }; + const reject = (err) => { + if (callbackCalled) { + return; } - this.buffer.copy(this.buffer, 0, sourceStart); - this.index = this.index - sourceStart; - return result; - } -} -class Reader { - constructor(readable, callback, onError) { - this.readable = readable; - this.callback = callback; - this.onError = onError; - this.buffer = new ProtocolBuffer(); - this.nextMessageLength = -1; - this.readable.on('data', (data) => { - this.onLengthData(data); + callbackCalled = true; + callback(err, null); + }; + // Generate three unique pipe names + const stdInPipeName = generatePipeName(); + const stdOutPipeName = generatePipeName(); + const stdErrPipeName = generatePipeName(); + const newEnv = generatePatchedEnv(process.env, stdInPipeName, stdOutPipeName, stdErrPipeName); + newEnv['NODE_PATH'] = path_1.default.join(modulePath, '..', '..', '..'); // tslint:disable-line + let childProcess; + // Begin listening to stderr pipe + let stdErrServer = net_1.default.createServer(stdErrStream => { + // From now on the childProcess.stderr is available for reading + childProcess.stderr = stdErrStream; + }); + stdErrServer.listen(stdErrPipeName); + // Begin listening to stdout pipe + let stdOutServer = net_1.default.createServer(stdOutStream => { + // The child process will write exactly one chunk with content `ready` when it has installed a listener to the stdin pipe + stdOutStream.once('data', (_chunk) => { + // The child process is sending me the `ready` chunk, time to connect to the stdin pipe + childProcess.stdin = net_1.default.connect(stdInPipeName); + // From now on the childProcess.stdout is available for reading + childProcess.stdout = stdOutStream; + resolve(childProcess); }); - } - onLengthData(data) { - try { - this.buffer.append(data); - while (true) { - if (this.nextMessageLength === -1) { - this.nextMessageLength = this.buffer.tryReadContentLength(); - if (this.nextMessageLength === -1) { - return; - } - } - const msg = this.buffer.tryReadContent(this.nextMessageLength); - if (msg === null) { - return; - } - this.nextMessageLength = -1; - const json = JSON.parse(msg); - this.callback(json); - } - } - catch (e) { - this.onError(e); + }); + stdOutServer.listen(stdOutPipeName); + let serverClosed = false; + const closeServer = () => { + if (serverClosed) { + return; } - } + serverClosed = true; + stdOutServer.close(); + stdErrServer.close(); + }; + // Create the process + logger.info('Forking TSServer', `PATH: ${newEnv['PATH']} `); + const bootstrapperPath = path_1.default.resolve(__dirname, '../bin/tsserverForkStart'); + childProcess = child_process_1.default.fork(bootstrapperPath, [modulePath].concat(args), { + silent: true, + env: newEnv, + execArgv: options.execArgv + }); + childProcess.once('error', (err) => { + closeServer(); + reject(err); + }); + childProcess.once('exit', (err) => { + closeServer(); + reject(err); + }); } -exports.Reader = Reader; +exports.fork = fork; /***/ }), -/* 133 */ +/* 132 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CallbackMap = void 0; -const typescriptService_1 = __webpack_require__(123); -class CallbackMap { - constructor() { - this._callbacks = new Map(); - this._asyncCallbacks = new Map(); +const coc_nvim_1 = __webpack_require__(1); +var Trace; +(function (Trace) { + Trace[Trace["Off"] = 0] = "Off"; + Trace[Trace["Messages"] = 1] = "Messages"; + Trace[Trace["Verbose"] = 2] = "Verbose"; +})(Trace || (Trace = {})); +(function (Trace) { + function fromString(value) { + value = value || ''; + value = value.toLowerCase(); + switch (value) { + case 'off': + return Trace.Off; + case 'messages': + return Trace.Messages; + case 'verbose': + return Trace.Verbose; + default: + return Trace.Off; + } } - destroy(cause) { - const cancellation = new typescriptService_1.ServerResponse.Cancelled(cause); - for (const callback of this._callbacks.values()) { - callback.onSuccess(cancellation); + Trace.fromString = fromString; +})(Trace || (Trace = {})); +class Tracer { + constructor(logger) { + this.logger = logger; + this.trace = Tracer.readTrace(); + } + static readTrace() { + let result = Trace.fromString(coc_nvim_1.workspace.getConfiguration('tsserver').get('trace.server', 'off')); + if (result === Trace.Off && !!process.env.TSS_TRACE) { + result = Trace.Messages; } - this._callbacks.clear(); - for (const callback of this._asyncCallbacks.values()) { - callback.onSuccess(cancellation); + return result; + } + traceRequest(request, responseExpected, queueLength) { + if (this.trace === Trace.Off) + return; + let data; + if (this.trace === Trace.Verbose && request.arguments) { + data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`; } - this._asyncCallbacks.clear(); + this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? 'yes' : 'no'}. Current queue length: ${queueLength}`, data); } - add(seq, callback, isAsync) { - if (isAsync) { - this._asyncCallbacks.set(seq, callback); + traceResponse(response, startTime) { + if (this.trace === Trace.Off) { + return; } - else { - this._callbacks.set(seq, callback); + let data; + if (this.trace === Trace.Verbose && response.body) { + data = `Result: ${JSON.stringify(response.body, null, 4)}`; } + this.logTrace(`Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? '. Message: ' + response.message : ''}`, data); } - fetch(seq) { - const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq); - this.delete(seq); - return callback; + traceEvent(event) { + if (this.trace === Trace.Off) { + return; + } + let data; + if (this.trace === Trace.Verbose && event.body) { + data = `Data: ${JSON.stringify(event.body, null, 4)}`; + } + this.logTrace(`Event received: ${event.event} (${event.seq}).`, data); } - delete(seq) { - if (!this._callbacks.delete(seq)) { - this._asyncCallbacks.delete(seq); + logTrace(message, data) { + if (this.trace !== Trace.Off) { + this.logger.logLevel('Trace', message, data); + } + } + traceRequestCompleted(command, request_seq, startTime) { + if (this.trace === Trace.Off) { + return; } + this.logTrace(`Async response received: ${command} (${request_seq}). Request took ${Date.now() - startTime} ms.`); } } -exports.CallbackMap = CallbackMap; +exports.default = Tracer; /***/ }), -/* 134 */ +/* 133 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); -exports.RequestQueue = exports.RequestQueueingType = void 0; -var RequestQueueingType; -(function (RequestQueueingType) { - /** - * Normal request that is executed in order. - */ - RequestQueueingType[RequestQueueingType["Normal"] = 1] = "Normal"; - /** - * Request that normal requests jump in front of in the queue. - */ - RequestQueueingType[RequestQueueingType["LowPriority"] = 2] = "LowPriority"; - /** - * A fence that blocks request reordering. - * - * Fences are not reordered. Unlike a normal request, a fence will never jump in front of a low priority request - * in the request queue. - */ - RequestQueueingType[RequestQueueingType["Fence"] = 3] = "Fence"; -})(RequestQueueingType = exports.RequestQueueingType || (exports.RequestQueueingType = {})); -class RequestQueue { - constructor() { - this.queue = []; - this.sequenceNumber = 0; - } - get length() { - return this.queue.length; - } - enqueue(item) { - if (item.queueingType === RequestQueueingType.Normal) { - let index = this.queue.length - 1; - while (index >= 0) { - if (this.queue[index].queueingType !== RequestQueueingType.LowPriority) { - break; - } - --index; - } - this.queue.splice(index + 1, 0, item); - } - else { - // Only normal priority requests can be reordered. All other requests just go to the end. - this.queue.push(item); - } - } - dequeue() { - return this.queue.shift(); - } - tryDeletePendingRequest(seq) { - for (let i = 0; i < this.queue.length; i++) { - if (this.queue[i].request.seq === seq) { - this.queue.splice(i, 1); - return true; - } - } - return false; +exports.inferredProjectConfig = void 0; +function inferredProjectConfig(config) { + const base = { + module: 'commonjs', + target: 'es2016', + jsx: 'preserve' + }; + if (config.checkJs) { + base.checkJs = true; } - createRequest(command, args) { - return { - seq: this.sequenceNumber++, - type: 'request', - command, - arguments: args - }; + if (config.experimentalDecorators) { + base.experimentalDecorators = true; } + return base; } -exports.RequestQueue = RequestQueue; - - -/***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; +exports.inferredProjectConfig = inferredProjectConfig; + + +/***/ }), +/* 134 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); +exports.TypeScriptVersionProvider = exports.TypeScriptVersion = void 0; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +const fs_1 = __importDefault(__webpack_require__(102)); +const path_1 = __importDefault(__webpack_require__(13)); const coc_nvim_1 = __webpack_require__(1); -const vscode_languageserver_protocol_1 = __webpack_require__(3); const api_1 = __importDefault(__webpack_require__(40)); -const async_1 = __webpack_require__(136); -const typeConverters = __importStar(__webpack_require__(37)); -const languageModeIds = __importStar(__webpack_require__(116)); -function mode2ScriptKind(mode) { - switch (mode) { - case languageModeIds.typescript: - return 'TS'; - case languageModeIds.typescripttsx: - return 'TSX'; - case languageModeIds.typescriptjsx: - return 'TSX'; - case languageModeIds.typescriptreact: - return 'TSX'; - case languageModeIds.javascript: - return 'JS'; - case languageModeIds.javascriptreact: - return 'JSX'; - } - return undefined; -} -/** - * Manages synchronization of buffers with the TS server. - * - * If supported, batches together file changes. This allows the TS server to more efficiently process changes. - */ -class BufferSynchronizer { - constructor(client) { - this.client = client; - this._pending = {}; - this._pendingFiles = new Set(); +const requireFunc = true ? require : undefined; +class TypeScriptVersion { + constructor(path, _pathLabel) { + this.path = path; + this._pathLabel = _pathLabel; + this._api = null; } - open(args) { - this.client.executeWithoutWaitingForResponse('open', args); + get tscPath() { + return path_1.default.resolve(this.path, '../bin/tsc'); } - close(filepath) { - const args = { file: filepath }; - this.client.executeWithoutWaitingForResponse('close', args); + get tsServerPath() { + return path_1.default.resolve(this.path, 'tsserver.js'); } - change(filepath, events) { - if (!events.length) { - return; - } - if (this.supportsBatching) { - this.updatePending(filepath, pending => { - if (!pending.changedFiles) { - pending.changedFiles = []; - } - pending.changedFiles.push({ - fileName: filepath, - textChanges: events.map((change) => ({ - newText: change.text, - start: typeConverters.Position.toLocation(change.range.start), - end: typeConverters.Position.toLocation(change.range.end), - })).reverse(), - }); - }); - } - else { - for (const event of events) { - const args = Object.assign({ insertString: event.text }, typeConverters.Range.toFormattingRequestArgs(filepath, event.range)); - this.client.executeWithoutWaitingForResponse('change', args); - } - } + get pathLabel() { + return typeof this._pathLabel === 'undefined' ? this.path : this._pathLabel; } - beforeCommand(command) { - if (command === 'updateOpen') { - return; - } - this.flush(); + get isValid() { + return this.version != null; } - flush() { - if (!this.supportsBatching) { - // We've already eagerly synchronized - return; - } - if (this._pending.changedFiles) { - this.client.executeWithoutWaitingForResponse('updateOpen', this._pending); - this._pending = {}; - this._pendingFiles.clear(); - } + get version() { + if (this._api) + return this._api; + let api = this._api = this.getTypeScriptVersion(this.tsServerPath); + return api; } - get supportsBatching() { - return this.client.apiVersion.gte(api_1.default.v340) && coc_nvim_1.workspace.getConfiguration('tsserver').get('useBatchedBufferSync', true); + get versionString() { + const version = this.version; + return version ? version.versionString : null; } - updatePending(filepath, f) { - if (this.supportsBatching && this._pendingFiles.has(filepath)) { - this.flush(); - this._pendingFiles.clear(); - f(this._pending); - this._pendingFiles.add(filepath); - } - else { - f(this._pending); + getTypeScriptVersion(serverPath) { + if (!fs_1.default.existsSync(serverPath)) { + return undefined; } - } - reset() { - this._pending = {}; - this._pendingFiles.clear(); - } -} -class BufferSyncSupport { - constructor(client) { - this.uris = new Set(); - this.disposables = []; - this.pendingDiagnostics = new Map(); - this._validateJavaScript = true; - this._validateTypeScript = true; - this.listening = false; - this._onDelete = new vscode_languageserver_protocol_1.Emitter(); - this.onDelete = this._onDelete.event; - this.client = client; - this.synchronizer = new BufferSynchronizer(client); - this.modeIds = new Set(languageModeIds.languageIds); - this.diagnosticDelayer = new async_1.Delayer(300); - } - listen() { - if (this.listening) { - return; + const p = serverPath.split(path_1.default.sep); + if (p.length <= 2) { + return undefined; } - this.listening = true; - coc_nvim_1.workspace.onDidOpenTextDocument(this.onDidOpenTextDocument, this, this.disposables); - coc_nvim_1.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, this.disposables); - coc_nvim_1.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, this.disposables); - coc_nvim_1.workspace.textDocuments.forEach(this.onDidOpenTextDocument, this); - this.updateConfiguration(); - coc_nvim_1.workspace.onDidChangeConfiguration(this.updateConfiguration, this, this.disposables); - } - dispose() { - this.pendingDiagnostics.clear(); - coc_nvim_1.disposeAll(this.disposables); - } - onDidOpenTextDocument(document) { - if (!this.modeIds.has(document.languageId)) - return; - let { uri } = document; - let filepath = this.client.toPath(uri); - this.uris.add(uri); - const args = { - file: filepath, - fileContent: document.getText() - }; - if (this.client.apiVersion.gte(api_1.default.v203)) { - const scriptKind = mode2ScriptKind(document.languageId); - if (scriptKind) { - args.scriptKindName = scriptKind; + const p2 = p.slice(0, -2); + const modulePath = p2.join(path_1.default.sep); + let fileName = path_1.default.join(modulePath, 'package.json'); + if (!fs_1.default.existsSync(fileName)) { + // Special case for ts dev versions + if (path_1.default.basename(modulePath) === 'built') { + fileName = path_1.default.join(modulePath, '..', 'package.json'); } } - if (this.client.apiVersion.gte(api_1.default.v230)) { - let root = this.client.getProjectRootPath(document.uri); - if (root) - args.projectRootPath = root; - } - this.synchronizer.open(args); - // this.client.executeWithoutWaitingForResponse('open', args) - this.requestDiagnostic(uri); - } - onDidCloseTextDocument(document) { - let { uri } = document; - if (!this.uris.has(uri)) - return; - let filepath = this.client.toPath(uri); - this.uris.delete(uri); - this.pendingDiagnostics.delete(uri); - this.synchronizer.close(filepath); - this._onDelete.fire(uri); - this.requestAllDiagnostics(); - // this.client.executeWithoutWaitingForResponse('close', args) - } - onDidChangeTextDocument(e) { - let { textDocument, contentChanges } = e; - let { uri } = textDocument; - if (!this.uris.has(uri)) - return; - let filepath = this.client.toPath(uri); - this.synchronizer.change(filepath, contentChanges); - const didTrigger = this.requestDiagnostic(uri); - if (!didTrigger && this.pendingGetErr) { - // In this case we always want to re-trigger all diagnostics - this.pendingGetErr.cancel(); - this.pendingGetErr = undefined; - this.triggerDiagnostics(); + if (!fs_1.default.existsSync(fileName)) { + return undefined; } - } - beforeCommand(command) { - this.synchronizer.beforeCommand(command); - } - interuptGetErr(f) { - if (!this.pendingGetErr) { - return f(); + const contents = fs_1.default.readFileSync(fileName).toString(); + let desc = null; + try { + desc = JSON.parse(contents); } - this.pendingGetErr.cancel(); - this.pendingGetErr = undefined; - const result = f(); - this.triggerDiagnostics(); - return result; - } - getErr(resources) { - const handledResources = resources.filter(resource => this.uris.has(resource.toString())); - if (!handledResources.length) { - return; + catch (err) { + return undefined; } - for (const resource of handledResources) { - let uri = resource.toString(); - if (this.shouldValidate(uri)) { - this.pendingDiagnostics.set(uri, Date.now()); - } + if (!desc || !desc.version) { + return undefined; } - this.triggerDiagnostics(); - } - has(uri) { - return this.uris.has(uri); + return desc.version ? api_1.default.fromVersionString(desc.version) : undefined; } - triggerDiagnostics(delay = 200) { - this.diagnosticDelayer.trigger(() => { - this.sendPendingDiagnostics(); - }, delay); +} +exports.TypeScriptVersion = TypeScriptVersion; +const MODULE_FOLDERS = ['node_modules/typescript/lib', '.vscode/pnpify/typescript/lib', '.yarn/sdks/typescript/lib']; +class TypeScriptVersionProvider { + constructor(configuration) { + this.configuration = configuration; } - requestAllDiagnostics() { - for (const uri of this.uris) { - if (this.shouldValidate(uri)) { - this.pendingDiagnostics.set(uri, Date.now()); - } - } - this.diagnosticDelayer.trigger(() => { - this.sendPendingDiagnostics(); - }, 200); + updateConfiguration(configuration) { + this.configuration = configuration; } - requestDiagnostic(uri) { - let document = coc_nvim_1.workspace.getDocument(uri); - if (!document || !this.shouldValidate(uri)) - return false; - this.pendingDiagnostics.set(uri, Date.now()); - const lineCount = document.lineCount; - const delay = Math.min(Math.max(Math.ceil(lineCount / 20), 300), 800); - this.triggerDiagnostics(delay); - return true; + getDefaultVersion() { + // tsdk from configuration + let { globalTsdk } = this.configuration; + if (globalTsdk) + return new TypeScriptVersion(globalTsdk); + return this.bundledVersion; } - hasPendingDiagnostics(uri) { - return this.pendingDiagnostics.has(uri); + get globalVersion() { + let { globalTsdk } = this.configuration; + if (globalTsdk) + return new TypeScriptVersion(coc_nvim_1.workspace.expand(globalTsdk)); + return undefined; } - sendPendingDiagnostics() { - const uris = Array.from(this.pendingDiagnostics.entries()) - .sort((a, b) => a[1] - b[1]) - .map(entry => entry[0]); - // Add all open TS buffers to the geterr request. They might be visible - for (const uri of this.uris) { - if (uris.indexOf(uri) == -1) { - uris.push(uri); + getLocalVersion() { + let folders = coc_nvim_1.workspace.workspaceFolders.map(f => coc_nvim_1.Uri.parse(f.uri).fsPath); + for (let p of folders) { + for (let folder of MODULE_FOLDERS) { + let libFolder = path_1.default.join(p, folder); + if (fs_1.default.existsSync(libFolder)) { + let version = new TypeScriptVersion(libFolder); + if (version.isValid) + return version; + } } } - let files = uris.map(uri => this.client.toPath(uri)); - if (files.length) { - if (this.pendingGetErr) - this.pendingGetErr.cancel(); - const getErr = this.pendingGetErr = GetErrRequest.executeGetErrRequest(this.client, files, () => { - if (this.pendingGetErr === getErr) { - this.pendingGetErr = undefined; - } - }); + return null; + } + get bundledVersion() { + try { + const file = requireFunc.resolve('typescript'); + const bundledVersion = new TypeScriptVersion(path_1.default.dirname(file), ''); + return bundledVersion; + } + catch (e) { + coc_nvim_1.workspace.showMessage('Bundled typescript module not found', 'error'); + return null; } - this.pendingDiagnostics.clear(); } - updateConfiguration() { - const jsConfig = coc_nvim_1.workspace.getConfiguration('javascript', null); - const tsConfig = coc_nvim_1.workspace.getConfiguration('typescript', null); - this._validateJavaScript = jsConfig.get('validate.enable', true); - this._validateTypeScript = tsConfig.get('validate.enable', true); +} +exports.TypeScriptVersionProvider = TypeScriptVersionProvider; + + +/***/ }), +/* 135 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const coc_nvim_1 = __webpack_require__(1); +class VersionStatus { + constructor(_normalizePath, enableJavascript) { + this._normalizePath = _normalizePath; + this.enableJavascript = enableJavascript; + this._versionBarEntry = coc_nvim_1.workspace.createStatusBarItem(99); + this._onChangeEditorSub = coc_nvim_1.events.on('BufEnter', this.onBufEnter, this); + this._versionBarEntry.show(); } - shouldValidate(uri) { - let doc = coc_nvim_1.workspace.getDocument(uri); - if (!doc) - return false; - if (languageModeIds.languageIds.indexOf(doc.filetype) == -1) { - return false; - } - if (doc.filetype.startsWith('javascript')) { - return this._validateJavaScript; - } - return this._validateTypeScript; + dispose() { + this._versionBarEntry.dispose(); + this._onChangeEditorSub.dispose(); } - reinitialize() { - var _a; - this.pendingDiagnostics.clear(); - (_a = this.pendingGetErr) === null || _a === void 0 ? void 0 : _a.cancel(); - this.synchronizer.reset(); - for (let doc of coc_nvim_1.workspace.documents) { - this.onDidOpenTextDocument(doc.textDocument); - } + onDidChangeTypeScriptVersion(_version) { + this._versionBarEntry.text = `TSC`; } -} -exports.default = BufferSyncSupport; -class GetErrRequest { - constructor(client, files, _token, onDone) { - this.files = files; - this._token = _token; - this._done = false; - const args = { - delay: 0, - files: this.files - }; - const done = () => { - if (this._done) { - return; - } - this._done = true; - onDone(); - }; - client.executeAsync('geterr', args, _token.token).then(done, done); + set loading(isLoading) { + this._versionBarEntry.isProgress = isLoading; } - static executeGetErrRequest(client, files, onDone) { - const token = new vscode_languageserver_protocol_1.CancellationTokenSource(); - return new GetErrRequest(client, files, token, onDone); + checkFiletype(filetype) { + if (filetype.startsWith('javascript') && this.enableJavascript) { + return true; + } + return filetype.startsWith('typescript'); } - cancel() { - if (!this._done) { - this._token.cancel(); + async onBufEnter(bufnr) { + let filetype = await coc_nvim_1.workspace.nvim.call('getbufvar', [bufnr, '&filetype', '']); + if (this.checkFiletype(filetype)) { + this._versionBarEntry.show(); + } + else { + this._versionBarEntry.hide(); } - this._token.dispose(); } } +exports.default = VersionStatus; /***/ }), @@ -14669,49 +14535,124 @@ class GetErrRequest { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.Delayer = void 0; -class Delayer { - constructor(defaultDelay) { - this.defaultDelay = defaultDelay; - this.timeout = null; - this.completionPromise = null; - this.onSuccess = null; - this.task = null; +exports.Reader = void 0; +const DefaultSize = 8192; +const ContentLength = 'Content-Length: '; +const ContentLengthSize = Buffer.byteLength(ContentLength, 'utf8'); +const Blank = Buffer.from(' ', 'utf8')[0]; +const BackslashR = Buffer.from('\r', 'utf8')[0]; +const BackslashN = Buffer.from('\n', 'utf8')[0]; +class ProtocolBuffer { + constructor() { + this.index = 0; + this.buffer = Buffer.allocUnsafe(DefaultSize); } - trigger(task, delay = this.defaultDelay) { - this.task = task; - if (delay >= 0) { - this.cancelTimeout(); + append(data) { + let toAppend = null; + if (Buffer.isBuffer(data)) { + toAppend = data; } - if (!this.completionPromise) { - this.completionPromise = new Promise(resolve => { - this.onSuccess = resolve; - }).then(() => { - this.completionPromise = null; - this.onSuccess = null; - let result = this.task && this.task(); - this.task = null; - return result; - }); + else { + toAppend = Buffer.from(data, 'utf8'); } - if (delay >= 0 || this.timeout === null) { - this.timeout = setTimeout(() => { - this.timeout = null; - if (this.onSuccess) { - this.onSuccess(undefined); - } - }, delay >= 0 ? delay : this.defaultDelay); + if (this.buffer.length - this.index >= toAppend.length) { + toAppend.copy(this.buffer, this.index, 0, toAppend.length); } - return this.completionPromise; + else { + let newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * + DefaultSize; + if (this.index === 0) { + this.buffer = Buffer.allocUnsafe(newSize); + toAppend.copy(this.buffer, 0, 0, toAppend.length); + } + else { + this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize); + } + } + this.index += toAppend.length; } - cancelTimeout() { - if (this.timeout !== null) { - clearTimeout(this.timeout); - this.timeout = null; + tryReadContentLength() { + let result = -1; + let current = 0; + // we are utf8 encoding... + while (current < this.index && + (this.buffer[current] === Blank || + this.buffer[current] === BackslashR || + this.buffer[current] === BackslashN)) { + current++; + } + if (this.index < current + ContentLengthSize) { + return result; + } + current += ContentLengthSize; + let start = current; + while (current < this.index && this.buffer[current] !== BackslashR) { + current++; + } + if (current + 3 >= this.index || + this.buffer[current + 1] !== BackslashN || + this.buffer[current + 2] !== BackslashR || + this.buffer[current + 3] !== BackslashN) { + return result; + } + let data = this.buffer.toString('utf8', start, current); + result = parseInt(data, 10); + this.buffer = this.buffer.slice(current + 4); + this.index = this.index - (current + 4); + return result; + } + tryReadContent(length) { + if (this.index < length) { + return null; + } + let result = this.buffer.toString('utf8', 0, length); + let sourceStart = length; + while (sourceStart < this.index && + (this.buffer[sourceStart] === BackslashR || + this.buffer[sourceStart] === BackslashN)) { + sourceStart++; } + this.buffer.copy(this.buffer, 0, sourceStart); + this.index = this.index - sourceStart; + return result; } } -exports.Delayer = Delayer; +class Reader { + constructor(readable, callback, onError) { + this.readable = readable; + this.callback = callback; + this.onError = onError; + this.buffer = new ProtocolBuffer(); + this.nextMessageLength = -1; + this.readable.on('data', (data) => { + this.onLengthData(data); + }); + } + onLengthData(data) { + try { + this.buffer.append(data); + while (true) { + if (this.nextMessageLength === -1) { + this.nextMessageLength = this.buffer.tryReadContentLength(); + if (this.nextMessageLength === -1) { + return; + } + } + const msg = this.buffer.tryReadContent(this.nextMessageLength); + if (msg === null) { + return; + } + this.nextMessageLength = -1; + const json = JSON.parse(msg); + this.callback(json); + } + } + catch (e) { + this.onError(e); + } + } +} +exports.Reader = Reader; /***/ }), @@ -14721,140 +14662,95 @@ exports.Delayer = Delayer; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.DiagnosticsManager = exports.DiagnosticKind = exports.DiagnosticSet = void 0; +exports.AtaProgressReporter = void 0; +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +const vscode_languageserver_protocol_1 = __webpack_require__(3); const coc_nvim_1 = __webpack_require__(1); -const resourceMap_1 = __webpack_require__(138); -class DiagnosticSet { - constructor() { - this._map = new resourceMap_1.ResourceMap(); - } - set(uri, diagnostics) { - this._map.set(uri, diagnostics); - } - get(uri) { - return this._map.get(uri) || []; - } - clear() { - this._map = new resourceMap_1.ResourceMap(); - } -} -exports.DiagnosticSet = DiagnosticSet; -var DiagnosticKind; -(function (DiagnosticKind) { - DiagnosticKind[DiagnosticKind["Syntax"] = 0] = "Syntax"; - DiagnosticKind[DiagnosticKind["Semantic"] = 1] = "Semantic"; - DiagnosticKind[DiagnosticKind["Suggestion"] = 2] = "Suggestion"; -})(DiagnosticKind = exports.DiagnosticKind || (exports.DiagnosticKind = {})); -const allDiagnosticKinds = [ - DiagnosticKind.Syntax, - DiagnosticKind.Semantic, - DiagnosticKind.Suggestion -]; -class DiagnosticsManager { - constructor() { - this._diagnostics = new Map(); - this._pendingUpdates = new resourceMap_1.ResourceMap(); - this._enableJavascriptSuggestions = true; - this._enableTypescriptSuggestions = true; - this.updateDelay = 200; - for (const kind of allDiagnosticKinds) { - this._diagnostics.set(kind, new DiagnosticSet()); - } - this._currentDiagnostics = coc_nvim_1.languages.createDiagnosticCollection('tsserver'); - } - dispose() { - this._currentDiagnostics.dispose(); - for (const value of this._pendingUpdates.values) { - clearTimeout(value); - } - this._pendingUpdates = new resourceMap_1.ResourceMap(); +const typingsInstallTimeout = 30 * 1000; +class TypingsStatus { + constructor(client) { + this._acquiringTypings = Object.create({}); + this._subscriptions = []; + this._client = client; + this._subscriptions.push(this._client.onDidBeginInstallTypings(event => this.onBeginInstallTypings(event.eventId))); + this._subscriptions.push(this._client.onDidEndInstallTypings(event => this.onEndInstallTypings(event.eventId))); } - reInitialize() { - this._currentDiagnostics.clear(); - for (const diagnosticSet of this._diagnostics.values()) { - diagnosticSet.clear(); + dispose() { + this._subscriptions.forEach(x => x.dispose()); + for (const eventId of Object.keys(this._acquiringTypings)) { + clearTimeout(this._acquiringTypings[eventId]); } } - setEnableSuggestions(languageId, value) { - let curr = languageId == 'javascript' ? this._enableJavascriptSuggestions : this._enableTypescriptSuggestions; - if (curr == value) { - return; - } - if (languageId == 'javascript') { - this._enableJavascriptSuggestions = value; - } - else { - this._enableTypescriptSuggestions = value; - } + get isAcquiringTypings() { + return Object.keys(this._acquiringTypings).length > 0; } - diagnosticsReceived(kind, uri, diagnostics) { - const collection = this._diagnostics.get(kind); - if (!collection) + onBeginInstallTypings(eventId) { + if (this._acquiringTypings[eventId]) { return; - if (diagnostics.length === 0) { - const existing = collection.get(uri); - if (existing.length === 0) { - // No need to update - return; - } } - collection.set(uri, diagnostics); - this.scheduleDiagnosticsUpdate(uri); - } - configFileDiagnosticsReceived(uri, diagnostics) { - this._currentDiagnostics.set(uri, diagnostics); - } - delete(uri) { - this._currentDiagnostics.delete(uri); - } - getDiagnostics(uri) { - return this._currentDiagnostics.get(uri) || []; - return []; + this._acquiringTypings[eventId] = setTimeout(() => { + this.onEndInstallTypings(eventId); + }, typingsInstallTimeout); } - scheduleDiagnosticsUpdate(uri) { - if (!this._pendingUpdates.has(uri)) { - this._pendingUpdates.set(uri, setTimeout(() => this.updateCurrentDiagnostics(uri), this.updateDelay)); + onEndInstallTypings(eventId) { + const timer = this._acquiringTypings[eventId]; + if (timer) { + clearTimeout(timer); } + delete this._acquiringTypings[eventId]; } - updateCurrentDiagnostics(uri) { - if (this._pendingUpdates.has(uri)) { - clearTimeout(this._pendingUpdates.get(uri)); - this._pendingUpdates.delete(uri); - } - const allDiagnostics = [ - ...this._diagnostics.get(DiagnosticKind.Syntax).get(uri), - ...this._diagnostics.get(DiagnosticKind.Semantic).get(uri), - ...this.getSuggestionDiagnostics(uri) - ]; - this._currentDiagnostics.set(uri, allDiagnostics); +} +exports.default = TypingsStatus; +class AtaProgressReporter { + constructor(client) { + this._promises = new Map(); + this._invalid = false; + this.statusItem = coc_nvim_1.workspace.createStatusBarItem(10, { progress: true }); + const disposables = []; + disposables.push(client.onDidBeginInstallTypings(e => this._onBegin(e.eventId))); + disposables.push(client.onDidEndInstallTypings(e => this._onEndOrTimeout(e.eventId))); + disposables.push(client.onTypesInstallerInitializationFailed(_ => this.onTypesInstallerInitializationFailed())); + this._disposable = vscode_languageserver_protocol_1.Disposable.create(() => { + disposables.forEach(disposable => { + disposable.dispose(); + }); + }); } - getSuggestionDiagnostics(uri) { - const enabled = this.suggestionsEnabled(uri); - return this._diagnostics - .get(DiagnosticKind.Suggestion) - .get(uri) - .filter(x => { - if (!enabled) { - // Still show unused - return x.code == 6133; - } - return enabled; + dispose() { + this._disposable.dispose(); + this._promises.forEach(value => value()); + } + _onBegin(eventId) { + const handle = setTimeout(() => this._onEndOrTimeout(eventId), typingsInstallTimeout); + new Promise(resolve => { + this._promises.set(eventId, () => { + clearTimeout(handle); + resolve(); + }); }); + this.statusItem.text = 'Fetching data for better TypeScript IntelliSense'; + this.statusItem.show(); } - suggestionsEnabled(uri) { - let doc = coc_nvim_1.workspace.getDocument(uri); - if (!doc) - return false; - if (doc.filetype.startsWith('javascript')) { - return this._enableJavascriptSuggestions; + _onEndOrTimeout(eventId) { + this.statusItem.hide(); + const resolve = this._promises.get(eventId); + if (resolve) { + this._promises.delete(eventId); + resolve(); } - if (doc.filetype.startsWith('typescript')) { - return this._enableTypescriptSuggestions; + } + onTypesInstallerInitializationFailed() { + this.statusItem.hide(); + if (!this._invalid) { + coc_nvim_1.workspace.showMessage('Could not install typings files for JavaScript language features. Please ensure that NPM is installed', 'error'); } - return true; + this._invalid = true; } } -exports.DiagnosticsManager = DiagnosticsManager; +exports.AtaProgressReporter = AtaProgressReporter; /***/ }), @@ -14863,79 +14759,131 @@ exports.DiagnosticsManager = DiagnosticsManager; "use strict"; -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", { value: true }); -exports.isWindowsPath = exports.ResourceMap = void 0; -/** - * Maps of file resources - * - * Attempts to handle correct mapping on both case sensitive and case in-sensitive - * file systems. - */ -class ResourceMap { - constructor(_normalizePath) { - this._normalizePath = _normalizePath; - this._map = new Map(); - } - has(resource) { - const file = this.toKey(resource); - return !!file && this._map.has(file); - } - get(resource) { - const file = this.toKey(resource); - return file ? this._map.get(file) : undefined; +const coc_nvim_1 = __webpack_require__(1); +const path_1 = __importDefault(__webpack_require__(13)); +const vscode_languageserver_protocol_1 = __webpack_require__(3); +const countRegex = /Found\s+(\d+)\s+error/; +const errorRegex = /^(.+)\((\d+),(\d+)\):\s(\w+)\sTS(\d+):\s*(.+)$/; +var TscStatus; +(function (TscStatus) { + TscStatus[TscStatus["INIT"] = 0] = "INIT"; + TscStatus[TscStatus["COMPILING"] = 1] = "COMPILING"; + TscStatus[TscStatus["RUNNING"] = 2] = "RUNNING"; + TscStatus[TscStatus["ERROR"] = 3] = "ERROR"; +})(TscStatus || (TscStatus = {})); +class WatchProject { + constructor(client) { + this.client = client; + this.disposables = []; + this.statusItem = coc_nvim_1.workspace.createStatusBarItem(1, { progress: true }); + let task = this.task = coc_nvim_1.workspace.createTask('TSC'); + this.disposables.push(coc_nvim_1.commands.registerCommand(WatchProject.id, async () => { + let opts = this.options = await this.getOptions(); + await this.start(opts); + })); + task.onExit(code => { + if (code != 0) { + coc_nvim_1.workspace.showMessage(`TSC exit with code ${code}`, 'warning'); + } + this.onStop(); + }); + task.onStdout(lines => { + for (let line of lines) { + this.onLine(line); + } + }); + task.onStderr(lines => { + coc_nvim_1.workspace.showMessage(`TSC error: ` + lines.join('\n'), 'error'); + }); + this.disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => { + task.dispose(); + })); + this.check().catch(_e => { + // noop + }); } - set(resource, value) { - const file = this.toKey(resource); - if (file) { - this._map.set(file, value); + async check() { + let running = await this.task.running; + if (running) { + this.options = await this.getOptions(); + this.statusItem.isProgress = false; + this.statusItem.text = '?'; + this.statusItem.show(); } - } - delete(resource) { - const file = this.toKey(resource); - if (file) { - this._map.delete(file); + else { + this.onStop(); } } - get values() { - return this._map.values(); + async start(options) { + await this.task.start(options); } - get keys() { - return this._map.keys(); + onStop() { + this.statusItem.hide(); } - toKey(resource) { - const key = this._normalizePath - ? this._normalizePath(resource) - : resource; - if (!key) { - return key; - } - return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key; + onStart() { + this.statusItem.text = 'compiling'; + this.statusItem.isProgress = true; + this.statusItem.show(); + coc_nvim_1.workspace.nvim.call('setqflist', [[]], true); } - isCaseInsensitivePath(path) { - if (isWindowsPath(path)) { - return true; + onLine(line) { + if (countRegex.test(line)) { + let ms = line.match(countRegex); + this.statusItem.text = ms[1] == '0' ? '✓' : '✗'; + this.statusItem.isProgress = false; + } + else if (WatchProject.startTexts.findIndex(s => line.indexOf(s) !== -1) != -1) { + this.onStart(); + } + else { + let ms = line.match(errorRegex); + if (!ms) + return; + let fullpath = path_1.default.join(this.options.cwd, ms[1]); + let uri = coc_nvim_1.Uri.file(fullpath).toString(); + let doc = coc_nvim_1.workspace.getDocument(uri); + let bufnr = doc ? doc.bufnr : null; + let item = { + filename: fullpath, + lnum: Number(ms[2]), + col: Number(ms[3]), + text: `[tsc ${ms[5]}] ${ms[6]}`, + type: /error/i.test(ms[4]) ? 'E' : 'W' + }; + if (bufnr) + item.bufnr = bufnr; + coc_nvim_1.workspace.nvim.call('setqflist', [[item], 'a']); } - return path[0] === '/' && this.onIsCaseInsenitiveFileSystem; } - get onIsCaseInsenitiveFileSystem() { - if (process.platform === 'win32') { - return true; + async getOptions() { + let { tscPath } = this.client; + if (!tscPath) { + coc_nvim_1.workspace.showMessage(`Local & global tsc not found`, 'error'); + return; } - if (process.platform === 'darwin') { - return true; + let find = await coc_nvim_1.workspace.findUp(['tsconfig.json']); + if (!find) { + coc_nvim_1.workspace.showMessage('tsconfig.json not found!', 'error'); + return; } - return false; + let root = path_1.default.dirname(find); + return { + cmd: tscPath, + args: ['-p', 'tsconfig.json', '--watch', 'true', '--pretty', 'false'], + cwd: root + }; + } + dispose() { + coc_nvim_1.disposeAll(this.disposables); } } -exports.ResourceMap = ResourceMap; -function isWindowsPath(path) { - return /^[a-zA-Z]:\\/.test(path); -} -exports.isWindowsPath = isWindowsPath; +exports.default = WatchProject; +WatchProject.id = 'tsserver.watchBuild'; +WatchProject.startTexts = ['Starting compilation in watch mode', 'Starting incremental compilation']; /***/ }), @@ -14944,96 +14892,120 @@ exports.isWindowsPath = isWindowsPath; "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", { value: true }); -exports.AtaProgressReporter = void 0; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const vscode_languageserver_protocol_1 = __webpack_require__(3); const coc_nvim_1 = __webpack_require__(1); -const typingsInstallTimeout = 30 * 1000; -class TypingsStatus { - constructor(client) { - this._acquiringTypings = Object.create({}); - this._subscriptions = []; - this._client = client; - this._subscriptions.push(this._client.onDidBeginInstallTypings(event => this.onBeginInstallTypings(event.eventId))); - this._subscriptions.push(this._client.onDidEndInstallTypings(event => this.onEndInstallTypings(event.eventId))); - } - dispose() { - this._subscriptions.forEach(x => x.dispose()); - for (const eventId of Object.keys(this._acquiringTypings)) { - clearTimeout(this._acquiringTypings[eventId]); - } +const typeConverters = __importStar(__webpack_require__(37)); +const api_1 = __importDefault(__webpack_require__(40)); +function getSymbolKind(item) { + switch (item.kind) { + case 'method': + return vscode_languageserver_protocol_1.SymbolKind.Method; + case 'enum': + return vscode_languageserver_protocol_1.SymbolKind.Enum; + case 'function': + return vscode_languageserver_protocol_1.SymbolKind.Function; + case 'class': + return vscode_languageserver_protocol_1.SymbolKind.Class; + case 'interface': + return vscode_languageserver_protocol_1.SymbolKind.Interface; + case 'var': + return vscode_languageserver_protocol_1.SymbolKind.Variable; + default: + return vscode_languageserver_protocol_1.SymbolKind.Variable; } - get isAcquiringTypings() { - return Object.keys(this._acquiringTypings).length > 0; +} +class TypeScriptWorkspaceSymbolProvider { + constructor(client, languageIds) { + this.client = client; + this.languageIds = languageIds; } - onBeginInstallTypings(eventId) { - if (this._acquiringTypings[eventId]) { - return; + async provideWorkspaceSymbols(search, token) { + let filepath; + if (this.searchAllOpenProjects) { + filepath = undefined; } - this._acquiringTypings[eventId] = setTimeout(() => { - this.onEndInstallTypings(eventId); - }, typingsInstallTimeout); - } - onEndInstallTypings(eventId) { - const timer = this._acquiringTypings[eventId]; - if (timer) { - clearTimeout(timer); + else { + let uri = this.getUri(); + filepath = uri ? this.client.toPath(uri) : undefined; + if (!filepath && this.client.apiVersion.lt(api_1.default.v390)) { + return []; + } } - delete this._acquiringTypings[eventId]; - } -} -exports.default = TypingsStatus; -class AtaProgressReporter { - constructor(client) { - this._promises = new Map(); - this._invalid = false; - this.statusItem = coc_nvim_1.workspace.createStatusBarItem(10, { progress: true }); - const disposables = []; - disposables.push(client.onDidBeginInstallTypings(e => this._onBegin(e.eventId))); - disposables.push(client.onDidEndInstallTypings(e => this._onEndOrTimeout(e.eventId))); - disposables.push(client.onTypesInstallerInitializationFailed(_ => this.onTypesInstallerInitializationFailed())); - this._disposable = vscode_languageserver_protocol_1.Disposable.create(() => { - disposables.forEach(disposable => { - disposable.dispose(); - }); - }); - } - dispose() { - this._disposable.dispose(); - this._promises.forEach(value => value()); - } - _onBegin(eventId) { - const handle = setTimeout(() => this._onEndOrTimeout(eventId), typingsInstallTimeout); - new Promise(resolve => { - this._promises.set(eventId, () => { - clearTimeout(handle); - resolve(); - }); - }); - this.statusItem.text = 'Fetching data for better TypeScript IntelliSense'; - this.statusItem.show(); + const args = { + file: filepath, + searchValue: search, + maxResultCount: 256, + }; + const response = await this.client.execute('navto', args, token); + if (response.type !== 'response' || response.body == null) + return []; + const result = []; + for (const item of response.body) { + if (!item.containerName && item.kind === 'alias') { + continue; + } + const label = TypeScriptWorkspaceSymbolProvider.getLabel(item); + const range = { + start: typeConverters.Position.fromLocation(item.start), + end: typeConverters.Position.fromLocation(item.end), + }; + const symbolInfo = vscode_languageserver_protocol_1.SymbolInformation.create(label, getSymbolKind(item), range, this.client.toResource(item.file)); + result.push(symbolInfo); + } + return result; } - _onEndOrTimeout(eventId) { - this.statusItem.hide(); - const resolve = this._promises.get(eventId); - if (resolve) { - this._promises.delete(eventId); - resolve(); + static getLabel(item) { + let label = item.name; + if (item.kind === 'method' || item.kind === 'function') { + label += '()'; } + return label; } - onTypesInstallerInitializationFailed() { - this.statusItem.hide(); - if (!this._invalid) { - coc_nvim_1.workspace.showMessage('Could not install typings files for JavaScript language features. Please ensure that NPM is installed', 'error'); + getUri() { + // typescript wants to have a resource even when asking + // general questions so we check the active editor. If this + // doesn't match we take the first TS document. + const documents = coc_nvim_1.workspace.textDocuments; + for (const document of documents) { + if (this.languageIds.indexOf(document.languageId) >= 0) { + return document.uri; + } } - this._invalid = true; + return undefined; + } + get searchAllOpenProjects() { + return this.client.apiVersion.gte(api_1.default.v390) + && coc_nvim_1.workspace.getConfiguration('typescript').get('workspaceSymbols.scope', 'allOpenProjects') === 'allOpenProjects'; } } -exports.AtaProgressReporter = AtaProgressReporter; +exports.default = TypeScriptWorkspaceSymbolProvider; /***/ }), @@ -15057,18 +15029,64 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.standardLanguageDescriptions = void 0; +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +const languageModeIds = __importStar(__webpack_require__(120)); +exports.standardLanguageDescriptions = [ + { + id: 'typescript', + diagnosticSource: 'ts', + diagnosticOwner: 'typescript', + modeIds: [languageModeIds.typescript, languageModeIds.typescriptreact, + languageModeIds.typescripttsx, languageModeIds.typescriptjsx], + diagnosticLanguage: 1 /* TypeScript */, + configFile: 'tsconfig.json', + configFilePattern: /^tsconfig(\..*)?\.json$/gi + }, + { + id: 'javascript', + diagnosticSource: 'ts', + diagnosticOwner: 'typescript', + modeIds: [languageModeIds.javascript, languageModeIds.javascriptreact, languageModeIds.javascriptjsx], + diagnosticLanguage: 0 /* JavaScript */, + configFile: 'jsconfig.json', + configFilePattern: /^jsconfig(\..*)?\.json$/gi + } +]; + + +/***/ }), +/* 141 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ConfigurePluginCommand = exports.AutoFixCommand = exports.TypeScriptGoToProjectConfigCommand = exports.OpenTsServerLogCommand = exports.ReloadProjectsCommand = void 0; @@ -15076,71 +15094,68 @@ const coc_nvim_1 = __webpack_require__(1); const vscode_languageserver_protocol_1 = __webpack_require__(3); const typeConverters = __importStar(__webpack_require__(37)); const vscode_languageserver_types_1 = __webpack_require__(18); -const modules_1 = __webpack_require__(112); -const helper_1 = __webpack_require__(100); -const languageModeIds_1 = __webpack_require__(116); +const modules_1 = __webpack_require__(100); +const helper_1 = __webpack_require__(98); class ReloadProjectsCommand { - constructor(client) { - this.client = client; + constructor(service) { + this.service = service; this.id = 'tsserver.reloadProjects'; } - execute() { - this.client.reloadProjects(); + async execute() { + let client = await this.service.getClientHost(); + client.reloadProjects(); coc_nvim_1.workspace.showMessage('projects reloaded'); } } exports.ReloadProjectsCommand = ReloadProjectsCommand; class OpenTsServerLogCommand { - constructor(client) { - this.client = client; + constructor(service) { + this.service = service; this.id = 'tsserver.openTsServerLog'; } - execute() { - this.client.serviceClient.openTsServerLogFile(); // tslint:disable-line + async execute() { + let client = await this.service.getClientHost(); + client.serviceClient.openTsServerLogFile(); // tslint:disable-line } } exports.OpenTsServerLogCommand = OpenTsServerLogCommand; class TypeScriptGoToProjectConfigCommand { - constructor(client) { - this.client = client; + constructor(service) { + this.service = service; this.id = 'tsserver.goToProjectConfig'; } - execute() { - return __awaiter(this, void 0, void 0, function* () { - let doc = yield coc_nvim_1.workspace.document; - let { filetype } = doc; - if (languageModeIds_1.languageIds.indexOf(filetype) == -1) { - coc_nvim_1.workspace.showMessage(`Could not determine TypeScript or JavaScript project. Unsupported file type: ${filetype}`, 'warning'); - return; - } - // doc.filetype - yield goToProjectConfig(this.client, doc.uri); - }); + async execute() { + let client = await this.service.getClientHost(); + let doc = await coc_nvim_1.workspace.document; + let { languageId } = doc.textDocument; + if (client.serviceClient.modeIds.indexOf(languageId) == -1) { + throw new Error(`Could not determine TypeScript or JavaScript project. Unsupported file type: ${languageId}`); + return; + } + await goToProjectConfig(client, doc.uri); } } exports.TypeScriptGoToProjectConfigCommand = TypeScriptGoToProjectConfigCommand; -function goToProjectConfig(clientHost, uri) { - return __awaiter(this, void 0, void 0, function* () { - const client = clientHost.serviceClient; - const file = client.toPath(uri); - let res; - try { - res = yield client.execute('projectInfo', { file, needFileNameList: false }, vscode_languageserver_protocol_1.CancellationToken.None); - } - catch (_a) { - // noop - } - if (!res || !res.body) { - coc_nvim_1.workspace.showMessage('Could not determine TypeScript or JavaScript project.', 'warning'); - return; - } - const { configFileName } = res.body; - if (configFileName && !isImplicitProjectConfigFile(configFileName)) { - yield coc_nvim_1.workspace.openResource(coc_nvim_1.Uri.file(configFileName).toString()); - return; - } - coc_nvim_1.workspace.showMessage('Config file not found', 'warning'); - }); +async function goToProjectConfig(clientHost, uri) { + const client = clientHost.serviceClient; + const file = client.toPath(uri); + let res; + try { + res = await client.execute('projectInfo', { file, needFileNameList: false }, vscode_languageserver_protocol_1.CancellationToken.None); + } + catch (_a) { + // noop + } + if (!res || !res.body) { + coc_nvim_1.workspace.showMessage('Could not determine TypeScript or JavaScript project.', 'warning'); + return; + } + const { configFileName } = res.body; + if (configFileName && !isImplicitProjectConfigFile(configFileName)) { + await coc_nvim_1.workspace.openResource(coc_nvim_1.Uri.file(configFileName).toString()); + return; + } + coc_nvim_1.workspace.showMessage('Config file not found', 'warning'); } function isImplicitProjectConfigFile(configFileName) { return configFileName.indexOf('/dev/null/') === 0; @@ -15151,83 +15166,85 @@ const autoFixableDiagnosticCodes = new Set([ 2304, ]); class AutoFixCommand { - constructor(client) { - this.client = client; + constructor(service) { + this.service = service; this.id = 'tsserver.executeAutofix'; } - execute() { - return __awaiter(this, void 0, void 0, function* () { - let document = yield coc_nvim_1.workspace.document; - let { uri } = document; - if (!this.client.handles(uri)) { - coc_nvim_1.workspace.showMessage(`Document ${uri} is not handled by tsserver.`, 'warning'); - return; - } - let file = this.client.serviceClient.toPath(document.uri); - let diagnostics = coc_nvim_1.diagnosticManager.getDiagnostics(document.uri); - let missingDiagnostics = diagnostics.filter(o => o.code == 2307); - if (missingDiagnostics.length) { - let names = missingDiagnostics.map(o => { - let ms = o.message.match(/module\s'(.+)'\./); - return ms ? ms[1] : null; + async execute() { + if (this.service.state != coc_nvim_1.ServiceStat.Running) { + throw new Error('service not running'); + return; + } + let client = await this.service.getClientHost(); + let document = await coc_nvim_1.workspace.document; + let handles = await client.handles(document.textDocument); + if (!handles) { + throw new Error(`Document ${document.uri} is not handled by tsserver.`); + return; + } + let file = client.serviceClient.toPath(document.uri); + let diagnostics = coc_nvim_1.diagnosticManager.getDiagnostics(document.uri); + let missingDiagnostics = diagnostics.filter(o => o.code == 2307); + if (missingDiagnostics.length) { + let names = missingDiagnostics.map(o => { + let ms = o.message.match(/module\s'(.+)'\./); + return ms ? ms[1] : null; + }); + names = names.filter(s => s != null); + if (names.length) { + modules_1.installModules(document.uri, names).catch(e => { + console.error(e.message); // tslint:disable-line }); - names = names.filter(s => s != null); - if (names.length) { - modules_1.installModules(document.uri, names).catch(e => { - console.error(e.message); // tslint:disable-line - }); - } } - diagnostics = diagnostics.filter(x => autoFixableDiagnosticCodes.has(x.code)); - if (diagnostics.length == 0) - return; - diagnostics = diagnostics.reduce((arr, curr) => { - if (curr.code == 2304 && arr.findIndex(o => o.message == curr.message) != -1) - return arr; - arr.push(curr); + } + diagnostics = diagnostics.filter(x => autoFixableDiagnosticCodes.has(x.code)); + if (diagnostics.length == 0) + return; + diagnostics = diagnostics.reduce((arr, curr) => { + if (curr.code == 2304 && arr.findIndex(o => o.message == curr.message) != -1) return arr; - }, []); - let client = this.client.serviceClient; - let edits = []; - let command; - let names = []; - for (let diagnostic of diagnostics) { - const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+(diagnostic.code)] }); - const response = yield client.execute('getCodeFixes', args, vscode_languageserver_protocol_1.CancellationToken.None); - if (response.type !== 'response' || !response.body || response.body.length < 1) { - if (diagnostic.code == 2304) { - let { range } = diagnostic; - let line = document.getline(range.start.line); - let name = line.slice(range.start.character, range.end.character); - if (helper_1.nodeModules.indexOf(name) !== -1 && names.indexOf(name) == -1) { - names.push(name); - edits.push({ - range: vscode_languageserver_types_1.Range.create(0, 0, 0, 0), - newText: `import ${name} from '${name}'\n` - }); - command = 'tsserver.organizeImports'; - } - } - continue; - } - const fix = response.body[0]; - for (let change of fix.changes) { - if (change.fileName != file) - continue; - // change.fileName - for (let ch of change.textChanges) { + arr.push(curr); + return arr; + }, []); + let edits = []; + let command; + let names = []; + for (let diagnostic of diagnostics) { + const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+(diagnostic.code)] }); + const response = await client.serviceClient.execute('getCodeFixes', args, vscode_languageserver_protocol_1.CancellationToken.None); + if (response.type !== 'response' || !response.body || response.body.length < 1) { + if (diagnostic.code == 2304) { + let { range } = diagnostic; + let line = document.getline(range.start.line); + let name = line.slice(range.start.character, range.end.character); + if (helper_1.nodeModules.indexOf(name) !== -1 && names.indexOf(name) == -1) { + names.push(name); edits.push({ - range: typeConverters.Range.fromTextSpan(ch), - newText: ch.newText + range: vscode_languageserver_types_1.Range.create(0, 0, 0, 0), + newText: `import ${name} from '${name}'\n` }); + command = 'tsserver.organizeImports'; } } + continue; } - if (edits.length) - yield document.applyEdits(coc_nvim_1.workspace.nvim, edits); - if (command) - coc_nvim_1.commands.executeCommand(command); - }); + const fix = response.body[0]; + for (let change of fix.changes) { + if (change.fileName != file) + continue; + // change.fileName + for (let ch of change.textChanges) { + edits.push({ + range: typeConverters.Range.fromTextSpan(ch), + newText: ch.newText + }); + } + } + } + if (edits.length) + await document.applyEdits(edits); + if (command) + coc_nvim_1.commands.executeCommand(command); } } exports.AutoFixCommand = AutoFixCommand; @@ -15244,7 +15261,7 @@ exports.ConfigurePluginCommand = ConfigurePluginCommand; /***/ }), -/* 141 */ +/* 142 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -15268,7 +15285,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; };