Repository navigation
Replace api.updateSnapshot - #64204
Andrew Branch (andrewbranch) merged 30 commits into
Conversation
…hange, with RemoveProgram counterpart
…pshot() and getCurrentLanguageServerSnapshot()
There was a problem hiding this comment.
🟡 Changes recommended
Snapshot refresh and repeated-open handling contain correctness issues, and removePrograms exposes an overly broad project-ID type.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Replaces latest-snapshot state with explicit snapshot creation and derivation, adding synthetic-program lifecycle support and branded project IDs.
Changes:
- Adds
createSnapshot,Snapshot.update, and LSP snapshot retrieval. - Supports creating, removing, and ensuring synthetic programs.
- Updates protocols, generators, caches, and tests for the new model.
File summaries
| File | Description |
|---|---|
tsc/internal/project/snapshothost.go |
Adds independent root snapshots. |
tsc/internal/project/snapshot.go |
Adds synthetic-program operations. |
tsc/internal/project/snapshot_test.go |
Tests synthetic lifecycle. |
tsc/internal/project/session.go |
Passes clients explicitly during cloning. |
tsc/internal/project/refcountcache_test.go |
Updates cache tests for synthetic programs. |
tsc/internal/project/projectcollectionbuilder.go |
Manages synthetic projects and program updates. |
tsc/internal/project/projectcollection.go |
Integrates synthetic projects into lookups. |
tsc/internal/project/project.go |
Defines synthetic projects and IDs. |
tsc/internal/project/project_stringer_generated.go |
Adds generated synthetic-kind text. |
tsc/internal/api/session.go |
Implements the redesigned snapshot API. |
tsc/internal/api/session_temporary_test.go |
Tests explicit-base updates. |
tsc/internal/api/session_createprogram_test.go |
Tests snapshot-created programs. |
tsc/internal/api/session_completion_test.go |
Migrates completion setup. |
tsc/internal/api/session_apistate_test.go |
Tests LSP snapshot state and ownership. |
tsc/internal/api/proto.go |
Defines new protocol methods and types. |
tsc/internal/api/proto_test.go |
Tests ensurePrograms decoding. |
tools/gen-proto/main.go |
Generates branded IDs and embedded interfaces. |
tools/gen-proto/main_test.go |
Verifies generated protocol output. |
packages/typescript/test/sync/astnav.test.ts |
Migrates synchronous AST navigation tests. |
packages/typescript/test/sync/ast.test.ts |
Migrates synchronous AST tests. |
packages/typescript/test/sync/api.bench.ts |
Migrates synchronous benchmarks. |
packages/typescript/test/sync/api-generators.test.ts |
Updates generator parity coverage. |
packages/typescript/test/diagnosticFormatter.test.ts |
Migrates diagnostic tests. |
packages/typescript/test/async/astnav.test.ts |
Migrates asynchronous AST navigation tests. |
packages/typescript/test/async/api.bench.ts |
Migrates asynchronous benchmarks. |
packages/typescript/src/api/sync/api.ts |
Exposes the synchronous snapshot model. |
packages/typescript/src/api/sourceFileCache.ts |
Supports branded project IDs in caching. |
packages/typescript/src/api/proto.ts |
Adds snapshot request compatibility conversion. |
packages/typescript/src/api/proto.generated.ts |
Updates generated wire declarations. |
packages/typescript/src/api/async/api.ts |
Exposes the asynchronous snapshot model. |
Review details
Files not reviewed (1)
- tsc/internal/project/project_stringer_generated.go: Generated file
- Files reviewed: 29/32 changed files
- Comments generated: 3
- Review effort level: Balanced
💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.
ea254df to
8399b74
Compare
|
I have a refactor on top of this to use strongly typed project IDs that are not just |
There was a problem hiding this comment.
🟡 Changes recommended
LSP reconciliation can mishandle close-and-reopen requests, and solution-wide operations may consume stale synthetic programs.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Files not reviewed (1)
- tsc/internal/project/project_stringer_generated.go: Generated file
Suppressed comments (1)
tsc/internal/api/session.go:1245
- The same pre-request filtering breaks close-and-reopen for files: when a currently owned file appears in both lists,
OpenFilesis removed here andCloseFilesis retained below, leaving the file closed. Independent snapshot reconciliation processes closes before opens, so the two APIs now produce different final states for the same change set. Compute both deltas from a temporary open-file state so the reopen wins.
for uri := range apiRequest.OpenFiles.Keys() {
path := s.toPath(uri.FileName())
if s.openFiles.Has(path) {
apiRequest.OpenFiles.Delete(uri)
} else {
- Files reviewed: 31/34 changed files
- Comments generated: 2
- Review effort level: Balanced
There was a problem hiding this comment.
🟡 Changes recommended
Malformed or unknown program identifiers can currently cause incorrect success, unintended removal, or a server panic.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Files not reviewed (1)
- tsc/internal/project/project_stringer_generated.go: Generated file
Suppressed comments (1)
Previously missed (1) — in code that hasn't changed since the last review.
tsc/internal/project/projectcollectionbuilder.go:310
- Unknown project IDs are silently ignored because
DidRequestProjectreturns without indicating whether it found anything. Consequently,ensureProgramscan report success even though the requested program is absent (for example, when an ID from an unrelated snapshot is supplied). Validate every requested ID against this snapshot and return a client error when one is missing.
- Files reviewed: 33/36 changed files
- Comments generated: 2
- Review effort level: Balanced
Wesley Wigham (weswigham)
left a comment
There was a problem hiding this comment.
I think it looks good, but if you'd like, I think we could use more dedicated test coverage of forking snapshots. I only saw, like, one assertion that file contents didn't leak between siblings reading through the test changes - but there's a lot more potential shared state between sibling snapshots than just file contents. There's obviously nothing in the typesystem ensuring that we're only sharing data by-copy on snapshot update and not by-ref, after all, and by-ref was sufficient for sequential, single snapshots. In particular, I don't see any changes to Snapshot.Clone, which implies it was already totally multi-snapshot-safe, which is great if true, but we're not really testing it rigorously. Auto-imports caches, config file caches, and probably more all look probably immutable/independent, but we're not really exercising them via tests.
|
That's never a bad thing to have more of, and while there could always be some corner where there is a bug, I think we do have a decent amount of pre-existing coverage of that because we actually have had the possibility of sibling snapshots for a long time, just not ones that an API consumer could get their hands on, and not siblings that were themselves cloned. Both auto-imports snapshots and the previous dedicated “temporary file update” snapshots were forking the main line, with auto-imports having the possibility of being adopted back into the main line if it never actually had a sibling. But those, along with routine parallel processing of LSP requests, means we have spent a while hardening the snapshot's immutability guarantee by tracking down panics from editor telemetry. |
|
Hey Andrew Branch (@andrewbranch)! I migrated ts-loader's branch for the new API to these changes in this commit: TypeStrong/ts-loader@339d06d It went pretty well - though it looks like there might be a regression. I enclose a report written with the help of Claude. Hopefully it makes sense. Changes madeAll changes are in
Verification
The one remaining failure:
|
John Reilly (@johnnyreilly), according to Copilot, this is happening because ts-loader is using the filename |
|
I think the answer is partly but not entirely. With a little bit of help from Claude I've made some changes which you can see in TypeStrong/ts-loader@693fd7c - here's a write up which is hopefully readable enough: (incidentally I'm not sure all of the changes in my last commit will be required when your changes land?) Issue 1 (the one you diagnosed) — confirmed, and it was a bug on our side. As you guessed, we were aliasing Issue 2 — a second, distinct repro of the same panic, Windows-only, and it corrects something in my earlier report. Once issue 1 was fixed, we still hit "no project found for opened file" on Windows for a different scenario: our older This is the part that corrects my original report: I'd claimed the panic was specific to We worked around it on our end by catching that failure and retrying without |
|
Hm, I've investigated, but I can't reproduce that. Can you get Claude to generate a contained repro, or even repro instructions tied to a specific commit of your PR? |
|
Yup will do - I wonder if you haven't been able to repro because it only surfaced on Windows during my testing? Claude has reproduced - I'll get it to drop a comment below. See failure on Windows: https://github.com/TypeStrong/ts-loader/actions/runs/35692331446/job/106631768957 |
|
Got it — put together a minimal, ts-loader/webpack-free repro. It only reproduces on Windows, which is presumably why you couldn't hit it locally. Repro instructions (tied to a specific commit):
Or standalone, no checkout needed — just // repro.js
const path = require('path');
const { API } = require('typescript/unstable/sync');
const projectDir = __dirname; // needs a tsconfig.json here, e.g. { "compilerOptions": { "module": "commonjs" } }
const tsconfigPath = path.join(projectDir, 'tsconfig.json');
// Never written to real disk - served only via the fs overrides below, and
// not listed by the tsconfig, so it isn't part of that project's file list.
const virtualFileName = path.join(projectDir, 'virtual.ts');
const virtualFiles = new Map([[virtualFileName, 'export const hello = "world";\n']]);
const api = new API({
fs: {
fileExists: fileName => (virtualFiles.has(fileName) ? true : undefined),
readFile: fileName => virtualFiles.get(fileName),
},
});
// The very first createSnapshot() call for this API instance, opening a
// project and a file not in that project in the same request.
const snapshot = api.createSnapshot({
openProjects: [tsconfigPath],
openFiles: [virtualFileName],
});
console.log('No panic:', !!snapshot);On Windows this throws: On macOS it prints Confirmed via GitHub Actions ( |
|
John Reilly (@johnnyreilly) hmmm, I think I may have inadvertently fixed you with #64391. I think the issue was your drive letter getting accidentally lowercased by us during |
|
Oh nice! I'll try and test with the latest nightly today and report back |
|
Your diagnosis is correct - I see |
…jects Per microsoft/TypeScript#64204 (comment) and microsoft/TypeScript#64204 (comment), the "no project found for opened file" failure traces back to a Windows drive-letter casing mismatch. ts-loader was itself contributing to that: `openProjects` always carried `configFilePath`'s resolvedFilePathCache'd (lowercased) form, but `openFiles` and `fileNotifications.changed`/`deleted` used `fileName`'s natural, unmodified casing - so a single snapshot request could mix a lowercase-drive-letter project path with a differently-cased file path. Canonicalizes every file name sent to the API the same way project paths already are, at the single point (`updateSnapshot`) where the wire params are built - doesn't touch how `apiFileName` is used anywhere else (getSourceFile, getConfiguredProject, dependency tracking, etc.), keeping this a narrow, wire-boundary-only change. The existing catch-and-retry workaround for this same failure shape stays in place as a safety net regardless of how much this narrows the problem. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…jects Per microsoft/TypeScript#64204 (comment) and microsoft/TypeScript#64204 (comment), the "no project found for opened file" failure traces back to a Windows drive-letter casing mismatch. ts-loader was itself contributing to that: `openProjects` always carried `configFilePath`'s resolvedFilePathCache'd (lowercased) form, but `openFiles` and `fileNotifications.changed`/`deleted` used `fileName`'s natural, unmodified casing - so a single snapshot request could mix a lowercase-drive-letter project path with a differently-cased file path. Canonicalizes every file name sent to the API the same way project paths already are, at the single point (`updateSnapshot`) where the wire params are built - doesn't touch how `apiFileName` is used anywhere else (getSourceFile, getConfiguredProject, dependency tracking, etc.), keeping this a narrow, wire-boundary-only change. This supersedes (and lets us remove) the earlier catch-and-retry workaround for the same symptom: confirmed via .github/workflows/windows-test-probe.yml that this fix alone (no retry logic) is sufficient - appendSuffixTo and the full 50-suite comparison run both pass on Windows without it. Removed rather than kept as a redundant safety net since it was catching *any* thrown error and retrying, which risked masking a genuinely different failure (e.g. a broken tsconfig) behind a confusing second error. Co-Authored-By: Claude Sonnet 5 <[email protected]>
|
Yeah I've moved ts-loader to using the normalised filenames for Thanks Andrew Branch (@andrewbranch)! |
…jects Upgrades to typescript@next 7.1.0-dev.20260922.1 and fixes the "no project found for opened file" failure that persisted against it on Windows (see microsoft/TypeScript#64204 (comment) onwards). Per microsoft/TypeScript#64204 (comment) and microsoft/TypeScript#64204 (comment), the failure traces back to a Windows drive-letter casing mismatch. ts-loader was itself contributing to that: `openProjects` always carried `configFilePath`'s resolvedFilePathCache'd (lowercased) form, but `openFiles` and `fileNotifications.changed`/`deleted` used `fileName`'s natural, unmodified casing - so a single snapshot request could mix a lowercase-drive-letter project path with a differently-cased file path. Canonicalizes every file name sent to the API the same way project paths already are, at the single point (`updateSnapshot`) where the wire params are built - doesn't touch how `apiFileName` is used anywhere else (getSourceFile, getConfiguredProject, dependency tracking, etc.), keeping this a narrow, wire-boundary-only change. Confirmed via .github/workflows/windows-test-probe.yml that this fix alone is sufficient - appendSuffixTo and the full 50-suite comparison run both pass on Windows without any additional workaround. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…jects Upgrades to typescript@next 7.1.0-dev.20260922.1 and fixes the "no project found for opened file" failure that persisted against it on Windows (see microsoft/TypeScript#64204 (comment) onwards). Per microsoft/TypeScript#64204 (comment) and microsoft/TypeScript#64204 (comment), the failure traces back to a Windows drive-letter casing mismatch. ts-loader was itself contributing to that: `openProjects` always carried `configFilePath`'s resolvedFilePathCache'd (lowercased) form, but `openFiles` and `fileNotifications.changed`/`deleted` used `fileName`'s natural, unmodified casing - so a single snapshot request could mix a lowercase-drive-letter project path with a differently-cased file path. Canonicalizes every file name sent to the API the same way project paths already are, at the single point (`updateSnapshot`) where the wire params are built - doesn't touch how `apiFileName` is used anywhere else (getSourceFile, getConfiguredProject, dependency tracking, etc.), keeping this a narrow, wire-boundary-only change. Confirmed via .github/workflows/windows-test-probe.yml that this fix alone is sufficient - appendSuffixTo and the full 50-suite comparison run both pass on Windows without any additional workaround. Co-Authored-By: Claude Sonnet 5 <[email protected]>
* feat: add tsgo transpile path * fix: load tsgo API via ESM import * Restrict execution-test TS matrix to tsgo version * chore: explicitly use [email protected] * Port build to TypeScript 7 native API * fix: large * fix native API execution test defaults * chore: remove test * fix: remove unused * fix: happify ashley * fix: use TS7 API in comparison test harness * fix: getProgram * feat: extra diagnostics * feat: match existing formatting * chore: regenerate yarn.lock * chore: remove happypack * fix: aliasResolution * chore: bump version * fix: colors * fix: webpack 4 * chore: rename * chore: remove unused * fix: rootDir in tests * fix: outputs * fix: declarationOutput * fix: declaration tests * fix: dependency * fix: output * fix: declarationWathc * chore: upgrade prettier * fix: reportFiels * fix: test * fix: onlyCompileBundledFiles * fix: style * fix: otherLoadersWatch * feat: settings.json * fix: output * chore: add setings * fix: resolveJsonModule * fix: tsconfileInvalid * fix: tsconfileInvalidFile * revert last fix * Comment out DIAGNOSTIC_CODE_FILE_NOT_FOUND constant Comment out the DIAGNOSTIC_CODE_FILE_NOT_FOUND constant. * chore: skip test * fix: yarn comparison-tests --single-test nodeModulesMeaningfulErrorWhenImportingTs * fix: output * chore: temp files better * feat: virtual file system * fix: sourceMapsShouldConsiderInputSourceMap * fix: allow spike rm * fix: Windows comparison-test failures in the tsgo API backend program.getSourceFileNames()/getConfigFileNames() and related lookups return the TypeScript API's forward-slash-normalized paths, but several call sites handed those straight to Node's OS-native `path` functions or to webpack's addDependency/addBuildDependency (which reject non-native absolute paths on Windows). This surfaced as a cluster of Windows-only comparison-test failures with no macOS/Linux equivalent: - getDirectResolvedImports/resolveRelativeSpecifier: dependant-recheck lookups failing (dependencyErrors) - findTransitiveDependants: multi-hop BFS matching failing (simpleDependency) - ensureSyntheticConfigForFile: synthetic project config content keyed under the wrong path, degrading emit for any file compiled via the synthetic single-file project fallback (basic, externals) - registerTypeScriptDependencies: two addDependency/addBuildDependency call sites passed a forward-slash path straight to webpack (externals) - createTypeScriptApiInstance: missing fileExists override for purely synthetic identities like component.vue.ts under appendTsSuffixTo (appendSuffixTo) Also: normalizes platform-dependent path depth embedded in TS18003/ TS5055/TS6059 compiler diagnostic messages in the comparison-test harness (same compiler behaviour on both platforms, just displayed relative to a different reference point), adds an on-demand windows-test-probe.yml workflow for fast, targeted Windows CI iteration, and reduces the test retry count. Verified against real Windows CI: all 50 comparison-test suites pass. * docs: edit AGENTS.md / deps for sourceMaps test / time * refactor: remove unverified Windows-fix leftovers proven unnecessary by testing Isolated and reverted each individually against real Windows CI (full suite where the change had broad reach, targeted tests otherwise) - all three passed without the change, confirming they were never load-bearing: - bumpMtimes in the comparison-test harness: added chasing a watchpack mtime-equality theory for dependencyErrors that turned out wrong; the actual fix was in getDirectResolvedImports (already in place). - ensureSyntheticConfigForFile's files-array path normalization: added before the real fix (syntheticConfigContents' store-side key normalization, which remains); the API evidently normalizes each files-array entry internally regardless of separator style. - registerTypeScriptDependencies' getConfigFileNames loop normalization: added speculatively alongside the confirmed addDependency fix in the same edit; never independently exercised by any actual failure. Full local suite (50/50) and full Windows CI suite (50/50) still pass with all three removed. * chore: "target": "es2022" * feat: chalk -> picocolors * feat: picocolors -> styleText * fix: test * fix: eslint -> oxlint * feat: styleText -> picocolors * chore: clean unused * chore: knip / upgrade deps * fix: execution tests * chore: remove experimentalWatchApi references * chore: remove experimentalWatchApi tests * chore: remove reference to watchapi in tests * fix: loader options hash * fix: loader options hash * fix: loader options hash * chore: update to latest nightly * chore: upgrade lint-staged * feat: transpileApi * fix: normalize transpileModule/transpileDeclaration fileName for Windows api.transpileModule/transpileDeclaration build their own virtual filesystem from `fileName` verbatim rather than resolving it through a Project, so an OS-native (backslash) path panics on Windows ("mixed posix and windows paths") and also breaks diagnostic location lookup (the echoed diagnostic.fileName no longer matches the OS-native apiFileName used as the lookup key). Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix: transpileDeclaration panics on Windows given an absolute fileName api.transpileDeclaration builds its own throwaway virtual filesystem from `fileName` verbatim rather than resolving it through a Project, and panics on Windows ("mixed posix and windows paths") given any absolute path there - OS-native or forward-slash-normalized alike. Stripping the OS-native configFilePath from compilerOptions and falling back a rootDir were both tried first and, per the Windows test probe workflow, neither stopped the panic. The actual fix: pass transpileDeclaration a bare basename instead of any absolute path at all. Unlike transpileModule (which needs fileName's real directory for e.g. rootDir-containment diagnostics like TS6059, and keeps its own absolute, forward-slash path), transpileDeclaration doesn't need real directory context - its own diagnostics (isolatedDeclarations violations) are purely syntactic, and any real rootDir violation for the same file is already caught by transpileModule's own call on it. Co-Authored-By: Claude Sonnet 5 <[email protected]> * docs: reduce comment verbosity - needs another pass * chore: remove workarounds no longer required since microsoft/TypeScript#64024 * chore: function expressions to function declarations * feat: knip * refactor: use API-provided startPosition/endPosition instead of a manual location lookup DiagnosticResponse already carries precomputed startPosition/endPosition (zero-based line/character) on every diagnostic - program-based (getSyntacticDiagnostics etc.) and transpileModule/transpileDeclaration alike - present exactly when there's a real position. That makes the manual location-resolution machinery unnecessary: getDiagnosticLocations, the DiagnosticLocationSource interface, makeSingleFileLocationSource, and computeLineAndCharacterFromText all existed solely to reconstruct what the API already returns, via a fileName-keyed lookup that only worked because callers pre-canonicalized fileName to match the API's internal spelling (see microsoft/TypeScript#64090). buildTypeScriptError now reads diagnostic.startPosition/endPosition directly, so no lookup is needed at all. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix: knip / simplify execution tests * fix: tests * fix: dont alias types * chore: trim comments * refactor: simplify logger * refactor: simplify logger * Change ColorFn type to an interface * Fix type annotation in ColorFn interface * chore: onlyCompileBundledFiles/context removed as options * refactor: naming * feat: remove fs-extra * feat: remove rimraf * feat: remove mkdirp * chore: remove compilerOptions loader option The tsgo-backed native API resolves compiler options purely from the on-disk tsconfig.json, with no per-loader-instance override hook, so compilerOptions has been inert since the 10.0.0 rewrite. Remove it as a valid loader option (matching how onlyCompileBundledFiles/context were removed) instead of leaving it silently accepted but ignored. Co-Authored-By: Claude Sonnet 5 <[email protected]> * test: regenerate snapshots affected by compilerOptions harness default removal The comparison-test harness injected compilerOptions: { newLine: 'LF' } into every test's loader options via its own default options object, independent of each fixture's own webpack.config.js. Removing compilerOptions as a valid loader option meant that default had to go too (test/comparison-tests/create-and-execute-test.js), which shifts the computed options-hash for every test that doesn't set an explicit instance name. A number of snapshots embed that hash literally as ts-loader-default_<hash>; regenerate them via --save-output. Verified the full diff contains only options-hash changes, dist/index.js stack-line normalization noise, and the couple-byte bundle size shift from the shortened validateLoaderOptionNames error message - no actual compiled-output changes. Co-Authored-By: Claude Sonnet 5 <[email protected]> * docs: CHANGELOG * fix: resolve .mts/.cts relative imports for dependency tracking relativeSpecifierExtensions (used by resolveRelativeSpecifier to match a relative import specifier against the program's source files for webpack dependency registration and transitive-dependant rechecking) only tried .ts/.tsx/.d.ts/.js/.jsx, unlike the neighbouring toDeclarationFileName which already handles .mts/.cts. A relative import resolving to a .mts/.cts file was silently treated as unresolved, so editing it neither registered a webpack dependency on the importer nor triggered a diagnostics recheck of it. Co-Authored-By: Claude Sonnet 5 <[email protected]> * perf: only force a full snapshot rescan once per build, not per file updateSnapshot passed { invalidateAll: true } unconditionally on every single file compiled, forcing the native API to discard its caches and rescan disk once per file rather than once per build - real watch-mode wiring (a hook tied to webpack's own build/rebuild boundary) didn't exist anywhere in the tsgo rewrite. Add TypeScriptInstance.pendingInvalidation, consumed by the first updateSnapshot call of a build and re-armed via a compiler.hooks.compile tap (fires once per build/watch-rebuild in both webpack 4 and 5), so only that first call forces the rescan; every other file compiled in the same build reuses the snapshot it already refreshed. Co-Authored-By: Claude Sonnet 5 <[email protected]> * perf: memoize direct-import resolution across a build's dependant recheck findTransitiveDependants rebuilt a fresh O(n) Set of every project file's name inside getDirectResolvedImports on every single call, and called it once per project file for every file compiled - roughly O(n^3) for a full build. The currently-compiling file's own imports were also recomputed a second time (once via registerResolvedImportDependencies, again inside the BFS). - comparableSourceFileNames is now built once per file compiled (passed down to callers) instead of once per candidate file inside the BFS. - Each project file's resolved-imports list is memoized in a new TypeScriptInstance.directImportsCache, reused across every file compiled in the same build via getCachedDirectResolvedImports. The currently-compiling file always recomputes fresh (never trusts a stale entry) and writes its result back, so other files' dependant searches - and the file's own subsequent BFS lookup - see it too, incidentally also fixing the double computation. - The cache is cleared whenever pendingInvalidation forces a real rescan (see the prior watch-mode fix), keeping it correct across builds. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix: key directImportsCache by FilePathKey, not raw file name registerResolvedImportDependencies wrote cache entries keyed by apiFileName (OS-native, from webpack), while findTransitiveDependants/getCachedDirectResolvedImports read/wrote entries keyed by program.getSourceFileNames() (forward-slash- normalized). On Windows those are different strings for the same file, so an entry written by one path could never be found by the other - silently defeating the memoization exactly where it mattered (the currently-compiled file's own entry). Key by FilePathKey via each instance's ResolvedPathCache instead, matching how instance.files/pendingDiagnostics/pendingDeclarationFiles already canonicalize path spelling and case-sensitivity. Co-Authored-By: Claude Sonnet 5 <[email protected]> * refactor: naming * perf: memoize the .d.ts dependency scan across a build registerTypeScriptDependencies iterated program.getSourceFileNames() (every file in the program) on every single compiled file just to find .d.ts files to register as dependencies - O(n) per file, O(n^2) over a build, even though that set only changes when the program's file set actually does. Add getProjectDtsFileNames, memoized per project (primary or a synthetic one-off project for an orphan file) in a new TypeScriptInstance.projectDtsFileNamesCache, cleared alongside directImportsCache whenever pendingInvalidation forces a real rescan. Keyed by FilePathKey (via ResolvedPathCache) for consistency with directImportsCache, though project config paths are already stable, single-sourced strings in this codebase. Co-Authored-By: Claude Sonnet 5 <[email protected]> * refactor: names * fix: cap orphan-file synthetic projects with LRU eviction ensureSyntheticConfigForFile created and permanently tracked one synthetic tsconfig + open project per distinct orphan file (e.g. every allowTsInNodeModules file ever compiled), with no eviction - each held its own ref-counted project open on the API side, so a long watch session touching many distinct orphan files leaked memory/state proportional to all of them, unbounded. Cap it at 20 (maxOrphanFileProjects), evicting the least-recently-used entry - tracked via Map insertion order, bumped on reuse - once the cap is hit. The evicted project's closeProjects is threaded through updateSnapshot to actually release its ref-counted open on the API side, and removed from openedProjectPaths so revisiting that file later reopens it fresh rather than treating it as still-open. Verified with a standalone scratch reproduction (22 distinct orphan files under allowTsInNodeModules): exactly 2 evictions occurred against the cap of 20, the build succeeded with no errors, and editing a previously-evicted file was correctly picked up on the next rebuild. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix: canonicalize configFilePath/syntheticConfig* via FilePath Two real bugs, same class as the earlier directImportsCache fix: - syntheticConfigContents's readFile/fileExists lookups used toComparablePath (slash-only normalization), while the sibling files Map right next to it already used resolvedPathCache (slash *and* case normalization) - a case-insensitive-filesystem spelling mismatch would silently miss. - syntheticConfigFiles was keyed by raw fileName. Two importers spelling/casing the same orphan file differently would be treated as distinct files, each spawning its own redundant synthetic project - undermining the LRU cap added previously. configFilePath and openedProjectPaths are converted too for consistency, though their values were already single-sourced and stable in practice. Added TypeScriptInstance.resolvedPathCache so functions that only receive TypeScriptInstance (not the outer TSInstance) - openPrimaryProject, prepareSnapshotForFile, ensureSyntheticConfigForFile, updateSnapshot - can canonicalize a path without threading it through as a separate parameter. Co-Authored-By: Claude Sonnet 5 <[email protected]> * refactor: rename * refactor: names - Use interface instead of type for the plain object shape TypeScriptApiModule, matching AGENTS.md's convention. - Extract reportConfigFileParsingErrors, deduplicating the ~20-line broken-tsconfig error-reporting block shared by getTypeScriptEmit and getTranspileOnlyEmit. Co-Authored-By: Claude Sonnet 5 <[email protected]> * refactor: thread resolvedFilePathCache instead of storing it twice TypeScriptInstance.resolvedFilePathCache duplicated the exact same function reference already stored on the owning TSInstance's own resolvedPathCache field. Drop the stored field; thread it as an explicit parameter through prepareSnapshotForFile/ensureSyntheticConfigForFile instead, sourced from instance.resolvedPathCache at the getTypeScriptEmit call site - matching the convention already used by getProjectDtsFileNames, registerResolvedImportDependencies, getCachedDirectResolvedImports, and findTransitiveDependants. Co-Authored-By: Claude Sonnet 5 <[email protected]> * refactor: rename * feat: split diagnostics * feat: format * fix: benchmark close issue * fix: bound benchmark scenario wall-clock time to fit CI's job timeout The tsgo sync API spawns a native child process per ts-loader instance, making a "cold build" iteration ~10-20x more expensive than the classic API's cheap in-process instantiation; touching a widely-imported (hub) file is similarly ~35x more expensive per incremental rebuild due to per-dependant recheck round trips over the sync RPC channel. The fixed iteration counts (tuned for the classic API's cost profile) made the cold-typeCheck and hub-touch scenarios alone take ~28 minutes combined, blowing the 20-minute CI job timeout before a single scenario finished. Cap each scenario's wall-clock time in run-side.mts instead of guessing a smaller fixed iteration count, so cheap scenarios keep their full sample size while expensive ones stop once they've collected enough measured samples. Confirmed locally: full default run (300 files) went from never finishing to completing in ~4 minutes. * perf: batch transitive-dependant recheck to once per build, not once per file Profiling the benchmark's slowness (tsgo branch showing 10-20x worse numbers than the classic branch, contrary to tsgo's own "faster compiler" characteristic) traced 83-91% of both cold-build and hub-touch-rebuild time to recheckTransitiveDependants: it ran once per file webpack compiled rather than once per build, and each call does a full O(project size) dependant search plus two diagnostic calls per dependant found. For a wide-fanout change (a file most of the project depends on) that's close to O(n²) work in a single build. The raw tsgo API itself opens a 300-file project and double-diagnoses every file in ~25ms - it's not the bottleneck. Batches the recheck into one pass per build instead: getTypeScriptEmit now just records which files it compiled (changedFilesThisBuild), and a new recheckAllTransitiveDependants runs once from the existing postCompile hook, searching dependants of the whole changed-file set in a single pass. Getting this right needed two follow-up fixes surfaced by comparison tests, both around same-build ordering: - A changed file can itself import another changed file compiled later in the same build (e.g. an entry file and the dependency it just changed). Its own diagnostics may have been computed before that other file's compile updated the shared file cache the API's readFile override serves from. findTransitiveDependants no longer excludes changed files from being found as dependants of each other, so this gets caught and rechecked too. - The recheck's own snapshot needs a forced full rescan (pendingInvalidation = true) rather than reusing the arbitrary anchor file's incremental view, otherwise it can still read a stale copy of a same-build sibling. Only costs one extra rescan per build (not per file), so it's affordable now. Measured on a synthetic 300-file fixture: cold build ~9.1s -> ~1.0s, hub-touch incremental rebuild ~4.2s -> ~300-380ms. Full comparison-test suite (including all watch-mode tests) still passes. * chore: newer TypeScript version * feat: perf optimisations * feat: perf tweaks * fix: format * chore: optimisations * fix: improve transpile by applying @andrewbranch's git diff from microsoft/TypeScript#63875 (comment) * fix: typo * feat: have one base snapshot per total webpack build rather than one per file * docs: cleanup unused * feat: migrate to new snapshot API from microsoft/TypeScript#64204 * fix: resolve two Windows/virtual-file panics in the new snapshot API Two related "no project found for opened file" Go-side panics surfaced against a virtual (never-on-disk) identity while migrating to the new snapshot API: 1. `toApiFacingFileName` aliases a file with an unrecognized extension (e.g. a Vue SFC's extracted `<script>` block, `App.vue` -> `App.vue.ts`) for every API-facing call, including `openFiles`. But the `fs.fileExists`/ `readFile` host overrides looked up content keyed only by the real name, never by that alias, so the API's callback for `App.vue.ts` came up empty on both the virtual map and real disk - from the host's perspective the file genuinely didn't exist. Fixed by having those overrides fall back to the pre-alias name (`toRealFacingFileName`) on a miss. 2. Separately, on Windows only, `appendSuffixTo` (the older `appendTsSuffixTo` option) hit the same panic for a different reason: its aliased entry file is the very first file webpack compiles, so the very first `createSnapshot` call has to open the project and that not-yet-a-member file together, in one request - a combination the API panics on regardless of whether create or update does it. Fixed by catching that failure in `updateSnapshot` and retrying without `openFiles`, letting the existing synthetic-config fallback in `prepareSnapshotForFile` take over exactly as it already does for any later never-before-seen file. Verified via `yarn comparison-tests` (50/50, both fixes needed for sourceMapsShouldConsiderInputSourceMap) and via .github/workflows/windows-test-probe.yml (50/50 on Windows, where the second bug only reproduces). Co-Authored-By: Claude Sonnet 5 <[email protected]> * chore: add standalone repro for the "no project found for opened file" panic A minimal, ts-loader/webpack-free repro of the second panic shape described in the PR discussion: a fresh API instance's very first createSnapshot() call opens a project and, in the same request, opens a file that isn't part of that project (real, inferred, or synthetic) - which should fall back to the inferred project per SnapshotRequestChangesParams.openFiles's own doc comment, but instead panics on Windows. Doesn't reproduce on macOS/Linux. Also extends windows-test-probe.yml with a repro_script input so this (or any other standalone script) can be run on the Windows runner on-demand, for verifying platform-specific upstream issues like this one. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix: canonicalize openFiles/fileNotifications casing to match openProjects Upgrades to typescript@next 7.1.0-dev.20260922.1 and fixes the "no project found for opened file" failure that persisted against it on Windows (see microsoft/TypeScript#64204 (comment) onwards). Per microsoft/TypeScript#64204 (comment) and microsoft/TypeScript#64204 (comment), the failure traces back to a Windows drive-letter casing mismatch. ts-loader was itself contributing to that: `openProjects` always carried `configFilePath`'s resolvedFilePathCache'd (lowercased) form, but `openFiles` and `fileNotifications.changed`/`deleted` used `fileName`'s natural, unmodified casing - so a single snapshot request could mix a lowercase-drive-letter project path with a differently-cased file path. Canonicalizes every file name sent to the API the same way project paths already are, at the single point (`updateSnapshot`) where the wire params are built - doesn't touch how `apiFileName` is used anywhere else (getSourceFile, getConfiguredProject, dependency tracking, etc.), keeping this a narrow, wire-boundary-only change. Confirmed via .github/workflows/windows-test-probe.yml that this fix alone is sufficient - appendSuffixTo and the full 50-suite comparison run both pass on Windows without any additional workaround. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix: upgrade typescript nightly and fix fallout on all platforms Bumped the floating `typescript` dependency to a newer nightly (7.1.0-dev.20261002.1), which changed the shape of the new unstable sync API's FileSystemCallbacks (now requires all 8 callbacks instead of just fileExists/readFile, and undefined no longer means "defer to the real filesystem" - that's now the explicit serverFS.useOS sentinel). Updated typeScriptApi.ts's fs override accordingly; everything other than fileExists/readFile now just defers to the OS via serverFS.useOS. That nightly bump also changed the compiler's own declaration-map/ source-map emission for two existing fixtures (declarationOutputWithMaps, tsconfigInvalid) - confirmed via a side-by-side plain `tsc` comparison against both nightlies, not a ts-loader bug - so those fixtures are regenerated to match the new (correct, for this compiler version) output. Also surfaced a third, Windows-only failure in sourceMapsShouldConsiderInputSourceMap. Root-caused via git history (bisecting known-good/known-bad CI runs) plus a timing benchmark of typescript/unstable/sync's out-of-process API on both nightlies/both platforms: vue-loader's webpack5 pitching mechanism re-requests each SFC block through the full loader chain, and which of the resulting "pitching" vs "final" modules webpack visits first (and so which sourcesContent index each lands at) depends on their relative completion timing - not stable across machines or even repeated runs on one machine. The nightly bump measured faster on both OSes but by a different relative amount each (~30% vs ~15% cold-start, ~0% vs ~5% warm, Mac vs Windows), a plausible trigger for flipping this pre-existing race; the race itself predates the bump and isn't ts-loader's to fix (tried a custom devtoolModuleFilenameTemplate first - doesn't hold, since the instability is in which modules get created, not how they're named). Worked around by not byte-comparing that one test's bundle.js.map - see the comment at its call site in create-and-execute-test.js. Also pinned *.vue to LF line endings in .gitattributes, which isn't the cause but is a reasonable consistency fix regardless. * fix: format * chore: execution tests on mac * chore: lose unstable as mentioned in microsoft/TypeScript#64709 * fix: can do prerelease * docs: README * fix: logger not respecting option * fix: typescript version * chore: version upgrade * fix: lockfile churn * chore: upgrade to 7.1.0-beta * feat: newImportedFileWatch test * refactor: use createPrograms for orphan files instead of synthetic tsconfigs * fix: don't export SyntheticProgram (knip) Co-Authored-By: Claude Opus 5.5 <[email protected]> * refactor: layer webpack-supplied content into the snapshot instead of fs callbacks Each compiled file's content is now added as a persistent fileSystem layer on the instance snapshot (sent in the same request as any openFiles for it), replacing the readFile/fileExists callbacks and runWithTemporaryFileUpdate. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs: add an example * docs: README and CHANGELOG fixes for 7.1.0-beta - install typescript@beta rather than next - list projectReferences among the accepted-but-inert options - correct errorFormatter's colors type Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: detect filesystem case sensitivity and pass it to the API useCaseSensitiveFileNames now defaults to probing the volume the tsconfig.json is on (as tsc does, and as v9 did via ts.sys) instead of assuming case-sensitive on every non-Windows platform, and the resolved value is passed to the TypeScript API so both agree on which paths are the same file. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs: point README at examples/simple and drop links to removed examples Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs: describe project references support accurately for v10 Co-Authored-By: Claude Opus 5.5 <[email protected]> * test: fail watch tests promptly and support deleting files in patches A failed assertion thrown from webpack's watch callback left the watcher open, so mocha never exited; the harness now closes it and fails the test. A patch file named <file>.__deleted__ now deletes <file> when applied. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: recheck dependants of deleted and re-created files in watch mode - compare paths canonically (via resolvedFilePathCache) when finding a changed file's dependants: the API echoes back the casing it was given, so on a case-insensitive filesystem exact-string comparison found none - treat a modified file the program didn't previously contain as created: clear directImportsCache (other files' imports may now resolve) and tell the API it was created - merge, rather than overwrite, unconsumed watcher changes, so a rebuild that compiles nothing (e.g. a pure deletion) doesn't lose them Adds the deletedFileWatch comparison test. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: send real-cased paths to the TypeScript API ts-loader passed its canonical (lowercased, when case-insensitive) paths to the API, which echoes back whatever casing it is given - so on Windows, and on macOS since case sensitivity is detected, TypeScript's messages showed lowercased paths. The canonical form is now only used for ts-loader's own cache keys; openProjects, openFiles and file notifications get real-cased paths. The comparison test harness no longer forces useCaseSensitiveFileNames: true, so the default is tested on every OS; snapshots change only in the options-derived instance hash. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: evict synthetic programs in a request of their own Sending removePrograms in the same snapshot update as createPrograms crashes tsgo 7.1.0-beta (nil dereference in ProjectCollectionBuilder.HandleAPIRequest), so any project with more than 20 orphan files killed the compiler process once the synthetic-program cap started evicting. Adds manyOrphanFiles (25 orphan files) as a regression test. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf: share one synthetic program across all orphan files Files outside the configured project each got their own synthetic program (capped at 20, least-recently-used evicted), each a near-complete copy of the project - so a tsconfig whose files list only a .d.ts (every module an orphan) rebuilt programs constantly: 8.1s vs 0.6s for the same 300-file fixture with an include glob. They now share one program, as classic ts-loader's single language service did, whose extra roots are only the orphan files it doesn't already contain via an import. Being a superset of the primary project, it also gives the transitive- dependant recheck the full import graph, so dependants of a changed orphan file are rechecked again (a regression from classic). Adds an all-orphan-files variant of the benchmark fixture with cold and hub-touch typeCheck scenarios: -92% and -95% vs the previous commit. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test: add orphanDependantWatch comparison test Every module is an orphan (the tsconfig lists only a .d.ts); changing an imported file's type must still be reported in the unchanged importer, which only the transitive-dependant recheck catches. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Update CHANGELOG with details on unsupported features Clarified the status of unsupported features in the CHANGELOG. * Update README to remove v10 upgrade notes Removed sections on upgrading to v10 and Yarn Plug’n’Play from the README. * docs: improve README * chore: prepare 10.0.0-beta.0 release - set version to 10.0.0-beta.0 - restrict typescript peer dependency to >=7.1.0-beta - add a files allowlist so only built output is published - document installing the beta via the next dist-tag Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: report diagnostics for unbundled project files and drop stale ones - type-check project files webpack doesn't bundle (all on the first build, then the ones webpack's watcher reports changed), and watch them so edits trigger a rebuild - matching v9 without onlyCompileBundledFiles - drop stored diagnostics and declaration files for files that are no longer in the program or a webpack module, e.g. deleted files - comparison-test harness records diagnostics-only rebuilds (same hash) - update fixture .d.ts files to valid TS 7 syntax Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: resolve import dependencies with the native module resolver Dependency tracking and the transitive-dependant recheck only followed relative specifiers, resolved by hand, so a change reached through a tsconfig paths alias (or baseUrl, package exports, ...) left stale diagnostics. Resolve every import via the program's getResolvedModuleFromModuleSpecifier instead, batched into one round trip per pass, skipping unresolved and external-library imports. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: John Reilly <[email protected]> Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: Claude Sonnet 5 <[email protected]>
Closes #64154. Read that issue for the big picture overview—here’s the list of changes and decisions:
api.updateSnapshot()is replaced by:api.getCurrentLanguageServerSnapshot(changes?)available in LSP mode onlyapi.createSnapshot(changes?)available alwaysconst newSnapshot = snapshot.update(changes)changestakes three new operations:snap.update({ createPrograms: [/* ... */] })adds programs to any snapshotsnap.update({ reconfigurePrograms: [/* ... */] })changes the root files, options, or references of a program created withcreateProgramssnap.update({ ensurePrograms: [/* ... */] })returns a snapshot where projects with the given IDs have up-to-date programs.snap.update({ ensurePrograms: true })ensures all projects are up to date.oldProgramas an option in creating a program. Instead, a program can be incrementally updated by notifying the API of its changed files and usingensurePrograms:updateSnapshotrequest. Now, you have to useensurePrograms. (The exception is that projects returned byopenProjectsoropenFilesare automatically updated without need for a separateensurePrograms, even if they're already open/created.ensureProgramsis mainly needed in combination withfileChanges, so you can say which projects you care about.)operationwith information about the request that created it. Currently onlycreateProgramsandopenFilescontribute tooperation, since those result in the creation of projects with an ID that might not be known to the caller ahead of time.project.idnow has the typeProjectId = ConfiguredProjectId | InferredProjectId | SyntheticProjectId, each of which is a branded string.ConfiguredProjectIdis a subtype ofPath. The same ID is also exposed onprogram.idfor convenience.api.createProgram(rootFiles, options)is basically shorthand forapi.createSnapshot({ createPrograms: [{ rootFiles, options }] }).operation.createdPrograms[0].fileChangestofileNotificationsandAPIFileChangestoFileNotifications