diff --git a/build-plugins/generate-license-file.ts b/build-plugins/generate-license-file.ts index 42f1e363c38..d1b6cf11640 100644 --- a/build-plugins/generate-license-file.ts +++ b/build-plugins/generate-license-file.ts @@ -1,24 +1,24 @@ import { readFileSync, writeFileSync } from 'fs'; -import { PluginImpl } from 'rollup'; -import license, { Dependency, Person } from 'rollup-plugin-license'; +import type { PluginImpl } from 'rollup'; +import license, { type Dependency, type Person } from 'rollup-plugin-license'; -function generateLicenseFile(dependencies: Dependency[]) { +function generateLicenseFile(dependencies: readonly Dependency[]) { const coreLicense = readFileSync('LICENSE-CORE.md'); - const licenses = new Set(); - const dependencyLicenseTexts = dependencies + const licenses = new Set(); + const dependencyLicenseTexts = Array.from(dependencies) .sort(({ name: nameA }, { name: nameB }) => (nameA! > nameB! ? 1 : -1)) .map(({ name, license, licenseText, author, maintainers, contributors, repository }) => { let text = `## ${name}\n`; if (license) { text += `License: ${license}\n`; } - const names = new Set(); - if (author && author.name) { + const names = new Set(); + if (author?.name) { names.add(author.name); } // TODO there is an inconsistency in the rollup-plugin-license types for (const person of contributors.concat(maintainers as unknown as Person[])) { - if (person && person.name) { + if (person?.name) { names.add(person.name); } } @@ -39,7 +39,7 @@ function generateLicenseFile(dependencies: Dependency[]) { .join('\n') + '\n'; } - licenses.add(license); + licenses.add(license!); return text; }) .join('\n---------------------------------------\n\n'); @@ -59,16 +59,18 @@ function generateLicenseFile(dependencies: Dependency[]) { } } -export default function getLicenseHandler(): { +interface LicenseHandler { collectLicenses: PluginImpl; writeLicense: PluginImpl; -} { - const licenses = new Map(); +} + +export default function getLicenseHandler(): LicenseHandler { + const licenses = new Map(); return { collectLicenses() { - function addLicenses(dependencies: Dependency[]) { + function addLicenses(dependencies: readonly Dependency[]) { for (const dependency of dependencies) { - licenses.set(dependency.name, dependency); + licenses.set(dependency.name!, dependency); } } diff --git a/cli/run/loadConfigFile.ts b/cli/run/loadConfigFile.ts index 3b07543aa6d..0f80b9a8c8b 100644 --- a/cli/run/loadConfigFile.ts +++ b/cli/run/loadConfigFile.ts @@ -2,14 +2,14 @@ import { realpathSync } from 'fs'; import { extname, isAbsolute } from 'path'; import { pathToFileURL } from 'url'; import * as rollup from '../../src/node-entry'; -import { MergedRollupOptions } from '../../src/rollup/types'; +import type { MergedRollupOptions } from '../../src/rollup/types'; import { bold } from '../../src/utils/colors'; import { error } from '../../src/utils/error'; import { mergeOptions } from '../../src/utils/options/mergeOptions'; -import { GenericConfigObject } from '../../src/utils/options/options'; +import type { GenericConfigObject } from '../../src/utils/options/options'; import relativeId from '../../src/utils/relativeId'; import { stderr } from '../logging'; -import batchWarnings, { BatchWarnings } from './batchWarnings'; +import batchWarnings, { type BatchWarnings } from './batchWarnings'; import { addCommandPluginsToInputOptions, addPluginsFromCommandOption } from './commandPlugins'; function supportsNativeESM(): boolean { diff --git a/cli/run/loadConfigFromCommand.ts b/cli/run/loadConfigFromCommand.ts index 5f75caf6640..69edc8b83e1 100644 --- a/cli/run/loadConfigFromCommand.ts +++ b/cli/run/loadConfigFromCommand.ts @@ -4,7 +4,7 @@ import batchWarnings, { BatchWarnings } from './batchWarnings'; import { addCommandPluginsToInputOptions } from './commandPlugins'; import { stdinName } from './stdin'; -export default async function loadConfigFromCommand(command: Record): Promise<{ +export default async function loadConfigFromCommand(command: Record): Promise<{ options: MergedRollupOptions[]; warnings: BatchWarnings; }> { diff --git a/cli/run/resetScreen.ts b/cli/run/resetScreen.ts index 3cf34ee8657..6045fce0b44 100644 --- a/cli/run/resetScreen.ts +++ b/cli/run/resetScreen.ts @@ -1,4 +1,4 @@ -import { MergedRollupOptions } from '../../src/rollup/types'; +import type { MergedRollupOptions } from '../../src/rollup/types'; import { stderr } from '../logging'; const CLEAR_SCREEN = '\u001Bc'; diff --git a/cli/run/stdin.ts b/cli/run/stdin.ts index c4c0b853435..ec181af0975 100644 --- a/cli/run/stdin.ts +++ b/cli/run/stdin.ts @@ -1,4 +1,4 @@ -import { Plugin } from '../../src/rollup/types'; +import type { Plugin } from '../../src/rollup/types'; export const stdinName = '-'; diff --git a/cli/run/waitForInput.ts b/cli/run/waitForInput.ts index 946ee79423d..69fdd9254c2 100644 --- a/cli/run/waitForInput.ts +++ b/cli/run/waitForInput.ts @@ -1,5 +1,5 @@ -import { PluginContext } from 'rollup'; -import { NormalizedInputOptions, Plugin } from '../../src/rollup/types'; +import type { PluginContext } from 'rollup'; +import type { NormalizedInputOptions, Plugin } from '../../src/rollup/types'; import { bold } from '../../src/utils/colors'; import { stderr } from '../logging'; @@ -8,9 +8,9 @@ export function waitForInputPlugin(): Plugin { async buildStart(this: PluginContext, options: NormalizedInputOptions) { const inputSpecifiers = Array.isArray(options.input) ? options.input - : Object.keys(options.input as { [entryAlias: string]: string }); + : Object.keys(options.input); - let lastAwaitedSpecifier = null; + let lastAwaitedSpecifier: string | null = null; checkSpecifiers: while (true) { for (const specifier of inputSpecifiers) { if ((await this.resolve(specifier)) === null) { diff --git a/cli/run/watch-cli.ts b/cli/run/watch-cli.ts index 3e8e619a961..6224cfefce6 100644 --- a/cli/run/watch-cli.ts +++ b/cli/run/watch-cli.ts @@ -1,14 +1,15 @@ import { type FSWatcher, readFileSync } from 'fs'; +import process from 'process'; import chokidar from 'chokidar'; import dateTime from 'date-time'; import ms from 'pretty-ms'; import onExit from 'signal-exit'; import * as rollup from '../../src/node-entry'; -import { MergedRollupOptions, RollupWatcher } from '../../src/rollup/types'; +import type { MergedRollupOptions, RollupWatcher } from '../../src/rollup/types'; import { bold, cyan, green, underline } from '../../src/utils/colors'; import relativeId from '../../src/utils/relativeId'; import { handleError, stderr } from '../logging'; -import { BatchWarnings } from './batchWarnings'; +import type { BatchWarnings } from './batchWarnings'; import { getConfigPath } from './getConfigPath'; import loadAndParseConfigFile from './loadConfigFile'; import loadConfigFromCommand from './loadConfigFromCommand'; diff --git a/src/Bundle.ts b/src/Bundle.ts index 6c23f85d34e..8fcac9d9bd3 100644 --- a/src/Bundle.ts +++ b/src/Bundle.ts @@ -1,8 +1,8 @@ import Chunk from './Chunk'; -import ExternalModule from './ExternalModule'; -import Graph from './Graph'; +import type ExternalModule from './ExternalModule'; +import type Graph from './Graph'; import Module from './Module'; -import { +import type { GetManualChunk, NormalizedInputOptions, NormalizedOutputOptions, @@ -13,8 +13,8 @@ import { WarningHandler } from './rollup/types'; import { FILE_PLACEHOLDER } from './utils/FileEmitter'; -import { PluginDriver } from './utils/PluginDriver'; -import { Addons, createAddons } from './utils/addons'; +import type { PluginDriver } from './utils/PluginDriver'; +import { type Addons, createAddons } from './utils/addons'; import { getChunkAssignments } from './utils/chunkAssignment'; import commondir from './utils/commondir'; import { @@ -25,7 +25,7 @@ import { warnDeprecation } from './utils/error'; import { sortByExecutionOrder } from './utils/executionOrder'; -import { GenerateCodeSnippets, getGenerateCodeSnippets } from './utils/generateCodeSnippets'; +import { type GenerateCodeSnippets, getGenerateCodeSnippets } from './utils/generateCodeSnippets'; import { basename, isAbsolute } from './utils/path'; import { timeEnd, timeStart } from './utils/timers'; @@ -104,7 +104,7 @@ export default class Bundle { } private async addManualChunks( - manualChunks: Record + manualChunks: Record ): Promise> { const manualChunkAliasByEntry = new Map(); const chunkEntries = await Promise.all( @@ -305,7 +305,7 @@ function validateOptionsForMultiChunkOutput( ); } -function getIncludedModules(modulesById: Map): Module[] { +function getIncludedModules(modulesById: ReadonlyMap): Module[] { return [...modulesById.values()].filter( (module): module is Module => module instanceof Module && @@ -317,7 +317,7 @@ function addModuleToManualChunk( alias: string, module: Module, manualChunkAliasByEntry: Map -) { +): void { const existingAlias = manualChunkAliasByEntry.get(module); if (typeof existingAlias === 'string' && existingAlias !== alias) { return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias)); diff --git a/src/Chunk.ts b/src/Chunk.ts index abe85246265..4fd0b855972 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -1,17 +1,17 @@ -import MagicString, { Bundle as MagicStringBundle, SourceMap } from 'magic-string'; +import MagicString, { Bundle as MagicStringBundle, type SourceMap } from 'magic-string'; import { relative } from '../browser/path'; import ExternalModule from './ExternalModule'; import Module from './Module'; import ExportDefaultDeclaration from './ast/nodes/ExportDefaultDeclaration'; import FunctionDeclaration from './ast/nodes/FunctionDeclaration'; -import ChildScope from './ast/scopes/ChildScope'; +import type ChildScope from './ast/scopes/ChildScope'; import ExportDefaultVariable from './ast/variables/ExportDefaultVariable'; import LocalVariable from './ast/variables/LocalVariable'; import NamespaceVariable from './ast/variables/NamespaceVariable'; import SyntheticNamedExportVariable from './ast/variables/SyntheticNamedExportVariable'; -import Variable from './ast/variables/Variable'; +import type Variable from './ast/variables/Variable'; import finalisers from './finalisers/index'; -import { +import type { DecodedSourceMapOrMissing, GetInterop, GlobalsOption, @@ -23,11 +23,11 @@ import { RenderedModule, WarningHandler } from './rollup/types'; -import { PluginDriver } from './utils/PluginDriver'; -import { Addons } from './utils/addons'; +import type { PluginDriver } from './utils/PluginDriver'; +import type { Addons } from './utils/addons'; import { collapseSourcemaps } from './utils/collapseSourcemaps'; import { createHash } from './utils/crypto'; -import { deconflictChunk, DependenciesToBeDeconflicted } from './utils/deconflictChunk'; +import { deconflictChunk, type DependenciesToBeDeconflicted } from './utils/deconflictChunk'; import { errCyclicCrossChunkReexport, errFailedValidation, @@ -38,7 +38,7 @@ import { } from './utils/error'; import { escapeId } from './utils/escapeId'; import { assignExportsToMangledNames, assignExportsToNames } from './utils/exportNames'; -import { GenerateCodeSnippets } from './utils/generateCodeSnippets'; +import type { GenerateCodeSnippets } from './utils/generateCodeSnippets'; import getExportMode from './utils/getExportMode'; import { getId } from './utils/getId'; import getIndentString from './utils/getIndentString'; @@ -54,7 +54,7 @@ import { import { basename, dirname, extname, isAbsolute, normalize, resolve } from './utils/path'; import relativeId, { getAliasName } from './utils/relativeId'; import renderChunk from './utils/renderChunk'; -import { RenderOptions } from './utils/renderHelpers'; +import type { RenderOptions } from './utils/renderHelpers'; import { makeUnique, renderNamePattern } from './utils/renderNamePattern'; import { timeEnd, timeStart } from './utils/timers'; import { MISSING_EXPORT_SHIM_VARIABLE } from './utils/variableNames'; @@ -165,13 +165,13 @@ export default class Chunk { private strictFacade = false; private usedModules: Module[] = undefined as never; constructor( - private readonly orderedModules: Module[], + private readonly orderedModules: readonly Module[], private readonly inputOptions: NormalizedInputOptions, private readonly outputOptions: NormalizedOutputOptions, - private readonly unsetOptions: Set, + private readonly unsetOptions: ReadonlySet, private readonly pluginDriver: PluginDriver, - private readonly modulesById: Map, - private readonly chunkByModule: Map, + private readonly modulesById: ReadonlyMap, + private readonly chunkByModule: ReadonlyMap, private readonly facadeChunkByModule: Map, private readonly includedNamespaces: Set, private readonly manualChunkAlias: string | null @@ -209,10 +209,10 @@ export default class Chunk { private static generateFacade( inputOptions: NormalizedInputOptions, outputOptions: NormalizedOutputOptions, - unsetOptions: Set, + unsetOptions: ReadonlySet, pluginDriver: PluginDriver, - modulesById: Map, - chunkByModule: Map, + modulesById: ReadonlyMap, + chunkByModule: ReadonlyMap, facadeChunkByModule: Map, includedNamespaces: Set, facadedModule: Module, @@ -833,7 +833,7 @@ export default class Chunk { } } - private checkCircularDependencyImport(variable: Variable, importingModule: Module) { + private checkCircularDependencyImport(variable: Variable, importingModule: Module): void { const variableModule = variable.module; if (variableModule instanceof Module) { const exportChunk = this.chunkByModule.get(variableModule); diff --git a/src/ExternalModule.ts b/src/ExternalModule.ts index 8071e2c61d9..e83f5409a9d 100644 --- a/src/ExternalModule.ts +++ b/src/ExternalModule.ts @@ -1,5 +1,5 @@ import ExternalVariable from './ast/variables/ExternalVariable'; -import { +import type { CustomPluginOptions, ModuleInfo, NormalizedInputOptions, diff --git a/src/Graph.ts b/src/Graph.ts index df2ed2fb29c..38afb11c095 100644 --- a/src/Graph.ts +++ b/src/Graph.ts @@ -1,10 +1,10 @@ import * as acorn from 'acorn'; -import ExternalModule from './ExternalModule'; +import type ExternalModule from './ExternalModule'; import Module from './Module'; -import { ModuleLoader, UnresolvedModule } from './ModuleLoader'; +import { ModuleLoader, type UnresolvedModule } from './ModuleLoader'; import GlobalScope from './ast/scopes/GlobalScope'; import { PathTracker } from './ast/utils/PathTracker'; -import { +import type { ModuleInfo, ModuleJSON, NormalizedInputOptions, diff --git a/src/Module.ts b/src/Module.ts index 443d16e9c43..0c9d09f1a63 100644 --- a/src/Module.ts +++ b/src/Module.ts @@ -3,31 +3,31 @@ import * as acorn from 'acorn'; import { locate } from 'locate-character'; import MagicString from 'magic-string'; import ExternalModule from './ExternalModule'; -import Graph from './Graph'; +import type Graph from './Graph'; import { createHasEffectsContext, createInclusionContext } from './ast/ExecutionContext'; import ExportAllDeclaration from './ast/nodes/ExportAllDeclaration'; import ExportDefaultDeclaration from './ast/nodes/ExportDefaultDeclaration'; -import ExportNamedDeclaration from './ast/nodes/ExportNamedDeclaration'; -import Identifier from './ast/nodes/Identifier'; -import ImportDeclaration from './ast/nodes/ImportDeclaration'; -import ImportExpression from './ast/nodes/ImportExpression'; +import type ExportNamedDeclaration from './ast/nodes/ExportNamedDeclaration'; +import type Identifier from './ast/nodes/Identifier'; +import type ImportDeclaration from './ast/nodes/ImportDeclaration'; +import type ImportExpression from './ast/nodes/ImportExpression'; import Literal from './ast/nodes/Literal'; -import MetaProperty from './ast/nodes/MetaProperty'; +import type MetaProperty from './ast/nodes/MetaProperty'; import * as NodeType from './ast/nodes/NodeType'; import Program from './ast/nodes/Program'; import TemplateLiteral from './ast/nodes/TemplateLiteral'; import VariableDeclaration from './ast/nodes/VariableDeclaration'; import { nodeConstructors } from './ast/nodes/index'; -import { ExpressionNode, NodeBase } from './ast/nodes/shared/Node'; +import type { ExpressionNode, NodeBase } from './ast/nodes/shared/Node'; import ModuleScope from './ast/scopes/ModuleScope'; -import { PathTracker, UNKNOWN_PATH } from './ast/utils/PathTracker'; +import { type PathTracker, UNKNOWN_PATH } from './ast/utils/PathTracker'; import ExportDefaultVariable from './ast/variables/ExportDefaultVariable'; import ExportShimVariable from './ast/variables/ExportShimVariable'; import ExternalVariable from './ast/variables/ExternalVariable'; import NamespaceVariable from './ast/variables/NamespaceVariable'; import SyntheticNamedExportVariable from './ast/variables/SyntheticNamedExportVariable'; -import Variable from './ast/variables/Variable'; -import { +import type Variable from './ast/variables/Variable'; +import type { CustomPluginOptions, DecodedSourceMapOrMissing, EmittedFile, @@ -62,7 +62,7 @@ import { getOriginalLocation } from './utils/getOriginalLocation'; import { makeLegal } from './utils/identifierHelpers'; import { basename, extname } from './utils/path'; import relativeId from './utils/relativeId'; -import { RenderOptions } from './utils/renderHelpers'; +import type { RenderOptions } from './utils/renderHelpers'; import { timeEnd, timeStart } from './utils/timers'; import { markModuleAndImpureDependenciesAsExecuted } from './utils/traverseStaticDependencies'; import { MISSING_EXPORT_SHIM_VARIABLE } from './utils/variableNames'; @@ -991,12 +991,14 @@ export default class Module { private addRelevantSideEffectDependencies( relevantDependencies: Set, - necessaryDependencies: Set, - alwaysCheckedDependencies: Set + necessaryDependencies: ReadonlySet, + alwaysCheckedDependencies: ReadonlySet ): void { const handledDependencies = new Set(); - const addSideEffectDependencies = (possibleDependencies: Set) => { + const addSideEffectDependencies = ( + possibleDependencies: ReadonlySet + ) => { for (const dependency of possibleDependencies) { if (handledDependencies.has(dependency)) { continue; diff --git a/src/ModuleLoader.ts b/src/ModuleLoader.ts index 7fd31350013..5b7aa53174e 100644 --- a/src/ModuleLoader.ts +++ b/src/ModuleLoader.ts @@ -1,7 +1,7 @@ import * as acorn from 'acorn'; import ExternalModule from './ExternalModule'; -import Graph from './Graph'; -import Module, { DynamicImport } from './Module'; +import type Graph from './Graph'; +import Module, { type DynamicImport } from './Module'; import type { CustomPluginOptions, EmittedChunk, @@ -15,7 +15,7 @@ import type { ResolvedId, ResolveIdResult } from './rollup/types'; -import { PluginDriver } from './utils/PluginDriver'; +import type { PluginDriver } from './utils/PluginDriver'; import { EMPTY_OBJECT } from './utils/blank'; import { errBadLoader, @@ -584,10 +584,8 @@ export class ModuleLoader { moduleSideEffects: this.hasModuleSideEffects(source, true), syntheticNamedExports: false }; - } else { - if (resolvedId.external && resolvedId.syntheticNamedExports) { - this.options.onwarn(errExternalSyntheticExports(source, importer)); - } + } else if (resolvedId.external && resolvedId.syntheticNamedExports) { + this.options.onwarn(errExternalSyntheticExports(source, importer)); } return resolvedId; } diff --git a/src/ast/scopes/ChildScope.ts b/src/ast/scopes/ChildScope.ts index 96ca9d95c67..cc679dce13c 100644 --- a/src/ast/scopes/ChildScope.ts +++ b/src/ast/scopes/ChildScope.ts @@ -51,8 +51,8 @@ export default class ChildScope extends Scope { addUsedOutsideNames( usedNames: Set, format: InternalModuleFormat, - exportNamesByVariable: ReadonlyMap, - accessedGlobalsByScope: ReadonlyMap> + exportNamesByVariable: ReadonlyMap, + accessedGlobalsByScope: ReadonlyMap> ): void { for (const variable of this.accessedOutsideVariables.values()) { if (variable.included) { @@ -76,8 +76,8 @@ export default class ChildScope extends Scope { deconflict( format: InternalModuleFormat, - exportNamesByVariable: ReadonlyMap, - accessedGlobalsByScope: ReadonlyMap> + exportNamesByVariable: ReadonlyMap, + accessedGlobalsByScope: ReadonlyMap> ): void { const usedNames = new Set(); this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope); diff --git a/src/ast/scopes/ModuleScope.ts b/src/ast/scopes/ModuleScope.ts index e6e328a7b89..a264626885c 100644 --- a/src/ast/scopes/ModuleScope.ts +++ b/src/ast/scopes/ModuleScope.ts @@ -33,8 +33,8 @@ export default class ModuleScope extends ChildScope { deconflict( format: InternalModuleFormat, - exportNamesByVariable: ReadonlyMap, - accessedGlobalsByScope: ReadonlyMap> + exportNamesByVariable: ReadonlyMap, + accessedGlobalsByScope: ReadonlyMap> ): void { // all module level variables are already deconflicted when deconflicting the chunk for (const scope of this.children) diff --git a/src/rollup/rollup.ts b/src/rollup/rollup.ts index f1b19802c57..fc9eacf5028 100644 --- a/src/rollup/rollup.ts +++ b/src/rollup/rollup.ts @@ -1,18 +1,18 @@ import { version as rollupVersion } from 'package.json'; import Bundle from '../Bundle'; import Graph from '../Graph'; -import { PluginDriver } from '../utils/PluginDriver'; +import type { PluginDriver } from '../utils/PluginDriver'; import { ensureArray } from '../utils/ensureArray'; import { errAlreadyClosed, errCannotEmitFromOptionsHook, error } from '../utils/error'; import { writeFile } from '../utils/fs'; import { normalizeInputOptions } from '../utils/options/normalizeInputOptions'; import { normalizeOutputOptions } from '../utils/options/normalizeOutputOptions'; -import { GenericConfigObject } from '../utils/options/options'; +import type { GenericConfigObject } from '../utils/options/options'; import { basename, dirname, resolve } from '../utils/path'; import { ANONYMOUS_OUTPUT_PLUGIN_PREFIX, ANONYMOUS_PLUGIN_PREFIX } from '../utils/pluginUtils'; import { SOURCEMAPPING_URL } from '../utils/sourceMappingURL'; import { getTimings, initialiseTimers, timeEnd, timeStart } from '../utils/timers'; -import { +import type { NormalizedInputOptions, NormalizedOutputOptions, OutputAsset, @@ -136,7 +136,7 @@ function applyOptionHook(watchMode: boolean) { }; } -function normalizePlugins(plugins: Plugin[], anonymousPrefix: string): void { +function normalizePlugins(plugins: readonly Plugin[], anonymousPrefix: string): void { for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) { const plugin = plugins[pluginIndex]; if (!plugin.name) { @@ -148,7 +148,7 @@ function normalizePlugins(plugins: Plugin[], anonymousPrefix: string): void { async function handleGenerateWrite( isWrite: boolean, inputOptions: NormalizedInputOptions, - unsetInputOptions: Set, + unsetInputOptions: ReadonlySet, rawOutputOptions: GenericConfigObject, graph: Graph ): Promise { @@ -181,7 +181,7 @@ function getOutputOptionsAndPluginDriver( rawOutputOptions: GenericConfigObject, inputPluginDriver: PluginDriver, inputOptions: NormalizedInputOptions, - unsetInputOptions: Set + unsetInputOptions: ReadonlySet ): { options: NormalizedOutputOptions; outputPluginDriver: PluginDriver; @@ -202,7 +202,7 @@ function getOutputOptionsAndPluginDriver( function getOutputOptions( inputOptions: NormalizedInputOptions, - unsetInputOptions: Set, + unsetInputOptions: ReadonlySet, rawOutputOptions: GenericConfigObject, outputPluginDriver: PluginDriver ): { options: NormalizedOutputOptions; unsetOptions: Set } { diff --git a/src/utils/FileEmitter.ts b/src/utils/FileEmitter.ts index c88c1205881..2845bcafff6 100644 --- a/src/utils/FileEmitter.ts +++ b/src/utils/FileEmitter.ts @@ -1,7 +1,7 @@ -import Chunk from '../Chunk'; -import Graph from '../Graph'; -import Module from '../Module'; -import { +import type Chunk from '../Chunk'; +import type Graph from '../Graph'; +import type Module from '../Module'; +import type { EmittedChunk, FilePlaceholder, NormalizedInputOptions, @@ -141,7 +141,7 @@ function getAssetFileName(file: ConsumedAsset, referenceId: string): string { function getChunkFileName( file: ConsumedChunk, - facadeChunkByModule: Map | null + facadeChunkByModule: ReadonlyMap | null ): string { const fileName = file.fileName || (file.module && facadeChunkByModule?.get(file.module)?.id); if (!fileName) return error(errChunkNotGeneratedForFileName(file.fileName || file.name)); @@ -150,8 +150,8 @@ function getChunkFileName( export class FileEmitter { private bundle: OutputBundleWithPlaceholders | null = null; - private facadeChunkByModule: Map | null = null; - private filesByReferenceId: Map; + private facadeChunkByModule: ReadonlyMap | null = null; + private readonly filesByReferenceId: Map; private outputOptions: NormalizedOutputOptions | null = null; constructor( @@ -231,7 +231,7 @@ export class FileEmitter { public setOutputBundle = ( outputBundle: OutputBundleWithPlaceholders, outputOptions: NormalizedOutputOptions, - facadeChunkByModule: Map + facadeChunkByModule: ReadonlyMap ): void => { this.outputOptions = outputOptions; this.bundle = outputBundle; diff --git a/src/utils/PluginCache.ts b/src/utils/PluginCache.ts index bc86d580bb6..65e3fb90d45 100644 --- a/src/utils/PluginCache.ts +++ b/src/utils/PluginCache.ts @@ -1,4 +1,4 @@ -import { PluginCache, SerializablePluginCache } from '../rollup/types'; +import type { PluginCache, SerializablePluginCache } from '../rollup/types'; import { error } from './error'; import { ANONYMOUS_OUTPUT_PLUGIN_PREFIX, ANONYMOUS_PLUGIN_PREFIX } from './pluginUtils'; diff --git a/src/utils/PluginContext.ts b/src/utils/PluginContext.ts index 5afd1d7dfc1..2994e32c501 100644 --- a/src/utils/PluginContext.ts +++ b/src/utils/PluginContext.ts @@ -1,13 +1,13 @@ import { version as rollupVersion } from 'package.json'; -import Graph from '../Graph'; -import { +import type Graph from '../Graph'; +import type { NormalizedInputOptions, Plugin, PluginCache, PluginContext, SerializablePluginCache } from '../rollup/types'; -import { FileEmitter } from './FileEmitter'; +import type { FileEmitter } from './FileEmitter'; import { createPluginCache, getCacheForUncacheablePlugin, NO_CACHE } from './PluginCache'; import { BLANK } from './blank'; import { BuildPhase } from './buildPhase'; diff --git a/src/utils/PluginDriver.ts b/src/utils/PluginDriver.ts index b96b54880b1..e37bdab5e0b 100644 --- a/src/utils/PluginDriver.ts +++ b/src/utils/PluginDriver.ts @@ -1,7 +1,7 @@ -import Chunk from '../Chunk'; -import Graph from '../Graph'; -import Module from '../Module'; -import { +import type Chunk from '../Chunk'; +import type Graph from '../Graph'; +import type Module from '../Module'; +import type { AddonHookFunction, AsyncPluginHooks, EmitFile, @@ -63,7 +63,7 @@ const inputHooks = Object.keys(inputHookNames); export type ReplaceContext = (context: PluginContext, plugin: Plugin) => PluginContext; -function throwInvalidHookError(hookName: string, pluginName: string) { +function throwInvalidHookError(hookName: string, pluginName: string): never { return error({ code: 'INVALID_PLUGIN_HOOK', message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.` @@ -77,13 +77,13 @@ export class PluginDriver { public readonly setOutputBundle: ( outputBundle: OutputBundleWithPlaceholders, outputOptions: NormalizedOutputOptions, - facadeChunkByModule: Map + facadeChunkByModule: ReadonlyMap ) => void; private readonly fileEmitter: FileEmitter; private readonly pluginCache: Record | undefined; - private readonly pluginContexts = new Map(); - private readonly plugins: Plugin[]; + private readonly pluginContexts: ReadonlyMap; + private readonly plugins: readonly Plugin[]; constructor( private readonly graph: Graph, @@ -105,12 +105,14 @@ export class PluginDriver { this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter); this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []); const existingPluginNames = new Set(); - for (const plugin of this.plugins) { - this.pluginContexts.set( + + this.pluginContexts = new Map( + this.plugins.map(plugin => [ plugin, getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames) - ); - } + ]) + ); + if (basePluginDriver) { for (const plugin of userPlugins) { for (const hook of inputHooks) { diff --git a/src/utils/addons.ts b/src/utils/addons.ts index 1f5bb356793..c9daeb4f12c 100644 --- a/src/utils/addons.ts +++ b/src/utils/addons.ts @@ -1,5 +1,5 @@ -import { NormalizedOutputOptions } from '../rollup/types'; -import { PluginDriver } from './PluginDriver'; +import type { NormalizedOutputOptions } from '../rollup/types'; +import type { PluginDriver } from './PluginDriver'; import { error } from './error'; export interface Addons { diff --git a/src/utils/blank.ts b/src/utils/blank.ts index b0715d324b9..a0741f4a212 100644 --- a/src/utils/blank.ts +++ b/src/utils/blank.ts @@ -1,3 +1,3 @@ -export const BLANK: Record = Object.freeze(Object.create(null)); +export const BLANK: Record = Object.freeze(Object.create(null)); export const EMPTY_OBJECT = Object.freeze({}); export const EMPTY_ARRAY = Object.freeze([]); diff --git a/src/utils/chunkAssignment.ts b/src/utils/chunkAssignment.ts index a4fe740d3b2..4a42e3da78a 100644 --- a/src/utils/chunkAssignment.ts +++ b/src/utils/chunkAssignment.ts @@ -6,11 +6,11 @@ type DependentModuleMap = Map>; type ChunkDefinitions = { alias: string | null; modules: Module[] }[]; export function getChunkAssignments( - entryModules: Module[], - manualChunkAliasByEntry: Map + entryModules: readonly Module[], + manualChunkAliasByEntry: ReadonlyMap ): ChunkDefinitions { const chunkDefinitions: ChunkDefinitions = []; - const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys()); + const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys()); const manualChunkModulesByAlias: Record = Object.create(null); for (const [entry, alias] of manualChunkAliasByEntry) { const chunkModules = (manualChunkModulesByAlias[alias] = @@ -29,7 +29,7 @@ export function getChunkAssignments( function assignEntryToStaticDependencies( entry: Module, - dynamicDependentEntryPoints: Set | null + dynamicDependentEntryPoints: ReadonlySet | null ) { const modulesToHandle = new Set([entry]); for (const module of modulesToHandle) { @@ -54,8 +54,8 @@ export function getChunkAssignments( } function areEntryPointsContainedOrDynamicallyDependent( - entryPoints: Set, - containedIn: Set + entryPoints: ReadonlySet, + containedIn: ReadonlySet ): boolean { const entriesToCheck = new Set(entryPoints); for (const entry of entriesToCheck) { @@ -96,7 +96,7 @@ function addStaticDependenciesToManualChunk( entry: Module, manualChunkModules: Module[], modulesInManualChunks: Set -) { +): void { const modulesToHandle = new Set([entry]); for (const module of modulesToHandle) { modulesInManualChunks.add(module); @@ -109,7 +109,7 @@ function addStaticDependenciesToManualChunk( } } -function analyzeModuleGraph(entryModules: Module[]): { +function analyzeModuleGraph(entryModules: readonly Module[]): { dependentEntryPointsByModule: DependentModuleMap; dynamicEntryModules: Set; } { @@ -117,7 +117,7 @@ function analyzeModuleGraph(entryModules: Module[]): { const dependentEntryPointsByModule: DependentModuleMap = new Map(); const entriesToHandle = new Set(entryModules); for (const currentEntry of entriesToHandle) { - const modulesToHandle = new Set([currentEntry]); + const modulesToHandle = new Set([currentEntry]); for (const module of modulesToHandle) { getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry); for (const dependency of module.getDependenciesToBeIncluded()) { @@ -142,7 +142,7 @@ function analyzeModuleGraph(entryModules: Module[]): { function getDynamicDependentEntryPoints( dependentEntryPointsByModule: DependentModuleMap, - dynamicEntryModules: Set + dynamicEntryModules: ReadonlySet ): DependentModuleMap { const dynamicallyDependentEntryPointsByDynamicEntry: DependentModuleMap = new Map(); for (const dynamicEntry of dynamicEntryModules) { @@ -164,7 +164,7 @@ function getDynamicDependentEntryPoints( } function createChunks( - allEntryPoints: Module[], + allEntryPoints: readonly Module[], assignedEntryPointsByModule: DependentModuleMap ): ChunkDefinitions { const chunkModules: { [chunkSignature: string]: Module[] } = Object.create(null); diff --git a/src/utils/collapseSourcemaps.ts b/src/utils/collapseSourcemaps.ts index 2d188baaa03..2f9ac46025d 100644 --- a/src/utils/collapseSourcemaps.ts +++ b/src/utils/collapseSourcemaps.ts @@ -1,6 +1,6 @@ -import { DecodedSourceMap, SourceMap } from 'magic-string'; -import Module from '../Module'; -import { +import { type DecodedSourceMap, SourceMap } from 'magic-string'; +import type Module from '../Module'; +import type { DecodedSourceMapOrMissing, ExistingDecodedSourceMap, SourceMapSegment, @@ -32,12 +32,12 @@ interface SourceMapSegmentObject { } class Link { - readonly mappings: SourceMapSegment[][]; - readonly names: string[]; + readonly mappings: readonly SourceMapSegment[][]; + readonly names: readonly string[]; readonly sources: (Source | Link)[]; constructor( - map: { mappings: SourceMapSegment[][]; names: string[] }, + map: { mappings: readonly SourceMapSegment[][]; names: readonly string[] }, sources: (Source | Link)[] ) { this.sources = sources; @@ -218,12 +218,8 @@ export function collapseSourcemaps( ) ); - // DecodedSourceMap (from magic-string) uses a number[] instead of the more - // correct SourceMapSegment tuples. Cast it here to gain type safety. - let source = new Link(map as ExistingDecodedSourceMap, moduleSources); - - source = bundleSourcemapChain.reduce(linkMap, source); - + const link = new Link(map, moduleSources); + const source = bundleSourcemapChain.reduce(linkMap, link); let { sources, sourcesContent, names, mappings } = source.traceMappings(); if (file) { diff --git a/src/utils/decodedSourcemap.ts b/src/utils/decodedSourcemap.ts index 3b4acfcf6a4..f49e4f64336 100644 --- a/src/utils/decodedSourcemap.ts +++ b/src/utils/decodedSourcemap.ts @@ -1,5 +1,9 @@ import { decode } from 'sourcemap-codec'; -import { ExistingDecodedSourceMap, ExistingRawSourceMap, SourceMapInput } from '../rollup/types'; +import type { + ExistingDecodedSourceMap, + ExistingRawSourceMap, + SourceMapInput +} from '../rollup/types'; type Input = SourceMapInput | ExistingDecodedSourceMap | undefined; @@ -18,12 +22,7 @@ export function decodedSourcemap(map: Input): ExistingDecodedSourceMap | null { }; } - let mappings; - if (typeof map.mappings === 'string') { - mappings = decode(map.mappings); - } else { - mappings = map.mappings; - } + const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings; return { ...(map as ExistingRawSourceMap | ExistingDecodedSourceMap), mappings }; } diff --git a/src/utils/deconflictChunk.ts b/src/utils/deconflictChunk.ts index d19c41dc2a3..e3bd7e91dbe 100644 --- a/src/utils/deconflictChunk.ts +++ b/src/utils/deconflictChunk.ts @@ -1,11 +1,11 @@ -import Chunk from '../Chunk'; +import type Chunk from '../Chunk'; import ExternalModule from '../ExternalModule'; -import Module from '../Module'; -import ChildScope from '../ast/scopes/ChildScope'; +import type Module from '../Module'; +import type ChildScope from '../ast/scopes/ChildScope'; import ExportDefaultVariable from '../ast/variables/ExportDefaultVariable'; -import SyntheticNamedExportVariable from '../ast/variables/SyntheticNamedExportVariable'; -import Variable from '../ast/variables/Variable'; -import { GetInterop, InternalModuleFormat } from '../rollup/types'; +import type SyntheticNamedExportVariable from '../ast/variables/SyntheticNamedExportVariable'; +import type Variable from '../ast/variables/Variable'; +import type { GetInterop, InternalModuleFormat } from '../rollup/types'; import { canDefaultBeTakenFromNamespace, defaultInteropHelpersByInteropType, @@ -15,21 +15,21 @@ import { import { getSafeName } from './safeName'; export interface DependenciesToBeDeconflicted { - deconflictedDefault: Set; - deconflictedNamespace: Set; - dependencies: Set; + deconflictedDefault: ReadonlySet; + deconflictedNamespace: ReadonlySet; + dependencies: ReadonlySet; } const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT: { [format in InternalModuleFormat]: ( usedNames: Set, - imports: Set, + imports: ReadonlySet, dependenciesToBeDeconflicted: DependenciesToBeDeconflicted, interop: GetInterop, preserveModules: boolean, externalLiveBindings: boolean, - chunkByModule: Map, - syntheticExports: Set + chunkByModule: ReadonlyMap, + syntheticExports: ReadonlySet ) => void; } = { amd: deconflictImportsOther, @@ -43,16 +43,16 @@ const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT: { export function deconflictChunk( modules: readonly Module[], dependenciesToBeDeconflicted: DependenciesToBeDeconflicted, - imports: Set, + imports: ReadonlySet, usedNames: Set, format: InternalModuleFormat, interop: GetInterop, preserveModules: boolean, externalLiveBindings: boolean, - chunkByModule: Map, - syntheticExports: Set, - exportNamesByVariable: ReadonlyMap, - accessedGlobalsByScope: ReadonlyMap>, + chunkByModule: ReadonlyMap, + syntheticExports: ReadonlySet, + exportNamesByVariable: ReadonlyMap, + accessedGlobalsByScope: ReadonlyMap>, includedNamespaces: ReadonlySet ): void { const reversedModules = modules.slice().reverse(); @@ -88,8 +88,8 @@ function deconflictImportsEsmOrSystem( _interop: GetInterop, preserveModules: boolean, _externalLiveBindings: boolean, - chunkByModule: Map, - syntheticExports: Set + chunkByModule: ReadonlyMap, + syntheticExports: ReadonlySet ) { // This is needed for namespace reexports for (const dependency of dependenciesToBeDeconflicted.dependencies) { @@ -128,12 +128,12 @@ function deconflictImportsEsmOrSystem( function deconflictImportsOther( usedNames: Set, - imports: Set, + imports: ReadonlySet, { deconflictedDefault, deconflictedNamespace, dependencies }: DependenciesToBeDeconflicted, interop: GetInterop, preserveModules: boolean, externalLiveBindings: boolean, - chunkByModule: Map + chunkByModule: ReadonlyMap ): void { for (const chunkOrExternalModule of dependencies) { chunkOrExternalModule.variableName = getSafeName( diff --git a/src/utils/error.ts b/src/utils/error.ts index 7f583b91fa1..f17ea17f0ab 100644 --- a/src/utils/error.ts +++ b/src/utils/error.ts @@ -1,6 +1,6 @@ import { locate } from 'locate-character'; -import Module from '../Module'; -import { +import type Module from '../Module'; +import type { NormalizedInputOptions, RollupError, RollupLogProps, @@ -220,7 +220,7 @@ export function errInvalidExportOptionValue(optionValue: string): RollupLogProps export function errIncompatibleExportOptionValue( optionValue: string, - keys: string[], + keys: readonly string[], entryModule: string ): RollupLogProps { return { diff --git a/src/utils/escapeId.ts b/src/utils/escapeId.ts index ac94444ad17..ce22df4be1c 100644 --- a/src/utils/escapeId.ts +++ b/src/utils/escapeId.ts @@ -1,6 +1,7 @@ const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/; const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g; const backSlashRegEx = /\\/g; + export function escapeId(id: string): string { if (!id.match(needsEscapeRegEx)) return id; return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1'); diff --git a/src/utils/executionOrder.ts b/src/utils/executionOrder.ts index d966f993ba7..005313dadc5 100644 --- a/src/utils/executionOrder.ts +++ b/src/utils/executionOrder.ts @@ -1,4 +1,4 @@ -import ExternalModule from '../ExternalModule'; +import type ExternalModule from '../ExternalModule'; import Module from '../Module'; import relativeId from './relativeId'; @@ -71,7 +71,7 @@ export function analyseModuleExecution(entryModules: readonly Module[]): { function getCyclePath( module: Module, parent: Module, - parents: Map + parents: ReadonlyMap ): string[] { const cycleSymbol = Symbol(module.id); const path = [relativeId(module.id)]; diff --git a/src/utils/exportNames.ts b/src/utils/exportNames.ts index 880c5f90193..e24c411555e 100644 --- a/src/utils/exportNames.ts +++ b/src/utils/exportNames.ts @@ -1,4 +1,4 @@ -import Variable from '../ast/variables/Variable'; +import type Variable from '../ast/variables/Variable'; import RESERVED_NAMES from './RESERVED_NAMES'; import { toBase64 } from './base64'; diff --git a/src/utils/generateCodeSnippets.ts b/src/utils/generateCodeSnippets.ts index 4ec00a5ba99..7db90175846 100644 --- a/src/utils/generateCodeSnippets.ts +++ b/src/utils/generateCodeSnippets.ts @@ -1,4 +1,4 @@ -import { NormalizedOutputOptions } from '../rollup/types'; +import type { NormalizedOutputOptions } from '../rollup/types'; import RESERVED_NAMES from './RESERVED_NAMES'; export interface GenerateCodeSnippets { diff --git a/src/utils/getExportMode.ts b/src/utils/getExportMode.ts index d0854ef9959..d7965457c91 100644 --- a/src/utils/getExportMode.ts +++ b/src/utils/getExportMode.ts @@ -1,5 +1,5 @@ -import Chunk from '../Chunk'; -import { NormalizedOutputOptions, WarningHandler } from '../rollup/types'; +import type Chunk from '../Chunk'; +import type { NormalizedOutputOptions, WarningHandler } from '../rollup/types'; import { errIncompatibleExportOptionValue, errMixedExport, diff --git a/src/utils/getIndentString.ts b/src/utils/getIndentString.ts index b7cd960ba44..dc9f4a36157 100644 --- a/src/utils/getIndentString.ts +++ b/src/utils/getIndentString.ts @@ -1,4 +1,4 @@ -import Module from '../Module'; +import type Module from '../Module'; function guessIndentString(code: string): string | null { const lines = code.split('\n'); diff --git a/src/utils/getOriginalLocation.ts b/src/utils/getOriginalLocation.ts index fb615b0a397..f5f8e7544c8 100644 --- a/src/utils/getOriginalLocation.ts +++ b/src/utils/getOriginalLocation.ts @@ -1,4 +1,4 @@ -import { DecodedSourceMapOrMissing, ExistingDecodedSourceMap } from '../rollup/types'; +import type { DecodedSourceMapOrMissing, ExistingDecodedSourceMap } from '../rollup/types'; export function getOriginalLocation( sourcemapChain: readonly DecodedSourceMapOrMissing[], diff --git a/src/utils/getStaticDependencies.ts b/src/utils/getStaticDependencies.ts index 173206e1a78..41d4a72a26a 100644 --- a/src/utils/getStaticDependencies.ts +++ b/src/utils/getStaticDependencies.ts @@ -1,6 +1,6 @@ -import Chunk from '../Chunk'; +import type Chunk from '../Chunk'; import ExternalModule from '../ExternalModule'; -import Module from '../Module'; +import type Module from '../Module'; export function getStaticDependencies( chunk: Chunk, diff --git a/src/utils/hookActions.ts b/src/utils/hookActions.ts index eca7b630545..b94be501aa9 100644 --- a/src/utils/hookActions.ts +++ b/src/utils/hookActions.ts @@ -1,4 +1,4 @@ -const unfulfilledActions: Set<[string, string, Parameters]> = new Set(); +const unfulfilledActions = new Set<[string, string, Parameters]>(); export function addUnresolvedAction(actionTuple: [string, string, Parameters]): void { unfulfilledActions.add(actionTuple); diff --git a/src/utils/interopHelpers.ts b/src/utils/interopHelpers.ts index cbffbf7d3b1..4c4c86e7d91 100644 --- a/src/utils/interopHelpers.ts +++ b/src/utils/interopHelpers.ts @@ -37,8 +37,8 @@ export const canDefaultBeTakenFromNamespace = ( defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE; export const getHelpersBlock = ( - additionalHelpers: Set | null, - accessedGlobals: Set, + additionalHelpers: ReadonlySet | null, + accessedGlobals: ReadonlySet, indent: string, snippets: GenerateCodeSnippets, liveBindings: boolean, @@ -72,7 +72,7 @@ const HELPER_GENERATORS: { liveBindings: boolean, freeze: boolean, namespaceToStringTag: boolean, - usedHelpers: Set + usedHelpers: ReadonlySet ) => string; } = { [INTEROP_DEFAULT_LEGACY_VARIABLE](_t, snippets, liveBindings) { diff --git a/src/utils/options/mergeOptions.ts b/src/utils/options/mergeOptions.ts index 472090b1847..9a923172ba9 100644 --- a/src/utils/options/mergeOptions.ts +++ b/src/utils/options/mergeOptions.ts @@ -1,4 +1,4 @@ -import { +import type { ExternalOption, InputOptions, MergedRollupOptions, @@ -8,11 +8,11 @@ import { WarningHandlerWithDefault } from '../../rollup/types'; import { ensureArray } from '../ensureArray'; -import { CommandConfigObject } from './normalizeInputOptions'; +import type { CommandConfigObject } from './normalizeInputOptions'; import { defaultOnWarn, generatedCodePresets, - GenericConfigObject, + type GenericConfigObject, objectifyOption, objectifyOptionWithPresets, treeshakePresets, diff --git a/src/utils/options/normalizeInputOptions.ts b/src/utils/options/normalizeInputOptions.ts index de12b6dd33e..9b8805cb2af 100644 --- a/src/utils/options/normalizeInputOptions.ts +++ b/src/utils/options/normalizeInputOptions.ts @@ -1,5 +1,5 @@ import * as acorn from 'acorn'; -import { +import type { HasModuleSideEffects, InputOptions, ModuleSideEffectsOption, @@ -15,7 +15,7 @@ import { resolve } from '../path'; import relativeId from '../relativeId'; import { defaultOnWarn, - GenericConfigObject, + type GenericConfigObject, getOptionWithPreset, treeshakePresets, warnUnknownOptions diff --git a/src/utils/options/normalizeOutputOptions.ts b/src/utils/options/normalizeOutputOptions.ts index 3bae48b27a3..038204ff2db 100644 --- a/src/utils/options/normalizeOutputOptions.ts +++ b/src/utils/options/normalizeOutputOptions.ts @@ -1,4 +1,4 @@ -import { +import type { InternalModuleFormat, InteropType, NormalizedInputOptions, @@ -12,7 +12,7 @@ import { resolve } from '../path'; import { sanitizeFileName as defaultSanitizeFileName } from '../sanitizeFileName'; import { generatedCodePresets, - GenericConfigObject, + type GenericConfigObject, getOptionWithPreset, warnUnknownOptions } from './options'; @@ -20,7 +20,7 @@ import { export function normalizeOutputOptions( config: OutputOptions, inputOptions: NormalizedInputOptions, - unsetInputOptions: Set + unsetInputOptions: ReadonlySet ): { options: NormalizedOutputOptions; unsetOptions: Set } { // These are options that may trigger special warnings or behaviour later // if the user did not select an explicit value @@ -357,7 +357,14 @@ const getIndent = (config: OutputOptions, compact: boolean): NormalizedOutputOpt return configIndent === false ? '' : configIndent ?? true; }; -const ALLOWED_INTEROP_TYPES = new Set(['auto', 'esModule', 'default', 'defaultOnly', true, false]); +const ALLOWED_INTEROP_TYPES: ReadonlySet = new Set([ + 'auto', + 'esModule', + 'default', + 'defaultOnly', + true, + false +]); const getInterop = ( config: OutputOptions, diff --git a/src/utils/options/options.ts b/src/utils/options/options.ts index cfcf75b9306..5f49c2a7f21 100644 --- a/src/utils/options/options.ts +++ b/src/utils/options/options.ts @@ -1,4 +1,4 @@ -import { +import type { InputOptions, NormalizedGeneratedCodeOptions, NormalizedOutputOptions, @@ -38,7 +38,7 @@ export function warnUnknownOptions( } } -type ObjectValue = Base extends Record ? Base : never; +type ObjectValue = Base extends Record ? Base : never; export const treeshakePresets: { [key in NonNullable< diff --git a/src/utils/pluginUtils.ts b/src/utils/pluginUtils.ts index 1bac7a304c5..05cc8ba25b3 100644 --- a/src/utils/pluginUtils.ts +++ b/src/utils/pluginUtils.ts @@ -1,4 +1,4 @@ -import { NormalizedInputOptions, Plugin, RollupError } from '../rollup/types'; +import type { NormalizedInputOptions, Plugin, RollupError } from '../rollup/types'; import { error, Errors, warnDeprecation } from './error'; export const ANONYMOUS_PLUGIN_PREFIX = 'at position '; @@ -24,9 +24,9 @@ export function throwPluginError( return error(err); } -export const deprecatedHooks: { active: boolean; deprecated: string; replacement: string }[] = [ +const deprecatedHooks = [ { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' } -]; +] as const; export function warnDeprecatedHooks( plugins: readonly Plugin[], diff --git a/src/utils/pureComments.ts b/src/utils/pureComments.ts index e68eec664b8..dc385a284fa 100644 --- a/src/utils/pureComments.ts +++ b/src/utils/pureComments.ts @@ -1,5 +1,5 @@ import * as acorn from 'acorn'; -import { BaseWalker, base as basicWalker } from 'acorn-walk'; +import { type BaseWalker, base as basicWalker } from 'acorn-walk'; import { BinaryExpression, CallExpression, @@ -50,7 +50,7 @@ const neitherWithespaceNorBrackets = /[^\s(]/g; const noWhitespace = /\S/g; function markPureNode(node: NodeWithComments, comment: acorn.Comment, code: string): void { - const annotatedNodes = []; + const annotatedNodes: NodeWithComments[] = []; let invalidAnnotation: boolean | undefined; const codeInBetween = code.slice(comment.end, node.start); if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) { @@ -129,7 +129,7 @@ function doesNotMatchOutsideComment(code: string, forbiddenChars: RegExp): boole const pureCommentRegex = /[@#]__PURE__/; export function addAnnotations( - comments: acorn.Comment[], + comments: readonly acorn.Comment[], esTreeAst: acorn.Node, code: string ): void { diff --git a/src/utils/reassignedExportsMember.ts b/src/utils/reassignedExportsMember.ts index c7ac51146f1..41abd0ad2e3 100644 --- a/src/utils/reassignedExportsMember.ts +++ b/src/utils/reassignedExportsMember.ts @@ -1,8 +1,8 @@ -import Variable from '../ast/variables/Variable'; +import type Variable from '../ast/variables/Variable'; export function isReassignedExportsMember( variable: Variable, - exportNamesByVariable: ReadonlyMap + exportNamesByVariable: ReadonlyMap ): boolean { return ( variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned diff --git a/src/utils/renderChunk.ts b/src/utils/renderChunk.ts index ac0c63e62a5..8b2467abd61 100644 --- a/src/utils/renderChunk.ts +++ b/src/utils/renderChunk.ts @@ -1,11 +1,11 @@ -import { +import type { DecodedSourceMapOrMissing, NormalizedOutputOptions, Plugin, RenderedChunk, SourceMapInput } from '../rollup/types'; -import { PluginDriver } from './PluginDriver'; +import type { PluginDriver } from './PluginDriver'; import { decodedSourcemap } from './decodedSourcemap'; export default function renderChunk({ diff --git a/src/utils/renderHelpers.ts b/src/utils/renderHelpers.ts index 6e9c6c2d209..fb328ceb582 100644 --- a/src/utils/renderHelpers.ts +++ b/src/utils/renderHelpers.ts @@ -1,9 +1,9 @@ -import MagicString from 'magic-string'; -import { Node, StatementNode } from '../ast/nodes/shared/Node'; -import Variable from '../ast/variables/Variable'; -import { InternalModuleFormat } from '../rollup/types'; -import { PluginDriver } from './PluginDriver'; -import { GenerateCodeSnippets } from './generateCodeSnippets'; +import type MagicString from 'magic-string'; +import type { Node, StatementNode } from '../ast/nodes/shared/Node'; +import type Variable from '../ast/variables/Variable'; +import type { InternalModuleFormat } from '../rollup/types'; +import type { PluginDriver } from './PluginDriver'; +import type { GenerateCodeSnippets } from './generateCodeSnippets'; import { treeshakeNode } from './treeshakeNode'; export interface RenderOptions { diff --git a/src/utils/renderNamePattern.ts b/src/utils/renderNamePattern.ts index aed61cc8a68..0bf89b563b7 100644 --- a/src/utils/renderNamePattern.ts +++ b/src/utils/renderNamePattern.ts @@ -30,7 +30,7 @@ export function renderNamePattern( }); } -export function makeUnique(name: string, existingNames: Record): string { +export function makeUnique(name: string, existingNames: Record): string { const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase())); if (!existingNamesLowercase.has(name.toLocaleLowerCase())) return name; diff --git a/src/utils/resolveId.ts b/src/utils/resolveId.ts index 221cab3f79b..9654d8f85ab 100644 --- a/src/utils/resolveId.ts +++ b/src/utils/resolveId.ts @@ -1,5 +1,5 @@ -import { CustomPluginOptions, Plugin, ResolvedId, ResolveIdResult } from '../rollup/types'; -import { PluginDriver } from './PluginDriver'; +import type { CustomPluginOptions, Plugin, ResolvedId, ResolveIdResult } from '../rollup/types'; +import type { PluginDriver } from './PluginDriver'; import { lstatSync, readdirSync, realpathSync } from './fs'; import { basename, dirname, isAbsolute, resolve } from './path'; import { resolveIdViaPlugins } from './resolveIdViaPlugins'; diff --git a/src/utils/resolveIdViaPlugins.ts b/src/utils/resolveIdViaPlugins.ts index 20d177e6bc2..02a4975a8ca 100644 --- a/src/utils/resolveIdViaPlugins.ts +++ b/src/utils/resolveIdViaPlugins.ts @@ -1,11 +1,11 @@ -import { +import type { CustomPluginOptions, Plugin, PluginContext, ResolvedId, ResolveIdResult } from '../rollup/types'; -import { PluginDriver, ReplaceContext } from './PluginDriver'; +import type { PluginDriver, ReplaceContext } from './PluginDriver'; import { BLANK } from './blank'; export function resolveIdViaPlugins( diff --git a/src/utils/systemJsRendering.ts b/src/utils/systemJsRendering.ts index 6d8e9fed0a9..600778e779f 100644 --- a/src/utils/systemJsRendering.ts +++ b/src/utils/systemJsRendering.ts @@ -1,6 +1,6 @@ -import MagicString from 'magic-string'; -import Variable from '../ast/variables/Variable'; -import { RenderOptions } from './renderHelpers'; +import type MagicString from 'magic-string'; +import type Variable from '../ast/variables/Variable'; +import type { RenderOptions } from './renderHelpers'; export function getSystemExportStatement( exportedVariables: readonly Variable[], diff --git a/src/utils/transform.ts b/src/utils/transform.ts index 67cc23a3e20..a4607242320 100644 --- a/src/utils/transform.ts +++ b/src/utils/transform.ts @@ -1,6 +1,6 @@ import MagicString, { SourceMap } from 'magic-string'; -import Module from '../Module'; -import { +import type Module from '../Module'; +import type { DecodedSourceMapOrMissing, EmittedFile, ExistingRawSourceMap, @@ -15,7 +15,7 @@ import { WarningHandler } from '../rollup/types'; import { getTrackedPluginCache } from './PluginCache'; -import { PluginDriver } from './PluginDriver'; +import type { PluginDriver } from './PluginDriver'; import { collapseSourcemap } from './collapseSourcemaps'; import { decodedSourcemap } from './decodedSourcemap'; import { augmentCodeLocation, errNoTransformMapOrAstWithoutCode } from './error'; diff --git a/src/utils/traverseStaticDependencies.ts b/src/utils/traverseStaticDependencies.ts index c371d9f78ac..54a3bb42aca 100644 --- a/src/utils/traverseStaticDependencies.ts +++ b/src/utils/traverseStaticDependencies.ts @@ -1,5 +1,5 @@ import ExternalModule from '../ExternalModule'; -import Module from '../Module'; +import type Module from '../Module'; export function markModuleAndImpureDependenciesAsExecuted(baseModule: Module): void { baseModule.isExecuted = true; diff --git a/src/utils/treeshakeNode.ts b/src/utils/treeshakeNode.ts index d59d4ee5dcf..47375d87021 100644 --- a/src/utils/treeshakeNode.ts +++ b/src/utils/treeshakeNode.ts @@ -1,6 +1,6 @@ -import MagicString from 'magic-string'; +import type MagicString from 'magic-string'; import * as NodeType from '../ast/nodes/NodeType'; -import { Node } from '../ast/nodes/shared/Node'; +import type { Node } from '../ast/nodes/shared/Node'; export function treeshakeNode(node: Node, code: MagicString, start: number, end: number): void { code.remove(start, end); diff --git a/src/watch/watch-proxy.ts b/src/watch/watch-proxy.ts index a760d20cdfd..0ca30d39a1b 100644 --- a/src/watch/watch-proxy.ts +++ b/src/watch/watch-proxy.ts @@ -1,8 +1,8 @@ import { EventEmitter } from 'events'; -import { RollupWatcher } from '../rollup/types'; +import type { RollupWatcher } from '../rollup/types'; import { ensureArray } from '../utils/ensureArray'; import { errInvalidOption, error } from '../utils/error'; -import { GenericConfigObject } from '../utils/options/options'; +import type { GenericConfigObject } from '../utils/options/options'; import { loadFsEvents } from './fsevents-importer'; class WatchEmitter extends EventEmitter { diff --git a/src/watch/watch.ts b/src/watch/watch.ts index 134124cc7b1..000183491e4 100644 --- a/src/watch/watch.ts +++ b/src/watch/watch.ts @@ -1,7 +1,7 @@ import { resolve } from 'path'; import { createFilter } from '@rollup/pluginutils'; import { rollupInternal } from '../rollup/rollup'; -import { +import type { ChangeEvent, MergedRollupOptions, OutputOptions, @@ -11,7 +11,7 @@ import { WatcherOptions } from '../rollup/types'; import { mergeOptions } from '../utils/options/mergeOptions'; -import { GenericConfigObject } from '../utils/options/options'; +import type { GenericConfigObject } from '../utils/options/options'; import { FileWatcher } from './fileWatcher'; const eventsRewrites: Record> = {