Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions packages/typescript/test/async/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2309,6 +2309,55 @@ describe("BuildOrchestrator", () => {
}]);
});

test("runs content mappers when the API allows external code", {
skip: process.env.TS_API_TEST_WASM ? "WASM cannot spawn external content mapper processes" : false,
}, async t => {
const directory = mkdtempSync(join(tmpdir(), "ts-build-content-mapper-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
const mapperDirectory = join(directory, "node_modules", "mapper");
mkdirSync(mapperDirectory, { recursive: true });
const mapperScript = `
import { createMessageConnection } from ${JSON.stringify(new URL("../../vendor/vscode-jsonrpc/lib/node/main.js", import.meta.url).href)};
const connection = createMessageConnection(process.stdin, process.stdout);
connection.onRequest("initialize", () => ({ positionEncoding: "utf-8", diagnosticSource: "mapper" }));
connection.onRequest("openProject", () => ({}));
connection.onRequest("closeProject", () => null);
connection.onRequest("transform", ({ content }) => ({
text: "export {};",
extension: ".ts",
supplemental: [{ text: content, extension: ".ts" }],
}));
connection.listen();
`;
writeFileSync(
join(mapperDirectory, "package.json"),
JSON.stringify({
name: "mapper",
version: "1.0.0",
typescript: { contentMapper: { exec: [process.execPath, "--input-type=module", "--eval", mapperScript] } },
}),
);
writeFileSync(
join(directory, "tsconfig.json"),
JSON.stringify({
compilerOptions: { noEmit: true, incremental: true },
files: ["app.box", "main.ts"],
contentMappers: [{ package: "mapper", extensions: [".box"] }],
}),
);
writeFileSync(join(directory, "app.box"), "declare const supplementalValue: number;");
writeFileSync(join(directory, "main.ts"), "const value: string = supplementalValue;");
await using api = new API({ cwd: directory, runExternalCode: true });
const expected = [[2322, "Type 'number' is not assignable to type 'string'."]];
for (let i = 0; i < 2; i++) {
// @ts-ignore -- Internal API exercised by source tests.
await using orchestrator = await api.createBuildOrchestrator(["tsconfig.json"], {});
const response = await orchestrator.build();
assert.deepEqual(response.diagnostics?.map((diagnostic: { code: number; text: string; }) => [diagnostic.code, diagnostic.text]), expected);
assert.ok(existsSync(join(directory, "tsconfig.tsbuildinfo")));
}
});

test("returns build response information after clean", async () => {
const { api: disposableApi } = spawnAPIWithFS({ ...files });
await using api = disposableApi;
Expand Down
49 changes: 49 additions & 0 deletions packages/typescript/test/sync/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2133,6 +2133,55 @@ describe("BuildOrchestrator", () => {
}]);
});

test("runs content mappers when the API allows external code", {
skip: process.env.TS_API_TEST_WASM ? "WASM cannot spawn external content mapper processes" : false,
}, t => {
const directory = mkdtempSync(join(tmpdir(), "ts-build-content-mapper-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
const mapperDirectory = join(directory, "node_modules", "mapper");
mkdirSync(mapperDirectory, { recursive: true });
const mapperScript = `
import { createMessageConnection } from ${JSON.stringify(new URL("../../vendor/vscode-jsonrpc/lib/node/main.js", import.meta.url).href)};
const connection = createMessageConnection(process.stdin, process.stdout);
connection.onRequest("initialize", () => ({ positionEncoding: "utf-8", diagnosticSource: "mapper" }));
connection.onRequest("openProject", () => ({}));
connection.onRequest("closeProject", () => null);
connection.onRequest("transform", ({ content }) => ({
text: "export {};",
extension: ".ts",
supplemental: [{ text: content, extension: ".ts" }],
}));
connection.listen();
`;
writeFileSync(
join(mapperDirectory, "package.json"),
JSON.stringify({
name: "mapper",
version: "1.0.0",
typescript: { contentMapper: { exec: [process.execPath, "--input-type=module", "--eval", mapperScript] } },
}),
);
writeFileSync(
join(directory, "tsconfig.json"),
JSON.stringify({
compilerOptions: { noEmit: true, incremental: true },
files: ["app.box", "main.ts"],
contentMappers: [{ package: "mapper", extensions: [".box"] }],
}),
);
writeFileSync(join(directory, "app.box"), "declare const supplementalValue: number;");
writeFileSync(join(directory, "main.ts"), "const value: string = supplementalValue;");
using api = new API({ cwd: directory, runExternalCode: true });
const expected = [[2322, "Type 'number' is not assignable to type 'string'."]];
for (let i = 0; i < 2; i++) {
// @ts-ignore -- Internal API exercised by source tests.
using orchestrator = api.createBuildOrchestrator(["tsconfig.json"], {});
const response = orchestrator.build();
assert.deepEqual(response.diagnostics?.map((diagnostic: { code: number; text: string; }) => [diagnostic.code, diagnostic.text]), expected);
assert.ok(existsSync(join(directory, "tsconfig.tsbuildinfo")));
}
});

test("returns build response information after clean", () => {
const { api: disposableApi } = spawnAPIWithFS({ ...files });
using api = disposableApi;
Expand Down
13 changes: 12 additions & 1 deletion tsc/internal/api/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -1968,6 +1968,10 @@ func (s *Session) handleCreateBuildOrchestrator(ctx context.Context, params *Cre
if params.BuildOptions != nil {
command.BuildOptions = params.BuildOptions
}
if command.CompilerOptions.RunExternalCode.IsUnknown() && s.snapshotHost.RunExternalCode() {
// As with snapshots, configured content mappers may run when the session allows external code.
command.CompilerOptions.RunExternalCode = core.TSTrue
}
orchestrator := build.NewOrchestrator(build.Options{
Sys: buildSys,
Command: command,
Expand Down Expand Up @@ -2083,7 +2087,14 @@ func (s *apiBuildSystem) GetEnvironmentVariable(name string) (string, bool) {
}

func (s *apiBuildSystem) Spawn(command []string, dir string, stderr io.Writer) (io.ReadWriteCloser, error) {
return nil, errors.New("spawning processes is not supported by the API build orchestrator")
if !s.session.snapshotHost.RunExternalCode() {
return nil, errors.New("the API session does not allow running external code")
}
spawner := s.session.snapshotHost.ContentMapperSpawner()
if spawner == nil {
return nil, errors.New("spawning processes is not supported by the API session")
}
return spawner.Spawn(command, dir, stderr)
}
func (s *apiBuildSystem) Now() time.Time { return time.Now() }
func (s *apiBuildSystem) SinceStart() time.Duration { return time.Since(s.start) }
Expand Down
118 changes: 118 additions & 0 deletions tsc/internal/api/session_build_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package api

import (
"context"
"testing"

"github.com/microsoft/TypeScript/tsc/internal/bundled"
"github.com/microsoft/TypeScript/tsc/internal/core"
"github.com/microsoft/TypeScript/tsc/internal/project"
"github.com/microsoft/TypeScript/tsc/internal/testutil/contentmappertest"
"github.com/microsoft/TypeScript/tsc/internal/testutil/projecttestutil"
"gotest.tools/v3/assert"
)

func newContentMapperBuildSession(t *testing.T, runExternalCode bool) *Session {
t.Helper()
files := map[string]any{
"/home/project/tsconfig.json": `{"compilerOptions":{"noEmit":true,"incremental":true},"files":["app.box","main.ts"],"contentMappers":[{"package":"mapper","extensions":[".box"]}]}`,
"/home/project/node_modules/mapper/package.json": contentmappertest.PackageJSON(contentmappertest.SupplementalMapper),
"/home/project/app.box": "declare const supplementalValue: number;",
"/home/project/main.ts": "const value: string = supplementalValue;",
}
init, _ := projecttestutil.GetSessionInitOptions(files, &project.SessionOptions{
CurrentDirectory: "/home/project",
DefaultLibraryPath: bundled.LibPath(),
RunExternalCode: runExternalCode,
}, nil)
init.Spawner = contentmappertest.NewSpawner()
session := NewStandaloneSession(init, nil)
t.Cleanup(session.Close)
return session
}

func buildWithOrchestrator(t *testing.T, session *Session, compilerOptions *core.CompilerOptions) *BuildResponse {
t.Helper()
created, err := session.handleCreateBuildOrchestrator(context.Background(), &CreateBuildOrchestratorParams{
RootNames: []string{"tsconfig.json"},
CompilerOptions: compilerOptions,
})
assert.NilError(t, err)
t.Cleanup(func() {
_, _ = session.handleDisposeBuildOrchestrator(context.Background(), &DisposeBuildOrchestratorParams{BuildOrchestratorID: created.BuildOrchestratorID})
})
response, err := session.handleBuild(context.Background(), &BuildParams{BuildOrchestratorID: created.BuildOrchestratorID})
assert.NilError(t, err)
return response
}

type buildDiagnostic struct {
Code int32
Messages []string
}

func buildDiagnostics(response *BuildResponse) []buildDiagnostic {
result := make([]buildDiagnostic, 0, len(response.Diagnostics))
for _, diagnostic := range response.Diagnostics {
messages := []string{diagnostic.Text}
for _, chain := range diagnostic.MessageChain {
messages = append(messages, chain.Text)
}
result = append(result, buildDiagnostic{Code: diagnostic.Code, Messages: messages})
}
return result
}

func TestBuildOrchestratorRunsContentMappers(t *testing.T) {
t.Parallel()

expected := []buildDiagnostic{{Code: 2322, Messages: []string{"Type 'number' is not assignable to type 'string'."}}}

t.Run("inherits runExternalCode from the session", func(t *testing.T) {
t.Parallel()
session := newContentMapperBuildSession(t, true)
assert.DeepEqual(t, buildDiagnostics(buildWithOrchestrator(t, session, nil)), expected)
// A later build reuses the incremental build info and reports the same diagnostics.
assert.DeepEqual(t, buildDiagnostics(buildWithOrchestrator(t, session, nil)), expected)
})

t.Run("runs mappers when runExternalCode is set explicitly", func(t *testing.T) {
t.Parallel()
session := newContentMapperBuildSession(t, true)
response := buildWithOrchestrator(t, session, &core.CompilerOptions{RunExternalCode: core.TSTrue})
assert.DeepEqual(t, buildDiagnostics(response), expected)
})

t.Run("respects runExternalCode disabled by the orchestrator", func(t *testing.T) {
t.Parallel()
session := newContentMapperBuildSession(t, true)
response := buildWithOrchestrator(t, session, &core.CompilerOptions{RunExternalCode: core.TSFalse})
assert.Assert(t, hasBuildDiagnostic(response, 18068))
})

t.Run("does not inherit runExternalCode from an untrusted session", func(t *testing.T) {
t.Parallel()
session := newContentMapperBuildSession(t, false)
response := buildWithOrchestrator(t, session, nil)
assert.Assert(t, hasBuildDiagnostic(response, 18068))
})

t.Run("does not spawn mappers for an untrusted session", func(t *testing.T) {
t.Parallel()
session := newContentMapperBuildSession(t, false)
response := buildWithOrchestrator(t, session, &core.CompilerOptions{RunExternalCode: core.TSTrue})
assert.DeepEqual(t, buildDiagnostics(response), []buildDiagnostic{{Code: 18099, Messages: []string{
"The content mapper 'mapper' could not be initialized.",
"The content mapper command 'supplemental-mapper' could not be started: the API session does not allow running external code",
}}})
})
}

func hasBuildDiagnostic(response *BuildResponse, code int32) bool {
for _, diagnostic := range response.Diagnostics {
if diagnostic.Code == code {
return true
}
}
return false
}
13 changes: 13 additions & 0 deletions tsc/internal/project/snapshothost.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type SnapshotHost struct {
extendedConfigCache *ExtendedConfigCache
programCounter *programCounter
contentMapperHost contentmapper.Host
contentMapperSpawner contentmapper.Spawner

snapshotID atomic.Uint64
}
Expand Down Expand Up @@ -93,6 +94,7 @@ func NewSnapshotHost(init *SessionInit) *SnapshotHost {
extendedConfigCache: NewExtendedConfigCache(),
programCounter: &programCounter{},
contentMapperHost: newContentMapperHost(init),
contentMapperSpawner: init.Spawner,
}
}

Expand Down Expand Up @@ -193,6 +195,17 @@ func (s *SnapshotHost) DefaultLibraryPath() tspath.RootedDirectoryPath {
return s.options.DefaultLibraryPath
}

// RunExternalCode reports whether configured content mappers may run their (external) processes.
func (s *SnapshotHost) RunExternalCode() bool {
return s.options.RunExternalCode
}

// ContentMapperSpawner returns the spawner that launches content mapper processes, or nil when the host
// cannot spawn processes. Callers must check RunExternalCode before spawning.
func (s *SnapshotHost) ContentMapperSpawner() contentmapper.Spawner {
return s.contentMapperSpawner
}

func (s *SnapshotHost) Close() {
if s.contentMapperHost != nil {
_ = s.contentMapperHost.Close()
Expand Down
Loading