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
9 changes: 9 additions & 0 deletions packages/typescript/src/api/async/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1885,6 +1885,15 @@ export class Program<Id extends ProjectId = ProjectId> implements FormatDiagnost
return result ?? undefined;
}

async getAllDependencies(file: DocumentIdentifier): Promise<readonly RootedFilePath[]> {
const data = await this.client.apiRequest("getAllDependencies", {
snapshot: this.snapshotId,
project: this.project.handle,
file,
});
return data ?? [];
}

async getSourceFileNames(): Promise<readonly RootedFilePath[]> {
const data = await this.client.apiRequest("getSourceFileNames", {
snapshot: this.snapshotId,
Expand Down
3 changes: 3 additions & 0 deletions packages/typescript/src/api/proto.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export interface APIMethodInfo {
getResolvedModuleFromModuleSpecifier: APIMethod<GetResolvedModuleFromModuleSpecifierParams, ResolvedModule | null>;
getResolvedTypeReferenceDirective: APIMethod<GetResolvedTypeReferenceDirectiveParams, ResolvedTypeReferenceDirective | null>;
getResolvedTypeReferenceDirectiveFromTypeReferenceDirective: APIMethod<GetResolvedTypeReferenceDirectiveFromReferenceParams, ResolvedTypeReferenceDirective | null>;
getAllDependencies: APIMethod<GetSourceFileParams, RootedFilePath[]>;
getConfigFileNames: APIMethod<GetProjectDiagnosticsParams, RootedFilePath[] | null>;
getConfigSourceFile: APIMethod<GetSourceFileParams, SourceFileResponse | null>;
resolveName: APIMethod<ResolveNameParams, SymbolResponse | null>;
Expand Down Expand Up @@ -1167,6 +1168,7 @@ export interface BatchRequest {
| "getAliasSymbolOfType"
| "getAliasTypeArgumentsOfType"
| "getAliasedSymbol"
| "getAllDependencies"
| "getAnyType"
| "getApparentPropertiesOfType"
| "getApparentType"
Expand Down Expand Up @@ -1349,6 +1351,7 @@ export interface BatchResponse {
| "getAliasSymbolOfType"
| "getAliasTypeArgumentsOfType"
| "getAliasedSymbol"
| "getAllDependencies"
| "getAnyType"
| "getApparentPropertiesOfType"
| "getApparentType"
Expand Down
27 changes: 27 additions & 0 deletions packages/typescript/src/api/sync/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3264,6 +3264,33 @@ export class Program<Id extends ProjectId = ProjectId> implements FormatDiagnost
);
}

get getAllDependencies(): {
(file: DocumentIdentifier): readonly RootedFilePath[];
gen(file: DocumentIdentifier): Generator<ProtocolRequest, readonly RootedFilePath[], ProtocolResponse["result"]>;
} {
const owner = this;
return cacheGeneratorMethod(
owner,
"getAllDependencies",
function (file: DocumentIdentifier): readonly RootedFilePath[] {
const data = owner.client.apiRequest("getAllDependencies", {
snapshot: owner.snapshotId,
project: owner.project.handle,
file,
});
return data ?? [];
},
function* (file: DocumentIdentifier): Generator<ProtocolRequest, readonly RootedFilePath[], ProtocolResponse["result"]> {
const data = yield* apiRequest("getAllDependencies", {
snapshot: owner.snapshotId,
project: owner.project.handle,
file,
});
return data ?? [];
},
);
}

get getSourceFileNames(): {
(): readonly RootedFilePath[];
gen(): Generator<ProtocolRequest, readonly RootedFilePath[], ProtocolResponse["result"]>;
Expand Down
42 changes: 42 additions & 0 deletions packages/typescript/test/async/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1322,6 +1322,48 @@ declare module "augmentation" {}`,
await program.dispose();
});

test("Program getAllDependencies", async () => {
await using api = spawnAPI({
"/src/index.ts": `/// <reference types="pkg-types" />
import { a } from "./a";
export const value = a;`,
"/src/a.ts": `import type { Shared } from "./shared";
export const a: Shared["a"] = 1;`,
"/src/shared.ts": `export interface Shared { a: number; }`,
"/src/augment.ts": `export {};
declare module "./shared" { interface Shared { b: string; } }`,
"/src/unrelated.ts": `export const unrelated = 1;`,
"/src/script.ts": `const scriptValue = 1;`,
"/node_modules/@types/pkg-types/package.json": JSON.stringify({ name: "@types/pkg-types", version: "1.0.0", types: "index.d.ts" }),
"/node_modules/@types/pkg-types/index.d.ts": `export {};`,
});

const program = await api.createProgram(
["/src/index.ts", "/src/augment.ts", "/src/unrelated.ts", "/src/script.ts"],
{ module: ModuleKind.ESNext, moduleResolution: ModuleResolutionKind.Bundler, noLib: true, types: [] },
);

assert.deepEqual(await program.getAllDependencies("/src/index.ts"), [
"/src/index.ts",
"/node_modules/@types/pkg-types/index.d.ts",
"/src/shared.ts",
"/src/a.ts",
"/src/augment.ts",
]);
assert.deepEqual(await program.getAllDependencies("/src/augment.ts"), ["/src/augment.ts", "/src/shared.ts"]);
assert.deepEqual(await program.getAllDependencies("/src/unrelated.ts"), ["/src/unrelated.ts"]);

const sourceFileNames = await program.getSourceFileNames();
assert.deepEqual(await program.getAllDependencies("/src/script.ts"), [
"/src/script.ts",
...sourceFileNames.filter(fileName => fileName !== "/src/script.ts"),
]);

await assert.rejects(program.getAllDependencies("/src/missing.ts"), /source file not found/); // @sync: assert.throws(() => program.getAllDependencies("/src/missing.ts"), /source file not found/);

await program.dispose();
});

test("createProgram resolves raw compiler option paths", async () => {
await using api = spawnAPI({
"/src/index.ts": `import { value } from "ba"; export { value };`,
Expand Down
1 change: 1 addition & 0 deletions packages/typescript/test/sync/api-generators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1613,6 +1613,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () =>
parityCase("Program", "getResolvedModuleFromModuleSpecifier", program.getResolvedModuleFromModuleSpecifier, assertDeepEquivalent, importSpecifier),
parityCase("Program", "getResolvedTypeReferenceDirective", program.getResolvedTypeReferenceDirective, assertDeepEquivalent, "/src/index.ts", "parity", ModuleKind.CommonJS),
parityCase("Program", "getResolvedTypeReferenceDirectiveFromTypeReferenceDirective", program.getResolvedTypeReferenceDirectiveFromTypeReferenceDirective, assertDeepEquivalent, typeReferenceDirective, "/src/index.ts"),
parityCase("Program", "getAllDependencies", program.getAllDependencies, assertDeepEquivalent, "/src/index.ts"),
parityCase("Program", "getSourceFileByPath", program.getSourceFileByPath, assertOptionalSourceFilesEquivalent, indexFile.path),
parityCase("Program", "getSourceFileNames", program.getSourceFileNames, assertDeepEquivalent),
parityCase("Program", "getSourceFileMetadata", program.getSourceFileMetadata, assertDeepEquivalent, "/src/index.ts"),
Expand Down
42 changes: 42 additions & 0 deletions packages/typescript/test/sync/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1309,6 +1309,48 @@ declare module "augmentation" {}`,
program.dispose();
});

test("Program getAllDependencies", () => {
using api = spawnAPI({
"/src/index.ts": `/// <reference types="pkg-types" />
import { a } from "./a";
export const value = a;`,
"/src/a.ts": `import type { Shared } from "./shared";
export const a: Shared["a"] = 1;`,
"/src/shared.ts": `export interface Shared { a: number; }`,
"/src/augment.ts": `export {};
declare module "./shared" { interface Shared { b: string; } }`,
"/src/unrelated.ts": `export const unrelated = 1;`,
"/src/script.ts": `const scriptValue = 1;`,
"/node_modules/@types/pkg-types/package.json": JSON.stringify({ name: "@types/pkg-types", version: "1.0.0", types: "index.d.ts" }),
"/node_modules/@types/pkg-types/index.d.ts": `export {};`,
});

const program = api.createProgram(
["/src/index.ts", "/src/augment.ts", "/src/unrelated.ts", "/src/script.ts"],
{ module: ModuleKind.ESNext, moduleResolution: ModuleResolutionKind.Bundler, noLib: true, types: [] },
);

assert.deepEqual(program.getAllDependencies("/src/index.ts"), [
"/src/index.ts",
"/node_modules/@types/pkg-types/index.d.ts",
"/src/shared.ts",
"/src/a.ts",
"/src/augment.ts",
]);
assert.deepEqual(program.getAllDependencies("/src/augment.ts"), ["/src/augment.ts", "/src/shared.ts"]);
assert.deepEqual(program.getAllDependencies("/src/unrelated.ts"), ["/src/unrelated.ts"]);

const sourceFileNames = program.getSourceFileNames();
assert.deepEqual(program.getAllDependencies("/src/script.ts"), [
"/src/script.ts",
...sourceFileNames.filter(fileName => fileName !== "/src/script.ts"),
]);

assert.throws(() => program.getAllDependencies("/src/missing.ts"), /source file not found/);

program.dispose();
});

test("createProgram resolves raw compiler option paths", () => {
using api = spawnAPI({
"/src/index.ts": `import { value } from "ba"; export { value };`,
Expand Down
2 changes: 2 additions & 0 deletions tsc/internal/api/proto.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ const (
MethodGetResolvedModuleFromModuleSpecifier Method = "getResolvedModuleFromModuleSpecifier"
MethodGetResolvedTypeReferenceDirective Method = "getResolvedTypeReferenceDirective"
MethodGetResolvedTypeReferenceDirectiveFromReference Method = "getResolvedTypeReferenceDirectiveFromTypeReferenceDirective"
MethodGetAllDependencies Method = "getAllDependencies"
MethodGetConfigFileNames Method = "getConfigFileNames"
MethodGetConfigSourceFile Method = "getConfigSourceFile"
MethodResolveName Method = "resolveName"
Expand Down Expand Up @@ -633,6 +634,7 @@ var unmarshalers = map[Method]func([]byte) (any, error){
MethodGetResolvedModuleFromModuleSpecifier: unmarshallerFor[GetResolvedModuleFromModuleSpecifierParams],
MethodGetResolvedTypeReferenceDirective: unmarshallerFor[GetResolvedTypeReferenceDirectiveParams],
MethodGetResolvedTypeReferenceDirectiveFromReference: unmarshallerFor[GetResolvedTypeReferenceDirectiveFromReferenceParams],
MethodGetAllDependencies: unmarshallerFor[GetSourceFileParams],
MethodGetConfigFileNames: unmarshallerFor[GetProjectDiagnosticsParams],
MethodGetConfigSourceFile: unmarshallerFor[GetSourceFileParams],
MethodGetSymbolAtPosition: unmarshallerFor[GetSymbolAtPositionParams],
Expand Down
21 changes: 21 additions & 0 deletions tsc/internal/api/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
compilerdebug "github.com/microsoft/TypeScript/tsc/internal/debug"
"github.com/microsoft/TypeScript/tsc/internal/diagnostics"
"github.com/microsoft/TypeScript/tsc/internal/execute/build"
"github.com/microsoft/TypeScript/tsc/internal/execute/incremental"
"github.com/microsoft/TypeScript/tsc/internal/execute/tsc"
"github.com/microsoft/TypeScript/tsc/internal/format"
"github.com/microsoft/TypeScript/tsc/internal/ipc"
Expand Down Expand Up @@ -965,6 +966,8 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json.
return s.handleGetResolvedTypeReferenceDirective(ctx, parsed.(*GetResolvedTypeReferenceDirectiveParams))
case string(MethodGetResolvedTypeReferenceDirectiveFromReference):
return s.handleGetResolvedTypeReferenceDirectiveFromReference(ctx, parsed.(*GetResolvedTypeReferenceDirectiveFromReferenceParams))
case string(MethodGetAllDependencies):
return s.handleGetAllDependencies(ctx, parsed.(*GetSourceFileParams))
case string(MethodGetConfigFileNames):
return s.handleGetConfigFileNames(ctx, parsed.(*GetProjectDiagnosticsParams))
case string(MethodGetConfigSourceFile):
Expand Down Expand Up @@ -2666,6 +2669,24 @@ func (s *Session) handleGetResolvedTypeReferenceDirectiveFromReference(ctx conte
return newResolvedTypeReferenceDirectiveResponse(program.GetResolvedTypeReferenceDirective(sourceFile, params.TypeDirectiveName, mode)), nil
}

func (s *Session) handleGetAllDependencies(ctx context.Context, params *GetSourceFileParams) ([]tspath.RootedFilePath, error) {
sd, err := s.getSnapshotData(params.Snapshot)
if err != nil {
return nil, err
}
program, err := sd.getProgram(params.Project)
if err != nil {
return nil, err
}
sourceFile, err := s.resolveOptionalSourceFile(program, &params.File)
if err != nil {
return nil, err
}
ch, done := program.GetTypeCheckerForFile(ctx, sourceFile)
defer done()
return core.Map(incremental.GetAllDependencies(program, ch, sourceFile), (*ast.SourceFile).FileName), nil
}

// handleGetSymbolAtPosition returns the symbol at a position in a file.
// @gen-proto-nullable
func (s *Session) handleGetSymbolAtPosition(ctx context.Context, params *GetSymbolAtPositionParams) (*SymbolResponse, error) {
Expand Down
83 changes: 83 additions & 0 deletions tsc/internal/api/session_dependencies_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package api

import (
"context"
"errors"
"fmt"
"testing"

"github.com/microsoft/TypeScript/tsc/internal/testutil/projecttestutil"
"github.com/microsoft/TypeScript/tsc/internal/tspath"
"gotest.tools/v3/assert"
)

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

tests := []struct {
name string
disableSourceRedirect bool
expected []tspath.RootedFilePath
}{
{
name: "uses sources of project references",
expected: []tspath.RootedFilePath{"/home/projects/app/src/index.ts", "/home/projects/shared/src/util.ts"},
},
{
name: "uses outputs of project references",
disableSourceRedirect: true,
expected: []tspath.RootedFilePath{"/home/projects/app/src/index.ts", "/home/projects/shared/dist/util.d.ts"},
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()

const configFileName = "/home/projects/app/tsconfig.json"
projectSession, _ := projecttestutil.Setup(map[string]any{
"/home/projects/shared/tsconfig.json": `{ "compilerOptions": { "composite": true, "noLib": true, "rootDir": "src", "outDir": "dist" }, "include": ["src"] }`,
"/home/projects/shared/src/util.ts": `export const util = 1;`,
"/home/projects/shared/dist/util.d.ts": `export declare const util = 1;`,
configFileName: fmt.Sprintf(
`{ "compilerOptions": { "noLib": true, "disableSourceOfProjectReferenceRedirect": %t }, "references": [{ "path": "../shared" }], "include": ["src"] }`,
test.disableSourceRedirect,
),
"/home/projects/app/src/index.ts": `import { util } from "../../shared/src/util"; export const value = util;`,
"/home/projects/app/src/unrelated.ts": `export const unrelated = 1;`,
})
defer projectSession.Close()
session := NewLSPSession(projectSession, nil)
defer session.Close()

snapshot, err := session.handleCreateSnapshot(context.Background(), &CreateSnapshotParams{
OpenProjects: []DocumentIdentifier{{FileName: configFileName}},
})
assert.NilError(t, err)
projectHandle := snapshot.Projects[0].Handle

dependencies, err := session.handleGetAllDependencies(context.Background(), &GetSourceFileParams{
Snapshot: snapshot.Snapshot,
Project: projectHandle,
File: DocumentIdentifier{FileName: "/home/projects/app/src/index.ts"},
})
assert.NilError(t, err)
assert.DeepEqual(t, dependencies, test.expected)

dependencies, err = session.handleGetAllDependencies(context.Background(), &GetSourceFileParams{
Snapshot: snapshot.Snapshot,
Project: projectHandle,
File: DocumentIdentifier{FileName: "/home/projects/app/src/unrelated.ts"},
})
assert.NilError(t, err)
assert.DeepEqual(t, dependencies, []tspath.RootedFilePath{"/home/projects/app/src/unrelated.ts"})

_, err = session.handleGetAllDependencies(context.Background(), &GetSourceFileParams{
Snapshot: snapshot.Snapshot,
Project: projectHandle,
File: DocumentIdentifier{FileName: "/home/projects/app/src/missing.ts"},
})
assert.Assert(t, errors.Is(err, ErrClientError))
})
}
}
42 changes: 42 additions & 0 deletions tsc/internal/execute/incremental/dependencies.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package incremental

import (
"github.com/microsoft/TypeScript/tsc/internal/ast"
"github.com/microsoft/TypeScript/tsc/internal/checker"
"github.com/microsoft/TypeScript/tsc/internal/collections"
"github.com/microsoft/TypeScript/tsc/internal/compiler"
"github.com/microsoft/TypeScript/tsc/internal/core"
"github.com/microsoft/TypeScript/tsc/internal/tspath"
)

func GetAllDependencies(program *compiler.Program, checker *checker.Checker, file *ast.SourceFile) []*ast.SourceFile {
files := program.GetSourceFiles()
if !fileAffectsGlobalScope(file) {
seen := collections.Set[tspath.PathKey]{}
queue := []tspath.PathKey{file.PathKey()}
for len(queue) > 0 {
path := queue[len(queue)-1]
queue = queue[:len(queue)-1]
current := program.GetSourceFileByPath(path)
if current == nil || !seen.AddIfAbsent(current.PathKey()) {
continue
}
if references := getReferencedFilesWithChecker(program, checker, current); references != nil {
for reference := range references.Keys() {
queue = append(queue, reference)
}
}
}
files = core.Filter(files, func(f *ast.SourceFile) bool {
return seen.Has(f.PathKey())
})
}
dependencies := make([]*ast.SourceFile, 0, len(files))
dependencies = append(dependencies, file)
for _, f := range files {
if f != file {
dependencies = append(dependencies, f)
}
}
return dependencies
}
Loading