Skip to content

Commit c0cac52

Browse files
leonidazclaude
andcommitted
feat(vscode-plugin): Go to Source Definition goes past .d.ts files in .tsrx files
TSRX: Go to Source Definition used to run Go to Definition and prefer a .tsrx result. VS Code's own command and the TypeScript 7 extension's run only in TypeScript and JavaScript files. Now, with VS Code's own TypeScript (5.9 or 6), the command sends @tsrx/typescript-plugin's `_tsrx:findSourceDefinition` through typescript.tsserverRequest: `useState` opens React's JavaScript instead of @types/react. With TypeScript 7 it opens the definition and says why the first time: tsc --lsp answers the request for .tsrx files, but the TypeScript 7 extension's command refuses them (microsoft/TypeScript#64576). The TYPESCRIPT_7_SOURCE_DEFINITION flag hands over once that ships (#992). Both paths open results with editor.action.goToLocations and an explicit file and position, so they work without the editor focus. The editor tests now run the command on `useState` in every setup where TypeScript works. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent e8d10bc commit c0cac52

8 files changed

Lines changed: 395 additions & 80 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@tsrx/typescript-plugin': patch
3+
'@tsrx/vscode-plugin': patch
4+
---
5+
6+
**Go to Source Definition** now works in `.tsrx` files with VS Code's own TypeScript (5.9 or 6). Like Go to Definition, it opens a symbol's definition, but it goes past a `.d.ts` file to the JavaScript behind it: `useState` opens React's JavaScript, not `@types/react`. Before, the command only ran Go to Definition. VS Code's own Go to Source Definition runs only in TypeScript and JavaScript files.
7+
8+
`@tsrx/typescript-plugin` adds the request the extension sends, `_tsrx:findSourceDefinition`, and fixes tsserver's `findSourceDefinition` for `.tsrx` files. It used to fail with "Debug Failure. Script kind should match provided ScriptKind" for a symbol from a library: tsserver checks the library in a helper project without plugins, which read the `.tsrx` file as plain TypeScript. The plugin now sets up that helper project too.
9+
10+
With TypeScript 7, the command opens the definition and says that Go to Source Definition does not work in `.tsrx` files yet: `tsc --lsp` can answer the request, but the TypeScript 7 extension runs its command only in TypeScript and JavaScript files (microsoft/TypeScript#64576).

‎packages/vscode-plugin/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,13 @@ On the native backend (TypeScript 7):
157157
keyword highlights from the TSRX language server do not show. In this case, VS
158158
Code uses only the multi-document highlight provider of the TypeScript 7
159159
extension.
160+
- **Go to Source Definition:** TSRX's command opens the definition instead, and
161+
says why the first time. `tsc --lsp` can find the source definition in `.tsrx`
162+
files, but the TypeScript 7 extension runs its command only in TypeScript and
163+
JavaScript files
164+
([microsoft/TypeScript#64576](https://github.com/microsoft/TypeScript/issues/64576)).
165+
On the classic backend, the command goes past a `.d.ts` file to the JavaScript
166+
behind it.
160167

161168
### Known limitation on both backends
162169

‎packages/vscode-plugin/editor-tests/harness/checks.cjs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,19 @@ exports.run = async () => {
230230
),
231231
diagnostics: diagnostics_of(main.uri),
232232
};
233+
234+
// TSRX's Go to Source Definition on `useState`: the file it opens.
235+
const source_editor = await vscode.window.showTextDocument(document);
236+
const use_state = document.positionAt(document.getText().indexOf('useState(0)') + 2);
237+
source_editor.selection = new vscode.Selection(use_state, use_state);
238+
await within(vscode.commands.executeCommand('tsrx.goToSourceDefinition'), 30000, undefined);
239+
const source_deadline = Date.now() + 10000;
240+
while (vscode.window.activeTextEditor?.document === document && Date.now() < source_deadline) {
241+
await sleep(250);
242+
}
243+
const opened = vscode.window.activeTextEditor?.document;
244+
result.sourceDefinition =
245+
opened && opened !== document ? opened.uri.path.split('/node_modules/').pop() : undefined;
233246
// Back to the file, so it is what gets reverted and closed below.
234247
await vscode.window.showTextDocument(document);
235248

‎packages/vscode-plugin/editor-tests/run.js‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,23 @@ function imports_problem(result) {
397397
return undefined;
398398
}
399399

400+
/**
401+
* TSRX's Go to Source Definition on `useState`: React's JavaScript where VS Code's
402+
* own TypeScript serves the file, the `.d.ts` definition on TypeScript 7 (which has
403+
* no way to run it in `.tsrx` files yet, microsoft/TypeScript#64576).
404+
* @param {import('./scenarios.js').Scenario} scenario
405+
* @param {Record<string, any>} result
406+
*/
407+
function source_definition_problem(scenario, result) {
408+
const expected =
409+
scenario.expect === 'vscode-typescript'
410+
? /^react\/cjs\/react\.\w+\.js$/
411+
: /^@types\/react\/index\.d\.ts$/;
412+
return expected.test(result.sourceDefinition ?? '')
413+
? undefined
414+
: `expected Go to Source Definition to open ${expected}, got ${JSON.stringify(result.sourceDefinition)}`;
415+
}
416+
400417
/**
401418
* The fallback for `hide-test-windows.swift`: VS Code brings its first window to the
402419
* front even when `open` starts it hidden in the background. When the instance is in
@@ -474,11 +491,14 @@ for (const scenario of selected) {
474491
(result?.notices ?? []).map((/** @type {{ id: string }} */ notice) => notice.id).join(', ') ||
475492
'none';
476493
const imports = scenario.expect === 'nothing' ? undefined : imports_problem(result ?? {});
494+
const source_definition =
495+
scenario.expect === 'nothing' ? undefined : source_definition_problem(scenario, result ?? {});
496+
const feature = imports ?? source_definition;
477497
const problem =
478498
observed !== scenario.expect
479499
? `expected ${scenario.expect}, got ${observed}`
480-
: imports
481-
? imports
500+
: feature
501+
? feature
482502
: scenario.closingTag !== undefined && closing_tag !== scenario.closingTag
483503
? `expected ${JSON.stringify(scenario.closingTag)} after typing <b>, got ${JSON.stringify(closing_tag)}`
484504
: status !== scenario.typescript
@@ -493,6 +513,7 @@ for (const scenario of selected) {
493513
expected: scenario.expect,
494514
observed,
495515
imports: scenario.expect === 'nothing' ? '-' : imports ? 'FAIL' : 'ok',
516+
'source definition': result?.sourceDefinition?.split('/').pop() ?? '-',
496517
'after typing <b>': closing_tag,
497518
'TypeScript status': [status, result?.typescriptStatus?.version].filter(Boolean).join(' '),
498519
notices,

‎packages/vscode-plugin/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@
158158
{
159159
"command": "tsrx.goToSourceDefinition",
160160
"when": "resourceLangId == tsrx",
161-
"group": "navigation@9"
161+
"group": "navigation@1.41"
162162
}
163163
],
164164
"explorer/context": [

‎packages/vscode-plugin/src/extension.js‎

Lines changed: 7 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import * as lsp from 'vscode-languageclient/node';
2424
import { createLabsInfo } from '@volar/vscode';
2525
import { activate_closing_tags } from './closing-tags.js';
2626
import { register_restart_command } from './restart.js';
27+
import { register_source_definition_command } from './source-definition.js';
2728
import { CompileErrorDedupe } from './diagnostics.js';
2829
import { activate_typescript } from './typescript.js';
2930
import { activate_typescript_guidance } from './typescript-guidance.js';
@@ -98,8 +99,12 @@ export async function activate(context) {
9899

99100
// Which TypeScript serves .tsrx files, and what to do when none can.
100101
const typescript_guidance = activate_typescript_guidance(context);
101-
// Registered before the server starts, so it can retry a server that failed to start.
102-
context.subscriptions.push(register_restart_command(() => client));
102+
// Registered before the server starts: the restart command can retry a server that
103+
// failed to start, and Go to Source Definition needs only TypeScript.
104+
context.subscriptions.push(
105+
register_restart_command(() => client),
106+
register_source_definition_command(),
107+
);
103108

104109
const serverModule = path.join(__dirname, 'server.js');
105110

@@ -239,9 +244,6 @@ export async function activate(context) {
239244

240245
await activate_typescript(context);
241246

242-
addCustomCommands(context);
243-
console.log('[TSRX] Registered custom commands');
244-
245247
console.log('[TSRX] Extension activated successfully');
246248
// `typescriptGuidance` is read by the editor tests (`editor-tests/harness`).
247249
return { ...volar_labs.extensionExports, typescriptGuidance: typescript_guidance };
@@ -253,78 +255,6 @@ export async function activate(context) {
253255
}
254256
}
255257

256-
/**
257-
* The extension's own commands.
258-
* @param {import('vscode').ExtensionContext} context
259-
*/
260-
function addCustomCommands(context) {
261-
context.subscriptions.push(
262-
vscode.commands.registerCommand('tsrx.goToSourceDefinition', async () => {
263-
try {
264-
const editor = vscode.window.activeTextEditor;
265-
if (!editor) {
266-
console.log('[TSRX] No active editor');
267-
return;
268-
}
269-
270-
const position = editor.selection.active;
271-
console.log('[TSRX] Getting definitions at position:', position);
272-
273-
// Use VS Code's definition provider API
274-
const definitions = await vscode.commands.executeCommand(
275-
'vscode.executeDefinitionProvider',
276-
editor.document.uri,
277-
position,
278-
);
279-
280-
console.log('[TSRX] Definitions result:', definitions);
281-
282-
if (!definitions || !Array.isArray(definitions) || definitions.length === 0) {
283-
vscode.window.showInformationMessage('No definition found');
284-
return;
285-
}
286-
287-
// Filter for .tsrx files (prefer source over .d.ts)
288-
// Definition objects can have either `uri` or `targetUri`
289-
const tsrxDefinition = definitions.find((d) => {
290-
const uri = d?.uri || d?.targetUri;
291-
if (!uri) {
292-
console.warn('[TSRX] Definition has no uri:', d);
293-
return false;
294-
}
295-
const is_tsrx = is_tsrx_file_path(uri.path);
296-
console.log('[TSRX] Checking definition:', uri.path, 'isTSRX:', is_tsrx);
297-
return is_tsrx;
298-
});
299-
300-
if (tsrxDefinition) {
301-
const uri = tsrxDefinition.uri || tsrxDefinition.targetUri;
302-
const range = tsrxDefinition.range || tsrxDefinition.targetRange;
303-
console.log('[TSRX] Found tsrx definition:', uri.path);
304-
await vscode.window.showTextDocument(uri, {
305-
selection: range,
306-
});
307-
} else {
308-
// If no .tsrx file found, just go to the first definition (might be .d.ts)
309-
const firstDef = definitions[0];
310-
const uri = firstDef?.uri || firstDef?.targetUri;
311-
const range = firstDef?.range || firstDef?.targetRange;
312-
console.log('[TSRX] No .tsrx definition, using first result:', uri?.path);
313-
if (uri) {
314-
await vscode.window.showTextDocument(uri, {
315-
selection: range,
316-
});
317-
}
318-
}
319-
} catch (error) {
320-
console.error('[TSRX] Error in goToSourceDefinition:', error);
321-
const message = error instanceof Error ? error.message : String(error);
322-
vscode.window.showErrorMessage(`Go to Source Definition failed: ${message}`);
323-
}
324-
}),
325-
);
326-
}
327-
328258
async function configurePrettier() {
329259
try {
330260
const config = vscode.workspace.getConfiguration();
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
import vscode from 'vscode';
2+
import { SOURCE_DEFINITION_COMMAND } from '@tsrx/typescript-plugin/src/plugin-source-definition.js';
3+
import { TYPESCRIPT_7_TRACKING_URL } from '@tsrx/typescript-plugin/src/typescript-version.js';
4+
import { typescript_7_on } from './typescript-7.js';
5+
6+
export const GO_TO_SOURCE_DEFINITION_COMMAND = 'tsrx.goToSourceDefinition';
7+
8+
/**
9+
* Whether the TypeScript 7 extension's Go to Source Definition runs in `.tsrx` files.
10+
* `tsc --lsp` answers its request (`custom/textDocument/sourceDefinition`) for them
11+
* through the content mapper, but the command only runs in TypeScript and JavaScript
12+
* files, and no other extension can send the request (microsoft/TypeScript#64576).
13+
* Set this to true once a fixed extension ships (tsrx-org/tsrx#992).
14+
*/
15+
const TYPESCRIPT_7_SOURCE_DEFINITION = false;
16+
17+
const NO_SOURCE_DEFINITIONS = 'No source definitions found.';
18+
19+
/**
20+
* **Go to Source Definition** in `.tsrx` files: like Go to Definition, but it goes
21+
* past a `.d.ts` file to the JavaScript behind it. VS Code's own command and the
22+
* TypeScript 7 extension's only run in TypeScript and JavaScript files.
23+
*
24+
* - VS Code's own TypeScript (5.9 or 6): `typescript.tsserverRequest` sends
25+
* `@tsrx/typescript-plugin`'s `SOURCE_DEFINITION_COMMAND`, which runs tsserver's
26+
* `findSourceDefinition`. That command forwards only requests whose name starts
27+
* with `_`, besides a few built-in ones.
28+
* - TypeScript 7: Go to Definition, until `TYPESCRIPT_7_SOURCE_DEFINITION`. The first
29+
* time in a session, a message says why.
30+
* @returns {import('vscode').Disposable}
31+
*/
32+
export function register_source_definition_command() {
33+
let explained = false;
34+
return vscode.commands.registerCommand(GO_TO_SOURCE_DEFINITION_COMMAND, async () => {
35+
const editor = vscode.window.activeTextEditor;
36+
if (!editor) return;
37+
const { document } = editor;
38+
const position = editor.selection.active;
39+
40+
/** @type {import('vscode').Location[] | undefined} */
41+
let locations;
42+
let not_found = NO_SOURCE_DEFINITIONS;
43+
if (typescript_7_on()) {
44+
if (TYPESCRIPT_7_SOURCE_DEFINITION) {
45+
return vscode.commands.executeCommand('typescript.native-preview.goToSourceDefinition');
46+
}
47+
if (!explained) {
48+
explained = true;
49+
void vscode.window
50+
.showInformationMessage(
51+
'Go to Source Definition does not work in .tsrx files with TypeScript 7 yet. TSRX opened the definition instead.',
52+
'Learn More',
53+
)
54+
.then((choice) => {
55+
if (choice) void vscode.env.openExternal(vscode.Uri.parse(TYPESCRIPT_7_TRACKING_URL));
56+
});
57+
}
58+
locations = await definitions(document.uri, position);
59+
not_found = 'No definition found.';
60+
} else {
61+
locations = await vscode.window.withProgress(
62+
{ location: vscode.ProgressLocation.Window, title: 'Finding source definitions' },
63+
() => source_definitions(document.uri, position),
64+
);
65+
if (!locations) return;
66+
}
67+
// The editor and position are explicit, so this works without the editor focus.
68+
await vscode.commands.executeCommand(
69+
'editor.action.goToLocations',
70+
document.uri,
71+
position,
72+
locations,
73+
'goto',
74+
not_found,
75+
);
76+
});
77+
}
78+
79+
/**
80+
* tsserver's source definitions, through `@tsrx/typescript-plugin`'s request.
81+
* @param {import('vscode').Uri} uri
82+
* @param {import('vscode').Position} position
83+
* @returns {Promise<import('vscode').Location[] | undefined>} `undefined` when the request
84+
* failed (after saying so) or was cancelled.
85+
*/
86+
async function source_definitions(uri, position) {
87+
/** @type {{ type?: string, body?: Array<{ file: string, start: TsserverPosition, end: TsserverPosition }> } | undefined} */
88+
let response;
89+
try {
90+
response = await vscode.commands.executeCommand(
91+
'typescript.tsserverRequest',
92+
SOURCE_DEFINITION_COMMAND,
93+
{ file: uri, line: position.line + 1, offset: position.character + 1 },
94+
);
95+
} catch (error) {
96+
const message = error instanceof Error ? error.message : String(error);
97+
vscode.window.showErrorMessage(`Go to Source Definition failed: ${message}`);
98+
return undefined;
99+
}
100+
if (response?.type === 'cancelled') return undefined;
101+
return (response?.body ?? []).map(
102+
(span) =>
103+
new vscode.Location(
104+
vscode.Uri.file(span.file),
105+
new vscode.Range(
106+
span.start.line - 1,
107+
span.start.offset - 1,
108+
span.end.line - 1,
109+
span.end.offset - 1,
110+
),
111+
),
112+
);
113+
}
114+
115+
/**
116+
* Go to Definition's locations, from whichever TypeScript serves the file.
117+
* @param {import('vscode').Uri} uri
118+
* @param {import('vscode').Position} position
119+
* @returns {Promise<import('vscode').Location[]>}
120+
*/
121+
async function definitions(uri, position) {
122+
/** @type {Array<import('vscode').Location | import('vscode').LocationLink> | undefined} */
123+
const found = await vscode.commands.executeCommand(
124+
'vscode.executeDefinitionProvider',
125+
uri,
126+
position,
127+
);
128+
return (found ?? []).map((definition) =>
129+
'targetUri' in definition
130+
? new vscode.Location(
131+
definition.targetUri,
132+
definition.targetSelectionRange ?? definition.targetRange,
133+
)
134+
: definition,
135+
);
136+
}
137+
138+
/** @typedef {{ line: number, offset: number }} TsserverPosition One-based, as tsserver counts. */

0 commit comments

Comments
 (0)