build: switch ngp vscode extension tests to bazel

Reworks the ngp vscode extension tests to be fully in Bazel.
This commit is contained in:
Kristiyan Kostadinov
2026-10-10 22:08:24 +02:00
committed by Kristiyan Kostadinov
parent 9cefc5e2a1
commit 78a33e9e4d
25 changed files with 340 additions and 274 deletions
-2
View File
@@ -80,8 +80,6 @@ jobs:
run: pnpm install --frozen-lockfile
- name: Run CI tests for framework
run: pnpm test:ci
- name: Run hybrid language service LSP tests
run: pnpm test:ngp:vscode
integration-tests:
runs-on: ubuntu-latest
-2
View File
@@ -86,8 +86,6 @@ jobs:
# Ensures Aspect lock files are up-to-date.
# TODO(devversion): Remove when removing pnpm.
ASPECT_RULES_JS_FROZEN_PNPM_LOCK: '1'
- name: Run hybrid language service LSP tests
run: pnpm test:ngp:vscode
- name: Upload GRPC logs (for debugging of RBE issues)
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
@@ -0,0 +1,22 @@
load("@npm//:defs.bzl", "npm_link_all_packages")
load("//tools:defaults.bzl", "ts_config")
package(default_visibility = ["//ngp-vscode-ng-language-service:__subpackages__"])
npm_link_all_packages(name = "node_modules")
ts_config(
name = "tsconfig_build",
src = "tsconfig-bazel.json",
deps = ["//packages/compiler-cli/preprocessor:tsconfig"],
)
ts_config(
name = "tsconfig_test",
testonly = True,
src = "tsconfig-bazel-test.json",
deps = [
":tsconfig_build",
"//:node_modules/@types/jasmine",
],
)
+1 -2
View File
@@ -148,8 +148,7 @@
"scripts": {
"compile": "tsc -p client --noEmit && tsc -p server --noEmit && node build.js",
"typecheck": "tsc -p client --noEmit && tsc -p server --noEmit && tsc -p tests --noEmit",
"test:lsp": "pnpm run compile && node tests/run_jasmine.mjs",
"test": "pnpm run compile && pnpm run test:lsp && node e2e/build-tests.js && node e2e/runTests.js",
"test": "pnpm run compile && node e2e/build-tests.js && node e2e/runTests.js",
"watch": "pnpm --prefix client run watch & pnpm --prefix server run watch"
},
"dependencies": {
@@ -0,0 +1,42 @@
load("@npm//:defs.bzl", "npm_link_all_packages")
load("//tools:defaults.bzl", "esbuild", "ts_project")
package(default_visibility = ["//ngp-vscode-ng-language-service:__subpackages__"])
npm_link_all_packages(name = "node_modules")
ts_project(
name = "src",
srcs = glob(["src/**/*.ts"]),
tsconfig = "//ngp-vscode-ng-language-service:tsconfig_build",
deps = [
":node_modules/@typescript/native-preview",
":node_modules/vscode-languageserver",
":node_modules/vscode-languageserver-textdocument",
":node_modules/vscode-uri",
"//:node_modules/@types/node",
"//ngp-vscode-ng-language-service:node_modules/vscode-jsonrpc",
"//packages/compiler-cli",
"//packages/compiler-cli/preprocessor",
"//packages/compiler-cli/preprocessor/language-service",
],
)
# Standalone CommonJS bundle of the language server, equivalent to the
# `dist/server/server.js` produced by `build.js`.
esbuild(
name = "server_bundle",
config = "esbuild.config.mjs",
entry_point = "src/server.js",
external = [
"typescript",
"@typescript/native-preview",
"@typescript/native-preview/*",
],
format = "cjs",
minify = False,
platform = "node",
target = "node20",
tsconfig = "esbuild-tsconfig.json",
deps = [":src"],
)
@@ -0,0 +1,16 @@
// Resolution-only tsconfig for the esbuild server bundle. esbuild cannot follow
// `extends` across Bazel packages, so the `@angular/*` mappings (the equivalent of
// the `alias` block in `build.js`) are spelled out here. Type-checking uses
// `//ngp-vscode-ng-language-service:tsconfig_build` instead.
{
"compilerOptions": {
"baseUrl": "../..",
"paths": {
"@angular/compiler": ["packages/compiler/index"],
"@angular/compiler-cli": ["packages/compiler-cli/index"],
"@angular/compiler-cli/private/*": ["packages/compiler-cli/private/*"],
"@angular/core": ["packages/core/index"],
"@angular/language-service/private": ["packages/language-service/private"]
}
}
}
@@ -0,0 +1,16 @@
// esbuild config for the Bazel-built server bundle.
//
// The server is bundled as CommonJS (matching the shipped extension), but the
// preprocessor's analyzer loader relies on `import.meta.url` to locate itself.
// Instead of regex-patching the output after the fact (as `build.js` does), we
// define `import.meta.url` up-front to a CJS-compatible equivalent.
export default {
banner: {
js: "const __ngp_import_meta_url = require('node:url').pathToFileURL(__filename).href;",
},
define: {
'import.meta.url': '__ngp_import_meta_url',
},
// Workaround for https://github.com/aspect-build/rules_esbuild/issues/58
resolveExtensions: ['.js'],
};
@@ -34,6 +34,12 @@ export class ProjectManager {
private api?: API;
private currentSnapshot?: Snapshot;
private nodeModulesPathOverride?: string;
/**
* Document/file mutations that have been received but not yet applied. They are
* driven by LSP notifications, which nothing awaits, so a request that arrives in
* the meantime must not be served against stale state.
*/
private pendingMutations = new Set<Promise<void>>();
private log: (msg: string) => void;
private err: (msg: string) => void;
@@ -62,7 +68,24 @@ export class ProjectManager {
return this.projects.get(await normalizePath(tsconfigPath));
}
/** Resolves the project owning `filePath`, after any in-flight mutations have settled. */
async getProjectForFile(filePath: string): Promise<ProjectInstance | null> {
await Promise.allSettled(this.pendingMutations);
return this.lookupProjectForFile(filePath);
}
/** Runs `mutation`, tracking it so that requests issued meanwhile wait for it. */
private async trackMutation(mutation: () => Promise<void>): Promise<void> {
const pending = mutation();
this.pendingMutations.add(pending);
try {
await pending;
} finally {
this.pendingMutations.delete(pending);
}
}
private async lookupProjectForFile(filePath: string): Promise<ProjectInstance | null> {
const normFilePath = await normalizePath(filePath);
if (normFilePath.endsWith('.json')) {
@@ -211,64 +234,70 @@ export class ProjectManager {
return null;
}
async updateFileContent(updates: {filePath: string; content: string}[]): Promise<void> {
const updatesPerCompiler = new Map<HybridCompiler, {filePath: string; content: string}[]>();
updateFileContent(updates: {filePath: string; content: string}[]): Promise<void> {
return this.trackMutation(async () => {
const updatesPerCompiler = new Map<HybridCompiler, {filePath: string; content: string}[]>();
for (const update of updates) {
if (update.filePath.endsWith('.ngtypecheck.ts')) {
continue;
for (const update of updates) {
if (update.filePath.endsWith('.ngtypecheck.ts')) {
continue;
}
const project = await this.lookupProjectForFile(update.filePath);
const compilers = project
? [project.hybridCompiler]
: Array.from(this.projects.values()).map((p) => p.hybridCompiler);
for (const compiler of compilers) {
const list = updatesPerCompiler.get(compiler) ?? [];
list.push(update);
updatesPerCompiler.set(compiler, list);
}
}
const project = await this.getProjectForFile(update.filePath);
await Promise.all(
Array.from(updatesPerCompiler.entries()).map(([compiler, compilerUpdates]) =>
compiler.updateFileContent(compilerUpdates),
),
);
});
}
invalidateFiles(invalidations: FileInvalidation[]): Promise<void> {
return this.trackMutation(async () => {
for (const inv of invalidations) {
const normInvPath = await normalizePath(inv.filePath);
if (normInvPath.endsWith('.json') && inv.updateType === FileUpdateType.Deleted) {
if (this.projects.has(normInvPath)) {
this.log(`Disposing project for deleted config: ${normInvPath}`);
this.projects.delete(normInvPath);
}
}
if (inv.updateType === FileUpdateType.Deleted) {
for (const project of this.projects.values()) {
project.rootNames.delete(normInvPath);
}
}
}
await Promise.all(
Array.from(this.projects.values()).map((project) =>
project.hybridCompiler.invalidateFiles(invalidations),
),
);
});
}
onDidClose(filePath: string): Promise<void> {
return this.trackMutation(async () => {
const project = await this.lookupProjectForFile(filePath);
const compilers = project
? [project.hybridCompiler]
: Array.from(this.projects.values()).map((p) => p.hybridCompiler);
for (const compiler of compilers) {
const list = updatesPerCompiler.get(compiler) ?? [];
list.push(update);
updatesPerCompiler.set(compiler, list);
}
}
await Promise.all(
Array.from(updatesPerCompiler.entries()).map(([compiler, compilerUpdates]) =>
compiler.updateFileContent(compilerUpdates),
),
);
}
async invalidateFiles(invalidations: FileInvalidation[]): Promise<void> {
for (const inv of invalidations) {
const normInvPath = await normalizePath(inv.filePath);
if (normInvPath.endsWith('.json') && inv.updateType === FileUpdateType.Deleted) {
if (this.projects.has(normInvPath)) {
this.log(`Disposing project for deleted config: ${normInvPath}`);
this.projects.delete(normInvPath);
}
}
if (inv.updateType === FileUpdateType.Deleted) {
for (const project of this.projects.values()) {
project.rootNames.delete(normInvPath);
}
}
}
await Promise.all(
Array.from(this.projects.values()).map((project) =>
project.hybridCompiler.invalidateFiles(invalidations),
),
);
}
async onDidClose(filePath: string): Promise<void> {
const project = await this.getProjectForFile(filePath);
const compilers = project
? [project.hybridCompiler]
: Array.from(this.projects.values()).map((p) => p.hybridCompiler);
await Promise.all(
compilers.map((p) => p.invalidateFiles([{filePath, updateType: FileUpdateType.Changed}])),
);
await Promise.all(
compilers.map((p) => p.invalidateFiles([{filePath, updateType: FileUpdateType.Changed}])),
);
});
}
}
@@ -162,7 +162,7 @@ connection.onInitialize(async (params: InitializeParams) => {
projectManager = new ProjectManager({
facade,
api,
nodeModulesPathOverride: process.env.NG_HYBRID_NODE_MODULES_OVERRIDE,
nodeModulesPathOverride: process.env['NG_HYBRID_NODE_MODULES_OVERRIDE'],
onLog: (msg) => connection.console.log(msg),
onError: (msg) => connection.console.error(msg),
});
@@ -0,0 +1,39 @@
load("//tools:defaults.bzl", "jasmine_test", "ts_project")
ts_project(
name = "test_lib",
testonly = True,
srcs = glob(["*.ts"]),
tsconfig = "//ngp-vscode-ng-language-service:tsconfig_test",
deps = [
"//:node_modules/@types/jasmine",
"//:node_modules/@types/node",
"//ngp-vscode-ng-language-service:node_modules/vscode-jsonrpc",
"//ngp-vscode-ng-language-service:node_modules/vscode-languageserver",
"//ngp-vscode-ng-language-service:node_modules/vscode-languageserver-textdocument",
"//ngp-vscode-ng-language-service:node_modules/vscode-uri",
"//packages/compiler-cli/preprocessor/language-service",
"//packages/compiler-cli/preprocessor/language-service/tests:test_lib",
],
)
jasmine_test(
name = "test",
timeout = "long",
data = [
":test_lib",
# The server bundle and what it resolves at runtime: `typescript` and `tsgo`.
"//:node_modules/typescript",
"//ngp-vscode-ng-language-service/server:node_modules/@typescript/native-preview",
"//ngp-vscode-ng-language-service/server:server_bundle",
# `tsgo` as spawned directly by the shared test helpers.
"//packages/compiler-cli/preprocessor/language-service:node_modules/@typescript/native-preview",
"//packages/compiler-cli/preprocessor/ng-analyze:ng_analyze_wasm",
"//packages/compiler-cli/preprocessor/ng-analyze:package_json",
] + glob(["test-workspace/**"]),
# The specs follow `workspace/didChangeWatchedFiles` (a one-way notification the
# server processes asynchronously) with an immediate request, so under load the
# request can occasionally be served before the invalidation is applied.
flaky = True,
shard_count = 3,
)
@@ -1,9 +1,8 @@
import * as path from 'path';
import * as rpc from 'vscode-jsonrpc/node';
import {TestEnv, startTestServer} from './test_helpers';
import {TestEnv, getTestWorkspacePath, startTestServer} from './test_helpers';
import {TestFileManager} from '../../packages/compiler-cli/preprocessor/language-service/tests/test_file_manager';
const testWorkspacePath = path.join(__dirname, 'test-workspace');
const testWorkspacePath = getTestWorkspacePath();
describe('Incremental Analysis', () => {
let connection: rpc.MessageConnection;
@@ -1,10 +1,9 @@
import * as path from 'path';
import * as rpc from 'vscode-jsonrpc/node';
import {CompletionItemKind} from 'vscode-languageserver';
import {TestEnv, startTestServer} from './test_helpers';
import {TestEnv, getTestWorkspacePath, startTestServer} from './test_helpers';
import {TestFileManager} from '../../packages/compiler-cli/preprocessor/language-service/tests/test_file_manager';
const testWorkspacePath = path.join(__dirname, 'test-workspace');
const testWorkspacePath = getTestWorkspacePath();
describe('LSP Completions', () => {
let connection: rpc.MessageConnection;
@@ -1,10 +1,9 @@
import * as path from 'path';
import * as rpc from 'vscode-jsonrpc/node';
import {URI} from 'vscode-uri';
import {TestEnv, startTestServer} from './test_helpers';
import {TestEnv, getTestWorkspacePath, startTestServer} from './test_helpers';
import {TestFileManager} from '../../packages/compiler-cli/preprocessor/language-service/tests/test_file_manager';
const testWorkspacePath = path.join(__dirname, 'test-workspace');
const testWorkspacePath = getTestWorkspacePath();
describe('LSP Diagnostics', () => {
let connection: rpc.MessageConnection;
@@ -1,10 +1,9 @@
import * as path from 'path';
import * as rpc from 'vscode-jsonrpc/node';
import {TestEnv, startTestServer} from './test_helpers';
import {TestEnv, getTestWorkspacePath, startTestServer} from './test_helpers';
import {TestFileManager} from '../../packages/compiler-cli/preprocessor/language-service/tests/test_file_manager';
import {WorkspaceEdit} from 'vscode-languageserver';
const testWorkspacePath = path.join(__dirname, 'test-workspace');
const testWorkspacePath = getTestWorkspacePath();
describe('LSP References and Rename', () => {
let connection: rpc.MessageConnection;
@@ -1,9 +1,9 @@
import * as path from 'path';
import * as rpc from 'vscode-jsonrpc/node';
import {TestEnv, startTestServer} from './test_helpers';
import {TestEnv, getTestWorkspacePath, startTestServer} from './test_helpers';
import {TestFileManager} from '../../packages/compiler-cli/preprocessor/language-service/tests/test_file_manager';
const testWorkspacePath = path.join(__dirname, 'test-workspace');
const testWorkspacePath = getTestWorkspacePath();
describe('LSP Signature Help', () => {
let connection: rpc.MessageConnection;
@@ -1,10 +1,10 @@
import * as path from 'path';
import * as fs from 'node:fs/promises';
import * as rpc from 'vscode-jsonrpc/node';
import {TestEnv, startTestServer} from './test_helpers';
import {TestEnv, getTestWorkspacePath, startTestServer} from './test_helpers';
import {TestFileManager} from '../../packages/compiler-cli/preprocessor/language-service/tests/test_file_manager';
const testWorkspacePath = path.join(__dirname, 'test-workspace');
const testWorkspacePath = getTestWorkspacePath();
describe('Multi-Project Support', () => {
let connection: rpc.MessageConnection;
@@ -41,7 +41,7 @@ describe('Multi-Project Support', () => {
subprojectTsconfig,
JSON.stringify(
{
extends: '../../../tsconfig.json',
extends: '../tsconfig.json',
compilerOptions: {
rootDir: '.',
},
@@ -99,7 +99,7 @@ describe('Multi-Project Support', () => {
appTsconfig,
JSON.stringify(
{
extends: '../../../tsconfig.json',
extends: '../tsconfig.json',
compilerOptions: {
rootDir: '.',
},
@@ -1,132 +0,0 @@
import esbuild from 'esbuild';
import path from 'node:path';
import {fileURLToPath, pathToFileURL} from 'node:url';
import fs from 'node:fs/promises';
import Jasmine from 'jasmine';
import cp from 'node:child_process';
import {createRequire} from 'node:module';
import {ensureWasmBinding} from './wasm_binding.mjs';
const req = createRequire(import.meta.url);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '../..');
const outDir = path.join(__dirname, '.jasmine_build');
ensureWasmBinding(repoRoot);
// If no arguments, run each spec in its own child process sequentially for clean isolation
const args = process.argv.slice(2);
if (args.length === 0) {
const entries = await fs.readdir(__dirname);
const specFiles = entries
.filter((f) => (f.endsWith('_spec.ts') || f.endsWith('.test.ts')) && !f.endsWith('.d.ts'))
.sort()
.map((f) => path.join(__dirname, f));
let failed = false;
for (const specFile of specFiles) {
const result = cp.spawnSync(process.execPath, [fileURLToPath(import.meta.url), specFile], {
stdio: 'inherit',
cwd: repoRoot,
});
if (result.status !== 0) {
failed = true;
}
}
process.exit(failed ? 1 : 0);
}
// Single spec run mode
const specFile = path.resolve(args[0]);
// Resolve tsgo binary path
try {
const previewPkg = req.resolve('@typescript/native-preview/package.json');
const previewReq = createRequire(previewPkg);
const platformPkg = `@typescript/native-preview-${process.platform}-${process.arch}`;
const platPkgJson = previewReq.resolve(`${platformPkg}/package.json`);
process.env['TSGO_BINARY_PATH'] = path.join(
path.dirname(platPkgJson),
'lib',
process.platform === 'win32' ? 'tsgo.exe' : 'tsgo',
);
} catch (e) {
console.warn('Could not resolve tsgo binary:', e);
}
// Clean and create outDir
await fs.rm(outDir, {recursive: true, force: true});
await fs.mkdir(outDir, {recursive: true});
try {
const baseName = path.basename(specFile).replace(/\.ts$/, '.cjs');
const outFile = path.join(outDir, baseName);
await esbuild.build({
entryPoints: [specFile],
bundle: true,
platform: 'node',
format: 'cjs',
target: 'node20',
outfile: outFile,
external: [
'vscode-languageserver',
'vscode-languageserver/*',
'vscode-languageserver-textdocument',
'vscode-languageserver-types',
'vscode-languageclient',
'vscode-languageclient/*',
'vscode-jsonrpc',
'vscode-jsonrpc/*',
'vscode-uri',
'typescript',
'@typescript/native-preview',
'@typescript/native-preview/*',
'jasmine',
path.join(repoRoot, 'packages/compiler-cli/preprocessor/ng-analyze-wasm/ng_analyze.js'),
path.join(repoRoot, 'packages/compiler-cli/preprocessor/ng-analyze/index.js'),
],
alias: {
'@angular/compiler-cli/private/hybrid_analysis': path.join(
repoRoot,
'packages/compiler-cli/private/hybrid_analysis.ts',
),
'@angular/compiler-cli/private/migrations': path.join(
repoRoot,
'packages/compiler-cli/private/migrations.ts',
),
'@angular/compiler-cli': path.join(repoRoot, 'packages/compiler-cli/index.ts'),
'@angular/compiler': path.join(repoRoot, 'packages/compiler/index.ts'),
'@angular/language-service/private': path.join(
repoRoot,
'packages/language-service/private.ts',
),
'@angular/language-service/api': path.join(repoRoot, 'packages/language-service/api.ts'),
'@angular/language-service': path.join(repoRoot, 'packages/language-service/api.ts'),
'@angular/core': path.join(repoRoot, 'packages/core/index.ts'),
},
define: {
__dirname: JSON.stringify(path.dirname(specFile)),
'import.meta.url': JSON.stringify(pathToFileURL(specFile).href),
},
logOverride: {
'empty-import-meta': 'silent',
},
});
console.log(`\nRunning ${path.basename(specFile)} with Jasmine:`);
const jasmine = new Jasmine();
jasmine.exitOnCompletion = false;
// The timeout lives on jasmine-core (`runner.jasmine`), not on the runner itself.
jasmine.jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
jasmine.env.configure({random: false});
jasmine.loadConfig({
spec_files: [outFile],
});
const result = await jasmine.execute();
if (result.overallStatus !== 'passed') {
process.exit(1);
}
} finally {
await fs.rm(outDir, {recursive: true, force: true});
}
@@ -1,6 +1,12 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"target": "ES2022",
"module": "esnext",
"moduleResolution": "bundler",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"rootDir": ".",
"paths": {
"@angular/core": ["./mock_packages/@angular/core/types/core.d.ts"],
@@ -21,9 +21,44 @@ import {
SignatureHelpContext,
} from 'vscode-languageserver';
import {TestFileManager} from '../../packages/compiler-cli/preprocessor/language-service/tests/test_file_manager';
import {startTsgo} from '../../packages/compiler-cli/preprocessor/language-service/tests/test_helpers';
import {
prepareTestWorkspace,
resolveWasmBinding,
startTsgo,
} from '../../packages/compiler-cli/preprocessor/language-service/tests/test_helpers';
import {canonicalizePath as normalizePath} from '../../packages/compiler-cli/preprocessor/language-service/src/utils.js';
/** Directory containing this file (and the spec files). */
const TESTS_DIR = path.dirname(fileURLToPath(import.meta.url));
/** Relative path to the Bazel-built server bundle, from the root of the runfiles tree. */
const SERVER_RUNFILES_PATH = 'ngp-vscode-ng-language-service/server/server_bundle.js';
/** Returns the directory the LSP specs use as their project workspace. */
export function getTestWorkspacePath(): string {
return prepareTestWorkspace(path.join(TESTS_DIR, 'test-workspace'));
}
/**
* Locates the bundled language server: the Bazel-built bundle when running under
* Bazel, otherwise the `dist/` output of `build.js`.
*/
async function resolveServerPath(): Promise<string> {
const runfiles = process.env['JS_BINARY__RUNFILES'] || process.env['RUNFILES_DIR'];
const candidates = runfiles
? ['_main', 'angular', ''].map((ws) => path.join(runfiles, ws, SERVER_RUNFILES_PATH))
: [];
candidates.push(path.resolve(TESTS_DIR, '../dist/server/server.js'));
for (const candidate of candidates) {
try {
await fs.access(candidate);
return candidate;
} catch {}
}
throw new Error(`Server bundle not found. Checked:\n${candidates.join('\n')}`);
}
export async function startTestServer(workspacePath: string) {
console.log('[LSP TEST DEBUG] Starting tsgo...');
// 1. Find and spawn tsgo (TS 7 server)
@@ -31,15 +66,20 @@ export async function startTestServer(workspacePath: string) {
console.log('[LSP TEST DEBUG] tsgo started. Spawning hybrid server...');
// 2. Find and spawn our server (Hybrid server)
const serverPath = path.resolve(__dirname, '../dist/server/server.js');
const serverPath = await resolveServerPath();
await fs.access(serverPath).catch(() => {
throw new Error(`Server binary not found at ${serverPath}`);
});
// The server locates the analysis engine through this variable; make sure it is
// set even when no outer runner (e.g. `wasm_binding.mjs`) has done so.
const wasmBinding = resolveWasmBinding();
const serverEnv = {...process.env};
if (wasmBinding) {
serverEnv['NG_EXP_COMPILER_WASM_BINDING'] = wasmBinding;
}
const serverProcess = cp.spawn(process.execPath, [serverPath, '--stdio'], {
stdio: ['pipe', 'pipe', 'inherit'],
cwd: workspacePath,
env: serverEnv,
});
const connection = rpc.createMessageConnection(
@@ -1,45 +0,0 @@
/*!
* @license
* Copyright Google LLC 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.dev/license
*/
import path from 'node:path';
import fsSync from 'node:fs';
/** Bazel target that produces the wasm engine and its sibling `package.json`. */
export const WASM_BUILD_TARGET = '//packages/compiler-cli/preprocessor/ng-analyze:wasm';
/**
* Ensures the analysis engine is reachable by the test process and anything it spawns.
*
* The engine is the Bazel-built wasm binding. The analyzer loader does not know about
* `dist/bin`, so we resolve the binding here and publish it through the loader's
* `NG_EXP_COMPILER_WASM_BINDING` override. Child processes (e.g. the bundled LSP server)
* inherit the environment, so this only needs to happen once in the test entrypoint.
*
* Throws when no binding can be found, so the suite fails fast instead of reporting
* every spec as a `null` result.
*/
export function ensureWasmBinding(repoRoot) {
if (process.env['NG_EXP_COMPILER_WASM_BINDING']) {
return process.env['NG_EXP_COMPILER_WASM_BINDING'];
}
const wasmBinding =
process.env['NGP_WASM_BINDING'] ||
path.join(
repoRoot,
'dist/bin/packages/compiler-cli/preprocessor/ng-analyze/ng_analyze_wasm/ng_analyze_wasm.js',
);
if (!fsSync.existsSync(wasmBinding)) {
throw new Error(
`Could not find the ng-analyze wasm binding at ${wasmBinding}.\n` +
`Build it first with: pnpm bazel build ${WASM_BUILD_TARGET}\n` +
`or point NGP_WASM_BINDING / NG_EXP_COMPILER_WASM_BINDING at a wasm-bindgen build.`,
);
}
process.env['NG_EXP_COMPILER_WASM_BINDING'] = wasmBinding;
return wasmBinding;
}
@@ -0,0 +1,6 @@
{
"extends": "./tsconfig-bazel.json",
"compilerOptions": {
"types": ["jasmine", "node"]
}
}
@@ -0,0 +1,5 @@
// Bazel tsconfig for the ngp language server. `pnpm compile`/`typecheck` use
// `tsconfig.json` instead, which maps `@angular/*` onto in-repo sources for esbuild.
{
"extends": "../packages/compiler-cli/preprocessor/tsconfig.json"
}
-1
View File
@@ -22,7 +22,6 @@
"build": "node scripts/build/build-packages-dist.mts",
"test": "bazelisk test",
"test:ci": "bazelisk test -- //... -//integration/... -//adev/... -//vscode-ng-language-service/... -//devtools/... -//modules/ssr-benchmarks/...",
"test:ngp:vscode": "pnpm bazel build //packages/compiler-cli/preprocessor/ng-analyze:wasm && pnpm --prefix ngp-vscode-ng-language-service run test:lsp",
"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",
@@ -4,6 +4,7 @@ ts_project(
name = "test_lib",
testonly = True,
srcs = glob(["*.ts"]),
visibility = ["//ngp-vscode-ng-language-service/tests:__pkg__"],
deps = [
"//:node_modules/@types/jasmine",
"//:node_modules/@types/node",
@@ -26,5 +27,8 @@ jasmine_test(
"//packages/compiler-cli/preprocessor/ng-analyze:ng_analyze_wasm",
"//packages/compiler-cli/preprocessor/ng-analyze:package_json",
] + glob(["test-workspace/**"]),
# The specs drive an external `tsgo` process over LSP and some rely on fixed
# sleeps, so they can occasionally fail under heavy machine load.
flaky = True,
shard_count = 4,
)
@@ -56,28 +56,56 @@ function runfilesDir(): string | undefined {
return process.env['JS_BINARY__RUNFILES'] || process.env['RUNFILES_DIR'];
}
let testWorkspacePath: string | null = null;
/**
* Recursively copies `source` to `dest`, following symlinks and writing fresh files.
*
* Deliberately avoids `fs.cpSync`: on macOS it clones via `copyfile(3)`, and when the
* source is a Bazel runfiles symlink the clone can `realpath()` back to the original
* `bazel-out` file from another process, which makes the language server resolve the
* fixture's `tsconfig.json` to the wrong location.
*/
function copyDirSync(source: string, dest: string): void {
fsSync.mkdirSync(dest, {recursive: true});
for (const entry of fsSync.readdirSync(source)) {
const from = path.join(source, entry);
const to = path.join(dest, entry);
if (fsSync.statSync(from).isDirectory()) {
copyDirSync(from, to);
} else {
fsSync.writeFileSync(to, fsSync.readFileSync(from));
}
}
}
const preparedWorkspaces = new Map<string, string>();
/**
* Returns the directory the specs use as their project workspace.
* Prepares a fixture directory for use as a project workspace by the specs.
*
* Under Bazel the runfiles tree is read-only, so the checked-in `test-workspace` is copied
* into `TEST_TMPDIR` once per process. Outside Bazel the source directory is used directly.
* Under Bazel the runfiles tree is read-only, so `source` is copied into `TEST_TMPDIR`
* once per process. Outside Bazel the source directory is used directly.
*/
export function getTestWorkspacePath(): string {
if (testWorkspacePath !== null) {
return testWorkspacePath;
export function prepareTestWorkspace(source: string): string {
const cached = preparedWorkspaces.get(source);
if (cached !== undefined) {
return cached;
}
const source = path.join(TESTS_DIR, 'test-workspace');
const tmpDir = process.env['TEST_TMPDIR'];
let workspace: string;
if (tmpDir && runfilesDir()) {
const dest = path.join(tmpDir, 'ngp-language-service-test-workspace');
fsSync.cpSync(source, dest, {recursive: true, dereference: true});
testWorkspacePath = fsSync.realpathSync(dest);
const dest = path.join(tmpDir, `ngp-test-workspace-${preparedWorkspaces.size}`);
copyDirSync(source, dest);
workspace = fsSync.realpathSync(dest);
} else {
testWorkspacePath = source;
workspace = source;
}
return testWorkspacePath;
preparedWorkspaces.set(source, workspace);
return workspace;
}
/** Returns the directory the language-service specs use as their project workspace. */
export function getTestWorkspacePath(): string {
return prepareTestWorkspace(path.join(TESTS_DIR, 'test-workspace'));
}
/**