From 67f74e2defb288853b3155a4b1d217642a803aa4 Mon Sep 17 00:00:00 2001 From: Daniel Nalborczyk Date: Tue, 28 Dec 2021 23:12:00 -0500 Subject: [PATCH] more type fixes --- browser/resolveId.ts | 4 +-- build-plugins/generate-license-file.ts | 8 ++--- cli/run/batchWarnings.ts | 17 ++++++---- cli/run/commandPlugins.ts | 5 ++- cli/run/getConfigPath.ts | 6 ++-- cli/run/loadConfigFile.ts | 18 +++++----- cli/run/resetScreen.ts | 2 +- cli/run/watch-cli.ts | 14 ++++---- src/Chunk.ts | 46 +++++++++++++------------- src/ModuleLoader.ts | 2 +- src/utils/PluginDriver.ts | 12 +++---- src/utils/commondir.ts | 4 +-- src/utils/getOriginalLocation.ts | 2 +- src/utils/getStaticDependencies.ts | 6 ++-- src/utils/resolveId.ts | 4 +-- src/utils/resolveIdViaPlugins.ts | 4 +-- src/watch/fileWatcher.ts | 16 ++++----- src/watch/watch.ts | 24 +++++++------- 18 files changed, 101 insertions(+), 93 deletions(-) diff --git a/browser/resolveId.ts b/browser/resolveId.ts index 945768fb94f..6eccc297b11 100644 --- a/browser/resolveId.ts +++ b/browser/resolveId.ts @@ -13,9 +13,9 @@ export async function resolveId( importer: string | undefined, customOptions: CustomPluginOptions | undefined, isEntry: boolean | undefined, - skip: { importer: string | undefined; plugin: Plugin; source: string }[] | null + skip: readonly { importer: string | undefined; plugin: Plugin; source: string }[] | null ) => Promise, - skip: { importer: string | undefined; plugin: Plugin; source: string }[] | null, + skip: readonly { importer: string | undefined; plugin: Plugin; source: string }[] | null, customOptions: CustomPluginOptions | undefined, isEntry: boolean ): Promise { diff --git a/build-plugins/generate-license-file.ts b/build-plugins/generate-license-file.ts index e64391c9617..42f1e363c38 100644 --- a/build-plugins/generate-license-file.ts +++ b/build-plugins/generate-license-file.ts @@ -1,9 +1,9 @@ -import fs from 'fs'; +import { readFileSync, writeFileSync } from 'fs'; import { PluginImpl } from 'rollup'; import license, { Dependency, Person } from 'rollup-plugin-license'; function generateLicenseFile(dependencies: Dependency[]) { - const coreLicense = fs.readFileSync('LICENSE-CORE.md'); + const coreLicense = readFileSync('LICENSE-CORE.md'); const licenses = new Set(); const dependencyLicenseTexts = dependencies .sort(({ name: nameA }, { name: nameB }) => (nameA! > nameB! ? 1 : -1)) @@ -52,9 +52,9 @@ function generateLicenseFile(dependencies: Dependency[]) { `${Array.from(licenses).join(', ')}\n\n` + `# Bundled dependencies:\n` + dependencyLicenseTexts; - const existingLicenseText = fs.readFileSync('LICENSE.md', 'utf8'); + const existingLicenseText = readFileSync('LICENSE.md', 'utf8'); if (existingLicenseText !== licenseText) { - fs.writeFileSync('LICENSE.md', licenseText); + writeFileSync('LICENSE.md', licenseText); console.warn('LICENSE.md updated. You should commit the updated file.'); } } diff --git a/cli/run/batchWarnings.ts b/cli/run/batchWarnings.ts index a6beab9daa8..48a56bca26b 100644 --- a/cli/run/batchWarnings.ts +++ b/cli/run/batchWarnings.ts @@ -248,17 +248,22 @@ const deferredHandlers: { } }; -function title(str: string) { +function title(str: string): void { stderr(bold(yellow(`(!) ${str}`))); } -function info(url: string) { +function info(url: string): void { stderr(gray(url)); } -function nest(array: T[], prop: string) { - const nested: { items: T[]; key: string }[] = []; - const lookup = new Map(); +interface Nested { + items: T[]; + key: string; +} + +function nest(array: readonly T[], prop: string): Nested[] { + const nested: Nested[] = []; + const lookup = new Map>(); for (const item of array) { const key = (item as any)[prop]; @@ -275,7 +280,7 @@ function nest(array: T[], prop: string) { return nested; } -function showTruncatedWarnings(warnings: RollupWarning[]) { +function showTruncatedWarnings(warnings: readonly RollupWarning[]): void { const nestedByModule = nest(warnings, 'id'); const displayedByModule = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule; diff --git a/cli/run/commandPlugins.ts b/cli/run/commandPlugins.ts index df4bb31d662..67fce28a866 100644 --- a/cli/run/commandPlugins.ts +++ b/cli/run/commandPlugins.ts @@ -38,7 +38,10 @@ export async function addPluginsFromCommandOption( } } -async function loadAndRegisterPlugin(inputOptions: InputOptions, pluginText: string) { +async function loadAndRegisterPlugin( + inputOptions: InputOptions, + pluginText: string +): Promise { let plugin: any = null; let pluginArg: any = undefined; if (pluginText[0] === '{') { diff --git a/cli/run/getConfigPath.ts b/cli/run/getConfigPath.ts index 10623faf256..e47039008fe 100644 --- a/cli/run/getConfigPath.ts +++ b/cli/run/getConfigPath.ts @@ -1,5 +1,5 @@ import { readdirSync } from 'fs'; -import * as path from 'path'; +import { resolve } from 'path'; import relative from 'require-relative'; import { handleError } from '../logging'; @@ -8,7 +8,7 @@ const DEFAULT_CONFIG_BASE = 'rollup.config'; export function getConfigPath(commandConfig: string | true): string { const cwd = process.cwd(); if (commandConfig === true) { - return path.resolve(findConfigFileNameInCwd()); + return resolve(findConfigFileNameInCwd()); } if (commandConfig.slice(0, 5) === 'node:') { const pkgName = commandConfig.slice(5); @@ -28,7 +28,7 @@ export function getConfigPath(commandConfig: string | true): string { } } } - return path.resolve(commandConfig); + return resolve(commandConfig); } function findConfigFileNameInCwd(): string { diff --git a/cli/run/loadConfigFile.ts b/cli/run/loadConfigFile.ts index 1ddba4d142e..3b07543aa6d 100644 --- a/cli/run/loadConfigFile.ts +++ b/cli/run/loadConfigFile.ts @@ -1,5 +1,5 @@ -import * as fs from 'fs'; -import * as path from 'path'; +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'; @@ -12,7 +12,7 @@ import { stderr } from '../logging'; import batchWarnings, { BatchWarnings } from './batchWarnings'; import { addCommandPluginsToInputOptions, addPluginsFromCommandOption } from './commandPlugins'; -function supportsNativeESM() { +function supportsNativeESM(): boolean { return Number(/^v(\d+)/.exec(process.version)![1]) >= 13; } @@ -44,7 +44,7 @@ async function loadConfigFile( fileName: string, commandOptions: Record ): Promise { - const extension = path.extname(fileName); + const extension = extname(fileName); const configFileExport = commandOptions.configPlugin || @@ -68,7 +68,7 @@ async function getDefaultFromTranspiledConfigFile( const warnings = batchWarnings(); const inputOptions = { external: (id: string) => - (id[0] !== '.' && !path.isAbsolute(id)) || id.slice(-5, id.length) === '.json', + (id[0] !== '.' && !isAbsolute(id)) || id.slice(-5, id.length) === '.json', input: fileName, onwarn: warnings.add, plugins: [], @@ -102,9 +102,9 @@ async function getDefaultFromTranspiledConfigFile( return loadConfigFromBundledFile(fileName, code); } -async function loadConfigFromBundledFile(fileName: string, bundledCode: string) { - const resolvedFileName = fs.realpathSync(fileName); - const extension = path.extname(resolvedFileName); +async function loadConfigFromBundledFile(fileName: string, bundledCode: string): Promise { + const resolvedFileName = realpathSync(fileName); + const extension = extname(resolvedFileName); const defaultLoader = require.extensions[extension]; require.extensions[extension] = (module: NodeModule, requiredFileName: string) => { if (requiredFileName === resolvedFileName) { @@ -132,7 +132,7 @@ async function loadConfigFromBundledFile(fileName: string, bundledCode: string) } } -async function getConfigList(configFileExport: any, commandOptions: any) { +async function getConfigList(configFileExport: any, commandOptions: any): Promise { const config = await (typeof configFileExport === 'function' ? configFileExport(commandOptions) : configFileExport); diff --git a/cli/run/resetScreen.ts b/cli/run/resetScreen.ts index 39fc53c70b3..3cf34ee8657 100644 --- a/cli/run/resetScreen.ts +++ b/cli/run/resetScreen.ts @@ -4,7 +4,7 @@ import { stderr } from '../logging'; const CLEAR_SCREEN = '\u001Bc'; export function getResetScreen( - configs: MergedRollupOptions[], + configs: readonly MergedRollupOptions[], allowClearScreen: boolean | undefined ): (heading: string) => void { let clearScreen = allowClearScreen; diff --git a/cli/run/watch-cli.ts b/cli/run/watch-cli.ts index 7baa555d876..9c83fc8265e 100644 --- a/cli/run/watch-cli.ts +++ b/cli/run/watch-cli.ts @@ -1,4 +1,4 @@ -import fs from 'fs'; +import { type FSWatcher, readFileSync } from 'fs'; import chokidar from 'chokidar'; import dateTime from 'date-time'; import ms from 'pretty-ms'; @@ -22,17 +22,17 @@ export async function watch(command: Record): Promise { let configs: MergedRollupOptions[]; let warnings: BatchWarnings; let watcher: RollupWatcher; - let configWatcher: fs.FSWatcher; + let configWatcher: FSWatcher; const configFile = command.config ? getConfigPath(command.config) : null; onExit(close); - process.on('uncaughtException' as any, close); + process.on('uncaughtException', close); if (!process.stdin.isTTY) { process.stdin.on('end', close); process.stdin.resume(); } - async function loadConfigFromFileAndTrack(configFile: string) { + async function loadConfigFromFileAndTrack(configFile: string): Promise { let reloadingConfig = false; let aborted = false; let configFileData: string | null = null; @@ -42,7 +42,7 @@ export async function watch(command: Record): Promise { async function reloadConfigFile() { try { - const newConfigFileData = fs.readFileSync(configFile, 'utf-8'); + const newConfigFileData = readFileSync(configFile, 'utf-8'); if (newConfigFileData === configFileData) { return; } @@ -83,7 +83,7 @@ export async function watch(command: Record): Promise { const resetScreen = getResetScreen(configs!, isTTY); - function start(configs: MergedRollupOptions[]) { + function start(configs: MergedRollupOptions[]): void { try { watcher = rollup.watch(configs as any); } catch (err: any) { @@ -144,7 +144,7 @@ export async function watch(command: Record): Promise { }); } - function close(code: number | null) { + function close(code: number | null): void { process.removeListener('uncaughtException', close); // removing a non-existent listener is a no-op process.stdin.removeListener('end', close); diff --git a/src/Chunk.ts b/src/Chunk.ts index 1f218cf595a..ffe876bc8cc 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -108,7 +108,7 @@ function getGlobalName( globals: GlobalsOption, hasExports: boolean, warn: WarningHandler -) { +): string | undefined { const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id]; if (globalName) { return globalName; @@ -126,7 +126,7 @@ function getGlobalName( } export default class Chunk { - entryModules: Module[] = []; + readonly entryModules: Module[] = []; execIndex: number; exportMode: 'none' | 'named' | 'default' = 'named'; facadeModule: Module | null = null; @@ -136,27 +136,27 @@ export default class Chunk { suggestedVariableName: string; variableName = ''; - private accessedGlobalsByScope = new Map>(); + private readonly accessedGlobalsByScope = new Map>(); private dependencies = new Set(); - private dynamicDependencies = new Set(); - private dynamicEntryModules: Module[] = []; + private readonly dynamicDependencies = new Set(); + private readonly dynamicEntryModules: Module[] = []; private dynamicName: string | null = null; - private exportNamesByVariable = new Map(); - private exports = new Set(); - private exportsByName: Record = Object.create(null); + private readonly exportNamesByVariable = new Map(); + private readonly exports = new Set(); + private readonly exportsByName: Record = Object.create(null); private fileName: string | null = null; private implicitEntryModules: Module[] = []; - private implicitlyLoadedBefore = new Set(); - private imports = new Set(); + private readonly implicitlyLoadedBefore = new Set(); + private readonly imports = new Set(); private indentString: string = undefined as never; - private readonly isEmpty: boolean = true; + private isEmpty = true; private name: string | null = null; private renderedDependencies: Map | null = null; private renderedExports: ChunkExports | null = null; - private renderedHash: string = undefined as never; - private renderedModuleSources = new Map(); - private renderedModules: { + private renderedHash: string | undefined = undefined; + private readonly renderedModuleSources = new Map(); + private readonly renderedModules: { [moduleId: string]: RenderedModule; } = Object.create(null); private renderedSource: MagicStringBundle | null = null; @@ -251,7 +251,7 @@ export default class Chunk { return chunk; } - canModuleBeFacade(module: Module, exposedVariables: Set): boolean { + canModuleBeFacade(module: Module, exposedVariables: ReadonlySet): boolean { const moduleExportNamesByVariable = module.getExportNamesByVariable(); for (const exposedVariable of this.exports) { if (!moduleExportNamesByVariable.has(exposedVariable)) { @@ -429,9 +429,9 @@ export default class Chunk { preserveModulesRelativeDir: string, options: NormalizedOutputOptions, existingNames: Record, - unsetOptions: Set + unsetOptions: ReadonlySet ): string { - const id = this.orderedModules[0].id; + const [{ id }] = this.orderedModules; const sanitizedId = this.outputOptions.sanitizeFileName(id); let path: string; @@ -641,7 +641,7 @@ export default class Chunk { this.renderedSource = magicString.trim(); } - this.renderedHash = undefined as never; + this.renderedHash = undefined; if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) { const chunkName = this.getChunkName(); @@ -811,9 +811,9 @@ export default class Chunk { } private addDependenciesToChunk( - moduleDependencies: Set, + moduleDependencies: ReadonlySet, chunkDependencies: Set - ) { + ): void { for (const module of moduleDependencies) { if (module instanceof Module) { const chunk = this.chunkByModule.get(module); @@ -826,7 +826,7 @@ export default class Chunk { } } - private assignFacadeName({ fileName, name }: FacadeName, facadedModule: Module) { + private assignFacadeName({ fileName, name }: FacadeName, facadedModule: Module): void { if (fileName) { this.fileName = fileName; } else { @@ -870,7 +870,7 @@ export default class Chunk { hash.update( [addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':') ); - hash.update(options.format as string); + hash.update(options.format); const dependenciesForHashing = new Set([this]); for (const current of dependenciesForHashing) { if (current instanceof ExternalModule) { @@ -1306,7 +1306,7 @@ export default class Chunk { break; } } - const usedNames = new Set(['Object', 'Promise']); + const usedNames = new Set(['Object', 'Promise']); if (this.needsExportsShim) { usedNames.add(MISSING_EXPORT_SHIM_VARIABLE); } diff --git a/src/ModuleLoader.ts b/src/ModuleLoader.ts index 92e602d2e13..0c01e039e1b 100644 --- a/src/ModuleLoader.ts +++ b/src/ModuleLoader.ts @@ -176,7 +176,7 @@ export class ModuleLoader { importer: string | undefined, customOptions: CustomPluginOptions | undefined, isEntry: boolean | undefined, - skip: { importer: string | undefined; plugin: Plugin; source: string }[] | null = null + skip: readonly { importer: string | undefined; plugin: Plugin; source: string }[] | null = null ): Promise => { return this.addDefaultsToResolvedId( this.getNormalizedResolvedIdWithoutDefaults( diff --git a/src/utils/PluginDriver.ts b/src/utils/PluginDriver.ts index 1c0d347a333..def22bb9dcf 100644 --- a/src/utils/PluginDriver.ts +++ b/src/utils/PluginDriver.ts @@ -69,19 +69,19 @@ function throwInvalidHookError(hookName: string, pluginName: string) { } export class PluginDriver { - public emitFile: EmitFile; + public readonly emitFile: EmitFile; public finaliseAssets: () => void; public getFileName: (fileReferenceId: string) => string; - public setOutputBundle: ( + public readonly setOutputBundle: ( outputBundle: OutputBundleWithPlaceholders, outputOptions: NormalizedOutputOptions, facadeChunkByModule: Map ) => void; - private fileEmitter: FileEmitter; - private pluginCache: Record | undefined; - private pluginContexts = new Map(); - private plugins: Plugin[]; + private readonly fileEmitter: FileEmitter; + private readonly pluginCache: Record | undefined; + private readonly pluginContexts = new Map(); + private readonly plugins: Plugin[]; constructor( private readonly graph: Graph, diff --git a/src/utils/commondir.ts b/src/utils/commondir.ts index 42619d84f36..95a705d2e4f 100644 --- a/src/utils/commondir.ts +++ b/src/utils/commondir.ts @@ -1,9 +1,9 @@ -import * as path from './path'; +import { dirname } from './path'; // ported from https://github.com/substack/node-commondir export default function commondir(files: readonly string[]): string { if (files.length === 0) return '/'; - if (files.length === 1) return path.dirname(files[0]); + if (files.length === 1) return dirname(files[0]); const commonSegments = files.slice(1).reduce((commonSegments, file) => { const pathSegements = file.split(/\/+|\\+/); let i; diff --git a/src/utils/getOriginalLocation.ts b/src/utils/getOriginalLocation.ts index 692888dd472..fb615b0a397 100644 --- a/src/utils/getOriginalLocation.ts +++ b/src/utils/getOriginalLocation.ts @@ -1,7 +1,7 @@ import { DecodedSourceMapOrMissing, ExistingDecodedSourceMap } from '../rollup/types'; export function getOriginalLocation( - sourcemapChain: DecodedSourceMapOrMissing[], + sourcemapChain: readonly DecodedSourceMapOrMissing[], location: { column: number; line: number; name?: string; source?: string } ): { column: number; line: number } { const filteredSourcemapChain = sourcemapChain.filter( diff --git a/src/utils/getStaticDependencies.ts b/src/utils/getStaticDependencies.ts index 5d3a447c9f5..173206e1a78 100644 --- a/src/utils/getStaticDependencies.ts +++ b/src/utils/getStaticDependencies.ts @@ -4,8 +4,8 @@ import Module from '../Module'; export function getStaticDependencies( chunk: Chunk, - orderedModules: Module[], - chunkByModule: Map + orderedModules: readonly Module[], + chunkByModule: ReadonlyMap ): Set { const staticDependencyBlocks: (Chunk | ExternalModule)[][] = []; const handledDependencies = new Set(); @@ -31,7 +31,7 @@ function addStaticDependencies( staticDependencies: (Chunk | ExternalModule)[], handledModules: Set, chunk: Chunk, - chunkByModule: Map + chunkByModule: ReadonlyMap ): void { const dependencies = module.getDependenciesToBeIncluded(); for (const dependency of dependencies) { diff --git a/src/utils/resolveId.ts b/src/utils/resolveId.ts index c6a908f926f..221cab3f79b 100644 --- a/src/utils/resolveId.ts +++ b/src/utils/resolveId.ts @@ -14,9 +14,9 @@ export async function resolveId( importer: string | undefined, customOptions: CustomPluginOptions | undefined, isEntry: boolean | undefined, - skip: { importer: string | undefined; plugin: Plugin; source: string }[] | null + skip: readonly { importer: string | undefined; plugin: Plugin; source: string }[] | null ) => Promise, - skip: { importer: string | undefined; plugin: Plugin; source: string }[] | null, + skip: readonly { importer: string | undefined; plugin: Plugin; source: string }[] | null, customOptions: CustomPluginOptions | undefined, isEntry: boolean ): Promise { diff --git a/src/utils/resolveIdViaPlugins.ts b/src/utils/resolveIdViaPlugins.ts index 23a14a332d6..20d177e6bc2 100644 --- a/src/utils/resolveIdViaPlugins.ts +++ b/src/utils/resolveIdViaPlugins.ts @@ -17,9 +17,9 @@ export function resolveIdViaPlugins( importer: string | undefined, customOptions: CustomPluginOptions | undefined, isEntry: boolean | undefined, - skip: { importer: string | undefined; plugin: Plugin; source: string }[] | null + skip: readonly { importer: string | undefined; plugin: Plugin; source: string }[] | null ) => Promise, - skip: { importer: string | undefined; plugin: Plugin; source: string }[] | null, + skip: readonly { importer: string | undefined; plugin: Plugin; source: string }[] | null, customOptions: CustomPluginOptions | undefined, isEntry: boolean ): Promise { diff --git a/src/watch/fileWatcher.ts b/src/watch/fileWatcher.ts index d774b74b04d..f586ae7f1f5 100644 --- a/src/watch/fileWatcher.ts +++ b/src/watch/fileWatcher.ts @@ -1,13 +1,13 @@ import { platform } from 'os'; -import chokidar, { FSWatcher } from 'chokidar'; -import { ChangeEvent, ChokidarOptions } from '../rollup/types'; -import { Task } from './watch'; +import chokidar, { type FSWatcher } from 'chokidar'; +import type { ChangeEvent, ChokidarOptions } from '../rollup/types'; +import type { Task } from './watch'; export class FileWatcher { - private chokidarOptions: ChokidarOptions; - private task: Task; - private transformWatchers = new Map(); - private watcher: FSWatcher; + private readonly chokidarOptions: ChokidarOptions; + private readonly task: Task; + private readonly transformWatchers = new Map(); + private readonly watcher: FSWatcher; constructor(task: Task, chokidarOptions: ChokidarOptions) { this.chokidarOptions = chokidarOptions; @@ -33,7 +33,7 @@ export class FileWatcher { watch(id: string, isTransformDependency: boolean): void { if (isTransformDependency) { - const watcher = this.transformWatchers.get(id) || this.createWatcher(id); + const watcher = this.transformWatchers.get(id) ?? this.createWatcher(id); watcher.add(id); this.transformWatchers.set(id, watcher); } else { diff --git a/src/watch/watch.ts b/src/watch/watch.ts index 9ed301f729e..134124cc7b1 100644 --- a/src/watch/watch.ts +++ b/src/watch/watch.ts @@ -1,4 +1,4 @@ -import * as path from 'path'; +import { resolve } from 'path'; import { createFilter } from '@rollup/pluginutils'; import { rollupInternal } from '../rollup/rollup'; import { @@ -33,16 +33,16 @@ const eventsRewrites: Record(); + private readonly invalidatedIds = new Map(); private rerun = false; private running = true; - private tasks: Task[]; + private readonly tasks: Task[]; - constructor(configs: GenericConfigObject[], emitter: RollupWatcher) { + constructor(configs: readonly GenericConfigObject[], emitter: RollupWatcher) { this.emitter = emitter; emitter.close = this.close.bind(this); this.tasks = configs.map(config => new Task(this, config)); @@ -97,7 +97,7 @@ export class Watcher { }, this.buildDelay); } - private async run() { + private async run(): Promise { this.running = true; this.emitter.emit('event', { code: 'START' @@ -123,15 +123,15 @@ export class Task { watchFiles: string[] = []; private closed = false; - private fileWatcher: FileWatcher; + private readonly fileWatcher: FileWatcher; private filter: (id: string) => boolean; private invalidated = true; - private options: MergedRollupOptions; - private outputFiles: string[]; - private outputs: OutputOptions[]; + private readonly options: MergedRollupOptions; + private readonly outputFiles: string[]; + private readonly outputs: OutputOptions[]; private skipWrite: boolean; private watched = new Set(); - private watcher: Watcher; + private readonly watcher: Watcher; constructor(watcher: Watcher, config: GenericConfigObject) { this.watcher = watcher; @@ -140,7 +140,7 @@ export class Task { this.options = mergeOptions(config); this.outputs = this.options.output; this.outputFiles = this.outputs.map(output => { - if (output.file || output.dir) return path.resolve(output.file || output.dir!); + if (output.file || output.dir) return resolve(output.file || output.dir!); return undefined as never; });