From b40910ddc778b3cf4b383e0ce4deb2e6081f1b4a Mon Sep 17 00:00:00 2001 From: Tiger Oakes Date: Tue, 24 Dec 2019 14:11:22 -0800 Subject: [PATCH] Use ! to assert not-null in typescript --- browser/path.ts | 4 +- cli/logging.ts | 6 +-- cli/run/build.ts | 13 +++-- src/Chunk.ts | 46 ++++++++-------- src/ExternalModule.ts | 2 +- src/Graph.ts | 65 ++++++++++------------- src/Module.ts | 15 +++--- src/ModuleLoader.ts | 6 +-- src/ast/nodes/CallExpression.ts | 14 ++--- src/ast/nodes/ExportAllDeclaration.ts | 5 +- src/ast/nodes/Identifier.ts | 12 ++--- src/ast/nodes/IfStatement.ts | 4 +- src/ast/nodes/ImportDeclaration.ts | 5 +- src/ast/nodes/Literal.ts | 4 +- src/ast/nodes/MemberExpression.ts | 28 +++------- src/ast/nodes/MetaProperty.ts | 2 +- src/ast/nodes/ObjectExpression.ts | 4 +- src/ast/nodes/Property.ts | 14 ++--- src/ast/nodes/SwitchCase.ts | 8 +-- src/ast/nodes/TaggedTemplateExpression.ts | 7 +-- src/ast/nodes/VariableDeclaration.ts | 13 +++-- src/ast/scopes/ReturnValueScope.ts | 2 +- src/ast/values.ts | 8 +-- src/ast/variables/LocalVariable.ts | 7 ++- src/finalisers/amd.ts | 4 +- src/finalisers/cjs.ts | 4 +- src/finalisers/iife.ts | 16 ++---- src/finalisers/shared/getExportBlock.ts | 4 +- src/finalisers/shared/setupNamespace.ts | 10 ++-- src/finalisers/umd.ts | 29 +++++----- src/rollup/index.ts | 23 ++++---- src/utils/FileEmitter.ts | 3 +- src/utils/PluginContext.ts | 2 +- src/utils/PluginDriver.ts | 2 +- src/utils/collapseSourcemaps.ts | 2 +- src/utils/deconflictChunk.ts | 9 ++-- src/utils/executionOrder.ts | 2 +- src/utils/getIndentString.ts | 2 +- src/utils/renderHelpers.ts | 2 +- src/utils/timers.ts | 2 +- src/utils/transform.ts | 8 +-- src/watch/fileWatchers.ts | 4 +- src/watch/index.ts | 2 +- 43 files changed, 177 insertions(+), 247 deletions(-) diff --git a/browser/path.ts b/browser/path.ts index 19be8664082..ecae1fa030f 100644 --- a/browser/path.ts +++ b/browser/path.ts @@ -28,7 +28,7 @@ export function dirname(path: string) { } export function extname(path: string) { - const match = /\.[^.]+$/.exec(basename(path) as string); + const match = /\.[^.]+$/.exec(basename(path)!); if (!match) return ''; return match[0]; } @@ -58,7 +58,7 @@ export function relative(from: string, to: string) { } export function resolve(...paths: string[]) { - let resolvedParts = (paths.shift() as string).split(/[/\\]/); + let resolvedParts = paths.shift()!.split(/[/\\]/); paths.forEach(path => { if (isAbsolute(path)) { diff --git a/cli/logging.ts b/cli/logging.ts index 0cc1206d3cd..5902ff9204c 100644 --- a/cli/logging.ts +++ b/cli/logging.ts @@ -15,8 +15,8 @@ export function handleError(err: RollupError, recover = false) { let description = err.message || err; if (err.name) description = `${err.name}: ${description}`; const message = - ((err as { plugin?: string }).plugin - ? `(plugin ${(err as { plugin?: string }).plugin}) ${description}` + (err.plugin + ? `(plugin ${(err).plugin}) ${description}` : description) || err; stderr(tc.bold.red(`[!] ${tc.bold(message.toString())}`)); @@ -26,7 +26,7 @@ export function handleError(err: RollupError, recover = false) { } if (err.loc) { - stderr(`${relativeId((err.loc.file || err.id) as string)} (${err.loc.line}:${err.loc.column})`); + stderr(`${relativeId((err.loc.file || err.id)!)} (${err.loc.line}:${err.loc.column})`); } else if (err.id) { stderr(relativeId(err.id)); } diff --git a/cli/run/build.ts b/cli/run/build.ts index e8454e20580..8182b9cce72 100644 --- a/cli/run/build.ts +++ b/cli/run/build.ts @@ -1,7 +1,7 @@ import ms from 'pretty-ms'; import tc from 'turbocolor'; import * as rollup from '../../src/node-entry'; -import { InputOptions, OutputOptions, RollupBuild, SourceMap } from '../../src/rollup/types'; +import { InputOptions, OutputOptions, RollupBuild } from '../../src/rollup/types'; import relativeId from '../../src/utils/relativeId'; import { handleError, stderr } from '../logging'; import SOURCEMAPPING_URL from '../sourceMappingUrl'; @@ -19,9 +19,9 @@ export default function build( const start = Date.now(); const files = useStdout ? ['stdout'] - : outputOptions.map(t => relativeId(t.file || (t.dir as string))); + : outputOptions.map(t => relativeId(t.file || t.dir!)); if (!silent) { - let inputFiles: string = undefined as any; + let inputFiles: string | undefined; if (typeof inputOptions.input === 'string') { inputFiles = inputOptions.input; } else if (inputOptions.input instanceof Array) { @@ -31,7 +31,7 @@ export default function build( .map(name => (inputOptions.input as Record)[name]) .join(', '); } - stderr(tc.cyan(`\n${tc.bold(inputFiles)} → ${tc.bold(files.join(', '))}...`)); + stderr(tc.cyan(`\n${tc.bold(inputFiles!)} → ${tc.bold(files.join(', '))}...`)); } return rollup @@ -54,8 +54,7 @@ export default function build( } else { source = file.code; if (output.sourcemap === 'inline') { - source += `\n//# ${SOURCEMAPPING_URL}=${(file - .map as SourceMap).toUrl()}\n`; + source += `\n//# ${SOURCEMAPPING_URL}=${file.map!.toUrl()}\n`; } } if (outputs.length > 1) @@ -66,7 +65,7 @@ export default function build( }); } - return Promise.all(outputOptions.map(output => bundle.write(output) as Promise)).then( + return Promise.all(outputOptions.map(output => bundle.write(output))).then( () => bundle ); }) diff --git a/src/Chunk.ts b/src/Chunk.ts index 550f3bb4d34..96941bc4f5a 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -89,7 +89,7 @@ const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx']; function getGlobalName( module: ExternalModule, - globals: GlobalsOption, + globals: GlobalsOption | undefined, graph: Graph, hasExports: boolean ) { @@ -130,7 +130,7 @@ export default class Chunk { if (!facadedModule.facadeChunk) { facadedModule.facadeChunk = chunk; } - chunk.dependencies = [facadedModule.chunk as Chunk]; + chunk.dependencies = [facadedModule.chunk!]; chunk.dynamicDependencies = []; chunk.facadeModule = facadedModule; for (const exportName of facadedModule.getAllExportNames()) { @@ -662,7 +662,7 @@ export default class Chunk { if (dep instanceof ExternalModule && !dep.renormalizeRenderPath) continue; const renderedDependency = this.renderedDeclarations.dependencies[i]; - const depId = dep instanceof ExternalModule ? renderedDependency.id : (dep.id as string); + const depId = dep instanceof ExternalModule ? renderedDependency.id : dep.id!; if (dep instanceof Chunk) renderedDependency.namedExportsMode = dep.exportMode !== 'default'; renderedDependency.id = this.getRelativePath(depId); } @@ -673,7 +673,7 @@ export default class Chunk { const hasExports = this.renderedDeclarations.exports.length !== 0 || this.renderedDeclarations.dependencies.some( - dep => (dep.reexports && dep.reexports.length !== 0) as boolean + dep => (dep.reexports && dep.reexports.length !== 0)! ); let usesTopLevelAwait = false; @@ -700,19 +700,19 @@ export default class Chunk { } const magicString = finalise( - this.renderedSource as MagicStringBundle, + this.renderedSource!, { accessedGlobals, dependencies: this.renderedDeclarations.dependencies, exports: this.renderedDeclarations.exports, hasExports, indentString: this.indentString, - intro: addons.intro as string, + intro: addons.intro!, isEntryModuleFacade: this.graph.preserveModules || (this.facadeModule !== null && this.facadeModule.isEntryPoint), namedExportsMode: this.exportMode !== 'default', - outro: addons.outro as string, + outro: addons.outro!, usesTopLevelAwait, varOrConst: options.preferConst ? 'const' : 'var', warn: this.graph.warn.bind(this.graph) @@ -741,8 +741,8 @@ export default class Chunk { let file: string; if (options.file) file = resolve(options.sourcemapFile || options.file); - else if (options.dir) file = resolve(options.dir, this.id as string); - else file = resolve(this.id as string); + else if (options.dir) file = resolve(options.dir, this.id!); + else file = resolve(this.id!); const decodedMap = magicString.generateDecodedMap({}); map = collapseSourcemaps( @@ -751,7 +751,7 @@ export default class Chunk { decodedMap, this.usedModules, chunkSourcemapChain, - options.sourcemapExcludeSources as boolean + options.sourcemapExcludeSources! ); map.sources = map.sources.map(sourcePath => normalize( @@ -810,7 +810,7 @@ export default class Chunk { } let dependency: Chunk | ExternalModule; if (depModule instanceof Module) { - dependency = depModule.chunk as Chunk; + dependency = depModule.chunk!; } else { if (!(depModule.used || depModule.moduleSideEffects)) { continue; @@ -887,11 +887,11 @@ 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 as Chunk)) { - const resolutionChunk = resolution.facadeChunk || (resolution.chunk as Chunk); + if (resolution.chunk !== this && isChunkRendered(resolution.chunk!)) { + const resolutionChunk = resolution.facadeChunk || resolution.chunk!; node.renderFinalResolution( code, - `'${this.getRelativePath(resolutionChunk.id as string)}'`, + `'${this.getRelativePath(resolutionChunk.id!)}'`, format ); } @@ -915,7 +915,7 @@ export default class Chunk { private finaliseImportMetas(format: string, outputPluginDriver: PluginDriver): void { for (const [module, code] of this.renderedModuleSources) { for (const importMeta of module.importMetas) { - importMeta.renderFinalMechanism(code, this.id as string, format, outputPluginDriver); + importMeta.renderFinalMechanism(code, this.id!, format, outputPluginDriver); } } } @@ -937,7 +937,7 @@ export default class Chunk { // skip local exports if (!module || module.chunk === this) continue; if (module instanceof Module) { - exportChunk = module.chunk as Chunk; + exportChunk = module.chunk!; importName = exportChunk.getVariableExportName(variable); needsLiveBinding = variable.isReassigned; } else { @@ -970,7 +970,7 @@ export default class Chunk { imported: variable.module instanceof ExternalModule ? variable.name - : ((variable.module as Module).chunk as Chunk).getVariableExportName(variable), + : variable.module!.chunk!.getVariableExportName(variable), local: variable.getName() }); } @@ -996,10 +996,10 @@ export default class Chunk { if (options.format === 'umd' || options.format === 'iife') { globalName = getGlobalName( dep, - options.globals as GlobalsOption, + options.globals, this.graph, exportsNames || exportsDefault - ) as string; + )!; } } @@ -1071,7 +1071,7 @@ export default class Chunk { } private getRelativePath(targetPath: string): string { - const relativePath = normalize(relative(dirname(this.id as string), targetPath)); + const relativePath = normalize(relative(dirname(this.id!), targetPath)); return relativePath.startsWith('../') ? relativePath : './' + relativePath; } @@ -1096,7 +1096,7 @@ export default class Chunk { const namespace = resolution.getOrCreateNamespace(); node.setResolution('named', namespace); } else { - node.setResolution((resolution.chunk as Chunk).exportMode); + node.setResolution(resolution.chunk!.exportMode); } } else { node.setResolution('auto'); @@ -1167,7 +1167,7 @@ export default class Chunk { if ((variable.module as Module).chunk !== this) { this.imports.add(variable); if (variable.module instanceof Module) { - (variable.module.chunk as Chunk).exports.add(variable); + variable.module.chunk!.exports.add(variable); } } } @@ -1191,7 +1191,7 @@ export default class Chunk { if ((variable.module as Module).chunk !== this) { this.imports.add(variable); if (variable.module instanceof Module) { - (variable.module.chunk as Chunk).exports.add(variable); + variable.module.chunk!.exports.add(variable); } } } diff --git a/src/ExternalModule.ts b/src/ExternalModule.ts index 5511a26d84f..0830e18176e 100644 --- a/src/ExternalModule.ts +++ b/src/ExternalModule.ts @@ -30,7 +30,7 @@ export default class ExternalModule { this.moduleSideEffects = moduleSideEffects; const parts = id.split(/[\\/]/); - this.variableName = makeLegal(parts.pop() as string); + this.variableName = makeLegal(parts.pop()!); this.nameSuggestions = Object.create(null); this.declarations = Object.create(null); diff --git a/src/Graph.ts b/src/Graph.ts index 68fbf33f3f4..b5f20987a65 100644 --- a/src/Graph.ts +++ b/src/Graph.ts @@ -9,13 +9,10 @@ import ExternalModule from './ExternalModule'; import Module, { defaultAcornOptions } from './Module'; import { ModuleLoader, UnresolvedModule } from './ModuleLoader'; import { - ExternalOption, GetManualChunk, InputOptions, ManualChunksOption, ModuleJSON, - ModuleSideEffectsOption, - PureModulesOption, RollupCache, RollupWarning, RollupWatcher, @@ -103,31 +100,29 @@ export default class Graph { for (const key of Object.keys(cache)) cache[key][0]++; } } - this.preserveModules = options.preserveModules as boolean; - this.strictDeprecations = options.strictDeprecations as boolean; + this.preserveModules = options.preserveModules!; + this.strictDeprecations = options.strictDeprecations!; - this.cacheExpiry = options.experimentalCacheExpiry as number; + this.cacheExpiry = options.experimentalCacheExpiry!; if (options.treeshake !== false) { - this.treeshakingOptions = options.treeshake - ? { - annotations: (options.treeshake as TreeshakingOptions).annotations !== false, - moduleSideEffects: (options.treeshake as TreeshakingOptions).moduleSideEffects, - propertyReadSideEffects: - (options.treeshake as TreeshakingOptions).propertyReadSideEffects !== false, - pureExternalModules: (options.treeshake as TreeshakingOptions).pureExternalModules, - tryCatchDeoptimization: - (options.treeshake as TreeshakingOptions).tryCatchDeoptimization !== false, - unknownGlobalSideEffects: - (options.treeshake as TreeshakingOptions).unknownGlobalSideEffects !== false - } - : { - annotations: true, - moduleSideEffects: true, - propertyReadSideEffects: true, - tryCatchDeoptimization: true, - unknownGlobalSideEffects: true - }; + this.treeshakingOptions = + options.treeshake && options.treeshake !== true + ? { + annotations: options.treeshake.annotations !== false, + moduleSideEffects: options.treeshake.moduleSideEffects, + propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false, + pureExternalModules: options.treeshake.pureExternalModules, + tryCatchDeoptimization: options.treeshake.tryCatchDeoptimization !== false, + unknownGlobalSideEffects: options.treeshake.unknownGlobalSideEffects !== false + } + : { + annotations: true, + moduleSideEffects: true, + propertyReadSideEffects: true, + tryCatchDeoptimization: true, + unknownGlobalSideEffects: true + }; if (typeof this.treeshakingOptions.pureExternalModules !== 'undefined') { this.warnDeprecation( `The "treeshake.pureExternalModules" option is deprecated. The "treeshake.moduleSideEffects" option should be used instead. "treeshake.pureExternalModules: true" is equivalent to "treeshake.moduleSideEffects: 'no-external'"`, @@ -145,7 +140,7 @@ export default class Graph { this.pluginDriver = new PluginDriver( this, - options.plugins as Plugin[], + options.plugins!, this.pluginCache, options.preserveSymlinks === true, watcher @@ -182,7 +177,7 @@ export default class Graph { acornPluginsToInject.push(injectImportMeta, injectExportNsFrom); if (options.experimentalTopLevelAwait) { - (this.acornOptions as any).allowAwaitOutsideFunction = true; + this.acornOptions.allowAwaitOutsideFunction = true; } const acornInjectPlugins = options.acornInjectPlugins; @@ -193,19 +188,15 @@ export default class Graph { ? [acornInjectPlugins] : []) ); - this.acornParser = acorn.Parser.extend(...acornPluginsToInject) as any; + this.acornParser = acorn.Parser.extend(...acornPluginsToInject); this.moduleLoader = new ModuleLoader( this, this.moduleById, this.pluginDriver, - options.external as ExternalOption, + options.external!, (typeof options.manualChunks === 'function' && options.manualChunks) as GetManualChunk | null, - (this.treeshakingOptions - ? this.treeshakingOptions.moduleSideEffects - : null) as ModuleSideEffectsOption, - (this.treeshakingOptions - ? this.treeshakingOptions.pureExternalModules - : false) as PureModulesOption + (this.treeshakingOptions ? this.treeshakingOptions.moduleSideEffects : null)!, + (this.treeshakingOptions ? this.treeshakingOptions.pureExternalModules : false)! ); } @@ -366,9 +357,7 @@ export default class Graph { if (warning.plugin) str += `(${warning.plugin} plugin) `; if (warning.loc) - str += `${relativeId(warning.loc.file as string)} (${warning.loc.line}:${ - warning.loc.column - }) `; + str += `${relativeId(warning.loc.file!)} (${warning.loc.line}:${warning.loc.column}) `; str += warning.message; return str; diff --git a/src/Module.ts b/src/Module.ts index bf8b3531edc..790af80d82f 100644 --- a/src/Module.ts +++ b/src/Module.ts @@ -158,7 +158,7 @@ function handleMissingExport( message: `'${exportName}' is not exported by ${relativeId(importedModule)}`, url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module` }, - importerStart as number + importerStart! ); } @@ -566,7 +566,7 @@ export default class Module { const fileName = this.id; this.magicString = new MagicString(code, { - filename: (this.excludeFromSourcemap ? null : fileName) as string, // don't include plugin helpers in sourcemap + filename: (this.excludeFromSourcemap ? null : fileName)!, // don't include plugin helpers in sourcemap indentExclusionRanges: [] }); this.removeExistingSourceMap(); @@ -578,8 +578,7 @@ export default class Module { addExport: this.addExport.bind(this), addImport: this.addImport.bind(this), addImportMeta: this.addImportMeta.bind(this), - annotations: (this.graph.treeshakingOptions && - this.graph.treeshakingOptions.annotations) as boolean, + annotations: (this.graph.treeshakingOptions && this.graph.treeshakingOptions.annotations)!, code, // Only needed for debugging deoptimizationTracker: this.graph.deoptimizationTracker, error: this.error.bind(this), @@ -599,14 +598,14 @@ export default class Module { nodeConstructors, preserveModules: this.graph.preserveModules, propertyReadSideEffects: (!this.graph.treeshakingOptions || - this.graph.treeshakingOptions.propertyReadSideEffects) as boolean, + this.graph.treeshakingOptions.propertyReadSideEffects)!, traceExport: this.getVariableForExportName.bind(this), traceVariable: this.traceVariable.bind(this), treeshake: !!this.graph.treeshakingOptions, tryCatchDeoptimization: (!this.graph.treeshakingOptions || - this.graph.treeshakingOptions.tryCatchDeoptimization) as boolean, + this.graph.treeshakingOptions.tryCatchDeoptimization)!, unknownGlobalSideEffects: (!this.graph.treeshakingOptions || - this.graph.treeshakingOptions.unknownGlobalSideEffects) as boolean, + this.graph.treeshakingOptions.unknownGlobalSideEffects)!, usesTopLevelAwait: false, warn: this.warn.bind(this), warnDeprecation: this.graph.warnDeprecation.bind(this.graph) @@ -647,7 +646,7 @@ export default class Module { if (name in this.importDescriptions) { const importDeclaration = this.importDescriptions[name]; - const otherModule = importDeclaration.module as Module | ExternalModule; + const otherModule = importDeclaration.module!; if (otherModule instanceof Module && importDeclaration.name === '*') { return otherModule.getOrCreateNamespace(); diff --git a/src/ModuleLoader.ts b/src/ModuleLoader.ts index 9c6e21f8256..faafbc9ac50 100644 --- a/src/ModuleLoader.ts +++ b/src/ModuleLoader.ts @@ -338,11 +338,11 @@ export class ModuleLoader { const exportAllModule = this.modulesById.get(id); if (exportAllModule instanceof ExternalModule) continue; - for (const name in (exportAllModule as Module).exportsAll) { + for (const name in exportAllModule!.exportsAll) { if (name in module.exportsAll) { - this.graph.warn(errNamespaceConflict(name, module, exportAllModule as Module)); + this.graph.warn(errNamespaceConflict(name, module, exportAllModule!)); } else { - module.exportsAll[name] = (exportAllModule as Module).exportsAll[name]; + module.exportsAll[name] = exportAllModule!.exportsAll[name]; } } } diff --git a/src/ast/nodes/CallExpression.ts b/src/ast/nodes/CallExpression.ts index e510d5e1ab7..705362ffe88 100644 --- a/src/ast/nodes/CallExpression.ts +++ b/src/ast/nodes/CallExpression.ts @@ -164,7 +164,7 @@ export default class CallExpression extends NodeBase implements DeoptimizableEnt const trackedExpressions = context.accessed.getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.returnExpression as ExpressionEntity).hasEffectsWhenAccessedAtPath(path, context); + return this.returnExpression!.hasEffectsWhenAccessedAtPath(path, context); } hasEffectsWhenAssignedAtPath(path: ObjectPath, context: HasEffectsContext): boolean { @@ -172,7 +172,7 @@ export default class CallExpression extends NodeBase implements DeoptimizableEnt const trackedExpressions = context.assigned.getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.returnExpression as ExpressionEntity).hasEffectsWhenAssignedAtPath(path, context); + return this.returnExpression!.hasEffectsWhenAssignedAtPath(path, context); } hasEffectsWhenCalledAtPath( @@ -186,11 +186,7 @@ export default class CallExpression extends NodeBase implements DeoptimizableEnt ).getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.returnExpression as ExpressionEntity).hasEffectsWhenCalledAtPath( - path, - callOptions, - context - ); + return this.returnExpression!.hasEffectsWhenCalledAtPath(path, callOptions, context); } include(context: InclusionContext, includeChildrenRecursively: IncludeChildren) { @@ -208,8 +204,8 @@ export default class CallExpression extends NodeBase implements DeoptimizableEnt this.callee.include(context, false); } this.callee.includeCallArguments(context, this.arguments); - if (!(this.returnExpression as ExpressionEntity).included) { - (this.returnExpression as ExpressionEntity).include(context, false); + if (!this.returnExpression!.included) { + this.returnExpression!.include(context, false); } } diff --git a/src/ast/nodes/ExportAllDeclaration.ts b/src/ast/nodes/ExportAllDeclaration.ts index b7cb6b7c7b7..d33eb26c1d4 100644 --- a/src/ast/nodes/ExportAllDeclaration.ts +++ b/src/ast/nodes/ExportAllDeclaration.ts @@ -18,10 +18,7 @@ export default class ExportAllDeclaration extends NodeBase { } render(code: MagicString, _options: RenderOptions, nodeRenderOptions?: NodeRenderOptions) { - code.remove( - (nodeRenderOptions as NodeRenderOptions).start as number, - (nodeRenderOptions as NodeRenderOptions).end as number - ); + code.remove(nodeRenderOptions!.start!, nodeRenderOptions!.end!); } } diff --git a/src/ast/nodes/Identifier.ts b/src/ast/nodes/Identifier.ts index 9a94c48f8e1..2187d0952d0 100644 --- a/src/ast/nodes/Identifier.ts +++ b/src/ast/nodes/Identifier.ts @@ -78,7 +78,7 @@ export default class Identifier extends NodeBase implements PatternNode { if (path.length === 0 && !this.scope.contains(this.name)) { this.disallowImportReassignment(); } - (this.variable as Variable).deoptimizePath(path); + this.variable!.deoptimizePath(path); } getLiteralValueAtPath( @@ -87,7 +87,7 @@ export default class Identifier extends NodeBase implements PatternNode { origin: DeoptimizableEntity ): LiteralValueOrUnknown { if (!this.bound) this.bind(); - return (this.variable as Variable).getLiteralValueAtPath(path, recursionTracker, origin); + return this.variable!.getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath( @@ -96,11 +96,7 @@ export default class Identifier extends NodeBase implements PatternNode { origin: DeoptimizableEntity ) { if (!this.bound) this.bind(); - return (this.variable as Variable).getReturnExpressionWhenCalledAtPath( - path, - recursionTracker, - origin - ); + return this.variable!.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); } hasEffects(): boolean { @@ -137,7 +133,7 @@ export default class Identifier extends NodeBase implements PatternNode { } includeCallArguments(context: InclusionContext, args: (ExpressionNode | SpreadElement)[]): void { - (this.variable as Variable).includeCallArguments(context, args); + this.variable!.includeCallArguments(context, args); } render( diff --git a/src/ast/nodes/IfStatement.ts b/src/ast/nodes/IfStatement.ts index 1edcc537e04..615fb1c3951 100644 --- a/src/ast/nodes/IfStatement.ts +++ b/src/ast/nodes/IfStatement.ts @@ -63,9 +63,7 @@ export default class IfStatement extends StatementBase implements DeoptimizableE ? this.alternate === null || !this.alternate.included : !this.consequent.included) ) { - const singleRetainedBranch = (this.testValue - ? this.consequent - : this.alternate) as StatementNode; + const singleRetainedBranch = (this.testValue ? this.consequent : this.alternate)!; code.remove(this.start, singleRetainedBranch.start); code.remove(singleRetainedBranch.end, this.end); removeAnnotations(this, code); diff --git a/src/ast/nodes/ImportDeclaration.ts b/src/ast/nodes/ImportDeclaration.ts index 6a7de851669..450381bad86 100644 --- a/src/ast/nodes/ImportDeclaration.ts +++ b/src/ast/nodes/ImportDeclaration.ts @@ -24,10 +24,7 @@ export default class ImportDeclaration extends NodeBase { } render(code: MagicString, _options: RenderOptions, nodeRenderOptions?: NodeRenderOptions) { - code.remove( - (nodeRenderOptions as NodeRenderOptions).start as number, - (nodeRenderOptions as NodeRenderOptions).end as number - ); + code.remove(nodeRenderOptions!.start!, nodeRenderOptions!.end!); } } diff --git a/src/ast/nodes/Literal.ts b/src/ast/nodes/Literal.ts index 29f575f52bb..7672d684bbc 100644 --- a/src/ast/nodes/Literal.ts +++ b/src/ast/nodes/Literal.ts @@ -16,7 +16,7 @@ import { NodeBase } from './shared/Node'; export type LiteralValue = string | boolean | null | number | RegExp | undefined; -export default class Literal extends NodeBase { +export default class Literal extends NodeBase { type!: NodeType.tLiteral; value!: T; @@ -33,7 +33,7 @@ export default class Literal extends NodeBase { ) { return UnknownValue; } - return this.value as any; + return this.value; } getReturnExpressionWhenCalledAtPath(path: ObjectPath) { diff --git a/src/ast/nodes/MemberExpression.ts b/src/ast/nodes/MemberExpression.ts index 099a1c3a274..ce0dd89a6e8 100644 --- a/src/ast/nodes/MemberExpression.ts +++ b/src/ast/nodes/MemberExpression.ts @@ -89,23 +89,17 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE const path = getPathIfNotComputed(this); const baseVariable = path && this.scope.findVariable(path[0].key); if (baseVariable && baseVariable.isNamespace) { - const resolvedVariable = this.resolveNamespaceVariables( - baseVariable, - (path as PathWithPositions).slice(1) - ); + const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path!.slice(1)); if (!resolvedVariable) { super.bind(); } else if (typeof resolvedVariable === 'string') { this.replacement = resolvedVariable; } else { if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) { - resolvedVariable.module.suggestName((path as PathWithPositions)[0].key); + resolvedVariable.module.suggestName(path![0].key); } this.variable = resolvedVariable; - this.scope.addNamespaceMemberAccess( - getStringFromPath(path as PathWithPositions), - resolvedVariable - ); + this.scope.addNamespaceMemberAccess(getStringFromPath(path!), resolvedVariable); } } else { super.bind(); @@ -181,7 +175,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE this.property.hasEffects(context) || this.object.hasEffects(context) || (this.context.propertyReadSideEffects && - this.object.hasEffectsWhenAccessedAtPath([this.propertyKey as ObjectPathKey], context)) + this.object.hasEffectsWhenAccessedAtPath([this.propertyKey!], context)) ); } @@ -190,20 +184,14 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE if (this.variable !== null) { return this.variable.hasEffectsWhenAccessedAtPath(path, context); } - return this.object.hasEffectsWhenAccessedAtPath( - [this.propertyKey as ObjectPathKey, ...path], - context - ); + return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey!, ...path], context); } hasEffectsWhenAssignedAtPath(path: ObjectPath, context: HasEffectsContext): boolean { if (this.variable !== null) { return this.variable.hasEffectsWhenAssignedAtPath(path, context); } - return this.object.hasEffectsWhenAssignedAtPath( - [this.propertyKey as ObjectPathKey, ...path], - context - ); + return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey!, ...path], context); } hasEffectsWhenCalledAtPath( @@ -215,7 +203,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context); } return this.object.hasEffectsWhenCalledAtPath( - [this.propertyKey as ObjectPathKey, ...path], + [this.propertyKey!, ...path], callOptions, context ); @@ -254,7 +242,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE if (this.variable || this.replacement) { let replacement = this.variable ? this.variable.getName() : this.replacement; if (isCalleeOfDifferentParent) replacement = '0, ' + replacement; - code.overwrite(this.start, this.end, replacement as string, { + code.overwrite(this.start, this.end, replacement!, { contentOnly: true, storeName: true }); diff --git a/src/ast/nodes/MetaProperty.ts b/src/ast/nodes/MetaProperty.ts index 25bd4aebe1d..7a9d68674fe 100644 --- a/src/ast/nodes/MetaProperty.ts +++ b/src/ast/nodes/MetaProperty.ts @@ -114,7 +114,7 @@ export default class MetaProperty extends NodeBase { fileName, format, moduleId: this.context.module.id, - referenceId: referenceId || assetReferenceId || (chunkReferenceId as string), + referenceId: referenceId || assetReferenceId || chunkReferenceId!, relativePath } ]); diff --git a/src/ast/nodes/ObjectExpression.ts b/src/ast/nodes/ObjectExpression.ts index 338b8b546ac..c0c2097bf7d 100644 --- a/src/ast/nodes/ObjectExpression.ts +++ b/src/ast/nodes/ObjectExpression.ts @@ -137,7 +137,7 @@ export default class ObjectExpression extends NodeBase implements DeoptimizableE } else { this.expressionsToBeDeoptimized.set(key, [origin]); } - return (propertyMap[key].exactMatchRead as Property).getLiteralValueAtPath( + return propertyMap[key].exactMatchRead!.getLiteralValueAtPath( path.slice(1), recursionTracker, origin @@ -181,7 +181,7 @@ export default class ObjectExpression extends NodeBase implements DeoptimizableE } else { this.expressionsToBeDeoptimized.set(key, [origin]); } - return (propertyMap[key].exactMatchRead as Property).getReturnExpressionWhenCalledAtPath( + return propertyMap[key].exactMatchRead!.getReturnExpressionWhenCalledAtPath( path.slice(1), recursionTracker, origin diff --git a/src/ast/nodes/Property.ts b/src/ast/nodes/Property.ts index 6354bc9522b..a154f47a2ac 100644 --- a/src/ast/nodes/Property.ts +++ b/src/ast/nodes/Property.ts @@ -93,8 +93,7 @@ export default class Property extends NodeBase implements DeoptimizableEntity { trackedExpressions.add(this); return ( this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context) || - (path.length > 0 && - (this.returnExpression as ExpressionEntity).hasEffectsWhenAccessedAtPath(path, context)) + (path.length > 0 && this.returnExpression!.hasEffectsWhenAccessedAtPath(path, context)) ); } return this.value.hasEffectsWhenAccessedAtPath(path, context); @@ -105,10 +104,7 @@ export default class Property extends NodeBase implements DeoptimizableEntity { const trackedExpressions = context.assigned.getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.returnExpression as ExpressionEntity).hasEffectsWhenAssignedAtPath( - path, - context - ); + return this.returnExpression!.hasEffectsWhenAssignedAtPath(path, context); } if (this.kind === 'set') { const trackedExpressions = context.assigned.getEntities(path); @@ -131,11 +127,7 @@ export default class Property extends NodeBase implements DeoptimizableEntity { ).getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.returnExpression as ExpressionEntity).hasEffectsWhenCalledAtPath( - path, - callOptions, - context - ); + return this.returnExpression!.hasEffectsWhenCalledAtPath(path, callOptions, context); } return this.value.hasEffectsWhenCalledAtPath(path, callOptions, context); } diff --git a/src/ast/nodes/SwitchCase.ts b/src/ast/nodes/SwitchCase.ts index 376f72cb521..8baef42daeb 100644 --- a/src/ast/nodes/SwitchCase.ts +++ b/src/ast/nodes/SwitchCase.ts @@ -40,13 +40,7 @@ export default class SwitchCase extends NodeBase { ? this.test.end : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7; const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1; - renderStatementList( - this.consequent, - code, - consequentStart, - (nodeRenderOptions as NodeRenderOptions).end as number, - options - ); + renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions!.end!, options); } else { super.render(code, options); } diff --git a/src/ast/nodes/TaggedTemplateExpression.ts b/src/ast/nodes/TaggedTemplateExpression.ts index 079b883e955..64eb23c98f3 100644 --- a/src/ast/nodes/TaggedTemplateExpression.ts +++ b/src/ast/nodes/TaggedTemplateExpression.ts @@ -16,19 +16,20 @@ export default class TaggedTemplateExpression extends NodeBase { bind() { super.bind(); if (this.tag.type === NodeType.Identifier) { - const variable = this.scope.findVariable((this.tag as Identifier).name); + const name = (this.tag as Identifier).name; + const variable = this.scope.findVariable(name); if (variable.isNamespace) { this.context.error( { code: 'CANNOT_CALL_NAMESPACE', - message: `Cannot call a namespace ('${(this.tag as Identifier).name}')` + message: `Cannot call a namespace ('${name}')` }, this.start ); } - if ((this.tag as Identifier).name === 'eval') { + if (name === 'eval') { this.context.warn( { code: 'EVAL', diff --git a/src/ast/nodes/VariableDeclaration.ts b/src/ast/nodes/VariableDeclaration.ts index 88208238f17..f8955a56258 100644 --- a/src/ast/nodes/VariableDeclaration.ts +++ b/src/ast/nodes/VariableDeclaration.ts @@ -22,7 +22,7 @@ function areAllDeclarationsIncludedAndNotExported(declarations: VariableDeclarat for (const declarator of declarations) { if (!declarator.included) return false; if (declarator.id.type === NodeType.Identifier) { - if ((declarator.id.variable as Variable).exportName) return false; + if (declarator.id.variable!.exportName) return false; } else { const exportedVariables: Variable[] = []; declarator.id.addExportedVariables(exportedVariables); @@ -138,7 +138,7 @@ export default class VariableDeclaration extends NodeBase { this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0) ); - let actualContentEnd, renderedContentEnd; + let actualContentEnd: number | undefined, renderedContentEnd: number; if (/\n\s*$/.test(code.slice(this.start, separatedNodes[0].start))) { renderedContentEnd = this.start + this.kind.length; } else { @@ -176,11 +176,10 @@ export default class VariableDeclaration extends NodeBase { if (options.format === 'system' && node.init !== null) { if (node.id.type !== NodeType.Identifier) { node.id.addExportedVariables(systemPatternExports); - } else if ((node.id.variable as Variable).exportName) { + } else if (node.id.variable!.exportName) { code.prependLeft( code.original.indexOf('=', node.id.end) + 1, - ` exports('${(node.id.variable as Variable).safeExportName || - (node.id.variable as Variable).exportName}',` + ` exports('${node.id.variable!.safeExportName || node.id.variable!.exportName}',` ); nextSeparatorString += ')'; } @@ -205,7 +204,7 @@ export default class VariableDeclaration extends NodeBase { actualContentEnd = contentEnd; renderedContentEnd = end; hasRenderedContent = true; - lastSeparatorPos = separator as number; + lastSeparatorPos = separator!; separatorString = nextSeparatorString; } if (hasRenderedContent) { @@ -213,7 +212,7 @@ export default class VariableDeclaration extends NodeBase { code, separatorString, lastSeparatorPos, - actualContentEnd as number, + actualContentEnd!, renderedContentEnd, !isNoStatement, systemPatternExports diff --git a/src/ast/scopes/ReturnValueScope.ts b/src/ast/scopes/ReturnValueScope.ts index 51975004fec..8647cd299ba 100644 --- a/src/ast/scopes/ReturnValueScope.ts +++ b/src/ast/scopes/ReturnValueScope.ts @@ -13,7 +13,7 @@ export default class ReturnValueScope extends ParameterScope { getReturnExpression(): ExpressionEntity { if (this.returnExpression === null) this.updateReturnExpression(); - return this.returnExpression as ExpressionEntity; + return this.returnExpression!; } private updateReturnExpression() { diff --git a/src/ast/values.ts b/src/ast/values.ts index 3f563c5928d..f2c179ac2c8 100644 --- a/src/ast/values.ts +++ b/src/ast/values.ts @@ -440,7 +440,7 @@ const literalStringMembers: MemberDescriptions = assembleMemberDescriptions( objectMembers ); -export function getLiteralMembersForValue(value: T) { +export function getLiteralMembersForValue(value: T) { switch (typeof value) { case 'boolean': return literalBooleanMembers; @@ -467,7 +467,7 @@ export function hasMemberEffectWhenCalled( ) return true; if (!members[memberName].callsArgs) return false; - for (const argIndex of members[memberName].callsArgs as number[]) { + for (const argIndex of members[memberName].callsArgs!) { if ( callOptions.args[argIndex] && callOptions.args[argIndex].hasEffectsWhenCalledAtPath( @@ -490,6 +490,6 @@ export function getMemberReturnExpressionWhenCalled( ): ExpressionEntity { if (typeof memberName !== 'string' || !members[memberName]) return UNKNOWN_EXPRESSION; return members[memberName].returnsPrimitive !== null - ? (members[memberName].returnsPrimitive as ExpressionEntity) - : new (members[memberName].returns as any)(); + ? members[memberName].returnsPrimitive! + : new members[memberName].returns!(); } diff --git a/src/ast/variables/LocalVariable.ts b/src/ast/variables/LocalVariable.ts index 56e21339be2..f72e5aa2a73 100644 --- a/src/ast/variables/LocalVariable.ts +++ b/src/ast/variables/LocalVariable.ts @@ -128,7 +128,7 @@ export default class LocalVariable extends Variable { const trackedExpressions = context.accessed.getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context)) as boolean; + return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context))!; } hasEffectsWhenAssignedAtPath(path: ObjectPath, context: HasEffectsContext) { @@ -138,7 +138,7 @@ export default class LocalVariable extends Variable { const trackedExpressions = context.assigned.getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context)) as boolean; + return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context))!; } hasEffectsWhenCalledAtPath( @@ -153,8 +153,7 @@ export default class LocalVariable extends Variable { ).getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.init && - this.init.hasEffectsWhenCalledAtPath(path, callOptions, context)) as boolean; + return (this.init && this.init.hasEffectsWhenCalledAtPath(path, callOptions, context))!; } include(context: InclusionContext) { diff --git a/src/finalisers/amd.ts b/src/finalisers/amd.ts index c0cff6626f4..2a2ebcefa8b 100644 --- a/src/finalisers/amd.ts +++ b/src/finalisers/amd.ts @@ -84,8 +84,8 @@ export default function amd( exports, dependencies, namedExportsMode, - options.interop as boolean, - options.compact as boolean, + options.interop, + options.compact, t ); if (exportBlock) magicString.append(n + n + exportBlock); diff --git a/src/finalisers/cjs.ts b/src/finalisers/cjs.ts index 67dc2d31dd8..08475600fc0 100644 --- a/src/finalisers/cjs.ts +++ b/src/finalisers/cjs.ts @@ -89,8 +89,8 @@ export default function cjs( exports, dependencies, namedExportsMode, - options.interop as boolean, - options.compact as boolean, + options.interop, + options.compact, t, `module.exports${_}=${_}` ); diff --git a/src/finalisers/iife.ts b/src/finalisers/iife.ts index 7fc5a6b0950..789a8ddfb58 100644 --- a/src/finalisers/iife.ts +++ b/src/finalisers/iife.ts @@ -1,5 +1,5 @@ import { Bundle as MagicStringBundle } from 'magic-string'; -import { GlobalsOption, OutputOptions } from '../rollup/types'; +import { OutputOptions } from '../rollup/types'; import { error } from '../utils/error'; import { isLegal } from '../utils/identifierHelpers'; import { FinaliserOptions } from './index'; @@ -55,7 +55,7 @@ export default function iife( if (namedExportsMode && hasExports) { if (extend) { - deps.unshift(`${thisProp(name as string)}${_}=${_}${thisProp(name as string)}${_}||${_}{}`); + deps.unshift(`${thisProp(name!)}${_}=${_}${thisProp(name!)}${_}||${_}{}`); args.unshift('exports'); } else { deps.unshift('{}'); @@ -74,13 +74,7 @@ export default function iife( } if (isNamespaced && hasExports) { - wrapperIntro = - setupNamespace( - name as string, - 'this', - options.globals as GlobalsOption, - options.compact as boolean - ) + wrapperIntro; + wrapperIntro = setupNamespace(name!, 'this', options.globals, options.compact) + wrapperIntro; } let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`; @@ -99,8 +93,8 @@ export default function iife( exports, dependencies, namedExportsMode, - options.interop as boolean, - options.compact as boolean, + options.interop, + options.compact, t ); if (exportBlock) magicString.append(n + n + exportBlock); diff --git a/src/finalisers/shared/getExportBlock.ts b/src/finalisers/shared/getExportBlock.ts index 266bd7e6efe..70fcda4ac29 100644 --- a/src/finalisers/shared/getExportBlock.ts +++ b/src/finalisers/shared/getExportBlock.ts @@ -4,8 +4,8 @@ export default function getExportBlock( exports: ChunkExports, dependencies: ChunkDependencies, namedExportsMode: boolean, - interop: boolean, - compact: boolean, + interop: boolean | undefined, + compact: boolean | undefined, t: string, mechanism = 'return ' ) { diff --git a/src/finalisers/shared/setupNamespace.ts b/src/finalisers/shared/setupNamespace.ts index bfa78ee82fe..0f1c1425908 100644 --- a/src/finalisers/shared/setupNamespace.ts +++ b/src/finalisers/shared/setupNamespace.ts @@ -4,8 +4,8 @@ import { property } from './sanitize'; export default function setupNamespace( name: string, root: string, - globals: GlobalsOption, - compact: boolean + globals: GlobalsOption | undefined, + compact: boolean | undefined ) { const parts = name.split('.'); if (globals) { @@ -28,8 +28,8 @@ export default function setupNamespace( export function assignToDeepVariable( deepName: string, root: string, - globals: GlobalsOption, - compact: boolean, + globals: GlobalsOption | undefined, + compact: boolean | undefined, assignment: string ): string { const _ = compact ? '' : ' '; @@ -42,7 +42,7 @@ export function assignToDeepVariable( let acc = root; let deepAssignment = parts .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`)) - .concat(`${acc}${property(last as string)}`) + .concat(`${acc}${property(last!)}`) .join(`,${_}`) .concat(`${_}=${_}${assignment}`); if (parts.length > 0) { diff --git a/src/finalisers/umd.ts b/src/finalisers/umd.ts index e9e9f3e1b26..9374338e57a 100644 --- a/src/finalisers/umd.ts +++ b/src/finalisers/umd.ts @@ -63,11 +63,11 @@ export default function umd( cjsDeps.unshift(`exports`); globalDeps.unshift( assignToDeepVariable( - options.name as string, + options.name!, globalVar, options.globals as GlobalsOption, - options.compact as boolean, - `${options.extend ? `${globalProp(options.name as string, globalVar)}${_}||${_}` : ''}{}` + options.compact!, + `${options.extend ? `${globalProp(options.name!, globalVar)}${_}||${_}` : ''}{}` ) ); @@ -92,10 +92,10 @@ export default function umd( if (!namedExportsMode && hasExports) { factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable( - options.name as string, + options.name!, globalVar, - options.globals as GlobalsOption, - options.compact as boolean, + options.globals, + options.compact, `${factoryVar}(${globalDeps.join(`,${_}`)})` )};`; } else if (namedExportsMode) { @@ -106,22 +106,21 @@ export default function umd( } iifeExport = `(function${_}()${_}{${n}` + - `${t}${t}var current${_}=${_}${safeAccess(options.name as string, globalVar, _)};${n}` + + `${t}${t}var current${_}=${_}${safeAccess(options.name!, globalVar, _)};${n}` + `${t}${t}${factory}${n}` + `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` + - `${globalProp( - options.name as string, - globalVar - )}${_}=${_}current;${_}return ${noConflictExportsVar}${options.compact ? '' : '; '}};${n}` + + `${globalProp(options.name!, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${ + options.compact ? '' : '; ' + }};${n}` + `${t}}())`; } else { iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`; if (!namedExportsMode && hasExports) { iifeExport = assignToDeepVariable( - options.name as string, + options.name!, globalVar, options.globals as GlobalsOption, - options.compact as boolean, + options.compact!, iifeExport ); } @@ -158,8 +157,8 @@ export default function umd( exports, dependencies, namedExportsMode, - options.interop as boolean, - options.compact as boolean, + options.interop, + options.compact, t ); if (exportBlock) magicString.append(n + n + exportBlock); diff --git a/src/rollup/index.ts b/src/rollup/index.ts index 15ef60746f0..07221af6f74 100644 --- a/src/rollup/index.ts +++ b/src/rollup/index.ts @@ -28,7 +28,6 @@ import { OutputOptions, Plugin, RollupBuild, - RollupCache, RollupOutput, RollupWatcher, WarningHandler @@ -170,7 +169,7 @@ function assignChunksToBundle( const chunk = chunks[i]; const facadeModule = chunk.facadeModule; - outputBundle[chunk.id as string] = { + outputBundle[chunk.id!] = { code: undefined as any, dynamicImports: chunk.getDynamicImportIds(), exports: chunk.getExportNames(), @@ -211,7 +210,7 @@ export default async function rollup(rawInputOptions: GenericConfigObject): Prom chunks = await graph.build( inputOptions.input as string | string[] | Record, inputOptions.manualChunks, - inputOptions.inlineDynamicImports as boolean + inputOptions.inlineDynamicImports! ); } catch (err) { const watchFiles = Object.keys(graph.watchFiles); @@ -275,7 +274,7 @@ export default async function rollup(rawInputOptions: GenericConfigObject): Prom chunk.preRender(outputOptions, inputBase); } if (!optimized && inputOptions.experimentalOptimizeChunks) { - optimizeChunks(chunks, outputOptions, inputOptions.chunkGroupingSize as number, inputBase); + optimizeChunks(chunks, outputOptions, inputOptions.chunkGroupingSize!, inputBase); optimized = true; } assignChunkIds( @@ -291,7 +290,7 @@ export default async function rollup(rawInputOptions: GenericConfigObject): Prom await Promise.all( chunks.map(chunk => { - const outputChunk = outputBundleWithPlaceholders[chunk.id as string] as OutputChunk; + const outputChunk = outputBundleWithPlaceholders[chunk.id!] as OutputChunk; return chunk .render(outputOptions, addons, outputChunk, outputPluginDriver) .then(rendered => { @@ -328,7 +327,7 @@ export default async function rollup(rawInputOptions: GenericConfigObject): Prom const cache = useCache ? graph.getCache() : undefined; const result: RollupBuild = { - cache: cache as RollupCache, + cache: cache!, generate: ((rawOutputOptions: GenericConfigObject) => { const { outputOptions, outputPluginDriver } = getOutputOptionsAndPluginDriver( rawOutputOptions @@ -412,8 +411,7 @@ function createOutput(outputBundle: Record outputBundle[fileName]) .filter(outputFile => Object.keys(outputFile).length > 0) as ( | OutputChunk - | OutputAsset - )[]).sort((outputFileA, outputFileB) => { + | OutputAsset)[]).sort((outputFileA, outputFileB) => { const fileTypeA = getSortingFileType(outputFileA); const fileTypeB = getSortingFileType(outputFileB); if (fileTypeA === fileTypeB) return 0; @@ -428,10 +426,7 @@ function writeOutputFile( outputOptions: OutputOptions, outputPluginDriver: PluginDriver ): Promise { - const fileName = resolve( - outputOptions.dir || dirname(outputOptions.file as string), - outputFile.fileName - ); + const fileName = resolve(outputOptions.dir || dirname(outputOptions.file!), outputFile.fileName); let writeSourceMapPromise: Promise; let source: string | Buffer; if (outputFile.type === 'asset') { @@ -478,8 +473,8 @@ function normalizeOutputOptions( config: { output: { ...rawOutputOptions, - ...(rawOutputOptions.output as Object), - ...(inputOptions.output as Object) + ...(rawOutputOptions.output as object), + ...(inputOptions.output as object) } } }); diff --git a/src/utils/FileEmitter.ts b/src/utils/FileEmitter.ts index 88e34a8bb3d..b051b5ebb6c 100644 --- a/src/utils/FileEmitter.ts +++ b/src/utils/FileEmitter.ts @@ -1,4 +1,3 @@ -import Chunk from '../Chunk'; import Graph from '../Graph'; import Module from '../Module'; import { FilePlaceholder, OutputBundleWithPlaceholders } from '../rollup/types'; @@ -132,7 +131,7 @@ function getAssetFileName(file: ConsumedAsset, referenceId: string): string { } function getChunkFileName(file: ConsumedChunk): string { - const fileName = file.fileName || (file.module && (file.module.facadeChunk as Chunk).id); + const fileName = file.fileName || (file.module && file.module.facadeChunk!.id); if (!fileName) return error(errChunkNotGeneratedForFileName(file.fileName || file.name)); return fileName; } diff --git a/src/utils/PluginContext.ts b/src/utils/PluginContext.ts index 62bbdf64191..f89ec229f37 100644 --- a/src/utils/PluginContext.ts +++ b/src/utils/PluginContext.ts @@ -194,7 +194,7 @@ export function getPluginContexts( }); deprecationWarningShown = true; } - return (watcher as RollupWatcher).on(event, handler); + return watcher!.on(event, handler); } return { diff --git a/src/utils/PluginDriver.ts b/src/utils/PluginDriver.ts index fc080e7f3e8..a95c3992414 100644 --- a/src/utils/PluginDriver.ts +++ b/src/utils/PluginDriver.ts @@ -207,7 +207,7 @@ export class PluginDriver { args: Args, replaceContext?: ReplaceContext ): Promise { - let promise: Promise = Promise.resolve() as any; + let promise: Promise = Promise.resolve(); for (let i = 0; i < this.plugins.length; i++) promise = promise.then(() => this.runHook(hookName, args as any[], i, false, replaceContext) diff --git a/src/utils/collapseSourcemaps.ts b/src/utils/collapseSourcemaps.ts index c20a8348fab..edd9c4191cb 100644 --- a/src/utils/collapseSourcemaps.ts +++ b/src/utils/collapseSourcemaps.ts @@ -205,7 +205,7 @@ export function collapseSourcemaps( map: DecodedSourceMap, modules: Module[], bundleSourcemapChain: DecodedSourceMapOrMissing[], - excludeContent: boolean + excludeContent: boolean | undefined ) { const linkMap = getLinkMap(bundle.graph); const moduleSources = modules diff --git a/src/utils/deconflictChunk.ts b/src/utils/deconflictChunk.ts index 2cf63c1f9e9..7519bf763bc 100644 --- a/src/utils/deconflictChunk.ts +++ b/src/utils/deconflictChunk.ts @@ -93,14 +93,13 @@ function deconflictImportsOther( variable.setRenderNames(module.variableName, null); } } else { - const chunk = (module as Module).chunk as Chunk; + const chunk = module!.chunk!; if (chunk.exportMode === 'default' || (preserveModules && variable.isNamespace)) { variable.setRenderNames(null, chunk.variableName); } else { - variable.setRenderNames( - chunk.variableName, - chunk.getVariableExportName(variable) as string | null - ); + variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable) as + | string + | null); } } } diff --git a/src/utils/executionOrder.ts b/src/utils/executionOrder.ts index 1343def8f59..e5b1f75c288 100644 --- a/src/utils/executionOrder.ts +++ b/src/utils/executionOrder.ts @@ -73,7 +73,7 @@ function getCyclePath(id: string, parentId: string, parents: { [id: string]: str let curId = parentId; while (curId !== id) { path.push(relativeId(curId)); - curId = parents[curId] as string; + curId = parents[curId]!; if (!curId) break; } path.push(path[0]); diff --git a/src/utils/getIndentString.ts b/src/utils/getIndentString.ts index fb63f21e94d..32fd4c8cc47 100644 --- a/src/utils/getIndentString.ts +++ b/src/utils/getIndentString.ts @@ -19,7 +19,7 @@ function guessIndentString(code: string) { // Otherwise, we need to guess the multiple const min = spaced.reduce((previous, current) => { - const numSpaces = (/^ +/.exec(current) as RegExpExecArray)[0].length; + const numSpaces = /^ +/.exec(current)![0].length; return Math.min(numSpaces, previous); }, Infinity); diff --git a/src/utils/renderHelpers.ts b/src/utils/renderHelpers.ts index 3e4610ca9b6..1363ce535e4 100644 --- a/src/utils/renderHelpers.ts +++ b/src/utils/renderHelpers.ts @@ -102,7 +102,7 @@ export function renderStatementList( }) : currentNode.render(code, options); } else { - treeshakeNode(currentNode, code, currentNodeStart as number, nextNodeStart); + treeshakeNode(currentNode, code, currentNodeStart!, nextNodeStart); } } else { currentNode.render(code, options); diff --git a/src/utils/timers.ts b/src/utils/timers.ts index 6683c39c93b..ad886db561e 100644 --- a/src/utils/timers.ts +++ b/src/utils/timers.ts @@ -128,7 +128,7 @@ export function initialiseTimers(inputOptions: InputOptions) { setTimeHelpers(); timeStart = timeStartImpl; timeEnd = timeEndImpl; - inputOptions.plugins = (inputOptions.plugins as Plugin[]).map(getPluginWithTimers); + inputOptions.plugins = inputOptions.plugins!.map(getPluginWithTimers); } else { timeStart = NOOP; timeEnd = NOOP; diff --git a/src/utils/transform.ts b/src/utils/transform.ts index 3e16df29471..9c83aa32f45 100644 --- a/src/utils/transform.ts +++ b/src/utils/transform.ts @@ -126,12 +126,12 @@ export default function transform( return pluginContext.error(err); }, emitAsset(name: string, source?: string | Buffer) { - const emittedFile = { type: 'asset' as 'asset', name, source }; + const emittedFile = { type: 'asset' as const, name, source }; emittedFiles.push({ ...emittedFile }); return graph.pluginDriver.emitFile(emittedFile); }, emitChunk(id, options) { - const emittedFile = { type: 'chunk' as 'chunk', id, name: options && options.name }; + const emittedFile = { type: 'chunk' as const, id, name: options && options.name }; emittedFiles.push({ ...emittedFile }); return graph.pluginDriver.emitFile(emittedFile); }, @@ -175,7 +175,7 @@ export default function transform( return new SourceMap({ ...combinedMap, file: null as any, - sourcesContent: combinedMap.sourcesContent as string[] + sourcesContent: combinedMap.sourcesContent! }); } }; @@ -186,7 +186,7 @@ export default function transform( if (!customTransformCache && setAssetSourceErr) throw setAssetSourceErr; return { - ast: ast as any, + ast: ast!, code, customTransformCache, moduleSideEffects, diff --git a/src/watch/fileWatchers.ts b/src/watch/fileWatchers.ts index b2d231fdba9..52f968e9309 100644 --- a/src/watch/fileWatchers.ts +++ b/src/watch/fileWatchers.ts @@ -15,7 +15,7 @@ export function addTask( isTransformDependency: boolean ) { if (!watchers.has(chokidarOptionsHash)) watchers.set(chokidarOptionsHash, new Map()); - const group = watchers.get(chokidarOptionsHash) as Map; + const group = watchers.get(chokidarOptionsHash)!; const watcher = group.get(id) || new FileWatcher(id, chokidarOptions, group); if (!watcher.fsWatcher) { @@ -26,7 +26,7 @@ export function addTask( } export function deleteTask(id: string, target: Task, chokidarOptionsHash: string) { - const group = watchers.get(chokidarOptionsHash) as Map; + const group = watchers.get(chokidarOptionsHash)!; const watcher = group.get(id); if (watcher) watcher.deleteTask(target, group); } diff --git a/src/watch/index.ts b/src/watch/index.ts index 799e2cfb7ff..958dfcd19f8 100644 --- a/src/watch/index.ts +++ b/src/watch/index.ts @@ -141,7 +141,7 @@ export class Task { this.outputs = outputOptions; this.outputFiles = this.outputs.map(output => { - if (output.file || output.dir) return path.resolve(output.file || (output.dir as string)); + if (output.file || output.dir) return path.resolve(output.file || output.dir!); return undefined as any; });