// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import type { AddressInfo } from 'node:net'; import type * as TRspack from '@rspack/core'; import type * as TRspackDevServer from '@rspack/dev-server'; import { AsyncParallelHook, AsyncSeriesBailHook, AsyncSeriesHook, AsyncSeriesWaterfallHook } from 'tapable'; import { CertificateManager, type ICertificate } from '@rushstack/debug-certificate-manager'; import { FileError, InternalError, LegacyAdapters } from '@rushstack/node-core-library'; import type { HeftConfiguration, IHeftTaskSession, IHeftTaskPlugin, IHeftTaskRunHookOptions, IScopedLogger, IHeftTaskRunIncrementalHookOptions } from '@rushstack/heft'; import { type IRspackConfiguration, type IRspackPluginAccessor, PLUGIN_NAME, type IRspackPluginAccessorHooks, type RspackCoreImport } from './shared'; import { tryLoadRspackConfigurationAsync } from './RspackConfigurationLoader'; import { type DeferredWatchFileSystem, OverrideNodeWatchFSPlugin } from './DeferredWatchFileSystem'; export interface IRspackPluginOptions { devConfigurationPath?: string | undefined; configurationPath?: string | undefined; } const SERVE_PARAMETER_LONG_NAME: '--serve' = '--serve'; const RSPACK_PACKAGE_NAME: '@rspack/core' = '@rspack/core'; const RSPACK_DEV_SERVER_PACKAGE_NAME: '@rspack/dev-server' = '@rspack/dev-server'; const RSPACK_DEV_SERVER_ENV_VAR_NAME: 'RSPACK_DEV_SERVER' = 'RSPACK_DEV_SERVER'; const WEBPACK_DEV_MIDDLEWARE_PACKAGE_NAME: 'webpack-dev-middleware' = 'webpack-dev-middleware'; /** * @internal */ export default class RspackPlugin implements IHeftTaskPlugin { #accessor: IRspackPluginAccessor | undefined; #isServeMode: boolean = false; #rspack: RspackCoreImport | undefined; #rspackCompiler: TRspack.Compiler | TRspack.MultiCompiler | undefined; #rspackConfiguration: IRspackConfiguration | undefined | false = false; #rspackCompilationDonePromise: Promise | undefined; #rspackCompilationDonePromiseResolveFn: (() => void) | undefined; #watchFileSystems: Set | undefined; #warnings: Error[] = []; #errors: Error[] = []; public get accessor(): IRspackPluginAccessor { if (!this.#accessor) { this.#accessor = { hooks: _createAccessorHooks(), parameters: { isServeMode: this.#isServeMode } }; } return this.#accessor; } public apply( taskSession: IHeftTaskSession, heftConfiguration: HeftConfiguration, options: IRspackPluginOptions = {} ): void { this.#isServeMode = taskSession.parameters.getFlagParameter(SERVE_PARAMETER_LONG_NAME).value; if (this.#isServeMode && !taskSession.parameters.watch) { throw new Error( `The ${JSON.stringify( SERVE_PARAMETER_LONG_NAME )} parameter is only available when running in watch mode.` + ` Try replacing "${taskSession.parsedCommandLine?.unaliasedCommandName}" with` + ` "${taskSession.parsedCommandLine?.unaliasedCommandName}-watch" in your Heft command line.` ); } taskSession.hooks.run.tapPromise(PLUGIN_NAME, async (runOptions: IHeftTaskRunHookOptions) => { await this.#runRspackAsync(taskSession, heftConfiguration, options); }); taskSession.hooks.runIncremental.tapPromise( PLUGIN_NAME, async (runOptions: IHeftTaskRunIncrementalHookOptions) => { await this.#runRspackWatchAsync(taskSession, heftConfiguration, options, runOptions.requestRun); } ); } async #getRspackConfigurationAsync( taskSession: IHeftTaskSession, heftConfiguration: HeftConfiguration, options: IRspackPluginOptions, requestRun?: () => void ): Promise { if (this.#rspackConfiguration === false) { const rspackConfiguration: IRspackConfiguration | undefined = await tryLoadRspackConfigurationAsync( { taskSession, heftConfiguration, hooks: this.accessor.hooks, serveMode: this.#isServeMode, loadRspackAsyncFn: this.#loadRspackAsync.bind(this, taskSession, heftConfiguration) }, options ); if (rspackConfiguration && requestRun) { const overrideWatchFSPlugin: OverrideNodeWatchFSPlugin = new OverrideNodeWatchFSPlugin(requestRun); this.#watchFileSystems = overrideWatchFSPlugin.fileSystems; for (const config of Array.isArray(rspackConfiguration) ? rspackConfiguration : [rspackConfiguration]) { if (!config.plugins) { config.plugins = [overrideWatchFSPlugin]; } else { config.plugins.unshift(overrideWatchFSPlugin); } } } this.#rspackConfiguration = rspackConfiguration; } return this.#rspackConfiguration; } async #loadRspackAsync( taskSession: IHeftTaskSession, heftConfiguration: HeftConfiguration ): Promise { if (!this.#rspack) { try { const rspackPackagePath: string = await heftConfiguration.rigPackageResolver.resolvePackageAsync( RSPACK_PACKAGE_NAME, taskSession.logger.terminal ); this.#rspack = await import(rspackPackagePath); taskSession.logger.terminal.writeDebugLine(`Using Rspack from rig package at "${rspackPackagePath}"`); } catch (e) { // Fallback to bundled version if not found in rig. this.#rspack = await import(RSPACK_PACKAGE_NAME); taskSession.logger.terminal.writeDebugLine(`Using Rspack from built-in "${RSPACK_PACKAGE_NAME}"`); } } return this.#rspack!; } async #getRspackCompilerAsync( taskSession: IHeftTaskSession, heftConfiguration: HeftConfiguration, rspackConfiguration: IRspackConfiguration ): Promise { if (!this.#rspackCompiler) { const rspack: RspackCoreImport = await this.#loadRspackAsync(taskSession, heftConfiguration); taskSession.logger.terminal.writeLine(`Using Rspack version ${rspack.version}`); this.#rspackCompiler = Array.isArray(rspackConfiguration) ? rspack.default(rspackConfiguration) /* (rspack.Compilation[]) => MultiCompiler */ : rspack.default(rspackConfiguration); /* (rspack.Compilation) => Compiler */ } return this.#rspackCompiler; } async #runRspackAsync( taskSession: IHeftTaskSession, heftConfiguration: HeftConfiguration, options: IRspackPluginOptions ): Promise { this.#validateEnvironmentVariable(taskSession); if (taskSession.parameters.watch || this.#isServeMode) { // Should never happen, but just in case throw new InternalError('Cannot run Rspack in compilation mode when watch mode is enabled'); } // Load the config and compiler, and return if there is no config found const rspackConfiguration: IRspackConfiguration | undefined = await this.#getRspackConfigurationAsync( taskSession, heftConfiguration, options ); if (!rspackConfiguration) { return; } const compiler: TRspack.Compiler | TRspack.MultiCompiler = await this.#getRspackCompilerAsync( taskSession, heftConfiguration, rspackConfiguration ); taskSession.logger.terminal.writeLine('Running Rspack compilation'); // Run the rspack compiler let stats: TRspack.Stats | TRspack.MultiStats | undefined; try { stats = await LegacyAdapters.convertCallbackToPromise( (compiler as TRspack.Compiler).run.bind(compiler) ); await LegacyAdapters.convertCallbackToPromise(compiler.close.bind(compiler)); } catch (e) { taskSession.logger.emitError(e as Error); } // Emit the errors from the stats object, if present if (stats) { this.#recordErrors(stats, heftConfiguration.buildFolderPath); this.#emitErrors(taskSession.logger); if (this.accessor.hooks.onEmitStats.isUsed()) { await this.accessor.hooks.onEmitStats.promise(stats); } } } async #runRspackWatchAsync( taskSession: IHeftTaskSession, heftConfiguration: HeftConfiguration, options: IRspackPluginOptions, requestRun: () => void ): Promise { // Save a handle to the original promise, since the this-scoped promise will be replaced whenever // the compilation completes. let rspackCompilationDonePromise: Promise | undefined = this.#rspackCompilationDonePromise; let isInitial: boolean = false; if (!this.#rspackCompiler) { isInitial = true; this.#validateEnvironmentVariable(taskSession); if (!taskSession.parameters.watch) { // Should never happen, but just in case throw new InternalError('Cannot run Rspack in watch mode when watch mode is not enabled'); } // Load the config and compiler, and return if there is no config found const rspackConfiguration: IRspackConfiguration | undefined = await this.#getRspackConfigurationAsync( taskSession, heftConfiguration, options, requestRun ); if (!rspackConfiguration) { return; } // Get the compiler which will be used for both serve and watch mode const compiler: TRspack.Compiler | TRspack.MultiCompiler = await this.#getRspackCompilerAsync( taskSession, heftConfiguration, rspackConfiguration ); // Set up the hook to detect when the watcher completes the watcher compilation. We will also log out // errors from the compilation if present from the output stats object. this.#rspackCompilationDonePromise = new Promise((resolve: () => void) => { this.#rspackCompilationDonePromiseResolveFn = resolve; }); rspackCompilationDonePromise = this.#rspackCompilationDonePromise; compiler.hooks.done.tap(PLUGIN_NAME, (stats?: TRspack.Stats | TRspack.MultiStats) => { this.#rspackCompilationDonePromiseResolveFn!(); this.#rspackCompilationDonePromise = new Promise((resolve: () => void) => { this.#rspackCompilationDonePromiseResolveFn = resolve; }); if (stats) { this.#recordErrors(stats, heftConfiguration.buildFolderPath); } }); // Determine how we will run the compiler. When serving, we will run the compiler // via the @rspack/dev-server. Otherwise, we will run the compiler directly. if (this.#isServeMode) { const defaultDevServerOptions: TRspackDevServer.Configuration = { host: 'localhost', devMiddleware: { publicPath: '/', stats: { cached: false, cachedAssets: false, colors: heftConfiguration.terminalProvider.supportsColor } }, client: { logging: 'info', webSocketURL: { port: 8080 } }, watchFiles: [], static: [], port: 8080, onListening: (server: TRspackDevServer.RspackDevServer) => { const addressInfo: AddressInfo | string | undefined = server.server?.address() as AddressInfo; if (addressInfo) { let url: string; if (typeof addressInfo === 'string') { url = addressInfo; } else { const address: string = addressInfo.family === 'IPv6' ? `[${addressInfo.address}]:${addressInfo.port}` : `${addressInfo.address}:${addressInfo.port}`; url = `https://${address}/`; } taskSession.logger.terminal.writeLine(`Started Rspack Dev Server at ${url}`); } } }; // Obtain the devServerOptions from the rspack configuration, and combine with the default options let devServerOptions: TRspackDevServer.Configuration; if (Array.isArray(rspackConfiguration)) { const filteredDevServerOptions: TRspackDevServer.Configuration[] = rspackConfiguration .map((configuration) => configuration.devServer) .filter((devServer): devServer is TRspackDevServer.Configuration => !!devServer); if (filteredDevServerOptions.length > 1) { taskSession.logger.emitWarning( new Error(`Detected multiple rspack devServer configurations, using the first one.`) ); } devServerOptions = { ...defaultDevServerOptions, ...filteredDevServerOptions[0] }; } else { devServerOptions = { ...defaultDevServerOptions, ...rspackConfiguration.devServer }; } // Add the certificate and key to the devServerOptions if these fields don't already have values if (!devServerOptions.server) { const certificateManager: CertificateManager = new CertificateManager(); const certificate: ICertificate = await certificateManager.ensureCertificateAsync( true, taskSession.logger.terminal ); // Update the web socket URL to use the hostname provided by the certificate const clientConfiguration: TRspackDevServer.Configuration['client'] = devServerOptions.client; const hostname: string | undefined = certificate.subjectAltNames?.[0]; if (hostname && typeof clientConfiguration === 'object') { const { webSocketURL } = clientConfiguration; if (typeof webSocketURL === 'object') { clientConfiguration.webSocketURL = { ...webSocketURL, hostname }; } } devServerOptions = { ...devServerOptions, server: { type: 'https', options: { minVersion: 'TLSv1.3', key: certificate.pemKey, cert: certificate.pemCertificate, ca: certificate.pemCaCertificate } } }; } // Since the webpack-dev-server does not return infrastructure errors via a callback like // compiler.watch(...), we will need to intercept them and log them ourselves. // note: @rspack/dev-server extends webpack-dev-server and also has this behavior compiler.hooks.infrastructureLog.tap( PLUGIN_NAME, (name: string, type: string, args: unknown[] | undefined) => { if (name === WEBPACK_DEV_MIDDLEWARE_PACKAGE_NAME && type === 'error') { const error: Error | undefined = args?.[0] as Error | undefined; if (error) { taskSession.logger.emitError(error); } } } ); // The webpack-dev-server package has a design flaw, where merely loading its package will set the // WEBPACK_DEV_SERVER environment variable -- even if no APIs are accessed. This environment variable // causes incorrect behavior if Heft is not running in serve mode. Thus, we need to be careful to call // require() only if Heft is in serve mode. // note: @rspack/dev-server extends webpack-dev-server and also has this behavior taskSession.logger.terminal.writeLine('Starting rspack-dev-server'); const RspackDevServer: typeof TRspackDevServer.RspackDevServer = ( await import(RSPACK_DEV_SERVER_PACKAGE_NAME) ).RspackDevServer; const rspackDevServer: TRspackDevServer.RspackDevServer = new RspackDevServer( devServerOptions, compiler ); await rspackDevServer.start(); } else { // Create the watcher. Compilation will start immediately after invoking watch(). taskSession.logger.terminal.writeLine('Starting Rspack watcher'); const { onGetWatchOptions } = this.accessor.hooks; const watchOptions: | Parameters[0] | Parameters[0] = onGetWatchOptions.isUsed() ? await onGetWatchOptions.promise({}, rspackConfiguration) : {}; (compiler as TRspack.Compiler).watch(watchOptions, (error?: Error | null) => { if (error) { taskSession.logger.emitError(error); } }); } } let hasChanges: boolean = true; if (!isInitial && this.#watchFileSystems) { hasChanges = false; for (const watchFileSystem of this.#watchFileSystems) { // The upstream tasks may have just written files that the watcher has seen but not recorded yet. hasChanges = (await watchFileSystem.flushAsync()) || hasChanges; } } // Resume the compilation, wait for the compilation to complete, then suspend the watchers until the // next iteration. Even if there are no changes, the promise should resolve since resuming from a // suspended state invalidates the state of the watcher. if (hasChanges) { taskSession.logger.terminal.writeLine('Running incremental Rspack compilation'); await rspackCompilationDonePromise; } else { taskSession.logger.terminal.writeLine( 'Rspack has not detected changes. Listing previous diagnostics.' ); } this.#emitErrors(taskSession.logger); } #validateEnvironmentVariable(taskSession: IHeftTaskSession): void { if (!this.#isServeMode && process.env[RSPACK_DEV_SERVER_ENV_VAR_NAME]) { taskSession.logger.emitWarning( new Error( `The "${RSPACK_DEV_SERVER_ENV_VAR_NAME}" environment variable is set, ` + 'which will cause problems when rspack is not running in serve mode. ' + `(Did a dependency inadvertently load the "${RSPACK_DEV_SERVER_PACKAGE_NAME}" package?)` ) ); } } #emitErrors(logger: IScopedLogger): void { for (const warning of this.#warnings) { logger.emitWarning(warning); } for (const error of this.#errors) { logger.emitError(error); } } #recordErrors(stats: TRspack.Stats | TRspack.MultiStats, buildFolderPath: string): void { const errors: Error[] = this.#errors; const warnings: Error[] = this.#warnings; errors.length = 0; warnings.length = 0; if (stats.hasErrors() || stats.hasWarnings()) { const serializedStats: TRspack.StatsCompilation[] = [stats.toJson('errors-warnings')]; for (const compilationStats of serializedStats) { if (compilationStats.warnings) { for (const warning of compilationStats.warnings) { warnings.push(this.#normalizeError(buildFolderPath, warning)); } } if (compilationStats.errors) { for (const error of compilationStats.errors) { errors.push(this.#normalizeError(buildFolderPath, error)); } } if (compilationStats.children) { for (const child of compilationStats.children) { serializedStats.push(child); } } } } } #normalizeError(buildFolderPath: string, error: TRspack.StatsError): Error { if (error instanceof Error) { return error; } else if (error.moduleIdentifier) { let lineNumber: number | undefined; let columnNumber: number | undefined; if (error.loc) { // Format of ":-" // https://webpack.js.org/api/stats/#errors-and-warnings const [lineNumberRaw, columnRangeRaw] = error.loc.split(':'); const [startColumnRaw] = columnRangeRaw.split('-'); if (lineNumberRaw) { lineNumber = parseInt(lineNumberRaw, 10); if (Number.isNaN(lineNumber)) { lineNumber = undefined; } } if (startColumnRaw) { columnNumber = parseInt(startColumnRaw, 10); if (Number.isNaN(columnNumber)) { columnNumber = undefined; } } } return new FileError(error.message, { absolutePath: error.moduleIdentifier, projectFolder: buildFolderPath, line: lineNumber, column: columnNumber }); } else { return new Error(error.message); } } } /** * @internal */ export function _createAccessorHooks(): IRspackPluginAccessorHooks { return { onLoadConfiguration: new AsyncSeriesBailHook(), onConfigure: new AsyncSeriesHook(['rspackConfiguration']), onAfterConfigure: new AsyncParallelHook(['rspackConfiguration']), onEmitStats: new AsyncParallelHook(['rspackStats']), onGetWatchOptions: new AsyncSeriesWaterfallHook(['watchOptions', 'rspackConfiguration']) }; }