Skip to content

Commit

Permalink
fix: align stats types with Rspack (#3324)
Browse files Browse the repository at this point in the history
  • Loading branch information
chenjiahan authored Aug 30, 2024
1 parent a03b2b0 commit 38f3dda
Show file tree
Hide file tree
Showing 13 changed files with 56 additions and 82 deletions.
6 changes: 3 additions & 3 deletions packages/core/src/client/hmr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*
* Tips: this package will be bundled and running in the browser, do not import any Node.js modules.
*/
import type { ClientConfig, StatsError } from '../types';
import type { ClientConfig, Rspack } from '../types';
import { formatStatsMessages } from './format';

const compilationName = RSBUILD_COMPILATION_NAME;
Expand Down Expand Up @@ -85,7 +85,7 @@ function handleSuccess() {
}

// Compilation with warnings (e.g. ESLint).
function handleWarnings(warnings: StatsError[]) {
function handleWarnings(warnings: Rspack.StatsError[]) {
clearOutdatedErrors();

const isHotUpdate = !isFirstCompilation;
Expand Down Expand Up @@ -114,7 +114,7 @@ function handleWarnings(warnings: StatsError[]) {
}

// Compilation with errors (e.g. syntax error or missing modules).
function handleErrors(errors: StatsError[]) {
function handleErrors(errors: Rspack.StatsError[]) {
clearOutdatedErrors();

isFirstCompilation = false;
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/helpers/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { StatsCompilation, StatsValue } from '@rspack/core';
import color from 'picocolors';
import { formatStatsMessages } from '../client/format';
import { logger } from '../logger';
import type { MultiStats, Rspack, Stats, StatsError } from '../types';
import type { Rspack } from '../types';
import { isMultiCompiler } from './';

/**
Expand Down Expand Up @@ -93,7 +93,7 @@ export const getAllStatsErrors = (
// stats error + childCompiler error
// only append child errors when stats error does not exist, because some errors will exist in both stats and childCompiler
if (statsData.errorsCount && statsData.errors?.length === 0) {
return statsData.children?.reduce<StatsError[]>(
return statsData.children?.reduce<Rspack.StatsError[]>(
(errors, curr) => errors.concat(curr.errors || []),
[],
);
Expand All @@ -106,7 +106,7 @@ export const getAllStatsWarnings = (
statsData: StatsCompilation,
): Rspack.StatsError[] | undefined => {
if (statsData.warningsCount && statsData.warnings?.length === 0) {
return statsData.children?.reduce<StatsError[]>(
return statsData.children?.reduce<Rspack.StatsError[]>(
(warnings, curr) => warnings.concat(curr.warnings || []),
[],
);
Expand All @@ -130,7 +130,7 @@ export function getStatsOptions(
}

export function formatStats(
stats: Stats | MultiStats,
stats: Rspack.Stats | Rspack.MultiStats,
options: StatsValue = {},
): {
message?: string;
Expand Down
10 changes: 4 additions & 6 deletions packages/core/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import type {
ModifyRspackConfigFn,
ModifyWebpackChainFn,
ModifyWebpackConfigFn,
MultiStats,
OnAfterBuildFn,
OnAfterCreateCompilerFn,
OnAfterEnvironmentCompileFn,
Expand All @@ -28,7 +27,6 @@ import type {
OnDevCompileDoneFn,
OnExitFn,
Rspack,
Stats,
} from './types';

export function createEnvironmentAsyncHook<
Expand Down Expand Up @@ -364,7 +362,7 @@ export const registerBuildHook = ({
],
});

const onDone = async (stats: Stats | MultiStats) => {
const onDone = async (stats: Rspack.Stats | Rspack.MultiStats) => {
const p = context.hooks.onAfterBuild.call({
isFirstCompile,
stats,
Expand All @@ -375,7 +373,7 @@ export const registerBuildHook = ({
await p;
};

const onEnvironmentDone = async (buildIndex: number, stats: Stats) => {
const onEnvironmentDone = async (buildIndex: number, stats: Rspack.Stats) => {
await context.hooks.onAfterEnvironmentCompile.callInEnvironment({
environment: environmentList[buildIndex].name,
args: [
Expand Down Expand Up @@ -437,7 +435,7 @@ export const registerDevHook = ({
],
});

const onDone = async (stats: Stats | MultiStats) => {
const onDone = async (stats: Rspack.Stats | Rspack.MultiStats) => {
const p = context.hooks.onDevCompileDone.call({
isFirstCompile,
stats,
Expand All @@ -447,7 +445,7 @@ export const registerDevHook = ({
await p;
};

const onEnvironmentDone = async (buildIndex: number, stats: Stats) => {
const onEnvironmentDone = async (buildIndex: number, stats: Rspack.Stats) => {
await context.hooks.onAfterEnvironmentCompile.callInEnvironment({
environment: environmentList[buildIndex].name,
args: [
Expand Down
11 changes: 3 additions & 8 deletions packages/core/src/plugins/fileSize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,7 @@ import zlib from 'node:zlib';
import color from 'picocolors';
import { CSS_REGEX, HTML_REGEX, JS_REGEX } from '../constants';
import { logger } from '../logger';
import type {
PrintFileSizeOptions,
RsbuildPlugin,
Stats,
StatsAsset,
} from '../types';
import type { PrintFileSizeOptions, RsbuildPlugin, Rspack } from '../types';

const gzip = promisify(zlib.gzip);

Expand Down Expand Up @@ -82,7 +77,7 @@ const coloringAssetName = (assetName: string) => {

async function printFileSizes(
options: PrintFileSizeOptions,
stats: Stats,
stats: Rspack.Stats,
rootPath: string,
) {
const logs: string[] = [];
Expand All @@ -91,7 +86,7 @@ async function printFileSizes(
}

const formatAsset = async (
asset: StatsAsset,
asset: Rspack.StatsAsset,
distPath: string,
distFolder: string,
) => {
Expand Down
46 changes: 24 additions & 22 deletions packages/core/src/provider/build.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { rspack } from '@rspack/core';
import { registerBuildHook } from '../hooks';
import { logger } from '../logger';
import type { BuildOptions, MultiStats, Rspack, Stats } from '../types';
import type { BuildOptions, Rspack } from '../types';
import { createCompiler } from './createCompiler';
import type { InitConfigsOptions } from './initConfigs';

Expand Down Expand Up @@ -46,26 +46,28 @@ export const build = async (
};
}

await new Promise<{ stats?: Stats | MultiStats }>((resolve, reject) => {
compiler.run((err, stats?: Stats | MultiStats) => {
if (err || stats?.hasErrors()) {
const buildError = err || new Error('Rspack build failed!');
reject(buildError);
}
// If there is a compilation error, the close method should not be called.
// Otherwise the bundler may generate an invalid cache.
else {
// When using run or watch, call close and wait for it to finish before calling run or watch again.
// Concurrent compilations will corrupt the output files.
compiler.close((closeErr) => {
if (closeErr) {
logger.error(closeErr);
}
await new Promise<{ stats?: Rspack.Stats | Rspack.MultiStats }>(
(resolve, reject) => {
compiler.run((err, stats?: Rspack.Stats | Rspack.MultiStats) => {
if (err || stats?.hasErrors()) {
const buildError = err || new Error('Rspack build failed!');
reject(buildError);
}
// If there is a compilation error, the close method should not be called.
// Otherwise the bundler may generate an invalid cache.
else {
// When using run or watch, call close and wait for it to finish before calling run or watch again.
// Concurrent compilations will corrupt the output files.
compiler.close((closeErr) => {
if (closeErr) {
logger.error(closeErr);
}

// Assert type of stats must align to compiler.
resolve({ stats });
});
}
});
});
// Assert type of stats must align to compiler.
resolve({ stats });
});
}
});
},
);
};
13 changes: 8 additions & 5 deletions packages/core/src/provider/createCompiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
} from '../helpers';
import { registerDevHook } from '../hooks';
import { logger } from '../logger';
import type { DevConfig, MultiStats, Rspack, Stats } from '../types';
import type { DevConfig, Rspack } from '../types';
import { type InitConfigsOptions, initConfigs } from './initConfigs';

export async function createCompiler(options: InitConfigsOptions): Promise<{
Expand Down Expand Up @@ -61,7 +61,7 @@ export async function createCompiler(options: InitConfigsOptions): Promise<{
compiler.hooks.run.tap('rsbuild:run', logRspackVersion);
}

const done = (stats: Stats | MultiStats) => {
const done = (stats: Rspack.Stats | Rspack.MultiStats) => {
const statsJson = stats.toJson({
all: false,
timings: true,
Expand Down Expand Up @@ -98,9 +98,12 @@ export async function createCompiler(options: InitConfigsOptions): Promise<{
isCompiling = false;
};

compiler.hooks.done.tap('rsbuild:done', (stats: Stats | MultiStats) => {
done(stats);
});
compiler.hooks.done.tap(
'rsbuild:done',
(stats: Rspack.Stats | Rspack.MultiStats) => {
done(stats);
},
);

if (context.normalizedConfig?.mode === 'development') {
registerDevHook({
Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/server/devServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import type {
NormalizedConfig,
NormalizedDevConfig,
Rspack,
Stats,
} from '../types';
import { getTransformedHtml, loadBundle } from './environment';
import {
Expand Down Expand Up @@ -120,7 +119,7 @@ export async function createDevServer<
};

let outputFileSystem: Rspack.OutputFileSystem = fs;
let lastStats: Stats[];
let lastStats: Rspack.Stats[];

// should register onDevCompileDone hook before startCompile
const waitFirstCompileDone = runCompile
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/server/environment.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { join } from 'node:path';
import type { EnvironmentContext, Stats } from '../types';
import type { EnvironmentContext, Rspack } from '../types';
import { run } from './runner';

export type ServerUtils = {
Expand All @@ -8,7 +8,7 @@ export type ServerUtils = {
};

export const loadBundle = async <T>(
stats: Stats,
stats: Rspack.Stats,
entryName: string,
utils: ServerUtils,
): Promise<T> => {
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/server/socketServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { parse } from 'node:querystring';
import type Ws from 'ws';
import { getAllStatsErrors, getAllStatsWarnings } from '../helpers';
import { logger } from '../logger';
import type { DevConfig, Stats } from '../types';
import type { DevConfig, Rspack } from '../types';
import { getCompilationName } from './helper';

interface ExtWebSocket extends Ws {
Expand All @@ -31,7 +31,7 @@ export class SocketServer {

private readonly options: DevConfig;

private stats: Record<string, Stats>;
private stats: Record<string, Rspack.Stats>;
private initialChunks: Record<string, Set<string>>;

private timer: ReturnType<typeof setInterval> | null = null;
Expand Down Expand Up @@ -92,7 +92,7 @@ export class SocketServer {
});
}

public updateStats(stats: Stats): void {
public updateStats(stats: Rspack.Stats): void {
const compilationName = getCompilationName(stats.compilation);

this.stats[compilationName] = stats;
Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/types/config/dev.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { WatchOptions } from 'chokidar';
import type { Rspack } from '../rspack';
import type { Stats } from '../stats';

export type ProgressBarConfig = {
id?: string;
Expand All @@ -20,7 +19,7 @@ export type EnvironmentAPI = {
/**
* Get stats info about current environment.
*/
getStats: () => Promise<Stats>;
getStats: () => Promise<Rspack.Stats>;

/**
* Load and execute stats bundle in Server.
Expand Down
7 changes: 3 additions & 4 deletions packages/core/src/types/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import type {
} from './config';
import type { RsbuildEntry, RsbuildTarget } from './rsbuild';
import type { Rspack } from './rspack';
import type { MultiStats, Stats } from './stats';
import type { HtmlRspackPlugin, WebpackConfig } from './thirdParty';
import type { MaybePromise } from './utils';

Expand All @@ -36,14 +35,14 @@ export type OnBeforeBuildFn<B = 'rspack'> = (

export type OnAfterEnvironmentCompileFn = (
params: CompileCommonParams & {
stats?: Stats;
stats?: Rspack.Stats;
environment: EnvironmentContext;
},
) => MaybePromise<void>;

export type OnAfterBuildFn = (
params: CompileCommonParams & {
stats?: Stats | MultiStats;
stats?: Rspack.Stats | Rspack.MultiStats;
environments: Record<string, EnvironmentContext>;
},
) => MaybePromise<void>;
Expand All @@ -52,7 +51,7 @@ export type OnCloseDevServerFn = () => MaybePromise<void>;

export type OnDevCompileDoneFn = (params: {
isFirstCompile: boolean;
stats: Stats | MultiStats;
stats: Rspack.Stats | Rspack.MultiStats;
environments: Record<string, EnvironmentContext>;
}) => MaybePromise<void>;

Expand Down
1 change: 0 additions & 1 deletion packages/core/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,5 @@ export * from './context';
export * from './utils';
export * from './plugin';
export * from './config';
export * from './stats';
export * from './hooks';
export * from './thirdParty';
20 changes: 0 additions & 20 deletions packages/core/src/types/stats.ts

This file was deleted.

0 comments on commit 38f3dda

Please sign in to comment.