diff --git a/tsc/internal/api/requestfilesystem/filechanges.go b/tsc/internal/api/requestfilesystem/filechanges.go index 28568887648ba..03c21d2b6a0e1 100644 --- a/tsc/internal/api/requestfilesystem/filechanges.go +++ b/tsc/internal/api/requestfilesystem/filechanges.go @@ -27,6 +27,7 @@ func (s *requestFileSystem) ExpandFileChanges(summary project.FileChangeSummary) expand(&summary.Changed) expand(&summary.Created) expand(&summary.Deleted) + expand(&summary.DiskChanged) return summary } diff --git a/tsc/internal/api/requestfilesystem/requestfilesystem_test.go b/tsc/internal/api/requestfilesystem/requestfilesystem_test.go index 3dff635480b56..dee1fd941c34e 100644 --- a/tsc/internal/api/requestfilesystem/requestfilesystem_test.go +++ b/tsc/internal/api/requestfilesystem/requestfilesystem_test.go @@ -45,6 +45,27 @@ func newLayeredRequestFileSystem(params *RequestFileSystem, base vfs.FS, current return fileSystem.(*requestFileSystem), nil } +func TestRequestFileSystemExpandDiskChangedAliases(t *testing.T) { + t.Parallel() + fileSystem, err := newRequestFileSystem(&RequestFileSystem{ + Kind: KindFull, + Files: map[string]string{ + "/packages/pkg/package.json": `{"name":"pkg"}`, + }, + Symlinks: map[string]RequestSymlink{ + "/project/node_modules/pkg": {Target: "../../../packages/pkg"}, + }, + }, vfstest.FromMap(map[string]string{}, tspath.CaseSensitive), "/") + assert.NilError(t, err) + + var change project.FileChangeSummary + change.DiskChanged.Add("file:///packages/pkg/package.json") + expanded := fileSystem.ExpandFileChanges(change) + + assert.Assert(t, expanded.DiskChanged.Has("file:///packages/pkg/package.json")) + assert.Assert(t, expanded.DiskChanged.Has("file:///project/node_modules/pkg/package.json")) +} + func verifyCompactionWithoutHostReads(t *testing.T, layer *requestFileSystem, host *trackingvfs.FS, paths []string) { t.Helper() compacted, err := newRequestFileSystem(&RequestFileSystem{Kind: KindLayer}, layer, layer.currentDirectory.AsString()) diff --git a/tsc/internal/project/contentmapper_test.go b/tsc/internal/project/contentmapper_test.go index a524edfe723f9..5a352f1719d16 100644 --- a/tsc/internal/project/contentmapper_test.go +++ b/tsc/internal/project/contentmapper_test.go @@ -909,6 +909,165 @@ func TestDynamicContentMapperInProject(t *testing.T) { assert.Assert(t, !mappedFile.IsContentMapperFailureStub()) } +func TestDynamicContentMapperRefreshesForSavedOverlay(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + save bool + watch bool + editAfterSave bool + openAfterWatch bool + closeAfterSave bool + }{ + {name: "save", save: true}, + {name: "watch", watch: true}, + {name: "save and watch", save: true, watch: true}, + {name: "save then edit", save: true, editAfterSave: true}, + {name: "watch then open", watch: true, openAfterWatch: true}, + {name: "save then close", save: true, closeAfterSave: true}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + files := map[string]any{ + "/home/project/tsconfig.json": `{ "contentMappers": [{ "package": "mapper", "extensions": [".box"] }] }`, + "/home/project/node_modules/mapper/package.json": contentmappertest.PackageJSON(contentmappertest.DynamicVerbatimMapper), + "/home/project/mapper.config.json": `{ "version": 1 }`, + "/home/project/app.box": "export const value = 1;\n", + "/home/project/main.ts": `import { value } from "./app.box"; value;`, + } + init, utils := projecttestutil.GetSessionInitOptions(files, &project.SessionOptions{ + CurrentDirectory: "/home/project", + DefaultLibraryPath: bundled.LibPath(), + TypingsLocation: projecttestutil.TestTypingsLocation, + PositionEncoding: lsproto.PositionEncodingKindUTF8, + RunExternalCode: true, + }, nil) + lifecycle := &contentmappertest.ProjectLifecycle{} + init.Spawner = contentmappertest.NewSpawnerWithProjectLifecycle(lifecycle) + session := project.NewSession(init) + defer session.Close() + + ctx := context.Background() + mainURI := lsproto.DocumentUri("file:///home/project/main.ts") + configURI := lsproto.DocumentUri("file:///home/project/mapper.config.json") + session.DidOpenFile(ctx, mainURI, 1, files["/home/project/main.ts"].(string), lsproto.LanguageKindTypeScript) + if !test.openAfterWatch { + session.DidOpenFile(ctx, configURI, 1, files["/home/project/mapper.config.json"].(string), lsproto.LanguageKindJSON) + } + languageService, err := session.GetLanguageService(ctx, mainURI) + assert.NilError(t, err) + opens := lifecycle.Opens.Load() + closes := lifecycle.Closes.Load() + assert.Assert(t, opens > 0) + + const savedContent = `{ "version": 2 }` + if !test.openAfterWatch { + session.DidChangeFile(ctx, configURI, 2, []lsproto.TextDocumentContentChangePartialOrWholeDocument{{ + WholeDocument: &lsproto.TextDocumentContentChangeWholeDocument{Text: savedContent}, + }}) + // Flush the edit before saving; the mapper cannot observe unsaved overlay content. + languageService, err = session.GetLanguageService(ctx, mainURI) + assert.NilError(t, err) + } + assert.Equal(t, lifecycle.Opens.Load(), opens) + assert.Equal(t, lifecycle.Closes.Load(), closes) + program := languageService.GetProgram() + + assert.NilError(t, utils.FS().WriteFile(configURI.FileName(), savedContent)) + if test.save { + session.DidSaveFile(ctx, configURI) + } + if test.watch { + session.DidChangeWatchedFiles(ctx, []*lsproto.FileEvent{{Uri: configURI, Type: lsproto.FileChangeTypeChanged}}) + } + if test.editAfterSave { + session.DidChangeFile(ctx, configURI, 3, []lsproto.TextDocumentContentChangePartialOrWholeDocument{{ + WholeDocument: &lsproto.TextDocumentContentChangeWholeDocument{Text: `{ "version": 3 }`}, + }}) + } + if test.openAfterWatch { + session.DidOpenFile(ctx, configURI, 1, savedContent, lsproto.LanguageKindJSON) + } + if test.closeAfterSave { + session.DidCloseFile(ctx, configURI) + } + session.WaitForBackgroundTasks() + languageService, err = session.GetLanguageService(ctx, mainURI) + assert.NilError(t, err) + assert.Equal(t, lifecycle.Closes.Load(), closes+1) + assert.Equal(t, lifecycle.Opens.Load(), opens+1) + assert.Assert(t, languageService.GetProgram() != program) + + session.DidSaveFile(ctx, mainURI) + session.DidChangeWatchedFiles(ctx, []*lsproto.FileEvent{{Uri: mainURI, Type: lsproto.FileChangeTypeChanged}}) + session.WaitForBackgroundTasks() + _, err = session.GetLanguageService(ctx, mainURI) + assert.NilError(t, err) + assert.Equal(t, lifecycle.Opens.Load(), opens+1) + }) + } +} + +func TestDynamicContentMapperRefreshesForWatchedOverlayAlias(t *testing.T) { + t.Parallel() + const projectDirectory = "/home/project/node_modules/pkg" + const configContent = `{ "version": 1 }` + const mainContent = `import { value } from "./app.box"; value;` + files := map[string]any{ + projectDirectory: vfstest.Symlink("/packages/pkg"), + "/home/project/node_modules/mapper/package.json": contentmappertest.PackageJSON(contentmappertest.DynamicVerbatimMapper), + "/packages/pkg/tsconfig.json": `{ "compilerOptions": { "resolveJsonModule": true }, "files": ["main.ts", "mapper.config.json"], "contentMappers": [{ "package": "mapper", "extensions": [".box"] }] }`, + "/packages/pkg/mapper.config.json": configContent, + "/packages/pkg/app.box": "export const value = 1;\n", + "/packages/pkg/main.ts": mainContent, + } + init, utils := projecttestutil.GetSessionInitOptions(files, &project.SessionOptions{ + CurrentDirectory: projectDirectory, + DefaultLibraryPath: bundled.LibPath(), + PositionEncoding: lsproto.PositionEncodingKindUTF8, + RunExternalCode: true, + }, nil) + lifecycle := &contentmappertest.ProjectLifecycle{} + init.Spawner = contentmappertest.NewSpawnerWithProjectLifecycle(lifecycle) + session := project.NewSession(init) + defer session.Close() + + ctx := t.Context() + mainURI := lsproto.DocumentUri("file://" + projectDirectory + "/main.ts") + configURI := lsproto.DocumentUri("file://" + projectDirectory + "/mapper.config.json") + session.DidOpenFile(ctx, mainURI, 1, mainContent, lsproto.LanguageKindTypeScript) + _, err := session.GetLanguageService(ctx, mainURI) + assert.NilError(t, err) + session.DidOpenFile(ctx, configURI, 1, configContent, lsproto.LanguageKindJSON) + _, err = session.GetLanguageService(ctx, mainURI) + assert.NilError(t, err) + opens := lifecycle.Opens.Load() + closes := lifecycle.Closes.Load() + assert.Assert(t, opens > 0) + + session.DidChangeFile(ctx, configURI, 2, []lsproto.TextDocumentContentChangePartialOrWholeDocument{{ + WholeDocument: &lsproto.TextDocumentContentChangeWholeDocument{Text: `{ "version": 3 }`}, + }}) + _, err = session.GetLanguageService(ctx, mainURI) + assert.NilError(t, err) + assert.Equal(t, lifecycle.Opens.Load(), opens) + assert.Equal(t, lifecycle.Closes.Load(), closes) + + assert.NilError(t, utils.FS().WriteFile("/packages/pkg/mapper.config.json", `{ "version": 2 }`)) + session.DidChangeWatchedFiles(ctx, []*lsproto.FileEvent{{ + Uri: "file:///packages/pkg/mapper.config.json", + Type: lsproto.FileChangeTypeChanged, + }}) + session.WaitForBackgroundTasks() + _, err = session.GetLanguageService(ctx, mainURI) + assert.NilError(t, err) + assert.Equal(t, lifecycle.Opens.Load(), opens+1) + assert.Equal(t, lifecycle.Closes.Load(), closes+1) + content, ok := session.Snapshot().ReadFile(configURI.FileName()) + assert.Assert(t, ok) + assert.Equal(t, content, `{ "version": 3 }`) +} + func TestDynamicContentMapperRefreshesForMixedWatchBatches(t *testing.T) { t.Parallel() for _, test := range []struct { diff --git a/tsc/internal/project/filechange.go b/tsc/internal/project/filechange.go index 251b63fcf335d..341fdbf9539dd 100644 --- a/tsc/internal/project/filechange.go +++ b/tsc/internal/project/filechange.go @@ -48,6 +48,9 @@ type FileChangeSummary struct { // Only set when file watching is enabled Deleted collections.Set[lsproto.DocumentUri] + // DiskChanged records disk changes, including those hidden by overlays, for consumers that read directly from disk. + DiskChanged collections.Set[lsproto.DocumentUri] + // IncludesWatchChangeOutsideNodeModules is true if the summary includes a create, change, or delete watch // event of a file outside a node_modules directory. IncludesWatchChangeOutsideNodeModules bool @@ -60,11 +63,12 @@ func (f FileChangeSummary) Clone() FileChangeSummary { f.Changed = *f.Changed.Clone() f.Created = *f.Created.Clone() f.Deleted = *f.Deleted.Clone() + f.DiskChanged = *f.DiskChanged.Clone() return f } func (f FileChangeSummary) IsEmpty() bool { - return !f.InvalidateAll && f.Opened == "" && f.Reopened == "" && f.Closed.Len() == 0 && f.Changed.Len() == 0 && f.Created.Len() == 0 && f.Deleted.Len() == 0 + return !f.InvalidateAll && f.Opened == "" && f.Reopened == "" && f.Closed.Len() == 0 && f.Changed.Len() == 0 && f.Created.Len() == 0 && f.Deleted.Len() == 0 && f.DiskChanged.Len() == 0 } func (f FileChangeSummary) HasExcessiveWatchEvents() bool { @@ -92,6 +96,9 @@ func mergeFileChangeSummary(dst *FileChangeSummary, src FileChangeSummary) { for uri := range src.Deleted.Keys() { dst.Deleted.Add(uri) } + for uri := range src.DiskChanged.Keys() { + dst.DiskChanged.Add(uri) + } if src.IncludesWatchChangeOutsideNodeModules { dst.IncludesWatchChangeOutsideNodeModules = true } diff --git a/tsc/internal/project/overlayfs.go b/tsc/internal/project/overlayfs.go index 291dd211c8382..e11d058fc5318 100644 --- a/tsc/internal/project/overlayfs.go +++ b/tsc/internal/project/overlayfs.go @@ -425,6 +425,7 @@ func (fs *overlayFS) processChanges(changes []FileChange) (FileChangeSummary, ma watchChanged bool changes []*FileChange saved bool + saveObserved bool created bool deleted bool watchObserved bool @@ -474,6 +475,7 @@ func (fs *overlayFS) processChanges(changes []FileChange) (FileChangeSummary, ma events.watchChanged = false case FileChangeKindSave: events.saved = true + events.saveObserved = true case FileChangeKindWatchCreate: if events.deleted { // Delete followed by create becomes a change @@ -504,6 +506,10 @@ func (fs *overlayFS) processChanges(changes []FileChange) (FileChangeSummary, ma path := uri.PathKey(fs.caseSensitivity) o := newOverlays[path] + if events.saveObserved || events.watchChanged || (o != nil || events.openChange != nil) && events.watchObserved { + result.DiskChanged.Add(uri) + } + if events.openChange != nil { if result.Opened != "" || result.Reopened != "" { panic("can only process one file open event at a time") @@ -564,7 +570,7 @@ func (fs *overlayFS) processChanges(changes []FileChange) (FileChangeSummary, ma } } - if o != nil && (events.watchObserved || events.saved) { + if o != nil && (events.watchObserved || events.saveObserved) { if matchesDiskText, _ := o.computeMatchesDiskText(fs.host); matchesDiskText != o.MatchesDiskText() { o = newOverlay(o.FileName(), o.Content(), o.Version(), o.kind) o.matchesDiskText = matchesDiskText diff --git a/tsc/internal/project/overlayfs_test.go b/tsc/internal/project/overlayfs_test.go index 26f1bcff3f339..8cbe0622fc6a3 100644 --- a/tsc/internal/project/overlayfs_test.go +++ b/tsc/internal/project/overlayfs_test.go @@ -129,6 +129,7 @@ func TestProcessChanges(t *testing.T) { assert.Assert(t, result.Changed.Has(testURI1)) assert.Equal(t, result.Changed.Len(), 1) + assert.Assert(t, result.DiskChanged.Has(testURI1)) }) t.Run("save marks overlay as matching disk", func(t *testing.T) { @@ -153,9 +154,9 @@ func TestProcessChanges(t *testing.T) { URI: testURI1, }, }) - // We don't observe saves for snapshot changes, - // so they're not included in the summary - assert.Assert(t, result.IsEmpty()) + assert.Equal(t, result.Changed.Len(), 0) + assert.Assert(t, result.DiskChanged.Has(testURI1)) + assert.Assert(t, !result.IsEmpty()) // Check that the overlay is marked as matching disk text fh := fs.GetFile(testURI1.FileName()) @@ -163,6 +164,77 @@ func TestProcessChanges(t *testing.T) { assert.Assert(t, fh.MatchesDiskText()) }) + t.Run("save followed by edit records disk change", func(t *testing.T) { + t.Parallel() + fs := createOverlayFS() + const savedContent = "const x = 1;" + fs.processChanges([]FileChange{ + { + Kind: FileChangeKindOpen, + URI: testURI1, + Version: 1, + Content: savedContent, + LanguageKind: lsproto.LanguageKindTypeScript, + }, + }) + assert.NilError(t, fs.host.WriteFile(testURI1.FileName(), savedContent)) + + result, _ := fs.processChanges([]FileChange{ + {Kind: FileChangeKindSave, URI: testURI1}, + { + Kind: FileChangeKindChange, + URI: testURI1, + Version: 2, + Changes: []lsproto.TextDocumentContentChangePartialOrWholeDocument{{ + WholeDocument: &lsproto.TextDocumentContentChangeWholeDocument{Text: "const x = 2;"}, + }}, + }, + }) + + assert.Assert(t, result.DiskChanged.Has(testURI1)) + assert.Assert(t, !fs.GetFile(testURI1.FileName()).MatchesDiskText()) + }) + + for _, test := range []struct { + name string + diskChange FileChangeKind + transition FileChangeKind + }{ + {name: "watch then open", diskChange: FileChangeKindWatchChange, transition: FileChangeKindOpen}, + {name: "save then reopen", diskChange: FileChangeKindSave, transition: FileChangeKindOpen}, + {name: "save then close", diskChange: FileChangeKindSave, transition: FileChangeKindClose}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + fs := createOverlayFS() + const savedContent = "const x = 1;" + if test.diskChange == FileChangeKindSave { + fs.processChanges([]FileChange{{ + Kind: FileChangeKindOpen, + URI: testURI1, + Version: 1, + Content: savedContent, + LanguageKind: lsproto.LanguageKindTypeScript, + }}) + } + assert.NilError(t, fs.host.WriteFile(testURI1.FileName(), savedContent)) + + result, _ := fs.processChanges([]FileChange{ + {Kind: test.diskChange, URI: testURI1}, + { + Kind: test.transition, + URI: testURI1, + Version: 2, + Content: savedContent, + LanguageKind: lsproto.LanguageKindTypeScript, + }, + }) + + assert.Assert(t, result.DiskChanged.Has(testURI1)) + assert.Equal(t, result.Changed.Len(), 0) + }) + } + t.Run("open falls back to file extension for unknown language kind", func(t *testing.T) { t.Parallel() fs := createOverlayFS() @@ -240,12 +312,14 @@ func TestProcessChanges(t *testing.T) { // Now process a watch change assert.NilError(t, fs.host.WriteFile(testURI1.FileName(), "const x = 2;")) - fs.processChanges([]FileChange{ + result, _ := fs.processChanges([]FileChange{ { Kind: FileChangeKindWatchChange, URI: testURI1, }, }) + assert.Equal(t, result.Changed.Len(), 0) + assert.Assert(t, result.DiskChanged.Has(testURI1)) assert.Assert(t, !fs.GetFile(testURI1.FileName()).MatchesDiskText()) }) diff --git a/tsc/internal/project/projectcollectionbuilder.go b/tsc/internal/project/projectcollectionbuilder.go index 2520db25c7b87..5a28556508973 100644 --- a/tsc/internal/project/projectcollectionbuilder.go +++ b/tsc/internal/project/projectcollectionbuilder.go @@ -415,9 +415,19 @@ func (b *ProjectCollectionBuilder) DidChangeFiles(summary FileChangeSummary, log deletedFiles := toPaths(summary.Deleted) createdFiles := toPaths(summary.Created) if b.contentMapperHost != nil { - allWatchChanges := slices.Concat(changedFiles, deletedFiles, createdFiles) + // Mapper processes read from disk, so overlay-only changes cannot affect their configuration. + allWatchChanges := toPaths(summary.DiskChanged) + for uri := range summary.Changed.Keys() { + path := uri.PathKey(b.base.caseSensitivity) + if _, hasOverlay := b.overlays[path]; !hasOverlay && !summary.DiskChanged.Has(uri) { + allWatchChanges = append(allWatchChanges, path) + } + } + allWatchChanges = append(allWatchChanges, deletedFiles...) + refreshAll := summary.InvalidateAll || len(allWatchChanges) > excessiveChangeThreshold + allWatchChanges = append(allWatchChanges, createdFiles...) b.forEachProject(func(entry dirty.Value[*Project]) bool { - b.refreshContentMapperProjectForChanges(entry, allWatchChanges, summary.HasExcessiveNonCreateWatchEvents(), logger) + b.refreshContentMapperProjectForChanges(entry, allWatchChanges, refreshAll, logger) return true }) } diff --git a/tsc/internal/project/snapshotfs.go b/tsc/internal/project/snapshotfs.go index 0331f96d90331..6553749c905a0 100644 --- a/tsc/internal/project/snapshotfs.go +++ b/tsc/internal/project/snapshotfs.go @@ -613,7 +613,7 @@ func (s *snapshotFSBuilder) reloadEntryIfContentChanged(entry *dirty.SyncMapEntr return changed } -// expandRealpathAliases adds synthetic URIs to the Changed, Created, and Deleted sets for +// expandRealpathAliases adds synthetic URIs to the Changed, Created, Deleted, and DiskChanged sets for // files that were accessed through node_modules symlinks. When a watch event arrives // using a realpath, this expands it to include the symlink-based path so that // downstream consumers (markDirtyFiles, markFilesChanged) can find cached entries. @@ -643,6 +643,7 @@ func (s *SnapshotFS) expandRealpathAliases(change FileChangeSummary) FileChangeS expandSet(&change.Changed) expandSet(&change.Created) expandSet(&change.Deleted) + expandSet(&change.DiskChanged) if change.Created.Len() > 0 { createdDirectories := collections.NewSetWithSizeHint[tspath.PathKey](change.Created.Len()) diff --git a/tsc/internal/project/snapshotfs_test.go b/tsc/internal/project/snapshotfs_test.go index 0910c865f13bd..e6fd1c67d2f03 100644 --- a/tsc/internal/project/snapshotfs_test.go +++ b/tsc/internal/project/snapshotfs_test.go @@ -1183,12 +1183,15 @@ func TestRealpathAliasLifecycle(t *testing.T) { // Simulate a watch event on the REALPATH. change := FileChangeSummary{} change.Changed.Add("file:///packages/mylib/package.json") + change.DiskChanged.Add("file:///packages/mylib/package.json") expanded := snapshot.expandRealpathAliases(change) // Should now also contain the symlink path. assert.Assert(t, expanded.Changed.Has("file:///packages/mylib/package.json"), "original event should remain") assert.Assert(t, expanded.Changed.Has("file:///project/node_modules/mylib/package.json"), "symlink event should be added") + assert.Assert(t, expanded.DiskChanged.Has("file:///packages/mylib/package.json"), "original disk event should remain") + assert.Assert(t, expanded.DiskChanged.Has("file:///project/node_modules/mylib/package.json"), "symlink disk event should be added") }) t.Run("expandRealpathAliases expands delete events", func(t *testing.T) {