diff --git a/bin/src/run/loadConfigFile.ts b/bin/src/run/loadConfigFile.ts index f3f8444655a..5ba694161dc 100644 --- a/bin/src/run/loadConfigFile.ts +++ b/bin/src/run/loadConfigFile.ts @@ -40,9 +40,9 @@ export default function loadConfigFile( .then(({ output: [{ code }] }: RollupOutput) => { // temporarily override require const defaultLoader = require.extensions['.js']; - require.extensions['.js'] = (module: NodeModuleWithCompile, filename: string) => { + require.extensions['.js'] = (module: NodeModule, filename: string) => { if (filename === configFile) { - module._compile(code, filename); + (module as NodeModuleWithCompile)._compile(code, filename); } else { defaultLoader(module, filename); } diff --git a/src/Chunk.ts b/src/Chunk.ts index b08695446fc..c553c1ca151 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -113,7 +113,7 @@ export function isChunkRendered(chunk: Chunk): boolean { export default class Chunk { static generateFacade(graph: Graph, facadedModule: Module): Chunk { const chunk = new Chunk(graph, []); - chunk.dependencies = [facadedModule.chunk]; + chunk.dependencies = [facadedModule.chunk as Chunk]; chunk.dynamicDependencies = []; chunk.facadeModule = facadedModule; facadedModule.facadeChunk = chunk; @@ -135,13 +135,13 @@ export default class Chunk { isEmpty: boolean; manualChunkAlias: string | null = null; orderedModules: Module[]; - renderedModules: { + renderedModules?: { [moduleId: string]: RenderedModule; }; usedModules: Module[] = undefined as any; variableName: string; - private chunkName: string | void; + private chunkName?: string; private dependencies: (ExternalModule | Chunk)[] = undefined as any; private dynamicDependencies: (ExternalModule | Chunk)[] = undefined as any; private exportNames: { [name: string]: Variable } = Object.create(null); @@ -524,7 +524,7 @@ export default class Chunk { let hoistedSource = ''; - this.renderedModules = Object.create(null); + const renderedModules = (this.renderedModules = Object.create(null)); this.renderedModuleSources = []; for (let i = 0; i < this.orderedModules.length; i++) { @@ -535,7 +535,7 @@ export default class Chunk { this.renderedModuleSources.push(source); const { renderedExports, removedExports } = module.getRenderedExports(); - this.renderedModules[module.id] = { + renderedModules[module.id] = { originalLength: module.originalCode.length, removedExports, renderedExports, @@ -774,7 +774,7 @@ export default class Chunk { } let dependency: Chunk | ExternalModule; if (depModule instanceof Module) { - dependency = depModule.chunk; + dependency = depModule.chunk as Chunk; } else { if (!(depModule.used || depModule.moduleSideEffects)) { continue; @@ -820,8 +820,8 @@ export default class Chunk { for (const { node, resolution } of module.dynamicImports) { if (!resolution) continue; if (resolution instanceof Module) { - if (resolution.chunk !== this && isChunkRendered(resolution.chunk)) { - const resolutionChunk = resolution.facadeChunk || resolution.chunk; + if (resolution.chunk !== this && isChunkRendered(resolution.chunk as Chunk)) { + const resolutionChunk = resolution.facadeChunk || (resolution.chunk as Chunk); let relPath = normalize(relative(dirname(this.id), resolutionChunk.id)); if (!relPath.startsWith('../')) relPath = './' + relPath; node.renderFinalResolution(code, `'${relPath}'`, format); @@ -866,8 +866,8 @@ export default class Chunk { // skip local exports if (!module || module.chunk === this) continue; if (module instanceof Module) { - exportChunk = module.chunk; - importName = module.chunk.getVariableExportName(variable); + exportChunk = module.chunk as Chunk; + importName = exportChunk.getVariableExportName(variable); needsLiveBinding = variable.isReassigned; } else { exportChunk = module; @@ -899,7 +899,7 @@ export default class Chunk { imported: variable.module instanceof ExternalModule ? variable.name - : (variable.module as Module).chunk.getVariableExportName(variable), + : ((variable.module as Module).chunk as Chunk).getVariableExportName(variable), local: variable.getName() }); } @@ -938,7 +938,7 @@ export default class Chunk { globalName, id, // chunk id updated on render imports: imports.length > 0 ? imports : (null as any), - isChunk: !(dep as ExternalModule).isExternal, + isChunk: dep instanceof Chunk, name: dep.variableName, namedExportsMode, reexports @@ -1081,7 +1081,7 @@ export default class Chunk { if ((variable.module as Module).chunk !== this) { this.imports.add(variable); if (variable.module instanceof Module) { - variable.module.chunk.exports.add(variable); + (variable.module.chunk as Chunk).exports.add(variable); } } } @@ -1102,7 +1102,7 @@ export default class Chunk { if ((variable.module as Module).chunk !== this) { this.imports.add(variable); if (variable.module instanceof Module) { - variable.module.chunk.exports.add(variable); + (variable.module.chunk as Chunk).exports.add(variable); } } } diff --git a/src/ExternalModule.ts b/src/ExternalModule.ts index 843602d907a..80845f6b968 100644 --- a/src/ExternalModule.ts +++ b/src/ExternalModule.ts @@ -12,7 +12,6 @@ export default class ExternalModule { exportsNames = false; exportsNamespace = false; id: string; - isExternal = true; moduleSideEffects: boolean; mostCommonSuggestion = 0; nameSuggestions: { [name: string]: number }; diff --git a/src/Graph.ts b/src/Graph.ts index 605cbb8f55d..0ee15e0fb5c 100644 --- a/src/Graph.ts +++ b/src/Graph.ts @@ -79,9 +79,7 @@ export default class Graph { preserveModules: boolean; scope: GlobalScope; shimMissingExports: boolean; - // deprecated - treeshake: boolean; - treeshakingOptions: TreeshakingOptions; + treeshakingOptions?: TreeshakingOptions; watchFiles: Record = Object.create(null); private cacheExpiry: number; @@ -89,7 +87,7 @@ export default class Graph { private externalModules: ExternalModule[] = []; private modules: Module[] = []; private onwarn: WarningHandler; - private pluginCache: Record; + private pluginCache?: Record; constructor(options: InputOptions, watcher?: RollupWatcher) { this.curChunkIndex = 0; @@ -112,8 +110,7 @@ export default class Graph { this.cacheExpiry = options.experimentalCacheExpiry as number; - this.treeshake = options.treeshake !== false; - if (this.treeshake) { + if (options.treeshake !== false) { this.treeshakingOptions = options.treeshake ? { annotations: (options.treeshake as TreeshakingOptions).annotations !== false, @@ -191,10 +188,12 @@ export default class Graph { this.pluginDriver, options.external as ExternalOption, (typeof options.manualChunks === 'function' && options.manualChunks) as GetManualChunk | null, - (this.treeshake + (this.treeshakingOptions ? this.treeshakingOptions.moduleSideEffects : null) as ModuleSideEffectsOption, - (this.treeshake ? this.treeshakingOptions.pureExternalModules : false) as PureModulesOption + (this.treeshakingOptions + ? this.treeshakingOptions.pureExternalModules + : false) as PureModulesOption ); } @@ -344,7 +343,7 @@ export default class Graph { } includeMarked(modules: Module[]) { - if (this.treeshake) { + if (this.treeshakingOptions) { let treeshakingPass = 1; do { timeStart(`treeshaking pass ${treeshakingPass}`, 3); diff --git a/src/Module.ts b/src/Module.ts index 3c5d2f5d8de..8c24293c905 100644 --- a/src/Module.ts +++ b/src/Module.ts @@ -166,11 +166,11 @@ const MISSING_EXPORT_SHIM_DESCRIPTION: ExportDescription = { }; export default class Module { - chunk: Chunk; + chunk?: Chunk; chunkAlias: string = null as any; - code: string; + code!: string; comments: CommentDescription[] = []; - customTransformCache: boolean; + customTransformCache!: boolean; dependencies: (Module | ExternalModule)[] = []; dynamicallyImportedBy: Module[] = []; dynamicDependencies: (Module | ExternalModule)[] = []; @@ -193,30 +193,29 @@ export default class Module { imports = new Set(); isEntryPoint: boolean; isExecuted = false; - isExternal: false; isUserDefinedEntryPoint = false; manualChunkAlias: string = null as any; moduleSideEffects: boolean; - originalCode: string; - originalSourcemap: RawSourceMap | void; + originalCode!: string; + originalSourcemap!: RawSourceMap | void; reexports: { [name: string]: ReexportDescription } = Object.create(null); - resolvedIds: ResolvedIdMap; - scope: ModuleScope; - sourcemapChain: RawSourceMap[]; + resolvedIds!: ResolvedIdMap; + scope!: ModuleScope; + sourcemapChain!: RawSourceMap[]; sources: string[] = []; - transformAssets: Asset[]; + transformAssets?: Asset[]; usesTopLevelAwait = false; private allExportNames?: Set; - private ast: Program; - private astContext: AstContext; + private ast!: Program; + private astContext!: AstContext; private context: string; - private esTreeAst: ESTree.Program; + private esTreeAst!: ESTree.Program; private graph: Graph; - private magicString: MagicString; + private magicString!: MagicString; private namespaceVariable: NamespaceVariable = undefined as any; - private transformDependencies: string[]; - private transitiveReexports: string[]; + private transformDependencies!: string[]; + private transitiveReexports?: string[]; constructor(graph: Graph, id: string, moduleSideEffects: boolean, isEntry: boolean) { this.id = id; @@ -319,7 +318,10 @@ export default class Module { const exportNamesByVariable: Map = new Map(); for (const exportName of this.getAllExportNames()) { const tracedVariable = this.getVariableForExportName(exportName); - if (!tracedVariable || !(tracedVariable.included || tracedVariable.isExternal)) { + if ( + !tracedVariable || + !(tracedVariable.included || tracedVariable instanceof ExternalVariable) + ) { continue; } const existingExportNames = exportNamesByVariable.get(tracedVariable); @@ -464,8 +466,8 @@ export default class Module { for (const name of this.getReexports()) { const variable = this.getVariableForExportName(name); - if (variable.isExternal) { - variable.reexported = (variable as ExternalVariable).module.reexported = true; + if (variable instanceof ExternalVariable) { + variable.reexported = variable.module.reexported = true; } else if (!variable.included) { variable.include(); variable.deoptimizePath(UNKNOWN_PATH); @@ -560,7 +562,8 @@ export default class Module { addExport: this.addExport.bind(this), addImport: this.addImport.bind(this), addImportMeta: this.addImportMeta.bind(this), - annotations: (this.graph.treeshake && this.graph.treeshakingOptions.annotations) as boolean, + annotations: (this.graph.treeshakingOptions && + this.graph.treeshakingOptions.annotations) as boolean, code, // Only needed for debugging deoptimizationTracker: this.graph.deoptimizationTracker, error: this.error.bind(this), @@ -581,11 +584,11 @@ export default class Module { moduleContext: this.context, nodeConstructors, preserveModules: this.graph.preserveModules, - propertyReadSideEffects: (!this.graph.treeshake || + propertyReadSideEffects: (!this.graph.treeshakingOptions || this.graph.treeshakingOptions.propertyReadSideEffects) as boolean, traceExport: this.getVariableForExportName.bind(this), traceVariable: this.traceVariable.bind(this), - treeshake: this.graph.treeshake, + treeshake: !!this.graph.treeshakingOptions, usesTopLevelAwait: false, warn: this.warn.bind(this) }; @@ -627,8 +630,8 @@ export default class Module { const importDeclaration = this.importDescriptions[name]; const otherModule = importDeclaration.module as Module | ExternalModule; - if (!otherModule.isExternal && importDeclaration.name === '*') { - return (otherModule as Module).getOrCreateNamespace(); + if (otherModule instanceof Module && importDeclaration.name === '*') { + return (otherModule).getOrCreateNamespace(); } const declaration = otherModule.getVariableForExportName(importDeclaration.name); diff --git a/src/ModuleLoader.ts b/src/ModuleLoader.ts index bd30b79b88f..b5cf4d699f8 100644 --- a/src/ModuleLoader.ts +++ b/src/ModuleLoader.ts @@ -1,4 +1,5 @@ import * as ESTree from 'estree'; +import Chunk from './Chunk'; import ExternalModule from './ExternalModule'; import Graph from './Graph'; import Module from './Module'; @@ -10,7 +11,6 @@ import { PureModulesOption, ResolvedId, ResolveIdResult, - SourceDescription, TransformModuleJSON } from './rollup/types'; import { @@ -56,7 +56,7 @@ function getIdMatcher>( return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false; } else if (option) { const ids = new Set(Array.isArray(option) ? option : option ? [option] : []); - return id => ids.has(id); + return (id => ids.has(id)) as (id: string, ...args: T) => boolean; } else { return () => false; } @@ -211,7 +211,7 @@ export class ModuleLoader { entryRecord.module && (entryRecord.module.facadeChunk ? entryRecord.module.facadeChunk.id - : entryRecord.module.chunk.id); + : (entryRecord.module.chunk as Chunk).id); if (!fileName) return error(errChunkNotGeneratedForFileName(entryRecord)); return fileName; } @@ -221,7 +221,7 @@ export class ModuleLoader { this.isExternal(source, importer, false) ? { id: source, external: true } : this.pluginDriver.hookFirst('resolveId', [source, importer], null, skip as number) - ).then((result: ResolveIdResult) => this.normalizeResolveIdResult(result, importer, source)); + ).then(result => this.normalizeResolveIdResult(result, importer, source)); } private addToManualChunk(alias: string, module: Module) { @@ -302,9 +302,7 @@ export class ModuleLoader { } timeStart('load modules', 3); - return Promise.resolve( - this.pluginDriver.hookFirst<'load', string | SourceDescription>('load', [id]) - ) + return Promise.resolve(this.pluginDriver.hookFirst('load', [id])) .catch((err: Error) => { timeEnd('load modules', 3); let msg = `Could not load ${id}`; @@ -409,33 +407,31 @@ export class ModuleLoader { { alias, unresolvedId }: UnresolvedModuleWithAlias, isEntry: boolean ): Promise => - this.pluginDriver - .hookFirst('resolveId', [unresolvedId, undefined as any]) - .then((resolveIdResult: ResolveIdResult) => { - if ( - resolveIdResult === false || - (resolveIdResult && typeof resolveIdResult === 'object' && resolveIdResult.external) - ) { - return error(errEntryCannotBeExternal(unresolvedId)); - } - const id = - resolveIdResult && typeof resolveIdResult === 'object' - ? resolveIdResult.id - : resolveIdResult; - - if (typeof id === 'string') { - return this.fetchModule(id, undefined as any, true, isEntry).then(module => { - if (alias !== null) { - if (module.chunkAlias !== null && module.chunkAlias !== alias) { - return error(errCannotAssignModuleToChunk(module.id, alias, module.chunkAlias)); - } - module.chunkAlias = alias; + this.pluginDriver.hookFirst('resolveId', [unresolvedId, undefined]).then(resolveIdResult => { + if ( + resolveIdResult === false || + (resolveIdResult && typeof resolveIdResult === 'object' && resolveIdResult.external) + ) { + return error(errEntryCannotBeExternal(unresolvedId)); + } + const id = + resolveIdResult && typeof resolveIdResult === 'object' + ? resolveIdResult.id + : resolveIdResult; + + if (typeof id === 'string') { + return this.fetchModule(id, undefined as any, true, isEntry).then(module => { + if (alias !== null) { + if (module.chunkAlias !== null && module.chunkAlias !== alias) { + return error(errCannotAssignModuleToChunk(module.id, alias, module.chunkAlias)); } - return module; - }); - } - return error(errUnresolvedEntry(unresolvedId)); - }); + module.chunkAlias = alias; + } + return module; + }); + } + return error(errUnresolvedEntry(unresolvedId)); + }); private normalizeResolveIdResult( resolveIdResult: ResolveIdResult, @@ -502,7 +498,7 @@ export class ModuleLoader { // TODO we only should expose the acorn AST here return this.pluginDriver .hookFirst('resolveDynamicImport', [specifier, importer]) - .then((resolution: ResolveIdResult) => { + .then(resolution => { if (typeof specifier !== 'string') { if (typeof resolution === 'string') { return resolution; diff --git a/src/ast/nodes/ArrayExpression.ts b/src/ast/nodes/ArrayExpression.ts index 8976d41386f..e2c432ac6e1 100644 --- a/src/ast/nodes/ArrayExpression.ts +++ b/src/ast/nodes/ArrayExpression.ts @@ -13,8 +13,8 @@ import { ExpressionNode, NodeBase } from './shared/Node'; import SpreadElement from './SpreadElement'; export default class ArrayExpression extends NodeBase { - elements: (ExpressionNode | SpreadElement | null)[]; - type: NodeType.tArrayExpression; + elements!: (ExpressionNode | SpreadElement | null)[]; + type!: NodeType.tArrayExpression; bind() { super.bind(); diff --git a/src/ast/nodes/ArrayPattern.ts b/src/ast/nodes/ArrayPattern.ts index 411b88c020c..a4be8b707b9 100644 --- a/src/ast/nodes/ArrayPattern.ts +++ b/src/ast/nodes/ArrayPattern.ts @@ -7,8 +7,8 @@ import { NodeBase } from './shared/Node'; import { PatternNode } from './shared/Pattern'; export default class ArrayPattern extends NodeBase implements PatternNode { - elements: (PatternNode | null)[]; - type: NodeType.tArrayPattern; + elements!: (PatternNode | null)[]; + type!: NodeType.tArrayPattern; addExportedVariables(variables: Variable[]): void { for (const element of this.elements) { diff --git a/src/ast/nodes/ArrowFunctionExpression.ts b/src/ast/nodes/ArrowFunctionExpression.ts index 7f9151ee747..1ad780d7b30 100644 --- a/src/ast/nodes/ArrowFunctionExpression.ts +++ b/src/ast/nodes/ArrowFunctionExpression.ts @@ -9,11 +9,11 @@ import { ExpressionNode, GenericEsTreeNode, NodeBase } from './shared/Node'; import { PatternNode } from './shared/Pattern'; export default class ArrowFunctionExpression extends NodeBase { - body: BlockStatement | ExpressionNode; - params: PatternNode[]; - preventChildBlockScope: true; - scope: ReturnValueScope; - type: NodeType.tArrowFunctionExpression; + body!: BlockStatement | ExpressionNode; + params!: PatternNode[]; + preventChildBlockScope!: true; + scope!: ReturnValueScope; + type!: NodeType.tArrowFunctionExpression; createScope(parentScope: Scope) { this.scope = new ReturnValueScope(parentScope, this.context); @@ -58,7 +58,6 @@ export default class ArrowFunctionExpression extends NodeBase { } initialise() { - this.included = false; for (const param of this.params) { param.declare('parameter', UNKNOWN_EXPRESSION); } diff --git a/src/ast/nodes/AssignmentExpression.ts b/src/ast/nodes/AssignmentExpression.ts index 6b8f5322121..804e058c04c 100644 --- a/src/ast/nodes/AssignmentExpression.ts +++ b/src/ast/nodes/AssignmentExpression.ts @@ -9,8 +9,8 @@ import { ExpressionNode, NodeBase } from './shared/Node'; import { PatternNode } from './shared/Pattern'; export default class AssignmentExpression extends NodeBase { - left: PatternNode | ExpressionNode; - operator: + left!: PatternNode | ExpressionNode; + operator!: | '=' | '+=' | '-=' @@ -24,8 +24,8 @@ export default class AssignmentExpression extends NodeBase { | '^=' | '&=' | '**='; - right: ExpressionNode; - type: NodeType.tAssignmentExpression; + right!: ExpressionNode; + type!: NodeType.tAssignmentExpression; bind() { super.bind(); diff --git a/src/ast/nodes/AssignmentPattern.ts b/src/ast/nodes/AssignmentPattern.ts index 08923adb476..4428b9d2b42 100644 --- a/src/ast/nodes/AssignmentPattern.ts +++ b/src/ast/nodes/AssignmentPattern.ts @@ -10,9 +10,9 @@ import { ExpressionNode, NodeBase } from './shared/Node'; import { PatternNode } from './shared/Pattern'; export default class AssignmentPattern extends NodeBase implements PatternNode { - left: PatternNode; - right: ExpressionNode; - type: NodeType.tAssignmentPattern; + left!: PatternNode; + right!: ExpressionNode; + type!: NodeType.tAssignmentPattern; addExportedVariables(variables: Variable[]): void { this.left.addExportedVariables(variables); diff --git a/src/ast/nodes/AwaitExpression.ts b/src/ast/nodes/AwaitExpression.ts index 231af82bb8c..936ea75bac1 100644 --- a/src/ast/nodes/AwaitExpression.ts +++ b/src/ast/nodes/AwaitExpression.ts @@ -7,8 +7,8 @@ import FunctionNode from './shared/FunctionNode'; import { ExpressionNode, Node, NodeBase } from './shared/Node'; export default class AwaitExpression extends NodeBase { - argument: ExpressionNode; - type: NodeType.tAwaitExpression; + argument!: ExpressionNode; + type!: NodeType.tAwaitExpression; hasEffects(options: ExecutionPathOptions) { return super.hasEffects(options) || !options.ignoreReturnAwaitYield(); diff --git a/src/ast/nodes/BinaryExpression.ts b/src/ast/nodes/BinaryExpression.ts index e7cb450981a..66e657949ff 100644 --- a/src/ast/nodes/BinaryExpression.ts +++ b/src/ast/nodes/BinaryExpression.ts @@ -37,10 +37,10 @@ const binaryOperators: { }; export default class BinaryExpression extends NodeBase { - left: ExpressionNode; - operator: keyof typeof binaryOperators; - right: ExpressionNode; - type: NodeType.tBinaryExpression; + left!: ExpressionNode; + operator!: keyof typeof binaryOperators; + right!: ExpressionNode; + type!: NodeType.tBinaryExpression; getLiteralValueAtPath( path: ObjectPath, diff --git a/src/ast/nodes/BlockStatement.ts b/src/ast/nodes/BlockStatement.ts index 79fa8e8d97e..1951954fdc5 100644 --- a/src/ast/nodes/BlockStatement.ts +++ b/src/ast/nodes/BlockStatement.ts @@ -9,8 +9,8 @@ import * as NodeType from './NodeType'; import { Node, StatementBase, StatementNode } from './shared/Node'; export default class BlockStatement extends StatementBase { - body: StatementNode[]; - type: NodeType.tBlockStatement; + body!: StatementNode[]; + type!: NodeType.tBlockStatement; addImplicitReturnExpressionToScope() { const lastStatement = this.body[this.body.length - 1]; diff --git a/src/ast/nodes/BreakStatement.ts b/src/ast/nodes/BreakStatement.ts index 51d365cceb2..24b6e3c01e2 100644 --- a/src/ast/nodes/BreakStatement.ts +++ b/src/ast/nodes/BreakStatement.ts @@ -4,8 +4,8 @@ import * as NodeType from './NodeType'; import { StatementBase } from './shared/Node'; export default class BreakStatement extends StatementBase { - label: Identifier | null; - type: NodeType.tBreakStatement; + label!: Identifier | null; + type!: NodeType.tBreakStatement; hasEffects(options: ExecutionPathOptions) { return ( diff --git a/src/ast/nodes/CallExpression.ts b/src/ast/nodes/CallExpression.ts index c25d203dfbc..29ef44ff584 100644 --- a/src/ast/nodes/CallExpression.ts +++ b/src/ast/nodes/CallExpression.ts @@ -24,14 +24,14 @@ import SpreadElement from './SpreadElement'; export default class CallExpression extends NodeBase implements DeoptimizableEntity { annotatedPure?: boolean; - arguments: (ExpressionNode | SpreadElement)[]; - callee: ExpressionNode; - type: NodeType.tCallExpression; + arguments!: (ExpressionNode | SpreadElement)[]; + callee!: ExpressionNode; + type!: NodeType.tCallExpression; - private callOptions: CallOptions; + private callOptions!: CallOptions; // We collect deoptimization information if returnExpression !== UNKNOWN_EXPRESSION - private expressionsToBeDeoptimized: DeoptimizableEntity[]; - private returnExpression: ExpressionEntity | null; + private expressionsToBeDeoptimized: DeoptimizableEntity[] = []; + private returnExpression: ExpressionEntity | null = null; bind() { super.bind(); @@ -204,14 +204,11 @@ export default class CallExpression extends NodeBase implements DeoptimizableEnt } initialise() { - this.included = false; - this.returnExpression = null; this.callOptions = CallOptions.create({ args: this.arguments, callIdentifier: this, withNew: false }); - this.expressionsToBeDeoptimized = []; } render( diff --git a/src/ast/nodes/CatchClause.ts b/src/ast/nodes/CatchClause.ts index 9d6b0cb10f6..c7885e8ab80 100644 --- a/src/ast/nodes/CatchClause.ts +++ b/src/ast/nodes/CatchClause.ts @@ -7,19 +7,17 @@ import { GenericEsTreeNode, NodeBase } from './shared/Node'; import { PatternNode } from './shared/Pattern'; export default class CatchClause extends NodeBase { - body: BlockStatement; - param: PatternNode | null; - preventChildBlockScope: true; - scope: CatchScope; - type: NodeType.tCatchClause; + body!: BlockStatement; + param!: PatternNode | null; + preventChildBlockScope!: true; + scope!: CatchScope; + type!: NodeType.tCatchClause; createScope(parentScope: Scope) { this.scope = new CatchScope(parentScope, this.context); } initialise() { - this.included = false; - if (this.param) { this.param.declare('parameter', UNKNOWN_EXPRESSION); } diff --git a/src/ast/nodes/ClassBody.ts b/src/ast/nodes/ClassBody.ts index d0b9e6aa590..c6cf7d4e559 100644 --- a/src/ast/nodes/ClassBody.ts +++ b/src/ast/nodes/ClassBody.ts @@ -6,10 +6,10 @@ import * as NodeType from './NodeType'; import { NodeBase } from './shared/Node'; export default class ClassBody extends NodeBase { - body: MethodDefinition[]; - type: NodeType.tClassBody; + body!: MethodDefinition[]; + type!: NodeType.tClassBody; - private classConstructor: MethodDefinition | null; + private classConstructor!: MethodDefinition | null; hasEffectsWhenCalledAtPath( path: ObjectPath, @@ -26,7 +26,6 @@ export default class ClassBody extends NodeBase { } initialise() { - this.included = false; for (const method of this.body) { if (method.kind === 'constructor') { this.classConstructor = method; diff --git a/src/ast/nodes/ClassDeclaration.ts b/src/ast/nodes/ClassDeclaration.ts index 42207d580a7..a1bb9abbc4f 100644 --- a/src/ast/nodes/ClassDeclaration.ts +++ b/src/ast/nodes/ClassDeclaration.ts @@ -7,8 +7,8 @@ import ClassNode from './shared/ClassNode'; import { GenericEsTreeNode } from './shared/Node'; export default class ClassDeclaration extends ClassNode { - id: IdentifierWithVariable | null; - type: NodeType.tClassDeclaration; + id!: IdentifierWithVariable | null; + type!: NodeType.tClassDeclaration; initialise() { super.initialise(); diff --git a/src/ast/nodes/ClassExpression.ts b/src/ast/nodes/ClassExpression.ts index 54fa77af5f4..6d9effd2dda 100644 --- a/src/ast/nodes/ClassExpression.ts +++ b/src/ast/nodes/ClassExpression.ts @@ -2,5 +2,5 @@ import * as NodeType from './NodeType'; import ClassNode from './shared/ClassNode'; export default class ClassExpression extends ClassNode { - type: NodeType.tClassExpression; + type!: NodeType.tClassExpression; } diff --git a/src/ast/nodes/ConditionalExpression.ts b/src/ast/nodes/ConditionalExpression.ts index 8b5a5688a34..6d31e4251f3 100644 --- a/src/ast/nodes/ConditionalExpression.ts +++ b/src/ast/nodes/ConditionalExpression.ts @@ -23,16 +23,16 @@ import { MultiExpression } from './shared/MultiExpression'; import { ExpressionNode, NodeBase } from './shared/Node'; export default class ConditionalExpression extends NodeBase implements DeoptimizableEntity { - alternate: ExpressionNode; - consequent: ExpressionNode; - test: ExpressionNode; - type: NodeType.tConditionalExpression; + alternate!: ExpressionNode; + consequent!: ExpressionNode; + test!: ExpressionNode; + type!: NodeType.tConditionalExpression; // We collect deoptimization information if usedBranch !== null - private expressionsToBeDeoptimized: DeoptimizableEntity[]; - private isBranchResolutionAnalysed: boolean; - private unusedBranch: ExpressionNode | null; - private usedBranch: ExpressionNode | null; + private expressionsToBeDeoptimized: DeoptimizableEntity[] = []; + private isBranchResolutionAnalysed = false; + private unusedBranch: ExpressionNode | null = null; + private usedBranch: ExpressionNode | null = null; bind() { super.bind(); @@ -144,14 +144,6 @@ export default class ConditionalExpression extends NodeBase implements Deoptimiz } } - initialise() { - this.included = false; - this.isBranchResolutionAnalysed = false; - this.usedBranch = null; - this.unusedBranch = null; - this.expressionsToBeDeoptimized = []; - } - render( code: MagicString, options: RenderOptions, diff --git a/src/ast/nodes/DoWhileStatement.ts b/src/ast/nodes/DoWhileStatement.ts index 807fe3eb08a..8d4eac9c8ba 100644 --- a/src/ast/nodes/DoWhileStatement.ts +++ b/src/ast/nodes/DoWhileStatement.ts @@ -3,9 +3,9 @@ import * as NodeType from './NodeType'; import { ExpressionNode, StatementBase, StatementNode } from './shared/Node'; export default class DoWhileStatement extends StatementBase { - body: StatementNode; - test: ExpressionNode; - type: NodeType.tDoWhileStatement; + body!: StatementNode; + test!: ExpressionNode; + type!: NodeType.tDoWhileStatement; hasEffects(options: ExecutionPathOptions): boolean { return ( diff --git a/src/ast/nodes/EmptyStatement.ts b/src/ast/nodes/EmptyStatement.ts index fca9f6ce0c4..7021b32d7ab 100644 --- a/src/ast/nodes/EmptyStatement.ts +++ b/src/ast/nodes/EmptyStatement.ts @@ -2,7 +2,7 @@ import * as NodeType from './NodeType'; import { StatementBase } from './shared/Node'; export default class EmptyStatement extends StatementBase { - type: NodeType.tEmptyStatement; + type!: NodeType.tEmptyStatement; hasEffects(): boolean { return false; diff --git a/src/ast/nodes/ExportAllDeclaration.ts b/src/ast/nodes/ExportAllDeclaration.ts index db9cb969051..6d94846222e 100644 --- a/src/ast/nodes/ExportAllDeclaration.ts +++ b/src/ast/nodes/ExportAllDeclaration.ts @@ -6,16 +6,15 @@ import * as NodeType from './NodeType'; import { NodeBase } from './shared/Node'; export default class ExportAllDeclaration extends NodeBase { - needsBoundaries: true; - source: Literal; - type: NodeType.tExportAllDeclaration; + needsBoundaries!: true; + source!: Literal; + type!: NodeType.tExportAllDeclaration; hasEffects() { return false; } initialise() { - this.included = false; this.context.addExport(this); } diff --git a/src/ast/nodes/ExportDefaultDeclaration.ts b/src/ast/nodes/ExportDefaultDeclaration.ts index d266878444d..6493009027d 100644 --- a/src/ast/nodes/ExportDefaultDeclaration.ts +++ b/src/ast/nodes/ExportDefaultDeclaration.ts @@ -35,13 +35,13 @@ function getIdInsertPosition(code: string, declarationKeyword: string, start = 0 } export default class ExportDefaultDeclaration extends NodeBase { - declaration: FunctionDeclaration | ClassDeclaration | ExpressionNode; - needsBoundaries: true; - scope: ModuleScope; - type: NodeType.tExportDefaultDeclaration; - variable: ExportDefaultVariable; + declaration!: FunctionDeclaration | ClassDeclaration | ExpressionNode; + needsBoundaries!: true; + scope!: ModuleScope; + type!: NodeType.tExportDefaultDeclaration; + variable!: ExportDefaultVariable; - private declarationName: string; + private declarationName: string | undefined; include(includeAllChildrenRecursively: boolean) { super.include(includeAllChildrenRecursively); @@ -51,7 +51,6 @@ export default class ExportDefaultDeclaration extends NodeBase { } initialise() { - this.included = false; const declaration = this.declaration as FunctionDeclaration | ClassDeclaration; this.declarationName = (declaration.id && declaration.id.name) || (this.declaration as Identifier).name; diff --git a/src/ast/nodes/ExportNamedDeclaration.ts b/src/ast/nodes/ExportNamedDeclaration.ts index 26529c7d336..fbb90c3692e 100644 --- a/src/ast/nodes/ExportNamedDeclaration.ts +++ b/src/ast/nodes/ExportNamedDeclaration.ts @@ -11,11 +11,11 @@ import { Node, NodeBase } from './shared/Node'; import VariableDeclaration from './VariableDeclaration'; export default class ExportNamedDeclaration extends NodeBase { - declaration: FunctionDeclaration | ClassDeclaration | VariableDeclaration | null; - needsBoundaries: true; - source: Literal | null; - specifiers: ExportSpecifier[]; - type: NodeType.tExportNamedDeclaration; + declaration!: FunctionDeclaration | ClassDeclaration | VariableDeclaration | null; + needsBoundaries!: true; + source!: Literal | null; + specifiers!: ExportSpecifier[]; + type!: NodeType.tExportNamedDeclaration; bind() { // Do not bind specifiers @@ -27,7 +27,6 @@ export default class ExportNamedDeclaration extends NodeBase { } initialise() { - this.included = false; this.context.addExport(this); } diff --git a/src/ast/nodes/ExpressionStatement.ts b/src/ast/nodes/ExpressionStatement.ts index a9def0969cb..de4aa1d8a7d 100644 --- a/src/ast/nodes/ExpressionStatement.ts +++ b/src/ast/nodes/ExpressionStatement.ts @@ -5,10 +5,9 @@ import { ExpressionNode, StatementBase } from './shared/Node'; export default class ExpressionStatement extends StatementBase { directive?: string; - expression: ExpressionNode; + expression!: ExpressionNode; initialise() { - this.included = false; if ( this.directive && this.directive !== 'use strict' && diff --git a/src/ast/nodes/ForInStatement.ts b/src/ast/nodes/ForInStatement.ts index 3dcb9cd0ed7..192531f7a77 100644 --- a/src/ast/nodes/ForInStatement.ts +++ b/src/ast/nodes/ForInStatement.ts @@ -10,10 +10,10 @@ import { PatternNode } from './shared/Pattern'; import VariableDeclaration from './VariableDeclaration'; export default class ForInStatement extends StatementBase { - body: StatementNode; - left: VariableDeclaration | PatternNode; - right: ExpressionNode; - type: NodeType.tForInStatement; + body!: StatementNode; + left!: VariableDeclaration | PatternNode; + right!: ExpressionNode; + type!: NodeType.tForInStatement; bind() { this.left.bind(); diff --git a/src/ast/nodes/ForOfStatement.ts b/src/ast/nodes/ForOfStatement.ts index 15599acc6a2..3bbbe76bd26 100644 --- a/src/ast/nodes/ForOfStatement.ts +++ b/src/ast/nodes/ForOfStatement.ts @@ -10,11 +10,11 @@ import { PatternNode } from './shared/Pattern'; import VariableDeclaration from './VariableDeclaration'; export default class ForOfStatement extends StatementBase { - await: boolean; - body: StatementNode; - left: VariableDeclaration | PatternNode; - right: ExpressionNode; - type: NodeType.tForOfStatement; + await!: boolean; + body!: StatementNode; + left!: VariableDeclaration | PatternNode; + right!: ExpressionNode; + type!: NodeType.tForOfStatement; bind() { this.left.bind(); diff --git a/src/ast/nodes/ForStatement.ts b/src/ast/nodes/ForStatement.ts index dc8c283982b..a6d633491aa 100644 --- a/src/ast/nodes/ForStatement.ts +++ b/src/ast/nodes/ForStatement.ts @@ -8,11 +8,11 @@ import { ExpressionNode, StatementBase, StatementNode } from './shared/Node'; import VariableDeclaration from './VariableDeclaration'; export default class ForStatement extends StatementBase { - body: StatementNode; - init: VariableDeclaration | ExpressionNode | null; - test: ExpressionNode | null; - type: NodeType.tForStatement; - update: ExpressionNode | null; + body!: StatementNode; + init!: VariableDeclaration | ExpressionNode | null; + test!: ExpressionNode | null; + type!: NodeType.tForStatement; + update!: ExpressionNode | null; createScope(parentScope: Scope) { this.scope = new BlockScope(parentScope); diff --git a/src/ast/nodes/FunctionDeclaration.ts b/src/ast/nodes/FunctionDeclaration.ts index 8eb6af0d413..a02561dc7c7 100644 --- a/src/ast/nodes/FunctionDeclaration.ts +++ b/src/ast/nodes/FunctionDeclaration.ts @@ -5,7 +5,7 @@ import FunctionNode from './shared/FunctionNode'; import { GenericEsTreeNode } from './shared/Node'; export default class FunctionDeclaration extends FunctionNode { - type: NodeType.tFunctionDeclaration; + type!: NodeType.tFunctionDeclaration; initialise() { super.initialise(); diff --git a/src/ast/nodes/FunctionExpression.ts b/src/ast/nodes/FunctionExpression.ts index 4bb01ffb53a..999126de59c 100644 --- a/src/ast/nodes/FunctionExpression.ts +++ b/src/ast/nodes/FunctionExpression.ts @@ -2,5 +2,5 @@ import * as NodeType from './NodeType'; import FunctionNode from './shared/FunctionNode'; export default class FunctionExpression extends FunctionNode { - type: NodeType.tFunctionExpression; + type!: NodeType.tFunctionExpression; } diff --git a/src/ast/nodes/Identifier.ts b/src/ast/nodes/Identifier.ts index cbea7bbd66e..b5d23860f27 100644 --- a/src/ast/nodes/Identifier.ts +++ b/src/ast/nodes/Identifier.ts @@ -18,11 +18,11 @@ import { PatternNode } from './shared/Pattern'; export type IdentifierWithVariable = Identifier & { variable: Variable }; export default class Identifier extends NodeBase implements PatternNode { - name: string; - type: NodeType.tIdentifier; + name!: string; + type!: NodeType.tIdentifier; - variable: Variable | null; - private bound: boolean; + variable: Variable | null = null; + private bound = false; addExportedVariables(variables: Variable[]): void { if (this.variable !== null && this.variable.exportName) { @@ -39,10 +39,10 @@ export default class Identifier extends NodeBase implements PatternNode { } if ( this.variable !== null && - (this.variable as LocalVariable).isLocal && - (this.variable as LocalVariable).additionalInitializers !== null + this.variable instanceof LocalVariable && + this.variable.additionalInitializers !== null ) { - (this.variable as LocalVariable).consolidateInitializers(); + this.variable.consolidateInitializers(); } } @@ -128,15 +128,6 @@ export default class Identifier extends NodeBase implements PatternNode { } } - initialise() { - this.included = false; - this.bound = false; - // To avoid later shape mutations - if (!this.variable) { - this.variable = null; - } - } - render( code: MagicString, _options: RenderOptions, diff --git a/src/ast/nodes/IfStatement.ts b/src/ast/nodes/IfStatement.ts index 1233c66932a..9a1b1301bda 100644 --- a/src/ast/nodes/IfStatement.ts +++ b/src/ast/nodes/IfStatement.ts @@ -9,12 +9,12 @@ import * as NodeType from './NodeType'; import { ExpressionNode, StatementBase, StatementNode } from './shared/Node'; export default class IfStatement extends StatementBase implements DeoptimizableEntity { - alternate: StatementNode | null; - consequent: StatementNode; - test: ExpressionNode; - type: NodeType.tIfStatement; + alternate!: StatementNode | null; + consequent!: StatementNode; + test!: ExpressionNode; + type!: NodeType.tIfStatement; - private isTestValueAnalysed: boolean; + private isTestValueAnalysed = false; private testValue: LiteralValueOrUnknown; bind() { @@ -68,11 +68,6 @@ export default class IfStatement extends StatementBase implements DeoptimizableE } } - initialise() { - this.included = false; - this.isTestValueAnalysed = false; - } - render(code: MagicString, options: RenderOptions) { // Note that unknown test values are always included if ( diff --git a/src/ast/nodes/Import.ts b/src/ast/nodes/Import.ts index fba12dab55e..e5a147de1c5 100644 --- a/src/ast/nodes/Import.ts +++ b/src/ast/nodes/Import.ts @@ -54,11 +54,11 @@ const accessedImportGlobals = { }; export default class Import extends NodeBase { - parent: CallExpression; - type: NodeType.tImport; + parent!: CallExpression; + type!: NodeType.tImport; - private resolutionInterop: boolean; - private resolutionNamespace: string; + private resolutionInterop = false; + private resolutionNamespace?: string; include() { if (!this.included) { @@ -69,9 +69,6 @@ export default class Import extends NodeBase { } initialise() { - this.included = false; - this.resolutionNamespace = undefined as any; - this.resolutionInterop = false; this.context.addDynamicImport(this); } diff --git a/src/ast/nodes/ImportDeclaration.ts b/src/ast/nodes/ImportDeclaration.ts index ce7f375712f..9184317c964 100644 --- a/src/ast/nodes/ImportDeclaration.ts +++ b/src/ast/nodes/ImportDeclaration.ts @@ -9,10 +9,10 @@ import * as NodeType from './NodeType'; import { NodeBase } from './shared/Node'; export default class ImportDeclaration extends NodeBase { - needsBoundaries: true; - source: Literal; - specifiers: (ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier)[]; - type: NodeType.tImportDeclaration; + needsBoundaries!: true; + source!: Literal; + specifiers!: (ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier)[]; + type!: NodeType.tImportDeclaration; bind() {} @@ -21,7 +21,6 @@ export default class ImportDeclaration extends NodeBase { } initialise() { - this.included = false; this.context.addImport(this); } diff --git a/src/ast/nodes/LabeledStatement.ts b/src/ast/nodes/LabeledStatement.ts index 9a670f49951..9a2e7b8d5a3 100644 --- a/src/ast/nodes/LabeledStatement.ts +++ b/src/ast/nodes/LabeledStatement.ts @@ -4,9 +4,9 @@ import * as NodeType from './NodeType'; import { StatementBase, StatementNode } from './shared/Node'; export default class LabeledStatement extends StatementBase { - body: StatementNode; - label: Identifier; - type: NodeType.tLabeledStatement; + body!: StatementNode; + label!: Identifier; + type!: NodeType.tLabeledStatement; hasEffects(options: ExecutionPathOptions) { return this.body.hasEffects(options.setIgnoreLabel(this.label.name).setIgnoreBreakStatements()); diff --git a/src/ast/nodes/Literal.ts b/src/ast/nodes/Literal.ts index 0130868a7a7..5f423880cd1 100644 --- a/src/ast/nodes/Literal.ts +++ b/src/ast/nodes/Literal.ts @@ -18,10 +18,10 @@ import { NodeBase } from './shared/Node'; export type LiteralValue = string | boolean | null | number | RegExp | undefined; export default class Literal extends NodeBase { - type: NodeType.tLiteral; - value: T; + type!: NodeType.tLiteral; + value!: T; - private members: { [key: string]: MemberDescription }; + private members!: { [key: string]: MemberDescription }; getLiteralValueAtPath(path: ObjectPath): LiteralValueOrUnknown { if ( @@ -63,7 +63,6 @@ export default class Literal extends NodeBase { } initialise() { - this.included = false; this.members = getLiteralMembersForValue(this.value); } diff --git a/src/ast/nodes/LogicalExpression.ts b/src/ast/nodes/LogicalExpression.ts index 04c7b9ec05c..d3de85a8381 100644 --- a/src/ast/nodes/LogicalExpression.ts +++ b/src/ast/nodes/LogicalExpression.ts @@ -25,16 +25,16 @@ import { ExpressionNode, NodeBase } from './shared/Node'; export type LogicalOperator = '||' | '&&'; export default class LogicalExpression extends NodeBase implements DeoptimizableEntity { - left: ExpressionNode; - operator: LogicalOperator; - right: ExpressionNode; - type: NodeType.tLogicalExpression; + left!: ExpressionNode; + operator!: LogicalOperator; + right!: ExpressionNode; + type!: NodeType.tLogicalExpression; // We collect deoptimization information if usedBranch !== null - private expressionsToBeDeoptimized: DeoptimizableEntity[]; - private isBranchResolutionAnalysed: boolean; - private unusedBranch: ExpressionNode | null; - private usedBranch: ExpressionNode | null; + private expressionsToBeDeoptimized: DeoptimizableEntity[] = []; + private isBranchResolutionAnalysed = false; + private unusedBranch: ExpressionNode | null = null; + private usedBranch: ExpressionNode | null = null; bind() { super.bind(); @@ -148,14 +148,6 @@ export default class LogicalExpression extends NodeBase implements Deoptimizable } } - initialise() { - this.included = false; - this.isBranchResolutionAnalysed = false; - this.usedBranch = null; - this.unusedBranch = null; - this.expressionsToBeDeoptimized = []; - } - render( code: MagicString, options: RenderOptions, diff --git a/src/ast/nodes/MemberExpression.ts b/src/ast/nodes/MemberExpression.ts index 31010a3834c..0cae867c9ae 100644 --- a/src/ast/nodes/MemberExpression.ts +++ b/src/ast/nodes/MemberExpression.ts @@ -70,16 +70,16 @@ function getStringFromPath(path: PathWithPositions): string { } export default class MemberExpression extends NodeBase implements DeoptimizableEntity, PatternNode { - computed: boolean; - object: ExpressionNode; - property: ExpressionNode; - propertyKey: ObjectPathKey | null; - type: NodeType.tMemberExpression; - variable: Variable = null as any; + computed!: boolean; + object!: ExpressionNode; + property!: ExpressionNode; + propertyKey!: ObjectPathKey | null; + type!: NodeType.tMemberExpression; + variable: Variable | null = null; - private bound: boolean; - private expressionsToBeDeoptimized: DeoptimizableEntity[]; - private replacement: string | null; + private bound = false; + private expressionsToBeDeoptimized: DeoptimizableEntity[] = []; + private replacement: string | null = null; addExportedVariables(): void {} @@ -98,10 +98,8 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE } else if (typeof resolvedVariable === 'string') { this.replacement = resolvedVariable; } else { - if (resolvedVariable.isExternal && (resolvedVariable as ExternalVariable).module) { - (resolvedVariable as ExternalVariable).module.suggestName( - (path as PathWithPositions)[0].key - ); + if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) { + resolvedVariable.module.suggestName((path as PathWithPositions)[0].key); } this.variable = resolvedVariable; this.scope.addNamespaceMemberAccess( @@ -225,12 +223,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE } initialise() { - this.included = false; this.propertyKey = getResolvablePropertyKey(this); - this.variable = null as any; - this.bound = false; - this.replacement = null; - this.expressionsToBeDeoptimized = []; } render( @@ -283,13 +276,15 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE if (path.length === 0) return baseVariable; if (!baseVariable.isNamespace) return null; const exportName = path[0].key; - const variable = baseVariable.isExternal - ? (baseVariable as ExternalVariable).module.getVariableForExportName(exportName) - : (baseVariable as NamespaceVariable).context.traceExport(exportName); + const variable = + baseVariable instanceof ExternalVariable + ? baseVariable.module.getVariableForExportName(exportName) + : (baseVariable as NamespaceVariable).context.traceExport(exportName); if (!variable) { - const fileName = baseVariable.isExternal - ? (baseVariable as ExternalVariable).module.id - : (baseVariable as NamespaceVariable).context.fileName; + const fileName = + baseVariable instanceof ExternalVariable + ? baseVariable.module.id + : (baseVariable as NamespaceVariable).context.fileName; this.context.warn( { code: 'MISSING_EXPORT', diff --git a/src/ast/nodes/MetaProperty.ts b/src/ast/nodes/MetaProperty.ts index a3833e11f28..9a159ebc5fc 100644 --- a/src/ast/nodes/MetaProperty.ts +++ b/src/ast/nodes/MetaProperty.ts @@ -12,9 +12,9 @@ const ASSET_PREFIX = 'ROLLUP_ASSET_URL_'; const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_'; export default class MetaProperty extends NodeBase { - meta: Identifier; - property: Identifier; - type: NodeType.tMetaProperty; + meta!: Identifier; + property!: Identifier; + type!: NodeType.tMetaProperty; private metaProperty?: string | null; @@ -44,7 +44,6 @@ export default class MetaProperty extends NodeBase { if (this.meta.name === 'import') { this.context.addImportMeta(this); } - this.included = false; } renderFinalMechanism( diff --git a/src/ast/nodes/MethodDefinition.ts b/src/ast/nodes/MethodDefinition.ts index 156466e80e7..5fca36e5fc1 100644 --- a/src/ast/nodes/MethodDefinition.ts +++ b/src/ast/nodes/MethodDefinition.ts @@ -6,12 +6,12 @@ import * as NodeType from './NodeType'; import { ExpressionNode, NodeBase } from './shared/Node'; export default class MethodDefinition extends NodeBase { - computed: boolean; - key: ExpressionNode; - kind: 'constructor' | 'method' | 'get' | 'set'; - static: boolean; - type: NodeType.tMethodDefinition; - value: FunctionExpression; + computed!: boolean; + key!: ExpressionNode; + kind!: 'constructor' | 'method' | 'get' | 'set'; + static!: boolean; + type!: NodeType.tMethodDefinition; + value!: FunctionExpression; hasEffects(options: ExecutionPathOptions) { return this.key.hasEffects(options); diff --git a/src/ast/nodes/NewExpression.ts b/src/ast/nodes/NewExpression.ts index 12563d61807..ea5c69813b8 100644 --- a/src/ast/nodes/NewExpression.ts +++ b/src/ast/nodes/NewExpression.ts @@ -6,11 +6,11 @@ import { ExpressionNode, NodeBase } from './shared/Node'; export default class NewExpression extends NodeBase { annotatedPure?: boolean; - arguments: ExpressionNode[]; - callee: ExpressionNode; - type: NodeType.tNewExpression; + arguments!: ExpressionNode[]; + callee!: ExpressionNode; + type!: NodeType.tNewExpression; - private callOptions: CallOptions; + private callOptions!: CallOptions; bind() { super.bind(); @@ -37,7 +37,6 @@ export default class NewExpression extends NodeBase { } initialise() { - this.included = false; this.callOptions = CallOptions.create({ args: this.arguments, callIdentifier: this, diff --git a/src/ast/nodes/ObjectExpression.ts b/src/ast/nodes/ObjectExpression.ts index cc32ad54df0..666330c4021 100644 --- a/src/ast/nodes/ObjectExpression.ts +++ b/src/ast/nodes/ObjectExpression.ts @@ -37,16 +37,16 @@ interface PropertyMap { } export default class ObjectExpression extends NodeBase { - properties: (Property | SpreadElement)[]; - type: NodeType.tObjectExpression; + properties!: (Property | SpreadElement)[]; + type!: NodeType.tObjectExpression; private deoptimizedPaths = new Set(); // We collect deoptimization information if we can resolve a computed property access private expressionsToBeDeoptimized = new Map(); private hasUnknownDeoptimizedProperty = false; private propertyMap: PropertyMap | null = null; - private unmatchablePropertiesRead: (Property | SpreadElement)[] | null; - private unmatchablePropertiesWrite: Property[] | null; + private unmatchablePropertiesRead: (Property | SpreadElement)[] = []; + private unmatchablePropertiesWrite: Property[] = []; bind() { super.bind(); @@ -114,7 +114,7 @@ export default class ObjectExpression extends NodeBase { path.length === 1 && !(this.propertyMap as PropertyMap)[key] && !objectMembers[key] && - (this.unmatchablePropertiesRead as (Property | SpreadElement)[]).length === 0 + (this.unmatchablePropertiesRead).length === 0 ) { const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key); if (expressionsToBeDeoptimized) { @@ -162,7 +162,7 @@ export default class ObjectExpression extends NodeBase { if ( path.length === 1 && objectMembers[key] && - this.unmatchablePropertiesRead!.length === 0 && + this.unmatchablePropertiesRead.length === 0 && (!(this.propertyMap as PropertyMap)[key] || (this.propertyMap as PropertyMap)[key].exactMatchRead === null) ) @@ -266,10 +266,6 @@ export default class ObjectExpression extends NodeBase { return false; } - initialise() { - this.included = false; - } - render( code: MagicString, options: RenderOptions, @@ -284,8 +280,6 @@ export default class ObjectExpression extends NodeBase { private buildPropertyMap() { this.propertyMap = Object.create(null); - this.unmatchablePropertiesRead = []; - this.unmatchablePropertiesWrite = []; for (let index = this.properties.length - 1; index >= 0; index--) { const property = this.properties[index]; if (property instanceof SpreadElement) { diff --git a/src/ast/nodes/ObjectPattern.ts b/src/ast/nodes/ObjectPattern.ts index 6752f990c77..d72ba408714 100644 --- a/src/ast/nodes/ObjectPattern.ts +++ b/src/ast/nodes/ObjectPattern.ts @@ -9,8 +9,8 @@ import { NodeBase } from './shared/Node'; import { PatternNode } from './shared/Pattern'; export default class ObjectPattern extends NodeBase implements PatternNode { - properties: (Property | RestElement)[]; - type: NodeType.tObjectPattern; + properties!: (Property | RestElement)[]; + type!: NodeType.tObjectPattern; addExportedVariables(variables: Variable[]): void { for (const property of this.properties) { diff --git a/src/ast/nodes/Program.ts b/src/ast/nodes/Program.ts index f2ad851e9a9..078d265ab67 100644 --- a/src/ast/nodes/Program.ts +++ b/src/ast/nodes/Program.ts @@ -5,9 +5,9 @@ import * as NodeType from './NodeType'; import { NodeBase, StatementNode } from './shared/Node'; export default class Program extends NodeBase { - body: StatementNode[]; - sourceType: 'module'; - type: NodeType.tProgram; + body!: StatementNode[]; + sourceType!: 'module'; + type!: NodeType.tProgram; hasEffects(options: ExecutionPathOptions) { for (const node of this.body) { diff --git a/src/ast/nodes/Property.ts b/src/ast/nodes/Property.ts index a6b283a477d..1fa9d60912a 100644 --- a/src/ast/nodes/Property.ts +++ b/src/ast/nodes/Property.ts @@ -20,17 +20,17 @@ import { ExpressionEntity } from './shared/Expression'; import { ExpressionNode, NodeBase } from './shared/Node'; export default class Property extends NodeBase implements DeoptimizableEntity { - computed: boolean; - key: ExpressionNode; - kind: 'init' | 'get' | 'set'; - method: boolean; - shorthand: boolean; - type: NodeType.tProperty; - value: ExpressionNode; + computed!: boolean; + key!: ExpressionNode; + kind!: 'init' | 'get' | 'set'; + method!: boolean; + shorthand!: boolean; + type!: NodeType.tProperty; + value!: ExpressionNode; - private accessorCallOptions: CallOptions; + private accessorCallOptions!: CallOptions; private declarationInit: ExpressionEntity | null = null; - private returnExpression: ExpressionEntity | null; + private returnExpression: ExpressionEntity | null = null; bind() { super.bind(); @@ -155,8 +155,6 @@ export default class Property extends NodeBase implements DeoptimizableEntity { } initialise() { - this.included = false; - this.returnExpression = null; this.accessorCallOptions = CallOptions.create({ callIdentifier: this, withNew: false diff --git a/src/ast/nodes/RestElement.ts b/src/ast/nodes/RestElement.ts index 11696ac2f4c..6927f9865c3 100644 --- a/src/ast/nodes/RestElement.ts +++ b/src/ast/nodes/RestElement.ts @@ -7,8 +7,8 @@ import { NodeBase } from './shared/Node'; import { PatternNode } from './shared/Pattern'; export default class RestElement extends NodeBase implements PatternNode { - argument: PatternNode; - type: NodeType.tRestElement; + argument!: PatternNode; + type!: NodeType.tRestElement; private declarationInit: ExpressionEntity | null = null; diff --git a/src/ast/nodes/ReturnStatement.ts b/src/ast/nodes/ReturnStatement.ts index c456fc9983b..d8f41c8370e 100644 --- a/src/ast/nodes/ReturnStatement.ts +++ b/src/ast/nodes/ReturnStatement.ts @@ -6,8 +6,8 @@ import * as NodeType from './NodeType'; import { ExpressionNode, StatementBase } from './shared/Node'; export default class ReturnStatement extends StatementBase { - argument: ExpressionNode | null; - type: NodeType.tReturnStatement; + argument!: ExpressionNode | null; + type!: NodeType.tReturnStatement; hasEffects(options: ExecutionPathOptions) { return ( @@ -17,7 +17,6 @@ export default class ReturnStatement extends StatementBase { } initialise() { - this.included = false; this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION); } diff --git a/src/ast/nodes/SequenceExpression.ts b/src/ast/nodes/SequenceExpression.ts index d409e095243..9f3c267ce84 100644 --- a/src/ast/nodes/SequenceExpression.ts +++ b/src/ast/nodes/SequenceExpression.ts @@ -16,8 +16,8 @@ import * as NodeType from './NodeType'; import { ExpressionNode, NodeBase } from './shared/Node'; export default class SequenceExpression extends NodeBase { - expressions: ExpressionNode[]; - type: NodeType.tSequenceExpression; + expressions!: ExpressionNode[]; + type!: NodeType.tSequenceExpression; deoptimizePath(path: ObjectPath) { if (path.length > 0) this.expressions[this.expressions.length - 1].deoptimizePath(path); diff --git a/src/ast/nodes/SpreadElement.ts b/src/ast/nodes/SpreadElement.ts index 0d37012cb9e..2ddbcffbac0 100644 --- a/src/ast/nodes/SpreadElement.ts +++ b/src/ast/nodes/SpreadElement.ts @@ -3,8 +3,8 @@ import * as NodeType from './NodeType'; import { ExpressionNode, NodeBase } from './shared/Node'; export default class SpreadElement extends NodeBase { - argument: ExpressionNode; - type: NodeType.tSpreadElement; + argument!: ExpressionNode; + type!: NodeType.tSpreadElement; bind() { super.bind(); diff --git a/src/ast/nodes/SwitchCase.ts b/src/ast/nodes/SwitchCase.ts index c9148ba79c1..5fafd439936 100644 --- a/src/ast/nodes/SwitchCase.ts +++ b/src/ast/nodes/SwitchCase.ts @@ -8,9 +8,9 @@ import * as NodeType from './NodeType'; import { ExpressionNode, NodeBase, StatementNode } from './shared/Node'; export default class SwitchCase extends NodeBase { - consequent: StatementNode[]; - test: ExpressionNode | null; - type: NodeType.tSwitchCase; + consequent!: StatementNode[]; + test!: ExpressionNode | null; + type!: NodeType.tSwitchCase; include(includeAllChildrenRecursively: boolean) { this.included = true; diff --git a/src/ast/nodes/SwitchStatement.ts b/src/ast/nodes/SwitchStatement.ts index def7a56c944..b826bdf2787 100644 --- a/src/ast/nodes/SwitchStatement.ts +++ b/src/ast/nodes/SwitchStatement.ts @@ -6,9 +6,9 @@ import { ExpressionNode, StatementBase } from './shared/Node'; import SwitchCase from './SwitchCase'; export default class SwitchStatement extends StatementBase { - cases: SwitchCase[]; - discriminant: ExpressionNode; - type: NodeType.tSwitchStatement; + cases!: SwitchCase[]; + discriminant!: ExpressionNode; + type!: NodeType.tSwitchStatement; createScope(parentScope: Scope) { this.scope = new BlockScope(parentScope); diff --git a/src/ast/nodes/TaggedTemplateExpression.ts b/src/ast/nodes/TaggedTemplateExpression.ts index 7e7f81860be..f976cec2102 100644 --- a/src/ast/nodes/TaggedTemplateExpression.ts +++ b/src/ast/nodes/TaggedTemplateExpression.ts @@ -7,11 +7,11 @@ import { ExpressionNode, NodeBase } from './shared/Node'; import TemplateLiteral from './TemplateLiteral'; export default class TaggedTemplateExpression extends NodeBase { - quasi: TemplateLiteral; - tag: ExpressionNode; - type: NodeType.tTaggedTemplateExpression; + quasi!: TemplateLiteral; + tag!: ExpressionNode; + type!: NodeType.tTaggedTemplateExpression; - private callOptions: CallOptions; + private callOptions!: CallOptions; bind() { super.bind(); @@ -53,7 +53,6 @@ export default class TaggedTemplateExpression extends NodeBase { } initialise() { - this.included = false; this.callOptions = CallOptions.create({ callIdentifier: this, withNew: false diff --git a/src/ast/nodes/TemplateElement.ts b/src/ast/nodes/TemplateElement.ts index 9c2e5b9333f..25ec2aa11d9 100644 --- a/src/ast/nodes/TemplateElement.ts +++ b/src/ast/nodes/TemplateElement.ts @@ -3,9 +3,9 @@ import * as NodeType from './NodeType'; import { NodeBase } from './shared/Node'; export default class TemplateElement extends NodeBase { - tail: boolean; - type: NodeType.tTemplateElement; - value: { + tail!: boolean; + type!: NodeType.tTemplateElement; + value!: { cooked: string | null; raw: string; }; diff --git a/src/ast/nodes/TemplateLiteral.ts b/src/ast/nodes/TemplateLiteral.ts index d4b283a56b6..f628bd25af2 100644 --- a/src/ast/nodes/TemplateLiteral.ts +++ b/src/ast/nodes/TemplateLiteral.ts @@ -6,9 +6,9 @@ import { ExpressionNode, NodeBase } from './shared/Node'; import TemplateElement from './TemplateElement'; export default class TemplateLiteral extends NodeBase { - expressions: ExpressionNode[]; - quasis: TemplateElement[]; - type: NodeType.tTemplateLiteral; + expressions!: ExpressionNode[]; + quasis!: TemplateElement[]; + type!: NodeType.tTemplateLiteral; getLiteralValueAtPath(path: ObjectPath): LiteralValueOrUnknown { if (path.length > 0 || this.quasis.length !== 1) { diff --git a/src/ast/nodes/ThisExpression.ts b/src/ast/nodes/ThisExpression.ts index 0647f8c0a4a..15700265831 100644 --- a/src/ast/nodes/ThisExpression.ts +++ b/src/ast/nodes/ThisExpression.ts @@ -8,10 +8,10 @@ import * as NodeType from './NodeType'; import { NodeBase } from './shared/Node'; export default class ThisExpression extends NodeBase { - type: NodeType.tThisExpression; + type!: NodeType.tThisExpression; - variable: ThisVariable; - private alias: string | null; + variable!: ThisVariable; + private alias!: string | null; bind() { super.bind(); @@ -27,8 +27,6 @@ export default class ThisExpression extends NodeBase { } initialise() { - this.included = false; - this.variable = null as any; this.alias = this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null; if (this.alias === 'undefined') { diff --git a/src/ast/nodes/ThrowStatement.ts b/src/ast/nodes/ThrowStatement.ts index 422d6e40976..1127c6100c5 100644 --- a/src/ast/nodes/ThrowStatement.ts +++ b/src/ast/nodes/ThrowStatement.ts @@ -3,8 +3,8 @@ import * as NodeType from './NodeType'; import { ExpressionNode, StatementBase } from './shared/Node'; export default class ThrowStatement extends StatementBase { - argument: ExpressionNode; - type: NodeType.tThrowStatement; + argument!: ExpressionNode; + type!: NodeType.tThrowStatement; hasEffects(_options: ExecutionPathOptions) { return true; diff --git a/src/ast/nodes/UnaryExpression.ts b/src/ast/nodes/UnaryExpression.ts index 53ccd32acff..7a69c68115e 100644 --- a/src/ast/nodes/UnaryExpression.ts +++ b/src/ast/nodes/UnaryExpression.ts @@ -19,10 +19,10 @@ const unaryOperators: { }; export default class UnaryExpression extends NodeBase { - argument: ExpressionNode; - operator: keyof typeof unaryOperators; - prefix: boolean; - type: NodeType.tUnaryExpression; + argument!: ExpressionNode; + operator!: keyof typeof unaryOperators; + prefix!: boolean; + type!: NodeType.tUnaryExpression; bind() { super.bind(); diff --git a/src/ast/nodes/UpdateExpression.ts b/src/ast/nodes/UpdateExpression.ts index 38cccb5e625..1083d5948cd 100644 --- a/src/ast/nodes/UpdateExpression.ts +++ b/src/ast/nodes/UpdateExpression.ts @@ -7,10 +7,10 @@ import * as NodeType from './NodeType'; import { ExpressionNode, NodeBase } from './shared/Node'; export default class UpdateExpression extends NodeBase { - argument: ExpressionNode; - operator: '++' | '--'; - prefix: boolean; - type: NodeType.tUpdateExpression; + argument!: ExpressionNode; + operator!: '++' | '--'; + prefix!: boolean; + type!: NodeType.tUpdateExpression; bind() { super.bind(); diff --git a/src/ast/nodes/VariableDeclaration.ts b/src/ast/nodes/VariableDeclaration.ts index cb559c4efb0..763c3ba340a 100644 --- a/src/ast/nodes/VariableDeclaration.ts +++ b/src/ast/nodes/VariableDeclaration.ts @@ -35,9 +35,9 @@ function areAllDeclarationsIncludedAndNotExported(declarations: VariableDeclarat } export default class VariableDeclaration extends NodeBase { - declarations: VariableDeclarator[]; - kind: 'var' | 'let' | 'const'; - type: NodeType.tVariableDeclaration; + declarations!: VariableDeclarator[]; + kind!: 'var' | 'let' | 'const'; + type!: NodeType.tVariableDeclaration; deoptimizePath(_path: ObjectPath) { for (const declarator of this.declarations) { @@ -65,7 +65,6 @@ export default class VariableDeclaration extends NodeBase { } initialise() { - this.included = false; for (const declarator of this.declarations) { declarator.declareDeclarator(this.kind); } diff --git a/src/ast/nodes/VariableDeclarator.ts b/src/ast/nodes/VariableDeclarator.ts index b6c5eaa4101..292401b4f69 100644 --- a/src/ast/nodes/VariableDeclarator.ts +++ b/src/ast/nodes/VariableDeclarator.ts @@ -6,9 +6,9 @@ import { ExpressionNode, NodeBase } from './shared/Node'; import { PatternNode } from './shared/Pattern'; export default class VariableDeclarator extends NodeBase { - id: PatternNode; - init: ExpressionNode | null; - type: NodeType.tVariableDeclarator; + id!: PatternNode; + init!: ExpressionNode | null; + type!: NodeType.tVariableDeclarator; declareDeclarator(kind: string) { this.id.declare(kind, this.init || UNDEFINED_EXPRESSION); diff --git a/src/ast/nodes/WhileStatement.ts b/src/ast/nodes/WhileStatement.ts index 30d54805fad..5338276d1e7 100644 --- a/src/ast/nodes/WhileStatement.ts +++ b/src/ast/nodes/WhileStatement.ts @@ -3,9 +3,9 @@ import * as NodeType from './NodeType'; import { ExpressionNode, StatementBase, StatementNode } from './shared/Node'; export default class WhileStatement extends StatementBase { - body: StatementNode; - test: ExpressionNode; - type: NodeType.tWhileStatement; + body!: StatementNode; + test!: ExpressionNode; + type!: NodeType.tWhileStatement; hasEffects(options: ExecutionPathOptions): boolean { return ( diff --git a/src/ast/nodes/YieldExpression.ts b/src/ast/nodes/YieldExpression.ts index 2620dedd5a6..fef3d5ddd38 100644 --- a/src/ast/nodes/YieldExpression.ts +++ b/src/ast/nodes/YieldExpression.ts @@ -6,9 +6,9 @@ import * as NodeType from './NodeType'; import { ExpressionNode, NodeBase } from './shared/Node'; export default class YieldExpression extends NodeBase { - argument: ExpressionNode | null; - delegate: boolean; - type: NodeType.tYieldExpression; + argument!: ExpressionNode | null; + delegate!: boolean; + type!: NodeType.tYieldExpression; bind() { super.bind(); diff --git a/src/ast/nodes/shared/ClassNode.ts b/src/ast/nodes/shared/ClassNode.ts index 7761dcae3fb..fae1c97144d 100644 --- a/src/ast/nodes/shared/ClassNode.ts +++ b/src/ast/nodes/shared/ClassNode.ts @@ -8,9 +8,9 @@ import Identifier from '../Identifier'; import { ExpressionNode, NodeBase } from './Node'; export default class ClassNode extends NodeBase { - body: ClassBody; - id: Identifier | null; - superClass: ExpressionNode | null; + body!: ClassBody; + id!: Identifier | null; + superClass!: ExpressionNode | null; createScope(parentScope: Scope) { this.scope = new ChildScope(parentScope); @@ -37,7 +37,6 @@ export default class ClassNode extends NodeBase { } initialise() { - this.included = false; if (this.id !== null) { this.id.declare('class', this); } diff --git a/src/ast/nodes/shared/FunctionNode.ts b/src/ast/nodes/shared/FunctionNode.ts index c832bd65dcc..6e5dc20336a 100644 --- a/src/ast/nodes/shared/FunctionNode.ts +++ b/src/ast/nodes/shared/FunctionNode.ts @@ -9,14 +9,14 @@ import { GenericEsTreeNode, NodeBase } from './Node'; import { PatternNode } from './Pattern'; export default class FunctionNode extends NodeBase { - async: boolean; - body: BlockStatement; - id: IdentifierWithVariable | null; - params: PatternNode[]; - preventChildBlockScope: true; - scope: BlockScope; + async!: boolean; + body!: BlockStatement; + id!: IdentifierWithVariable | null; + params!: PatternNode[]; + preventChildBlockScope!: true; + scope!: BlockScope; - private isPrototypeDeoptimized: boolean; + private isPrototypeDeoptimized = false; createScope(parentScope: FunctionScope) { this.scope = new FunctionScope(parentScope, this.context); @@ -79,8 +79,6 @@ export default class FunctionNode extends NodeBase { } initialise() { - this.included = false; - this.isPrototypeDeoptimized = false; if (this.id !== null) { this.id.declare('function', this); } diff --git a/src/ast/nodes/shared/MultiExpression.ts b/src/ast/nodes/shared/MultiExpression.ts index dd82a12c784..0bdef758f1c 100644 --- a/src/ast/nodes/shared/MultiExpression.ts +++ b/src/ast/nodes/shared/MultiExpression.ts @@ -6,7 +6,7 @@ import { LiteralValueOrUnknown, ObjectPath, UNKNOWN_VALUE } from '../../values'; import { ExpressionEntity } from './Expression'; export class MultiExpression implements ExpressionEntity { - included: boolean; + included = false; private expressions: ExpressionEntity[]; diff --git a/src/ast/nodes/shared/Node.ts b/src/ast/nodes/shared/Node.ts index 3ea2ca57dfc..153390e8185 100644 --- a/src/ast/nodes/shared/Node.ts +++ b/src/ast/nodes/shared/Node.ts @@ -81,13 +81,13 @@ const NEW_EXECUTION_PATH = ExecutionPathOptions.create(); export class NodeBase implements ExpressionNode { context: AstContext; - end: number; - included: boolean; + end!: number; + included = false; keys: string[]; parent: Node | { context: AstContext; type: string }; - scope: ChildScope; - start: number; - type: string; + scope!: ChildScope; + start!: number; + type!: string; constructor( esTreeNode: GenericEsTreeNode, @@ -200,9 +200,7 @@ export class NodeBase implements ExpressionNode { /** * Override to perform special initialisation steps after the scope is initialised */ - initialise() { - this.included = false; - } + initialise() {} insertSemicolon(code: MagicString) { if (code.original[this.end - 1] !== ';') { diff --git a/src/ast/scopes/ModuleScope.ts b/src/ast/scopes/ModuleScope.ts index f1216638342..ec9698a1945 100644 --- a/src/ast/scopes/ModuleScope.ts +++ b/src/ast/scopes/ModuleScope.ts @@ -10,7 +10,7 @@ import GlobalScope from './GlobalScope'; export default class ModuleScope extends ChildScope { context: AstContext; - parent: GlobalScope; + parent!: GlobalScope; constructor(parent: GlobalScope, context: AstContext) { super(parent); diff --git a/src/ast/variables/ExportDefaultVariable.ts b/src/ast/variables/ExportDefaultVariable.ts index 6ad3902cd4c..8f2e38adf7f 100644 --- a/src/ast/variables/ExportDefaultVariable.ts +++ b/src/ast/variables/ExportDefaultVariable.ts @@ -7,8 +7,7 @@ import LocalVariable from './LocalVariable'; import Variable from './Variable'; export default class ExportDefaultVariable extends LocalVariable { - hasId: boolean; - isDefault: true; + hasId = false; // Not initialised during construction private originalId: IdentifierWithVariable | null = null; @@ -86,5 +85,3 @@ export default class ExportDefaultVariable extends LocalVariable { } ExportDefaultVariable.prototype.getBaseVariableName = ExportDefaultVariable.prototype.getName; - -ExportDefaultVariable.prototype.isDefault = true; diff --git a/src/ast/variables/ExternalVariable.ts b/src/ast/variables/ExternalVariable.ts index 797edfca0d7..9ffe9679cb0 100644 --- a/src/ast/variables/ExternalVariable.ts +++ b/src/ast/variables/ExternalVariable.ts @@ -3,7 +3,6 @@ import Identifier from '../nodes/Identifier'; import Variable from './Variable'; export default class ExternalVariable extends Variable { - isExternal: true; isNamespace: boolean; module: ExternalModule; referenced: boolean; @@ -29,5 +28,3 @@ export default class ExternalVariable extends Variable { } } } - -ExternalVariable.prototype.isExternal = true; diff --git a/src/ast/variables/LocalVariable.ts b/src/ast/variables/LocalVariable.ts index 99f32f99e0a..6eec92f9c8c 100644 --- a/src/ast/variables/LocalVariable.ts +++ b/src/ast/variables/LocalVariable.ts @@ -26,7 +26,6 @@ export default class LocalVariable extends Variable { additionalInitializers: ExpressionEntity[] | null = null; declarations: (Identifier | ExportDefaultDeclaration)[]; init: ExpressionEntity | null; - isLocal: true; module: Module; // Caching and deoptimization: @@ -192,5 +191,3 @@ export default class LocalVariable extends Variable { } } } - -LocalVariable.prototype.isLocal = true; diff --git a/src/ast/variables/NamespaceVariable.ts b/src/ast/variables/NamespaceVariable.ts index 02ad7036001..7260cd14d3a 100644 --- a/src/ast/variables/NamespaceVariable.ts +++ b/src/ast/variables/NamespaceVariable.ts @@ -7,7 +7,7 @@ import Variable from './Variable'; export default class NamespaceVariable extends Variable { context: AstContext; - isNamespace: true; + isNamespace!: true; memberVariables: { [name: string]: Variable } = Object.create(null); module: Module; diff --git a/src/ast/variables/Variable.ts b/src/ast/variables/Variable.ts index c7b2b5d21ec..2f8b40d0560 100644 --- a/src/ast/variables/Variable.ts +++ b/src/ast/variables/Variable.ts @@ -11,12 +11,10 @@ import { LiteralValueOrUnknown, ObjectPath, UNKNOWN_EXPRESSION, UNKNOWN_VALUE } export default class Variable implements ExpressionEntity { exportName: string | null = null; included = false; - isDefault?: boolean; - isExternal?: boolean; isId = false; isNamespace?: boolean; isReassigned = false; - module: Module | ExternalModule | null; + module?: Module | ExternalModule; name: string; reexported = false; renderBaseName: string | null = null; diff --git a/src/rollup/types.d.ts b/src/rollup/types.d.ts index bb020febbcc..4c5e9be8986 100644 --- a/src/rollup/types.d.ts +++ b/src/rollup/types.d.ts @@ -170,7 +170,7 @@ export type ResolveIdResult = string | false | void | PartialResolvedId; export type ResolveIdHook = ( this: PluginContext, source: string, - importer: string + importer: string | undefined ) => Promise | ResolveIdResult; export type IsExternal = (source: string, importer: string, isResolved: boolean) => boolean | void; diff --git a/src/utils/collapseSourcemaps.ts b/src/utils/collapseSourcemaps.ts index 33332c9689c..db4f838c6fc 100644 --- a/src/utils/collapseSourcemaps.ts +++ b/src/utils/collapseSourcemaps.ts @@ -168,7 +168,7 @@ export default function collapseSourcemaps( }; } - return new Link(map, [source]) as any; + return new Link(map, [source]); } const moduleSources = modules @@ -200,14 +200,14 @@ export default function collapseSourcemaps( } } - source = sourcemapChain.reduce(linkMap, source); + source = sourcemapChain.reduce(linkMap as any, source); return source; }); let source = new Link(map as any, moduleSources); - source = bundleSourcemapChain.reduce(linkMap, source); + source = bundleSourcemapChain.reduce(linkMap as any, source); let { sources, sourcesContent, names, mappings } = source.traceMappings(); diff --git a/src/utils/deconflictChunk.ts b/src/utils/deconflictChunk.ts index 8bce2a67e75..089e332bde7 100644 --- a/src/utils/deconflictChunk.ts +++ b/src/utils/deconflictChunk.ts @@ -110,7 +110,7 @@ function deconflictImportsOther( variable.setRenderNames(module.variableName, null); } } else { - const chunk = (module as Module).chunk; + const chunk = (module as Module).chunk as Chunk; if (chunk.exportMode === 'default' || (preserveModules && variable.isNamespace)) { variable.setRenderNames(null, chunk.variableName); } else { diff --git a/src/utils/pluginDriver.ts b/src/utils/pluginDriver.ts index 796b1a272cb..4dea64ab464 100644 --- a/src/utils/pluginDriver.ts +++ b/src/utils/pluginDriver.ts @@ -24,6 +24,7 @@ import { } from './error'; type Args = T extends (...args: infer K) => any ? K : never; +type EnsurePromise = Promise ? K : T>; export interface PluginDriver { emitAsset: EmitAsset; @@ -34,7 +35,7 @@ export interface PluginDriver { args: Args, hookContext?: HookContext | null, skip?: number - ): Promise; + ): EnsurePromise; hookFirstSync>( hook: H, args: Args, @@ -50,7 +51,7 @@ export interface PluginDriver { args: any[], reduce: Reduce, hookContext?: HookContext - ): Promise; + ): EnsurePromise; hookReduceArg0Sync>( hook: H, args: any[], @@ -89,7 +90,7 @@ const deprecatedHookNames: Record = { export function createPluginDriver( graph: Graph, options: InputOptions, - pluginCache: Record, + pluginCache: Record | void, watcher?: RollupWatcher ): PluginDriver { const plugins = [ @@ -387,7 +388,7 @@ export function createPluginDriver( // chains synchronously, reduces returns of type R, to type T, handling the reduced value as the first hook argument hookReduceArg0Sync(name, [arg0, ...args], reduce, hookContext) { for (let i = 0; i < plugins.length; i++) { - const result = runHookSync(name, [arg0, ...args], i, false, hookContext); + const result: any = runHookSync(name, [arg0, ...args], i, false, hookContext); arg0 = reduce.call(pluginContexts[i], arg0, result, plugins[i]); } return arg0; diff --git a/src/utils/renderChunk.ts b/src/utils/renderChunk.ts index b8e148c9c0e..74c3511a3ee 100644 --- a/src/utils/renderChunk.ts +++ b/src/utils/renderChunk.ts @@ -18,7 +18,7 @@ export default function renderChunk({ options: OutputOptions; renderChunk: RenderedChunk; sourcemapChain: RawSourceMap[]; -}) { +}): Promise { const renderChunkReducer = (code: string, result: any, plugin: Plugin): string => { if (result == null) return code; @@ -59,7 +59,7 @@ export default function renderChunk({ }) .catch(err => { if (inRenderChunk) throw err; - error(err, { + return error(err, { code: inTransformBundle ? 'BAD_BUNDLE_TRANSFORMER' : 'BAD_CHUNK_TRANSFORMER', message: `Error transforming ${(inTransformBundle ? 'bundle' : 'chunk') + (err.plugin ? ` with '${err.plugin}' plugin` : '')}: ${err.message}`, diff --git a/src/utils/timers.ts b/src/utils/timers.ts index 3eafb44a764..f92c9ff2dab 100644 --- a/src/utils/timers.ts +++ b/src/utils/timers.ts @@ -1,6 +1,6 @@ import { InputOptions, SerializedTimings } from '../rollup/types'; -type StartTime = [number, number] | number; +type StartTime = [number, number]; interface Timer { memory: number; @@ -15,7 +15,7 @@ interface Timers { } const NOOP = () => {}; -let getStartTime: () => StartTime = () => 0; +let getStartTime: () => StartTime = () => [0, 0]; let getElapsedTime: (previous: StartTime) => number = () => 0; let getMemory: () => number = () => 0; let timers: Timers = {}; @@ -25,10 +25,10 @@ const normalizeHrTime = (time: [number, number]) => time[0] * 1e3 + time[1] / 1e function setTimeHelpers() { if (typeof process !== 'undefined' && typeof process.hrtime === 'function') { getStartTime = process.hrtime.bind(process); - getElapsedTime = (previous: [number, number]) => normalizeHrTime(process.hrtime(previous)); + getElapsedTime = previous => normalizeHrTime(process.hrtime(previous)); } else if (typeof performance !== 'undefined' && typeof performance.now === 'function') { - getStartTime = performance.now.bind(performance); - getElapsedTime = (previous: number) => performance.now() - previous; + getStartTime = () => [performance.now(), 0]; + getElapsedTime = previous => performance.now() - previous[0]; } if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') { getMemory = () => process.memoryUsage().heapUsed; diff --git a/src/watch/fileWatchers.ts b/src/watch/fileWatchers.ts index c0c60686619..97c8084694b 100644 --- a/src/watch/fileWatchers.ts +++ b/src/watch/fileWatchers.ts @@ -18,7 +18,7 @@ export function addTask( const group = watchers.get(chokidarOptionsHash) as Map; const watcher = group.get(id) || new FileWatcher(id, chokidarOptions, group); - if (!watcher.fileExists) { + if (!watcher.fsWatcher) { if (isTransformDependency) throw new Error(`Transform dependency ${id} does not exist.`); } else { watcher.addTask(task, isTransformDependency); @@ -32,8 +32,7 @@ export function deleteTask(id: string, target: Task, chokidarOptionsHash: string } export default class FileWatcher { - fileExists: boolean; - fsWatcher: FSWatcher | fs.FSWatcher; + fsWatcher?: FSWatcher | fs.FSWatcher; private id: string; private tasks: Set; @@ -49,12 +48,10 @@ export default class FileWatcher { try { const stats = fs.statSync(id); modifiedTime = +stats.mtime; - this.fileExists = true; } catch (err) { if (err.code === 'ENOENT') { // can't watch files that don't exist (e.g. injected // by plugins somehow) - this.fileExists = false; return; } else { throw err; @@ -83,11 +80,9 @@ export default class FileWatcher { } }; - if (chokidarOptions) { - this.fsWatcher = chokidar.watch(id, chokidarOptions).on('all', handleWatchEvent); - } else { - this.fsWatcher = fs.watch(id, opts, handleWatchEvent); - } + this.fsWatcher = chokidarOptions + ? chokidar.watch(id, chokidarOptions).on('all', handleWatchEvent) + : fs.watch(id, opts, handleWatchEvent); group.set(id, this); } @@ -98,7 +93,7 @@ export default class FileWatcher { } close() { - this.fsWatcher.close(); + if (this.fsWatcher) this.fsWatcher.close(); } deleteTask(task: Task, group: Map) { diff --git a/src/watch/index.ts b/src/watch/index.ts index e261579b646..5086697cf0b 100644 --- a/src/watch/index.ts +++ b/src/watch/index.ts @@ -21,7 +21,7 @@ const DELAY = 200; export class Watcher { emitter: RollupWatcher; - private buildTimeout: NodeJS.Timer; + private buildTimeout: NodeJS.Timer | null = null; private invalidatedIds: Set = new Set(); private rerun = false; private running: boolean; @@ -71,7 +71,7 @@ export class Watcher { if (this.buildTimeout) clearTimeout(this.buildTimeout); this.buildTimeout = setTimeout(() => { - this.buildTimeout = undefined as any; + this.buildTimeout = null; this.invalidatedIds.forEach(id => this.emit('change', id)); this.invalidatedIds.clear(); this.emit('restart'); @@ -115,7 +115,7 @@ export class Watcher { export class Task { cache: RollupCache; - watchFiles: string[]; + watchFiles: string[] = []; private chokidarOptions: WatchOptions; private chokidarOptionsHash: string; diff --git a/tsconfig.json b/tsconfig.json index 8e8b711fab2..47182080643 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -9,8 +9,6 @@ "noUnusedParameters": true, "pretty": true, "skipLibCheck": true, - "strictPropertyInitialization": false, - "strictFunctionTypes": false, "strict": true, "target": "es2015" },