diff --git a/LICENSE.md b/LICENSE.md index fd5c20a53..3da0f176a 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -247,6 +247,23 @@ Repository: jonschlinkert/fill-range --------------------------------------- +## flru +License: MIT +By: Luke Edwards +Repository: lukeed/flru + +> MIT License +> +> Copyright (c) Luke Edwards (lukeed.com) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + ## glob-parent License: ISC By: Gulp Team, Elan Shanker, Blaine Bublitz diff --git a/browser/LICENSE.md b/browser/LICENSE.md index c393ff66b..f0c9254ed 100644 --- a/browser/LICENSE.md +++ b/browser/LICENSE.md @@ -88,6 +88,23 @@ Repository: https://github.com/acornjs/acorn.git --------------------------------------- +## flru +License: MIT +By: Luke Edwards +Repository: lukeed/flru + +> MIT License +> +> Copyright (c) Luke Edwards (lukeed.com) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + ## hash.js License: MIT By: Fedor Indutny diff --git a/package-lock.json b/package-lock.json index 49170f080..61525e279 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,6 +44,7 @@ "eslint-plugin-prettier": "^4.2.1", "eslint-plugin-unicorn": "^44.0.2", "fixturify": "^2.1.1", + "flru": "^1.0.2", "fs-extra": "^10.1.0", "github-api": "^3.4.0", "hash.js": "^1.1.7", @@ -3251,6 +3252,15 @@ "integrity": "sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==", "dev": true }, + "node_modules/flru": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz", + "integrity": "sha512-kWyh8ADvHBFz6ua5xYOPnUroZTT/bwWfrCeL0Wj1dzG4/YOmOcfJ99W8dOVyyynJN35rZ9aCOtHChqQovV7yog==", + "dev": true, + "engines": { + "node": ">=6" + } + }, "node_modules/follow-redirects": { "version": "1.15.2", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", @@ -10351,6 +10361,12 @@ "integrity": "sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==", "dev": true }, + "flru": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz", + "integrity": "sha512-kWyh8ADvHBFz6ua5xYOPnUroZTT/bwWfrCeL0Wj1dzG4/YOmOcfJ99W8dOVyyynJN35rZ9aCOtHChqQovV7yog==", + "dev": true + }, "follow-redirects": { "version": "1.15.2", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", diff --git a/package.json b/package.json index 0b47dfdd3..5a22ad044 100644 --- a/package.json +++ b/package.json @@ -90,6 +90,7 @@ "eslint-plugin-prettier": "^4.2.1", "eslint-plugin-unicorn": "^44.0.2", "fixturify": "^2.1.1", + "flru": "^1.0.2", "fs-extra": "^10.1.0", "github-api": "^3.4.0", "hash.js": "^1.1.7", diff --git a/src/Graph.ts b/src/Graph.ts index 099d3d3e9..6376ecf20 100644 --- a/src/Graph.ts +++ b/src/Graph.ts @@ -1,4 +1,5 @@ import * as acorn from 'acorn'; +import flru from 'flru'; import type ExternalModule from './ExternalModule'; import Module from './Module'; import { ModuleLoader, type UnresolvedModule } from './ModuleLoader'; @@ -52,6 +53,7 @@ function normalizeEntryModules( export default class Graph { readonly acornParser: typeof acorn.Parser; + readonly astLru = flru(5); readonly cachedModules = new Map(); readonly deoptimizationTracker = new PathTracker(); entryModules: Module[] = []; diff --git a/src/Module.ts b/src/Module.ts index 4fdd738f3..c9de0087a 100644 --- a/src/Module.ts +++ b/src/Module.ts @@ -770,10 +770,7 @@ export default class Module { this.transformDependencies = transformDependencies; this.customTransformCache = customTransformCache; this.updateOptions(moduleOptions); - - if (!ast) { - ast = this.tryParse(); - } + const moduleAst = ast || this.tryParse(); timeEnd('generate ast', 3); timeStart('analyze ast', 3); @@ -821,8 +818,26 @@ export default class Module { this.scope = new ModuleScope(this.graph.scope, this.astContext); this.namespace = new NamespaceVariable(this.astContext); - this.ast = new Program(ast, { context: this.astContext, type: 'Module' }, this.scope); - this.info.ast = ast; + this.ast = new Program(moduleAst, { context: this.astContext, type: 'Module' }, this.scope); + + // Assign AST directly if has existing one as there's no way to drop it from memory. + // If cache is enabled, also assign directly as otherwise it takes more CPU and memory to re-compute. + if (ast || this.options.cache !== false) { + this.info.ast = moduleAst; + } else { + // Make lazy and apply LRU cache to not hog the memory + Object.defineProperty(this.info, 'ast', { + get: () => { + if (this.graph.astLru.has(fileName)) { + return this.graph.astLru.get(fileName)!; + } else { + const parsedAst = this.tryParse(); + this.graph.astLru.set(fileName, parsedAst); + return parsedAst; + } + } + }); + } timeEnd('analyze ast', 3); } @@ -830,7 +845,7 @@ export default class Module { toJSON(): ModuleJSON { return { assertions: this.info.assertions, - ast: this.ast!.esTreeNode, + ast: this.info.ast!, code: this.info.code!, customTransformCache: this.customTransformCache, // eslint-disable-next-line unicorn/prefer-spread diff --git a/src/ModuleLoader.ts b/src/ModuleLoader.ts index 1c6f36db7..09dd56b1a 100644 --- a/src/ModuleLoader.ts +++ b/src/ModuleLoader.ts @@ -541,7 +541,7 @@ export class ModuleLoader { module, typeof dynamicImport.argument === 'string' ? dynamicImport.argument - : dynamicImport.argument.esTreeNode, + : dynamicImport.argument.esTreeNode!, module.id, getAssertionsFromImportExpression(dynamicImport.node) ); diff --git a/src/ast/nodes/ImportExpression.ts b/src/ast/nodes/ImportExpression.ts index 7a69568cd..81604c4de 100644 --- a/src/ast/nodes/ImportExpression.ts +++ b/src/ast/nodes/ImportExpression.ts @@ -14,7 +14,12 @@ import type ChildScope from '../scopes/ChildScope'; import type NamespaceVariable from '../variables/NamespaceVariable'; import type * as NodeType from './NodeType'; import type ObjectExpression from './ObjectExpression'; -import { type ExpressionNode, type IncludeChildren, NodeBase } from './shared/Node'; +import { + type ExpressionNode, + type GenericEsTreeNode, + type IncludeChildren, + NodeBase +} from './shared/Node'; interface DynamicImportMechanism { left: string; @@ -57,6 +62,11 @@ export default class ImportExpression extends NodeBase { this.context.addDynamicImport(this); } + parseNode(esTreeNode: GenericEsTreeNode): void { + // Keep the source AST to be used by renderDynamicImport + super.parseNode(esTreeNode, ['source']); + } + render(code: MagicString, options: RenderOptions): void { const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess } diff --git a/src/ast/nodes/shared/Node.ts b/src/ast/nodes/shared/Node.ts index e824f3e28..7280bd770 100644 --- a/src/ast/nodes/shared/Node.ts +++ b/src/ast/nodes/shared/Node.ts @@ -31,7 +31,7 @@ export interface Node extends Entity { annotations?: acorn.Comment[]; context: AstContext; end: number; - esTreeNode: GenericEsTreeNode; + esTreeNode: GenericEsTreeNode | null; included: boolean; keys: string[]; needsBoundaries?: boolean; @@ -119,7 +119,7 @@ export class NodeBase extends ExpressionEntity implements ExpressionNode { declare annotations?: acorn.Comment[]; context: AstContext; declare end: number; - esTreeNode: acorn.Node; + esTreeNode: acorn.Node | null; keys: string[]; parent: Node | { context: AstContext; type: string }; declare scope: ChildScope; @@ -140,10 +140,13 @@ export class NodeBase extends ExpressionEntity implements ExpressionNode { constructor( esTreeNode: GenericEsTreeNode, parent: Node | { context: AstContext; type: string }, - parentScope: ChildScope + parentScope: ChildScope, + keepEsTreeNode = false ) { super(); - this.esTreeNode = esTreeNode; + // Nodes can opt-in to keep the AST if needed during the build pipeline. + // Avoid true when possible as large AST takes up memory. + this.esTreeNode = keepEsTreeNode ? esTreeNode : null; this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode); this.parent = parent; this.context = parent.context; @@ -243,7 +246,7 @@ export class NodeBase extends ExpressionEntity implements ExpressionNode { } } - parseNode(esTreeNode: GenericEsTreeNode): void { + parseNode(esTreeNode: GenericEsTreeNode, keepEsTreeNodeKeys?: string[]): void { for (const [key, value] of Object.entries(esTreeNode)) { // That way, we can override this function to add custom initialisation and then call super.parseNode if (this.hasOwnProperty(key)) continue; @@ -262,14 +265,20 @@ export class NodeBase extends ExpressionEntity implements ExpressionNode { (this as GenericEsTreeNode)[key].push( child === null ? null - : new (this.context.getNodeConstructor(child.type))(child, this, this.scope) + : new (this.context.getNodeConstructor(child.type))( + child, + this, + this.scope, + keepEsTreeNodeKeys?.includes(key) + ) ); } } else { (this as GenericEsTreeNode)[key] = new (this.context.getNodeConstructor(value.type))( value, this, - this.scope + this.scope, + keepEsTreeNodeKeys?.includes(key) ); } } diff --git a/src/rollup/rollup.ts b/src/rollup/rollup.ts index 36c420466..73dd996d5 100644 --- a/src/rollup/rollup.ts +++ b/src/rollup/rollup.ts @@ -50,10 +50,12 @@ export async function rollupInternal( const graph = new Graph(inputOptions, watcher); - // remove the cache option from the memory after graph creation (cache is not used anymore) + // remove the cache object from the memory after graph creation (cache is not used anymore) const useCache = rawInputOptions.cache !== false; - delete inputOptions.cache; - delete rawInputOptions.cache; + if (rawInputOptions.cache) { + inputOptions.cache = undefined; + rawInputOptions.cache = undefined; + } timeStart('BUILD', 1); diff --git a/test/function/samples/plugin-module-information-no-cache/_config.js b/test/function/samples/plugin-module-information-no-cache/_config.js new file mode 100644 index 000000000..70ed68986 --- /dev/null +++ b/test/function/samples/plugin-module-information-no-cache/_config.js @@ -0,0 +1,65 @@ +const assert = require('node:assert'); +const path = require('node:path'); + +const ID_MAIN = path.join(__dirname, 'main.js'); + +module.exports = { + description: 'handles accessing module information via plugins with cache disabled', + options: { + cache: false, + plugins: [ + { + renderStart() { + const info = this.getModuleInfo(ID_MAIN); + const ast = { + type: 'Program', + start: 0, + end: 19, + body: [ + { + type: 'ExportDefaultDeclaration', + start: 0, + end: 18, + declaration: { + type: 'Literal', + start: 15, + end: 17, + value: 42, + raw: '42' + } + } + ], + sourceType: 'module' + }; + assert.deepStrictEqual(JSON.parse(JSON.stringify(info)), { + assertions: {}, + ast, + code: 'export default 42;\n', + dynamicallyImportedIdResolutions: [], + dynamicallyImportedIds: [], + dynamicImporters: [], + exportedBindings: { + '.': ['default'] + }, + exports: ['default'], + hasDefaultExport: true, + id: ID_MAIN, + implicitlyLoadedAfterOneOf: [], + implicitlyLoadedBefore: [], + importedIdResolutions: [], + importedIds: [], + importers: [], + isEntry: true, + isExternal: false, + isIncluded: true, + meta: {}, + moduleSideEffects: true, + syntheticNamedExports: false + }); + // Call AST again to ensure line coverage for cached getter + assert.deepStrictEqual(JSON.parse(JSON.stringify(info.ast)), ast); + } + } + ] + } +}; diff --git a/test/function/samples/plugin-module-information-no-cache/main.js b/test/function/samples/plugin-module-information-no-cache/main.js new file mode 100644 index 000000000..7a4e8a723 --- /dev/null +++ b/test/function/samples/plugin-module-information-no-cache/main.js @@ -0,0 +1 @@ +export default 42;