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: some code and type fixes #4413

Merged
merged 30 commits into from Feb 23, 2022
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
fab28a2
use readonly set
dnalborczyk Feb 19, 2022
055f4a0
refactor: re-use Array.prototype.map, remove Array.from map function
dnalborczyk Feb 19, 2022
6c812d0
refactor: remove else block
dnalborczyk Feb 19, 2022
eaada30
refactor: use logical nullish assignment
dnalborczyk Feb 19, 2022
a824fa7
fix: types
dnalborczyk Feb 20, 2022
14c2638
fix: add generic parameters for Map
dnalborczyk Feb 20, 2022
bdcbe6d
refactor: simplify
dnalborczyk Feb 20, 2022
96fe4ac
fix: remove type assertion
dnalborczyk Feb 20, 2022
45deb74
refactor: create map instance only once
dnalborczyk Feb 20, 2022
c3dbca6
refactor: use object.entries over .keys
dnalborczyk Feb 20, 2022
9d235a0
refactor: simplify
dnalborczyk Feb 20, 2022
9cdfc9b
refactor: simplify
dnalborczyk Feb 20, 2022
fac5c6a
remove unnecassary .values call
dnalborczyk Feb 20, 2022
33446da
refactor: simplify, use substring
dnalborczyk Feb 20, 2022
c18a0d6
remove unnecassary .entries
dnalborczyk Feb 20, 2022
884d34d
refactor: simplify
dnalborczyk Feb 20, 2022
b4df2b4
fix: replace deprecated .substr with .substring
dnalborczyk Feb 20, 2022
81054ea
Revert "refactor: re-use Array.prototype.map, remove Array.from map f…
dnalborczyk Feb 20, 2022
587acc8
add comment
dnalborczyk Feb 20, 2022
42b9a55
merge master
dnalborczyk Feb 23, 2022
da6dee6
fix hash update
dnalborczyk Feb 23, 2022
847fc1a
remove initial id base assignment
dnalborczyk Feb 23, 2022
011bb05
remove breaks, return early
dnalborczyk Feb 23, 2022
40e396c
remove default case
dnalborczyk Feb 23, 2022
c191ac4
return early
dnalborczyk Feb 23, 2022
60464a3
add generic type parameters, remove eslint-disable
dnalborczyk Feb 23, 2022
8183a62
use object shorthand
dnalborczyk Feb 23, 2022
eb0a2c8
order nit
dnalborczyk Feb 23, 2022
20f82aa
reference from this
dnalborczyk Feb 23, 2022
5b0c7a8
simplify, use map/filter
dnalborczyk Feb 23, 2022
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
13 changes: 6 additions & 7 deletions cli/run/batchWarnings.ts
Expand Up @@ -14,7 +14,7 @@ export interface BatchWarnings {

export default function batchWarnings(): BatchWarnings {
let count = 0;
let deferredWarnings = new Map<keyof typeof deferredHandlers, RollupWarning[]>();
const deferredWarnings = new Map<keyof typeof deferredHandlers, RollupWarning[]>();
let warningOccurred = false;

return {
Expand Down Expand Up @@ -59,7 +59,7 @@ export default function batchWarnings(): BatchWarnings {
deferredHandlers[code](deferredWarnings.get(code)!);
}

deferredWarnings = new Map();
deferredWarnings.clear();
count = 0;
},

Expand Down Expand Up @@ -224,13 +224,12 @@ const deferredHandlers: {
title('Unresolved dependencies');
info('https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency');

const dependencies = new Map();
const dependencies = new Map<string, string[]>();
for (const warning of warnings) {
getOrCreate(dependencies, warning.source, () => []).push(warning.importer);
getOrCreate(dependencies, warning.source, () => []).push(warning.importer!);
}

for (const dependency of dependencies.keys()) {
const importers = dependencies.get(dependency);
for (const [dependency, importers] of dependencies) {
stderr(`${bold(dependency)} (imported by ${importers.join(', ')})`);
}
},
Expand All @@ -243,7 +242,7 @@ const deferredHandlers: {
' imported from external module "' +
warning.source +
'" but never used in ' +
printQuotedStringList((warning.sources as string[]).map(id => relativeId(id)))
printQuotedStringList(warning.sources!.map(id => relativeId(id)))
);
}
}
Expand Down
7 changes: 2 additions & 5 deletions cli/run/index.ts
@@ -1,3 +1,4 @@
import { env } from 'process';
import type { MergedRollupOptions } from '../../src/rollup/types';
import { isWatchEnabled } from '../../src/utils/options/mergeOptions';
import { getAliasName } from '../../src/utils/relativeId';
Expand Down Expand Up @@ -48,11 +49,7 @@ export default async function runRollup(command: Record<string, any>): Promise<v
environment.forEach((arg: string) => {
arg.split(',').forEach((pair: string) => {
const [key, ...value] = pair.split(':');
if (value.length) {
process.env[key] = value.join(':');
} else {
process.env[key] = String(true);
}
env[key] = value.length === 0 ? String(true) : value.join(':');
});
});
}
Expand Down
3 changes: 1 addition & 2 deletions cli/run/timings.ts
Expand Up @@ -3,10 +3,9 @@ import type { SerializedTimings } from '../../src/rollup/types';
import { bold, underline } from '../../src/utils/colors';

