diff --git a/packages/compiler-cli/preprocessor/ng-analyze/src/compiler/analyzer.rs b/packages/compiler-cli/preprocessor/ng-analyze/src/compiler/analyzer.rs index e9b26c640fc..af1dc2d0d05 100644 --- a/packages/compiler-cli/preprocessor/ng-analyze/src/compiler/analyzer.rs +++ b/packages/compiler-cli/preprocessor/ng-analyze/src/compiler/analyzer.rs @@ -559,12 +559,17 @@ impl Analyzer { self.push_evicted_paths(evicted, invalidated_paths); } - /// Append the wire path of every file whose cached query was evicted. + /// Append the wire path or virtual module ID of every file whose cached query was evicted. fn push_evicted_paths(&self, evicted: Vec, invalidated_paths: &mut Vec) { let mut evicted: Vec = evicted .into_iter() .filter_map(|key| key.file_id()) - .map(|file_id| crate::fs::path_to_string(self.engine.lookup_path(file_id))) + .map(|file_id| match self.engine.lookup_module(file_id) { + (id, crate::host::IdKind::Virtual) => id.as_str().to_owned(), + (_, crate::host::IdKind::Path) => { + crate::fs::path_to_string(self.engine.lookup_path(file_id)) + } + }) .collect(); evicted.sort_unstable(); evicted.dedup(); @@ -740,6 +745,16 @@ impl Analyzer { Ok(dedup_preserving_order(invalidated_paths)) } + /// Flush every cached module resolution and return every module ID whose cached analysis was + /// evicted. + pub fn clear_resolution_cache_core(&self) -> Result, String> { + self.cancel_current_analysis(); + let mut invalidated_paths = Vec::new(); + let evicted = self.engine.clear_resolution_cache(); + self.push_evicted_paths(evicted, &mut invalidated_paths); + Ok(dedup_preserving_order(invalidated_paths)) + } + /// Install the given compilation roots and the tsconfig's `.d.ts` files (`None` keeps the /// current list), evicting every query that read the previous lists when either differs, and /// every query that read which root is `r3_symbols.ts` when that changes too. @@ -880,6 +895,20 @@ impl Analyzer { self.set_entry_points_core(entry_points) } + /// Flush every cached module resolution and return every module ID whose cached analysis was + /// evicted. + #[cfg(feature = "napi")] + #[napi] + pub fn clear_resolution_cache(&self) -> napi::Result> { + self.clear_resolution_cache_core() + .map_err(napi::Error::from_reason) + } + + #[cfg(not(feature = "napi"))] + pub fn clear_resolution_cache(&self) -> Result, String> { + self.clear_resolution_cache_core() + } + #[cfg(feature = "napi")] #[napi] pub fn analyze(&self) -> napi::Result { diff --git a/packages/compiler-cli/preprocessor/ng-analyze/src/compiler/tests.rs b/packages/compiler-cli/preprocessor/ng-analyze/src/compiler/tests.rs index 64a0607957c..9a0ed9f6cb4 100644 --- a/packages/compiler-cli/preprocessor/ng-analyze/src/compiler/tests.rs +++ b/packages/compiler-cli/preprocessor/ng-analyze/src/compiler/tests.rs @@ -5660,6 +5660,39 @@ fn test_invalidate_files_deleted_file_evicts_importer_after_unrelated_file_creat ); } +#[test] +fn test_clear_resolution_cache_re_resolves_cached_importers() { + let dir = tempfile::TempDir::new().unwrap(); + let root = dir.path().canonicalize().unwrap(); + let root_str = root.to_string_lossy().into_owned(); + let lib_dir = root.join("lib"); + std::fs::create_dir(&lib_dir).unwrap(); + std::fs::write(lib_dir.join("index.ts"), lib_source("[libIndex]")).unwrap(); + let app_path = format!("{root_str}/app.ts"); + + let analyzer = consumer_analyzer(&root_str, "./lib", HashMap::new()); + assert_eq!( + imported_lib_dir_selector(&analyzer, &app_path).as_deref(), + Some("[libIndex]") + ); + let app_wire_path = analyzer + .get_metadata_for_file(app_path.clone()) + .unwrap() + .file_path; + + // Write `lib.ts` shadowing `lib/index.ts` without reporting `FileUpdateType::Created`, then + // explicitly flush cached resolutions via `clear_resolution_cache`. + std::fs::write(root.join("lib.ts"), lib_source("[libDirect]")).unwrap(); + let invalidated = analyzer.clear_resolution_cache().unwrap(); + + assert!(invalidated.contains(&app_wire_path), "{invalidated:?}"); + assert_eq!( + imported_lib_dir_selector(&analyzer, &app_path).as_deref(), + Some("[libDirect]"), + "clear_resolution_cache must evict cached positive resolutions so ./lib re-resolves" + ); +} + #[cfg(unix)] #[test] fn test_canonical_paths_resolves_symlinked_host_paths() { diff --git a/packages/compiler-cli/preprocessor/ng-analyze/src/main.rs b/packages/compiler-cli/preprocessor/ng-analyze/src/main.rs index e1360b15e20..b18be32e6d3 100644 --- a/packages/compiler-cli/preprocessor/ng-analyze/src/main.rs +++ b/packages/compiler-cli/preprocessor/ng-analyze/src/main.rs @@ -294,6 +294,18 @@ fn handle_rpc_request(req: RpcRequest, analyzer: &mut Option) -> RpcRe }, } } + "clearResolutionCache" => match a.clear_resolution_cache_core() { + Ok(res) => RpcResponse { + id: req.id, + result: Some(serde_json::to_value(&res).unwrap()), + error: None, + }, + Err(e) => RpcResponse { + id: req.id, + result: None, + error: Some(e), + }, + }, "getTsFileForTemplate" => { let Ok(param) = serde_json::from_value::(req.params) else { return RpcResponse { diff --git a/packages/compiler-cli/preprocessor/ng-analyze/src/query/engine.rs b/packages/compiler-cli/preprocessor/ng-analyze/src/query/engine.rs index 96d28da0aad..9e29000dba7 100644 --- a/packages/compiler-cli/preprocessor/ng-analyze/src/query/engine.rs +++ b/packages/compiler-cli/preprocessor/ng-analyze/src/query/engine.rs @@ -424,8 +424,8 @@ impl QueryEngine { if let Some(cached) = self.resolution_cache.get(importer, &key) { return cached; } - // Read before asking the host, so that an answer which arrives after a structure change is - // recognized as superseded and not memoized. + // Read before asking the host, so that an answer which arrives after a structure change or + // a full flush is recognized as superseded and not memoized. let generation = self.resolution_cache.generation(); let mut kind_changed = false; let outcome = match self.host.resolve(req).await { @@ -1141,13 +1141,31 @@ impl QueryEngine { /// /// Must not run while a resolution is in progress. pub fn invalidate_module_resolution(&self) -> Vec { + self.evict_resolution_importers(|cache| cache.clear_for_structure_change()) + } + + /// Flush every cached module resolution and evict queries derived from any importer's + /// resolutions while keeping each file's `ParseFile` result cached. + /// + /// Must not run while a resolution is in progress. + pub fn clear_resolution_cache(&self) -> Vec { + self.evict_resolution_importers(|cache| cache.clear_all()) + } + + /// Clear the host's resolver cache, invalidate cached resolutions with `clear`, and evict the + /// queries of the importers it returns (keeping each one's `ParseFile`) along with every query + /// that recorded a failed resolution. + fn evict_resolution_importers( + &self, + clear: impl FnOnce(&crate::query::resolution_cache::ResolutionCache) -> HashSet, + ) -> Vec { self.host.clear_cache(); - let unresolved_importers = self.resolution_cache.clear_for_structure_change(); + let importers = clear(&self.resolution_cache); let mut evicted: HashSet = self .invalidate_file_id(UNRESOLVED_IMPORTS_FILE_ID) .into_iter() .collect(); - evicted.extend(self.evict_importers_preserving_parse(unresolved_importers)); + evicted.extend(self.evict_importers_preserving_parse(importers)); evicted.into_iter().collect() } @@ -5881,6 +5899,7 @@ mod tests { resolutions: RwLock>, modules: RwLock>, resolve_calls: Mutex>, + load_calls: Mutex>, } impl AnalysisHost for CountingAsyncHost { @@ -5900,6 +5919,7 @@ mod tests { _kind: LoadKind, _external: bool, ) -> HostFuture, HostError>> { + self.load_calls.lock().unwrap().push(id.as_str().to_owned()); let hit = self.modules.read().unwrap().get(id.as_str()).cloned(); yield_once(Ok(hit)) } @@ -5917,6 +5937,7 @@ mod tests { let app_path = "/cache_test/app.ts"; let barrel_path = "/cache_test/barrel.ts"; let child_path = "/cache_test/child.ts"; + let alt_child_path = "/cache_test/alt_child.ts"; let mut resolutions = HashMap::new(); resolutions.insert( @@ -5966,7 +5987,7 @@ mod tests { import { BarrelDir } from './barrel';\n\ @Component({\n\ selector: 'app-root',\n\ - template: '
',\n\ + template: '
',\n\ imports: [BarrelDir],\n\ })\n\ export class AppCmp {}\n", @@ -5982,11 +6003,13 @@ mod tests { }, ); modules.insert(child_path.to_owned(), child_source("[childV1]")); + modules.insert(alt_child_path.to_owned(), child_source("[childAlt]")); let host = Arc::new(CountingAsyncHost { resolutions: RwLock::new(resolutions), modules: RwLock::new(modules), resolve_calls: Mutex::new(Vec::new()), + load_calls: Mutex::new(Vec::new()), }); let registry = Arc::new(ResourceRegistry::default()); let entrypoints = Arc::new(RwLock::new(vec![PathBuf::from(app_path)])); @@ -6054,12 +6077,54 @@ mod tests { // Editing `app.ts` itself drops only `app.ts`'s cached resolutions while preserving // `barrel.ts`'s cached resolution to `./child`. engine.invalidate_file_id(app_id); + let engine_v3 = engine.clone(); let _ = block_on_with_timeout(async move { - let ctx = QueryContext::new(engine); + let ctx = QueryContext::new(engine_v3); ctx.analyze_file_semantic(app_id).await }); assert_eq!(count_for(app_path, "./barrel", ImportKind::Static), 1); assert_eq!(count_for(barrel_path, "./child", ImportKind::ReExport), 0); + + // Clearing the resolution cache re-resolves positive cached entries across all importers + // while keeping existing `ParseFile` results cached (no host `load` for `app` or `barrel`). + host.resolve_calls.lock().unwrap().clear(); + host.load_calls.lock().unwrap().clear(); + host.resolutions.write().unwrap().insert( + ( + barrel_path.to_owned(), + "./child".to_owned(), + ImportKind::ReExport, + ), + ResolvedModule { + id: ModuleId::new(alt_child_path), + id_kind: IdKind::Path, + format: Some(ModuleFormat::Ts), + external: false, + code: None, + }, + ); + let evicted = engine.clear_resolution_cache(); + assert!(evicted.contains(&QueryKey::AnalyzeFileSemantic(app_id))); + assert!(!evicted.contains(&QueryKey::ParseFile(app_id))); + assert!(!evicted.contains(&QueryKey::ParseFile(barrel_id))); + + let semantic_v4 = block_on_with_timeout(async move { + let ctx = QueryContext::new(engine); + ctx.analyze_file_semantic(app_id).await + }); + let cmp_v4 = semantic_v4.classes[0].as_component().expect("AppCmp"); + assert_eq!( + cmp_v4.resolved_declarations.as_ref().unwrap()[0] + .selector + .as_deref(), + Some("[childAlt]") + ); + assert_eq!(count_for(app_path, "./barrel", ImportKind::Static), 1); + assert_eq!(count_for(barrel_path, "./child", ImportKind::ReExport), 1); + assert_eq!( + *host.load_calls.lock().unwrap(), + vec![alt_child_path.to_owned()] + ); } /// A failed lookup served from the resolution cache must still mark the calling query as diff --git a/packages/compiler-cli/preprocessor/ng-analyze/src/query/resolution_cache.rs b/packages/compiler-cli/preprocessor/ng-analyze/src/query/resolution_cache.rs index 1eebaa0785d..e77e7deb169 100644 --- a/packages/compiler-cli/preprocessor/ng-analyze/src/query/resolution_cache.rs +++ b/packages/compiler-cli/preprocessor/ng-analyze/src/query/resolution_cache.rs @@ -38,8 +38,9 @@ struct CachedEntry { #[derive(Default)] struct ResolutionCacheInner { - /// Counts structure changes ([`ResolutionCache::clear_for_structure_change`]). An entry - /// recorded in an earlier generation is stale: it is no longer served, but it is kept so that + /// Counts structure changes ([`ResolutionCache::clear_for_structure_change`]) and full + /// flushes ([`ResolutionCache::clear_all`]). An entry recorded in an earlier generation is + /// stale: it is no longer served. A structure change keeps such entries so that /// [`Self::importers_by_target`] still covers an importer whose queries stayed cached and so /// do not resolve again. generation: u64, @@ -66,7 +67,8 @@ impl ResolutionCache { } /// The current generation. A lookup reads it before asking the host and passes it to - /// [`Self::insert`], so that an answer obtained across a structure change is not memoized. + /// [`Self::insert`], so that an answer obtained across a structure change or a full flush is + /// not memoized. pub fn generation(&self) -> u64 { self.inner.read().unwrap().generation } @@ -83,7 +85,7 @@ impl ResolutionCache { /// resolved to, or among the importers with a failed lookup. /// /// `generation` is the one read ([`Self::generation`]) before the host was asked. The outcome - /// is dropped when a structure change has superseded it since. + /// is dropped when a structure change or a full flush has superseded it since. pub fn insert( &self, importer: FileId, @@ -170,6 +172,21 @@ impl ResolutionCache { .into_keys() .collect() } + + /// Flush all cached resolutions and unresolved-specifier entries, returning every importer + /// `FileId` that held any positive or negative resolution entry. A lookup still waiting on + /// the host is superseded, so its answer is not memoized afterwards. + pub fn clear_all(&self) -> HashSet { + let mut guard = self.inner.write().unwrap(); + let inner = &mut *guard; + inner.generation += 1; + inner.importers_by_target.clear(); + let by_importer = std::mem::take(&mut inner.by_importer); + let unresolved = std::mem::take(&mut inner.unresolved_by_importer); + let mut importers: HashSet = by_importer.into_keys().collect(); + importers.extend(unresolved.into_keys()); + importers + } } fn remove_importer_locked(inner: &mut ResolutionCacheInner, importer: FileId) { @@ -458,4 +475,50 @@ mod tests { assert!(cache.get(importer, &key).is_none()); assert!(cache.remove_deleted_target(target).is_empty()); } + + #[test] + fn clear_all_returns_both_resolved_and_unresolved_importers() { + let cache = ResolutionCache::new(); + let importer_ok: FileId = 30; + let importer_missing: FileId = 31; + let target: FileId = 40; + + let ok_key = ResolutionLookupKey::from_request(&ResolveRequest::new( + "/app/ok.ts", + "./lib", + ImportKind::Static, + )); + let missing_key = ResolutionLookupKey::from_request(&ResolveRequest::new( + "/app/missing.ts", + "./nope", + ImportKind::Static, + )); + + let stale_gen = cache.generation(); + cache.insert( + importer_ok, + ok_key.clone(), + Ok(Some((target, resolved_module("/app/lib.ts")))), + stale_gen, + ); + cache.insert(importer_missing, missing_key.clone(), Ok(None), stale_gen); + + let cleared = cache.clear_all(); + assert_eq!(cleared, HashSet::from([importer_ok, importer_missing])); + assert!(cache.get(importer_ok, &ok_key).is_none()); + assert!(cache.get(importer_missing, &missing_key).is_none()); + assert!(cache.remove_deleted_target(target).is_empty()); + + // A lookup that started before the flush is answered after it. + cache.insert( + importer_ok, + ok_key.clone(), + Ok(Some((target, resolved_module("/app/lib.ts")))), + stale_gen, + ); + assert!(cache.get(importer_ok, &ok_key).is_none()); + assert!(cache.remove_deleted_target(target).is_empty()); + + assert!(cache.clear_for_structure_change().is_empty()); + } } diff --git a/packages/compiler-cli/preprocessor/ng-analyze/src/test_analyzer.rs b/packages/compiler-cli/preprocessor/ng-analyze/src/test_analyzer.rs index d0214734050..1e91365ecde 100644 --- a/packages/compiler-cli/preprocessor/ng-analyze/src/test_analyzer.rs +++ b/packages/compiler-cli/preprocessor/ng-analyze/src/test_analyzer.rs @@ -153,6 +153,17 @@ impl TestAnalyzer { self.analyzer.set_entry_points(entry_points) } + #[cfg(feature = "napi")] + #[napi] + pub fn clear_resolution_cache(&self) -> napi::Result> { + self.analyzer.clear_resolution_cache() + } + + #[cfg(not(feature = "napi"))] + pub fn clear_resolution_cache(&self) -> Result, String> { + self.analyzer.clear_resolution_cache() + } + #[cfg(feature = "napi")] #[napi] pub fn analyze(&self) -> napi::Result { diff --git a/packages/compiler-cli/preprocessor/ng-analyze/src/wasm.rs b/packages/compiler-cli/preprocessor/ng-analyze/src/wasm.rs index 9da1a365bd3..235c233742f 100644 --- a/packages/compiler-cli/preprocessor/ng-analyze/src/wasm.rs +++ b/packages/compiler-cli/preprocessor/ng-analyze/src/wasm.rs @@ -143,6 +143,11 @@ impl WasmAnalyzer { serde_json::to_string(&res).map_err(|e| e.to_string()) } + pub fn clear_resolution_cache(&self) -> Result { + let res = self.analyzer.clear_resolution_cache_core()?; + serde_json::to_string(&res).map_err(|e| e.to_string()) + } + pub fn get_ts_file_for_template(&self, template_path: String) -> Option { let res = self.analyzer.get_ts_file_for_template_core(template_path)?; serde_json::to_string(&res).ok() diff --git a/packages/compiler-cli/preprocessor/src/analyzer_napi.ts b/packages/compiler-cli/preprocessor/src/analyzer_napi.ts index 9007baa5942..a147d177d92 100644 --- a/packages/compiler-cli/preprocessor/src/analyzer_napi.ts +++ b/packages/compiler-cli/preprocessor/src/analyzer_napi.ts @@ -79,6 +79,10 @@ export class NapiAnalyzer implements IAnalyzer { return this.analyzer.setEntryPoints(entryPoints); } + async clearResolutionCache(): Promise { + return this.analyzer.clearResolutionCache(); + } + async getTsFileForTemplate(templatePath: string): Promise { return this.analyzer.getTsFileForTemplate(templatePath); } diff --git a/packages/compiler-cli/preprocessor/src/analyzer_sidecar.ts b/packages/compiler-cli/preprocessor/src/analyzer_sidecar.ts index edea40cd365..37c3a24e8db 100644 --- a/packages/compiler-cli/preprocessor/src/analyzer_sidecar.ts +++ b/packages/compiler-cli/preprocessor/src/analyzer_sidecar.ts @@ -372,6 +372,10 @@ export class SidecarAnalyzer implements IAnalyzer { return this.callRpc('setEntryPoints', entryPoints); } + async clearResolutionCache(): Promise { + return this.callRpc('clearResolutionCache', null); + } + async getTsFileForTemplate(templatePath: string): Promise { return this.callRpc('getTsFileForTemplate', {templatePath}); } diff --git a/packages/compiler-cli/preprocessor/src/analyzer_wasm.ts b/packages/compiler-cli/preprocessor/src/analyzer_wasm.ts index 26702b62171..ba9400d0d4d 100644 --- a/packages/compiler-cli/preprocessor/src/analyzer_wasm.ts +++ b/packages/compiler-cli/preprocessor/src/analyzer_wasm.ts @@ -27,6 +27,8 @@ export interface WasmInner { invalidate_files?(updatesJson: string): string; setEntryPoints?(entryPointsJson: string): string; set_entry_points?(entryPointsJson: string): string; + clearResolutionCache?(): string; + clear_resolution_cache?(): string; getMetadataForFile?(filePath: string): string | undefined; get_metadata_for_file?(filePath: string): string | undefined; getFileContent?(filePath: string): string; @@ -267,6 +269,14 @@ export class WasmAnalyzer implements IAnalyzer { return JSON.parse(res) as string[]; } + async clearResolutionCache(): Promise { + const res = this.invoke( + this.inner.clearResolutionCache ?? this.inner.clear_resolution_cache, + 'clearResolutionCache', + ); + return JSON.parse(res) as string[]; + } + async getTsFileForTemplate(templatePath: string): Promise { const res = this.invoke( this.inner.getTsFileForTemplate ?? this.inner.get_ts_file_for_template, diff --git a/packages/compiler-cli/preprocessor/src/hybrid_compiler.ts b/packages/compiler-cli/preprocessor/src/hybrid_compiler.ts index 25adb69b7a7..bfeebd362d9 100644 --- a/packages/compiler-cli/preprocessor/src/hybrid_compiler.ts +++ b/packages/compiler-cli/preprocessor/src/hybrid_compiler.ts @@ -116,6 +116,11 @@ export interface IAnalyzer { * is now stale. From then on the roots are no longer re-read from the tsconfig. */ setEntryPoints(entryPoints: string[]): Promise; + /** + * Flushes cached module resolutions and returns every module ID whose cached analysis is now + * stale. + */ + clearResolutionCache?(): Promise; getTsFileForTemplate(templatePath: string): Promise; getFileContent(filePath: string): Promise; /** @@ -776,6 +781,27 @@ export class HybridCompiler { }); } + /** + * Flushes cached module resolutions in the underlying analyzer and refreshes stale analyses on + * the queued delta pass. + */ + async clearResolutionCache(): Promise { + await this.enqueueUpdate(async () => { + if (!this.analyzer.clearResolutionCache) { + throw new Error('Analyzer does not support clearResolutionCache'); + } + const invalidated = await this.analyzer.clearResolutionCache(); + // The flush also evicts declaration files that resolved their own re-exports. None of them + // changed, and recording one would make the tracker start over and re-emit every file. The + // source files that import them are in `invalidated` as well. + const changed = invalidated.filter((filePath) => !filePath.endsWith('.d.ts')); + if (this.incrementalEnabled && changed.length > 0) { + this.incremental.recordChanges(changed, []); + } + return invalidated; + }); + } + /** * Applies file invalidations already executed on `this.analyzer` (e.g. when reusing a * `HybridCompiler` across persistent worker requests with `run()`). diff --git a/packages/compiler-cli/preprocessor/src/types.ts b/packages/compiler-cli/preprocessor/src/types.ts index c77e1970f47..341afd73979 100644 --- a/packages/compiler-cli/preprocessor/src/types.ts +++ b/packages/compiler-cli/preprocessor/src/types.ts @@ -28,6 +28,11 @@ export declare class Analyzer { * Paths must be absolute. From then on the roots are no longer re-read from the tsconfig. */ setEntryPoints(entryPoints: Array): Array; + /** + * Flush every cached module resolution and return every module ID whose cached analysis was + * evicted. + */ + clearResolutionCache(): Array; analyze(): AnalysisIterator; analyzeOptimized(): AnalysisIterator; analyzeDelta(): AnalysisIterator; @@ -50,6 +55,7 @@ export declare class TestAnalyzer { updateFileContent(updates: Array): Array; invalidateFiles(updates: Array): Array; setEntryPoints(entryPoints: Array): Array; + clearResolutionCache(): Array; analyze(): AnalysisIterator; analyzeOptimized(): AnalysisIterator; analyzeDelta(): AnalysisIterator; diff --git a/packages/compiler-cli/preprocessor/test/analyzer_wasm_spec.ts b/packages/compiler-cli/preprocessor/test/analyzer_wasm_spec.ts index 72a9f62464c..276de738851 100644 --- a/packages/compiler-cli/preprocessor/test/analyzer_wasm_spec.ts +++ b/packages/compiler-cli/preprocessor/test/analyzer_wasm_spec.ts @@ -28,6 +28,7 @@ function throwingInner(message: string): WasmInner { update_file_content: fail, invalidate_files: fail, set_entry_points: fail, + clear_resolution_cache: fail, get_file_content: fail, get_metadata_for_file: fail, get_ts_file_for_template: fail, @@ -40,6 +41,7 @@ describe('WasmAnalyzer engine errors', () => { const analyzer = new WasmAnalyzer(throwingInner(MESSAGE)); await expectAsync(analyzer.setEntryPoints(['src/main.ts'])).toBeRejectedWithError(MESSAGE); + await expectAsync(analyzer.clearResolutionCache()).toBeRejectedWithError(MESSAGE); await expectAsync(analyzer.updateFileContent([])).toBeRejectedWithError(MESSAGE); await expectAsync(analyzer.invalidateFiles([])).toBeRejectedWithError(MESSAGE); await expectAsync(analyzer.getFileContent('/main.ts')).toBeRejectedWithError(MESSAGE); @@ -75,10 +77,22 @@ describe('WasmAnalyzer engine errors', () => { it('still reports exports that an older engine build lacks', async () => { const inner = throwingInner('unused'); delete inner.set_entry_points; + delete inner.clear_resolution_cache; const analyzer = new WasmAnalyzer(inner); await expectAsync(analyzer.setEntryPoints(['/main.ts'])).toBeRejectedWithError( 'WasmInner does not support setEntryPoints', ); + await expectAsync(analyzer.clearResolutionCache()).toBeRejectedWithError( + 'WasmInner does not support clearResolutionCache', + ); + }); + + it('parses evicted module IDs returned by clearResolutionCache', async () => { + const inner = throwingInner('unused'); + inner.clear_resolution_cache = () => JSON.stringify(['/app/a.ts', '\0virtual:dep']); + const analyzer = new WasmAnalyzer(inner); + + expect(await analyzer.clearResolutionCache()).toEqual(['/app/a.ts', '\0virtual:dep']); }); }); diff --git a/packages/compiler-cli/preprocessor/test/hybrid_compiler_update_queue_spec.ts b/packages/compiler-cli/preprocessor/test/hybrid_compiler_update_queue_spec.ts index 504f1d75cc6..b9dccc577d1 100644 --- a/packages/compiler-cli/preprocessor/test/hybrid_compiler_update_queue_spec.ts +++ b/packages/compiler-cli/preprocessor/test/hybrid_compiler_update_queue_spec.ts @@ -51,6 +51,7 @@ class ScriptedAnalyzer implements IAnalyzer { // Optional engine capabilities a test may opt into. canonicalPaths?: IAnalyzer['canonicalPaths']; + clearResolutionCache?: IAnalyzer['clearResolutionCache']; async *analyze(): AsyncGenerator {} async *analyzeOptimized(): AsyncGenerator {} @@ -285,5 +286,37 @@ for (const {optimize} of [{optimize: true}, {optimize: false}]) { [['/real/b.html'], ['/real/c.ts']], ]); }); + + it('queues clearResolutionCache, evicts stale file caches, and records incremental changes', async () => { + const analyzer = new ScriptedAnalyzer(); + analyzer.clearResolutionCache = async () => { + analyzer.calls.push('clearResolutionCache'); + return ['/app/a.ts', '/node_modules/lib/index.d.ts']; + }; + const compiler = new HybridCompiler(analyzer, {optimize}); + const recordChanges = spyOn(compiler.incremental, 'recordChanges').and.callThrough(); + getOrCreateFileAnalysis(compiler.fileCache, '/app/a.ts'); + getOrCreateFileAnalysis(compiler.fileCache, '/node_modules/lib/index.d.ts'); + getOrCreateFileAnalysis(compiler.fileCache, '/app/keep.ts'); + + await compiler.clearResolutionCache(); + + expect(analyzer.calls).toEqual(['clearResolutionCache', deltaCall]); + expect([...compiler.fileCache.keys()]).toEqual(['/app/keep.ts']); + // An evicted declaration file did not change, so it is not recorded as one: that would + // make the next build re-emit every file. + expect(recordChanges.calls.allArgs()).toEqual([[['/app/a.ts'], []]]); + }); + + it('records no incremental change when clearResolutionCache only evicts declaration files', async () => { + const analyzer = new ScriptedAnalyzer(); + analyzer.clearResolutionCache = async () => ['/node_modules/lib/index.d.ts']; + const compiler = new HybridCompiler(analyzer, {optimize}); + const recordChanges = spyOn(compiler.incremental, 'recordChanges').and.callThrough(); + + await compiler.clearResolutionCache(); + + expect(recordChanges).not.toHaveBeenCalled(); + }); }); }