build: migrate vscode extension into repo (#63924)

Migrate the vscode extension for angular into this repository.

PR Close #63924
This commit is contained in:
Joey Perrott
2025-09-24 20:24:32 +00:00
committed by Jessica Janiuk
parent 25e93f0d01
commit 863c7eaafe
162 changed files with 18463 additions and 72 deletions
+7 -1
View File
@@ -4,7 +4,7 @@
# https://github.com/bazelbuild/bazel/issues/8106
.git
node_modules
dist
dist/
# All integration test node_modules folders
integration/animations/node_modules
@@ -39,6 +39,7 @@ integration/legacy-animations/node_modules
integration/legacy-animations-async/node_modules
integration/typings_test_ts59/node_modules
modules/ssr-benchmarks/node_modules
vscode-ng-language-service/integration/project/dist/
# For rules_js
adev/node_modules
@@ -69,3 +70,8 @@ packages/service-worker/node_modules
packages/zone.js/test/typings/node_modules
packages/zone.js/node_modules
tools/bazel/rules_angular_store/node_modules
vscode-ng-language-service/node_modules
vscode-ng-language-service/integration/pre_standalone_project/node_modules
vscode-ng-language-service/integration/workspace/node_modules
vscode-ng-language-service/integration/pre_apf_project/node_modules
vscode-ng-language-service/integration/project/node_modules
+15
View File
@@ -119,6 +119,21 @@ jobs:
- name: Build adev in fast mode to ensure it continues to work
run: pnpm bazel build //adev:build
vscode-ng-language-service:
runs-on:
labels: ubuntu-latest
steps:
- name: Initialize environment
uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@d776aff2258f15fc3dc1e63852887518eec3ad75
- name: Setup Bazel
uses: angular/dev-infra/github-actions/bazel/setup@d776aff2258f15fc3dc1e63852887518eec3ad75
- name: Setup Bazel RBE
uses: angular/dev-infra/github-actions/bazel/configure-remote@d776aff2258f15fc3dc1e63852887518eec3ad75
- name: Install node modules
run: pnpm install --frozen-lockfile
- name: Run tests
run: pnpm bazel test //vscode-ng-language-service/...
publish-snapshots:
runs-on:
labels: ubuntu-latest
+15
View File
@@ -127,6 +127,21 @@ jobs:
- name: Build adev in fast mode to ensure it continues to work
run: pnpm bazel build //adev:build
vscode-ng-language-service:
runs-on:
labels: ubuntu-latest
steps:
- name: Initialize environment
uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@d776aff2258f15fc3dc1e63852887518eec3ad75
- name: Setup Bazel
uses: angular/dev-infra/github-actions/bazel/setup@d776aff2258f15fc3dc1e63852887518eec3ad75
- name: Setup Bazel RBE
uses: angular/dev-infra/github-actions/bazel/configure-remote@d776aff2258f15fc3dc1e63852887518eec3ad75
- name: Install node modules
run: pnpm install --frozen-lockfile
- name: Run tests
run: pnpm bazel test //vscode-ng-language-service/...
zone-js:
runs-on:
labels: ubuntu-latest
-3
View File
@@ -16,9 +16,6 @@ pubspec.lock
!.devcontainer/recommended-devcontainer.json
!.devcontainer/recommended-Dockerfile
.settings/
.vscode/launch.json
.vscode/settings.json
.vscode/tasks.json
*.swo
*.swp
modules/.settings
+2
View File
@@ -25,6 +25,7 @@ export const commitMessage: CommitMessageConfig = {
'forms',
'http',
'language-service',
'language-server',
'localize',
'migrations',
'packaging',
@@ -34,6 +35,7 @@ export const commitMessage: CommitMessageConfig = {
'router',
'service-worker',
'upgrade',
'vscode-extension',
'zone.js',
],
};
+3
View File
@@ -25,6 +25,9 @@ export const format: FormatConfig = {
// Ignore generated javascript file(s)
'!.github/actions/deploy-docs-site/main.js',
// Ignore testing data files for language service
'!vscode-ng-language-service/syntaxes/test/data/*.ts',
],
},
'buildifier': true,
+1 -1
View File
@@ -42,7 +42,7 @@ function readPackage(pkg, context) {
// Change all locally generated packages to directly depend on the other local packages, instead
// of expecting them as peerDependencies automatically as we do not auto install peer deps. The
// package is also removed from peerDependencies as it was moved over and will just cause errors.
if (localAngularPackages.includes(key)) {
if (localAngularPackages.includes(key) && pkg.version === '0.0.0-PLACEHOLDER') {
pkg.dependencies = {
...pkg.dependencies,
[key]: 'workspace: *',
+94
View File
@@ -0,0 +1,94 @@
// A launch configuration that compiles the extension and then opens it inside a new window
{
"version": "0.2.0",
"configurations": [
{
"type": "extensionHost",
"request": "launch",
"name": "Launch Dev Client",
"runtimeExecutable": "${execPath}",
"args": [
"--disable-extensions",
"--extensionDevelopmentPath=${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/dist/bin/vscode-ng-language-service/client/src/*.js"
],
"preLaunchTask": {
"type": "npm",
"script": "vscode:watch"
}
},
{
"type": "extensionHost",
"request": "launch",
"name": "Launch Prod Client",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}/dist/bin/vscode-ng-language-service/npm"
],
"sourceMaps": false,
"preLaunchTask": "build vsix"
},
{
"type": "node",
"request": "attach",
"name": "Attach to Server",
"port": 6009,
"restart": true,
"outFiles": [
"${workspaceFolder}/dist/bin/vscode-ng-language-service/server/src/*.js"
]
},
{
"type": "node",
"request": "attach",
"name": "Attach to Jasmine",
"port": 9229,
"restart": true,
"outFiles": [
"${workspaceFolder}/dist/bin/vscode-ng-language-service/**/*.js"
],
},
{
"name": "Integration test: Attach to server",
"port": 9330,
"request": "attach",
"skipFiles": [
"<node_internals>/**"
],
"outFiles": [
"${workspaceFolder}/dist/bin/vscode-ng-language-service/integration/lsp/*.js"
],
"type": "node"
},
{
"name": "E2E Test",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--disable-extensions",
"--extensionDevelopmentPath=${workspaceFolder}/dist/bin/vscode-ng-language-service/npm",
"--extensionTestsPath=${workspaceFolder}/dist/bin/vscode-ng-language-service/integration/e2e/jasmine",
"${workspaceFolder}/vscode-ng-language-service/integration/project"
],
"outFiles": [
"${workspaceFolder}/dist/bin/vscode-ng-language-service/integration/e2e/*.js"
],
"preLaunchTask": {
"type": "npm",
"script": "compile:integration"
}
}
],
"compounds": [
{
"name": "Dev Client + Server",
"configurations": [
"Launch Dev Client",
"Attach to Server"
]
}
]
}
+43
View File
@@ -0,0 +1,43 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "compile",
"group": "build",
"presentation": {
"panel": "dedicated",
"reveal": "never"
},
"problemMatcher": [
"$tsc"
]
},
{
"type": "npm",
"script": "vscode:watch",
"isBackground": true,
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"panel": "dedicated",
"reveal": "never"
},
"problemMatcher": {
"base": "$tsc-watch",
"background": {
"activeOnStart": true,
"beginsPattern": "^iBazel \\[\\d{1,2}:\\d{1,2}(?:AM|PM)\\]: Querying for files to watch.*",
"endsPattern": "^INFO: Build completed successfully, \\d+ total action(s)?"
}
}
},
{
"type": "shell",
"label": "build vsix",
"command": "pnpm bazel build //vscode-ng-language-service:npm --config=release"
}
]
}
+4
View File
@@ -96,6 +96,10 @@ npm.npm_translate_lock(
"//packages/service-worker:package.json",
"//packages/upgrade:package.json",
"//tools/bazel/rules_angular_store:package.json",
"//vscode-ng-language-service/integration/pre_apf_project:package.json",
"//vscode-ng-language-service/integration/pre_standalone_project:package.json",
"//vscode-ng-language-service/integration/project:package.json",
"//vscode-ng-language-service/integration/workspace:package.json",
],
npmrc = "//:.npmrc",
pnpm_lock = "//:pnpm-lock.yaml",
+1 -1
View File
@@ -21,7 +21,7 @@
"ng-dev": "tsx --tsconfig .ng-dev/tsconfig.json node_modules/@angular/ng-dev/bundles/cli.mjs",
"build": "tsx --tsconfig scripts/tsconfig.json scripts/build/build-packages-dist.mts",
"test": "bazelisk test",
"test:ci": "bazelisk test -- //... -//integration/... -//adev/... -//devtools/... -//modules/ssr-benchmarks/...",
"test:ci": "bazelisk test -- //... -//integration/... -//adev/... -//vscode-ng-language-service/... -//devtools/... -//modules/ssr-benchmarks/...",
"integration-tests:ci": "bazelisk test -- //integration/...",
"test-tsec": "bazelisk test //... --build_tag_filters=tsec --test_tag_filters=tsec",
"lint": "pnpm --silent tslint && pnpm --silent ng-dev format changed --check",
+1757 -66
View File
File diff suppressed because it is too large Load Diff
+5
View File
@@ -26,6 +26,11 @@ packages:
- packages/zone.js/
- packages/zone.js/test/typings/
- tools/bazel/rules_angular_store/
- vscode-ng-language-service
- vscode-ng-language-service/integration/pre_standalone_project
- vscode-ng-language-service/integration/workspace
- vscode-ng-language-service/integration/pre_apf_project
- vscode-ng-language-service/integration/project
allowedDeprecatedVersions:
angular: '*'
+109
View File
@@ -0,0 +1,109 @@
load("@aspect_bazel_lib//lib:expand_template.bzl", "expand_template_rule")
load("@aspect_rules_js//js:defs.bzl", "js_library")
load("@aspect_rules_js//npm:defs.bzl", "npm_package")
load("@aspect_rules_ts//ts:defs.bzl", "ts_config")
load("@npm//:defs.bzl", "npm_link_all_packages")
load("@npm//vscode-ng-language-service:vsce/package_json.bzl", vsce_bin = "bin")
npm_link_all_packages(name = "node_modules")
js_library(
name = "package_json",
srcs = ["package.json"],
visibility = ["//vscode-ng-language-service/syntaxes/test:__pkg__"],
)
ts_config(
name = "tsconfig",
src = "tsconfig.json",
visibility = ["//visibility:public"],
)
expand_template_rule(
name = "package_json_expanded",
out = "package_expanded.json",
stamp_substitutions = {
"0.0.0-PLACEHOLDER": "{{BUILD_SCM_VERSION}}",
},
substitutions = {
"./bazel-bin/client/src/extension": "./index",
},
template = "package.json",
)
npm_package(
name = "vsix_sandbox",
srcs = [
"package_expanded.json",
"angular.png",
"CHANGELOG.md",
"README.md",
"//vscode-ng-language-service/client:index.js",
"//vscode-ng-language-service/server:npm_files",
"//vscode-ng-language-service/syntaxes:npm_files",
# Transitive closure of npm deps needed for vsce; this set was determined manually by
# running `bazel build //:vsix` and burning down missing packages. We do this so that we
# don't have to run an additional `npm install` action to create a node_modules within the
# //:npm npm_package where the vsce build takes place.
"//vscode-ng-language-service:node_modules/@angular/language-service",
"//vscode-ng-language-service:node_modules/balanced-match",
"//vscode-ng-language-service:node_modules/brace-expansion",
"//vscode-ng-language-service:node_modules/concat-map",
"//vscode-ng-language-service:node_modules/lru-cache",
"//vscode-ng-language-service:node_modules/minimatch",
"//vscode-ng-language-service:node_modules/semver",
"//vscode-ng-language-service:node_modules/typescript",
"//vscode-ng-language-service:node_modules/vscode-jsonrpc",
"//vscode-ng-language-service:node_modules/vscode-html-languageservice",
"//vscode-ng-language-service:node_modules/vscode-languageclient",
"//vscode-ng-language-service:node_modules/vscode-languageserver-protocol",
"//vscode-ng-language-service:node_modules/vscode-languageserver-textdocument",
"//vscode-ng-language-service:node_modules/vscode-languageserver-types",
"//vscode-ng-language-service:node_modules/vscode-languageserver",
"//vscode-ng-language-service:node_modules/vscode-nls",
"//vscode-ng-language-service:node_modules/vscode-uri",
"//vscode-ng-language-service:node_modules/yallist",
],
exclude_srcs_patterns = [
"*.map",
"**/*.map",
],
include_srcs_packages = [
"**",
],
replace_prefixes = {
"package_expanded.json": "package.json",
"server/package_expanded.json": "server/package.json",
"client/": "",
"syntaxes/src/": "syntaxes/",
},
)
vsce_bin.vsce(
name = "vsix",
srcs = [
":vsix_sandbox",
],
outs = ["ng-template.vsix"],
args = [
"package",
"-o",
"../ng-template.vsix",
],
chdir = "vscode-ng-language-service/vsix_sandbox",
# vsce requires npm on the PATH; we can get this from the Bazel rules_nodejs but it is not
# included by default in rules_js binary rules so we include it here explicitly
include_npm = True,
)
npm_package(
name = "npm",
srcs = [
":vsix",
":vsix_sandbox",
],
root_paths = [
"vsix_sandbox",
],
visibility = ["//vscode-ng-language-service/integration:__subpackages__"],
)
File diff suppressed because it is too large Load Diff
+79
View File
@@ -0,0 +1,79 @@
# Monorepo setup
This repository is a monorepo. All build outputs are created in the `bazel-bin` directory.
The `dependencies` in root [`package.json`](package.json) must include all production dependencies
of the client **and** and the server.
The dependencies of the `server` need to be duplicated in the root [`package.json`](package.json).
Therefore, if a new prod dependency is added to the server, it needs to be
added to both [`package.json`](package.json) and [`server/package.json`](server/package.json).
## Navigating Projects in IDE
This repository contains multiple TypeScript projects, each with its own `tsconfig.json`.
TypeScript's [project references](https://www.typescriptlang.org/docs/handbook/project-references.html) are used to handle the builds.
As a result, some projects depend on the `.d.ts` output of their dependencies, like `client`
and `server` depend on `common`. In order to navigate the projects in your IDE,
you need to first build them by running
```shell
pnpm compile
```
If you'd like to force a clean build, you can delete the existing build artifacts
by running
```shell
pnpm bazel build //:npm --config=release
```
## Formatting source code
This repository uses a common toolset provided in the angular organization for formatting, `ng-dev`. It is installed as a standard npm package,
and can be run locally with `pnpm format`.
## Test Local Changes in VSCode
Any changes made to the code in this repository or the upstream
`@angular/language-service` package can be immediately tested out in a
development version of VSCode. The instructions below explain how to bring up
a local instance and then install a local version of `@angular/language-service`.
### Check TypeScript version
First, make sure that the TypeScript version in `@angular/angular` is the same
as that used in this repository. If not, update the following files:
1. `typescript` dependency in [`package.json`](package.json)
2. `MIN_TS_VERSION` in [`version_provider.ts`](server/src/version_provider.ts)
### Launch VSCode in Extension Development Host
The scripts in `.vscode` directory are setup to automatically compile the code,
then launch a new instance of VSCode with the Angular extension installed.
To do so, either
1. Press F5, or
2. Go to Run on the sidebar, select `Launch Client` from the task list
After the client is launched, you can optionally choose to attach a debugger to
the local instance. To do so,
1. Go to Run on the sidebar, select `Attach to Server` from the task list
As a shortcut, there's also a task setup to automatically launch the client and
attach the debugger in a single step. To do so,
1. Go to Run on the sidebar, select `Client + Server` from the task list
Note: Because we are building with bazel, any breakpoints need to be set on the files in `bazel-bin/...` or by adding a `debugger;` statement before compilation.
### Install Local `@angular/language-service`
If changes are made to the upstream language service package, they can also be
tested locally. This involves building the NPM package, then updating the server
dependency. To do so, run the following script from the `@angular/angular`
repository.
```bash
./packages/language-service/build.sh /path/to/vscode-ng-language-service
```
+69
View File
@@ -0,0 +1,69 @@
# Angular Language Service
![demo](https://github.com/angular/vscode-ng-language-service/raw/main/demo.gif)
## Features
This extension provides a rich editing experience for Angular templates, both inline
and external templates including:
* Completions lists
* AOT Diagnostic messages
* Quick info
* Go to definition
## Download
Download the extension from [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=Angular.ng-template).
## Configuring compiler options for the Angular Language Service
The Angular Language Service uses the same set of options that are used to compile the application.
To get the most complete information in the editor, set the `strictTemplates` option in `tsconfig.json`,
as shown in the following example:
```
"angularCompilerOptions": {
"strictTemplates": true
}
```
For more information, see the [Angular compiler options](https://angular.io/guide/angular-compiler-options) guide.
## Versioning
The language service extension relies on the `@angular/language-service` and `typescript` packages
for its backend. `@angular/language-service` is always bundled with the extension, and is always
the latest version at the time of the release.
`typescript` is loaded, in order of priority, from:
1. The path specified by `typescript.tsdk` in project or global settings.
2. _(Recommended)_ The version of `typescript` bundled with the Angular Language Service extension.
3. The version of `typescript` present in the current workspace's node_modules.
We suggest **not** specifying `typescript.tsdk` in your VSCode settings
per method (1) above. If the `typescript` package is loaded by
methods (1) or (3), there is a potential for a mismatch between
the API expected by `@angular/language-service` and the API provided by `typescript`. This could
lead to a failure of the language service extension.
For more information, please see [#594](https://github.com/angular/vscode-ng-language-service/issues/594).
## Installing a particular release build
Download the `.vsix` file for the release that you want to install from the [releases](https://github.com/angular/vscode-ng-language-service/releases) tab.
*Do not open the .vsix file directly*. Instead, in Visual Studio code, go to the extensions tab. Click on the "..." menu in the upper right corner of the extensions tab, select "Install from vsix..." and then select the .vsix file for the release you just downloaded.
The extension can also be installed with the following command:
```
code --install-extension /path/to/ngls.vsix
```
## Angular Language Service for Other Editors
- [coc-angular](https://github.com/iamcco/coc-angular) for ([Neo](https://neovim.io))[vim](https://www.vim.org/)
- [nvim-lspconfig](https://github.com/neovim/nvim-lspconfig/blob/master/doc/configs.md#angularls) for [Neovim](https://neovim.io)
- [Wild Web Developer](https://github.com/eclipse/wildwebdeveloper) for Eclipse
- [lsp-mode](https://github.com/emacs-lsp/lsp-mode) for Emacs
Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

@@ -0,0 +1,39 @@
load("@aspect_rules_esbuild//esbuild:defs.bzl", "esbuild")
load("@aspect_rules_ts//ts:defs.bzl", "ts_config")
ts_config(
name = "tsconfig",
src = "tsconfig.json",
visibility = ["//vscode-ng-language-service/client:__subpackages__"],
deps = [
"//vscode-ng-language-service:tsconfig",
"//vscode-ng-language-service/common:tsconfig",
],
)
esbuild(
name = "index",
config = {
# Workaround for https://github.com/aspect-build/rules_esbuild/issues/58
"resolveExtensions": [".js"],
},
entry_point = "//vscode-ng-language-service/client/src:extension.js",
external = [
"fs",
"path",
"vscode",
"vscode-languageclient/node",
"vscode-languageserver-protocol",
"vscode-jsonrpc",
],
format = "cjs",
# Do not enable minification. It seems to break the extension on Windows (with WSL). See #1198.
minify = False,
platform = "node",
sourcemap = "external",
visibility = ["//vscode-ng-language-service:__pkg__"],
deps = [
"//:node_modules/source-map-support",
"//vscode-ng-language-service/client/src",
],
)
@@ -0,0 +1,19 @@
load("@aspect_rules_ts//ts:defs.bzl", "ts_project")
ts_project(
name = "src",
srcs = glob(["*.ts"]),
declaration = True,
source_map = True,
tsconfig = "//vscode-ng-language-service/client:tsconfig",
visibility = [
"//vscode-ng-language-service/client:__subpackages__",
],
deps = [
"//vscode-ng-language-service:node_modules/@types/node",
"//vscode-ng-language-service:node_modules/@types/vscode",
"//vscode-ng-language-service:node_modules/typescript",
"//vscode-ng-language-service:node_modules/vscode-languageclient",
"//vscode-ng-language-service/common",
],
)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,239 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as vscode from 'vscode';
import * as lsp from 'vscode-languageclient/node';
import {
OpenJsDocLinkCommand_Args,
OpenJsDocLinkCommandId,
ServerOptions,
} from '../../common/initialize';
import {AngularLanguageClient} from './client';
import {ANGULAR_SCHEME, TcbContentProvider} from './providers';
/**
* Represent a vscode command with an ID and an impl function `execute`.
*/
type Command<T = any> =
| {
id: string;
isTextEditorCommand: false;
execute(_: T): Promise<unknown>;
}
| {
id: string;
isTextEditorCommand: true;
execute(textEditor: vscode.TextEditor): Promise<unknown>;
};
/**
* Restart the language server by killing the process then spanwing a new one.
* @param client language client
* @param context extension context for adding disposables
*/
function restartNgServer(client: AngularLanguageClient): Command {
return {
id: 'angular.restartNgServer',
isTextEditorCommand: false,
async execute() {
await client.stop();
await client.start();
},
};
}
/**
* Open the current server log file in a new editor.
*/
function openLogFile(client: AngularLanguageClient): Command {
return {
id: 'angular.openLogFile',
isTextEditorCommand: false,
async execute() {
const serverOptions: ServerOptions | undefined = client.initializeResult?.serverOptions;
if (!serverOptions?.logFile) {
// Show a MessageItem to help users automatically update the
// configuration option then restart the server.
const selection = await vscode.window.showErrorMessage(
`Angular server logging is off. Please set 'angular.log' and restart the server.`,
'Enable logging and restart server',
);
if (selection) {
const isGlobalConfig = false;
await vscode.workspace
.getConfiguration()
.update('angular.log', 'verbose', isGlobalConfig);
// Server will automatically restart because the config is changed
}
return;
}
const document = await vscode.workspace.openTextDocument(serverOptions.logFile);
return vscode.window.showTextDocument(document);
},
};
}
/**
* Command getTemplateTcb displays a typecheck block for the template a user has
* an active selection over, if any.
* @param ngClient LSP client for the active session
* @param context extension context to which disposables are pushed
*/
function getTemplateTcb(
ngClient: AngularLanguageClient,
context: vscode.ExtensionContext,
): Command {
const TCB_HIGHLIGHT_DECORATION = vscode.window.createTextEditorDecorationType({
// See https://code.visualstudio.com/api/references/theme-color#editor-colors
backgroundColor: new vscode.ThemeColor('editor.selectionHighlightBackground'),
});
const tcbProvider = new TcbContentProvider();
const disposable = vscode.workspace.registerTextDocumentContentProvider(
ANGULAR_SCHEME,
tcbProvider,
);
context.subscriptions.push(disposable);
return {
id: 'angular.getTemplateTcb',
isTextEditorCommand: true,
async execute(textEditor: vscode.TextEditor) {
tcbProvider.clear();
const response = await ngClient.getTcbUnderCursor(textEditor);
if (response === undefined) {
return undefined;
}
// Change the scheme of the URI from `file` to `ng` so that the document
// content is requested from our own `TcbContentProvider`.
const tcbUri = response.uri.with({
scheme: ANGULAR_SCHEME,
});
tcbProvider.update(tcbUri, response.content);
const editor = await vscode.window.showTextDocument(tcbUri, {
viewColumn: vscode.ViewColumn.Beside,
preserveFocus: true, // cursor remains in the active editor
});
editor.setDecorations(TCB_HIGHLIGHT_DECORATION, response.selections);
},
};
}
/**
* Command goToComponentWithTemplateFile finds components which reference an external template in
* their `templateUrl`s.
*
* @param ngClient LSP client for the active session
*/
function goToComponentWithTemplateFile(ngClient: AngularLanguageClient): Command {
return {
id: 'angular.goToComponentWithTemplateFile',
isTextEditorCommand: true,
async execute(textEditor: vscode.TextEditor) {
const locations = await ngClient.getComponentsForOpenExternalTemplate(textEditor);
if (locations === undefined) {
return;
}
vscode.commands.executeCommand(
'editor.action.goToLocations',
textEditor.document.uri,
textEditor.selection.active,
locations,
'peek' /** what to do when there are multiple results */,
);
},
};
}
/**
* Command goToTemplateForComponent finds the template for a component.
*
* @param ngClient LSP client for the active session
*/
function goToTemplateForComponent(ngClient: AngularLanguageClient): Command {
return {
id: 'angular.goToTemplateForComponent',
isTextEditorCommand: true,
async execute(textEditor: vscode.TextEditor) {
const location = await ngClient.getTemplateLocationForComponent(textEditor);
if (location === null) {
return;
}
vscode.commands.executeCommand(
'editor.action.goToLocations',
textEditor.document.uri,
textEditor.selection.active,
[location],
'goto' /** What to do when there are multiple results (there can't be) */,
);
},
};
}
/**
* Proxy command for opening links in jsdoc comments.
*
* This is needed to avoid incorrectly rewriting uris.
*/
function openJsDocLinkCommand(): Command<OpenJsDocLinkCommand_Args> {
return {
id: OpenJsDocLinkCommandId,
isTextEditorCommand: false,
async execute(args) {
return await vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(args.file), <
vscode.TextDocumentShowOptions
>{
selection: new vscode.Range(
new vscode.Position(args.position?.start.line ?? 0, args.position?.start.character ?? 0),
new vscode.Position(args.position?.end.line ?? 0, args.position?.end.character ?? 0),
),
});
},
};
}
function applyCodeActionCommand(ngClient: AngularLanguageClient): Command {
return {
id: 'angular.applyCompletionCodeAction',
isTextEditorCommand: false,
async execute(args: lsp.WorkspaceEdit[]) {
await ngClient.applyWorkspaceEdits(args);
},
};
}
/**
* Register all supported vscode commands for the Angular extension.
* @param client language client
* @param context extension context for adding disposables
*/
export function registerCommands(
client: AngularLanguageClient,
context: vscode.ExtensionContext,
): void {
const commands: Command[] = [
restartNgServer(client),
openLogFile(client),
getTemplateTcb(client, context),
goToComponentWithTemplateFile(client),
goToTemplateForComponent(client),
openJsDocLinkCommand(),
applyCodeActionCommand(client),
];
for (const command of commands) {
const disposable = command.isTextEditorCommand
? vscode.commands.registerTextEditorCommand(command.id, command.execute)
: vscode.commands.registerCommand(command.id, command.execute);
context.subscriptions.push(disposable);
}
}
@@ -0,0 +1,147 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import * as vscode from 'vscode';
const ANGULAR_PROPERTY_ASSIGNMENTS = new Set([
'template',
'templateUrl',
'styleUrls',
'styleUrl',
'host',
]);
/**
* Determines if the position is inside a decorator
* property that supports language service features.
*/
export function isNotTypescriptOrSupportedDecoratorField(
document: vscode.TextDocument,
position: vscode.Position,
): boolean {
if (document.languageId !== 'typescript') {
return true;
}
return isPropertyAssignmentToStringOrStringInArray(
document.getText(),
document.offsetAt(position),
ANGULAR_PROPERTY_ASSIGNMENTS,
);
}
/**
* Determines if the position is inside a string literal. Returns `true` if the document language is
* not TypeScript.
*/
export function isInsideStringLiteral(
document: vscode.TextDocument,
position: vscode.Position,
): boolean {
if (document.languageId !== 'typescript') {
return true;
}
const offset = document.offsetAt(position);
const scanner = ts.createScanner(ts.ScriptTarget.ESNext, true /* skipTrivia */);
scanner.setText(document.getText());
let token: ts.SyntaxKind = scanner.scan();
while (token !== ts.SyntaxKind.EndOfFileToken && scanner.getStartPos() < offset) {
const isStringToken =
token === ts.SyntaxKind.StringLiteral ||
token === ts.SyntaxKind.NoSubstitutionTemplateLiteral;
const isCursorInToken =
scanner.getStartPos() <= offset &&
scanner.getStartPos() + scanner.getTokenText().length >= offset;
if (isCursorInToken && isStringToken) {
return true;
}
token = scanner.scan();
}
return false;
}
/**
* Basic scanner to determine if we're inside a string of a property with one of the given names.
*
* This scanner is not currently robust or perfect but provides us with an accurate answer _most_ of
* the time.
*
* False positives are OK here. Though this will give some false positives for determining if a
* position is within an Angular context, i.e. an object like `{template: ''}` that is not inside an
* `@Component` or `{styleUrls: [someFunction('stringL¦iteral')]}`, the @angular/language-service
* will always give us the correct answer. This helper gives us a quick win for optimizing the
* number of requests we send to the server.
*
* TODO(atscott): tagged templates don't work: #1872 /
* https://github.com/Microsoft/TypeScript/issues/20055
*/
function isPropertyAssignmentToStringOrStringInArray(
documentText: string,
offset: number,
propertyAssignmentNames: Set<string>,
): boolean {
const scanner = ts.createScanner(ts.ScriptTarget.ESNext, true /* skipTrivia */);
scanner.setText(documentText);
let token: ts.SyntaxKind = scanner.scan();
let lastToken: ts.SyntaxKind | undefined;
let lastTokenText: string | undefined;
let unclosedBraces = 0;
let unclosedBrackets = 0;
let propertyAssignmentContext = false;
while (token !== ts.SyntaxKind.EndOfFileToken && scanner.getStartPos() < offset) {
if (
lastToken === ts.SyntaxKind.Identifier &&
lastTokenText !== undefined &&
token === ts.SyntaxKind.ColonToken &&
propertyAssignmentNames.has(lastTokenText)
) {
propertyAssignmentContext = true;
token = scanner.scan();
continue;
}
if (unclosedBraces === 0 && unclosedBrackets === 0 && isPropertyAssignmentTerminator(token)) {
propertyAssignmentContext = false;
}
if (token === ts.SyntaxKind.OpenBracketToken) {
unclosedBrackets++;
} else if (token === ts.SyntaxKind.OpenBraceToken) {
unclosedBraces++;
} else if (token === ts.SyntaxKind.CloseBracketToken) {
unclosedBrackets--;
} else if (token === ts.SyntaxKind.CloseBraceToken) {
unclosedBraces--;
}
const isStringToken =
token === ts.SyntaxKind.StringLiteral ||
token === ts.SyntaxKind.NoSubstitutionTemplateLiteral;
const isCursorInToken =
scanner.getStartPos() <= offset &&
scanner.getStartPos() + scanner.getTokenText().length >= offset;
if (propertyAssignmentContext && isCursorInToken && isStringToken) {
return true;
}
lastTokenText = scanner.getTokenText();
lastToken = token;
token = scanner.scan();
}
return false;
}
function isPropertyAssignmentTerminator(token: ts.SyntaxKind) {
return (
token === ts.SyntaxKind.EndOfFileToken ||
token === ts.SyntaxKind.CommaToken ||
token === ts.SyntaxKind.SemicolonToken ||
token === ts.SyntaxKind.CloseBraceToken
);
}
@@ -0,0 +1,34 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as vscode from 'vscode';
import {AngularLanguageClient} from './client';
import {registerCommands} from './commands';
export function activate(context: vscode.ExtensionContext) {
const client = new AngularLanguageClient(context);
// Push the disposable to the context's subscriptions so that the
// client can be deactivated on extension deactivation
registerCommands(client, context);
// Restart the server on configuration change.
const disposable = vscode.workspace.onDidChangeConfiguration(
async (e: vscode.ConfigurationChangeEvent) => {
if (!e.affectsConfiguration('angular')) {
return;
}
await client.stop();
await client.start();
},
);
context.subscriptions.push(client, disposable);
client.start();
}
@@ -0,0 +1,64 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as vscode from 'vscode';
export const ANGULAR_SCHEME = 'ng';
/**
* Allocate a provider of documents corresponding to the `ng` URI scheme,
* which we will use to provide a virtual document with the TCB contents.
*
* We use a virtual document provider rather than opening an untitled file to
* ensure the buffer remains readonly (https://github.com/microsoft/vscode/issues/4873).
*/
export class TcbContentProvider implements vscode.TextDocumentContentProvider {
/**
* Event emitter used to notify VSCode of a change to the TCB virtual document,
* prompting it to re-evaluate the document content. This is needed to bust
* VSCode's document cache if someone requests a TCB that was previously opened.
* https://code.visualstudio.com/api/extension-guides/virtual-documents#update-virtual-documents
*/
private readonly onDidChangeEmitter = new vscode.EventEmitter<vscode.Uri>();
/**
* Name of the typecheck file.
*/
private tcbFile: vscode.Uri | null = null;
/**
* Content of the entire typecheck file.
*/
private tcbContent: string | null = null;
/**
* This callback is invoked only when user explicitly requests to view or
* update typecheck file. We do not automatically update the typecheck document
* when the source file changes.
*/
readonly onDidChange = this.onDidChangeEmitter.event;
provideTextDocumentContent(
uri: vscode.Uri,
token: vscode.CancellationToken,
): vscode.ProviderResult<string> {
if (uri.toString() !== this.tcbFile?.toString()) {
return null;
}
return this.tcbContent;
}
update(uri: vscode.Uri, content: string) {
this.tcbFile = uri;
this.tcbContent = content;
this.onDidChangeEmitter.fire(uri);
}
clear() {
this.tcbFile = null;
this.tcbContent = null;
}
}
@@ -0,0 +1,34 @@
load("@aspect_rules_jasmine//jasmine:defs.bzl", "jasmine_test")
load("@aspect_rules_ts//ts:defs.bzl", "ts_config", "ts_project")
ts_config(
name = "tsconfig",
src = "tsconfig.json",
deps = [
"//vscode-ng-language-service:tsconfig",
"//vscode-ng-language-service/client:tsconfig",
],
)
ts_project(
name = "tests",
srcs = glob(["*.ts"]),
declaration = True,
source_map = True,
tsconfig = ":tsconfig",
deps = [
"//vscode-ng-language-service:node_modules/@types/jasmine",
"//vscode-ng-language-service:node_modules/@types/vscode",
"//vscode-ng-language-service:node_modules/vscode-languageserver-textdocument",
"//vscode-ng-language-service/client/src",
],
)
jasmine_test(
name = "test",
args = ["*_spec.js"],
chdir = package_name(),
data = [":tests"],
node_modules = "//vscode-ng-language-service:node_modules",
tags = ["unit_test"],
)
@@ -0,0 +1,125 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as vscode from 'vscode';
import {DocumentUri, TextDocument} from 'vscode-languageserver-textdocument';
import {isNotTypescriptOrSupportedDecoratorField} from '../embedded_support';
describe('embedded language support', () => {
describe('isInsideAngularContext', () => {
it('empty file', () => {
test('¦', isNotTypescriptOrSupportedDecoratorField, false);
});
it('just after template', () => {
test(
`const foo = {template: '<div></div>'¦}`,
isNotTypescriptOrSupportedDecoratorField,
false,
);
});
it('inside template', () => {
test(
`const foo = {template: '<div>¦</div>'}`,
isNotTypescriptOrSupportedDecoratorField,
true,
);
});
it('just after templateUrl', () => {
test(
`const foo = {templateUrl: './abc.html'¦}`,
isNotTypescriptOrSupportedDecoratorField,
false,
);
});
it('inside templateUrl', () => {
test(
`const foo = {templateUrl: './abc¦.html'}`,
isNotTypescriptOrSupportedDecoratorField,
true,
);
});
it('just after styleUrls', () => {
test(
`const foo = {styleUrls: ['./abc.css']¦}`,
isNotTypescriptOrSupportedDecoratorField,
false,
);
});
it('inside first item of styleUrls', () => {
test(
`const foo = {styleUrls: ['./abc.c¦ss', 'def.css']}`,
isNotTypescriptOrSupportedDecoratorField,
true,
);
});
it('inside second item of styleUrls', () => {
test(
`const foo = {styleUrls: ['./abc.css', 'def¦.css']}`,
isNotTypescriptOrSupportedDecoratorField,
true,
);
});
it('inside second item of styleUrls, when first is complicated function', () => {
test(
`const foo = {styleUrls: [getCss({strict: true, dirs: ['apple', 'banana']}), 'def¦.css']}`,
isNotTypescriptOrSupportedDecoratorField,
true,
);
});
it('inside non-string item of styleUrls', () => {
test(
`const foo = {styleUrls: [getCss({strict: true¦, dirs: ['apple', 'banana']}), 'def.css']}`,
isNotTypescriptOrSupportedDecoratorField,
false,
);
});
});
});
function test(
fileWithCursor: string,
testFn: (doc: vscode.TextDocument, position: vscode.Position) => boolean,
expectation: boolean,
): void {
const {cursor, text} = extractCursorInfo(fileWithCursor);
const vdoc = TextDocument.create(
'test.ts' as DocumentUri,
'typescript',
0,
text,
) as {} as vscode.TextDocument;
(vdoc as any).fileName = 'test.ts';
const actual = testFn(vdoc, vdoc.positionAt(cursor));
expect(actual).toBe(expectation);
}
/**
* Given a text snippet which contains exactly one cursor symbol ('¦'), extract both the offset of
* that cursor within the text as well as the text snippet without the cursor.
*/
function extractCursorInfo(textWithCursor: string): {cursor: number; text: string} {
const cursor = textWithCursor.indexOf('¦');
if (cursor === -1 || textWithCursor.indexOf('¦', cursor + 1) !== -1) {
throw new Error(`Expected to find exactly one cursor symbol '¦'`);
}
return {
cursor,
text: textWithCursor.substr(0, cursor) + textWithCursor.substr(cursor + 1),
};
}
@@ -0,0 +1,5 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
}
}
@@ -0,0 +1 @@
{"root":["./embedded_support_spec.ts"],"version":"5.9.2"}
@@ -0,0 +1,10 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"rootDirs": [
".",
"../dist"
]
},
}

Some files were not shown because too many files have changed in this diff Show More