export function printTimings(timings: SerializedTimings): void {
Object.keys(timings).forEach(label => {
Object.entries(timings).forEach(([label, [time, memory, total]]) => {
const appliedColor =
label[0] === '#' ? (label[1] !== '#' ? underline : bold) : (text: string) => text;
const [time, memory, total] = timings[label];
const row = `${label}: ${time.toFixed(0)}ms, ${prettyBytes(memory)} / ${prettyBytes(total)}`;
console.info(appliedColor(row));
});
Expand Down
8 changes: 4 additions & 4 deletions src/Bundle.ts
Expand Up @@ -35,7 +35,7 @@ export default class Bundle {

constructor(
private readonly outputOptions: NormalizedOutputOptions,
private readonly unsetOptions: Set<string>,
private readonly unsetOptions: ReadonlySet<string>,
private readonly inputOptions: NormalizedInputOptions,
private readonly pluginDriver: PluginDriver,
private readonly graph: Graph
Expand Down Expand Up @@ -189,14 +189,14 @@ export default class Bundle {
);
(file as OutputAsset).type = 'asset';
}
if (this.outputOptions.validate && typeof (file as OutputChunk).code == 'string') {
if (this.outputOptions.validate && 'code' in file) {
try {
this.graph.contextParse((file as OutputChunk).code, {
this.graph.contextParse(file.code, {
allowHashBang: true,
ecmaVersion: 'latest'
});
} catch (err: any) {
this.inputOptions.onwarn(errChunkInvalid(file as OutputChunk, err));
this.inputOptions.onwarn(errChunkInvalid(file, err));
}
}
}
Expand Down
17 changes: 8 additions & 9 deletions src/Chunk.ts
Expand Up @@ -319,7 +319,7 @@ export default class Chunk {
const facades: Chunk[] = [];
const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
const exposedVariables = new Set<Variable>(
this.dynamicEntryModules.map(module => module.namespace)
this.dynamicEntryModules.map(({ namespace }) => namespace)
);
for (const module of entryModules) {
if (module.preserveSignature) {
Expand All @@ -331,11 +331,10 @@ export default class Chunk {
for (const module of entryModules) {
const requiredFacades: FacadeName[] = Array.from(
new Set(
module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)
),
name => ({
name
})
module.chunkNames
.filter(({ isUserDefined }) => isUserDefined)
.map(({ name }) => ({ name }))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't the same as it won't do name string deduping in the set.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great catch, thank you! too bad this wasn't caught by a test 😞 I reverted and added a comment.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually I think it does not change anything at the moment, which is why there is no test. The only situation where you have entries here is if the user used an object as entry point. In that case, the name properties are the keys of that object, and object keys deduplicate themselves. It does not hurt either, though.

)
);
if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
requiredFacades.push({});
Expand Down Expand Up @@ -451,7 +450,7 @@ export default class Chunk {
const extension = extname(sanitizedId);
const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
ext: () => extension.substr(1),
ext: () => extension.substring(1),
extname: () => extension,
format: () => options.format as string,
name: () => this.getChunkName()
Expand All @@ -467,7 +466,7 @@ export default class Chunk {
const extension = extname(sanitizedId);
const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
ext: () => extension.substr(1),
ext: () => extension.substring(1),
extname: () => extension,
format: () => options.format as string,
name: () => getAliasName(sanitizedId)
Expand Down Expand Up @@ -1162,7 +1161,7 @@ export default class Chunk {
let imported: string;
let needsLiveBinding = false;
if (exportName[0] === '*') {
const id = exportName.substr(1);
const id = exportName.substring(1);
if (interop(id) === 'defaultOnly') {
this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
}
Expand Down
3 changes: 1 addition & 2 deletions src/ExternalModule.ts
Expand Up @@ -117,8 +117,7 @@ export default class ExternalModule {

const importersSet = new Set<string>();
for (const name of unused) {
const { importers } = this.declarations[name].module;
for (const importer of importers) {
for (const importer of this.declarations[name].module.importers) {
importersSet.add(importer);
}
}
Expand Down
15 changes: 6 additions & 9 deletions src/ModuleLoader.ts
Expand Up @@ -438,9 +438,8 @@ export class ModuleLoader {
return error(errInternalIdCannotBeExternal(source, importer));
}
return Promise.resolve(externalModule);
} else {
return this.fetchModule(resolvedId, importer, false, false);
}
return this.fetchModule(resolvedId, importer, false, false);
}

private async fetchStaticDependencies(
Expand Down Expand Up @@ -672,13 +671,11 @@ export class ModuleLoader {
} as ResolvedId;
}
if (resolution == null) {
return (module.resolvedIds[specifier] =
module.resolvedIds[specifier] ||
this.handleResolveId(
await this.resolveId(specifier, module.id, EMPTY_OBJECT, false),
specifier,
module.id
));
return (module.resolvedIds[specifier] ??= this.handleResolveId(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we using ?? in the codebase now?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, nullish coalescing is used throughout the codebase, logical nullish assignment a little bit.

down-leveling only adds a tiny amount of additional code which results in almost the same amount without the change. if v3 were about to support node.js v14+ nullish coalescing would also run native as well. short circuiting should also make logical nullish assignment faster.

the correct syntax mapping would have been ||= rather, but I thought since ResolveId is an object, ??= would fit better to show the intend of only assigning when null or undefined.

await this.resolveId(specifier, module.id, EMPTY_OBJECT, false),
specifier,
module.id
));
}
return this.handleResolveId(
this.getResolvedIdWithDefaults(
Expand Down
8 changes: 4 additions & 4 deletions src/ast/nodes/MetaProperty.ts
Expand Up @@ -43,7 +43,7 @@ export default class MetaProperty extends NodeBase {
getReferencedFileName(outputPluginDriver: PluginDriver): string | null {
const metaProperty = this.metaProperty as string | null;
if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
return outputPluginDriver.getFileName(metaProperty.substr(FILE_PREFIX.length));
return outputPluginDriver.getFileName(metaProperty.substring(FILE_PREFIX.length));
}
return null;
}
Expand Down Expand Up @@ -91,23 +91,23 @@ export default class MetaProperty extends NodeBase {
let chunkReferenceId: string | null = null;
let fileName: string;
if (metaProperty.startsWith(FILE_PREFIX)) {
referenceId = metaProperty.substr(FILE_PREFIX.length);
referenceId = metaProperty.substring(FILE_PREFIX.length);
fileName = outputPluginDriver.getFileName(referenceId);
} else if (metaProperty.startsWith(ASSET_PREFIX)) {
warnDeprecation(
`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`,
true,
this.context.options
);
assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
assetReferenceId = metaProperty.substring(ASSET_PREFIX.length);
fileName = outputPluginDriver.getFileName(assetReferenceId);
} else {
warnDeprecation(
`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`,
true,
this.context.options
);
chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
chunkReferenceId = metaProperty.substring(CHUNK_PREFIX.length);
fileName = outputPluginDriver.getFileName(chunkReferenceId);
}
const relativePath = normalize(relative(dirname(chunkId), fileName));
Expand Down
7 changes: 3 additions & 4 deletions src/rollup/rollup.ts
Expand Up @@ -137,12 +137,11 @@ function applyOptionHook(watchMode: boolean) {
}

function normalizePlugins(plugins: readonly Plugin[], anonymousPrefix: string): void {
for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
const plugin = plugins[pluginIndex];
plugins.forEach((plugin, index) => {
if (!plugin.name) {
plugin.name = `${anonymousPrefix}${pluginIndex + 1}`;
plugin.name = `${anonymousPrefix}${index + 1}`;
}
}
});
}

async function handleGenerateWrite(
Expand Down
31 changes: 14 additions & 17 deletions src/utils/FileEmitter.ts
Expand Up @@ -42,16 +42,17 @@ function generateAssetFileName(
: outputOptions.assetFileNames,
'output.assetFileNames',
{
ext: () => extname(emittedName).substr(1),
ext: () => extname(emittedName).substring(1),
extname: () => extname(emittedName),
hash() {
const hash = createHash();
hash.update(emittedName);
hash.update(':');
hash.update(source);
return hash.digest('hex').substr(0, 8);
return createHash()
.update(emittedName)
.update(':')
.update(source)
.digest('hex')
.substring(0, 8);
},
name: () => emittedName.substr(0, emittedName.length - extname(emittedName).length)
name: () => emittedName.substring(0, emittedName.length - extname(emittedName).length)
}
),
bundle
Expand Down Expand Up @@ -165,7 +166,7 @@ export class FileEmitter {
}

public assertAssetsFinalized = (): void => {
for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
for (const [referenceId, emittedFile] of this.filesByReferenceId) {
if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
return error(errNoAssetSourceSet(emittedFile.name || referenceId));
}
Expand Down Expand Up @@ -241,24 +242,20 @@ export class FileEmitter {
reserveFileNameInBundle(emittedFile.fileName, this.bundle, this.options.onwarn);
}
}
for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
for (const [referenceId, consumedFile] of this.filesByReferenceId) {
if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.bundle);
}
}
};

private assignReferenceId(file: ConsumedFile, idBase: string): string {
let referenceId: string | undefined;
let referenceId = idBase;

do {
const hash = createHash();
if (referenceId) {
hash.update(referenceId);
} else {
hash.update(idBase);
}
referenceId = hash.digest('hex').substr(0, 8);
referenceId = createHash().update(referenceId).digest('hex').substring(0, 8);
dnalborczyk marked this conversation as resolved.
Show resolved Hide resolved
} while (this.filesByReferenceId.has(referenceId));

this.filesByReferenceId.set(referenceId, file);
return referenceId;
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/PluginDriver.ts
Expand Up @@ -133,7 +133,7 @@ export class PluginDriver {
hookName: H,
args: Parameters<PluginHooks[H]>,
replaceContext?: ReplaceContext | null,
skipped?: Set<Plugin> | null
skipped?: ReadonlySet<Plugin> | null
): EnsurePromise<ReturnType<PluginHooks[H]>> {
let promise: EnsurePromise<ReturnType<PluginHooks[H]>> = Promise.resolve(undefined as any);
for (const plugin of this.plugins) {
Expand Down
6 changes: 3 additions & 3 deletions src/utils/options/normalizeOutputOptions.ts
Expand Up @@ -380,9 +380,9 @@ const getInterop = (
errInvalidOption(
'output.interop',
'outputinterop',
`use one of ${Array.from(ALLOWED_INTEROP_TYPES.values(), value =>
JSON.stringify(value)
).join(', ')}`,
`use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(
', '
)}`,
interop
)
);
Expand Down
2 changes: 1 addition & 1 deletion src/utils/relativeId.ts
Expand Up @@ -2,7 +2,7 @@ import { basename, extname, isAbsolute, relative, resolve } from './path';

export function getAliasName(id: string): string {
const base = basename(id);
return base.substr(0, base.length - extname(id).length);
return base.substring(0, base.length - extname(id).length);
}

export default function relativeId(id: string): string {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/renderNamePattern.ts
Expand Up @@ -35,7 +35,7 @@ export function makeUnique(name: string, existingNames: Record<string, unknown>)
if (!existingNamesLowercase.has(name.toLocaleLowerCase())) return name;

const ext = extname(name);
name = name.substr(0, name.length - ext.length);
name = name.substring(0, name.length - ext.length);
let uniqueName: string,
uniqueIndex = 1;
while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()));
Expand Down
2 changes: 1 addition & 1 deletion src/watch/watch.ts
Expand Up @@ -89,7 +89,7 @@ export class Watcher {

this.buildTimeout = setTimeout(() => {
this.buildTimeout = null;
for (const [id, event] of this.invalidatedIds.entries()) {
for (const [id, event] of this.invalidatedIds) {
this.emitter.emit('change', id, { event });
}
this.invalidatedIds.clear();
Expand Down