* Specialized map of WeakRefs to module instances that caches source map * entries by `filename` and `sourceURL`. Cached entries can be iterated with * `for..of` syntax. * * The cache map maintains the cache entries by: * - `weakModuleMap`(Map): a strong sourceURL -> WeakRef(Module), * - WeakR
| 32 | * indeterministic callback of a finalization registry. |
| 33 | */ |
| 34 | class SourceMapCacheMap { |
| 35 | /** |
| 36 | * @type {Map<string, WeakRef<*>>} |
| 37 | * The cached module instance can be removed from the global module registry |
| 38 | * with approaches like mutating `require.cache`. |
| 39 | * The `weakModuleMap` exposes entries by `filename` and `sourceURL`. |
| 40 | * In the case of mutated module registry, obsolete entries are removed from |
| 41 | * the cache by the `finalizationRegistry`. |
| 42 | */ |
| 43 | #weakModuleMap = new SafeMap(); |
| 44 | |
| 45 | #cleanup = ({ keys }) => { |
| 46 | // Delete the entry if the weak target has been reclaimed. |
| 47 | // If the weak target is not reclaimed, the entry was overridden by a new |
| 48 | // weak target. |
| 49 | ArrayPrototypeForEach(keys, (key) => { |
| 50 | const ref = this.#weakModuleMap.get(key); |
| 51 | if (ref && ref.deref() === undefined) { |
| 52 | debug(`Cleanup obsolete source map cache entry with key: ${key}`); |
| 53 | this.#weakModuleMap.delete(key); |
| 54 | } |
| 55 | }); |
| 56 | }; |
| 57 | #finalizationRegistry = new SafeFinalizationRegistry(this.#cleanup); |
| 58 | |
| 59 | /** |
| 60 | * Sets the value for the given key, associated with the given module |
| 61 | * instance. |
| 62 | * @param {string[]} keys array of urls to index the value entry. |
| 63 | * @param {*} sourceMapData the value entry. |
| 64 | * @param {object} moduleInstance an object that can be weakly referenced and |
| 65 | * invalidate the [key, value] entry after this object is reclaimed. |
| 66 | */ |
| 67 | set(keys, sourceMapData, moduleInstance) { |
| 68 | const weakRef = new SafeWeakRef(moduleInstance); |
| 69 | ArrayPrototypeForEach(keys, (key) => this.#weakModuleMap.set(key, weakRef)); |
| 70 | moduleInstance[source_map_data_private_symbol] = sourceMapData; |
| 71 | this.#finalizationRegistry.register(moduleInstance, { keys }); |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * Get an entry by the given key. |
| 76 | * @param {string} key a file url or source url |
| 77 | * @returns {object|undefined} |
| 78 | */ |
| 79 | get(key) { |
| 80 | const weakRef = this.#weakModuleMap.get(key); |
| 81 | const moduleInstance = weakRef?.deref(); |
| 82 | if (moduleInstance === undefined) { |
| 83 | return; |
| 84 | } |
| 85 | return moduleInstance[source_map_data_private_symbol]; |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * Estimate the size of the cache. The actual size may be smaller because |
| 90 | * some entries may be reclaimed with the module instance. |
| 91 | * @returns {number} |