refactor(compiler-cli): support cold-start project discovery for html templates

Resolve sibling TypeScript files in ProjectManager.resolveTsconfigPath when a template's filename does not directly match its component (e.g. *.template.html -> *.component.ts), and initialize the TS 7 API session before starting the Angular language client so initial HTML document requests have an active API connection.

(cherry picked from commit f8e9ae8312)
This commit is contained in:
Andrew Scott
2026-11-18 18:11:22 +00:00
committed by Alon Mishne
parent b25324303f
commit 081e1cfbe3
4 changed files with 81 additions and 47 deletions
@@ -97,6 +97,26 @@ export async function activate(context: vscode.ExtensionContext) {
outputChannel.appendLine(`Could not get existing TypeScript API connection: ${err}`);
}
const tsGoPath = await resolveTsGoPath();
let ts7Client: LanguageClient | undefined;
if (tsGoPath) {
ts7Client = createTs7Client(tsGoPath);
try {
await ts7Client.start();
if (!tsApiPipe && !usingNativePreviewExtension) {
const res = await ts7Client.sendRequest<{sessionId: string; pipe: string}>(
'custom/initializeAPISession',
{},
);
if (res?.pipe) {
tsApiPipe = res.pipe;
}
}
} catch (err) {
outputChannel.appendLine(`Failed to start TS 7 Server: ${err}`);
}
}
const distServer = context.asAbsolutePath(path.join('dist', 'server', 'server.js'));
const bazelServer = context.asAbsolutePath(
path.join('..', 'dist', 'bin', 'ngp-vscode-ng-language-service', 'server', 'server_bundle.js'),
@@ -134,6 +154,10 @@ export async function activate(context: vscode.ExtensionContext) {
clientOptions,
);
if (ts7Client) {
context.subscriptions.push(registerTs7RelayHandlers(client, ts7Client));
}
registerCommands(context, client, outputChannel);
client
@@ -144,23 +168,9 @@ export async function activate(context: vscode.ExtensionContext) {
.catch((err) => {
outputChannel.appendLine(`Failed to start Angular Language Service: ${err}`);
});
const tsGoPath = await resolveTsGoPath();
// Launch ts7Client when tsGoPath is available so registerTs7RelayHandlers is active
// for TsGoFacade LSP requests. Only initialize an API session on ts7Client if we
// didn't already connect to typescriptteam.native-preview's API pipe.
if (tsGoPath) {
launchTs7Client(tsGoPath, context, clientReady, !tsApiPipe && !usingNativePreviewExtension);
}
}
function launchTs7Client(
tsGoPath: string,
context: vscode.ExtensionContext,
clientReady: Promise<void>,
initializeApiSession: boolean,
) {
function createTs7Client(tsGoPath: string): LanguageClient {
const isNative =
tsGoPath.includes(`typescript-${process.platform}-${process.arch}`) ||
tsGoPath.includes(`native-preview-${process.platform}-${process.arch}`) ||
@@ -210,34 +220,12 @@ function launchTs7Client(
},
};
const ts7Client = new LanguageClient(
return new LanguageClient(
'ng-ts-server',
'Angular TS 7 Server',
ts7ServerOptions,
ts7ClientOptions,
);
ts7Client
.start()
.then(async () => {
if (!initializeApiSession) {
return;
}
try {
const res = await ts7Client!.sendRequest<{sessionId: string; pipe: string}>(
'custom/initializeAPISession',
{},
);
if (res?.pipe) {
await clientReady;
client.sendNotification('angular/setTsApiPipe', {pipe: res.pipe});
}
} catch {}
})
.catch((err) => {
ts7OutputChannel.appendLine(`Failed to start TS 7 Server: ${err}`);
});
context.subscriptions.push(registerTs7RelayHandlers(client, ts7Client));
}
export function deactivate(): Thenable<void> | undefined {
@@ -7,6 +7,7 @@
*/
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import {readConfiguration} from '@angular/compiler-cli';
import {API, Snapshot} from '@typescript/native-preview/async';
import {HybridCompiler} from '../../../packages/compiler-cli/preprocessor/src/hybrid_compiler.js';
@@ -220,8 +221,11 @@ export class ProjectManager {
let targetPath = normFilePath;
let shouldOpenTarget = false;
if (normFilePath.endsWith('.html')) {
targetPath = normFilePath.replace(/\.html$/, '.ts');
shouldOpenTarget = await pathExists(targetPath);
const companionTsPath = await findCompanionTsFile(normFilePath);
if (companionTsPath) {
targetPath = companionTsPath;
shouldOpenTarget = true;
}
}
const previousSnapshot = this.currentSnapshot;
@@ -307,6 +311,39 @@ export class ProjectManager {
}
}
async function findCompanionTsFile(htmlFilePath: string): Promise<string | null> {
const directCandidate = htmlFilePath.replace(/\.html$/, '.ts');
if (await pathExists(directCandidate)) {
return directCandidate;
}
if (htmlFilePath.endsWith('.template.html')) {
const componentCandidate = htmlFilePath.replace(/\.template\.html$/, '.component.ts');
if (await pathExists(componentCandidate)) {
return componentCandidate;
}
}
try {
const dir = path.dirname(htmlFilePath);
const entries = await fs.readdir(dir);
const tsFiles = entries.filter(
(f) => f.endsWith('.ts') && !f.endsWith('.d.ts') && !f.endsWith('.ngtypecheck.ts'),
);
const preferred =
tsFiles.find((f) => f.endsWith('.component.ts')) ??
tsFiles.find(
(f) => !f.endsWith('.spec.ts') && !f.endsWith('.test.ts') && !f.endsWith('.e2e.ts'),
) ??
tsFiles[0];
if (preferred) {
return await normalizePath(path.join(dir, preferred));
}
} catch {}
return null;
}
function pathExists(p: string) {
return fs.access(p).then(
() => true,
@@ -175,6 +175,18 @@ connection.onInitialize(async (params: InitializeParams) => {
if (projectManager) {
projectManager.setApi(dynamicApi);
connection.console.log(`[SERVER] Connected to dynamic TS7 API pipe: ${params.pipe}`);
const openUpdates = documents
.all()
.map((doc) => ({filePath: fileURLToPath(doc.uri), content: doc.getText()}))
.filter(
({filePath}) =>
!filePath.endsWith('.ngtypecheck.ts') &&
(filePath.endsWith('.html') || filePath.endsWith('.ts')),
);
if (openUpdates.length > 0) {
await projectManager.updateFileContent(openUpdates);
connection.languages.diagnostics.refresh().catch(() => {});
}
}
} catch (err) {
connection.console.error(`[SERVER] Failed to connect to dynamic TS7 API pipe: ${err}`);
@@ -126,7 +126,7 @@ describe('Multi-Project Support', () => {
import {Component} from '@angular/core';
@Component({
selector: 'app-solution-test',
templateUrl: './solution.component.html',
templateUrl: './solution.template.html',
standalone: true,
})
export class SolutionTestComponent {
@@ -135,14 +135,11 @@ describe('Multi-Project Support', () => {
`;
const htmlContent = '<div [title]="¦solutionTitle"></div>';
const tsFilePath = await env.createFile('solution_proj/solution.component.ts', tsContent);
await env.createFile('solution_proj/solution.component.ts', tsContent);
try {
await env.run('solution_proj/solution.component.html', htmlContent, async (htmlFilePath) => {
// Open the TS file to populate the compiler with component declarations
await env.openFile(tsFilePath, tsContent);
// Verify hover on HTML file works cleanly
await env.run('solution_proj/solution.template.html', htmlContent, async (htmlFilePath) => {
// Verify hover on HTML file works cleanly without opening the TS file first
await env.expectHoverAtCursor(htmlFilePath, ['solutionTitle', 'string']);
});
} finally {