Skip to content
This repository was archived by the owner on Sep 1, 2026. It is now read-only.
Closed
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
3 changes: 2 additions & 1 deletion cmd/tsgo/lsp.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/microsoft/typescript-go/internal/lsp"
"github.com/microsoft/typescript-go/internal/pprof"
"github.com/microsoft/typescript-go/internal/vfs/osvfs"
"github.com/microsoft/typescript-go/internal/vfs/zipoverlay"
)

func runLSP(args []string) int {
Expand All @@ -40,7 +41,7 @@ func runLSP(args []string) int {
defer profileSession.Stop()
}

fs := bundled.WrapFS(osvfs.FS())
fs := bundled.WrapFS(zipoverlay.Wrap(osvfs.FS()))
defaultLibraryPath := bundled.LibPath()
typingsLocation := osvfs.GetGlobalTypingsCacheLocation()

Expand Down
3 changes: 2 additions & 1 deletion cmd/tsgo/sys.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/microsoft/typescript-go/internal/tspath"
"github.com/microsoft/typescript-go/internal/vfs"
"github.com/microsoft/typescript-go/internal/vfs/osvfs"
"github.com/microsoft/typescript-go/internal/vfs/zipoverlay"
"golang.org/x/term"
)

Expand Down Expand Up @@ -68,7 +69,7 @@ func newSystem() *osSys {

return &osSys{
cwd: tspath.NormalizePath(cwd),
fs: bundled.WrapFS(osvfs.FS()),
fs: bundled.WrapFS(zipoverlay.Wrap(osvfs.FS())),
defaultLibraryPath: bundled.LibPath(),
writer: os.Stdout,
start: time.Now(),
Expand Down
3 changes: 2 additions & 1 deletion internal/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/microsoft/typescript-go/internal/lsp/lsproto"
"github.com/microsoft/typescript-go/internal/project"
"github.com/microsoft/typescript-go/internal/vfs/osvfs"
"github.com/microsoft/typescript-go/internal/vfs/zipoverlay"
)

// StdioServerOptions configures the STDIO-based API server.
Expand Down Expand Up @@ -69,7 +70,7 @@ func (s *StdioServer) Run(ctx context.Context) error {
transport = t
}

fs := bundled.WrapFS(osvfs.FS())
fs := bundled.WrapFS(zipoverlay.Wrap(osvfs.FS()))

// Wrap the base FS with callbackFS if callbacks are requested
var callbackFS *callbackFS
Expand Down
115 changes: 115 additions & 0 deletions internal/module/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/diagnostics"
"github.com/microsoft/typescript-go/internal/packagejson"
"github.com/microsoft/typescript-go/internal/pnp"
"github.com/microsoft/typescript-go/internal/stringutil"
"github.com/microsoft/typescript-go/internal/tspath"
"github.com/microsoft/typescript-go/internal/vfs/vfsmatch"
Expand Down Expand Up @@ -159,6 +160,31 @@ type Resolver struct {
typingsLocation string
projectName string
// reportDiagnostic: DiagnosticReporter

pnpOnce sync.Once
pnpManifest *pnp.Manifest
}

// getPnpManifest discovers and loads the Yarn PnP manifest governing this
// program, once. It returns nil when the project is not a PnP project. Discovery
// walks up from the tsconfig directory (or the current directory) for a
// .pnp.data.json / .pnp.cjs sidecar.
func (r *Resolver) getPnpManifest() *pnp.Manifest {
r.pnpOnce.Do(func() {
fs := r.host.FS()
startDir := r.host.GetCurrentDirectory()
if r.compilerOptions.ConfigFilePath != "" {
startDir = tspath.GetDirectoryPath(r.compilerOptions.ConfigFilePath)
}
manifestPath := pnp.Find(startDir, fs.FileExists)
if manifestPath == "" {
return
}
if m, ok := pnp.Load(manifestPath, fs.ReadFile); ok {
r.pnpManifest = m
}
})
return r.pnpManifest
}

type ResolverOptions struct {
Expand Down Expand Up @@ -979,6 +1005,26 @@ func (r *resolutionState) getOutputDirectoriesForBaseDirectory(commonSourceDirGu
}

func (r *resolutionState) loadModuleFromNearestNodeModulesDirectory(typesScopeOnly bool) *resolved {
// Under Yarn PnP there is no node_modules tree; the manifest maps a package
// to its on-disk location. PnP governs package resolution for any importer it
// owns; when it doesn't own the importer (an ignored path) it reports
// "not governed" and the classic walk below runs.
if manifest := r.resolver.getPnpManifest(); manifest != nil {
result, governed := r.loadModuleFromPnp(manifest, typesScopeOnly)
if !result.shouldContinueSearching() {
return result
}
if governed {
// PnP owns this importer but the specifier is not resolvable through the
// manifest (undeclared dependency, unfulfilled peer, or a declared
// package whose file is missing). Do NOT fall through to the classic
// ancestor node_modules walk — that would resolve a phantom dependency
// from a stray node_modules the manifest does not sanction. Report "not
// found" so the caller still consults typeRoots but skips the walk.
return continueSearching()
}
}

mode := core.ResolutionModeCommonJS
if r.esmMode || r.conditionMatches("import") {
mode = core.ResolutionModeESM
Expand Down Expand Up @@ -1010,6 +1056,66 @@ func (r *resolutionState) loadModuleFromNearestNodeModulesDirectory(typesScopeOn
return continueSearching()
}

// loadModuleFromPnp resolves r.name through the Yarn PnP manifest, mirroring the
// classic walk's shape: preferred (TS/DTS) extensions on the implementation
// package first, then a DTS lookup in the matching @types package, then fallback
// (JS/JSON) extensions on the implementation. It returns a hit (governed true),
// or continueSearching() together with whether PnP governs the importer:
// governed is false only when the importer is outside PnP's control (an ignored
// path), in which case the caller runs the classic walk; when governed is true
// but nothing resolved, the caller must not run the classic walk.
func (r *resolutionState) loadModuleFromPnp(manifest *pnp.Manifest, typesScopeOnly bool) (*resolved, bool) {
tryLoad := func(ext extensions, res pnp.Result) *resolved {
if res.Status != pnp.Success {
return continueSearching()
}
rest := strings.TrimPrefix(res.Subpath, "/")
candidate := res.PackageDir
if rest != "" {
candidate = tspath.RemoveTrailingDirectorySeparator(tspath.NormalizePath(tspath.CombinePaths(res.PackageDir, rest)))
}
return r.loadModuleFromResolvedPackageDirectory(ext, candidate, rest, res.PackageDir)
}

priorityExtensions := r.extensions & (extensionsTypeScript | extensionsDeclaration)
secondaryExtensions := r.extensions & ^(extensionsTypeScript | extensionsDeclaration)

implResult := manifest.Resolve(r.name, r.containingDirectory)
// An ignored importer (not owned by PnP) short-circuits to the classic walk.
if implResult.Status == pnp.Skipped {
return continueSearching(), false
}

// (1) preferred extensions in the implementation package
if priorityExtensions != 0 && !typesScopeOnly {
if result := tryLoad(priorityExtensions, implResult); !result.shouldContinueSearching() {
return result, true
}
}

// (1ii) DTS in the @types package
if r.extensions&extensionsDeclaration != 0 {
packageName, subpath := ParsePackageName(r.name)
typesSpecifier := GetTypesPackageName(packageName)
if subpath != "" {
typesSpecifier += "/" + subpath
}
typesResult := manifest.Resolve(typesSpecifier, r.containingDirectory)
if result := tryLoad(extensionsDeclaration, typesResult); !result.shouldContinueSearching() {
return result, true
}
}

// (2) fallback extensions in the implementation package
if secondaryExtensions != 0 && !typesScopeOnly {
if result := tryLoad(secondaryExtensions, implResult); !result.shouldContinueSearching() {
return result, true
}
}

return continueSearching(), true
}

func (r *resolutionState) loadModuleFromNearestNodeModulesDirectoryWorker(ext extensions, mode core.ResolutionMode, typesScopeOnly bool) *resolved {
result, _ := tspath.ForEachAncestorDirectory(
r.containingDirectory,
Expand Down Expand Up @@ -1069,7 +1175,16 @@ func (r *resolutionState) loadModuleFromSpecificNodeModulesDirectory(ext extensi
if packageName == "" {
packageDirectory = candidate
}
return r.loadModuleFromResolvedPackageDirectory(ext, candidate, rest, packageDirectory)
}

// loadModuleFromResolvedPackageDirectory performs file / directory / exports /
// typesVersions resolution once the package's on-disk directory is known. It is
// shared by the classic node_modules walk (which derives packageDirectory from a
// node_modules folder) and Yarn PnP (which gets packageDirectory from the PnP
// manifest). candidate is packageDirectory joined with rest (the subpath within
// the package, "" for a bare package specifier).
func (r *resolutionState) loadModuleFromResolvedPackageDirectory(ext extensions, candidate string, rest string, packageDirectory string) *resolved {
if r.resolvePackageDirectoryOnly {
if r.resolver.host.FS().DirectoryExists(packageDirectory) {
return &resolved{path: packageDirectory}
Expand Down
168 changes: 168 additions & 0 deletions internal/pnp/edgecases_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
package pnp

import (
"strings"
"testing"
)

// A manifest exercising the top-level fallback: enableTopLevelFallback is on, the
// top-level package declares "shared", and app-b is on the fallbackExclusionList.
// app-a (not excluded) can reach "shared" through the fallback even though it does
// not declare it; app-b (excluded) cannot.
const fallbackManifest = `{
"dependencyTreeRoots": [{"name": "root", "reference": "workspace:."}],
"enableTopLevelFallback": true,
"fallbackExclusionList": [["app-b", ["workspace:packages/app-b"]]],
"fallbackPool": [["pooled", "npm:9.0.0"]],
"packageRegistryData": [
[null, [[null, {
"packageLocation": "./",
"packageDependencies": [
["app-a", "workspace:packages/app-a"],
["app-b", "workspace:packages/app-b"],
["shared", "npm:1.0.0"]
],
"linkType": "SOFT"
}]]],
["app-a", [["workspace:packages/app-a", {
"packageLocation": "./packages/app-a/",
"packageDependencies": [["app-a", "workspace:packages/app-a"]],
"linkType": "SOFT"
}]]],
["app-b", [["workspace:packages/app-b", {
"packageLocation": "./packages/app-b/",
"packageDependencies": [["app-b", "workspace:packages/app-b"]],
"linkType": "SOFT"
}]]],
["shared", [["npm:1.0.0", {
"packageLocation": "./.yarn/cache/shared-npm-1.0.0-abc.zip/node_modules/shared/",
"packageDependencies": [["shared", "npm:1.0.0"]],
"linkType": "HARD"
}]]],
["pooled", [["npm:9.0.0", {
"packageLocation": "./.yarn/cache/pooled-npm-9.0.0-def.zip/node_modules/pooled/",
"packageDependencies": [["pooled", "npm:9.0.0"]],
"linkType": "HARD"
}]]]
]
}`

func loadFallback(t *testing.T) *Manifest {
t.Helper()
const manifestPath = "/proj/.pnp.data.json"
m, ok := Load(manifestPath, func(p string) (string, bool) {
if p == manifestPath {
return fallbackManifest, true
}
return "", false
})
if !ok {
t.Fatal("failed to load fallback manifest")
}
return m
}

func TestResolveTopLevelFallback(t *testing.T) {
t.Parallel()
m := loadFallback(t)
// app-a does not declare "shared", but the top-level package does and app-a is
// not on the exclusion list: the fallback resolves it.
if r := m.Resolve("shared", "/proj/packages/app-a"); r.Status != Success ||
!strings.Contains(r.PackageDir, "shared-npm-1.0.0-abc.zip") {
t.Fatalf("app-a fallback to shared: status %d dir %q", r.Status, r.PackageDir)
}
// The fallback pool (distinct from the top-level deps) also satisfies an
// undeclared specifier.
if r := m.Resolve("pooled", "/proj/packages/app-a"); r.Status != Success ||
!strings.Contains(r.PackageDir, "pooled-npm-9.0.0-def.zip") {
t.Fatalf("app-a fallback to pooled: status %d dir %q", r.Status, r.PackageDir)
}
}

func TestResolveFallbackExclusion(t *testing.T) {
t.Parallel()
m := loadFallback(t)
// app-b IS on the fallbackExclusionList, so the top-level fallback does not
// apply: an undeclared specifier is NotFound, not silently resolved.
if r := m.Resolve("shared", "/proj/packages/app-b"); r.Status != NotFound {
t.Fatalf("app-b (excluded) resolving shared: status %d, want NotFound", r.Status)
}
}

func TestResolveTopLevelDoesNotFallBack(t *testing.T) {
t.Parallel()
m := loadFallback(t)
// The synthetic top-level (root) locator never uses fallbacks — it is the
// fallback source. "pooled" lives only in the fallback pool, so a non-root
// package reaches it but the root does not (an undeclared specifier from the
// root is NotFound, matching Yarn's `issuerLocator.name !== null` guard).
if r := m.Resolve("pooled", "/proj/packages/app-a"); r.Status != Success {
t.Fatalf("app-a resolving pooled: status %d, want Success", r.Status)
}
if r := m.Resolve("pooled", "/proj"); r.Status != NotFound {
t.Fatalf("root resolving pooled via pool: status %d, want NotFound (root must not fall back)", r.Status)
}
}

func TestResolveBareIdentifierParse(t *testing.T) {
t.Parallel()
m := loadFixture(t)
cases := []struct {
specifier string
wantFail bool
}{
{"@scope", true}, // scoped name with no second segment is invalid
{"@scope/pkg/sub", false}, // scoped name + subpath parses (then resolves/NotFound)
{"pkg/sub/deep", false}, // unscoped name + multi-segment subpath parses
}
for _, c := range cases {
r := m.Resolve(c.specifier, "/proj/packages/util")
if c.wantFail && r.Status != Failed {
t.Errorf("Resolve(%q) status = %d, want Failed", c.specifier, r.Status)
}
if !c.wantFail && r.Status == Failed {
t.Errorf("Resolve(%q) status = Failed, want a parse success", c.specifier)
}
}
}

func TestResolveCarriesScopedSubpath(t *testing.T) {
t.Parallel()
m := loadFixture(t)
// The subpath after a scoped package name is carried through unresolved-file
// resolution as the Subpath (here the package @t/util resolves and "/deep/x"
// rides along).
r := m.Resolve("@t/util/deep/x", "/proj")
if r.Status != Success || r.Subpath != "/deep/x" {
t.Fatalf("@t/util/deep/x: status %d subpath %q", r.Status, r.Subpath)
}
}

func TestLoadRejectsMalformed(t *testing.T) {
t.Parallel()
read := func(contents string) func(string) (string, bool) {
return func(p string) (string, bool) {
if p == "/proj/.pnp.data.json" || p == "/proj/.pnp.cjs" {
return contents, true
}
return "", false
}
}
// Malformed JSON sidecar.
if _, ok := Load("/proj/.pnp.data.json", read(`{not json`)); ok {
t.Error("Load accepted malformed JSON")
}
// A .pnp.cjs with no RAW_RUNTIME_STATE marker.
if _, ok := Load("/proj/.pnp.cjs", read("module.exports = {};\n")); ok {
t.Error("Load accepted a .cjs with no manifest marker")
}
// The marker present but NOT an assignment (e.g. only the JSON.parse use):
// requiring "=" keeps a stray textual mention from being mis-extracted.
if _, ok := Load("/proj/.pnp.cjs", read("hydrate(JSON.parse(RAW_RUNTIME_STATE));\n")); ok {
t.Error("Load accepted a RAW_RUNTIME_STATE use with no assignment")
}
// A missing file.
if _, ok := Load("/proj/.pnp.data.json", func(string) (string, bool) { return "", false }); ok {
t.Error("Load accepted a missing manifest file")
}
}
26 changes: 26 additions & 0 deletions internal/pnp/find.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package pnp

import (
"github.com/microsoft/typescript-go/internal/tspath"
)

// Manifest filenames, in the discovery order Yarn and esbuild use. Yarn writes
// .pnp.cjs always; .pnp.data.json additionally when pnpEnableInlining is false.
var manifestNames = []string{".pnp.data.json", ".pnp.cjs", ".pnp.js"}

// Find walks up from startDir (an absolute, normalized directory) looking for a
// PnP manifest, and returns the absolute path of the manifest file to load
// (preferring a .pnp.data.json sidecar, else the .pnp.cjs the data is inlined
// into), or "" if there is no PnP manifest above startDir.
func Find(startDir string, fileExists func(string) bool) string {
manifest, _ := tspath.ForEachAncestorDirectory(tspath.NormalizePath(startDir), func(dir string) (string, bool) {
for _, name := range manifestNames {
candidate := tspath.CombinePaths(dir, name)
if fileExists(candidate) {
return candidate, true
}
}
return "", false
})
return manifest
}
Loading