Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: improve & simplify types #4675

Merged
merged 3 commits into from Oct 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 1 addition & 3 deletions src/Chunk.ts
Expand Up @@ -725,9 +725,7 @@ export default class Chunk {
const map = module.getExportNamesByVariable();
for (const exportedVariable of map.keys()) {
const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
const importedVariable = isSynthetic
? (exportedVariable as SyntheticNamedExportVariable).getBaseVariable()
: exportedVariable;
const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
sxzz marked this conversation as resolved.
Show resolved Hide resolved
if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
this.checkCircularDependencyImport(importedVariable, module);
const exportingModule = importedVariable.module;
Expand Down
2 changes: 1 addition & 1 deletion src/Graph.ts
Expand Up @@ -91,7 +91,7 @@ export default class Graph {
watcher.onCurrentRun('close', handleClose);
}
this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
this.acornParser = acorn.Parser.extend(...(options.acornInjectPlugins as any));
this.acornParser = acorn.Parser.extend(...(options.acornInjectPlugins as any[]));
this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
this.fileOperationQueue = new Queue(options.maxParallelFileOps);
}
Expand Down
8 changes: 4 additions & 4 deletions src/ModuleLoader.ts
Expand Up @@ -58,9 +58,9 @@ type NormalizedResolveIdWithoutDefaults = Partial<PartialNull<ModuleOptions>> &
id: string;
};

type ResolveStaticDependencyPromise = Promise<[source: string, resolvedId: ResolvedId]>;
type ResolveStaticDependencyPromise = Promise<readonly [source: string, resolvedId: ResolvedId]>;
type ResolveDynamicDependencyPromise = Promise<
[dynamicImport: DynamicImport, resolvedId: ResolvedId | string | null]
readonly [dynamicImport: DynamicImport, resolvedId: ResolvedId | string | null]
>;
type LoadModulePromise = Promise<
[
Expand Down Expand Up @@ -548,7 +548,7 @@ export class ModuleLoader {
if (resolvedId && typeof resolvedId === 'object') {
dynamicImport.id = resolvedId.id;
}
return [dynamicImport, resolvedId] as [DynamicImport, ResolvedId | string | null];
return [dynamicImport, resolvedId] as const;
sxzz marked this conversation as resolved.
Show resolved Hide resolved
});
}

Expand All @@ -567,7 +567,7 @@ export class ModuleLoader {
module.id,
assertions
))
] as [string, ResolvedId]
] as const
);
}

Expand Down
41 changes: 21 additions & 20 deletions src/rollup/types.d.ts
@@ -1,9 +1,14 @@
export const VERSION: string;

type FalsyValue = false | null | undefined;
// utils
type NullValue = null | undefined | void;
type MaybeArray<T> = T | T[];
type MaybePromise<T> = T | Promise<T>;

type PartialNull<T> = {
[P in keyof T]: T[P] | null;
};

