import type { SnapManifest } from '@metamask/snaps-utils'; import { loadManifest } from '@metamask/snaps-utils/node'; import { assert, hasProperty, isObject } from '@metamask/utils'; import { bold, dim, red, yellow } from 'chalk'; import { isBuiltin } from 'module'; import type { Ora } from 'ora'; import { dirname, resolve } from 'path'; import type { Compiler, ProvidePlugin, Resolver, StatsError, WebpackPluginInstance, } from 'webpack'; import { Compilation, WebpackError, sources } from 'webpack'; import type { WebpackOptions } from './config'; import { formatText, pluralize, readWebpackFile } from './utils'; import { error, getErrorMessage, info, warn } from '../utils'; export type SnapsStatsPluginOptions = { /** * Whether to log the verbose stats. */ verbose?: boolean; }; /** * A plugin that logs the stats after compilation. This is useful for logging * the number of files compiled, and the time taken to compile them. */ export class SnapsStatsPlugin implements WebpackPluginInstance { /** * The options for the plugin. */ readonly options: SnapsStatsPluginOptions; /** * The spinner to use for logging. */ readonly #spinner?: Ora; constructor( options: SnapsStatsPluginOptions = { verbose: false, }, spinner?: Ora, ) { this.options = options; this.#spinner = spinner; } /** * Apply the plugin to the Webpack compiler. * * @param compiler - The Webpack compiler. */ apply(compiler: Compiler) { compiler.hooks.afterDone.tap(this.constructor.name, (stats) => { if (!stats) { return; } const { modules, time, errors, warnings } = stats.toJson(); assert(modules, 'Modules must be defined in stats.'); assert(time, 'Time must be defined in stats.'); if (errors?.length) { const formattedErrors = errors .map((statsError) => this.#getStatsErrorMessage(statsError, red)) .join('\n\n'); error( `Compiled ${modules.length} ${pluralize( modules.length, 'file', )} in ${time}ms with ${errors.length} ${pluralize( errors.length, 'error', )}.\n\n${formattedErrors}\n`, this.#spinner, ); this.#spinner?.stop(); process.exitCode = 1; return; } if (warnings?.length) { const formattedWarnings = warnings .map((statsWarning) => this.#getStatsErrorMessage(statsWarning, yellow), ) .join('\n\n'); warn( `Compiled ${modules.length} ${pluralize( modules.length, 'file', )} in ${time}ms with ${warnings.length} ${pluralize( warnings.length, 'warning', )}.\n\n${formattedWarnings}\n`, this.#spinner, ); } else { info( `Compiled ${modules.length} ${pluralize( modules.length, 'file', )} in ${time}ms.`, this.#spinner, ); } if (compiler.watchMode) { // The spinner may be restarted by the watch plugin, outside of the // `executeSteps` flow, so we stop it here just in case. this.#spinner?.succeed('Done!'); } }); } /** * Get the error message for the given stats error. * * @param statsError - The stats error. * @param color - The color to use for the error message. * @returns The error message. */ #getStatsErrorMessage( statsError: StatsError, color: typeof red | typeof yellow, ) { const baseMessage = this.options.verbose ? getErrorMessage(statsError) : statsError.message; const [first, ...rest] = baseMessage.split('\n'); return [ color(formatText(`• ${first}`, 4, 2)), ...rest.map((message) => formatText(color(message), 4)), statsError.details && `\n${formatText(dim(statsError.details), 6)}`, ] .filter(Boolean) .join('\n'); } } /** * The options for the {@link SnapsWatchPlugin}. */ export type SnapsWatchPluginOptions = { /** * The path to the manifest, to determine which files to watch. */ manifestPath: string; }; /** * A plugin that adds extra files to watch. This is useful for watching files * that are not imported by the entry point, such as the `snap.manifest.json` * file. */ export class SnapsWatchPlugin implements WebpackPluginInstance { /** * The options for the plugin. */ readonly options: SnapsWatchPluginOptions; /** * The spinner to use for logging. */ readonly #spinner?: Ora; constructor(options: SnapsWatchPluginOptions, spinner?: Ora) { this.options = options; this.#spinner = spinner; } /** * Apply the plugin to the Webpack compiler. * * @param compiler - The Webpack compiler. */ apply(compiler: Compiler) { compiler.hooks.invalid.tap(this.constructor.name, (file) => { this.#spinner?.start(); info(`Changes detected in ${yellow(file)}, recompiling.`, this.#spinner); }); compiler.hooks.afterEmit.tapPromise( this.constructor.name, async ({ fileDependencies }) => { const { files } = await loadManifest(this.options.manifestPath); files.forEach(fileDependencies.add.bind(fileDependencies)); }, ); } } /** * The options for the {@link SnapsBuiltInResolver}. */ export type SnapsBuiltInResolverOptions = { /** * The built-in modules to ignore. */ ignore?: string[]; }; /** * A Webpack resolve plugin. * * Copied from Webpack's own types, because the `ResolvePluginInstance` type is * a union, and can't be used as a type for a class. */ type ResolvePlugin = { apply: (resolver: Resolver) => void; }; /** * A plugin that logs a message when a built-in module is not resolved. The * MetaMask Snaps CLI does not support built-in modules by default, and this * plugin is used to warn the user when they try to import a built-in module, * when no fallback is configured. */ export class SnapsBuiltInResolver implements ResolvePlugin { /** * The built-in modules that have been imported, but not resolved. */ readonly unresolvedModules = new Set(); /** * The name of the resolver hook to tap into. */ readonly #source = 'described-resolve'; /** * The options for the plugin. */ readonly options: SnapsBuiltInResolverOptions; constructor( options: SnapsBuiltInResolverOptions = { ignore: [], }, ) { this.options = options; } /** * Apply the plugin to the Webpack resolver. * * @param resolver - The Webpack resolver. */ apply(resolver: Resolver) { resolver .getHook(this.#source) .tapAsync( this.constructor.name, ({ module: isModule, request }, _, callback) => { if (!isModule || !request) { return callback(); } const baseRequest = request.split('/')[0]; if ( isBuiltin(baseRequest) && !this.options.ignore?.includes(baseRequest) ) { const fallback = resolver.options.fallback.find( ({ name }) => name === baseRequest, ); if (fallback && !fallback.alias) { this.unresolvedModules.add(baseRequest); } } return callback(); }, ); } } /** * The options for the {@link SnapsBundleWarningsPlugin}. */ export type SnapsBundleWarningsPluginOptions = { /** * The {@link SnapsBuiltInResolver} instance to use for detecting built-in * modules. */ builtInResolver?: SnapsBuiltInResolver | false; /** * Whether to show warnings if built-in modules are used, but not provided by * Webpack's `fallback` configuration. */ builtIns?: boolean; /** * Whether to show warnings if the `Buffer` global is used, but not provided * by Webpack's `DefinePlugin`. */ buffer?: boolean; }; /** * A plugin that logs a message when: * * - A built-in module is not resolved. The MetaMask Snaps CLI does not support * built-in modules by default, and this plugin is used to warn the user when * they try to import a built-in module, when no fallback is configured. * - A snap uses the `Buffer` global. The MetaMask Snaps CLI does not support * the `Buffer` global by default, and this plugin is used to warn the user when * they try to use the `Buffer` global. * * We use both a resolver and a plugin, because the resolver is used to detect * when a built-in module is imported, and the plugin is used to log a single * message when the compilation is complete. We can't do everything in a single * plugin, because the resolver doesn't have access to the compilation, and the * plugin doesn't have access to the resolver. */ export class SnapsBundleWarningsPlugin implements WebpackPluginInstance { /** * The options for the plugin. */ readonly options: SnapsBundleWarningsPluginOptions; constructor( options: SnapsBundleWarningsPluginOptions = { buffer: true, builtIns: true, }, ) { this.options = options; } /** * Apply the plugin to the Webpack compiler. * * @param compiler - The Webpack compiler. */ apply(compiler: Compiler) { if (this.options.builtIns) { this.#checkBuiltIns(compiler); } if (this.options.buffer) { this.#checkBuffer(compiler); } } /** * Check if a built-in module is used, but not provided by Webpack's * `fallback` configuration. * * @param compiler - The Webpack compiler. */ #checkBuiltIns(compiler: Compiler) { compiler.hooks.afterCompile.tap(this.constructor.name, (compilation) => { if (!this.options.builtInResolver) { return; } const { unresolvedModules } = this.options.builtInResolver; if (unresolvedModules.size === 0) { return; } const formattedModules = new Array(...unresolvedModules) .map((name) => `• ${name}`) .join('\n'); const webpackError = new WebpackError( `The snap attempted to use one or more Node.js builtins, but no browser fallback has been provided. The MetaMask Snaps CLI does not support Node.js builtins by default. If you want to use this module, you must set ${bold( '`polyfills`', )} to ${bold( '`true`', )} or an object with the builtins to polyfill as the key and ${bold( '`true`', )} as the value. To disable this warning, set ${bold( '`stats.builtIns`', )} to ${bold( '`false`', )} in your snap config file, or add the module to the ${bold( '`stats.builtIns.ignore`', )} array.`, ); webpackError.details = formattedModules; compilation.warnings.push(webpackError); }); } /** * Check if the given instance is a `ProvidePlugin`. This is not guaranteed to * be accurate, but it's good enough for our purposes. If we were to use * `instanceof` instead, it might not work if multiple versions of Webpack are * installed. * * @param instance - The instance to check. * @returns Whether the instance is a `ProvidePlugin`, i.e., whether it's an * object with the name `ProvidePlugin` and a `definitions` property. */ #isProvidePlugin(instance: unknown): instance is ProvidePlugin { return ( isObject(instance) && instance.constructor.name === 'ProvidePlugin' && hasProperty(instance, 'definitions') ); } /** * Check if the `Buffer` global is used, but not provided by Webpack's * `DefinePlugin`. * * @param compiler - The Webpack compiler. */ #checkBuffer(compiler: Compiler) { const plugin = compiler.options.plugins?.find((instance) => this.#isProvidePlugin(instance), ); // If the `ProvidePlugin` is configured to provide `Buffer`, then we don't // need to warn the user. if (plugin) { const { definitions } = plugin; if (definitions.Buffer) { return; } } compiler.hooks.compilation.tap(this.constructor.name, (compilation) => { compilation.hooks.afterProcessAssets.tap( this.constructor.name, (assets) => { // Check if assets use `Buffer`. const bufferAssets = Object.entries(assets) .filter(([name]) => name.endsWith('.js')) .filter(([, asset]) => asset.source().includes('Buffer')); if (bufferAssets.length === 0) { return; } compilation.warnings.push( new WebpackError( `The snap attempted to use the Node.js Buffer global, which is not supported in the MetaMask Snaps CLI by default. To use the Buffer global, you must polyfill Buffer by setting ${bold( '`buffer`', )} to ${bold('`true`')} in the ${bold( '`polyfills`', )} config object in your snap config. To disable this warning, set ${bold( '`stats.buffer`', )} to ${bold('`false`')} in your snap config file.`, ), ); }, ); }); } } /** * The options for the {@link PreinstalledSnapsBundlePlugin}. */ export type PreinstalledSnapsBundlePluginOptions = { /** * The path to the manifest file. */ manifestPath: string; /** * The name of the output file. */ outputName: string; /** * The preinstalled options from the Webpack configuration. */ preinstalledOptions: WebpackOptions['preinstalledOptions']; }; /** * A plugin that creates a preinstalled Snap bundle from the compiled bundle. * This will read the manifest, and any required files (locales, icon), and * create a `preinstalled-snap.json` file that can be used to install the Snap * as a preinstalled Snap. */ export class PreinstalledSnapsBundlePlugin implements WebpackPluginInstance { readonly #options: PreinstalledSnapsBundlePluginOptions; readonly #spinner?: Ora; constructor(options: PreinstalledSnapsBundlePluginOptions, spinner?: Ora) { this.#options = options; this.#spinner = spinner; } /** * Apply the plugin to the Webpack compiler. * * @param compiler - The Webpack compiler. */ apply(compiler: Compiler) { compiler.hooks.compilation.tap(this.constructor.name, (compilation) => { compilation.hooks.processAssets.tapPromise( { name: this.constructor.name, // `PROCESS_ASSETS_STAGE_REPORT` is the last stage, so we ensure this // plugin runs after all other plugins have finished processing // assets. stage: Compilation.PROCESS_ASSETS_STAGE_REPORT, }, async () => { info('Creating preinstalled Snap bundle.', this.#spinner); const asset = compilation.getAsset(this.#options.outputName); if (!asset) { compilation.errors.push( new WebpackError( 'Bundle asset not found. Make sure to build the project first.', ), ); return; } const bundleSource = asset.source.source().toString(); const preinstalledSnapBundleJson = JSON.stringify( await this.#createPreinstalledBundle(compilation, bundleSource), null, 2, ); compilation.emitAsset( 'preinstalled-snap.json', new sources.RawSource(preinstalledSnapBundleJson), ); }, ); }); } /** * Create a preinstalled bundle object from the given bundle source. This will * load the manifest, read any required files (locales, icon), and return the * preinstalled bundle object. * * Custom auxiliary files are not currently supported in preinstalled Snaps. * * @param compilation - The Webpack compilation. * @param bundleSource - The source code of the bundle. * @returns The preinstalled bundle object. */ async #createPreinstalledBundle( compilation: Compilation, bundleSource: string, ) { const { mergedManifest } = await loadManifest(this.#options.manifestPath); const manifest = mergedManifest as SnapManifest; const basePath = dirname(this.#options.manifestPath); const files = [ { path: manifest.source.location.npm.filePath, value: bundleSource, }, ]; if (manifest.source.locales) { for (const locale of manifest.source.locales) { files.push({ path: locale, value: await readWebpackFile( compilation.inputFileSystem, resolve(basePath, locale), ), }); } } if (manifest.source.location.npm.iconPath) { const { iconPath } = manifest.source.location.npm; files.push({ path: manifest.source.location.npm.iconPath, // The icon is expected to be an SVG file, so we read it as UTF-8. value: await readWebpackFile( compilation.inputFileSystem, resolve(basePath, iconPath), ), }); } return { snapId: `npm:${manifest.source.location.npm.packageName}`, manifest, files, ...this.#options.preinstalledOptions, }; } }