mirror of
https://github.com/angular/angular.git
synced 2026-11-22 22:55:25 -05:00
refactor(compiler-cli): expose clearResolutionCache across preprocessor and HybridCompiler
Bundler integrations and workspace reconfigurations can change how module specifiers resolve without editing any individual source file—for example when alias tables, export conditions, or package layouts change between builds. While `invalidate_module_resolution` re-runs previously failed resolutions after file creation or deletion, callers also need a way to flush positive cached resolutions without discarding parsed ASTs. Add `ResolutionCache::clear_all` and `QueryEngine::clear_resolution_cache` to clear both host-internal and engine-level resolution caches and evict queries derived from any importer's resolutions while preserving cached `ParseFile` results. Expose `clear_resolution_cache` on `Analyzer`, `TestAnalyzer`, `WasmAnalyzer`, and the sidecar JSON-RPC server, returning the deduplicated list of stale module IDs while preserving virtual module IDs verbatim instead of normalizing backslashes. Surface `clearResolutionCache` on `IAnalyzer`, `WasmAnalyzer`, `NapiAnalyzer`, `SidecarAnalyzer`, and `HybridCompiler`. In `HybridCompiler`, sequence `clearResolutionCache` through the serialized update queue so evicted analyses are dropped from the TypeScript file cache, recorded for incremental emit, and refreshed on the following delta pass.
This commit is contained in:
committed by
Alon Mishne
parent
567ae3ed66
commit
688ff615af
@@ -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<QueryKey>, invalidated_paths: &mut Vec<String>) {
|
||||
let mut evicted: Vec<String> = 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<Vec<String>, 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<Vec<String>> {
|
||||
self.clear_resolution_cache_core()
|
||||
.map_err(napi::Error::from_reason)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "napi"))]
|
||||
pub fn clear_resolution_cache(&self) -> Result<Vec<String>, String> {
|
||||
self.clear_resolution_cache_core()
|
||||
}
|
||||
|
||||
#[cfg(feature = "napi")]
|
||||
#[napi]
|
||||
pub fn analyze(&self) -> napi::Result<crate::AnalysisIterator> {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -294,6 +294,18 @@ fn handle_rpc_request(req: RpcRequest, analyzer: &mut Option<Analyzer>) -> 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::<TemplatePathParam>(req.params) else {
|
||||
return RpcResponse {
|
||||
|
||||
@@ -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<QueryKey> {
|
||||
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<QueryKey> {
|
||||
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<FileId>,
|
||||
) -> Vec<QueryKey> {
|
||||
self.host.clear_cache();
|
||||
let unresolved_importers = self.resolution_cache.clear_for_structure_change();
|
||||
let importers = clear(&self.resolution_cache);
|
||||
let mut evicted: HashSet<QueryKey> = 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<HashMap<(String, String, ImportKind), ResolvedModule>>,
|
||||
modules: RwLock<HashMap<String, LoadedModule>>,
|
||||
resolve_calls: Mutex<Vec<(String, String, ImportKind)>>,
|
||||
load_calls: Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
impl AnalysisHost for CountingAsyncHost {
|
||||
@@ -5900,6 +5919,7 @@ mod tests {
|
||||
_kind: LoadKind,
|
||||
_external: bool,
|
||||
) -> HostFuture<Result<Option<LoadedModule>, 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: '<div childV1 childV2></div>',\n\
|
||||
template: '<div childV1 childV2 childAlt></div>',\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
|
||||
|
||||
@@ -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<FileId> {
|
||||
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<FileId> = 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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Vec<String>> {
|
||||
self.analyzer.clear_resolution_cache()
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "napi"))]
|
||||
pub fn clear_resolution_cache(&self) -> Result<Vec<String>, String> {
|
||||
self.analyzer.clear_resolution_cache()
|
||||
}
|
||||
|
||||
#[cfg(feature = "napi")]
|
||||
#[napi]
|
||||
pub fn analyze(&self) -> napi::Result<AnalysisIterator> {
|
||||
|
||||
@@ -143,6 +143,11 @@ impl WasmAnalyzer {
|
||||
serde_json::to_string(&res).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn clear_resolution_cache(&self) -> Result<String, String> {
|
||||
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<String> {
|
||||
let res = self.analyzer.get_ts_file_for_template_core(template_path)?;
|
||||
serde_json::to_string(&res).ok()
|
||||
|
||||
@@ -79,6 +79,10 @@ export class NapiAnalyzer implements IAnalyzer {
|
||||
return this.analyzer.setEntryPoints(entryPoints);
|
||||
}
|
||||
|
||||
async clearResolutionCache(): Promise<string[]> {
|
||||
return this.analyzer.clearResolutionCache();
|
||||
}
|
||||
|
||||
async getTsFileForTemplate(templatePath: string): Promise<nga.TemplateUsage[] | null> {
|
||||
return this.analyzer.getTsFileForTemplate(templatePath);
|
||||
}
|
||||
|
||||
@@ -372,6 +372,10 @@ export class SidecarAnalyzer implements IAnalyzer {
|
||||
return this.callRpc('setEntryPoints', entryPoints);
|
||||
}
|
||||
|
||||
async clearResolutionCache(): Promise<string[]> {
|
||||
return this.callRpc('clearResolutionCache', null);
|
||||
}
|
||||
|
||||
async getTsFileForTemplate(templatePath: string): Promise<TemplateUsage[] | null> {
|
||||
return this.callRpc('getTsFileForTemplate', {templatePath});
|
||||
}
|
||||
|
||||
@@ -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<string[]> {
|
||||
const res = this.invoke(
|
||||
this.inner.clearResolutionCache ?? this.inner.clear_resolution_cache,
|
||||
'clearResolutionCache',
|
||||
);
|
||||
return JSON.parse(res) as string[];
|
||||
}
|
||||
|
||||
async getTsFileForTemplate(templatePath: string): Promise<nga.TemplateUsage[] | null> {
|
||||
const res = this.invoke(
|
||||
this.inner.getTsFileForTemplate ?? this.inner.get_ts_file_for_template,
|
||||
|
||||
@@ -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<string[]>;
|
||||
/**
|
||||
* Flushes cached module resolutions and returns every module ID whose cached analysis is now
|
||||
* stale.
|
||||
*/
|
||||
clearResolutionCache?(): Promise<string[]>;
|
||||
getTsFileForTemplate(templatePath: string): Promise<nga.TemplateUsage[] | null>;
|
||||
getFileContent(filePath: string): Promise<string>;
|
||||
/**
|
||||
@@ -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<void> {
|
||||
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()`).
|
||||
|
||||
@@ -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<string>): Array<string>;
|
||||
/**
|
||||
* Flush every cached module resolution and return every module ID whose cached analysis was
|
||||
* evicted.
|
||||
*/
|
||||
clearResolutionCache(): Array<string>;
|
||||
analyze(): AnalysisIterator;
|
||||
analyzeOptimized(): AnalysisIterator;
|
||||
analyzeDelta(): AnalysisIterator;
|
||||
@@ -50,6 +55,7 @@ export declare class TestAnalyzer {
|
||||
updateFileContent(updates: Array<FileUpdate>): Array<string>;
|
||||
invalidateFiles(updates: Array<FileInvalidation>): Array<string>;
|
||||
setEntryPoints(entryPoints: Array<string>): Array<string>;
|
||||
clearResolutionCache(): Array<string>;
|
||||
analyze(): AnalysisIterator;
|
||||
analyzeOptimized(): AnalysisIterator;
|
||||
analyzeDelta(): AnalysisIterator;
|
||||
|
||||
@@ -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']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<CompilationChunk> {}
|
||||
async *analyzeOptimized(): AsyncGenerator<CompilationChunk> {}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user