export interface RollupError extends RollupLog {
name?: string;
stack?: string;
Expand Down Expand Up @@ -82,10 +87,6 @@ export interface SourceMap {

export type SourceMapInput = ExistingRawSourceMap | string | null | { mappings: '' };

type PartialNull<T> = {
[P in keyof T]: T[P] | null;
};

interface ModuleOptions {
assertions: Record<string, string>;
meta: CustomPluginOptions;
Expand Down Expand Up @@ -224,7 +225,7 @@ interface PartialResolvedId extends Partial<PartialNull<ModuleOptions>> {
id: string;
}

export type ResolveIdResult = string | false | null | void | PartialResolvedId;
export type ResolveIdResult = string | NullValue | false | PartialResolvedId;

export type ResolveIdHook = (
this: PluginContext,
Expand Down Expand Up @@ -252,19 +253,19 @@ export type IsExternal = (
isResolved: boolean
) => boolean;

export type IsPureModule = (id: string) => boolean | null | void;
export type IsPureModule = (id: string) => boolean | NullValue;

export type HasModuleSideEffects = (id: string, external: boolean) => boolean;

export type LoadResult = SourceDescription | string | null | void;
export type LoadResult = SourceDescription | string | NullValue;

export type LoadHook = (this: PluginContext, id: string) => LoadResult;

export interface TransformPluginContext extends PluginContext {
getCombinedSourcemap: () => SourceMap;
}

export type TransformResult = string | null | void | Partial<SourceDescription>;
export type TransformResult = string | NullValue | Partial<SourceDescription>;

export type TransformHook = (
this: TransformPluginContext,
Expand All @@ -280,7 +281,7 @@ export type RenderChunkHook = (
chunk: RenderedChunk,
options: NormalizedOutputOptions,
meta: { chunks: Record<string, RenderedChunk> }
) => { code: string; map?: SourceMapInput } | string | null | undefined;
) => { code: string; map?: SourceMapInput } | string | NullValue;

export type ResolveDynamicImportHook = (
this: PluginContext,
Expand All @@ -293,7 +294,7 @@ export type ResolveImportMetaHook = (
this: PluginContext,
property: string | null,
options: { chunkId: string; format: InternalModuleFormat; moduleId: string }
) => string | null | void;
) => string | NullValue;

export type ResolveFileUrlHook = (
this: PluginContext,
Expand All @@ -305,7 +306,7 @@ export type ResolveFileUrlHook = (
referenceId: string;
relativePath: string;
}
) => string | null | void;
) => string | NullValue;

export type AddonHookFunction = (
this: PluginContext,
Expand Down Expand Up @@ -351,8 +352,8 @@ export interface FunctionPluginHooks {
) => void;
load: LoadHook;
moduleParsed: ModuleParsedHook;
options: (this: MinimalPluginContext, options: InputOptions) => InputOptions | null | void;
outputOptions: (this: PluginContext, options: OutputOptions) => OutputOptions | null | void;
options: (this: MinimalPluginContext, options: InputOptions) => InputOptions | NullValue;
outputOptions: (this: PluginContext, options: OutputOptions) => OutputOptions | NullValue;
renderChunk: RenderChunkHook;
renderDynamicImport: (
this: PluginContext,
Expand All @@ -362,7 +363,7 @@ export interface FunctionPluginHooks {
moduleId: string;
targetModuleId: string | null;
}
) => { left: string; right: string } | null | void;
) => { left: string; right: string } | NullValue;
renderError: (this: PluginContext, error?: Error) => void;
renderStart: (
this: PluginContext,
Expand Down Expand Up @@ -481,13 +482,13 @@ interface ManualChunkMeta {
getModuleIds: () => IterableIterator<string>;
getModuleInfo: GetModuleInfo;
}
export type GetManualChunk = (id: string, meta: ManualChunkMeta) => string | null | void;
export type GetManualChunk = (id: string, meta: ManualChunkMeta) => string | NullValue;

export type ExternalOption =
| (string | RegExp)[]
| string
| RegExp
| ((source: string, importer: string | undefined, isResolved: boolean) => boolean | null | void);
| ((source: string, importer: string | undefined, isResolved: boolean) => boolean | NullValue);
export type PureModulesOption = boolean | string[] | IsPureModule;
export type GlobalsOption = { [name: string]: string } | ((name: string) => string);
export type InputOption = string | string[] | { [entryAlias: string]: string };
Expand All @@ -499,7 +500,7 @@ export type SourcemapPathTransformOption = (
sourcemapPath: string
) => string;

export type InputPluginOption = MaybePromise<Plugin | FalsyValue | InputPluginOption[]>;
export type InputPluginOption = MaybePromise<Plugin | NullValue | false | InputPluginOption[]>;

export interface InputOptions {
acorn?: Record<string, unknown>;
Expand All @@ -517,7 +518,7 @@ export interface InputOptions {
maxParallelFileOps?: number;
/** @deprecated Use the "maxParallelFileOps" option instead. */
maxParallelFileReads?: number;
moduleContext?: ((id: string) => string | null | void) | { [id: string]: string };
moduleContext?: ((id: string) => string | NullValue) | { [id: string]: string };
onwarn?: WarningHandlerWithDefault;
perf?: boolean;
plugins?: InputPluginOption;
Expand Down Expand Up @@ -623,7 +624,7 @@ export type NormalizedAmdOptions = (

type AddonFunction = (chunk: RenderedChunk) => string | Promise<string>;

type OutputPluginOption = MaybePromise<OutputPlugin | FalsyValue | OutputPluginOption[]>;
type OutputPluginOption = MaybePromise<OutputPlugin | NullValue | false | OutputPluginOption[]>;

export interface OutputOptions {
amd?: AmdOptions;
Expand Down
9 changes: 3 additions & 6 deletions src/utils/options/mergeOptions.ts
Expand Up @@ -5,8 +5,7 @@ import type {
OutputOptions,
RollupCache,
RollupOptions,
WarningHandler,
WarningHandlerWithDefault
WarningHandler
} from '../../rollup/types';
import { ensureArray } from '../ensureArray';
import type { CommandConfigObject } from './normalizeInputOptions';
Expand Down Expand Up @@ -159,17 +158,15 @@ async function mergeInputOptions(
}

const getExternal = (config: InputOptions, overrides: CommandConfigObject): ExternalOption => {
const configExternal = config.external as ExternalOption | undefined;
const configExternal = config.external;
return typeof configExternal === 'function'
? (source: string, importer: string | undefined, isResolved: boolean) =>
configExternal(source, importer, isResolved) || overrides.external.includes(source)
: [...ensureArray(configExternal), ...overrides.external];
};

const getOnWarn = (config: InputOptions, defaultOnWarnHandler: WarningHandler): WarningHandler =>
config.onwarn
? warning => (config.onwarn as WarningHandlerWithDefault)(warning, defaultOnWarnHandler)
: defaultOnWarnHandler;
config.onwarn ? warning => config.onwarn!(warning, defaultOnWarnHandler) : defaultOnWarnHandler;

const getObjectOption = <T extends object>(
config: T,
Expand Down
4 changes: 2 additions & 2 deletions src/utils/options/normalizeInputOptions.ts
Expand Up @@ -186,7 +186,7 @@ const getmaxParallelFileOps = (
warn: WarningHandler,
strictDeprecations: boolean
): NormalizedInputOptions['maxParallelFileOps'] => {
const maxParallelFileReads = config.maxParallelFileReads as unknown;
const maxParallelFileReads = config.maxParallelFileReads;
if (typeof maxParallelFileReads === 'number') {
warnDeprecationWithOptions(
'The "maxParallelFileReads" option is deprecated. Use the "maxParallelFileOps" option instead.',
Expand All @@ -195,7 +195,7 @@ const getmaxParallelFileOps = (
strictDeprecations
);
}
const maxParallelFileOps = (config.maxParallelFileOps as unknown) ?? maxParallelFileReads;
const maxParallelFileOps = config.maxParallelFileOps ?? maxParallelFileReads;
if (typeof maxParallelFileOps === 'number') {
if (maxParallelFileOps <= 0) return Infinity;
return maxParallelFileOps;
Expand Down
2 changes: 1 addition & 1 deletion src/utils/options/normalizeOutputOptions.ts
Expand Up @@ -287,7 +287,7 @@ const getAddon = <T extends 'banner' | 'footer' | 'intro' | 'outro'>(
if (typeof configAddon === 'function') {
return configAddon as NormalizedOutputOptions[T];
}
return () => (configAddon as string) || '';
return () => configAddon || '';
};

// eslint-disable-next-line unicorn/prevent-abbreviations
Expand Down
5 changes: 1 addition & 4 deletions src/utils/renderChunks.ts
Expand Up @@ -161,10 +161,7 @@ async function transformChunk(
map.sources = map.sources
.map(sourcePath => {
if (sourcemapPathTransform) {
const newSourcePath = sourcemapPathTransform(
sourcePath,
`${resultingFile}.map`
) as unknown;
const newSourcePath = sourcemapPathTransform(sourcePath, `${resultingFile}.map`);

if (typeof newSourcePath !== 'string') {
error(errorFailedValidation(`sourcemapPathTransform function must return a string.`));
Expand Down