Skip to content

Instantly share code, notes, and snippets.

@leonidaz
Created October 1, 2026 19:03
Show Gist options
  • Select an option

  • Save leonidaz/d1fcd2d140269282c7df1d3b84fe517f to your computer and use it in GitHub Desktop.

Select an option

Save leonidaz/d1fcd2d140269282c7df1d3b84fe517f to your computer and use it in GitHub Desktop.
TypeScript 7 VS Code extension: Go to Source Definition does not run in content-mapped files

TypeScript 7 VS Code extension: Go to Source Definition does not run in content-mapped files

.foo files contain TSX; mapper.mjs is a 47-line identity content mapper that returns them unchanged as .tsx (one verbatim span, all features). No framework, Volar, or tsserver plugin is involved. main.foo and control.ts have the same text:

import { greet } from "greeting";

export const text = greet("x");

greeting is a JavaScript library with its own index.d.ts, which setup.mjs writes into node_modules.

Verified with [email protected], the TypeScript 7 extension 1.0.1, VS Code 1.140.0, and Node.js 24.18.0 on macOS 26.6.2 x64.

Setup

npm install --ignore-scripts
npm run setup   # writes node_modules/identity-foo-mapper and node_modules/greeting

1. The language server answers for the content-mapped file

npm run ask

ask.mjs sends tsc --lsp the request of Go to Source Definition (custom/textDocument/sourceDefinition) on greet in both files:

main.foo definition:        node_modules/greeting/index.d.ts:1:25
main.foo source definition: node_modules/greeting/index.js:1:17
control.ts definition:        node_modules/greeting/index.d.ts:1:25
control.ts source definition: node_modules/greeting/index.js:1:17

2. The extension does not send it

