chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 12:38:42 +08:00
commit 2d485ba600
8326 changed files with 2641263 additions and 0 deletions
@@ -0,0 +1,2 @@
legacy-peer-deps="true"
timeout=180000
@@ -0,0 +1,33 @@
{
"version": "0.1.0",
// List of configurations. Add new configurations or edit existing ones.
"configurations": [
{
"name": "Attach",
"type": "node",
"request": "attach",
"port": 6044,
"protocol": "inspector",
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/out/**/*.js"]
},
{
"name": "Unit Tests",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/../../../node_modules/mocha/bin/_mocha",
"stopOnEntry": false,
"args": [
"--timeout",
"999999",
"--colors"
],
"cwd": "${workspaceFolder}",
"runtimeExecutable": null,
"runtimeArgs": [],
"env": {},
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/out/**/*.js"]
}
]
}
@@ -0,0 +1,9 @@
{
"version": "0.1.0",
"command": "npm",
"isShellCommand": true,
"showOutput": "silent",
"args": ["run", "watch"],
"isWatching": true,
"problemMatcher": "$tsc-watch"
}
@@ -0,0 +1,24 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const withBrowserDefaults = require('../../shared.webpack.config').browser;
const path = require('path');
module.exports = withBrowserDefaults({
context: __dirname,
entry: {
extension: './src/browser/cssServerWorkerMain.ts',
},
output: {
filename: 'cssServerMain.js',
path: path.join(__dirname, 'dist', 'browser'),
libraryTarget: 'var',
library: 'serverExportVar'
}
});
@@ -0,0 +1,22 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const withDefaults = require('../../shared.webpack.config');
const path = require('path');
module.exports = withDefaults({
context: path.join(__dirname),
entry: {
extension: './src/node/cssServerNodeMain.ts',
},
output: {
filename: 'cssServerMain.js',
path: path.join(__dirname, 'dist', 'node'),
}
});
+113
View File
@@ -0,0 +1,113 @@
{
"name": "vscode-css-languageserver",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "vscode-css-languageserver",
"version": "1.0.0",
"license": "MIT",
"dependencies": {
"@vscode/l10n": "^0.0.18",
"vscode-css-languageservice": "^6.3.3",
"vscode-languageserver": "^10.0.0-next.11",
"vscode-uri": "^3.0.8"
},
"devDependencies": {
"@types/mocha": "^9.1.1",
"@types/node": "20.x"
},
"engines": {
"node": "*"
}
},
"node_modules/@types/mocha": {
"version": "9.1.1",
"resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-9.1.1.tgz",
"integrity": "sha512-Z61JK7DKDtdKTWwLeElSEBcWGRLY8g95ic5FoQqI9CMx0ns/Ghep3B4DfcEimiKMvtamNVULVNKEsiwV3aQmXw==",
"dev": true
},
"node_modules/@types/node": {
"version": "20.11.24",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.24.tgz",
"integrity": "sha512-Kza43ewS3xoLgCEpQrsT+xRo/EJej1y0kVYGiLFE1NEODXGzTfwiC6tXTLMQskn1X4/Rjlh0MQUvx9W+L9long==",
"dev": true,
"dependencies": {
"undici-types": "~5.26.4"
}
},
"node_modules/@vscode/l10n": {
"version": "0.0.18",
"resolved": "https://registry.npmjs.org/@vscode/l10n/-/l10n-0.0.18.tgz",
"integrity": "sha512-KYSIHVmslkaCDyw013pphY+d7x1qV8IZupYfeIfzNA+nsaWHbn5uPuQRvdRFsa9zFzGeudPuoGoZ1Op4jrJXIQ=="
},
"node_modules/undici-types": {
"version": "5.26.5",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
"dev": true
},
"node_modules/vscode-css-languageservice": {
"version": "6.3.3",
"resolved": "https://registry.npmjs.org/vscode-css-languageservice/-/vscode-css-languageservice-6.3.3.tgz",
"integrity": "sha512-xXa+ftMPv6JxRgzkvPwZuDCafIdwDW3kyijGcfij1a2qBVScr2qli6MfgJzYm/AMYdbHq9I/4hdpKV0Thim2EA==",
"license": "MIT",
"dependencies": {
"@vscode/l10n": "^0.0.18",
"vscode-languageserver-textdocument": "^1.0.12",
"vscode-languageserver-types": "3.17.5",
"vscode-uri": "^3.0.8"
}
},
"node_modules/vscode-jsonrpc": {
"version": "9.0.0-next.6",
"resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-9.0.0-next.6.tgz",
"integrity": "sha512-KCSvUNsFiVciG9iqjJKBZOd66CN3ZKohDlYRmoOi+pd8l15MFLZ8wRG4c+wuzePGba/8WcCG2TM+C/GVlvuaeA==",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/vscode-languageserver": {
"version": "10.0.0-next.11",
"resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-10.0.0-next.11.tgz",
"integrity": "sha512-cmobSrVDYhlh/t02vz/bV8nNpds8mus5HnILULae2iAvOjoaJPnTAp0jJWoYdUqTpIVzT9JV6JMKqLEvdqpeqg==",
"license": "MIT",
"dependencies": {
"vscode-languageserver-protocol": "3.17.6-next.11"
},
"bin": {
"installServerIntoExtension": "bin/installServerIntoExtension"
}
},
"node_modules/vscode-languageserver-protocol": {
"version": "3.17.6-next.11",
"resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.6-next.11.tgz",
"integrity": "sha512-GeJxEp1TiLsp79f8WG5n10wLViXfgFKb99hU9K8m7KDWM95/QFEqWkm79f9LVm54tUK74I91a9EeiQLCS/FABQ==",
"dependencies": {
"vscode-jsonrpc": "9.0.0-next.6",
"vscode-languageserver-types": "3.17.6-next.5"
}
},
"node_modules/vscode-languageserver-protocol/node_modules/vscode-languageserver-types": {
"version": "3.17.6-next.5",
"resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.6-next.5.tgz",
"integrity": "sha512-QFmf3Yl1tCgUQfA77N9Me/LXldJXkIVypQbty2rJ1DNHQkC+iwvm4Z2tXg9czSwlhvv0pD4pbF5mT7WhAglolw=="
},
"node_modules/vscode-languageserver-textdocument": {
"version": "1.0.12",
"resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz",
"integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA=="
},
"node_modules/vscode-languageserver-types": {
"version": "3.17.5",
"resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz",
"integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg=="
},
"node_modules/vscode-uri": {
"version": "3.0.8",
"resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.0.8.tgz",
"integrity": "sha512-AyFQ0EVmsOZOlAnxoFOGOq1SQDWAB7C6aqMGS23svWAllfOaxbuFvcT8D1i8z3Gyn8fraVeZNNmN6e9bxxXkKw=="
}
}
}
@@ -0,0 +1,31 @@
{
"name": "vscode-css-languageserver",
"description": "CSS/LESS/SCSS language server",
"version": "1.0.0",
"author": "Microsoft Corporation",
"license": "MIT",
"engines": {
"node": "*"
},
"main": "./out/node/cssServerMain",
"browser": "./dist/browser/cssServerMain",
"dependencies": {
"@vscode/l10n": "^0.0.18",
"vscode-css-languageservice": "^6.3.3",
"vscode-languageserver": "^10.0.0-next.11",
"vscode-uri": "^3.0.8"
},
"devDependencies": {
"@types/mocha": "^9.1.1",
"@types/node": "20.x"
},
"scripts": {
"compile": "gulp compile-extension:css-language-features-server",
"watch": "gulp watch-extension:css-language-features-server",
"install-service-next": "npm install vscode-css-languageservice",
"install-service-local": "npm link vscode-css-languageservice",
"install-server-next": "npm install vscode-languageserver@next",
"install-server-local": "npm install vscode-languageserver",
"test": "node ./test/index.js"
}
}
@@ -0,0 +1,30 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { createConnection, BrowserMessageReader, BrowserMessageWriter, Disposable } from 'vscode-languageserver/browser';
import { RuntimeEnvironment, startServer } from '../cssServer';
const messageReader = new BrowserMessageReader(self);
const messageWriter = new BrowserMessageWriter(self);
const connection = createConnection(messageReader, messageWriter);
console.log = connection.console.log.bind(connection.console);
console.error = connection.console.error.bind(connection.console);
const runtime: RuntimeEnvironment = {
timer: {
setImmediate(callback: (...args: any[]) => void, ...args: any[]): Disposable {
const handle = setTimeout(callback, 0, ...args);
return { dispose: () => clearTimeout(handle) };
},
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): Disposable {
const handle = setTimeout(callback, ms, ...args);
return { dispose: () => clearTimeout(handle) };
}
}
};
startServer(connection, runtime);
@@ -0,0 +1,35 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as l10n from '@vscode/l10n';
let initialized = false;
const pendingMessages: any[] = [];
const messageHandler = async (e: any) => {
if (!initialized) {
const l10nLog: string[] = [];
initialized = true;
const i10lLocation = e.data.i10lLocation;
if (i10lLocation) {
try {
await l10n.config({ uri: i10lLocation });
l10nLog.push(`l10n: Configured to ${i10lLocation.toString()}.`);
} catch (e) {
l10nLog.push(`l10n: Problems loading ${i10lLocation.toString()} : ${e}.`);
}
} else {
l10nLog.push(`l10n: No bundle configured.`);
}
await import('./cssServerMain.js');
if (self.onmessage !== messageHandler) {
pendingMessages.forEach(msg => self.onmessage?.(msg));
pendingMessages.length = 0;
}
l10nLog.forEach(console.log);
} else {
pendingMessages.push(e);
}
};
self.onmessage = messageHandler;
@@ -0,0 +1,389 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import {
Connection, TextDocuments, InitializeParams, InitializeResult, ServerCapabilities, ConfigurationRequest, WorkspaceFolder, TextDocumentSyncKind, NotificationType, Disposable, TextDocumentIdentifier, Range, FormattingOptions, TextEdit, Diagnostic
} from 'vscode-languageserver';
import { URI } from 'vscode-uri';
import { getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageSettings, LanguageService, Stylesheet, TextDocument, Position } from 'vscode-css-languageservice';
import { getLanguageModelCache } from './languageModelCache';
import { runSafeAsync } from './utils/runner';
import { DiagnosticsSupport, registerDiagnosticsPullSupport, registerDiagnosticsPushSupport } from './utils/validation';
import { getDocumentContext } from './utils/documentContext';
import { fetchDataProviders } from './customData';
import { RequestService, getRequestService } from './requests';
namespace CustomDataChangedNotification {
export const type: NotificationType<string[]> = new NotificationType('css/customDataChanged');
}
export interface Settings {
css: LanguageSettings;
less: LanguageSettings;
scss: LanguageSettings;
}
export interface RuntimeEnvironment {
readonly file?: RequestService;
readonly http?: RequestService;
readonly timer: {
setImmediate(callback: (...args: any[]) => void, ...args: any[]): Disposable;
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): Disposable;
};
}
export function startServer(connection: Connection, runtime: RuntimeEnvironment) {
// Create a text document manager.
const documents = new TextDocuments(TextDocument);
// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);
const stylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => getLanguageService(document).parseStylesheet(document));
documents.onDidClose(e => {
stylesheets.onDocumentRemoved(e.document);
});
connection.onShutdown(() => {
stylesheets.dispose();
});
let scopedSettingsSupport = false;
let foldingRangeLimit = Number.MAX_VALUE;
let workspaceFolders: WorkspaceFolder[];
let formatterMaxNumberOfEdits = Number.MAX_VALUE;
let dataProvidersReady: Promise<any> = Promise.resolve();
let diagnosticsSupport: DiagnosticsSupport | undefined;
const languageServices: { [id: string]: LanguageService } = {};
const notReady = () => Promise.reject('Not Ready');
let requestService: RequestService = { getContent: notReady, stat: notReady, readDirectory: notReady };
// After the server has started the client sends an initialize request. The server receives
// in the passed params the rootPath of the workspace plus the client capabilities.
connection.onInitialize((params: InitializeParams): InitializeResult => {
const initializationOptions = params.initializationOptions as any || {};
workspaceFolders = (<any>params).workspaceFolders;
if (!Array.isArray(workspaceFolders)) {
workspaceFolders = [];
if (params.rootPath) {
workspaceFolders.push({ name: '', uri: URI.file(params.rootPath).toString(true) });
}
}
requestService = getRequestService(initializationOptions?.handledSchemas || ['file'], connection, runtime);
function getClientCapability<T>(name: string, def: T) {
const keys = name.split('.');
let c: any = params.capabilities;
for (let i = 0; c && i < keys.length; i++) {
if (!c.hasOwnProperty(keys[i])) {
return def;
}
c = c[keys[i]];
}
return c;
}
const snippetSupport = !!getClientCapability('textDocument.completion.completionItem.snippetSupport', false);
scopedSettingsSupport = !!getClientCapability('workspace.configuration', false);
foldingRangeLimit = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE);
formatterMaxNumberOfEdits = initializationOptions?.customCapabilities?.rangeFormatting?.editLimit || Number.MAX_VALUE;
languageServices.css = getCSSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities });
languageServices.scss = getSCSSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities });
languageServices.less = getLESSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities });
const supportsDiagnosticPull = getClientCapability('textDocument.diagnostic', undefined);
if (supportsDiagnosticPull === undefined) {
diagnosticsSupport = registerDiagnosticsPushSupport(documents, connection, runtime, validateTextDocument);
} else {
diagnosticsSupport = registerDiagnosticsPullSupport(documents, connection, runtime, validateTextDocument);
}
const capabilities: ServerCapabilities = {
textDocumentSync: TextDocumentSyncKind.Incremental,
completionProvider: snippetSupport ? { resolveProvider: false, triggerCharacters: ['/', '-', ':'] } : undefined,
hoverProvider: true,
documentSymbolProvider: true,
referencesProvider: true,
definitionProvider: true,
documentHighlightProvider: true,
documentLinkProvider: {
resolveProvider: false
},
codeActionProvider: true,
renameProvider: true,
colorProvider: {},
foldingRangeProvider: true,
selectionRangeProvider: true,
diagnosticProvider: {
documentSelector: null,
interFileDependencies: false,
workspaceDiagnostics: false
},
documentRangeFormattingProvider: initializationOptions?.provideFormatter === true,
documentFormattingProvider: initializationOptions?.provideFormatter === true,
};
return { capabilities };
});
function getLanguageService(document: TextDocument) {
let service = languageServices[document.languageId];
if (!service) {
connection.console.log('Document type is ' + document.languageId + ', using css instead.');
service = languageServices['css'];
}
return service;
}
let documentSettings: { [key: string]: Thenable<LanguageSettings | undefined> } = {};
// remove document settings on close
documents.onDidClose(e => {
delete documentSettings[e.document.uri];
});
function getDocumentSettings(textDocument: TextDocument): Thenable<LanguageSettings | undefined> {
if (scopedSettingsSupport) {
let promise = documentSettings[textDocument.uri];
if (!promise) {
const configRequestParam = { items: [{ scopeUri: textDocument.uri, section: textDocument.languageId }] };
promise = connection.sendRequest(ConfigurationRequest.type, configRequestParam).then(s => s[0] as LanguageSettings | undefined);
documentSettings[textDocument.uri] = promise;
}
return promise;
}
return Promise.resolve(undefined);
}
// The settings have changed. Is send on server activation as well.
connection.onDidChangeConfiguration(change => {
updateConfiguration(change.settings as any);
});
function updateConfiguration(settings: any) {
for (const languageId in languageServices) {
languageServices[languageId].configure(settings[languageId]);
}
// reset all document settings
documentSettings = {};
diagnosticsSupport?.requestRefresh();
}
async function validateTextDocument(textDocument: TextDocument): Promise<Diagnostic[]> {
const settingsPromise = getDocumentSettings(textDocument);
const [settings] = await Promise.all([settingsPromise, dataProvidersReady]);
const stylesheet = stylesheets.get(textDocument);
return getLanguageService(textDocument).doValidation(textDocument, stylesheet, settings);
}
function updateDataProviders(dataPaths: string[]) {
dataProvidersReady = fetchDataProviders(dataPaths, requestService).then(customDataProviders => {
for (const lang in languageServices) {
languageServices[lang].setDataProviders(true, customDataProviders);
}
});
}
connection.onCompletion((textDocumentPosition, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(textDocumentPosition.textDocument.uri);
if (document) {
const [settings,] = await Promise.all([getDocumentSettings(document), dataProvidersReady]);
const styleSheet = stylesheets.get(document);
const documentContext = getDocumentContext(document.uri, workspaceFolders);
return getLanguageService(document).doComplete2(document, textDocumentPosition.position, styleSheet, documentContext, settings?.completion);
}
return null;
}, null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`, token);
});
connection.onHover((textDocumentPosition, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(textDocumentPosition.textDocument.uri);
if (document) {
const [settings,] = await Promise.all([getDocumentSettings(document), dataProvidersReady]);
const styleSheet = stylesheets.get(document);
return getLanguageService(document).doHover(document, textDocumentPosition.position, styleSheet, settings?.hover);
}
return null;
}, null, `Error while computing hover for ${textDocumentPosition.textDocument.uri}`, token);
});
connection.onDocumentSymbol((documentSymbolParams, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(documentSymbolParams.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentSymbols2(document, stylesheet);
}
return [];
}, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, token);
});
connection.onDefinition((documentDefinitionParams, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(documentDefinitionParams.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDefinition(document, documentDefinitionParams.position, stylesheet);
}
return null;
}, null, `Error while computing definitions for ${documentDefinitionParams.textDocument.uri}`, token);
});
connection.onDocumentHighlight((documentHighlightParams, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(documentHighlightParams.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentHighlights(document, documentHighlightParams.position, stylesheet);
}
return [];
}, [], `Error while computing document highlights for ${documentHighlightParams.textDocument.uri}`, token);
});
connection.onDocumentLinks(async (documentLinkParams, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(documentLinkParams.textDocument.uri);
if (document) {
await dataProvidersReady;
const documentContext = getDocumentContext(document.uri, workspaceFolders);
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentLinks2(document, stylesheet, documentContext);
}
return [];
}, [], `Error while computing document links for ${documentLinkParams.textDocument.uri}`, token);
});
connection.onReferences((referenceParams, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(referenceParams.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findReferences(document, referenceParams.position, stylesheet);
}
return [];
}, [], `Error while computing references for ${referenceParams.textDocument.uri}`, token);
});
connection.onCodeAction((codeActionParams, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(codeActionParams.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).doCodeActions(document, codeActionParams.range, codeActionParams.context, stylesheet);
}
return [];
}, [], `Error while computing code actions for ${codeActionParams.textDocument.uri}`, token);
});
connection.onDocumentColor((params, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(params.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentColors(document, stylesheet);
}
return [];
}, [], `Error while computing document colors for ${params.textDocument.uri}`, token);
});
connection.onColorPresentation((params, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(params.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).getColorPresentations(document, stylesheet, params.color, params.range);
}
return [];
}, [], `Error while computing color presentations for ${params.textDocument.uri}`, token);
});
connection.onRenameRequest((renameParameters, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(renameParameters.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).doRename(document, renameParameters.position, renameParameters.newName, stylesheet);
}
return null;
}, null, `Error while computing renames for ${renameParameters.textDocument.uri}`, token);
});
connection.onFoldingRanges((params, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(params.textDocument.uri);
if (document) {
await dataProvidersReady;
return getLanguageService(document).getFoldingRanges(document, { rangeLimit: foldingRangeLimit });
}
return null;
}, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token);
});
connection.onSelectionRanges((params, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(params.textDocument.uri);
const positions: Position[] = params.positions;
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).getSelectionRanges(document, positions, stylesheet);
}
return [];
}, [], `Error while computing selection ranges for ${params.textDocument.uri}`, token);
});
async function onFormat(textDocument: TextDocumentIdentifier, range: Range | undefined, options: FormattingOptions): Promise<TextEdit[]> {
const document = documents.get(textDocument.uri);
if (document) {
const edits = getLanguageService(document).format(document, range ?? getFullRange(document), options);
if (edits.length > formatterMaxNumberOfEdits) {
const newText = TextDocument.applyEdits(document, edits);
return [TextEdit.replace(getFullRange(document), newText)];
}
return edits;
}
return [];
}
connection.onDocumentRangeFormatting((formatParams, token) => {
return runSafeAsync(runtime, () => onFormat(formatParams.textDocument, formatParams.range, formatParams.options), [], `Error while formatting range for ${formatParams.textDocument.uri}`, token);
});
connection.onDocumentFormatting((formatParams, token) => {
return runSafeAsync(runtime, () => onFormat(formatParams.textDocument, undefined, formatParams.options), [], `Error while formatting ${formatParams.textDocument.uri}`, token);
});
connection.onNotification(CustomDataChangedNotification.type, updateDataProviders);
// Listen on the connection
connection.listen();
}
function getFullRange(document: TextDocument): Range {
return Range.create(Position.create(0, 0), document.positionAt(document.getText().length));
}
@@ -0,0 +1,38 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ICSSDataProvider, newCSSDataProvider } from 'vscode-css-languageservice';
import { RequestService } from './requests';
export function fetchDataProviders(dataPaths: string[], requestService: RequestService): Promise<ICSSDataProvider[]> {
const providers = dataPaths.map(async p => {
try {
const content = await requestService.getContent(p);
return parseCSSData(content);
} catch (e) {
return newCSSDataProvider({ version: 1 });
}
});
return Promise.all(providers);
}
function parseCSSData(source: string): ICSSDataProvider {
let rawData: any;
try {
rawData = JSON.parse(source);
} catch (err) {
return newCSSDataProvider({ version: 1 });
}
return newCSSDataProvider({
version: rawData.version || 1,
properties: rawData.properties || [],
atDirectives: rawData.atDirectives || [],
pseudoClasses: rawData.pseudoClasses || [],
pseudoElements: rawData.pseudoElements || []
});
}
@@ -0,0 +1,82 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TextDocument } from 'vscode-css-languageservice';
export interface LanguageModelCache<T> {
get(document: TextDocument): T;
onDocumentRemoved(document: TextDocument): void;
dispose(): void;
}
export function getLanguageModelCache<T>(maxEntries: number, cleanupIntervalTimeInSec: number, parse: (document: TextDocument) => T): LanguageModelCache<T> {
let languageModels: { [uri: string]: { version: number; languageId: string; cTime: number; languageModel: T } } = {};
let nModels = 0;
let cleanupInterval: NodeJS.Timeout | undefined = undefined;
if (cleanupIntervalTimeInSec > 0) {
cleanupInterval = setInterval(() => {
const cutoffTime = Date.now() - cleanupIntervalTimeInSec * 1000;
const uris = Object.keys(languageModels);
for (const uri of uris) {
const languageModelInfo = languageModels[uri];
if (languageModelInfo.cTime < cutoffTime) {
delete languageModels[uri];
nModels--;
}
}
}, cleanupIntervalTimeInSec * 1000);
}
return {
get(document: TextDocument): T {
const version = document.version;
const languageId = document.languageId;
const languageModelInfo = languageModels[document.uri];
if (languageModelInfo && languageModelInfo.version === version && languageModelInfo.languageId === languageId) {
languageModelInfo.cTime = Date.now();
return languageModelInfo.languageModel;
}
const languageModel = parse(document);
languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now() };
if (!languageModelInfo) {
nModels++;
}
if (nModels === maxEntries) {
let oldestTime = Number.MAX_VALUE;
let oldestUri = null;
for (const uri in languageModels) {
const languageModelInfo = languageModels[uri];
if (languageModelInfo.cTime < oldestTime) {
oldestUri = uri;
oldestTime = languageModelInfo.cTime;
}
}
if (oldestUri) {
delete languageModels[oldestUri];
nModels--;
}
}
return languageModel;
},
onDocumentRemoved(document: TextDocument) {
const uri = document.uri;
if (languageModels[uri]) {
delete languageModels[uri];
nModels--;
}
},
dispose() {
if (typeof cleanupInterval !== 'undefined') {
clearInterval(cleanupInterval);
cleanupInterval = undefined;
languageModels = {};
nModels = 0;
}
}
};
}
@@ -0,0 +1,35 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { createConnection, Connection, Disposable } from 'vscode-languageserver/node';
import { formatError } from '../utils/runner';
import { RuntimeEnvironment, startServer } from '../cssServer';
import { getNodeFSRequestService } from './nodeFs';
// Create a connection for the server.
const connection: Connection = createConnection();
console.log = connection.console.log.bind(connection.console);
console.error = connection.console.error.bind(connection.console);
process.on('unhandledRejection', (e: any) => {
connection.console.error(formatError(`Unhandled exception`, e));
});
const runtime: RuntimeEnvironment = {
timer: {
setImmediate(callback: (...args: any[]) => void, ...args: any[]): Disposable {
const handle = setImmediate(callback, ...args);
return { dispose: () => clearImmediate(handle) };
},
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): Disposable {
const handle = setTimeout(callback, ms, ...args);
return { dispose: () => clearTimeout(handle) };
}
},
file: getNodeFSRequestService()
};
startServer(connection, runtime);
@@ -0,0 +1,21 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as l10n from '@vscode/l10n';
async function setupMain() {
const l10nLog: string[] = [];
const i10lLocation = process.env['VSCODE_L10N_BUNDLE_LOCATION'];
if (i10lLocation) {
try {
await l10n.config({ uri: i10lLocation });
l10nLog.push(`l10n: Configured to ${i10lLocation.toString()}`);
} catch (e) {
l10nLog.push(`l10n: Problems loading ${i10lLocation.toString()} : ${e}`);
}
}
await import('./cssServerMain.js');
l10nLog.forEach(console.log);
}
setupMain();
@@ -0,0 +1,87 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { RequestService } from '../requests';
import { URI as Uri } from 'vscode-uri';
import * as fs from 'fs';
import { FileType } from 'vscode-css-languageservice';
export function getNodeFSRequestService(): RequestService {
function ensureFileUri(location: string) {
if (!location.startsWith('file://')) {
throw new Error('fileRequestService can only handle file URLs');
}
}
return {
getContent(location: string, encoding?: BufferEncoding) {
ensureFileUri(location);
return new Promise((c, e) => {
const uri = Uri.parse(location);
fs.readFile(uri.fsPath, encoding, (err, buf) => {
if (err) {
return e(err);
}
c(buf.toString());
});
});
},
stat(location: string) {
ensureFileUri(location);
return new Promise((c, e) => {
const uri = Uri.parse(location);
fs.stat(uri.fsPath, (err, stats) => {
if (err) {
if (err.code === 'ENOENT') {
return c({ type: FileType.Unknown, ctime: -1, mtime: -1, size: -1 });
} else {
return e(err);
}
}
let type = FileType.Unknown;
if (stats.isFile()) {
type = FileType.File;
} else if (stats.isDirectory()) {
type = FileType.Directory;
} else if (stats.isSymbolicLink()) {
type = FileType.SymbolicLink;
}
c({
type,
ctime: stats.ctime.getTime(),
mtime: stats.mtime.getTime(),
size: stats.size
});
});
});
},
readDirectory(location: string) {
ensureFileUri(location);
return new Promise((c, e) => {
const path = Uri.parse(location).fsPath;
fs.readdir(path, { withFileTypes: true }, (err, children) => {
if (err) {
return e(err);
}
c(children.map(stat => {
if (stat.isSymbolicLink()) {
return [stat.name, FileType.SymbolicLink];
} else if (stat.isDirectory()) {
return [stat.name, FileType.Directory];
} else if (stat.isFile()) {
return [stat.name, FileType.File];
} else {
return [stat.name, FileType.Unknown];
}
}));
});
});
}
};
}
@@ -0,0 +1,103 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { RequestType, Connection } from 'vscode-languageserver';
import { RuntimeEnvironment } from './cssServer';
export namespace FsContentRequest {
export const type: RequestType<{ uri: string; encoding?: string }, string, any> = new RequestType('fs/content');
}
export namespace FsStatRequest {
export const type: RequestType<string, FileStat, any> = new RequestType('fs/stat');
}
export namespace FsReadDirRequest {
export const type: RequestType<string, [string, FileType][], any> = new RequestType('fs/readDir');
}
export enum FileType {
/**
* The file type is unknown.
*/
Unknown = 0,
/**
* A regular file.
*/
File = 1,
/**
* A directory.
*/
Directory = 2,
/**
* A symbolic link to a file.
*/
SymbolicLink = 64
}
export interface FileStat {
/**
* The type of the file, e.g. is a regular file, a directory, or symbolic link
* to a file.
*/
type: FileType;
/**
* The creation timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC.
*/
ctime: number;
/**
* The modification timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC.
*/
mtime: number;
/**
* The size in bytes.
*/
size: number;
}
export interface RequestService {
getContent(uri: string, encoding?: string): Promise<string>;
stat(uri: string): Promise<FileStat>;
readDirectory(uri: string): Promise<[string, FileType][]>;
}
export function getRequestService(handledSchemas: string[], connection: Connection, runtime: RuntimeEnvironment): RequestService {
const builtInHandlers: { [protocol: string]: RequestService | undefined } = {};
for (const protocol of handledSchemas) {
if (protocol === 'file') {
builtInHandlers[protocol] = runtime.file;
} else if (protocol === 'http' || protocol === 'https') {
builtInHandlers[protocol] = runtime.http;
}
}
return {
async stat(uri: string): Promise<FileStat> {
const handler = builtInHandlers[getScheme(uri)];
if (handler) {
return handler.stat(uri);
}
const res = await connection.sendRequest(FsStatRequest.type, uri.toString());
return res;
},
readDirectory(uri: string): Promise<[string, FileType][]> {
const handler = builtInHandlers[getScheme(uri)];
if (handler) {
return handler.readDirectory(uri);
}
return connection.sendRequest(FsReadDirRequest.type, uri.toString());
},
getContent(uri: string, encoding?: string): Promise<string> {
const handler = builtInHandlers[getScheme(uri)];
if (handler) {
return handler.getContent(uri, encoding);
}
return connection.sendRequest(FsContentRequest.type, { uri: uri.toString(), encoding });
}
};
}
function getScheme(uri: string) {
return uri.substr(0, uri.indexOf(':'));
}
@@ -0,0 +1,204 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'mocha';
import * as assert from 'assert';
import * as path from 'path';
import { URI } from 'vscode-uri';
import { TextDocument, CompletionList, TextEdit } from 'vscode-languageserver-types';
import { WorkspaceFolder } from 'vscode-languageserver-protocol';
import { getCSSLanguageService, LanguageServiceOptions, getSCSSLanguageService } from 'vscode-css-languageservice';
import { getNodeFSRequestService } from '../node/nodeFs';
import { getDocumentContext } from '../utils/documentContext';
export interface ItemDescription {
label: string;
resultText?: string;
}
suite('Completions', () => {
const assertCompletion = function (completions: CompletionList, expected: ItemDescription, document: TextDocument, _offset: number) {
const matches = completions.items.filter(completion => {
return completion.label === expected.label;
});
assert.strictEqual(matches.length, 1, `${expected.label} should only existing once: Actual: ${completions.items.map(c => c.label).join(', ')}`);
const match = matches[0];
if (expected.resultText && TextEdit.is(match.textEdit)) {
assert.strictEqual(TextDocument.applyEdits(document, [match.textEdit]), expected.resultText);
}
};
async function assertCompletions(value: string, expected: { count?: number; items?: ItemDescription[] }, testUri: string, workspaceFolders?: WorkspaceFolder[], lang: string = 'css'): Promise<any> {
const offset = value.indexOf('|');
value = value.substr(0, offset) + value.substr(offset + 1);
const document = TextDocument.create(testUri, lang, 0, value);
const position = document.positionAt(offset);
if (!workspaceFolders) {
workspaceFolders = [{ name: 'x', uri: testUri.substr(0, testUri.lastIndexOf('/')) }];
}
const lsOptions: LanguageServiceOptions = { fileSystemProvider: getNodeFSRequestService() };
const cssLanguageService = lang === 'scss' ? getSCSSLanguageService(lsOptions) : getCSSLanguageService(lsOptions);
const context = getDocumentContext(testUri, workspaceFolders);
const stylesheet = cssLanguageService.parseStylesheet(document);
const list = await cssLanguageService.doComplete2(document, position, stylesheet, context);
if (expected.count) {
assert.strictEqual(list.items.length, expected.count);
}
if (expected.items) {
for (const item of expected.items) {
assertCompletion(list, item, document, offset);
}
}
}
test('CSS url() Path completion', async function () {
const testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString(true);
const folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString(true) }];
await assertCompletions('html { background-image: url("./|")', {
items: [
{ label: 'about.html', resultText: 'html { background-image: url("./about.html")' }
]
}, testUri, folders);
await assertCompletions(`html { background-image: url('../|')`, {
items: [
{ label: 'about/', resultText: `html { background-image: url('../about/')` },
{ label: 'index.html', resultText: `html { background-image: url('../index.html')` },
{ label: 'src/', resultText: `html { background-image: url('../src/')` }
]
}, testUri, folders);
await assertCompletions(`html { background-image: url('../src/a|')`, {
items: [
{ label: 'feature.js', resultText: `html { background-image: url('../src/feature.js')` },
{ label: 'data/', resultText: `html { background-image: url('../src/data/')` },
{ label: 'test.js', resultText: `html { background-image: url('../src/test.js')` }
]
}, testUri, folders);
await assertCompletions(`html { background-image: url('../src/data/f|.asar')`, {
items: [
{ label: 'foo.asar', resultText: `html { background-image: url('../src/data/foo.asar')` }
]
}, testUri, folders);
await assertCompletions(`html { background-image: url('|')`, {
items: [
{ label: 'about.html', resultText: `html { background-image: url('about.html')` },
]
}, testUri, folders);
await assertCompletions(`html { background-image: url('/|')`, {
items: [
{ label: 'pathCompletionFixtures/', resultText: `html { background-image: url('/pathCompletionFixtures/')` }
]
}, testUri, folders);
await assertCompletions(`html { background-image: url('/pathCompletionFixtures/|')`, {
items: [
{ label: 'about/', resultText: `html { background-image: url('/pathCompletionFixtures/about/')` },
{ label: 'index.html', resultText: `html { background-image: url('/pathCompletionFixtures/index.html')` },
{ label: 'src/', resultText: `html { background-image: url('/pathCompletionFixtures/src/')` }
]
}, testUri, folders);
await assertCompletions(`html { background-image: url("/|")`, {
items: [
{ label: 'pathCompletionFixtures/', resultText: `html { background-image: url("/pathCompletionFixtures/")` }
]
}, testUri, folders);
});
test('CSS url() Path Completion - Unquoted url', async function () {
const testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString(true);
const folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString(true) }];
await assertCompletions('html { background-image: url(./|)', {
items: [
{ label: 'about.html', resultText: 'html { background-image: url(./about.html)' }
]
}, testUri, folders);
await assertCompletions('html { background-image: url(./a|)', {
items: [
{ label: 'about.html', resultText: 'html { background-image: url(./about.html)' }
]
}, testUri, folders);
await assertCompletions('html { background-image: url(../|src/)', {
items: [
{ label: 'about/', resultText: 'html { background-image: url(../about/)' }
]
}, testUri, folders);
await assertCompletions('html { background-image: url(../s|rc/)', {
items: [
{ label: 'about/', resultText: 'html { background-image: url(../about/)' }
]
}, testUri, folders);
});
test('CSS @import Path completion', async function () {
const testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString(true);
const folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString(true) }];
await assertCompletions(`@import './|'`, {
items: [
{ label: 'about.html', resultText: `@import './about.html'` },
]
}, testUri, folders);
await assertCompletions(`@import '../|'`, {
items: [
{ label: 'about/', resultText: `@import '../about/'` },
{ label: 'scss/', resultText: `@import '../scss/'` },
{ label: 'index.html', resultText: `@import '../index.html'` },
{ label: 'src/', resultText: `@import '../src/'` }
]
}, testUri, folders);
});
/**
* For SCSS, `@import 'foo';` can be used for importing partial file `_foo.scss`
*/
test('SCSS @import Path completion', async function () {
const testCSSUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString(true);
const folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString(true) }];
/**
* We are in a CSS file, so no special treatment for SCSS partial files
*/
await assertCompletions(`@import '../scss/|'`, {
items: [
{ label: 'main.scss', resultText: `@import '../scss/main.scss'` },
{ label: '_foo.scss', resultText: `@import '../scss/_foo.scss'` }
]
}, testCSSUri, folders);
const testSCSSUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/scss/main.scss')).toString(true);
await assertCompletions(`@import './|'`, {
items: [
{ label: '_foo.scss', resultText: `@import './foo'` }
]
}, testSCSSUri, folders, 'scss');
});
test('Completion should ignore files/folders starting with dot', async function () {
const testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString(true);
const folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString(true) }];
await assertCompletions('html { background-image: url("../|")', {
count: 4
}, testUri, folders);
});
});
@@ -0,0 +1,100 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'mocha';
import * as assert from 'assert';
import { URI } from 'vscode-uri';
import { resolve } from 'path';
import { TextDocument, DocumentLink } from 'vscode-languageserver-types';
import { WorkspaceFolder } from 'vscode-languageserver-protocol';
import { getCSSLanguageService } from 'vscode-css-languageservice';
import { getDocumentContext } from '../utils/documentContext';
import { getNodeFSRequestService } from '../node/nodeFs';
export interface ItemDescription {
offset: number;
value: string;
target: string;
}
suite('Links', () => {
const cssLanguageService = getCSSLanguageService({ fileSystemProvider: getNodeFSRequestService() });
const assertLink = function (links: DocumentLink[], expected: ItemDescription, document: TextDocument) {
const matches = links.filter(link => {
return document.offsetAt(link.range.start) === expected.offset;
});
assert.strictEqual(matches.length, 1, `${expected.offset} should only existing once: Actual: ${links.map(l => document.offsetAt(l.range.start)).join(', ')}`);
const match = matches[0];
assert.strictEqual(document.getText(match.range), expected.value);
assert.strictEqual(match.target, expected.target);
};
async function assertLinks(value: string, expected: ItemDescription[], testUri: string, workspaceFolders?: WorkspaceFolder[], lang: string = 'css'): Promise<void> {
const offset = value.indexOf('|');
value = value.substr(0, offset) + value.substr(offset + 1);
const document = TextDocument.create(testUri, lang, 0, value);
if (!workspaceFolders) {
workspaceFolders = [{ name: 'x', uri: testUri.substr(0, testUri.lastIndexOf('/')) }];
}
const context = getDocumentContext(testUri, workspaceFolders);
const stylesheet = cssLanguageService.parseStylesheet(document);
const links = await cssLanguageService.findDocumentLinks2(document, stylesheet, context)!;
assert.strictEqual(links.length, expected.length);
for (const item of expected) {
assertLink(links, item, document);
}
}
function getTestResource(path: string) {
return URI.file(resolve(__dirname, '../../test/linksTestFixtures', path)).toString(true);
}
test('url links', async function () {
const testUri = getTestResource('about.css');
const folders = [{ name: 'x', uri: getTestResource('') }];
await assertLinks('html { background-image: url("hello.html|")',
[{ offset: 29, value: '"hello.html"', target: getTestResource('hello.html') }], testUri, folders
);
});
test('url links - untitled', async function () {
const testUri = 'untitled:untitled-1';
const folders = [{ name: 'x', uri: getTestResource('') }];
await assertLinks('@import url("base.css|");")',
[{ offset: 12, value: '"base.css"', target: 'untitled:base.css' }], testUri, folders
);
});
test('node module resolving', async function () {
const testUri = getTestResource('about.css');
const folders = [{ name: 'x', uri: getTestResource('') }];
await assertLinks('html { background-image: url("~foo/hello.html|")',
[{ offset: 29, value: '"~foo/hello.html"', target: getTestResource('node_modules/foo/hello.html') }], testUri, folders
);
});
test('node module subfolder resolving', async function () {
const testUri = getTestResource('subdir/about.css');
const folders = [{ name: 'x', uri: getTestResource('') }];
await assertLinks('html { background-image: url("~foo/hello.html|")',
[{ offset: 29, value: '"~foo/hello.html"', target: getTestResource('node_modules/foo/hello.html') }], testUri, folders
);
});
});
@@ -0,0 +1,39 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DocumentContext } from 'vscode-css-languageservice';
import { endsWith, startsWith } from '../utils/strings';
import { WorkspaceFolder } from 'vscode-languageserver';
import { Utils, URI } from 'vscode-uri';
export function getDocumentContext(documentUri: string, workspaceFolders: WorkspaceFolder[]): DocumentContext {
function getRootFolder(): string | undefined {
for (const folder of workspaceFolders) {
let folderURI = folder.uri;
if (!endsWith(folderURI, '/')) {
folderURI = folderURI + '/';
}
if (startsWith(documentUri, folderURI)) {
return folderURI;
}
}
return undefined;
}
return {
resolveReference: (ref: string, base = documentUri) => {
if (ref[0] === '/') { // resolve absolute path against the current workspace folder
const folderUri = getRootFolder();
if (folderUri) {
return folderUri + ref.substring(1);
}
}
const baseUri = URI.parse(base);
const baseUriDir = baseUri.path.endsWith('/') ? baseUri : Utils.dirname(baseUri);
return Utils.resolvePath(baseUriDir, ref).toString(true);
},
};
}
@@ -0,0 +1,45 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ResponseError, CancellationToken, LSPErrorCodes } from 'vscode-languageserver';
import { RuntimeEnvironment } from '../cssServer';
export function formatError(message: string, err: any): string {
if (err instanceof Error) {
const error = <Error>err;
return `${message}: ${error.message}\n${error.stack}`;
} else if (typeof err === 'string') {
return `${message}: ${err}`;
} else if (err) {
return `${message}: ${err.toString()}`;
}
return message;
}
export function runSafeAsync<T>(runtime: RuntimeEnvironment, func: () => Thenable<T>, errorVal: T, errorMessage: string, token: CancellationToken): Thenable<T | ResponseError<any>> {
return new Promise<T | ResponseError<any>>((resolve) => {
runtime.timer.setImmediate(() => {
if (token.isCancellationRequested) {
resolve(cancelValue());
return;
}
return func().then(result => {
if (token.isCancellationRequested) {
resolve(cancelValue());
return;
} else {
resolve(result);
}
}, e => {
console.error(formatError(errorMessage, e));
resolve(errorVal);
});
});
});
}
function cancelValue<E>() {
return new ResponseError<E>(LSPErrorCodes.RequestCancelled, 'Request cancelled');
}
@@ -0,0 +1,32 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export function startsWith(haystack: string, needle: string): boolean {
if (haystack.length < needle.length) {
return false;
}
for (let i = 0; i < needle.length; i++) {
if (haystack[i] !== needle[i]) {
return false;
}
}
return true;
}
/**
* Determines if haystack ends with needle.
*/
export function endsWith(haystack: string, needle: string): boolean {
const diff = haystack.length - needle.length;
if (diff > 0) {
return haystack.lastIndexOf(needle) === diff;
} else if (diff === 0) {
return haystack === needle;
} else {
return false;
}
}
@@ -0,0 +1,108 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationToken, Connection, Diagnostic, Disposable, DocumentDiagnosticParams, DocumentDiagnosticReport, DocumentDiagnosticReportKind, TextDocuments } from 'vscode-languageserver';
import { TextDocument } from 'vscode-css-languageservice';
import { formatError, runSafeAsync } from './runner';
import { RuntimeEnvironment } from '../cssServer';
export type Validator = (textDocument: TextDocument) => Promise<Diagnostic[]>;
export type DiagnosticsSupport = {
dispose(): void;
requestRefresh(): void;
};
export function registerDiagnosticsPushSupport(documents: TextDocuments<TextDocument>, connection: Connection, runtime: RuntimeEnvironment, validate: Validator): DiagnosticsSupport {
const pendingValidationRequests: { [uri: string]: Disposable } = {};
const validationDelayMs = 500;
const disposables: Disposable[] = [];
// The content of a text document has changed. This event is emitted
// when the text document first opened or when its content has changed.
documents.onDidChangeContent(change => {
triggerValidation(change.document);
}, undefined, disposables);
// a document has closed: clear all diagnostics
documents.onDidClose(event => {
cleanPendingValidation(event.document);
connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] });
}, undefined, disposables);
function cleanPendingValidation(textDocument: TextDocument): void {
const request = pendingValidationRequests[textDocument.uri];
if (request) {
request.dispose();
delete pendingValidationRequests[textDocument.uri];
}
}
function triggerValidation(textDocument: TextDocument): void {
cleanPendingValidation(textDocument);
const request = pendingValidationRequests[textDocument.uri] = runtime.timer.setTimeout(async () => {
if (request === pendingValidationRequests[textDocument.uri]) {
try {
const diagnostics = await validate(textDocument);
if (request === pendingValidationRequests[textDocument.uri]) {
connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
}
delete pendingValidationRequests[textDocument.uri];
} catch (e) {
connection.console.error(formatError(`Error while validating ${textDocument.uri}`, e));
}
}
}, validationDelayMs);
}
return {
requestRefresh: () => {
documents.all().forEach(triggerValidation);
},
dispose: () => {
disposables.forEach(d => d.dispose());
disposables.length = 0;
const keys = Object.keys(pendingValidationRequests);
for (const key of keys) {
pendingValidationRequests[key].dispose();
delete pendingValidationRequests[key];
}
}
};
}
export function registerDiagnosticsPullSupport(documents: TextDocuments<TextDocument>, connection: Connection, runtime: RuntimeEnvironment, validate: Validator): DiagnosticsSupport {
function newDocumentDiagnosticReport(diagnostics: Diagnostic[]): DocumentDiagnosticReport {
return {
kind: DocumentDiagnosticReportKind.Full,
items: diagnostics
};
}
const registration = connection.languages.diagnostics.on(async (params: DocumentDiagnosticParams, token: CancellationToken) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(params.textDocument.uri);
if (document) {
return newDocumentDiagnosticReport(await validate(document));
}
return newDocumentDiagnosticReport([]);
}, newDocumentDiagnosticReport([]), `Error while computing diagnostics for ${params.textDocument.uri}`, token);
});
function requestRefresh(): void {
connection.languages.diagnostics.refresh();
}
return {
requestRefresh,
dispose: () => {
registration.dispose();
}
};
}
@@ -0,0 +1,34 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const path = require('path');
const Mocha = require('mocha');
const glob = require('glob');
const suite = 'Integration CSS Extension Tests';
const options = {
ui: 'tdd',
color: true,
timeout: 60000
};
if (process.env.BUILD_ARTIFACTSTAGINGDIRECTORY) {
options.reporter = 'mocha-multi-reporters';
options.reporterOptions = {
reporterEnabled: 'spec, mocha-junit-reporter',
mochaJunitReporterReporterOptions: {
testsuitesTitle: `${suite} ${process.platform}`,
mochaFile: path.join(process.env.BUILD_ARTIFACTSTAGINGDIRECTORY, `test-results/${process.platform}-${process.arch}-${suite.toLowerCase().replace(/[^\w]/g, '-')}-results.xml`)
}
};
}
const mocha = new Mocha(options);
glob.sync(__dirname + '/../out/test/**/*.test.js')
.forEach(file => mocha.addFile(file));
mocha.run(failures => process.exit(failures ? -1 : 0));
@@ -0,0 +1 @@
!/node_modules
@@ -0,0 +1 @@
{}
@@ -0,0 +1,4 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
@@ -0,0 +1,4 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
@@ -0,0 +1,4 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
@@ -0,0 +1,4 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
@@ -0,0 +1,4 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
@@ -0,0 +1,4 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
@@ -0,0 +1,4 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
@@ -0,0 +1,14 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./out",
"lib": [
"ES2020",
"WebWorker"
],
"module": "Node16",
},
"include": [
"src/**/*"
]
}