Skip to content

Commit

Permalink
Use ! to assert not-null in typescript (#3303)
Browse files Browse the repository at this point in the history
  • Loading branch information
NotWoods authored and lukastaegert committed Dec 25, 2019
1 parent b5a3f16 commit 8e7a447
Show file tree
Hide file tree
Showing 43 changed files with 177 additions and 247 deletions.
4 changes: 2 additions & 2 deletions browser/path.ts
Expand Up @@ -28,7 +28,7 @@ export function dirname(path: string) {
}

export function extname(path: string) {
const match = /\.[^.]+$/.exec(basename(path) as string);
const match = /\.[^.]+$/.exec(basename(path)!);
if (!match) return '';
return match[0];
}
Expand Down Expand Up @@ -58,7 +58,7 @@ export function relative(from: string, to: string) {
}

export function resolve(...paths: string[]) {
let resolvedParts = (paths.shift() as string).split(/[/\\]/);
let resolvedParts = paths.shift()!.split(/[/\\]/);

paths.forEach(path => {
if (isAbsolute(path)) {
Expand Down
6 changes: 3 additions & 3 deletions cli/logging.ts
Expand Up @@ -15,8 +15,8 @@ export function handleError(err: RollupError, recover = false) {
let description = err.message || err;
if (err.name) description = `${err.name}: ${description}`;
const message =
((err as { plugin?: string }).plugin
? `(plugin ${(err as { plugin?: string }).plugin}) ${description}`
(err.plugin
? `(plugin ${(err).plugin}) ${description}`
: description) || err;

stderr(tc.bold.red(`[!] ${tc.bold(message.toString())}`));
Expand All @@ -26,7 +26,7 @@ export function handleError(err: RollupError, recover = false) {
}

if (err.loc) {
stderr(`${relativeId((err.loc.file || err.id) as string)} (${err.loc.line}:${err.loc.column})`);
stderr(`${relativeId((err.loc.file || err.id)!)} (${err.loc.line}:${err.loc.column})`);
} else if (err.id) {
stderr(relativeId(err.id));
}
Expand Down
13 changes: 6 additions & 7 deletions cli/run/build.ts
@@ -1,7 +1,7 @@
import ms from 'pretty-ms';
import tc from 'turbocolor';
import * as rollup from '../../src/node-entry';
import { InputOptions, OutputOptions, RollupBuild, SourceMap } from '../../src/rollup/types';
import { InputOptions, OutputOptions, RollupBuild } from '../../src/rollup/types';
import relativeId from '../../src/utils/relativeId';
import { handleError, stderr } from '../logging';
import SOURCEMAPPING_URL from '../sourceMappingUrl';
Expand All @@ -19,9 +19,9 @@ export default function build(
const start = Date.now();
const files = useStdout
? ['stdout']
: outputOptions.map(t => relativeId(t.file || (t.dir as string)));
: outputOptions.map(t => relativeId(t.file || t.dir!));
if (!silent) {
let inputFiles: string = undefined as any;
let inputFiles: string | undefined;
if (typeof inputOptions.input === 'string') {
inputFiles = inputOptions.input;
} else if (inputOptions.input instanceof Array) {
Expand All @@ -31,7 +31,7 @@ export default function build(
.map(name => (inputOptions.input as Record<string, string>)[name])
.join(', ');
}
stderr(tc.cyan(`\n${tc.bold(inputFiles)}${tc.bold(files.join(', '))}...`));
stderr(tc.cyan(`\n${tc.bold(inputFiles!)}${tc.bold(files.join(', '))}...`));
}

return rollup
Expand All @@ -54,8 +54,7 @@ export default function build(
} else {
source = file.code;
if (output.sourcemap === 'inline') {
source += `\n//# ${SOURCEMAPPING_URL}=${(file
.map as SourceMap).toUrl()}\n`;
source += `\n//# ${SOURCEMAPPING_URL}=${file.map!.toUrl()}\n`;
}
}
if (outputs.length > 1)
Expand All @@ -66,7 +65,7 @@ export default function build(
});
}

return Promise.all(outputOptions.map(output => bundle.write(output) as Promise<any>)).then(
return Promise.all(outputOptions.map(output => bundle.write(output))).then(
() => bundle
);
})
Expand Down
46 changes: 23 additions & 23 deletions src/Chunk.ts
Expand Up @@ -89,7 +89,7 @@ const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];

function getGlobalName(
module: ExternalModule,
globals: GlobalsOption,
globals: GlobalsOption | undefined,
graph: Graph,
hasExports: boolean
) {
Expand Down Expand Up @@ -130,7 +130,7 @@ export default class Chunk {
if (!facadedModule.facadeChunk) {
facadedModule.facadeChunk = chunk;
}
chunk.dependencies = [facadedModule.chunk as Chunk];
chunk.dependencies = [facadedModule.chunk!];
chunk.dynamicDependencies = [];
chunk.facadeModule = facadedModule;
for (const exportName of facadedModule.getAllExportNames()) {
Expand Down Expand Up @@ -662,7 +662,7 @@ export default class Chunk {
if (dep instanceof ExternalModule && !dep.renormalizeRenderPath) continue;

const renderedDependency = this.renderedDeclarations.dependencies[i];
const depId = dep instanceof ExternalModule ? renderedDependency.id : (dep.id as string);
const depId = dep instanceof ExternalModule ? renderedDependency.id : dep.id!;
if (dep instanceof Chunk) renderedDependency.namedExportsMode = dep.exportMode !== 'default';
renderedDependency.id = this.getRelativePath(depId);
}
Expand All @@ -673,7 +673,7 @@ export default class Chunk {
const hasExports =
this.renderedDeclarations.exports.length !== 0 ||
this.renderedDeclarations.dependencies.some(
dep => (dep.reexports && dep.reexports.length !== 0) as boolean
dep => (dep.reexports && dep.reexports.length !== 0)!
);

let usesTopLevelAwait = false;
Expand All @@ -700,19 +700,19 @@ export default class Chunk {
}

const magicString = finalise(
this.renderedSource as MagicStringBundle,
this.renderedSource!,
{
accessedGlobals,
dependencies: this.renderedDeclarations.dependencies,
exports: this.renderedDeclarations.exports,
hasExports,
indentString: this.indentString,
intro: addons.intro as string,
intro: addons.intro!,
isEntryModuleFacade:
this.graph.preserveModules ||
(this.facadeModule !== null && this.facadeModule.isEntryPoint),
namedExportsMode: this.exportMode !== 'default',
outro: addons.outro as string,
outro: addons.outro!,
usesTopLevelAwait,
varOrConst: options.preferConst ? 'const' : 'var',
warn: this.graph.warn.bind(this.graph)
Expand Down Expand Up @@ -741,8 +741,8 @@ export default class Chunk {

let file: string;
if (options.file) file = resolve(options.sourcemapFile || options.file);
else if (options.dir) file = resolve(options.dir, this.id as string);
else file = resolve(this.id as string);
else if (options.dir) file = resolve(options.dir, this.id!);
else file = resolve(this.id!);

const decodedMap = magicString.generateDecodedMap({});
map = collapseSourcemaps(
Expand All @@ -751,7 +751,7 @@ export default class Chunk {
decodedMap,
this.usedModules,
chunkSourcemapChain,
options.sourcemapExcludeSources as boolean
options.sourcemapExcludeSources!
);
map.sources = map.sources.map(sourcePath =>
normalize(
Expand Down Expand Up @@ -810,7 +810,7 @@ export default class Chunk {
}
let dependency: Chunk | ExternalModule;
if (depModule instanceof Module) {
dependency = depModule.chunk as Chunk;
dependency = depModule.chunk!;
} else {
if (!(depModule.used || depModule.moduleSideEffects)) {
continue;
Expand Down Expand Up @@ -887,11 +887,11 @@ export default class Chunk {
for (const { node, resolution } of module.dynamicImports) {
if (!resolution) continue;
if (resolution instanceof Module) {
if (resolution.chunk !== this && isChunkRendered(resolution.chunk as Chunk)) {
const resolutionChunk = resolution.facadeChunk || (resolution.chunk as Chunk);
if (resolution.chunk !== this && isChunkRendered(resolution.chunk!)) {
const resolutionChunk = resolution.facadeChunk || resolution.chunk!;
node.renderFinalResolution(
code,
`'${this.getRelativePath(resolutionChunk.id as string)}'`,
`'${this.getRelativePath(resolutionChunk.id!)}'`,
format
);
}
Expand All @@ -915,7 +915,7 @@ export default class Chunk {
private finaliseImportMetas(format: string, outputPluginDriver: PluginDriver): void {
for (const [module, code] of this.renderedModuleSources) {
for (const importMeta of module.importMetas) {
importMeta.renderFinalMechanism(code, this.id as string, format, outputPluginDriver);
importMeta.renderFinalMechanism(code, this.id!, format, outputPluginDriver);
}
}
}
Expand All @@ -937,7 +937,7 @@ export default class Chunk {
// skip local exports
if (!module || module.chunk === this) continue;
if (module instanceof Module) {
exportChunk = module.chunk as Chunk;
exportChunk = module.chunk!;
importName = exportChunk.getVariableExportName(variable);
needsLiveBinding = variable.isReassigned;
} else {
Expand Down Expand Up @@ -970,7 +970,7 @@ export default class Chunk {
imported:
variable.module instanceof ExternalModule
? variable.name
: ((variable.module as Module).chunk as Chunk).getVariableExportName(variable),
: variable.module!.chunk!.getVariableExportName(variable),
local: variable.getName()
});
}
Expand All @@ -996,10 +996,10 @@ export default class Chunk {
if (options.format === 'umd' || options.format === 'iife') {
globalName = getGlobalName(
dep,
options.globals as GlobalsOption,
options.globals,
this.graph,
exportsNames || exportsDefault
) as string;
)!;
}
}

Expand Down Expand Up @@ -1071,7 +1071,7 @@ export default class Chunk {
}

private getRelativePath(targetPath: string): string {
const relativePath = normalize(relative(dirname(this.id as string), targetPath));
const relativePath = normalize(relative(dirname(this.id!), targetPath));
return relativePath.startsWith('../') ? relativePath : './' + relativePath;
}

Expand All @@ -1096,7 +1096,7 @@ export default class Chunk {
const namespace = resolution.getOrCreateNamespace();
node.setResolution('named', namespace);
} else {
node.setResolution((resolution.chunk as Chunk).exportMode);
node.setResolution(resolution.chunk!.exportMode);
}
} else {
node.setResolution('auto');
Expand Down Expand Up @@ -1167,7 +1167,7 @@ export default class Chunk {
if ((variable.module as Module).chunk !== this) {
this.imports.add(variable);
if (variable.module instanceof Module) {
(variable.module.chunk as Chunk).exports.add(variable);
variable.module.chunk!.exports.add(variable);
}
}
}
Expand All @@ -1191,7 +1191,7 @@ export default class Chunk {
if ((variable.module as Module).chunk !== this) {
this.imports.add(variable);
if (variable.module instanceof Module) {
(variable.module.chunk as Chunk).exports.add(variable);
variable.module.chunk!.exports.add(variable);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/ExternalModule.ts
Expand Up @@ -30,7 +30,7 @@ export default class ExternalModule {
this.moduleSideEffects = moduleSideEffects;

const parts = id.split(/[\\/]/);
this.variableName = makeLegal(parts.pop() as string);
this.variableName = makeLegal(parts.pop()!);

this.nameSuggestions = Object.create(null);
this.declarations = Object.create(null);
Expand Down
65 changes: 27 additions & 38 deletions src/Graph.ts
Expand Up @@ -9,13 +9,10 @@ import ExternalModule from './ExternalModule';
import Module, { defaultAcornOptions } from './Module';
import { ModuleLoader, UnresolvedModule } from './ModuleLoader';
import {
ExternalOption,
GetManualChunk,
InputOptions,
ManualChunksOption,
ModuleJSON,
ModuleSideEffectsOption,
PureModulesOption,
RollupCache,
RollupWarning,
RollupWatcher,
Expand Down Expand Up @@ -103,31 +100,29 @@ export default class Graph {
for (const key of Object.keys(cache)) cache[key][0]++;
}
}
this.preserveModules = options.preserveModules as boolean;
this.strictDeprecations = options.strictDeprecations as boolean;
this.preserveModules = options.preserveModules!;
this.strictDeprecations = options.strictDeprecations!;

this.cacheExpiry = options.experimentalCacheExpiry as number;
this.cacheExpiry = options.experimentalCacheExpiry!;

if (options.treeshake !== false) {
this.treeshakingOptions = options.treeshake
? {
annotations: (options.treeshake as TreeshakingOptions).annotations !== false,
moduleSideEffects: (options.treeshake as TreeshakingOptions).moduleSideEffects,
propertyReadSideEffects:
(options.treeshake as TreeshakingOptions).propertyReadSideEffects !== false,
pureExternalModules: (options.treeshake as TreeshakingOptions).pureExternalModules,
tryCatchDeoptimization:
(options.treeshake as TreeshakingOptions).tryCatchDeoptimization !== false,
unknownGlobalSideEffects:
(options.treeshake as TreeshakingOptions).unknownGlobalSideEffects !== false
}
: {
annotations: true,
moduleSideEffects: true,
propertyReadSideEffects: true,
tryCatchDeoptimization: true,
unknownGlobalSideEffects: true
};
this.treeshakingOptions =
options.treeshake && options.treeshake !== true
? {
annotations: options.treeshake.annotations !== false,
moduleSideEffects: options.treeshake.moduleSideEffects,
propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false,
pureExternalModules: options.treeshake.pureExternalModules,
tryCatchDeoptimization: options.treeshake.tryCatchDeoptimization !== false,
unknownGlobalSideEffects: options.treeshake.unknownGlobalSideEffects !== false
}
: {
annotations: true,
moduleSideEffects: true,
propertyReadSideEffects: true,
tryCatchDeoptimization: true,
unknownGlobalSideEffects: true
};
if (typeof this.treeshakingOptions.pureExternalModules !== 'undefined') {
this.warnDeprecation(
`The "treeshake.pureExternalModules" option is deprecated. The "treeshake.moduleSideEffects" option should be used instead. "treeshake.pureExternalModules: true" is equivalent to "treeshake.moduleSideEffects: 'no-external'"`,
Expand All @@ -145,7 +140,7 @@ export default class Graph {

this.pluginDriver = new PluginDriver(
this,
options.plugins as Plugin[],
options.plugins!,
this.pluginCache,
options.preserveSymlinks === true,
watcher
Expand Down Expand Up @@ -182,7 +177,7 @@ export default class Graph {
acornPluginsToInject.push(injectImportMeta, injectExportNsFrom);

if (options.experimentalTopLevelAwait) {
(this.acornOptions as any).allowAwaitOutsideFunction = true;
this.acornOptions.allowAwaitOutsideFunction = true;
}

const acornInjectPlugins = options.acornInjectPlugins;
Expand All @@ -193,19 +188,15 @@ export default class Graph {
? [acornInjectPlugins]
: [])
);
this.acornParser = acorn.Parser.extend(...acornPluginsToInject) as any;
this.acornParser = acorn.Parser.extend(...acornPluginsToInject);
this.moduleLoader = new ModuleLoader(
this,
this.moduleById,
this.pluginDriver,
options.external as ExternalOption,
options.external!,
(typeof options.manualChunks === 'function' && options.manualChunks) as GetManualChunk | null,
(this.treeshakingOptions
? this.treeshakingOptions.moduleSideEffects
: null) as ModuleSideEffectsOption,
(this.treeshakingOptions
? this.treeshakingOptions.pureExternalModules
: false) as PureModulesOption
(this.treeshakingOptions ? this.treeshakingOptions.moduleSideEffects : null)!,
(this.treeshakingOptions ? this.treeshakingOptions.pureExternalModules : false)!
);
}

Expand Down Expand Up @@ -366,9 +357,7 @@ export default class Graph {

if (warning.plugin) str += `(${warning.plugin} plugin) `;
if (warning.loc)
str += `${relativeId(warning.loc.file as string)} (${warning.loc.line}:${
warning.loc.column
}) `;
str += `${relativeId(warning.loc.file!)} (${warning.loc.line}:${warning.loc.column}) `;
str += warning.message;

return str;
Expand Down

0 comments on commit 8e7a447

Please sign in to comment.