Open this folder in VS Code with the TypeScript 7 extension, "js/ts.experimental.useTsgo": true, and "js/ts.tsdk.path": "node_modules/typescript" (the 7.1 nightly; the extension's bundled 7.0.2 has no content mappers). Trust the workspace. Put the cursor on greet in greet("x") and run TypeScript: Go to Source Definition from the Command Palette:

File Hover on greet Go to Source Definition
control.ts (alias) function greet(name: string): string opens node_modules/greeting/index.js
main.foo (alias) function greet(name: string): string opens nothing

The right-click menu has no Go to Source Definition entry in main.foo.

// Asks `tsc --lsp` for the definition and the source definition of `greet` in
// main.foo (content-mapped) and in control.ts (same text). The TypeScript 7 VS Code
// extension sends `custom/textDocument/sourceDefinition` for Go to Source Definition.
import { spawn } from "node:child_process";
import { readFileSync } from "node:fs";
import { fileURLToPath, pathToFileURL } from "node:url";
const root = fileURLToPath(new URL(".", import.meta.url));
const tsc = fileURLToPath(new URL("./node_modules/typescript/bin/tsc", import.meta.url));
const server = spawn(process.execPath, [tsc, "--lsp", "--stdio"], { cwd: root, stdio: ["pipe", "pipe", "inherit"] });
let nextId = 1;
const pending = new Map();
let buffered = Buffer.alloc(0);
const send = (message) => {
const body = Buffer.from(JSON.stringify({ jsonrpc: "2.0", ...message }));
server.stdin.write(`Content-Length: ${body.length}\r\n\r\n`);
server.stdin.write(body);
};
const request = (method, params) =>
new Promise((resolve) => {
const id = nextId++;
pending.set(id, resolve);
send({ id, method, params });
});
server.stdout.on("data", (chunk) => {
buffered = Buffer.concat([buffered, chunk]);
while (true) {
const headerEnd = buffered.indexOf("\r\n\r\n");
if (headerEnd < 0) return;
const length = Number(/Content-Length: (\d+)/i.exec(buffered.subarray(0, headerEnd).toString())[1]);
if (buffered.length < headerEnd + 4 + length) return;
const message = JSON.parse(buffered.subarray(headerEnd + 4, headerEnd + 4 + length).toString());
buffered = buffered.subarray(headerEnd + 4 + length);
if (message.method && message.id !== undefined) {
// Server-to-client requests: configuration, capability registration, progress.
const result = message.method === "workspace/configuration" ? message.params.items.map(() => null) : null;
send({ id: message.id, result });
} else if (message.id !== undefined && pending.has(message.id)) {
pending.get(message.id)(message.result ?? message.error);
pending.delete(message.id);
}
}
});
const uri = (file) => pathToFileURL(`${root}${file}`).href;
await request("initialize", {
processId: process.pid,
rootUri: pathToFileURL(root).href,
workspaceFolders: [{ uri: pathToFileURL(root).href, name: "repro" }],
capabilities: {
workspace: { configuration: true, workspaceFolders: true },
textDocument: {
synchronization: { dynamicRegistration: true },
diagnostic: { dynamicRegistration: true },
},
},
initializationOptions: { runExternalCode: true },
});
send({ method: "initialized", params: {} });
const show = (result) =>
(Array.isArray(result) ? result : result ? [result] : [])
.map((l) => {
const range = l.range ?? l.targetSelectionRange;
return `${(l.uri ?? l.targetUri).slice(pathToFileURL(root).href.length)}:${range.start.line + 1}:${range.start.character + 1}`;
})
.join(", ") || JSON.stringify(result);
for (const [file, languageId] of [["main.foo", "plaintext"], ["control.ts", "typescript"]]) {
const text = readFileSync(`${root}${file}`, "utf8");
send({ method: "textDocument/didOpen", params: { textDocument: { uri: uri(file), languageId, version: 1, text } } });
// Wait until the project (and the mapper) has loaded the file.
await request("textDocument/diagnostic", { textDocument: { uri: uri(file) } });
const line = text.split("\n").findIndex((l) => l.includes("greet("));
const params = { textDocument: { uri: uri(file) }, position: { line, character: text.split("\n")[line].indexOf("greet(") + 1 } };
console.log(`${file} definition: ${show(await request("textDocument/definition", params))}`);
console.log(`${file} source definition: ${show(await request("custom/textDocument/sourceDefinition", params))}`);
}
await request("shutdown");
send({ method: "exit" });
import { greet } from "greeting";
export const text = greet("x");
import { greet } from "greeting";
export const text = greet("x");
// Identity content mapper: .foo contains TSX, returned without changes.
// No TSRX, Volar, or framework dependencies.
let buffered = Buffer.alloc(0);
process.stdin.on("data", (chunk) => {
buffered = Buffer.concat([buffered, chunk]);
while (true) {
const headerEnd = buffered.indexOf("\r\n\r\n");
if (headerEnd < 0) return;
const header = buffered.subarray(0, headerEnd).toString("ascii");
const match = /^Content-Length:\s*(\d+)\s*$/im.exec(header);
if (!match) throw new Error("Missing Content-Length");
const end = headerEnd + 4 + Number(match[1]);
if (buffered.length < end) return;
const request = JSON.parse(buffered.subarray(headerEnd + 4, end).toString("utf8"));
buffered = buffered.subarray(end);
if (request.id === undefined || request.id === null) continue;
let result;
switch (request.method) {
case "initialize":
result = { positionEncoding: "utf-16", diagnosticSource: "foo" };
break;
case "openProject":
result = {};
break;
case "closeProject":
result = null;
break;
case "transform": {
const text = request.params.content;
result = {
text,
extension: ".tsx",
mappings: [[0, text.length, 0, text.length, 0]],
};
break;
}
default:
throw new Error(`Unexpected request: ${request.method}`);
}
const body = Buffer.from(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }));
process.stdout.write(`Content-Length: ${body.length}\r\n\r\n`);
process.stdout.write(body);
}
});
process.stdin.on("end", () => process.exit(0));
{
"name": "typescript-content-mapper-source-definition-repro",
"private": true,
"type": "module",
"scripts": {
"setup": "node setup.mjs",
"ask": "node ask.mjs"
},
"devDependencies": {
"typescript": "7.1.0-dev.20260930.4"
}
}
import { mkdirSync, writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
/** @param {string} directory @param {Record<string, string>} files */
function write(directory, files) {
const url = new URL(`./node_modules/${directory}/`, import.meta.url);
mkdirSync(url, { recursive: true });
for (const [name, text] of Object.entries(files)) writeFileSync(new URL(name, url), text);
}
// TypeScript resolves the local mapper package and starts this Node script.
write("identity-foo-mapper", {
"package.json": JSON.stringify({
name: "identity-foo-mapper",
version: "1.0.0",
type: "module",
typescript: {
contentMapper: {
exec: [process.execPath, fileURLToPath(new URL("./mapper.mjs", import.meta.url))],
compilerOptions: [],
},
},
}, null, 2) + "\n",
});
// A JavaScript library with its own declaration file.
write("greeting", {
"package.json": JSON.stringify({ name: "greeting", type: "module", main: "index.js", types: "index.d.ts" }, null, 2) + "\n",
"index.js": "export function greet(name) {\n return \"Hello \" + name;\n}\n",
"index.d.ts": "export declare function greet(name: string): string;\n",
});
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "preserve",
"strict": true,
"noEmit": true,
"types": []
},
"contentMappers": [
{
"package": "identity-foo-mapper",
"extensions": [
".foo"
]
}
],
"include": [
"main.foo",
"control.ts"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment