@metamask/snaps-cli 0.38.0-flask.1 → 0.38.2-flask.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -1
- package/dist/cjs/config.js +33 -0
- package/dist/cjs/config.js.map +1 -1
- package/dist/cjs/webpack/config.js +11 -6
- package/dist/cjs/webpack/config.js.map +1 -1
- package/dist/cjs/webpack/plugins.js +2 -2
- package/dist/cjs/webpack/plugins.js.map +1 -1
- package/dist/cjs/webpack/utils.js +55 -7
- package/dist/cjs/webpack/utils.js.map +1 -1
- package/dist/esm/config.js +33 -0
- package/dist/esm/config.js.map +1 -1
- package/dist/esm/webpack/config.js +13 -8
- package/dist/esm/webpack/config.js.map +1 -1
- package/dist/esm/webpack/plugins.js +2 -2
- package/dist/esm/webpack/plugins.js.map +1 -1
- package/dist/esm/webpack/utils.js +55 -7
- package/dist/esm/webpack/utils.js.map +1 -1
- package/dist/types/config.d.ts +166 -0
- package/dist/types/webpack/utils.d.ts +40 -8
- package/package.json +35 -14
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.38.2-flask.1]
|
|
10
|
+
### Added
|
|
11
|
+
- Add `polyfills` option to Webpack configuration ([#1650](https://github.com/MetaMask/snaps/pull/1650))
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
- Fix breaking change to SWC causing the CLI to break ([#1677](https://github.com/MetaMask/snaps/pull/1677))
|
|
15
|
+
|
|
16
|
+
## [0.38.1-flask.1]
|
|
17
|
+
### Changed
|
|
18
|
+
- Update all examples to use Webpack ([#1632](https://github.com/MetaMask/snaps/pull/1632))
|
|
19
|
+
|
|
9
20
|
## [0.38.0-flask.1]
|
|
10
21
|
### Added
|
|
11
22
|
- Add support for bundling with Webpack ([#1521](https://github.com/MetaMask/snaps/pull/1521))
|
|
@@ -24,5 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
24
35
|
- The version of the package no longer needs to match the version of all other
|
|
25
36
|
MetaMask Snaps packages.
|
|
26
37
|
|
|
27
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@0.38.
|
|
38
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@0.38.2-flask.1...HEAD
|
|
39
|
+
[0.38.2-flask.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@0.38.1-flask.1...@metamask/snaps-cli@0.38.2-flask.1
|
|
40
|
+
[0.38.1-flask.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@0.38.0-flask.1...@metamask/snaps-cli@0.38.1-flask.1
|
|
28
41
|
[0.38.0-flask.1]: https://github.com/MetaMask/snaps/releases/tag/@metamask/snaps-cli@0.38.0-flask.1
|
package/dist/cjs/config.js
CHANGED
|
@@ -132,6 +132,39 @@ const SnapsWebpackConfigStruct = (0, _superstruct.object)({
|
|
|
132
132
|
]), {}),
|
|
133
133
|
buffer: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), true)
|
|
134
134
|
}), {}),
|
|
135
|
+
polyfills: (0, _superstruct.defaulted)((0, _snapsutils.union)([
|
|
136
|
+
(0, _superstruct.boolean)(),
|
|
137
|
+
(0, _superstruct.object)({
|
|
138
|
+
assert: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
139
|
+
buffer: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
140
|
+
console: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
141
|
+
constants: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
142
|
+
crypto: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
143
|
+
domain: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
144
|
+
events: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
145
|
+
http: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
146
|
+
https: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
147
|
+
os: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
148
|
+
path: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
149
|
+
punycode: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
150
|
+
process: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
151
|
+
querystring: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
152
|
+
stream: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
153
|
+
/* eslint-disable @typescript-eslint/naming-convention */ _stream_duplex: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
154
|
+
_stream_passthrough: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
155
|
+
_stream_readable: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
156
|
+
_stream_transform: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
157
|
+
_stream_writable: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
158
|
+
string_decoder: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
159
|
+
/* eslint-enable @typescript-eslint/naming-convention */ sys: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
160
|
+
timers: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
161
|
+
tty: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
162
|
+
url: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
163
|
+
util: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
164
|
+
vm: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
165
|
+
zlib: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false)
|
|
166
|
+
})
|
|
167
|
+
]), false),
|
|
135
168
|
customizeWebpackConfig: (0, _superstruct.optional)(SnapsWebpackCustomizeWebpackConfigFunctionStruct),
|
|
136
169
|
experimental: (0, _superstruct.defaulted)((0, _superstruct.object)({
|
|
137
170
|
wasm: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false)
|
package/dist/cjs/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config.ts"],"sourcesContent":["import {\n createFromStruct,\n file,\n indent,\n isFile,\n literal,\n union,\n SnapsStructError,\n named,\n} from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\nimport { transform } from '@swc/core';\nimport type { BrowserifyObject } from 'browserify';\nimport { dim } from 'chalk';\nimport { readFile } from 'fs/promises';\nimport Module from 'module';\nimport { basename, dirname, resolve } from 'path';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n defaulted,\n define,\n func,\n number,\n object,\n optional,\n record,\n string,\n type,\n unknown,\n empty,\n} from 'superstruct';\nimport type { Configuration as WebpackConfiguration } from 'webpack';\n\nimport { TranspilationModes } from './builders';\nimport { ConfigError } from './errors';\nimport type { YargsArgs } from './types/yargs';\nimport { CONFIG_FILE, TS_CONFIG_FILE } from './utils';\n\nconst CONFIG_FILES = [CONFIG_FILE, TS_CONFIG_FILE];\n\n/**\n * The configuration for the Snaps CLI, stored as `snap.config.js` or\n * `snap.config.ts` in the root of the project.\n *\n * @deprecated The Browserify bundler is deprecated and will be removed in a\n * future release. Use the Webpack bundler instead.\n */\nexport type SnapBrowserifyConfig = {\n /**\n * The bundler to use to build the snap. For backwards compatibility, if not\n * specified, Browserify will be used. However, the Browserify bundler is\n * deprecated and will be removed in a future release, so it's recommended to\n * use the Webpack bundler instead.\n */\n bundler?: 'browserify';\n\n /**\n * The options for the Snaps CLI. These are merged with the options passed to\n * the CLI, with the CLI options taking precedence.\n *\n * @deprecated The Browserify bundler is deprecated and will be removed in a\n * future release. Use the Webpack bundler instead.\n */\n cliOptions?: {\n /**\n * The path to the snap bundle file.\n *\n * @default 'dist/bundle.js'\n */\n bundle?: string;\n\n /**\n * The directory to output the snap to. This is only used if `bundle` is\n * not specified.\n *\n * @default 'dist'\n */\n dist?: string;\n\n /**\n * Whether to attempt to evaluate the snap in SES. This can catch some errors\n * that would otherwise only be caught at runtime.\n *\n * @default true\n */\n eval?: boolean;\n\n /**\n * Whether to validate the snap manifest.\n *\n * @default true\n */\n manifest?: boolean;\n\n /**\n * The name of the bundle file. This is only used if `bundle` is not\n * specified.\n *\n * @default 'bundle.js'\n */\n outfileName?: string;\n\n /**\n * The port to run the server on.\n *\n * @default 8081\n */\n port?: number;\n\n /**\n * The root directory to serve the snap from.\n *\n * @default `process.cwd()`\n */\n root?: string;\n\n /**\n * Whether to generate source maps for the snap bundle.\n *\n * @default false\n */\n sourceMaps?: boolean;\n\n /**\n * The path to the snap entry point.\n *\n * @default 'src/index.js'\n */\n src?: string;\n\n /**\n * Whether to remove comments from the bundle.\n *\n * @default true\n */\n stripComments?: boolean;\n\n /**\n * Whether to suppress warnings.\n *\n * @default false\n */\n suppressWarnings?: boolean;\n\n /**\n * The transpilation mode to use, which determines which files are\n * transpiled.\n *\n * - `'localAndDeps'`: Transpile the snap entry point and all dependencies.\n * - `'localOnly'`: Transpile only the snap entry point.\n * - `'none'`: Don't transpile any files.\n *\n * @default 'localOnly'\n */\n transpilationMode?: 'localAndDeps' | 'localOnly' | 'none';\n\n /**\n * The dependencies to transpile when `transpilationMode` is set to\n * `'localAndDeps'`. If not specified, all dependencies will be transpiled.\n */\n depsToTranspile?: string[];\n\n /**\n * Whether to show original errors.\n *\n * @default true\n */\n verboseErrors?: boolean;\n\n /**\n * Whether to write the updated manifest to disk.\n *\n * @default true\n */\n writeManifest?: boolean;\n\n /**\n * Whether to serve the snap locally.\n *\n * @default true\n */\n serve?: boolean;\n };\n\n /**\n * A function that can be used to customize the Browserify instance used to\n * build the snap.\n *\n * @param bundler - The Browserify instance.\n * @deprecated The Browserify bundler is deprecated and will be removed in a\n * future release. Use the Webpack bundler instead.\n */\n bundlerCustomizer?: (bundler: BrowserifyObject) => void;\n};\n\n/**\n * The configuration for the Snaps CLI, stored as `snap.config.js` or\n * `snap.config.ts` in the root of the project.\n */\nexport type SnapWebpackConfig = {\n /**\n * The bundler to use to build the snap. For backwards compatibility, if not\n * specified, Browserify will be used. However, the Browserify bundler is\n * deprecated and will be removed in a future release, so it's recommended to\n * use the Webpack bundler instead.\n */\n bundler: 'webpack';\n\n /**\n * The path to the snap entry point. This should be a JavaScript or TypeScript\n * file.\n */\n input: string;\n\n /**\n * Whether to generate source maps for the snap. If `true`, source maps will\n * be generated as separate files. If `'inline'`, source maps will be\n * inlined in the generated JavaScript bundle.\n *\n * @default true\n */\n sourceMap?: boolean | 'inline';\n\n /**\n * Whether to attempt to evaluate the snap in SES. This can catch some errors\n * that would otherwise only be caught at runtime.\n *\n * @default true\n */\n evaluate?: boolean;\n\n output?: {\n /**\n * The path to the directory where the snap will be built. This directory\n * will be created if it doesn't exist.\n *\n * If the path is relative, it will be resolved relative to the current\n * working directory.\n *\n * @default 'dist'\n */\n path?: string;\n\n /**\n * The name of the JavaScript bundle file.\n *\n * @default 'bundle.js'\n */\n filename?: string;\n\n /**\n * Whether to clean the output directory before building the snap. If\n * `true`, the output directory will be deleted and recreated. Otherwise,\n * the output directory will be left as-is.\n *\n * @default false\n */\n clean?: boolean;\n\n /**\n * Whether to minimize the snap bundle. If `true`, the bundle will be\n * minified. Otherwise, the bundle will be left as-is.\n *\n * @default true\n */\n minimize?: boolean;\n };\n\n manifest?: {\n /**\n * The path to the snap manifest file. If the path is relative, it will be\n * resolved relative to the current working directory.\n *\n * @default 'snap.manifest.json'\n */\n path?: string;\n\n /**\n * Whether to automatically update the manifest. If `true`, the manifest\n * will be updated with the latest shasum of the snap bundle, and some\n * common fields will be updated if they are missing or incorrect. If\n * `false`, the manifest will be left as-is.\n *\n * @default true\n */\n update?: boolean;\n };\n\n server?: {\n /**\n * Whether to enable the local server. If `true`, the snap will be served\n * from a local server, when running the `watch` command. If `false`, the\n * snap will not be served.\n *\n * @default true\n */\n enabled?: boolean;\n\n /**\n * The root directory to serve the snap from. If the path is relative, it\n * will be resolved relative to the current working directory.\n *\n * @default `process.cwd()`\n */\n root?: string;\n\n /**\n * The port to run the server on.\n *\n * @default 8081\n */\n port?: number;\n };\n\n /**\n * The environment variables to set when building the snap. These will be\n * available in the snap as `process.env`. In addition to these environment\n * variables, the following environment variables will always be set:\n *\n * - `NODE_DEBUG`: `false`\n * - `NODE_ENV`: `'production'`\n * - `DEBUG`: `false`\n *\n * Any environment variables specified here will override these defaults. You\n * can also override any variables here by setting them in your shell when\n * running the CLI.\n */\n environment?: Record<string, unknown>;\n\n /**\n * Options that control the logging output of the CLI.\n */\n stats?: {\n /**\n * Whether to enable verbose logging.\n *\n * @default false\n */\n verbose?: boolean;\n\n /**\n * Whether to log warnings about unresolved built-in modules. If `false`,\n * warnings will not be logged.\n */\n builtIns?:\n | {\n /**\n * The built-in modules to ignore when resolving modules. If a module\n * is ignored, no warning will be logged if it is not resolved.\n */\n ignore?: string[];\n }\n | false;\n\n /**\n * Whether to log warnings about the use of the `Buffer` global. If `false`,\n * warnings will not be logged. If `true`, the CLI will warn if the `Buffer`\n * global is used, but not provided by Webpack's `DefinePlugin`.\n */\n buffer?: boolean;\n };\n\n /**\n * A function to customize the Webpack configuration used to build the snap.\n * This function will be called with the default Webpack configuration, and\n * should return the modified configuration. If not specified, the default\n * configuration will be used.\n *\n * It's recommended to use the `webpack-merge` package to merge the default\n * configuration with your customizations. The merge function is exported as\n * `merge` from the `@metamask/snaps-cli` package.\n *\n * @example\n * ```ts\n * import type { SnapsConfig } from '@metamask/snaps-cli';\n * import { merge } from '@metamask/snaps-cli';\n *\n * const config: SnapsConfig = {\n * bundler: 'webpack',\n * entry: 'src/index.ts',\n * customizeWebpackConfig: (config) => merge(config, {\n * module: {\n * rules: [\n * {\n * test: /\\.wasm$/,\n * type: 'assets/resource',\n * },\n * ],\n * },\n * }),\n * };\n *\n * export default config;\n * ```\n */\n customizeWebpackConfig?: (\n config: WebpackConfiguration,\n ) => WebpackConfiguration;\n\n /**\n * Experimental features that can be enabled. These features are not\n * guaranteed to be stable, and may be removed or changed in a future release.\n */\n experimental?: {\n /**\n * Whether to enable WebAssembly support. If `true`, the Webpack\n * configuration will be modified to support WebAssembly. If `false`, the\n * Webpack configuration will not be modified.\n *\n * @default false\n */\n wasm?: boolean;\n };\n};\n\n/**\n * The configuration for the Snaps CLI, stored as `snap.config.js` or\n * `snap.config.ts` in the root of the project.\n */\nexport type SnapConfig = SnapBrowserifyConfig | SnapWebpackConfig;\n\ntype SnapsBrowserifyBundlerCustomizerFunction = (\n bundler: BrowserifyObject,\n) => void;\n\n// This struct is essentially the same as the `func` struct, but it's defined\n// separately so that we include the function type in the inferred TypeScript\n// type definitions.\nconst SnapsBrowserifyBundlerCustomizerFunctionStruct =\n define<SnapsBrowserifyBundlerCustomizerFunction>(\n 'function',\n func().validator,\n );\n\nexport const SnapsBrowserifyConfigStruct = object({\n bundler: defaulted(literal('browserify'), 'browserify'),\n cliOptions: defaulted(\n object({\n bundle: optional(file()),\n dist: defaulted(file(), 'dist'),\n eval: defaulted(boolean(), true),\n manifest: defaulted(boolean(), true),\n port: defaulted(number(), 8081),\n outfileName: defaulted(string(), 'bundle.js'),\n root: defaulted(file(), process.cwd()),\n sourceMaps: defaulted(boolean(), false),\n src: defaulted(file(), 'src/index.js'),\n stripComments: defaulted(boolean(), true),\n suppressWarnings: defaulted(boolean(), false),\n transpilationMode: defaulted(\n union([literal('localAndDeps'), literal('localOnly'), literal('none')]),\n 'localOnly',\n ),\n depsToTranspile: defaulted(array(string()), []),\n verboseErrors: defaulted(boolean(), true),\n writeManifest: defaulted(boolean(), true),\n serve: defaulted(boolean(), true),\n }),\n {},\n ),\n bundlerCustomizer: optional(SnapsBrowserifyBundlerCustomizerFunctionStruct),\n});\n\ntype SnapsWebpackCustomizeWebpackConfigFunction = (\n config: WebpackConfiguration,\n) => WebpackConfiguration;\n\n// This struct is essentially the same as the `func` struct, but it's defined\n// separately so that we include the function type in the inferred TypeScript\n// type definitions.\nconst SnapsWebpackCustomizeWebpackConfigFunctionStruct =\n define<SnapsWebpackCustomizeWebpackConfigFunction>(\n 'function',\n func().validator,\n );\n\nexport const SnapsWebpackConfigStruct = object({\n bundler: literal('webpack'),\n input: defaulted(file(), resolve(process.cwd(), 'src/index.js')),\n sourceMap: defaulted(union([boolean(), literal('inline')]), true),\n evaluate: defaulted(boolean(), true),\n\n output: defaulted(\n object({\n path: defaulted(file(), resolve(process.cwd(), 'dist')),\n filename: defaulted(string(), 'bundle.js'),\n clean: defaulted(boolean(), false),\n minimize: defaulted(boolean(), true),\n }),\n {},\n ),\n\n manifest: defaulted(\n object({\n path: defaulted(file(), resolve(process.cwd(), 'snap.manifest.json')),\n update: defaulted(boolean(), true),\n }),\n {},\n ),\n\n server: defaulted(\n object({\n enabled: defaulted(boolean(), true),\n root: defaulted(file(), process.cwd()),\n port: defaulted(number(), 8081),\n }),\n {},\n ),\n\n environment: defaulted(record(string(), unknown()), {\n NODE_DEBUG: false,\n NODE_ENV: 'production',\n DEBUG: false,\n }),\n\n stats: defaulted(\n object({\n verbose: defaulted(boolean(), false),\n builtIns: defaulted(\n union([\n object({ ignore: defaulted(array(string()), []) }),\n literal(false),\n ]),\n {},\n ),\n buffer: defaulted(boolean(), true),\n }),\n {},\n ),\n\n customizeWebpackConfig: optional(\n SnapsWebpackCustomizeWebpackConfigFunctionStruct,\n ),\n\n experimental: defaulted(\n object({\n wasm: defaulted(boolean(), false),\n }),\n {},\n ),\n});\n\nexport const SnapsConfigStruct = type({\n bundler: defaulted(\n union([literal('browserify'), literal('webpack')]),\n 'browserify',\n ),\n});\n\nexport const LegacyOptionsStruct = union([\n named(\n 'object with `transpilationMode` set to `localAndDeps` and `depsToTranspile` set to an array of strings',\n type({\n depsToTranspile: array(string()),\n transpilationMode: literal(TranspilationModes.LocalAndDeps),\n writeManifest: boolean(),\n bundlerCustomizer: optional(\n SnapsBrowserifyBundlerCustomizerFunctionStruct,\n ),\n }),\n ),\n named(\n 'object without `depsToTranspile`',\n type({\n depsToTranspile: named('empty array', empty(array())),\n transpilationMode: union([\n literal(TranspilationModes.LocalOnly),\n literal(TranspilationModes.None),\n ]),\n writeManifest: boolean(),\n bundlerCustomizer: optional(\n SnapsBrowserifyBundlerCustomizerFunctionStruct,\n ),\n }),\n ),\n]);\n\nexport type LegacyOptions = Infer<typeof LegacyOptionsStruct>;\n\nexport type ProcessedBrowserifyConfig = Infer<\n typeof SnapsBrowserifyConfigStruct\n>;\n\nexport type ProcessedWebpackConfig = Infer<typeof SnapsWebpackConfigStruct> & {\n /**\n * The legacy Browserify config, if the bundler is Browserify. This is used\n * to support the legacy config format.\n */\n legacy?: LegacyOptions;\n};\n\nexport type ProcessedConfig = ProcessedWebpackConfig;\n\n/**\n * Get a validated snap config. This validates the config and adds default\n * values for any missing properties.\n *\n * @param config - The config to validate.\n * @param argv - The CLI arguments.\n * @returns The validated config.\n */\nexport function getConfig(config: unknown, argv: YargsArgs): ProcessedConfig {\n const prefix = 'The snap config file is invalid';\n const suffix = dim(\n // TODO: Link to `docs.metamask.io` once the docs are published.\n 'Refer to the documentation for more information: https://github.com/MetaMask/snaps/tree/main/packages/snaps-cli/',\n );\n\n const { bundler } = createFromStruct(\n config,\n SnapsConfigStruct,\n prefix,\n suffix,\n );\n\n if (bundler === 'browserify') {\n const legacyConfig = createFromStruct(\n config,\n SnapsBrowserifyConfigStruct,\n prefix,\n suffix,\n );\n\n return getWebpackConfig(mergeLegacyOptions(argv, legacyConfig));\n }\n\n return createFromStruct(config, SnapsWebpackConfigStruct, prefix, suffix);\n}\n\n/**\n * Load a snap config from a file. This supports both JavaScript and TypeScript\n * config files, in the CommonJS module format and the ES module format.\n *\n * This assumes that the config file exports a default object, either through\n * `module.exports` or `export default`.\n *\n * @param path - The full path to the config file.\n * @param argv - The CLI arguments.\n * @returns The validated config.\n * @throws If the config file is invalid, or if the config file does not have a\n * default export.\n */\nexport async function loadConfig(path: string, argv: YargsArgs) {\n try {\n const contents = await readFile(path, 'utf8');\n const source = await transform(contents, {\n swcrc: false,\n jsc: {\n parser: {\n syntax: 'typescript',\n },\n },\n module: {\n type: 'commonjs',\n },\n });\n\n const config = new Module(path);\n\n // @ts-expect-error - This function is not typed.\n config.paths = Module._nodeModulePaths(dirname(path));\n\n // @ts-expect-error - This function is not typed.\n config._compile(source.code, path);\n\n if (!hasProperty(config.exports, 'default')) {\n return getConfig(config.exports, argv);\n }\n\n return getConfig(config.exports.default, argv);\n } catch (error) {\n if (error instanceof SnapsStructError) {\n throw new ConfigError(error.message);\n }\n\n throw new ConfigError(\n `Unable to load snap config file at \"${path}\".\\n\\n${indent(\n error.message,\n )}`,\n );\n }\n}\n\n/**\n * Resolve a snap config. This function will look for a `snap.config.js` or\n * `snap.config.ts` file in the current or specified directory.\n *\n * @param path - The path to resolve the snap config from. Defaults to the\n * current working directory.\n * @param argv - The CLI arguments.\n * @returns The resolved and validated snap config.\n * @throws If a snap config could not be found.\n */\nexport async function resolveConfig(path: string, argv: YargsArgs) {\n for (const configFile of CONFIG_FILES) {\n const filePath = resolve(path, configFile);\n if (await isFile(filePath)) {\n return await loadConfig(filePath, argv);\n }\n }\n\n throw new ConfigError(\n `Could not find a \"snap.config.js\" or \"snap.config.ts\" file in the current or specified directory (\"${path}\").`,\n );\n}\n\n/**\n * Get a snap config from the CLI arguments. This will either load the config\n * from the specified config file, or resolve the config from the current\n * working directory.\n *\n * @param argv - The CLI arguments.\n * @param cwd - The current working directory. Defaults to `process.cwd()`.\n * @returns The resolved and validated snap config.\n */\nexport async function getConfigByArgv(\n argv: YargsArgs,\n cwd: string = process.cwd(),\n) {\n if (argv.config) {\n if (!(await isFile(argv.config))) {\n throw new ConfigError(\n `Could not find a config file at \"${argv.config}\". Make sure that the path is correct.`,\n );\n }\n\n return await loadConfig(argv.config, argv);\n }\n\n return await resolveConfig(cwd, argv);\n}\n\n/**\n * Merge legacy CLI options into the config. This is used to support the legacy\n * config format, where options can be specified both in the config file and\n * through CLI flags.\n *\n * @param argv - The CLI arguments.\n * @param config - The config to merge the CLI options into.\n * @returns The config with the CLI options merged in.\n * @deprecated This function is only used to support the legacy config format.\n */\nexport function mergeLegacyOptions(\n argv: YargsArgs,\n config: ProcessedBrowserifyConfig,\n) {\n const cliOptions = Object.keys(config.cliOptions).reduce<\n ProcessedBrowserifyConfig['cliOptions']\n >((accumulator, key) => {\n if (argv[key] !== undefined) {\n return {\n ...accumulator,\n [key]: argv[key],\n };\n }\n\n return accumulator;\n }, config.cliOptions);\n\n return {\n ...config,\n cliOptions,\n };\n}\n\n/**\n * Get a Webpack config from a legacy browserify config. This is used to\n * support the legacy config format, and convert it to the new format.\n *\n * @param legacyConfig - The legacy browserify config.\n * @returns The Webpack config.\n */\nexport function getWebpackConfig(\n legacyConfig: ProcessedBrowserifyConfig,\n): ProcessedWebpackConfig {\n const defaultConfig = create(\n { bundler: 'webpack' },\n SnapsWebpackConfigStruct,\n );\n\n // The legacy config has two options for specifying the output path and\n // filename: `bundle`, and `dist` + `outfileName`. If `bundle` is specified,\n // we use that as the output path and filename. Otherwise, we use `dist` and\n // `outfileName`.\n const path = legacyConfig.cliOptions.bundle\n ? dirname(legacyConfig.cliOptions.bundle)\n : legacyConfig.cliOptions.dist;\n\n const filename = legacyConfig.cliOptions.bundle\n ? basename(legacyConfig.cliOptions.bundle)\n : legacyConfig.cliOptions.outfileName;\n\n return {\n ...defaultConfig,\n input: legacyConfig.cliOptions.src,\n evaluate: legacyConfig.cliOptions.eval,\n sourceMap: legacyConfig.cliOptions.sourceMaps,\n output: {\n path,\n filename,\n\n // The legacy config has an option to remove comments from the bundle, but\n // the terser plugin does this by default, so we only enable the terser if\n // the legacy config has `stripComments` set to `true`. This is not a\n // perfect solution, but it's the best we can do without breaking the\n // legacy config.\n minimize: legacyConfig.cliOptions.stripComments,\n\n // The legacy config does not have a `clean` option, so we default to\n // `false` here.\n clean: false,\n },\n manifest: {\n // The legacy config does not have a `manifest` option, so we default to\n // `process.cwd()/snap.manifest.json`.\n path: resolve(process.cwd(), 'snap.manifest.json'),\n update: legacyConfig.cliOptions.writeManifest,\n },\n server: {\n enabled: legacyConfig.cliOptions.serve,\n port: legacyConfig.cliOptions.port,\n root: legacyConfig.cliOptions.root,\n },\n stats: {\n verbose: false,\n\n // These plugins are designed to be used with the modern config format, so\n // we disable them for the legacy config format.\n builtIns: false,\n buffer: false,\n },\n legacy: createFromStruct(\n {\n ...legacyConfig.cliOptions,\n bundlerCustomizer: legacyConfig.bundlerCustomizer,\n },\n LegacyOptionsStruct,\n 'Invalid Browserify CLI options',\n ),\n };\n}\n"],"names":["SnapsBrowserifyConfigStruct","SnapsWebpackConfigStruct","SnapsConfigStruct","LegacyOptionsStruct","getConfig","loadConfig","resolveConfig","getConfigByArgv","mergeLegacyOptions","getWebpackConfig","CONFIG_FILES","CONFIG_FILE","TS_CONFIG_FILE","SnapsBrowserifyBundlerCustomizerFunctionStruct","define","func","validator","object","bundler","defaulted","literal","cliOptions","bundle","optional","file","dist","eval","boolean","manifest","port","number","outfileName","string","root","process","cwd","sourceMaps","src","stripComments","suppressWarnings","transpilationMode","union","depsToTranspile","array","verboseErrors","writeManifest","serve","bundlerCustomizer","SnapsWebpackCustomizeWebpackConfigFunctionStruct","input","resolve","sourceMap","evaluate","output","path","filename","clean","minimize","update","server","enabled","environment","record","unknown","NODE_DEBUG","NODE_ENV","DEBUG","stats","verbose","builtIns","ignore","buffer","customizeWebpackConfig","experimental","wasm","type","named","TranspilationModes","LocalAndDeps","empty","LocalOnly","None","config","argv","prefix","suffix","dim","createFromStruct","legacyConfig","contents","readFile","source","transform","swcrc","jsc","parser","syntax","module","Module","paths","_nodeModulePaths","dirname","_compile","code","hasProperty","exports","default","error","SnapsStructError","ConfigError","message","indent","configFile","filePath","isFile","Object","keys","reduce","accumulator","key","undefined","defaultConfig","create","basename","legacy"],"mappings":";;;;;;;;;;;IAqbaA,2BAA2B;eAA3BA;;IA0CAC,wBAAwB;eAAxBA;;IAkEAC,iBAAiB;eAAjBA;;IAOAC,mBAAmB;eAAnBA;;IAoDGC,SAAS;eAATA;;IAyCMC,UAAU;eAAVA;;IAmDAC,aAAa;eAAbA;;IAsBAC,eAAe;eAAfA;;IA2BNC,kBAAkB;eAAlBA;;IA8BAC,gBAAgB;eAAhBA;;;4BA9vBT;uBACqB;sBACF;uBAEN;0BACK;+DACN;sBACwB;6BAiBpC;0BAG4B;wBACP;wBAEgB;;;;;;AAE5C,MAAMC,eAAe;IAACC,mBAAW;IAAEC,sBAAc;CAAC;AAmYlD,6EAA6E;AAC7E,6EAA6E;AAC7E,oBAAoB;AACpB,MAAMC,iDACJC,IAAAA,mBAAM,EACJ,YACAC,IAAAA,iBAAI,IAAGC,SAAS;AAGb,MAAMhB,8BAA8BiB,IAAAA,mBAAM,EAAC;IAChDC,SAASC,IAAAA,sBAAS,EAACC,IAAAA,mBAAO,EAAC,eAAe;IAC1CC,YAAYF,IAAAA,sBAAS,EACnBF,IAAAA,mBAAM,EAAC;QACLK,QAAQC,IAAAA,qBAAQ,EAACC,IAAAA,gBAAI;QACrBC,MAAMN,IAAAA,sBAAS,EAACK,IAAAA,gBAAI,KAAI;QACxBE,MAAMP,IAAAA,sBAAS,EAACQ,IAAAA,oBAAO,KAAI;QAC3BC,UAAUT,IAAAA,sBAAS,EAACQ,IAAAA,oBAAO,KAAI;QAC/BE,MAAMV,IAAAA,sBAAS,EAACW,IAAAA,mBAAM,KAAI;QAC1BC,aAAaZ,IAAAA,sBAAS,EAACa,IAAAA,mBAAM,KAAI;QACjCC,MAAMd,IAAAA,sBAAS,EAACK,IAAAA,gBAAI,KAAIU,QAAQC,GAAG;QACnCC,YAAYjB,IAAAA,sBAAS,EAACQ,IAAAA,oBAAO,KAAI;QACjCU,KAAKlB,IAAA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,UAAU,CAACI,IAAI;IAEhC,MAAM8B,WAAWiC,aAAanE,UAAU,CAACC,MAAM,GAC3CqG,IAAAA,cAAQ,EAACnC,aAAanE,UAAU,CAACC,MAAM,IACvCkE,aAAanE,UAAU,CAACU,WAAW;IAEvC,OAAO;QACL,GAAG0F,aAAa;QAChBxE,OAAOuC,aAAanE,UAAU,CAACgB,GAAG;QAClCe,UAAUoC,aAAanE,UAAU,CAACK,IAAI;QACtCyB,WAAWqC,aAAanE,UAAU,CAACe,UAAU;QAC7CiB,QAAQ;YACNC;YACAC;YAEA,0EAA0E;YAC1E,0EAA0E;YAC1E,qEAAqE;YACrE,qEAAqE;YACrE,iBAAiB;YACjBE,UAAU+B,aAAanE,UAAU,CAACiB,aAAa;YAE/C,qEAAqE;YACrE,gBAAgB;YAChBkB,OAAO;QACT;QACA5B,UAAU;YACR,wEAAwE;YACxE,sCAAsC;YACtC0B,MAAMJ,IAAAA,aAAO,EAAChB,QAAQC,GAAG,IAAI;YAC7BuB,QAAQ8B,aAAanE,UAAU,CAACwB,aAAa;QAC/C;QACAc,QAAQ;YACNC,SAAS4B,aAAanE,UAAU,CAACyB,KAAK;YACtCjB,MAAM2D,aAAanE,UAAU,CAACQ,IAAI;YAClCI,MAAMuD,aAAanE,UAAU,CAACY,IAAI;QACpC;QACAkC,OAAO;YACLC,SAAS;YAET,0EAA0E;YAC1E,gDAAgD;YAChDC,UAAU;YACVE,QAAQ;QACV;QACAqD,QAAQrC,IAAAA,4BAAgB,EACtB;YACE,GAAGC,aAAanE,UAAU;YAC1B0B,mBAAmByC,aAAazC,iBAAiB;QACnD,GACA5C,qBACA;IAEJ;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/config.ts"],"sourcesContent":["import {\n createFromStruct,\n file,\n indent,\n isFile,\n literal,\n union,\n SnapsStructError,\n named,\n} from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\nimport { transform } from '@swc/core';\nimport type { BrowserifyObject } from 'browserify';\nimport { dim } from 'chalk';\nimport { readFile } from 'fs/promises';\nimport Module from 'module';\nimport { basename, dirname, resolve } from 'path';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n defaulted,\n define,\n func,\n number,\n object,\n optional,\n record,\n string,\n type,\n unknown,\n empty,\n} from 'superstruct';\nimport type { Configuration as WebpackConfiguration } from 'webpack';\n\nimport { TranspilationModes } from './builders';\nimport { ConfigError } from './errors';\nimport type { YargsArgs } from './types/yargs';\nimport { CONFIG_FILE, TS_CONFIG_FILE } from './utils';\n\nconst CONFIG_FILES = [CONFIG_FILE, TS_CONFIG_FILE];\n\n/**\n * The configuration for the Snaps CLI, stored as `snap.config.js` or\n * `snap.config.ts` in the root of the project.\n *\n * @deprecated The Browserify bundler is deprecated and will be removed in a\n * future release. Use the Webpack bundler instead.\n */\nexport type SnapBrowserifyConfig = {\n /**\n * The bundler to use to build the snap. For backwards compatibility, if not\n * specified, Browserify will be used. However, the Browserify bundler is\n * deprecated and will be removed in a future release, so it's recommended to\n * use the Webpack bundler instead.\n */\n bundler?: 'browserify';\n\n /**\n * The options for the Snaps CLI. These are merged with the options passed to\n * the CLI, with the CLI options taking precedence.\n *\n * @deprecated The Browserify bundler is deprecated and will be removed in a\n * future release. Use the Webpack bundler instead.\n */\n cliOptions?: {\n /**\n * The path to the snap bundle file.\n *\n * @default 'dist/bundle.js'\n */\n bundle?: string;\n\n /**\n * The directory to output the snap to. This is only used if `bundle` is\n * not specified.\n *\n * @default 'dist'\n */\n dist?: string;\n\n /**\n * Whether to attempt to evaluate the snap in SES. This can catch some errors\n * that would otherwise only be caught at runtime.\n *\n * @default true\n */\n eval?: boolean;\n\n /**\n * Whether to validate the snap manifest.\n *\n * @default true\n */\n manifest?: boolean;\n\n /**\n * The name of the bundle file. This is only used if `bundle` is not\n * specified.\n *\n * @default 'bundle.js'\n */\n outfileName?: string;\n\n /**\n * The port to run the server on.\n *\n * @default 8081\n */\n port?: number;\n\n /**\n * The root directory to serve the snap from.\n *\n * @default `process.cwd()`\n */\n root?: string;\n\n /**\n * Whether to generate source maps for the snap bundle.\n *\n * @default false\n */\n sourceMaps?: boolean;\n\n /**\n * The path to the snap entry point.\n *\n * @default 'src/index.js'\n */\n src?: string;\n\n /**\n * Whether to remove comments from the bundle.\n *\n * @default true\n */\n stripComments?: boolean;\n\n /**\n * Whether to suppress warnings.\n *\n * @default false\n */\n suppressWarnings?: boolean;\n\n /**\n * The transpilation mode to use, which determines which files are\n * transpiled.\n *\n * - `'localAndDeps'`: Transpile the snap entry point and all dependencies.\n * - `'localOnly'`: Transpile only the snap entry point.\n * - `'none'`: Don't transpile any files.\n *\n * @default 'localOnly'\n */\n transpilationMode?: 'localAndDeps' | 'localOnly' | 'none';\n\n /**\n * The dependencies to transpile when `transpilationMode` is set to\n * `'localAndDeps'`. If not specified, all dependencies will be transpiled.\n */\n depsToTranspile?: string[];\n\n /**\n * Whether to show original errors.\n *\n * @default true\n */\n verboseErrors?: boolean;\n\n /**\n * Whether to write the updated manifest to disk.\n *\n * @default true\n */\n writeManifest?: boolean;\n\n /**\n * Whether to serve the snap locally.\n *\n * @default true\n */\n serve?: boolean;\n };\n\n /**\n * A function that can be used to customize the Browserify instance used to\n * build the snap.\n *\n * @param bundler - The Browserify instance.\n * @deprecated The Browserify bundler is deprecated and will be removed in a\n * future release. Use the Webpack bundler instead.\n */\n bundlerCustomizer?: (bundler: BrowserifyObject) => void;\n};\n\n/**\n * The configuration for the Snaps CLI, stored as `snap.config.js` or\n * `snap.config.ts` in the root of the project.\n */\nexport type SnapWebpackConfig = {\n /**\n * The bundler to use to build the snap. For backwards compatibility, if not\n * specified, Browserify will be used. However, the Browserify bundler is\n * deprecated and will be removed in a future release, so it's recommended to\n * use the Webpack bundler instead.\n */\n bundler: 'webpack';\n\n /**\n * The path to the snap entry point. This should be a JavaScript or TypeScript\n * file.\n */\n input: string;\n\n /**\n * Whether to generate source maps for the snap. If `true`, source maps will\n * be generated as separate files. If `'inline'`, source maps will be\n * inlined in the generated JavaScript bundle.\n *\n * @default true\n */\n sourceMap?: boolean | 'inline';\n\n /**\n * Whether to attempt to evaluate the snap in SES. This can catch some errors\n * that would otherwise only be caught at runtime.\n *\n * @default true\n */\n evaluate?: boolean;\n\n output?: {\n /**\n * The path to the directory where the snap will be built. This directory\n * will be created if it doesn't exist.\n *\n * If the path is relative, it will be resolved relative to the current\n * working directory.\n *\n * @default 'dist'\n */\n path?: string;\n\n /**\n * The name of the JavaScript bundle file.\n *\n * @default 'bundle.js'\n */\n filename?: string;\n\n /**\n * Whether to clean the output directory before building the snap. If\n * `true`, the output directory will be deleted and recreated. Otherwise,\n * the output directory will be left as-is.\n *\n * @default false\n */\n clean?: boolean;\n\n /**\n * Whether to minimize the snap bundle. If `true`, the bundle will be\n * minified. Otherwise, the bundle will be left as-is.\n *\n * @default true\n */\n minimize?: boolean;\n };\n\n manifest?: {\n /**\n * The path to the snap manifest file. If the path is relative, it will be\n * resolved relative to the current working directory.\n *\n * @default 'snap.manifest.json'\n */\n path?: string;\n\n /**\n * Whether to automatically update the manifest. If `true`, the manifest\n * will be updated with the latest shasum of the snap bundle, and some\n * common fields will be updated if they are missing or incorrect. If\n * `false`, the manifest will be left as-is.\n *\n * @default true\n */\n update?: boolean;\n };\n\n server?: {\n /**\n * Whether to enable the local server. If `true`, the snap will be served\n * from a local server, when running the `watch` command. If `false`, the\n * snap will not be served.\n *\n * @default true\n */\n enabled?: boolean;\n\n /**\n * The root directory to serve the snap from. If the path is relative, it\n * will be resolved relative to the current working directory.\n *\n * @default `process.cwd()`\n */\n root?: string;\n\n /**\n * The port to run the server on.\n *\n * @default 8081\n */\n port?: number;\n };\n\n /**\n * The environment variables to set when building the snap. These will be\n * available in the snap as `process.env`. In addition to these environment\n * variables, the following environment variables will always be set:\n *\n * - `NODE_DEBUG`: `false`\n * - `NODE_ENV`: `'production'`\n * - `DEBUG`: `false`\n *\n * Any environment variables specified here will override these defaults. You\n * can also override any variables here by setting them in your shell when\n * running the CLI.\n */\n environment?: Record<string, unknown>;\n\n /**\n * Options that control the logging output of the CLI.\n */\n stats?: {\n /**\n * Whether to enable verbose logging.\n *\n * @default false\n */\n verbose?: boolean;\n\n /**\n * Whether to log warnings about unresolved built-in modules. If `false`,\n * warnings will not be logged.\n */\n builtIns?:\n | {\n /**\n * The built-in modules to ignore when resolving modules. If a module\n * is ignored, no warning will be logged if it is not resolved.\n */\n ignore?: string[];\n }\n | false;\n\n /**\n * Whether to log warnings about the use of the `Buffer` global. If `false`,\n * warnings will not be logged. If `true`, the CLI will warn if the `Buffer`\n * global is used, but not provided by Webpack's `DefinePlugin`.\n */\n buffer?: boolean;\n };\n\n /**\n * Whether to provide polyfills for node builtins. If `true`, all the available\n * polyfills will be provided. If `false` no polyfills will be provided. If a\n * configuration object is passed only the polyfills set to `true` will be provided.\n *\n * @default false\n * @example\n * ```ts\n * polyfills: true\n *\n * // or\n *\n * polyfills: {\n * assert: true,\n * buffer: true\n * }\n * ```\n */\n polyfills?:\n | boolean\n | {\n assert?: boolean;\n buffer?: boolean;\n console?: boolean;\n constants?: boolean;\n crypto?: boolean;\n domain?: boolean;\n events?: boolean;\n http?: boolean;\n https?: boolean;\n os?: boolean;\n path?: boolean;\n punycode?: boolean;\n process?: boolean;\n querystring?: boolean;\n stream?: boolean;\n /* eslint-disable @typescript-eslint/naming-convention */\n _stream_duplex?: boolean;\n _stream_passthrough?: boolean;\n _stream_readable?: boolean;\n _stream_transform?: boolean;\n _stream_writable?: boolean;\n string_decoder?: boolean;\n /* eslint-enable @typescript-eslint/naming-convention */\n sys?: boolean;\n timers?: boolean;\n tty?: boolean;\n url?: boolean;\n util?: boolean;\n vm?: boolean;\n zlib?: boolean;\n };\n\n /**\n * A function to customize the Webpack configuration used to build the snap.\n * This function will be called with the default Webpack configuration, and\n * should return the modified configuration. If not specified, the default\n * configuration will be used.\n *\n * It's recommended to use the `webpack-merge` package to merge the default\n * configuration with your customizations. The merge function is exported as\n * `merge` from the `@metamask/snaps-cli` package.\n *\n * @example\n * ```ts\n * import type { SnapsConfig } from '@metamask/snaps-cli';\n * import { merge } from '@metamask/snaps-cli';\n *\n * const config: SnapsConfig = {\n * bundler: 'webpack',\n * entry: 'src/index.ts',\n * customizeWebpackConfig: (config) => merge(config, {\n * module: {\n * rules: [\n * {\n * test: /\\.wasm$/,\n * type: 'assets/resource',\n * },\n * ],\n * },\n * }),\n * };\n *\n * export default config;\n * ```\n */\n customizeWebpackConfig?: (\n config: WebpackConfiguration,\n ) => WebpackConfiguration;\n\n /**\n * Experimental features that can be enabled. These features are not\n * guaranteed to be stable, and may be removed or changed in a future release.\n */\n experimental?: {\n /**\n * Whether to enable WebAssembly support. If `true`, the Webpack\n * configuration will be modified to support WebAssembly. If `false`, the\n * Webpack configuration will not be modified.\n *\n * @default false\n */\n wasm?: boolean;\n };\n};\n\n/**\n * The configuration for the Snaps CLI, stored as `snap.config.js` or\n * `snap.config.ts` in the root of the project.\n */\nexport type SnapConfig = SnapBrowserifyConfig | SnapWebpackConfig;\n\ntype SnapsBrowserifyBundlerCustomizerFunction = (\n bundler: BrowserifyObject,\n) => void;\n\n// This struct is essentially the same as the `func` struct, but it's defined\n// separately so that we include the function type in the inferred TypeScript\n// type definitions.\nconst SnapsBrowserifyBundlerCustomizerFunctionStruct =\n define<SnapsBrowserifyBundlerCustomizerFunction>(\n 'function',\n func().validator,\n );\n\nexport const SnapsBrowserifyConfigStruct = object({\n bundler: defaulted(literal('browserify'), 'browserify'),\n cliOptions: defaulted(\n object({\n bundle: optional(file()),\n dist: defaulted(file(), 'dist'),\n eval: defaulted(boolean(), true),\n manifest: defaulted(boolean(), true),\n port: defaulted(number(), 8081),\n outfileName: defaulted(string(), 'bundle.js'),\n root: defaulted(file(), process.cwd()),\n sourceMaps: defaulted(boolean(), false),\n src: defaulted(file(), 'src/index.js'),\n stripComments: defaulted(boolean(), true),\n suppressWarnings: defaulted(boolean(), false),\n transpilationMode: defaulted(\n union([literal('localAndDeps'), literal('localOnly'), literal('none')]),\n 'localOnly',\n ),\n depsToTranspile: defaulted(array(string()), []),\n verboseErrors: defaulted(boolean(), true),\n writeManifest: defaulted(boolean(), true),\n serve: defaulted(boolean(), true),\n }),\n {},\n ),\n bundlerCustomizer: optional(SnapsBrowserifyBundlerCustomizerFunctionStruct),\n});\n\ntype SnapsWebpackCustomizeWebpackConfigFunction = (\n config: WebpackConfiguration,\n) => WebpackConfiguration;\n\n// This struct is essentially the same as the `func` struct, but it's defined\n// separately so that we include the function type in the inferred TypeScript\n// type definitions.\nconst SnapsWebpackCustomizeWebpackConfigFunctionStruct =\n define<SnapsWebpackCustomizeWebpackConfigFunction>(\n 'function',\n func().validator,\n );\n\nexport const SnapsWebpackConfigStruct = object({\n bundler: literal('webpack'),\n input: defaulted(file(), resolve(process.cwd(), 'src/index.js')),\n sourceMap: defaulted(union([boolean(), literal('inline')]), true),\n evaluate: defaulted(boolean(), true),\n\n output: defaulted(\n object({\n path: defaulted(file(), resolve(process.cwd(), 'dist')),\n filename: defaulted(string(), 'bundle.js'),\n clean: defaulted(boolean(), false),\n minimize: defaulted(boolean(), true),\n }),\n {},\n ),\n\n manifest: defaulted(\n object({\n path: defaulted(file(), resolve(process.cwd(), 'snap.manifest.json')),\n update: defaulted(boolean(), true),\n }),\n {},\n ),\n\n server: defaulted(\n object({\n enabled: defaulted(boolean(), true),\n root: defaulted(file(), process.cwd()),\n port: defaulted(number(), 8081),\n }),\n {},\n ),\n\n environment: defaulted(record(string(), unknown()), {\n NODE_DEBUG: false,\n NODE_ENV: 'production',\n DEBUG: false,\n }),\n\n stats: defaulted(\n object({\n verbose: defaulted(boolean(), false),\n builtIns: defaulted(\n union([\n object({ ignore: defaulted(array(string()), []) }),\n literal(false),\n ]),\n {},\n ),\n buffer: defaulted(boolean(), true),\n }),\n {},\n ),\n\n polyfills: defaulted(\n union([\n boolean(),\n object({\n assert: defaulted(boolean(), false),\n buffer: defaulted(boolean(), false),\n console: defaulted(boolean(), false),\n constants: defaulted(boolean(), false),\n crypto: defaulted(boolean(), false),\n domain: defaulted(boolean(), false),\n events: defaulted(boolean(), false),\n http: defaulted(boolean(), false),\n https: defaulted(boolean(), false),\n os: defaulted(boolean(), false),\n path: defaulted(boolean(), false),\n punycode: defaulted(boolean(), false),\n process: defaulted(boolean(), false),\n querystring: defaulted(boolean(), false),\n stream: defaulted(boolean(), false),\n /* eslint-disable @typescript-eslint/naming-convention */\n _stream_duplex: defaulted(boolean(), false),\n _stream_passthrough: defaulted(boolean(), false),\n _stream_readable: defaulted(boolean(), false),\n _stream_transform: defaulted(boolean(), false),\n _stream_writable: defaulted(boolean(), false),\n string_decoder: defaulted(boolean(), false),\n /* eslint-enable @typescript-eslint/naming-convention */\n sys: defaulted(boolean(), false),\n timers: defaulted(boolean(), false),\n tty: defaulted(boolean(), false),\n url: defaulted(boolean(), false),\n util: defaulted(boolean(), false),\n vm: defaulted(boolean(), false),\n zlib: defaulted(boolean(), false),\n }),\n ]),\n false,\n ),\n\n customizeWebpackConfig: optional(\n SnapsWebpackCustomizeWebpackConfigFunctionStruct,\n ),\n\n experimental: defaulted(\n object({\n wasm: defaulted(boolean(), false),\n }),\n {},\n ),\n});\n\nexport const SnapsConfigStruct = type({\n bundler: defaulted(\n union([literal('browserify'), literal('webpack')]),\n 'browserify',\n ),\n});\n\nexport const LegacyOptionsStruct = union([\n named(\n 'object with `transpilationMode` set to `localAndDeps` and `depsToTranspile` set to an array of strings',\n type({\n depsToTranspile: array(string()),\n transpilationMode: literal(TranspilationModes.LocalAndDeps),\n writeManifest: boolean(),\n bundlerCustomizer: optional(\n SnapsBrowserifyBundlerCustomizerFunctionStruct,\n ),\n }),\n ),\n named(\n 'object without `depsToTranspile`',\n type({\n depsToTranspile: named('empty array', empty(array())),\n transpilationMode: union([\n literal(TranspilationModes.LocalOnly),\n literal(TranspilationModes.None),\n ]),\n writeManifest: boolean(),\n bundlerCustomizer: optional(\n SnapsBrowserifyBundlerCustomizerFunctionStruct,\n ),\n }),\n ),\n]);\n\nexport type LegacyOptions = Infer<typeof LegacyOptionsStruct>;\n\nexport type ProcessedBrowserifyConfig = Infer<\n typeof SnapsBrowserifyConfigStruct\n>;\n\nexport type ProcessedWebpackConfig = Infer<typeof SnapsWebpackConfigStruct> & {\n /**\n * The legacy Browserify config, if the bundler is Browserify. This is used\n * to support the legacy config format.\n */\n legacy?: LegacyOptions;\n};\n\nexport type ProcessedConfig = ProcessedWebpackConfig;\n\n/**\n * Get a validated snap config. This validates the config and adds default\n * values for any missing properties.\n *\n * @param config - The config to validate.\n * @param argv - The CLI arguments.\n * @returns The validated config.\n */\nexport function getConfig(config: unknown, argv: YargsArgs): ProcessedConfig {\n const prefix = 'The snap config file is invalid';\n const suffix = dim(\n // TODO: Link to `docs.metamask.io` once the docs are published.\n 'Refer to the documentation for more information: https://github.com/MetaMask/snaps/tree/main/packages/snaps-cli/',\n );\n\n const { bundler } = createFromStruct(\n config,\n SnapsConfigStruct,\n prefix,\n suffix,\n );\n\n if (bundler === 'browserify') {\n const legacyConfig = createFromStruct(\n config,\n SnapsBrowserifyConfigStruct,\n prefix,\n suffix,\n );\n\n return getWebpackConfig(mergeLegacyOptions(argv, legacyConfig));\n }\n\n return createFromStruct(config, SnapsWebpackConfigStruct, prefix, suffix);\n}\n\n/**\n * Load a snap config from a file. This supports both JavaScript and TypeScript\n * config files, in the CommonJS module format and the ES module format.\n *\n * This assumes that the config file exports a default object, either through\n * `module.exports` or `export default`.\n *\n * @param path - The full path to the config file.\n * @param argv - The CLI arguments.\n * @returns The validated config.\n * @throws If the config file is invalid, or if the config file does not have a\n * default export.\n */\nexport async function loadConfig(path: string, argv: YargsArgs) {\n try {\n const contents = await readFile(path, 'utf8');\n const source = await transform(contents, {\n swcrc: false,\n jsc: {\n parser: {\n syntax: 'typescript',\n },\n },\n module: {\n type: 'commonjs',\n },\n });\n\n const config = new Module(path);\n\n // @ts-expect-error - This function is not typed.\n config.paths = Module._nodeModulePaths(dirname(path));\n\n // @ts-expect-error - This function is not typed.\n config._compile(source.code, path);\n\n if (!hasProperty(config.exports, 'default')) {\n return getConfig(config.exports, argv);\n }\n\n return getConfig(config.exports.default, argv);\n } catch (error) {\n if (error instanceof SnapsStructError) {\n throw new ConfigError(error.message);\n }\n\n throw new ConfigError(\n `Unable to load snap config file at \"${path}\".\\n\\n${indent(\n error.message,\n )}`,\n );\n }\n}\n\n/**\n * Resolve a snap config. This function will look for a `snap.config.js` or\n * `snap.config.ts` file in the current or specified directory.\n *\n * @param path - The path to resolve the snap config from. Defaults to the\n * current working directory.\n * @param argv - The CLI arguments.\n * @returns The resolved and validated snap config.\n * @throws If a snap config could not be found.\n */\nexport async function resolveConfig(path: string, argv: YargsArgs) {\n for (const configFile of CONFIG_FILES) {\n const filePath = resolve(path, configFile);\n if (await isFile(filePath)) {\n return await loadConfig(filePath, argv);\n }\n }\n\n throw new ConfigError(\n `Could not find a \"snap.config.js\" or \"snap.config.ts\" file in the current or specified directory (\"${path}\").`,\n );\n}\n\n/**\n * Get a snap config from the CLI arguments. This will either load the config\n * from the specified config file, or resolve the config from the current\n * working directory.\n *\n * @param argv - The CLI arguments.\n * @param cwd - The current working directory. Defaults to `process.cwd()`.\n * @returns The resolved and validated snap config.\n */\nexport async function getConfigByArgv(\n argv: YargsArgs,\n cwd: string = process.cwd(),\n) {\n if (argv.config) {\n if (!(await isFile(argv.config))) {\n throw new ConfigError(\n `Could not find a config file at \"${argv.config}\". Make sure that the path is correct.`,\n );\n }\n\n return await loadConfig(argv.config, argv);\n }\n\n return await resolveConfig(cwd, argv);\n}\n\n/**\n * Merge legacy CLI options into the config. This is used to support the legacy\n * config format, where options can be specified both in the config file and\n * through CLI flags.\n *\n * @param argv - The CLI arguments.\n * @param config - The config to merge the CLI options into.\n * @returns The config with the CLI options merged in.\n * @deprecated This function is only used to support the legacy config format.\n */\nexport function mergeLegacyOptions(\n argv: YargsArgs,\n config: ProcessedBrowserifyConfig,\n) {\n const cliOptions = Object.keys(config.cliOptions).reduce<\n ProcessedBrowserifyConfig['cliOptions']\n >((accumulator, key) => {\n if (argv[key] !== undefined) {\n return {\n ...accumulator,\n [key]: argv[key],\n };\n }\n\n return accumulator;\n }, config.cliOptions);\n\n return {\n ...config,\n cliOptions,\n };\n}\n\n/**\n * Get a Webpack config from a legacy browserify config. This is used to\n * support the legacy config format, and convert it to the new format.\n *\n * @param legacyConfig - The legacy browserify config.\n * @returns The Webpack config.\n */\nexport function getWebpackConfig(\n legacyConfig: ProcessedBrowserifyConfig,\n): ProcessedWebpackConfig {\n const defaultConfig = create(\n { bundler: 'webpack' },\n SnapsWebpackConfigStruct,\n );\n\n // The legacy config has two options for specifying the output path and\n // filename: `bundle`, and `dist` + `outfileName`. If `bundle` is specified,\n // we use that as the output path and filename. Otherwise, we use `dist` and\n // `outfileName`.\n const path = legacyConfig.cliOptions.bundle\n ? dirname(legacyConfig.cliOptions.bundle)\n : legacyConfig.cliOptions.dist;\n\n const filename = legacyConfig.cliOptions.bundle\n ? basename(legacyConfig.cliOptions.bundle)\n : legacyConfig.cliOptions.outfileName;\n\n return {\n ...defaultConfig,\n input: legacyConfig.cliOptions.src,\n evaluate: legacyConfig.cliOptions.eval,\n sourceMap: legacyConfig.cliOptions.sourceMaps,\n output: {\n path,\n filename,\n\n // The legacy config has an option to remove comments from the bundle, but\n // the terser plugin does this by default, so we only enable the terser if\n // the legacy config has `stripComments` set to `true`. This is not a\n // perfect solution, but it's the best we can do without breaking the\n // legacy config.\n minimize: legacyConfig.cliOptions.stripComments,\n\n // The legacy config does not have a `clean` option, so we default to\n // `false` here.\n clean: false,\n },\n manifest: {\n // The legacy config does not have a `manifest` option, so we default to\n // `process.cwd()/snap.manifest.json`.\n path: resolve(process.cwd(), 'snap.manifest.json'),\n update: legacyConfig.cliOptions.writeManifest,\n },\n server: {\n enabled: legacyConfig.cliOptions.serve,\n port: legacyConfig.cliOptions.port,\n root: legacyConfig.cliOptions.root,\n },\n stats: {\n verbose: false,\n\n // These plugins are designed to be used with the modern config format, so\n // we disable them for the legacy config format.\n builtIns: false,\n buffer: false,\n },\n legacy: createFromStruct(\n {\n ...legacyConfig.cliOptions,\n bundlerCustomizer: legacyConfig.bundlerCustomizer,\n },\n LegacyOptionsStruct,\n 'Invalid Browserify CLI options',\n ),\n };\n}\n"],"names":["SnapsBrowserifyConfigStruct","SnapsWebpackConfigStruct","SnapsConfigStruct","LegacyOptionsStruct","getConfig","loadConfig","resolveConfig","getConfigByArgv","mergeLegacyOptions","getWebpackConfig","CONFIG_FILES","CONFIG_FILE","TS_CONFIG_FILE","SnapsBrowserifyBundlerCustomizerFunctionStruct","define","func","validator","object","bundler","defaulted","literal","cliOptions","bundle","optional","file","dist","eval","boolean","manifest","port","number","outfileName","string","root","process","cwd","sourceMaps","src","stripComments","suppressWarnings","transpilationMode","union","depsToTranspile","array","verboseErrors","writeManifest","serve","bundlerCustomizer","SnapsWebpackCustomizeWebpackConfigFunctionStruct","input","resolve","sourceMap","evaluate","output","path","filename","clean","minimize","update","server","enabled","environment","record","unknown","NODE_DEBUG","NODE_ENV","DEBUG","stats","verbose","builtIns","ignore","buffer","polyfills","assert","console","constants","crypto","domain","events","http","https","os","punycode","querystring","stream","_stream_duplex","_stream_passthrough","_stream_readable","_stream_transform","_stream_writable","string_decoder","sys","timers","tty","url","util","vm","zlib","customizeWebpackConfig","experimental","wasm","type","named","TranspilationModes","LocalAndDeps","empty","LocalOnly","None","config","argv","prefix","suffix","dim","createFromStruct","legacyConfig","contents","readFile","source","transform","swcrc","jsc","parser","syntax","module","Module","paths","_nodeModulePaths","dirname","_compile","code","hasProperty","exports","default","error","SnapsStructError","ConfigError","message","indent","configFile","filePath","isFile","Object","keys","reduce","accumulator","key","undefined","defaultConfig","create","basename","legacy"],"mappings":";;;;;;;;;;;IA0eaA,2BAA2B;eAA3BA;;IA0CAC,wBAAwB;eAAxBA;;IAyGAC,iBAAiB;eAAjBA;;IAOAC,mBAAmB;eAAnBA;;IAoDGC,SAAS;eAATA;;IAyCMC,UAAU;eAAVA;;IAmDAC,aAAa;eAA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,gDAAgD;YAChDC,UAAU;YACVE,QAAQ;QACV;QACA+E,QAAQrC,IAAAA,4BAAgB,EACtB;YACE,GAAGC,aAAa7F,UAAU;YAC1B0B,mBAAmBmE,aAAanE,iBAAiB;QACnD,GACA5C,qBACA;IAEJ;AACF"}
|
|
@@ -9,7 +9,6 @@ Object.defineProperty(exports, "getDefaultConfiguration", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
const _snapswebpackplugin = /*#__PURE__*/ _interop_require_default(require("@metamask/snaps-webpack-plugin"));
|
|
12
|
-
const _module = require("module");
|
|
13
12
|
const _path = require("path");
|
|
14
13
|
const _terserwebpackplugin = /*#__PURE__*/ _interop_require_default(require("terser-webpack-plugin"));
|
|
15
14
|
const _webpack = require("webpack");
|
|
@@ -139,10 +138,7 @@ async function getDefaultConfiguration(config, options = {
|
|
|
139
138
|
* The fallback options. This tells Webpack how to handle imports that
|
|
140
139
|
* aren't resolved. By default, we set Node.js built-ins to `false`, so
|
|
141
140
|
* that they are ignored.
|
|
142
|
-
*/ fallback:
|
|
143
|
-
name,
|
|
144
|
-
false
|
|
145
|
-
])),
|
|
141
|
+
*/ fallback: (0, _utils.getFallbacks)(config.polyfills),
|
|
146
142
|
/**
|
|
147
143
|
* The plugins to use. We use the {@link SnapsBuiltInResolver} to show
|
|
148
144
|
* warnings about using Node.js built-ins, when no fallback is specified.
|
|
@@ -201,7 +197,16 @@ async function getDefaultConfiguration(config, options = {
|
|
|
201
197
|
files: [
|
|
202
198
|
config.manifest.path
|
|
203
199
|
]
|
|
204
|
-
}, options.spinner)
|
|
200
|
+
}, options.spinner),
|
|
201
|
+
/**
|
|
202
|
+
* The `ProviderPlugin` is a Webpack plugin that automatically load
|
|
203
|
+
* modules instead of having to import or require them everywhere.
|
|
204
|
+
*/ (config.polyfills === true || config.polyfills !== false && config.polyfills.buffer) && new _webpack.ProvidePlugin({
|
|
205
|
+
Buffer: [
|
|
206
|
+
'buffer',
|
|
207
|
+
'Buffer'
|
|
208
|
+
]
|
|
209
|
+
})
|
|
205
210
|
].filter(Boolean),
|
|
206
211
|
/**
|
|
207
212
|
* The optimization configuration. This tells Webpack how to optimize the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/webpack/config.ts"],"sourcesContent":["import SnapsWebpackPlugin from '@metamask/snaps-webpack-plugin';\nimport { builtinModules } from 'module';\nimport type { Ora } from 'ora';\nimport { resolve } from 'path';\nimport TerserPlugin from 'terser-webpack-plugin';\nimport type { Configuration } from 'webpack';\nimport { EnvironmentPlugin, ProgressPlugin } from 'webpack';\n\nimport type { ProcessedWebpackConfig } from '../config';\nimport {\n SnapsBuiltInResolver,\n SnapsBundleWarningsPlugin,\n SnapsStatsPlugin,\n SnapsWatchPlugin,\n} from './plugins';\nimport {\n BROWSERSLIST_FILE,\n getDefaultLoader,\n getDevTool,\n getProgressHandler,\n} from './utils';\n\nexport type WebpackOptions = {\n /**\n * Whether to watch for changes.\n */\n watch?: boolean;\n\n /**\n * Whether to evaluate the bundle. If this is set, it will override the\n * `evaluate` option in the config object.\n */\n evaluate?: boolean;\n\n /**\n * The spinner to use for logging.\n */\n spinner?: Ora;\n};\n\n/**\n * Get the default Webpack configuration. This is the configuration that will\n * be used if the user doesn't provide a custom Webpack configuration. The\n * configuration is based on the snap config.\n *\n * The default configuration includes:\n *\n * - `SWC` to transpile TypeScript and JavaScript files.\n * - `TerserPlugin` to minify the bundle.\n * - `SnapsWebpackPlugin` to validate the bundle and update the manifest.\n *\n * It can be customized through the `customizeWebpackConfig` function in the\n * snap config, but in most cases, you shouldn't need to do that.\n *\n * @param config - The processed snap Webpack config.\n * @param options - The Webpack options.\n * @returns The default Webpack configuration.\n */\nexport async function getDefaultConfiguration(\n config: ProcessedWebpackConfig,\n options: WebpackOptions = {\n evaluate: config.evaluate,\n },\n): Promise<Configuration> {\n const spinnerText = options.spinner?.text;\n const builtInResolver =\n config.stats.builtIns &&\n new SnapsBuiltInResolver(config.stats.builtIns, options.spinner);\n\n return {\n /**\n * The target is set to `browserslist` so that Webpack will compile the\n * bundle to support the browsers specified in the `.browserslistrc` file.\n * This Browserslist file contains the browsers that are supported by\n * MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/target/\n */\n target: `browserslist:${BROWSERSLIST_FILE}`,\n\n /**\n * The mode is set to `production` by default, so that Webpack will minify\n * and optimize the bundle.\n *\n * @see https://webpack.js.org/configuration/mode/\n */\n mode: 'production',\n\n /**\n * The entry point is set to the `input` value from the config object.\n *\n * @see https://webpack.js.org/configuration/entry-context/\n */\n entry: config.input,\n\n /**\n * The devtool option controls how source maps are generated. We set it to\n * the `sourceMap` value from the config object.\n *\n * @see https://webpack.js.org/configuration/devtool/\n */\n devtool: getDevTool(config.sourceMap),\n\n /**\n * The stats option controls how much information is printed to the console\n * when Webpack is running. We set it to `none` so that we can control the\n * output ourselves.\n *\n * @see https://webpack.js.org/configuration/stats/\n */\n stats: 'none',\n\n /**\n * The output options.\n *\n * @see https://webpack.js.org/configuration/output/\n */\n output: {\n /**\n * This indicates whether Webpack should clear the output directory\n * before building. We set it to the `clean` value from the config\n * object.\n *\n * @see https://webpack.js.org/configuration/output/#outputclean\n */\n clean: config.output.clean,\n\n /**\n * The filename of the bundle. We set it to the `filename` value from\n * the config object.\n *\n * @see https://webpack.js.org/configuration/output/#outputfilename\n */\n filename: config.output.filename,\n\n /**\n * The path to the output directory. We set it to the `path` value from\n * the config object.\n *\n * @see https://webpack.js.org/configuration/output/#outputpath\n */\n path: config.output.path,\n\n /**\n * The public path of the bundle. We set it to `/` by default, so that\n * the bundle can be loaded from the root of the server.\n *\n * @see https://webpack.js.org/configuration/output/#outputpublicpath\n */\n publicPath: '/',\n\n /**\n * The library configuration. This tells Webpack how to export the\n * bundle.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrary\n */\n library: {\n /**\n * This tells Webpack to export the bundle as a CommonJS module. This\n * is necessary for MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrarytarget\n */\n type: 'commonjs',\n },\n },\n\n /**\n * The module configuration. This is where we tell Webpack how to handle\n * different types of files.\n *\n * @see https://webpack.js.org/configuration/module/\n */\n module: {\n rules: [\n {\n test: /\\.[tj]sx?$/u,\n exclude: /node_modules/u,\n use: await getDefaultLoader(config),\n },\n\n config.experimental.wasm && {\n test: /\\.wasm$/u,\n use: {\n loader: resolve(__dirname, 'loaders', 'wasm'),\n },\n },\n ],\n },\n\n /**\n * The resolve configuration. This tells Webpack how to resolve imports.\n * We set it to resolve `.js` and `.ts` files.\n *\n * @see https://webpack.js.org/configuration/resolve/\n */\n resolve: {\n /**\n * The extensions to resolve. We set it to resolve `.js` and `.ts`\n * files.\n */\n extensions: ['.js', '.ts'],\n\n /**\n * The fallback options. This tells Webpack how to handle imports that\n * aren't resolved. By default, we set Node.js built-ins to `false`, so\n * that they are ignored.\n */\n fallback: Object.fromEntries(builtinModules.map((name) => [name, false])),\n\n /**\n * The plugins to use. We use the {@link SnapsBuiltInResolver} to show\n * warnings about using Node.js built-ins, when no fallback is specified.\n */\n plugins: [builtInResolver],\n },\n\n /**\n * The plugins to use.\n *\n * @see https://webpack.js.org/configuration/plugins/\n */\n plugins: [\n /**\n * The `SnapsWebpackPlugin` is a Webpack plugin that checks and updates\n * the manifest file, and evaluates the bundle in SES. While not strictly\n * required, it's highly recommended to use this plugin.\n */\n new SnapsWebpackPlugin({\n manifestPath: config.manifest.path,\n writeManifest: config.manifest.update,\n eval: !options.watch && options.evaluate,\n }),\n\n /**\n * The `SnapsStatsPlugin` is a Webpack plugin that handles the stats\n * output. It's used to show the stats in the terminal, in a format that\n * is easy to read.\n */\n new SnapsStatsPlugin({ verbose: config.stats.verbose }, options.spinner),\n\n /**\n * The `EnvironmentPlugin` is a Webpack plugin that adds environment\n * variables to the bundle. We use it to add the `NODE_ENV` and `DEBUG`\n * environment variables.\n */\n new EnvironmentPlugin(config.environment),\n\n /**\n * The `ProgressPlugin` is a Webpack plugin that logs the progress of\n * the build. We set it to log the progress to the spinner.\n */\n new ProgressPlugin({\n handler: getProgressHandler(options.spinner, spinnerText),\n }),\n\n /**\n * The `SnapsBundleWarningPlugin` is a Webpack plugin that shows a\n * warning when the bundle is potentially incompatible with MetaMask\n * Snaps.\n */\n new SnapsBundleWarningsPlugin(\n {\n builtInResolver,\n builtIns: Boolean(config.stats.builtIns),\n buffer: config.stats.buffer,\n },\n options.spinner,\n ),\n\n /**\n * The `WatchPlugin` is a Webpack plugin that adds extra files to watch\n * for changes. This is useful for rebuilding the bundle when the\n * manifest file changes.\n */\n options.watch &&\n new SnapsWatchPlugin(\n {\n bundle: resolve(config.output.path, config.output.filename),\n evaluate: options.evaluate,\n files: [config.manifest.path],\n },\n options.spinner,\n ),\n ].filter(Boolean),\n\n /**\n * The optimization configuration. This tells Webpack how to optimize the\n * bundle. Most of the time, you won't need to change this, as the default\n * options set by the `mode` option are sufficient.\n */\n optimization: {\n minimize: config.output.minimize,\n\n /**\n * The minimizer to use. We set it to use the `TerserPlugin`.\n */\n minimizer: [\n new TerserPlugin({\n parallel: true,\n }),\n ],\n },\n\n /**\n * The infrastructure logging configuration. This tells Webpack how to\n * log messages.\n *\n * @see https://webpack.js.org/configuration/infrastructure-logging\n */\n infrastructureLogging: {\n /**\n * The level of logging to use. We set it to `none`, so that we can\n * control the output ourselves.\n */\n level: 'none',\n },\n };\n}\n"],"names":["getDefaultConfiguration","config","options","evaluate","spinnerText","spinner","text","builtInResolver","stats","builtIns","SnapsBuiltInResolver","target","BROWSERSLIST_FILE","mode","entry","input","devtool","getDevTool","sourceMap","output","clean","filename","path","publicPath","library","type","module","rules","test","exclude","use","getDefaultLoader","experimental","wasm","loader","resolve","__dirname","extensions","fallback","Object","fromEntries","builtinModules","map","name","plugins","SnapsWebpackPlugin","manifestPath","manifest","writeManifest","update","eval","watch","SnapsStatsPlugin","verbose","EnvironmentPlugin","environment","ProgressPlugin","handler","getProgressHandler","SnapsBundleWarningsPlugin","Boolean","buffer","SnapsWatchPlugin","bundle","files","filter","optimization","minimize","minimizer","TerserPlugin","parallel","infrastructureLogging","level"],"mappings":";;;;+BA0DsBA;;;eAAAA;;;2EA1DS;wBACA;sBAEP;4EACC;yBAEyB;yBAQ3C;uBAMA;;;;;;AAsCA,eAAeA,wBACpBC,MAA8B,EAC9BC,UAA0B;IACxBC,UAAUF,OAAOE,QAAQ;AAC3B,CAAC;IAED,MAAMC,cAAcF,QAAQG,OAAO,EAAEC;IACrC,MAAMC,kBACJN,OAAOO,KAAK,CAACC,QAAQ,IACrB,IAAIC,6BAAoB,CAACT,OAAOO,KAAK,CAACC,QAAQ,EAAEP,QAAQG,OAAO;IAEjE,OAAO;QACL;;;;;;;KAOC,GACDM,QAAQ,CAAC,aAAa,EAAEC,wBAAiB,CAAC,CAAC;QAE3C;;;;;KAKC,GACDC,MAAM;QAEN;;;;KAIC,GACDC,OAAOb,OAAOc,KAAK;QAEnB;;;;;KAKC,GACDC,SAASC,IAAAA,iBAAU,EAAChB,OAAOiB,SAAS;QAEpC;;;;;;KAMC,GACDV,OAAO;QAEP;;;;KAIC,GACDW,QAAQ;YACN;;;;;;OAMC,GACDC,OAAOnB,OAAOkB,MAAM,CAACC,KAAK;YAE1B;;;;;OAKC,GACDC,UAAUpB,OAAOkB,MAAM,CAACE,QAAQ;YAEhC;;;;;OAKC,GACDC,MAAMrB,OAAOkB,MAAM,CAACG,IAAI;YAExB;;;;;OAKC,GACDC,YAAY;YAEZ;;;;;OAKC,GACDC,SAAS;gBACP;;;;;SAKC,GACDC,MAAM;YACR;QACF;QAEA;;;;;KAKC,GACDC,QAAQ;YACNC,OAAO;gBACL;oBACEC,MAAM;oBACNC,SAAS;oBACTC,KAAK,MAAMC,IAAAA,uBAAgB,EAAC9B;gBAC9B;gBAEAA,OAAO+B,YAAY,CAACC,IAAI,IAAI;oBAC1BL,MAAM;oBACNE,KAAK;wBACHI,QAAQC,IAAAA,aAAO,EAACC,WAAW,WAAW;oBACxC;gBACF;aACD;QACH;QAEA;;;;;KAKC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,cAAc;YACZC,UAAUlE,OAAOkB,MAAM,CAACgD,QAAQ;YAEhC;;OAEC,GACDC,WAAW;gBACT,IAAIC,4BAAY,CAAC;oBACfC,UAAU;gBACZ;aACD;QACH;QAEA;;;;;KAKC,GACDC,uBAAuB;YACrB;;;OAGC,GACDC,OAAO;QACT;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/webpack/config.ts"],"sourcesContent":["import SnapsWebpackPlugin from '@metamask/snaps-webpack-plugin';\nimport type { Ora } from 'ora';\nimport { resolve } from 'path';\nimport TerserPlugin from 'terser-webpack-plugin';\nimport type { Configuration } from 'webpack';\nimport { EnvironmentPlugin, ProgressPlugin, ProvidePlugin } from 'webpack';\n\nimport type { ProcessedWebpackConfig } from '../config';\nimport {\n SnapsBuiltInResolver,\n SnapsBundleWarningsPlugin,\n SnapsStatsPlugin,\n SnapsWatchPlugin,\n} from './plugins';\nimport {\n BROWSERSLIST_FILE,\n getDefaultLoader,\n getDevTool,\n getFallbacks,\n getProgressHandler,\n} from './utils';\n\nexport type WebpackOptions = {\n /**\n * Whether to watch for changes.\n */\n watch?: boolean;\n\n /**\n * Whether to evaluate the bundle. If this is set, it will override the\n * `evaluate` option in the config object.\n */\n evaluate?: boolean;\n\n /**\n * The spinner to use for logging.\n */\n spinner?: Ora;\n};\n\n/**\n * Get the default Webpack configuration. This is the configuration that will\n * be used if the user doesn't provide a custom Webpack configuration. The\n * configuration is based on the snap config.\n *\n * The default configuration includes:\n *\n * - `SWC` to transpile TypeScript and JavaScript files.\n * - `TerserPlugin` to minify the bundle.\n * - `SnapsWebpackPlugin` to validate the bundle and update the manifest.\n *\n * It can be customized through the `customizeWebpackConfig` function in the\n * snap config, but in most cases, you shouldn't need to do that.\n *\n * @param config - The processed snap Webpack config.\n * @param options - The Webpack options.\n * @returns The default Webpack configuration.\n */\nexport async function getDefaultConfiguration(\n config: ProcessedWebpackConfig,\n options: WebpackOptions = {\n evaluate: config.evaluate,\n },\n): Promise<Configuration> {\n const spinnerText = options.spinner?.text;\n const builtInResolver =\n config.stats.builtIns &&\n new SnapsBuiltInResolver(config.stats.builtIns, options.spinner);\n\n return {\n /**\n * The target is set to `browserslist` so that Webpack will compile the\n * bundle to support the browsers specified in the `.browserslistrc` file.\n * This Browserslist file contains the browsers that are supported by\n * MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/target/\n */\n target: `browserslist:${BROWSERSLIST_FILE}`,\n\n /**\n * The mode is set to `production` by default, so that Webpack will minify\n * and optimize the bundle.\n *\n * @see https://webpack.js.org/configuration/mode/\n */\n mode: 'production',\n\n /**\n * The entry point is set to the `input` value from the config object.\n *\n * @see https://webpack.js.org/configuration/entry-context/\n */\n entry: config.input,\n\n /**\n * The devtool option controls how source maps are generated. We set it to\n * the `sourceMap` value from the config object.\n *\n * @see https://webpack.js.org/configuration/devtool/\n */\n devtool: getDevTool(config.sourceMap),\n\n /**\n * The stats option controls how much information is printed to the console\n * when Webpack is running. We set it to `none` so that we can control the\n * output ourselves.\n *\n * @see https://webpack.js.org/configuration/stats/\n */\n stats: 'none',\n\n /**\n * The output options.\n *\n * @see https://webpack.js.org/configuration/output/\n */\n output: {\n /**\n * This indicates whether Webpack should clear the output directory\n * before building. We set it to the `clean` value from the config\n * object.\n *\n * @see https://webpack.js.org/configuration/output/#outputclean\n */\n clean: config.output.clean,\n\n /**\n * The filename of the bundle. We set it to the `filename` value from\n * the config object.\n *\n * @see https://webpack.js.org/configuration/output/#outputfilename\n */\n filename: config.output.filename,\n\n /**\n * The path to the output directory. We set it to the `path` value from\n * the config object.\n *\n * @see https://webpack.js.org/configuration/output/#outputpath\n */\n path: config.output.path,\n\n /**\n * The public path of the bundle. We set it to `/` by default, so that\n * the bundle can be loaded from the root of the server.\n *\n * @see https://webpack.js.org/configuration/output/#outputpublicpath\n */\n publicPath: '/',\n\n /**\n * The library configuration. This tells Webpack how to export the\n * bundle.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrary\n */\n library: {\n /**\n * This tells Webpack to export the bundle as a CommonJS module. This\n * is necessary for MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrarytarget\n */\n type: 'commonjs',\n },\n },\n\n /**\n * The module configuration. This is where we tell Webpack how to handle\n * different types of files.\n *\n * @see https://webpack.js.org/configuration/module/\n */\n module: {\n rules: [\n {\n test: /\\.[tj]sx?$/u,\n exclude: /node_modules/u,\n use: await getDefaultLoader(config),\n },\n\n config.experimental.wasm && {\n test: /\\.wasm$/u,\n use: {\n loader: resolve(__dirname, 'loaders', 'wasm'),\n },\n },\n ],\n },\n\n /**\n * The resolve configuration. This tells Webpack how to resolve imports.\n * We set it to resolve `.js` and `.ts` files.\n *\n * @see https://webpack.js.org/configuration/resolve/\n */\n resolve: {\n /**\n * The extensions to resolve. We set it to resolve `.js` and `.ts`\n * files.\n */\n extensions: ['.js', '.ts'],\n\n /**\n * The fallback options. This tells Webpack how to handle imports that\n * aren't resolved. By default, we set Node.js built-ins to `false`, so\n * that they are ignored.\n */\n fallback: getFallbacks(config.polyfills),\n\n /**\n * The plugins to use. We use the {@link SnapsBuiltInResolver} to show\n * warnings about using Node.js built-ins, when no fallback is specified.\n */\n plugins: [builtInResolver],\n },\n\n /**\n * The plugins to use.\n *\n * @see https://webpack.js.org/configuration/plugins/\n */\n plugins: [\n /**\n * The `SnapsWebpackPlugin` is a Webpack plugin that checks and updates\n * the manifest file, and evaluates the bundle in SES. While not strictly\n * required, it's highly recommended to use this plugin.\n */\n new SnapsWebpackPlugin({\n manifestPath: config.manifest.path,\n writeManifest: config.manifest.update,\n eval: !options.watch && options.evaluate,\n }),\n\n /**\n * The `SnapsStatsPlugin` is a Webpack plugin that handles the stats\n * output. It's used to show the stats in the terminal, in a format that\n * is easy to read.\n */\n new SnapsStatsPlugin({ verbose: config.stats.verbose }, options.spinner),\n\n /**\n * The `EnvironmentPlugin` is a Webpack plugin that adds environment\n * variables to the bundle. We use it to add the `NODE_ENV` and `DEBUG`\n * environment variables.\n */\n new EnvironmentPlugin(config.environment),\n\n /**\n * The `ProgressPlugin` is a Webpack plugin that logs the progress of\n * the build. We set it to log the progress to the spinner.\n */\n new ProgressPlugin({\n handler: getProgressHandler(options.spinner, spinnerText),\n }),\n\n /**\n * The `SnapsBundleWarningPlugin` is a Webpack plugin that shows a\n * warning when the bundle is potentially incompatible with MetaMask\n * Snaps.\n */\n new SnapsBundleWarningsPlugin(\n {\n builtInResolver,\n builtIns: Boolean(config.stats.builtIns),\n buffer: config.stats.buffer,\n },\n options.spinner,\n ),\n\n /**\n * The `WatchPlugin` is a Webpack plugin that adds extra files to watch\n * for changes. This is useful for rebuilding the bundle when the\n * manifest file changes.\n */\n options.watch &&\n new SnapsWatchPlugin(\n {\n bundle: resolve(config.output.path, config.output.filename),\n evaluate: options.evaluate,\n files: [config.manifest.path],\n },\n options.spinner,\n ),\n\n /**\n * The `ProviderPlugin` is a Webpack plugin that automatically load\n * modules instead of having to import or require them everywhere.\n */\n (config.polyfills === true ||\n (config.polyfills !== false && config.polyfills.buffer)) &&\n new ProvidePlugin({\n Buffer: ['buffer', 'Buffer'],\n }),\n ].filter(Boolean),\n\n /**\n * The optimization configuration. This tells Webpack how to optimize the\n * bundle. Most of the time, you won't need to change this, as the default\n * options set by the `mode` option are sufficient.\n */\n optimization: {\n minimize: config.output.minimize,\n\n /**\n * The minimizer to use. We set it to use the `TerserPlugin`.\n */\n minimizer: [\n new TerserPlugin({\n parallel: true,\n }),\n ],\n },\n\n /**\n * The infrastructure logging configuration. This tells Webpack how to\n * log messages.\n *\n * @see https://webpack.js.org/configuration/infrastructure-logging\n */\n infrastructureLogging: {\n /**\n * The level of logging to use. We set it to `none`, so that we can\n * control the output ourselves.\n */\n level: 'none',\n },\n };\n}\n"],"names":["getDefaultConfiguration","config","options","evaluate","spinnerText","spinner","text","builtInResolver","stats","builtIns","SnapsBuiltInResolver","target","BROWSERSLIST_FILE","mode","entry","input","devtool","getDevTool","sourceMap","output","clean","filename","path","publicPath","library","type","module","rules","test","exclude","use","getDefaultLoader","experimental","wasm","loader","resolve","__dirname","extensions","fallback","getFallbacks","polyfills","plugins","SnapsWebpackPlugin","manifestPath","manifest","writeManifest","update","eval","watch","SnapsStatsPlugin","verbose","EnvironmentPlugin","environment","ProgressPlugin","handler","getProgressHandler","SnapsBundleWarningsPlugin","Boolean","buffer","SnapsWatchPlugin","bundle","files","ProvidePlugin","Buffer","filter","optimization","minimize","minimizer","TerserPlugin","parallel","infrastructureLogging","level"],"mappings":";;;;+BA0DsBA;;;eAAAA;;;2EA1DS;sBAEP;4EACC;yBAEwC;yBAQ1D;uBAOA;;;;;;AAsCA,eAAeA,wBACpBC,MAA8B,EAC9BC,UAA0B;IACxBC,UAAUF,OAAOE,QAAQ;AAC3B,CAAC;IAED,MAAMC,cAAcF,QAAQG,OAAO,EAAEC;IACrC,MAAMC,kBACJN,OAAOO,KAAK,CAACC,QAAQ,IACrB,IAAIC,6BAAoB,CAACT,OAAOO,KAAK,CAACC,QAAQ,EAAEP,QAAQG,OAAO;IAEjE,OAAO;QACL;;;;;;;KAOC,GACDM,QAAQ,CAAC,aAAa,EAAEC,wBAAiB,CAAC,CAAC;QAE3C;;;;;KAKC,GACDC,MAAM;QAEN;;;;KAIC,GACDC,OAAOb,OAAOc,KAAK;QAEnB;;;;;KAKC,GACDC,SAASC,IAAAA,iBAAU,EAAChB,OAAOiB,SAAS;QAEpC;;;;;;KAMC,GACDV,OAAO;QAEP;;;;KAIC,GACDW,QAAQ;YACN;;;;;;OAMC,GACDC,OAAOnB,OAAOkB,MAAM,CAACC,KAAK;YAE1B;;;;;OAKC,GACDC,UAAUpB,OAAOkB,MAAM,CAACE,QAAQ;YAEhC;;;;;OAKC,GACDC,MAAMrB,OAAOkB,MAAM,CAACG,IAAI;YAExB;;;;;OAKC,GACDC,YAAY;YAEZ;;;;;OAKC,GACDC,SAAS;gBACP;;;;;SAKC,GACDC,MAAM;YACR;QACF;QAEA;;;;;KAKC,GACDC,QAAQ;YACNC,OAAO;gBACL;oB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,MAAM,CAACE,QAAQ;gBAC1DlB,UAAUD,QAAQC,QAAQ;gBAC1B0D,OAAO;oBAAC5D,OAAO2C,QAAQ,CAACtB,IAAI;iBAAC;YAC/B,GACApB,QAAQG,OAAO;YAGnB;;;OAGC,GACAJ,CAAAA,OAAOuC,SAAS,KAAK,QACnBvC,OAAOuC,SAAS,KAAK,SAASvC,OAAOuC,SAAS,CAACkB,MAAM,KACtD,IAAII,sBAAa,CAAC;gBAChBC,QAAQ;oBAAC;oBAAU;iBAAS;YAC9B;SACH,CAACC,MAAM,CAACP;QAET;;;;KAIC,GACDQ,cAAc;YACZC,UAAUjE,OAAOkB,MAAM,CAAC+C,QAAQ;YAEhC;;OAEC,GACDC,WAAW;gBACT,IAAIC,4BAAY,CAAC;oBACfC,UAAU;gBACZ;aACD;QACH;QAEA;;;;;KAKC,GACDC,uBAAuB;YACrB;;;OAGC,GACDC,OAAO;QACT;IACF;AACF"}
|
|
@@ -309,7 +309,7 @@ function checkBuiltIns(compiler) {
|
|
|
309
309
|
return;
|
|
310
310
|
}
|
|
311
311
|
const formattedModules = new Array(...unresolvedModules).map((name)=>(0, _snapsutils.indent)(`• ${name}`, 2)).join('\n');
|
|
312
|
-
(0, _utils1.warn)(`The snap attempted to use one or more Node.js builtins, but no browser fallback has been provided.\n` + `The MetaMask Snaps CLI does not support Node.js builtins by default. If you want to use this module, you must
|
|
312
|
+
(0, _utils1.warn)(`The snap attempted to use one or more Node.js builtins, but no browser fallback has been provided.\n` + `The MetaMask Snaps CLI does not support Node.js builtins by default. If you want to use this module, you must set ${(0, _chalk.yellow)(`polyfills`)} to ${(0, _chalk.yellow)(`true`)} or an object with the builtins to polyfill as the key and ${(0, _chalk.yellow)(`true`)} as the value.\n` + `To disable this warning, set ${(0, _chalk.yellow)('`stats.builtIns`')} to ${(0, _chalk.yellow)('`false`')} in your snap config file, or add the module to the ${(0, _chalk.yellow)('`stats.builtIns.ignore`')} array.\n\n${formattedModules}\n`, _class_private_field_get(this, _spinner3));
|
|
313
313
|
});
|
|
314
314
|
}
|
|
315
315
|
function isProvidePlugin(instance) {
|
|
@@ -332,7 +332,7 @@ function checkBuffer(compiler) {
|
|
|
332
332
|
if (bufferAssets.length === 0) {
|
|
333
333
|
return;
|
|
334
334
|
}
|
|
335
|
-
(0, _utils1.warn)(`The snap attempted to use the Node.js Buffer global, which is not supported
|
|
335
|
+
(0, _utils1.warn)(`The snap attempted to use the Node.js Buffer global, which is not supported in the MetaMask Snaps CLI by default.\n` + `To use the Buffer global, you must polyfill Buffer by setting ${(0, _chalk.yellow)(`buffer`)} to ${(0, _chalk.yellow)(`true`)} in the ${(0, _chalk.yellow)(`polyfills`)} config object in your snap config.\n` + `To disable this warning, set ${(0, _chalk.yellow)('`stats.buffer`')} to ${(0, _chalk.yellow)('`false`')} in your snap config file.`, _class_private_field_get(this, _spinner3));
|
|
336
336
|
});
|
|
337
337
|
});
|
|
338
338
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/webpack/plugins.ts"],"sourcesContent":["import { indent } from '@metamask/snaps-utils';\nimport { assert, hasProperty, isObject } from '@metamask/utils';\nimport { dim, red, yellow } from 'chalk';\nimport { isBuiltin } from 'module';\nimport type { Ora } from 'ora';\nimport type {\n Compiler,\n ProvidePlugin,\n ResolvePluginInstance,\n Resolver,\n StatsError,\n WebpackPluginInstance,\n} from 'webpack';\n\nimport { evaluate } from '../commands/eval';\nimport { error, getErrorMessage, info, warn } from '../utils';\nimport { pluralize } from './utils';\n\nexport type SnapsStatsPluginOptions = {\n /**\n * Whether to log the verbose stats.\n */\n verbose?: boolean;\n};\n\n/**\n * A plugin that logs the stats after compilation. This is useful for logging\n * the number of files compiled, and the time taken to compile them.\n */\nexport class SnapsStatsPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsStatsPluginOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(\n options: SnapsStatsPluginOptions = {\n verbose: false,\n },\n spinner?: Ora,\n ) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n compiler.hooks.afterDone.tap(this.constructor.name, (stats) => {\n if (!stats) {\n return;\n }\n\n const { modules, time, errors } = stats.toJson();\n\n assert(modules, 'Modules must be defined in stats.');\n assert(time, 'Time must be defined in stats.');\n\n if (errors?.length) {\n const formattedErrors = errors\n .map(this.#getStatsErrorMessage.bind(this))\n .join('\\n\\n');\n\n error(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms with ${errors.length} ${pluralize(\n errors.length,\n 'error',\n )}.\\n\\n${formattedErrors}\\n`,\n this.#spinner,\n );\n\n this.#spinner?.stop();\n\n process.exitCode = 1;\n return;\n }\n\n info(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms.`,\n this.#spinner,\n );\n\n if (compiler.watchMode) {\n // The spinner may be restarted by the watch plugin, outside of the\n // `executeSteps` flow, so we stop it here just in case.\n this.#spinner?.succeed('Done!');\n }\n });\n }\n\n /**\n * Get the error message for the given stats error.\n *\n * @param statsError - The stats error.\n * @returns The error message.\n */\n #getStatsErrorMessage(statsError: StatsError) {\n const baseMessage = this.options.verbose\n ? getErrorMessage(statsError)\n : statsError.message;\n\n const [first, ...rest] = baseMessage.split('\\n');\n\n return [\n indent(red(`• ${first}`), 2),\n ...rest.map((message) => indent(red(message), 4)),\n statsError.details && indent(dim(statsError.details), 4),\n ]\n .filter(Boolean)\n .join('\\n');\n }\n}\n\n/**\n * The options for the {@link SnapsWatchPlugin}.\n */\nexport type SnapsWatchPluginOptions = {\n /**\n * The bundle path. This is the file that will be evaluated, if the `evaluate`\n * option is set.\n */\n bundle?: string;\n\n /**\n * Whether to evaluate the bundle. This only applies if the `bundle` option is\n * set.\n */\n evaluate?: boolean;\n\n /**\n * The extra files to watch.\n */\n files?: string[];\n};\n\n/**\n * A plugin that adds extra files to watch. This is useful for watching files\n * that are not imported by the entry point, such as the `snap.manifest.json`\n * file.\n */\nexport class SnapsWatchPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsWatchPluginOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(options: SnapsWatchPluginOptions, spinner?: Ora) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n compiler.hooks.invalid.tap(this.constructor.name, (file) => {\n this.#spinner?.start();\n info(`Changes detected in ${yellow(file)}, recompiling.`, this.#spinner);\n });\n\n compiler.hooks.afterEmit.tapPromise(\n this.constructor.name,\n async ({ fileDependencies }) => {\n this.options.files?.forEach(\n fileDependencies.add.bind(fileDependencies),\n );\n\n if (this.options.bundle && this.options.evaluate) {\n await this.#safeEvaluate(this.options.bundle);\n }\n },\n );\n }\n\n /**\n * Safely evaluate the bundle at the given path. If an error occurs, it will\n * be logged to the console, rather than throwing an error.\n *\n * This function should never throw an error.\n *\n * @param bundlePath - The path to the bundle.\n */\n async #safeEvaluate(bundlePath: string) {\n try {\n await evaluate(bundlePath);\n info(`Snap bundle evaluated successfully.`, this.#spinner);\n } catch (evaluateError) {\n error(evaluateError.message, this.#spinner);\n }\n }\n}\n\n/**\n * The options for the {@link SnapsBuiltInResolver}.\n */\nexport type SnapsBuiltInResolverOptions = {\n /**\n * The built-in modules to ignore.\n */\n ignore?: string[];\n};\n\n/**\n * A plugin that logs a message when a built-in module is not resolved. The\n * MetaMask Snaps CLI does not support built-in modules by default, and this\n * plugin is used to warn the user when they try to import a built-in module,\n * when no fallback is configured.\n */\nexport class SnapsBuiltInResolver implements ResolvePluginInstance {\n /**\n * The built-in modules that have been imported, but not resolved.\n */\n readonly unresolvedModules = new Set<string>();\n\n /**\n * The name of the resolver hook to tap into.\n */\n readonly #source = 'described-resolve';\n\n /**\n * The options for the plugin.\n */\n readonly options: SnapsBuiltInResolverOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(\n options: SnapsBuiltInResolverOptions = {\n ignore: [],\n },\n spinner?: Ora,\n ) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack resolver.\n *\n * @param resolver - The Webpack resolver.\n */\n apply(resolver: Resolver) {\n resolver\n .getHook(this.#source)\n .tapAsync(\n this.constructor.name,\n ({ module: isModule, request }, _, callback) => {\n if (!isModule || !request) {\n return callback();\n }\n\n const baseRequest = request.split('/')[0];\n if (\n isBuiltin(baseRequest) &&\n !this.options.ignore?.includes(baseRequest)\n ) {\n const fallback = resolver.options.fallback.find(\n ({ name }) => name === baseRequest,\n );\n\n if (fallback && !fallback.alias) {\n this.unresolvedModules.add(baseRequest);\n }\n }\n\n return callback();\n },\n );\n }\n}\n\n/**\n * The options for the {@link SnapsBundleWarningsPlugin}.\n */\nexport type SnapsBundleWarningsPluginOptions = {\n /**\n * The {@link SnapsBuiltInResolver} instance to use for detecting built-in\n * modules.\n */\n builtInResolver?: SnapsBuiltInResolver | false;\n\n /**\n * Whether to show warnings if built-in modules are used, but not provided by\n * Webpack's `fallback` configuration.\n */\n builtIns?: boolean;\n\n /**\n * Whether to show warnings if the `Buffer` global is used, but not provided\n * by Webpack's `DefinePlugin`.\n */\n buffer?: boolean;\n};\n\n/**\n * A plugin that logs a message when:\n *\n * - A built-in module is not resolved. The MetaMask Snaps CLI does not support\n * built-in modules by default, and this plugin is used to warn the user when\n * they try to import a built-in module, when no fallback is configured.\n * - A snap uses the `Buffer` global. The MetaMask Snaps CLI does not support\n * the `Buffer` global by default, and this plugin is used to warn the user when\n * they try to use the `Buffer` global.\n *\n * We use both a resolver and a plugin, because the resolver is used to detect\n * when a built-in module is imported, and the plugin is used to log a single\n * message when the compilation is complete. We can't do everything in a single\n * plugin, because the resolver doesn't have access to the compilation, and the\n * plugin doesn't have access to the resolver.\n */\n\nexport class SnapsBundleWarningsPlugin implements WebpackPluginInstance {\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n /**\n * The options for the plugin.\n */\n readonly options: SnapsBundleWarningsPluginOptions;\n\n constructor(\n options: SnapsBundleWarningsPluginOptions = {\n buffer: true,\n builtIns: true,\n },\n spinner?: Ora,\n ) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n if (this.options.builtIns) {\n this.#checkBuiltIns(compiler);\n }\n\n if (this.options.buffer) {\n this.#checkBuffer(compiler);\n }\n }\n\n /**\n * Check if a built-in module is used, but not provided by Webpack's\n * `fallback` configuration.\n *\n * @param compiler - The Webpack compiler.\n */\n #checkBuiltIns(compiler: Compiler) {\n compiler.hooks.afterCompile.tap(this.constructor.name, () => {\n if (!this.options.builtInResolver) {\n return;\n }\n\n const { unresolvedModules } = this.options.builtInResolver;\n if (unresolvedModules.size === 0) {\n return;\n }\n\n const formattedModules = new Array(...unresolvedModules)\n .map((name) => indent(`• ${name}`, 2))\n .join('\\n');\n\n warn(\n `The snap attempted to use one or more Node.js builtins, but no browser fallback has been provided.\\n` +\n `The MetaMask Snaps CLI does not support Node.js builtins by default. If you want to use this module, you must provide a fallback: https://webpack.js.org/configuration/resolve/#resolvefallback.\\n` +\n `To disable this warning, set ${yellow(\n '`stats.builtIns`',\n )} to ${yellow(\n '`false`',\n )} in your snap config file, or add the module to the ${yellow(\n '`stats.builtIns.ignore`',\n )} array.\\n\\n${formattedModules}\\n`,\n this.#spinner,\n );\n });\n }\n\n /**\n * Check if the given instance is a `ProvidePlugin`. This is not guaranteed to\n * be accurate, but it's good enough for our purposes. If we were to use\n * `instanceof` instead, it might not work if multiple versions of Webpack are\n * installed.\n *\n * @param instance - The instance to check.\n * @returns Whether the instance is a `ProvidePlugin`, i.e., whether it's an\n * object with the name `ProvidePlugin` and a `definitions` property.\n */\n #isProvidePlugin(instance: unknown): instance is ProvidePlugin {\n return (\n isObject(instance) &&\n instance.constructor.name === 'ProvidePlugin' &&\n hasProperty(instance, 'definitions')\n );\n }\n\n /**\n * Check if the `Buffer` global is used, but not provided by Webpack's\n * `DefinePlugin`.\n *\n * @param compiler - The Webpack compiler.\n */\n #checkBuffer(compiler: Compiler) {\n const plugin = compiler.options.plugins?.find((instance) =>\n this.#isProvidePlugin(instance),\n ) as ProvidePlugin | undefined;\n\n // If the `ProvidePlugin` is configured to provide `Buffer`, then we don't\n // need to warn the user.\n if (plugin) {\n const { definitions } = plugin;\n if (definitions.Buffer) {\n return;\n }\n }\n\n compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {\n compilation.hooks.afterProcessAssets.tap(\n this.constructor.name,\n (assets) => {\n // Check if assets use `Buffer`.\n const bufferAssets = Object.entries(assets)\n .filter(([name]) => name.endsWith('.js'))\n .filter(([, asset]) => asset.source().includes('Buffer'));\n\n if (bufferAssets.length === 0) {\n return;\n }\n\n warn(\n `The snap attempted to use the Node.js Buffer global, which is not supported by the MetaMask Snaps CLI.\\n` +\n `To use the Buffer global, you must use the ${yellow(\n '`ProvidePlugin`',\n )} to inject it: https://webpack.js.org/plugins/provide-plugin/.\\n` +\n `To disable this warning, set ${yellow(\n '`stats.buffer`',\n )} to ${yellow('`false`')} in your snap config file.`,\n this.#spinner,\n );\n },\n );\n });\n }\n}\n"],"names":["SnapsStatsPlugin","SnapsWatchPlugin","SnapsBuiltInResolver","SnapsBundleWarningsPlugin","apply","compiler","hooks","afterDone","tap","constructor","name","stats","modules","time","errors","toJson","assert","length","formattedErrors","map","getStatsErrorMessage","bind","join","error","pluralize","spinner","stop","process","exitCode","info","watchMode","succeed","options","verbose","statsError","baseMessage","getErrorMessage","message","first","rest","split","indent","red","details","dim","filter","Boolean","invalid","file","start","yellow","afterEmit","tapPromise","fileDependencies","files","forEach","add","bundle","evaluate","safeEvaluate","bundlePath","evaluateError","resolver","getHook","source","tapAsync","module","isModule","request","_","callback","baseRequest","isBuiltin","ignore","includes","fallback","find","alias","unresolvedModules","Set","builtIns","checkBuiltIns","buffer","checkBuffer","afterCompile","builtInResolver","size","formattedModules","Array","warn","instance","isObject","hasProperty","plugin","plugins","isProvidePlugin","definitions","Buffer","compilation","afterProcessAssets","assets","bufferAssets","Object","entries","endsWith","asset"],"mappings":";;;;;;;;;;;IA6BaA,gBAAgB;eAAhBA;;IA6HAC,gBAAgB;eAAhBA;;IA2EAC,oBAAoB;eAApBA;;IA0GAC,yBAAyB;eAAzBA;;;4BA/UU;uBACuB;uBACb;wBACP;sBAWD;wBAC0B;wBACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAsBf,wCAkET;;;;;GAKC,GACD;AAjFK,MAAMH;IAqBX;;;;GAIC,GACDI,MAAMC,QAAkB,EAAE;QACxBA,SAASC,KAAK,CAACC,SAAS,CAACC,GAAG,CAAC,IAAI,CAACC,WAAW,CAACC,IAAI,EAAE,CAACC;YACnD,IAAI,CAACA,OAAO;gBACV;YACF;YAEA,MAAM,EAAEC,OAAO,EAAEC,IAAI,EAAEC,MAAM,EAAE,GAAGH,MAAMI,MAAM;YAE9CC,IAAAA,aAAM,EAACJ,SAAS;YAChBI,IAAAA,aAAM,EAACH,MAAM;YAEb,IAAIC,QAAQG,QAAQ;gBAClB,MAAMC,kBAAkBJ,OACrBK,GAAG,CAAC,0BAAA,IAAI,EAAEC,uBAAAA,sBAAqBC,IAAI,CAAC,IAAI,GACxCC,IAAI,CAAC;gBAERC,IAAAA,aAAK,EACH,CAAC,SAAS,EAAEX,QAAQK,MAAM,CAAC,CAAC,EAAEO,IAAAA,iBAAS,EACrCZ,QAAQK,MAAM,EACd,QACA,IAAI,EAAEJ,KAAK,QAAQ,EAAEC,OAAOG,MAAM,CAAC,CAAC,EAAEO,IAAAA,iBAAS,EAC/CV,OAAOG,MAAM,EACb,SACA,K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c,WAC7C,0BAAA,IAAI,EAAEK,kBAAAA,sBAAN,IAAI,EAAkBL;IAGxB,0EAA0E;IAC1E,yBAAyB;IACzB,IAAIG,QAAQ;QACV,MAAM,EAAEG,WAAW,EAAE,GAAGH;QACxB,IAAIG,YAAYC,MAAM,EAAE;YACtB;QACF;IACF;IAEA5F,SAASC,KAAK,CAAC4F,WAAW,CAAC1F,GAAG,CAAC,IAAI,CAACC,WAAW,CAACC,IAAI,EAAE,CAACwF;QACrDA,YAAY5F,KAAK,CAAC6F,kBAAkB,CAAC3F,GAAG,CACtC,IAAI,CAACC,WAAW,CAACC,IAAI,EACrB,CAAC0F;YACC,gCAAgC;YAChC,MAAMC,eAAeC,OAAOC,OAAO,CAACH,QACjCvD,MAAM,CAAC,CAAC,CAACnC,KAAK,GAAKA,KAAK8F,QAAQ,CAAC,QACjC3D,MAAM,CAAC,CAAC,GAAG4D,MAAM,GAAKA,MAAMzC,MAAM,GAAGU,QAAQ,CAAC;YAEjD,IAAI2B,aAAapF,MAAM,KAAK,GAAG;gBAC7B;YACF;YAEAwE,IAAAA,YAAI,EACF,CAAC,wGAAwG,CAAC,GACxG,CAAC,2CAA2C,EAAEvC,IAAAA,aAAM,EAClD,mBACA,gEAAgE,CAAC,GACnE,CAAC,6BAA6B,EAAEA,IAAAA,aAAM,EACpC,kBACA,IAAI,EAAEA,IAAAA,aAAM,EAAC,WAAW,0BAA0B,CAAC,2BACvD,IAAI,EAAEzB;QAEV;IAEJ;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/webpack/plugins.ts"],"sourcesContent":["import { indent } from '@metamask/snaps-utils';\nimport { assert, hasProperty, isObject } from '@metamask/utils';\nimport { dim, red, yellow } from 'chalk';\nimport { isBuiltin } from 'module';\nimport type { Ora } from 'ora';\nimport type {\n Compiler,\n ProvidePlugin,\n ResolvePluginInstance,\n Resolver,\n StatsError,\n WebpackPluginInstance,\n} from 'webpack';\n\nimport { evaluate } from '../commands/eval';\nimport { error, getErrorMessage, info, warn } from '../utils';\nimport { pluralize } from './utils';\n\nexport type SnapsStatsPluginOptions = {\n /**\n * Whether to log the verbose stats.\n */\n verbose?: boolean;\n};\n\n/**\n * A plugin that logs the stats after compilation. This is useful for logging\n * the number of files compiled, and the time taken to compile them.\n */\nexport class SnapsStatsPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsStatsPluginOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(\n options: SnapsStatsPluginOptions = {\n verbose: false,\n },\n spinner?: Ora,\n ) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n compiler.hooks.afterDone.tap(this.constructor.name, (stats) => {\n if (!stats) {\n return;\n }\n\n const { modules, time, errors } = stats.toJson();\n\n assert(modules, 'Modules must be defined in stats.');\n assert(time, 'Time must be defined in stats.');\n\n if (errors?.length) {\n const formattedErrors = errors\n .map(this.#getStatsErrorMessage.bind(this))\n .join('\\n\\n');\n\n error(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms with ${errors.length} ${pluralize(\n errors.length,\n 'error',\n )}.\\n\\n${formattedErrors}\\n`,\n this.#spinner,\n );\n\n this.#spinner?.stop();\n\n process.exitCode = 1;\n return;\n }\n\n info(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms.`,\n this.#spinner,\n );\n\n if (compiler.watchMode) {\n // The spinner may be restarted by the watch plugin, outside of the\n // `executeSteps` flow, so we stop it here just in case.\n this.#spinner?.succeed('Done!');\n }\n });\n }\n\n /**\n * Get the error message for the given stats error.\n *\n * @param statsError - The stats error.\n * @returns The error message.\n */\n #getStatsErrorMessage(statsError: StatsError) {\n const baseMessage = this.options.verbose\n ? getErrorMessage(statsError)\n : statsError.message;\n\n const [first, ...rest] = baseMessage.split('\\n');\n\n return [\n indent(red(`• ${first}`), 2),\n ...rest.map((message) => indent(red(message), 4)),\n statsError.details && indent(dim(statsError.details), 4),\n ]\n .filter(Boolean)\n .join('\\n');\n }\n}\n\n/**\n * The options for the {@link SnapsWatchPlugin}.\n */\nexport type SnapsWatchPluginOptions = {\n /**\n * The bundle path. This is the file that will be evaluated, if the `evaluate`\n * option is set.\n */\n bundle?: string;\n\n /**\n * Whether to evaluate the bundle. This only applies if the `bundle` option is\n * set.\n */\n evaluate?: boolean;\n\n /**\n * The extra files to watch.\n */\n files?: string[];\n};\n\n/**\n * A plugin that adds extra files to watch. This is useful for watching files\n * that are not imported by the entry point, such as the `snap.manifest.json`\n * file.\n */\nexport class SnapsWatchPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsWatchPluginOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(options: SnapsWatchPluginOptions, spinner?: Ora) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n compiler.hooks.invalid.tap(this.constructor.name, (file) => {\n this.#spinner?.start();\n info(`Changes detected in ${yellow(file)}, recompiling.`, this.#spinner);\n });\n\n compiler.hooks.afterEmit.tapPromise(\n this.constructor.name,\n async ({ fileDependencies }) => {\n this.options.files?.forEach(\n fileDependencies.add.bind(fileDependencies),\n );\n\n if (this.options.bundle && this.options.evaluate) {\n await this.#safeEvaluate(this.options.bundle);\n }\n },\n );\n }\n\n /**\n * Safely evaluate the bundle at the given path. If an error occurs, it will\n * be logged to the console, rather than throwing an error.\n *\n * This function should never throw an error.\n *\n * @param bundlePath - The path to the bundle.\n */\n async #safeEvaluate(bundlePath: string) {\n try {\n await evaluate(bundlePath);\n info(`Snap bundle evaluated successfully.`, this.#spinner);\n } catch (evaluateError) {\n error(evaluateError.message, this.#spinner);\n }\n }\n}\n\n/**\n * The options for the {@link SnapsBuiltInResolver}.\n */\nexport type SnapsBuiltInResolverOptions = {\n /**\n * The built-in modules to ignore.\n */\n ignore?: string[];\n};\n\n/**\n * A plugin that logs a message when a built-in module is not resolved. The\n * MetaMask Snaps CLI does not support built-in modules by default, and this\n * plugin is used to warn the user when they try to import a built-in module,\n * when no fallback is configured.\n */\nexport class SnapsBuiltInResolver implements ResolvePluginInstance {\n /**\n * The built-in modules that have been imported, but not resolved.\n */\n readonly unresolvedModules = new Set<string>();\n\n /**\n * The name of the resolver hook to tap into.\n */\n readonly #source = 'described-resolve';\n\n /**\n * The options for the plugin.\n */\n readonly options: SnapsBuiltInResolverOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(\n options: SnapsBuiltInResolverOptions = {\n ignore: [],\n },\n spinner?: Ora,\n ) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack resolver.\n *\n * @param resolver - The Webpack resolver.\n */\n apply(resolver: Resolver) {\n resolver\n .getHook(this.#source)\n .tapAsync(\n this.constructor.name,\n ({ module: isModule, request }, _, callback) => {\n if (!isModule || !request) {\n return callback();\n }\n\n const baseRequest = request.split('/')[0];\n if (\n isBuiltin(baseRequest) &&\n !this.options.ignore?.includes(baseRequest)\n ) {\n const fallback = resolver.options.fallback.find(\n ({ name }) => name === baseRequest,\n );\n\n if (fallback && !fallback.alias) {\n this.unresolvedModules.add(baseRequest);\n }\n }\n\n return callback();\n },\n );\n }\n}\n\n/**\n * The options for the {@link SnapsBundleWarningsPlugin}.\n */\nexport type SnapsBundleWarningsPluginOptions = {\n /**\n * The {@link SnapsBuiltInResolver} instance to use for detecting built-in\n * modules.\n */\n builtInResolver?: SnapsBuiltInResolver | false;\n\n /**\n * Whether to show warnings if built-in modules are used, but not provided by\n * Webpack's `fallback` configuration.\n */\n builtIns?: boolean;\n\n /**\n * Whether to show warnings if the `Buffer` global is used, but not provided\n * by Webpack's `DefinePlugin`.\n */\n buffer?: boolean;\n};\n\n/**\n * A plugin that logs a message when:\n *\n * - A built-in module is not resolved. The MetaMask Snaps CLI does not support\n * built-in modules by default, and this plugin is used to warn the user when\n * they try to import a built-in module, when no fallback is configured.\n * - A snap uses the `Buffer` global. The MetaMask Snaps CLI does not support\n * the `Buffer` global by default, and this plugin is used to warn the user when\n * they try to use the `Buffer` global.\n *\n * We use both a resolver and a plugin, because the resolver is used to detect\n * when a built-in module is imported, and the plugin is used to log a single\n * message when the compilation is complete. We can't do everything in a single\n * plugin, because the resolver doesn't have access to the compilation, and the\n * plugin doesn't have access to the resolver.\n */\n\nexport class SnapsBundleWarningsPlugin implements WebpackPluginInstance {\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n /**\n * The options for the plugin.\n */\n readonly options: SnapsBundleWarningsPluginOptions;\n\n constructor(\n options: SnapsBundleWarningsPluginOptions = {\n buffer: true,\n builtIns: true,\n },\n spinner?: Ora,\n ) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n if (this.options.builtIns) {\n this.#checkBuiltIns(compiler);\n }\n\n if (this.options.buffer) {\n this.#checkBuffer(compiler);\n }\n }\n\n /**\n * Check if a built-in module is used, but not provided by Webpack's\n * `fallback` configuration.\n *\n * @param compiler - The Webpack compiler.\n */\n #checkBuiltIns(compiler: Compiler) {\n compiler.hooks.afterCompile.tap(this.constructor.name, () => {\n if (!this.options.builtInResolver) {\n return;\n }\n\n const { unresolvedModules } = this.options.builtInResolver;\n if (unresolvedModules.size === 0) {\n return;\n }\n\n const formattedModules = new Array(...unresolvedModules)\n .map((name) => indent(`• ${name}`, 2))\n .join('\\n');\n\n warn(\n `The snap attempted to use one or more Node.js builtins, but no browser fallback has been provided.\\n` +\n `The MetaMask Snaps CLI does not support Node.js builtins by default. If you want to use this module, you must set ${yellow(\n `polyfills`,\n )} to ${yellow(\n `true`,\n )} or an object with the builtins to polyfill as the key and ${yellow(\n `true`,\n )} as the value.\\n` +\n `To disable this warning, set ${yellow(\n '`stats.builtIns`',\n )} to ${yellow(\n '`false`',\n )} in your snap config file, or add the module to the ${yellow(\n '`stats.builtIns.ignore`',\n )} array.\\n\\n${formattedModules}\\n`,\n this.#spinner,\n );\n });\n }\n\n /**\n * Check if the given instance is a `ProvidePlugin`. This is not guaranteed to\n * be accurate, but it's good enough for our purposes. If we were to use\n * `instanceof` instead, it might not work if multiple versions of Webpack are\n * installed.\n *\n * @param instance - The instance to check.\n * @returns Whether the instance is a `ProvidePlugin`, i.e., whether it's an\n * object with the name `ProvidePlugin` and a `definitions` property.\n */\n #isProvidePlugin(instance: unknown): instance is ProvidePlugin {\n return (\n isObject(instance) &&\n instance.constructor.name === 'ProvidePlugin' &&\n hasProperty(instance, 'definitions')\n );\n }\n\n /**\n * Check if the `Buffer` global is used, but not provided by Webpack's\n * `DefinePlugin`.\n *\n * @param compiler - The Webpack compiler.\n */\n #checkBuffer(compiler: Compiler) {\n const plugin = compiler.options.plugins?.find((instance) =>\n this.#isProvidePlugin(instance),\n ) as ProvidePlugin | undefined;\n\n // If the `ProvidePlugin` is configured to provide `Buffer`, then we don't\n // need to warn the user.\n if (plugin) {\n const { definitions } = plugin;\n if (definitions.Buffer) {\n return;\n }\n }\n\n compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {\n compilation.hooks.afterProcessAssets.tap(\n this.constructor.name,\n (assets) => {\n // Check if assets use `Buffer`.\n const bufferAssets = Object.entries(assets)\n .filter(([name]) => name.endsWith('.js'))\n .filter(([, asset]) => asset.source().includes('Buffer'));\n\n if (bufferAssets.length === 0) {\n return;\n }\n\n warn(\n `The snap attempted to use the Node.js Buffer global, which is not supported in the MetaMask Snaps CLI by default.\\n` +\n `To use the Buffer global, you must polyfill Buffer by setting ${yellow(\n `buffer`,\n )} to ${yellow(`true`)} in the ${yellow(\n `polyfills`,\n )} config object in your snap config.\\n` +\n `To disable this warning, set ${yellow(\n '`stats.buffer`',\n )} to ${yellow('`false`')} in your snap config file.`,\n this.#spinner,\n );\n },\n );\n });\n }\n}\n"],"names":["SnapsStatsPlugin","SnapsWatchPlugin","SnapsBuiltInResolver","SnapsBundleWarningsPlugin","apply","compiler","hooks","afterDone","tap","constructor","name","stats","modules","time","errors","toJson","assert","length","formattedErrors","map","getStatsErrorMessage","bind","join","error","pluralize","spinner","stop","process","exitCode","info","watchMode","succeed","options","verbose","statsError","baseMessage","getErrorMessage","message","first","rest","split","indent","red","details","dim","filter","Boolean","invalid","file","start","yellow","afterEmit","tapPromise","fileDependencies","files","forEach","add","bundle","evaluate","safeEvaluate","bundlePath","evaluateError","resolver","getHook","source","tapAsync","module","isModule","request","_","callback","baseRequest","isBuiltin","ignore","includes","fallback","find","alias","unresolvedModules","Set","builtIns","checkBuiltIns","buffer","checkBuffer","afterCompile","builtInResolver","size","formattedModules","Array","warn","instance","isObject","hasProperty","plugin","plugins","isProvidePlugin","definitions","Buffer","compilation","afterProcessAssets","assets","bufferAssets","Object","entries","endsWith","asset"],"mappings":";;;;;;;;;;;IA6BaA,gBAAgB;eAAhBA;;IA6HAC,gBAAgB;eAAhBA;;IA2EAC,oBAAoB;eAApBA;;IA0GAC,yBAAyB;eAAzBA;;;4BA/UU;uBACuB;uBACb;wBACP;sBAWD;wBAC0B;wBACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAsBf,wCAkET;;;;;GAKC,GACD;AAjFK,MAAMH;IAqBX;;;;GAIC,GACDI,MAAMC,QAAkB,EAAE;QACxBA,SAASC,KAAK,CAACC,SAAS,CAACC,GAAG,CAAC,IAAI,CAACC,WAAW,CAACC,IAAI,EAAE,CAACC;YACnD,IAAI,CAACA,OAAO;gBACV;YACF;YAEA,MAAM,EAAEC,OAAO,EAAEC,IAAI,EAAEC,MAAM,EAAE,GAAGH,MAAMI,MAAM;YAE9CC,IAAAA,aAAM,EAACJ,SAAS;YAChBI,IAAAA,aAA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AwE,IAAAA,YAAI,EACF,CAAC,mHAAmH,CAAC,GACnH,CAAC,8DAA8D,EAAEvC,IAAAA,aAAM,EACrE,CAAC,MAAM,CAAC,EACR,IAAI,EAAEA,IAAAA,aAAM,EAAC,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAEA,IAAAA,aAAM,EACrC,CAAC,SAAS,CAAC,EACX,qCAAqC,CAAC,GACxC,CAAC,6BAA6B,EAAEA,IAAAA,aAAM,EACpC,kBACA,IAAI,EAAEA,IAAAA,aAAM,EAAC,WAAW,0BAA0B,CAAC,2BACvD,IAAI,EAAEzB;QAEV;IAEJ;AACF"}
|
|
@@ -12,6 +12,9 @@ _export(exports, {
|
|
|
12
12
|
BROWSERSLIST_FILE: function() {
|
|
13
13
|
return BROWSERSLIST_FILE;
|
|
14
14
|
},
|
|
15
|
+
WEBPACK_FALLBACKS: function() {
|
|
16
|
+
return WEBPACK_FALLBACKS;
|
|
17
|
+
},
|
|
15
18
|
getDefaultLoader: function() {
|
|
16
19
|
return getDefaultLoader;
|
|
17
20
|
},
|
|
@@ -26,13 +29,47 @@ _export(exports, {
|
|
|
26
29
|
},
|
|
27
30
|
pluralize: function() {
|
|
28
31
|
return pluralize;
|
|
32
|
+
},
|
|
33
|
+
getFallbacks: function() {
|
|
34
|
+
return getFallbacks;
|
|
29
35
|
}
|
|
30
36
|
});
|
|
31
37
|
const _chalk = require("chalk");
|
|
32
38
|
const _fs = require("fs");
|
|
39
|
+
const _module = require("module");
|
|
33
40
|
const _path = require("path");
|
|
34
41
|
const BROWSERSLIST_FILE = (0, _path.resolve)((0, _path.dirname)(// eslint-disable-next-line n/no-extraneous-require
|
|
35
42
|
require.resolve('@metamask/snaps-cli/package.json')), '.browserslistrc');
|
|
43
|
+
const WEBPACK_FALLBACKS = {
|
|
44
|
+
assert: require.resolve('assert/'),
|
|
45
|
+
buffer: require.resolve('buffer/'),
|
|
46
|
+
console: require.resolve('console-browserify'),
|
|
47
|
+
constants: require.resolve('constants-browserify'),
|
|
48
|
+
crypto: require.resolve('crypto-browserify'),
|
|
49
|
+
domain: require.resolve('domain-browser'),
|
|
50
|
+
events: require.resolve('events/'),
|
|
51
|
+
http: require.resolve('stream-http'),
|
|
52
|
+
https: require.resolve('https-browserify'),
|
|
53
|
+
os: require.resolve('os-browserify/browser'),
|
|
54
|
+
path: require.resolve('path-browserify'),
|
|
55
|
+
punycode: require.resolve('punycode/'),
|
|
56
|
+
process: require.resolve('process/browser'),
|
|
57
|
+
querystring: require.resolve('querystring-es3'),
|
|
58
|
+
stream: require.resolve('stream-browserify'),
|
|
59
|
+
/* eslint-disable @typescript-eslint/naming-convention */ _stream_duplex: require.resolve('readable-stream/lib/_stream_duplex'),
|
|
60
|
+
_stream_passthrough: require.resolve('readable-stream/lib/_stream_passthrough'),
|
|
61
|
+
_stream_readable: require.resolve('readable-stream/lib/_stream_readable'),
|
|
62
|
+
_stream_transform: require.resolve('readable-stream/lib/_stream_transform'),
|
|
63
|
+
_stream_writable: require.resolve('readable-stream/lib/_stream_writable'),
|
|
64
|
+
string_decoder: require.resolve('string_decoder/'),
|
|
65
|
+
/* eslint-enable @typescript-eslint/naming-convention */ sys: require.resolve('util/'),
|
|
66
|
+
timers: require.resolve('timers-browserify'),
|
|
67
|
+
tty: require.resolve('tty-browserify'),
|
|
68
|
+
url: require.resolve('url/'),
|
|
69
|
+
util: require.resolve('util/'),
|
|
70
|
+
vm: require.resolve('vm-browserify'),
|
|
71
|
+
zlib: require.resolve('browserify-zlib')
|
|
72
|
+
};
|
|
36
73
|
async function getDefaultLoader({ legacy, sourceMap }) {
|
|
37
74
|
if (legacy) {
|
|
38
75
|
return {
|
|
@@ -69,13 +106,6 @@ async function getDefaultLoader({ legacy, sourceMap }) {
|
|
|
69
106
|
* This must be enabled if source maps are enabled in the config.
|
|
70
107
|
*/ sourceMaps: Boolean(getDevTool(sourceMap)),
|
|
71
108
|
jsc: {
|
|
72
|
-
/**
|
|
73
|
-
* MetaMask targets ES2020, so we set the target to ES2020. This
|
|
74
|
-
* ensures that the code is transpiled to ES2020, and that the
|
|
75
|
-
* necessary polyfills are added.
|
|
76
|
-
*
|
|
77
|
-
* @see https://swc.rs/docs/configuration/compilation#jsctarget
|
|
78
|
-
*/ target: 'es2020',
|
|
79
109
|
parser: {
|
|
80
110
|
/**
|
|
81
111
|
* This tells the parser to parse TypeScript files. If you
|
|
@@ -129,5 +159,23 @@ async function getBrowserslistTargets() {
|
|
|
129
159
|
function pluralize(count, singular, plural = `${singular}s`) {
|
|
130
160
|
return count === 1 ? singular : plural;
|
|
131
161
|
}
|
|
162
|
+
function getFallbacks(polyfills) {
|
|
163
|
+
if (polyfills === true) {
|
|
164
|
+
return Object.fromEntries(_module.builtinModules.map((name)=>[
|
|
165
|
+
name,
|
|
166
|
+
WEBPACK_FALLBACKS[name] ?? false
|
|
167
|
+
]));
|
|
168
|
+
}
|
|
169
|
+
if (polyfills === false) {
|
|
170
|
+
return Object.fromEntries(_module.builtinModules.map((name)=>[
|
|
171
|
+
name,
|
|
172
|
+
false
|
|
173
|
+
]));
|
|
174
|
+
}
|
|
175
|
+
return Object.fromEntries(_module.builtinModules.map((name)=>[
|
|
176
|
+
name,
|
|
177
|
+
polyfills[name] ? WEBPACK_FALLBACKS[name] : false
|
|
178
|
+
]));
|
|
179
|
+
}
|
|
132
180
|
|
|
133
181
|
//# sourceMappingURL=utils.js.map
|