diff --git a/packages/examples/packages/browserify/.depcheckrc.json b/packages/examples/packages/browserify/.depcheckrc.json deleted file mode 100644 index c437c59cd2..0000000000 --- a/packages/examples/packages/browserify/.depcheckrc.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "ignore-patterns": ["dist", "coverage"], - "ignores": [ - "@lavamoat/allow-scripts", - "@lavamoat/preinstall-always-fail", - "@metamask/auto-changelog", - "@metamask/eslint-*", - "@types/*", - "@typescript-eslint/*", - "eslint-config-*", - "eslint-plugin-*", - "jest-silent-reporter", - "prettier-plugin-packagejson", - "ts-node", - "typedoc", - "typescript" - ] -} diff --git a/packages/examples/packages/browserify/CHANGELOG.md b/packages/examples/packages/browserify/CHANGELOG.md deleted file mode 100644 index add2a8cbc1..0000000000 --- a/packages/examples/packages/browserify/CHANGELOG.md +++ /dev/null @@ -1,76 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] - -## [2.1.3] - -### Fixed - -- Bump MetaMask dependencies - -## [2.1.2] - -### Changed - -- Use error wrappers ([#2178](https://github.com/MetaMask/snaps/pull/2178)) - -## [2.1.1] - -### Changed - -- Remove snap icon ([#2189](https://github.com/MetaMask/snaps/pull/2189)) - -## [2.1.0] - -### Changed - -- Use `@metamask/snaps-sdk` package ([#1946](https://github.com/MetaMask/snaps/pull/1946)) - - This package replaces the `@metamask/snaps-types` and - - `@metamask/snaps-ui` packages, and is much more lightweight. - -## [2.0.1] - -### Changed - -- Update multiple MetaMask dependencies ([#1841](https://github.com/MetaMask/snaps/pull/1841)) - -## [2.0.0] - -### Changed - -- **BREAKING:** Bump minimum Node.js version to `^18.16.0` ([#1741](https://github.com/MetaMask/snaps/pull/1741)) - -## [1.0.0] - -### Changed - -- Initial stable release from main branch ([#1757](https://github.com/MetaMask/snaps/pull/1757)) - -## [0.38.1-flask.1] - -### Fixed - -- Remove unused dependencies ([#1680](https://github.com/MetaMask/snaps/pull/1680)) - -## [0.38.0-flask.1] - -### Added - -- Add Browserify example snap ([#1632](https://github.com/MetaMask/snaps/pull/1632)) - - This snap demonstrates how to use the deprecated Browserify configuration format. - -[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/browserify-example-snap@2.1.3...HEAD -[2.1.3]: https://github.com/MetaMask/snaps/compare/@metamask/browserify-example-snap@2.1.2...@metamask/browserify-example-snap@2.1.3 -[2.1.2]: https://github.com/MetaMask/snaps/compare/@metamask/browserify-example-snap@2.1.1...@metamask/browserify-example-snap@2.1.2 -[2.1.1]: https://github.com/MetaMask/snaps/compare/@metamask/browserify-example-snap@2.1.0...@metamask/browserify-example-snap@2.1.1 -[2.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/browserify-example-snap@2.0.1...@metamask/browserify-example-snap@2.1.0 -[2.0.1]: https://github.com/MetaMask/snaps/compare/@metamask/browserify-example-snap@2.0.0...@metamask/browserify-example-snap@2.0.1 -[2.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/browserify-example-snap@1.0.0...@metamask/browserify-example-snap@2.0.0 -[1.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/browserify-example-snap@0.38.1-flask.1...@metamask/browserify-example-snap@1.0.0 -[0.38.1-flask.1]: https://github.com/MetaMask/snaps/compare/@metamask/browserify-example-snap@0.38.0-flask.1...@metamask/browserify-example-snap@0.38.1-flask.1 -[0.38.0-flask.1]: https://github.com/MetaMask/snaps/releases/tag/@metamask/browserify-example-snap@0.38.0-flask.1 diff --git a/packages/examples/packages/browserify/LICENSE.APACHE2 b/packages/examples/packages/browserify/LICENSE.APACHE2 deleted file mode 100644 index bf37d0e612..0000000000 --- a/packages/examples/packages/browserify/LICENSE.APACHE2 +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2023 ConsenSys Software Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/packages/examples/packages/browserify/LICENSE.MIT0 b/packages/examples/packages/browserify/LICENSE.MIT0 deleted file mode 100644 index 913c577462..0000000000 --- a/packages/examples/packages/browserify/LICENSE.MIT0 +++ /dev/null @@ -1,16 +0,0 @@ -MIT No Attribution - -Copyright 2023 ConsenSys Software Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this -software and associated documentation files (the "Software"), to deal in the Software -without restriction, including without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/examples/packages/browserify/README.md b/packages/examples/packages/browserify/README.md deleted file mode 100644 index ea1e486150..0000000000 --- a/packages/examples/packages/browserify/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# `@metamask/browserify-example-snap` - -This snap demonstrates how to use the MetaMask Snaps CLI with the legacy -Browserify bundler. - -> **Warning**: The Browserify bundler in the MetaMask Snaps CLI is deprecated -> and will be removed in a future release. Please use the Webpack bundler -> instead. - -## Snap usage - -This snap exposes an `onRpcRequest` handler, which supports the following -JSON-RPC method: - -- `hello`: Returns a message for demonstration purposes. - -For more information, you can refer to -[the end-to-end tests](./src/index.test.ts). diff --git a/packages/examples/packages/browserify/jest.config.js b/packages/examples/packages/browserify/jest.config.js deleted file mode 100644 index f473a91b83..0000000000 --- a/packages/examples/packages/browserify/jest.config.js +++ /dev/null @@ -1,36 +0,0 @@ -const deepmerge = require('deepmerge'); - -const baseConfig = require('../../../../jest.config.base'); - -module.exports = deepmerge(baseConfig, { - preset: '@metamask/snaps-jest', - - // Since `@metamask/snaps-jest` runs in the browser, we can't collect - // coverage information. - collectCoverage: false, - - // This is required for the tests to run inside the `MetaMask/snaps` - // repository. You don't need this in your own project. - moduleNameMapper: { - '^@metamask/(.+)/production/jsx-runtime': [ - '/../../../$1/src/jsx/production/jsx-runtime', - '/../../../../node_modules/@metamask/$1/jsx/production/jsx-runtime', - '/node_modules/@metamask/$1/jsx/production/jsx-runtime', - ], - '^@metamask/(.+)/jsx': [ - '/../../../$1/src/jsx', - '/../../../../node_modules/@metamask/$1/jsx', - '/node_modules/@metamask/$1/jsx', - ], - '^@metamask/(.+)/node$': [ - '/../../../$1/src/node', - '/../../../../node_modules/@metamask/$1/node', - '/node_modules/@metamask/$1/node', - ], - '^@metamask/(.+)$': [ - '/../../../$1/src', - '/../../../../node_modules/@metamask/$1', - '/node_modules/@metamask/$1', - ], - }, -}); diff --git a/packages/examples/packages/browserify/package.json b/packages/examples/packages/browserify/package.json deleted file mode 100644 index 755f6cd3fc..0000000000 --- a/packages/examples/packages/browserify/package.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "name": "@metamask/browserify-example-snap", - "version": "2.1.3", - "description": "MetaMask example snap demonstrating how to use Browserify to bundle a snap", - "keywords": [ - "MetaMask", - "Snaps", - "Ethereum" - ], - "homepage": "https://github.com/MetaMask/snaps/tree/main/packages/examples/packages/browserify#readme", - "bugs": { - "url": "https://github.com/MetaMask/snaps/issues" - }, - "repository": { - "type": "git", - "url": "https://github.com/MetaMask/snaps.git" - }, - "license": "(MIT-0 OR Apache-2.0)", - "sideEffects": false, - "main": "./dist/bundle.js", - "files": [ - "dist", - "snap.manifest.json" - ], - "scripts": { - "build": "mm-snap build", - "build:clean": "yarn clean && yarn build", - "changelog:update": "../../../../scripts/update-changelog.sh @metamask/browserify-example-snap", - "changelog:validate": "../../../../scripts/validate-changelog.sh @metamask/browserify-example-snap", - "clean": "rimraf \"dist\"", - "lint": "yarn lint:eslint && yarn lint:misc --check && yarn changelog:validate && yarn lint:dependencies", - "lint:ci": "yarn lint", - "lint:dependencies": "depcheck", - "lint:eslint": "eslint . --cache", - "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write", - "lint:misc": "prettier --no-error-on-unmatched-pattern --log-level warn \"**/*.json\" \"**/*.md\" \"**/*.html\" \"!CHANGELOG.md\" \"!snap.manifest.json\" --ignore-path ../../../../.gitignore", - "publish:preview": "yarn npm publish --tag preview", - "since-latest-release": "../../../../scripts/since-latest-release.sh", - "start": "mm-snap watch", - "test": "jest --reporters=jest-silent-reporter", - "test:clean": "jest --clearCache", - "test:verbose": "jest --verbose", - "test:watch": "jest --watch" - }, - "dependencies": { - "@metamask/snaps-sdk": "workspace:^" - }, - "devDependencies": { - "@jest/globals": "^29.5.0", - "@lavamoat/allow-scripts": "^3.0.4", - "@metamask/auto-changelog": "^5.0.1", - "@metamask/snaps-cli": "workspace:^", - "@metamask/snaps-jest": "workspace:^", - "@swc/core": "1.3.78", - "@swc/jest": "^0.2.26", - "@types/node": "18.14.2", - "deepmerge": "^4.2.2", - "depcheck": "^1.4.7", - "eslint": "^9.11.0", - "jest": "^29.0.2", - "jest-silent-reporter": "^0.6.0", - "prettier": "^3.3.3", - "rimraf": "^4.1.2", - "ts-node": "^10.9.1", - "typescript": "~5.3.3" - }, - "engines": { - "node": "^18.16 || >=20" - }, - "publishConfig": { - "access": "public", - "registry": "https://registry.npmjs.org/" - } -} diff --git a/packages/examples/packages/browserify/snap.config.ts b/packages/examples/packages/browserify/snap.config.ts deleted file mode 100644 index b821ddbff0..0000000000 --- a/packages/examples/packages/browserify/snap.config.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { SnapConfig } from '@metamask/snaps-cli'; -import { resolve } from 'path'; - -const config: SnapConfig = { - bundler: 'browserify', - cliOptions: { - src: resolve(__dirname, 'src/index.ts'), - port: 8021, - }, -}; - -export default config; diff --git a/packages/examples/packages/browserify/snap.manifest.json b/packages/examples/packages/browserify/snap.manifest.json deleted file mode 100644 index 9ee4bcfdb5..0000000000 --- a/packages/examples/packages/browserify/snap.manifest.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "version": "2.1.3", - "description": "MetaMask example snap demonstrating how to use the Browserify plugin to bundle a snap.", - "proposedName": "Browserify Plugin Example Snap", - "repository": { - "type": "git", - "url": "https://github.com/MetaMask/snaps.git" - }, - "source": { - "shasum": "CDCcIudSL6vG5JCgP03ti4WnmJuuDFHFX95+tDFDqrY=", - "location": { - "npm": { - "filePath": "dist/bundle.js", - "packageName": "@metamask/browserify-example-snap", - "registry": "https://registry.npmjs.org" - } - } - }, - "initialPermissions": { - "endowment:rpc": { - "dapps": true - } - }, - "platformVersion": "6.22.0", - "manifestVersion": "0.1" -} diff --git a/packages/examples/packages/browserify/src/index.test.ts b/packages/examples/packages/browserify/src/index.test.ts deleted file mode 100644 index 1896880d22..0000000000 --- a/packages/examples/packages/browserify/src/index.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { expect } from '@jest/globals'; -import { installSnap } from '@metamask/snaps-jest'; - -describe('onRpcRequest', () => { - it('throws an error if the requested method does not exist', async () => { - const { request } = await installSnap(); - - const response = await request({ - method: 'foo', - }); - - expect(response).toRespondWithError({ - code: -32601, - message: 'The method does not exist / is not available.', - stack: expect.any(String), - data: { - method: 'foo', - cause: null, - }, - }); - }); - - describe('hello', () => { - it('returns "Hello from Browserify!"', async () => { - const { request } = await installSnap(); - - const response = await request({ - method: 'hello', - }); - - expect(response).toRespondWith( - 'Hello from the MetaMask Snaps CLI using Browserify!', - ); - }); - }); -}); diff --git a/packages/examples/packages/browserify/src/index.ts b/packages/examples/packages/browserify/src/index.ts deleted file mode 100644 index 92f1bbee41..0000000000 --- a/packages/examples/packages/browserify/src/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { - MethodNotFoundError, - type OnRpcRequestHandler, -} from '@metamask/snaps-sdk'; - -/** - * Handle incoming JSON-RPC requests from the dapp, sent through the - * `wallet_invokeSnap` method. This handler handles a single method: - * - * - `hello`: Returns a static message, "Hello from the MetaMask Snaps CLI using - * Browserify!". This is just for demonstration purposes, showing that a snap - * can be built with the MetaMask Snaps CLI using Browserify. - * - * Note that Browserify is not recommended, and only exists for backwards - * compatibility with existing snaps. New snaps should be built with Webpack. - * - * @param params - The request parameters. - * @param params.request - The JSON-RPC request object. - * @returns The JSON-RPC response. - * @see https://docs.metamask.io/snaps/reference/exports/#onrpcrequest - */ -export const onRpcRequest: OnRpcRequestHandler = async ({ request }) => { - switch (request.method) { - case 'hello': - return 'Hello from the MetaMask Snaps CLI using Browserify!'; - - default: { - throw new MethodNotFoundError({ method: request.method }); - } - } -}; diff --git a/packages/examples/packages/browserify/tsconfig.json b/packages/examples/packages/browserify/tsconfig.json deleted file mode 100644 index 5fbf260065..0000000000 --- a/packages/examples/packages/browserify/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "resolveJsonModule": true, - "baseUrl": "./", - "composite": false - }, - "include": ["src", "snap.config.ts"] -} diff --git a/packages/examples/packages/wasm/snap.manifest.json b/packages/examples/packages/wasm/snap.manifest.json index 33c30330bb..1828ca557a 100644 --- a/packages/examples/packages/wasm/snap.manifest.json +++ b/packages/examples/packages/wasm/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/MetaMask/snaps.git" }, "source": { - "shasum": "HehP6oFGpT5GZKlzNTVsHCTeTOlBF1044VvfhQGOCEk=", + "shasum": "6MsBR6Q/fNzDp5dGRWhBZLIBYu4o31cZRTI9iIUdIn0=", "location": { "npm": { "filePath": "dist/bundle.js", diff --git a/packages/snaps-cli/CHANGELOG.md b/packages/snaps-cli/CHANGELOG.md index 94d74984b4..a0fbc2009c 100644 --- a/packages/snaps-cli/CHANGELOG.md +++ b/packages/snaps-cli/CHANGELOG.md @@ -7,6 +7,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Remove deprecated Browserify configuration ([#3313](https://github.com/MetaMask/snaps/pull/3313)) + - The Browserify bundler is no longer supported. Snaps using the Browserify + bundler will need to be migrated to the new configuration format based on + Webpack. + - The `bundler` option in the Snap configuration file was removed, and the CLI + will show an error if it's used in config. + - Several command line flags that were used to configure the Browserify + bundler were removed. + - Use the config file to provide these options instead. + - The removed options are: + - `--bundle` + - `--dist` + - `--eval` + - `--manifest` + - `--outfileName` + - `--root` + - `--sourceMaps` + - `--src` + - `--stripComments` + - `--suppressWarnings` + - `--transpilationMode` + - `--depsToTranspile` + - `--verboseErrors` + - `--writeManifest` + - `--serve` + ## [6.7.0] ### Added diff --git a/packages/snaps-cli/README.md b/packages/snaps-cli/README.md index c716737cac..d9379e6552 100644 --- a/packages/snaps-cli/README.md +++ b/packages/snaps-cli/README.md @@ -4,7 +4,7 @@ A CLI for developing MetaMask Snaps. ## Installation -Use Node.js `16.0.0` or later. +Use Node.js `18.16.0` or later. We recommend [nvm](https://github.com/nvm-sh/nvm) for managing Node.js versions. Install a dev dependency in your snap project using `yarn` or `npm`: @@ -25,22 +25,20 @@ Commands: mm-snap watch Build Snap on change [aliases: w] Options: - --version Show version number [boolean] - -c, --config Path to config file [string] - --verboseErrors Display original errors [deprecated] [boolean] - --suppressWarnings Whether to suppress warnings [deprecated] [boolean] - -h, --help Show help [boolean] + --version Show version number [boolean] + -c, --config Path to config file [string] + -h, --help Show help [boolean] Examples: - mm-snap build Build './src/index.js' as - './dist/bundle.js' - mm-snap build --config Build './src/index.js' as - ./snap.config.build.ts './dist/bundle.js' using the config - in './snap.config.build.ts' + mm-snap build Build './src/index.js' as './dist/bu + ndle.js' + mm-snap build --config ./snap.config.bui Build './src/index.js' as './dist/bu + ld.ts ndle.js' using the config in './snap + .config.build.ts' mm-snap manifest --fix Check the snap manifest, and fix any - errors + errors mm-snap watch --port 8000 The snap input file for changes, and - serve it on port 8000 + serve it on port 8000 mm-snap serve --port 8000 Serve the snap bundle on port 8000 ``` @@ -134,7 +132,6 @@ The file should be placed in the project root directory. ```javascript module.exports = { - bundler: 'webpack', // default: 'browserify' input: 'src/index.js', output: { path: 'dist', @@ -154,7 +151,6 @@ exports a `SnapConfig` type that can be used to type the configuration object. import type { SnapConfig } from '@metamask/snaps-cli'; const config: SnapConfig = { - bundler: 'webpack', // default: 'browserify' input: 'src/index.js', output: { path: 'dist', @@ -171,7 +167,6 @@ The configuration file should not be published. ### Options -- [`bundler`](#bundler) - [`input`](#input) - [`output`](#output) - [`output.path`](#outputpath) @@ -191,18 +186,6 @@ The configuration file should not be published. - [`experimental`](#experimental) - [`experimental.wasm`](#experimentalwasm) -#### `bundler` - -- Type: `"browserify"` | `"webpack"` -- Default: `"browserify"` - -The bundler to use. The MetaMask Snaps CLI supports both Browserify and -Webpack. For backwards compatibility, Browserify is the default, but we -recommend using Webpack. Browserify support will be removed in the future. - -This section describes the options for the Webpack bundler. For Browserify, -refer to the [legacy options](#legacy-options) section. - #### `input` - Type: `string` @@ -425,219 +408,3 @@ import program from './program.wasm'; // Program is initialised synchronously. // ... ``` - -### Legacy Options - -> **Warning**: Using the Browserify-based build system is deprecated, and will -> be removed in a future version. Please migrate to the Webpack-based build -> system. - -- [`bundler`](#bundler) -- [`cliOptions`](#clioptions) - - [`cliOptions.bundle`](#clioptionsbundle) - - [`cliOptions.dist`](#clioptionsdist) - - [`cliOptions.eval`](#clioptionseval) - - [`cliOptions.manifest`](#clioptionsmanifest) - - [`cliOptions.outfileName`](#clioptionsoutfilename) - - [`cliOptions.port`](#clioptionsport) - - [`cliOptions.root`](#clioptionsroot) - - [`cliOptions.sourceMaps`](#clioptionssourcemaps) - - [`cliOptions.src`](#clioptionssrc) - - [`cliOptions.stripComments`](#clioptionsstripcomments) - - [`cliOptions.transpilationMode`](#clioptionstranspilationmode) - - [`cliOptions.depsToTranspile`](#clioptionsdepstotranspile) - - [`cliOptions.writeManifest`](#clioptionswritemanifest) - - [`cliOptions.serve`](#clioptionsserve) - - [`cliOptions.verboseErrors`](#clioptionsverboseerrors) - - [`cliOptions.suppressWarnings`](#clioptionssuppresswarnings) -- [`bundlerCustomizer`](#bundlercustomizer) - -#### `bundler` - -- Type: `"browserify"` | `"webpack"` -- Default: `"browserify"` - -The bundler to use. The MetaMask Snaps CLI supports both Browserify and -Webpack. For backwards compatibility, Browserify is the default, but we -recommend using Webpack. Browserify support will be removed in the future. - -This section describes the options for the Browserify bundler. For Webpack, -refer to the [options](#options) section. - -#### `cliOptions` - -- Type: `object` - -The CLI options. These can be specified using the CLI, but can also be -specified in the configuration file. For example, the `--port` option can be -specified in the configuration file as follows: - -```ts -export default { - cliOptions: { - port: 8081, - }, -}; -``` - -But can also be specified using the CLI: - -```bash -$ mm-snap serve --port 8081 -``` - -If the same option is specified in both the configuration file and the CLI, -the CLI option takes precedence. - -##### `cliOptions.bundle` - -- Type: `string` -- Default: `dist/bundle.js` - -The path to the bundle file. This is where the bundle will be written to. - -##### `cliOptions.dist` - -- Type: `string` -- Default: `dist` - -The path to the distribution directory. This is where the bundle file will be -written to, if the `bundle` option is not specified. - -##### `cliOptions.eval` - -- Type: `boolean` -- Default: `true` - -Whether to evaluate the bundle. If `true`, the bundle will be evaluated in the -MetaMask Snaps runtime, to check for any compatibility issues. - -##### `cliOptions.manifest` - -- Type: `boolean` -- Default: `true` - -Whether to validate the snap manifest. If `true`, the snap manifest will be -validated, and any errors or warnings will be shown. - -##### `cliOptions.outfileName` - -- Type: `string` -- Default: `bundle.js` - -The name of the bundle file. This is used to generate the bundle file path, -using the `dist` option. For example, if `dist` is `dist`, and `outfileName` -is `bundle.js`, the bundle file path will be `dist/bundle.js`. This option is -ignored if the `bundle` option is specified. - -##### `cliOptions.port` - -- Type: `number` -- Default: `8081` - -The port to use for the development server. - -##### `cliOptions.root` - -- Type: `string` -- Default: `.` - -The root directory. This should be the directory that contains the snap -manifest, and the `dist` directory. This will be served by the development -server. - -##### `cliOptions.sourceMaps` - -- Type: `boolean` -- Default: `false` - -Whether to generate source maps. If `true`, source maps will be generated for -the bundle. - -##### `cliOptions.src` - -- Type: `string` -- Default: `src/index.js` - -The path to the entry file. This is the file that will be bundled. - -##### `cliOptions.stripComments` - -- Type: `boolean` -- Default: `true` - -Whether to strip comments from the bundle. If `true`, comments will be stripped -from the bundle, and the bundle will be minified. - -##### `cliOptions.transpilationMode` - -- Type: `'localAndDeps' | 'localOnly' | 'none'` -- Default: `'localOnly'` - -The transpilation mode to use. This determines which files will be transpiled -by Babel. The possible values are: - -- `'localAndDeps'`: Transpile all files, including dependencies. -- `'localOnly'`: Transpile only local files. -- `'none'`: Do not transpile any files. - -##### `cliOptions.depsToTranspile` - -- Type: `string[]` -- Default: `[]` - -If `transpilationMode` is `'localAndDeps'`, this option can be used to specify -which dependencies should be transpiled. This is useful if you want to transpile -a limited set of dependencies, but not all of them. - -##### `cliOptions.writeManifest` - -- Type: `boolean` -- Default: `true` - -Whether to write the snap manifest. If `true`, the snap manifest will be written -with any changes made by the CLI, if the manifest is invalid. - -##### `cliOptions.serve` - -- Type: `boolean` -- Default: `true` - -Whether to serve the snap. If `true`, the snap will be served by the development -server, when running `mm-snap watch`. - -##### `cliOptions.suppressWarnings` - -- Type: `boolean` -- Default: `false` - -This option exists for backwards compatibility, and is ignored. - -##### `cliOptions.verboseErrors` - -- Type: `boolean` -- Default: `false` - -This option exists for backwards compatibility, and is ignored. - -#### `bundlerCustomizer` - -- Type: `(bundler: BrowserifyObject) => void` - -A function that customizes the bundler. This function is called after the -bundler is created, but before the bundle is written to disk. This can be used -to customize the bundler, for example to add plugins or transforms. - -```typescript -import type { SnapConfig } from '@metamask/snaps-cli'; -import type { BrowserifyObject } from 'browserify'; - -const config: SnapConfig = { - bundlerCustomizer: (bundler: BrowserifyObject) => { - // Add the BRFS transform to Browserify. - bundler.transform('brfs'); - }, -}; - -export default config; -``` diff --git a/packages/snaps-cli/package.json b/packages/snaps-cli/package.json index fb72dbd1ff..6cadb72387 100644 --- a/packages/snaps-cli/package.json +++ b/packages/snaps-cli/package.json @@ -35,7 +35,7 @@ "module": "./dist/index.mjs", "types": "./dist/index.d.cts", "bin": { - "mm-snap": "./dist/main.cjs" + "mm-snap": "./dist/main.mjs" }, "files": [ "dist", @@ -43,7 +43,7 @@ ], "scripts": { "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references", - "build:chmod": "chmod +x ./dist/main.mjs && chmod +x ./dist/main.js", + "build:chmod": "chmod +x ./dist/main.mjs && chmod +x ./dist/main.cjs", "build:post": "yarn build:chmod && yarn build:readme", "build:readme": "node ./scripts/updateReadme.js", "build:watch": "tsc-watch --onSuccess 'yarn build:chmod'", @@ -64,14 +64,6 @@ "test:watch": "jest --watch" }, "dependencies": { - "@babel/core": "^7.23.2", - "@babel/plugin-transform-class-properties": "^7.22.5", - "@babel/plugin-transform-class-static-block": "^7.22.11", - "@babel/plugin-transform-private-methods": "^7.22.5", - "@babel/plugin-transform-private-property-in-object": "^7.22.11", - "@babel/plugin-transform-runtime": "^7.13.2", - "@babel/preset-env": "^7.23.2", - "@babel/preset-typescript": "^7.23.2", "@metamask/snaps-sdk": "workspace:^", "@metamask/snaps-utils": "workspace:^", "@metamask/snaps-webpack-plugin": "workspace:^", @@ -79,8 +71,6 @@ "@metamask/utils": "^11.2.0", "@swc/core": "1.3.78", "assert": "^2.0.0", - "babelify": "^10.0.0", - "browserify": "^17.0.0", "browserify-zlib": "^0.2.0", "buffer": "^6.0.3", "chalk": "^4.1.2", @@ -121,7 +111,6 @@ "@metamask/auto-changelog": "^5.0.1", "@swc/jest": "^0.2.26", "@ts-bridge/cli": "^0.6.1", - "@types/browserify": "^12.0.37", "@types/jest": "^27.5.1", "@types/node": "18.14.2", "@types/serve-handler": "^6.1.0", diff --git a/packages/snaps-cli/scripts/updateReadme.js b/packages/snaps-cli/scripts/updateReadme.js index 69b289fa24..d64c73110c 100644 --- a/packages/snaps-cli/scripts/updateReadme.js +++ b/packages/snaps-cli/scripts/updateReadme.js @@ -13,7 +13,7 @@ main(); * `mm-snap --help`. */ async function main() { - const binPath = path.join(__dirname, '../dist/main.js'); + const binPath = path.join(__dirname, '../dist/main.mjs'); const readmePath = path.join(__dirname, '../README.md'); const currentReadme = await fs.readFile(readmePath, 'utf8'); diff --git a/packages/snaps-cli/src/__fixtures__/configs/javascript/snap.config.js b/packages/snaps-cli/src/__fixtures__/configs/javascript/snap.config.js index 5b7a94be11..7927c82cda 100644 --- a/packages/snaps-cli/src/__fixtures__/configs/javascript/snap.config.js +++ b/packages/snaps-cli/src/__fixtures__/configs/javascript/snap.config.js @@ -2,7 +2,6 @@ * @type {import('@metamask/snaps-cli').SnapConfig} */ const config = { - bundler: 'webpack', input: 'src/index.js', }; diff --git a/packages/snaps-cli/src/__mocks__/fs.ts b/packages/snaps-cli/src/__mocks__/fs.ts index e99b4338ba..273448b24a 100644 --- a/packages/snaps-cli/src/__mocks__/fs.ts +++ b/packages/snaps-cli/src/__mocks__/fs.ts @@ -3,20 +3,4 @@ import { createFsFromVolume, Volume } from 'memfs'; // Note: `Volume` implements most of the `fs` API, but not all. const volume = new Volume(); -const { join, dirname } = jest.requireActual('path'); - -// Browserify is trying to read some files when it's being imported, so we need -// to provide the files it's looking for. -const BROWSERIFY_FILES = [ - /* eslint-disable n/no-extraneous-require */ - join(dirname(require.resolve('is-core-module/package.json')), 'core.json'), - join(dirname(require.resolve('browser-pack/package.json')), '_prelude.js'), - /* eslint-enable n/no-extraneous-require */ -]; - -for (const file of BROWSERIFY_FILES) { - volume.mkdirSync(dirname(file), { recursive: true }); - volume.writeFileSync(file, jest.requireActual('fs').readFileSync(file)); -} - export = createFsFromVolume(volume); diff --git a/packages/snaps-cli/src/builders.ts b/packages/snaps-cli/src/builders.ts index 00020e40bf..61034587ef 100644 --- a/packages/snaps-cli/src/builders.ts +++ b/packages/snaps-cli/src/builders.ts @@ -1,11 +1,5 @@ import type { Options } from 'yargs'; -export enum TranspilationModes { - LocalAndDeps = 'localAndDeps', - LocalOnly = 'localOnly', - None = 'none', -} - const builders = { analyze: { describe: 'Analyze the Snap bundle', @@ -31,37 +25,6 @@ const builders = { normalize: true, }, - // Deprecated Browserify options. - bundle: { - alias: 'b', - describe: 'Snap bundle file', - type: 'string', - normalize: true, - deprecated: 'Use --input instead.', - }, - - dist: { - alias: 'd', - describe: 'Output directory', - type: 'string', - normalize: true, - deprecated: true, - }, - - eval: { - alias: 'e', - describe: 'Attempt to evaluate Snap bundle in SES', - type: 'boolean', - deprecated: true, - }, - - manifest: { - alias: 'm', - describe: 'Validate snap.manifest.json', - type: 'boolean', - deprecated: true, - }, - port: { alias: 'p', describe: 'Local server port for testing', @@ -74,81 +37,6 @@ const builders = { return port; }, - deprecated: true, - }, - - outfileName: { - alias: 'n', - describe: 'Output file name', - type: 'string', - deprecated: true, - }, - - root: { - alias: 'r', - describe: 'Server root directory', - type: 'string', - normalize: true, - deprecated: true, - }, - - sourceMaps: { - describe: 'Whether builds include sourcemaps', - type: 'boolean', - deprecated: true, - }, - - src: { - alias: 's', - describe: 'Source file', - type: 'string', - normalize: true, - deprecated: true, - }, - - stripComments: { - alias: 'strip', - describe: 'Whether to remove code comments from the build output', - type: 'boolean', - deprecated: true, - }, - - suppressWarnings: { - type: 'boolean', - describe: 'Whether to suppress warnings', - deprecated: true, - }, - - transpilationMode: { - type: 'string', - describe: - 'Whether to use Babel to transpile all source code (including dependencies), local source code only, or nothing', - choices: Object.values(TranspilationModes), - deprecated: true, - }, - - depsToTranspile: { - type: 'array', - describe: 'Transpile only the listed dependencies.', - deprecated: true, - }, - - verboseErrors: { - type: 'boolean', - describe: 'Display original errors', - deprecated: true, - }, - - writeManifest: { - describe: 'Make necessary changes to the snap manifest file', - type: 'boolean', - deprecated: true, - }, - - serve: { - describe: 'Serve snap file(s) locally for testing', - type: 'boolean', - deprecated: true, }, } as const satisfies Record>; diff --git a/packages/snaps-cli/src/cli.ts b/packages/snaps-cli/src/cli.ts index c26f5eb875..7422c4fade 100644 --- a/packages/snaps-cli/src/cli.ts +++ b/packages/snaps-cli/src/cli.ts @@ -57,8 +57,6 @@ export async function cli(argv: string[], commands: any) { .command(commands) .option('config', builders.config) - .option('verboseErrors', builders.verboseErrors) - .option('suppressWarnings', builders.suppressWarnings) .strict() diff --git a/packages/snaps-cli/src/commands/build/build.e2e.test.ts b/packages/snaps-cli/src/commands/build/build.e2e.test.ts index ebde010bcc..4c3782984b 100644 --- a/packages/snaps-cli/src/commands/build/build.e2e.test.ts +++ b/packages/snaps-cli/src/commands/build/build.e2e.test.ts @@ -2,28 +2,13 @@ import { promises as fs } from 'fs'; import { join } from 'path'; import type { TestRunner } from '../../test-utils'; -import { getCommandRunner, SNAP_BROWSERIFY_DIR } from '../../test-utils'; +import { getCommandRunner } from '../../test-utils'; describe('mm-snap build', () => { let runner: TestRunner; - let originalManifest: string; - - beforeEach(async () => { - // Since this is an end-to-end test, and we're working with a "real" snap, - // we have to make a copy of the original snap manifest, so we can modify it - // and reset it after the test. - originalManifest = await fs.readFile( - join(SNAP_BROWSERIFY_DIR, 'snap.manifest.json'), - 'utf-8', - ); - }); afterEach(async () => { runner?.kill(); - await fs.writeFile( - join(SNAP_BROWSERIFY_DIR, 'snap.manifest.json'), - originalManifest, - ); }); it.each(['build', 'b'])( @@ -54,33 +39,4 @@ describe('mm-snap build', () => { expect(runner.exitCode).toBe(0); }, ); - - it.each(['build', 'b'])( - 'builds a snap using "mm-snap %s" using a legacy config', - async (command) => { - runner = getCommandRunner(command, [], SNAP_BROWSERIFY_DIR); - await runner.wait(); - - expect(runner.stdout).toContainEqual( - expect.stringMatching(/Checking the input file\./u), - ); - expect(runner.stdout).toContainEqual( - expect.stringMatching(/Building the snap bundle\./u), - ); - expect(runner.stderr).toContainEqual( - expect.stringMatching( - /Compiled \d+ files? in \d+ms with \d+ warnings?\./u, - ), - ); - expect(runner.stderr).toContainEqual( - expect.stringContaining( - 'No icon found in the Snap manifest. It is recommended to include an icon for the Snap. See https://docs.metamask.io/snaps/how-to/design-a-snap/#guidelines-at-a-glance for more information.', - ), - ); - expect(runner.stdout).toContainEqual( - expect.stringMatching(/Evaluating the snap bundle\./u), - ); - expect(runner.exitCode).toBe(0); - }, - ); }); diff --git a/packages/snaps-cli/src/commands/build/build.test.ts b/packages/snaps-cli/src/commands/build/build.test.ts index 655d4901ac..6817e8bdac 100644 --- a/packages/snaps-cli/src/commands/build/build.test.ts +++ b/packages/snaps-cli/src/commands/build/build.test.ts @@ -21,7 +21,7 @@ describe('buildHandler', () => { await fs.promises.writeFile('/input.js', DEFAULT_SNAP_BUNDLE); jest.spyOn(console, 'log').mockImplementation(); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', output: { path: '/foo', @@ -47,7 +47,7 @@ describe('buildHandler', () => { await fs.promises.writeFile('/input.js', DEFAULT_SNAP_BUNDLE); jest.spyOn(console, 'log').mockImplementation(); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', output: { path: '/foo', @@ -94,7 +94,7 @@ describe('buildHandler', () => { await fs.promises.writeFile('/input.js', DEFAULT_SNAP_BUNDLE); jest.spyOn(console, 'log').mockImplementation(); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', output: { path: '/foo', @@ -112,7 +112,7 @@ describe('buildHandler', () => { it('checks if the input file exists', async () => { const log = jest.spyOn(console, 'error').mockImplementation(); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'fake-input-file.js', }); diff --git a/packages/snaps-cli/src/commands/build/build.ts b/packages/snaps-cli/src/commands/build/build.ts index a9b26bd74f..94de1ef689 100644 --- a/packages/snaps-cli/src/commands/build/build.ts +++ b/packages/snaps-cli/src/commands/build/build.ts @@ -4,7 +4,7 @@ import { resolve as pathResolve } from 'path'; import { build } from './implementation'; import { getBundleAnalyzerPort } from './utils'; -import type { ProcessedConfig, ProcessedWebpackConfig } from '../../config'; +import type { ProcessedConfig } from '../../config'; import { CommandError } from '../../errors'; import type { Steps } from '../../utils'; import { success, executeSteps, info } from '../../utils'; @@ -12,7 +12,7 @@ import { evaluate } from '../eval'; type BuildContext = { analyze: boolean; - config: ProcessedWebpackConfig; + config: ProcessedConfig; port?: number; }; diff --git a/packages/snaps-cli/src/commands/build/implementation.test.ts b/packages/snaps-cli/src/commands/build/implementation.test.ts index fcc06c5b30..178981d396 100644 --- a/packages/snaps-cli/src/commands/build/implementation.test.ts +++ b/packages/snaps-cli/src/commands/build/implementation.test.ts @@ -20,11 +20,6 @@ import { BROWSERSLIST_FILE } from '../../webpack/utils'; const { promises: fs } = normalFs; -const BROWSERIFY_LOADER_PATH = resolve( - __dirname, - '../../webpack/loaders/browserify.ts', -); - jest.mock('fs'); jest.mock('../../webpack', () => ({ @@ -52,15 +47,7 @@ jest.mock('../../webpack/utils', () => ({ getDefaultLoader: jest.fn< ReturnType, Parameters - // @ts-expect-error: Type mismatch. >(async (config) => { - if (config.legacy) { - return { - loader: BROWSERIFY_LOADER_PATH, - options: config.legacy, - }; - } - return jest .requireActual('../../webpack/utils') .getDefaultLoader(config); @@ -91,14 +78,6 @@ describe('build', () => { .requireActual('fs') .promises.readFile(BROWSERSLIST_FILE), ); - - await fs.mkdir(dirname(BROWSERIFY_LOADER_PATH), { recursive: true }); - await fs.writeFile( - BROWSERIFY_LOADER_PATH, - await jest - .requireActual('fs') - .promises.readFile(BROWSERIFY_LOADER_PATH), - ); }); afterEach(async () => { @@ -109,7 +88,7 @@ describe('build', () => { jest.spyOn(process, 'cwd').mockReturnValue('/snap'); const warn = jest.spyOn(console, 'warn').mockImplementation(); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/snap/input.js', output: { path: './', @@ -142,7 +121,7 @@ describe('build', () => { jest.spyOn(process, 'cwd').mockReturnValue('/snap'); const warn = jest.spyOn(console, 'warn').mockImplementation(); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/snap/input.js', output: { path: './', @@ -201,150 +180,6 @@ describe('build', () => { `); }); - it('builds the snap bundle using a legacy config', async () => { - jest.spyOn(process, 'cwd').mockReturnValue('/snap'); - const warn = jest.spyOn(console, 'warn').mockImplementation(); - - const config = getMockConfig('browserify', { - cliOptions: { - src: '/snap/input.js', - dist: '/snap', - outfileName: 'output.js', - eval: false, - }, - }); - - await build(config); - - // Manifest checksum mismatch is the warning - expect(warn).toHaveBeenCalledWith( - expect.stringMatching(/Compiled 1 file in \d+ms with 1 warning\./u), - ); - - const output = await fs.readFile('/snap/output.js', 'utf8'); - - // Browserify output is non-deterministic across different platforms (e.g., - // Windows vs. Linux), so we normalize it to make the snapshot - // deterministic. - const deterministicOutput = output - .replace(/var r=\{(\d+):/u, 'var r={1:') - .replace( - /u.exports\}\(\d+\);module.exports/u, - 'u.exports}(1);module.exports', - ); - - expect(deterministicOutput).toMatchInlineSnapshot( - `"(()=>{var r={1:r=>{r.exports=function(){function r(o,t,e){function n(s,i){if(!t[s]){if(!o[s]){if(u)return u(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var f=t[s]={exports:{}};o[s][0].call(f.exports,(function(r){return n(o[s][1][r]||r)}),f,f.exports,r,o,t,e)}return t[s].exports}for(var u=void 0,s=0;s{console.log("Hello, world!");const{method:o,id:t}=r;return o+t}},{}]},{},[1])(1)}},o={};var t=function t(e){var n=o[e];if(void 0!==n)return n.exports;var u=o[e]={exports:{}};return r[e](u,u.exports,t),u.exports}(1);module.exports=t})();"`, - ); - }); - - it('builds an unminimized snap bundle using a legacy config', async () => { - jest.spyOn(process, 'cwd').mockReturnValue('/snap'); - const warn = jest.spyOn(console, 'warn').mockImplementation(); - - const config = getMockConfig('browserify', { - cliOptions: { - src: '/snap/input.js', - dist: '/snap', - outfileName: 'output.js', - eval: false, - stripComments: false, - }, - }); - - await build(config); - - // Manifest checksum mismatch is the warning - expect(warn).toHaveBeenCalledWith( - expect.stringMatching(/Compiled 1 file in \d+ms with 1 warning\./u), - ); - - const output = await fs.readFile('/snap/output.js', 'utf8'); - - // Browserify output is non-deterministic across different platforms (e.g., - // Windows vs. Linux), so we normalize it to make the snapshot - // deterministic. - const deterministicOutput = output - .replace(/\d+: module/u, '1: module') - .replace( - /var __webpack_exports__ = __webpack_require__\(\d+\);/u, - 'var __webpack_exports__ = __webpack_require__(1);', - ); - - expect(deterministicOutput).toMatchInlineSnapshot(` - "(() => { - var __webpack_modules__ = { - 1: module => { - (function (f) { - if (true) { - module.exports = f(); - } else { - var g; - } - })(function () { - var define, module, exports; - return function () { - function r(e, n, t) { - function o(i, f) { - if (!n[i]) { - if (!e[i]) { - var c = undefined; - if (!f && c) return require(i, !0); - if (u) return u(i, !0); - var a = new Error("Cannot find module '" + i + "'"); - throw a.code = "MODULE_NOT_FOUND", a; - } - var p = n[i] = { - exports: {} - }; - e[i][0].call(p.exports, function (r) { - var n = e[i][1][r]; - return o(n || r); - }, p, p.exports, r, e, n, t); - } - return n[i].exports; - } - for (var u = undefined, i = 0; i < t.length; i++) o(t[i]); - return o; - } - return r; - }()({ - 1: [function (require, module, exports) { - "use strict"; - - module.exports.onRpcRequest = ({ - request - }) => { - console.log("Hello, world!"); - const { - method, - id - } = request; - return method + id; - }; - }, {}] - }, {}, [1])(1); - }); - } - }; - var __webpack_module_cache__ = {}; - function __webpack_require__(moduleId) { - var cachedModule = __webpack_module_cache__[moduleId]; - if (cachedModule !== undefined) { - return cachedModule.exports; - } - var module = __webpack_module_cache__[moduleId] = { - exports: {} - }; - __webpack_modules__[moduleId](module, module.exports, __webpack_require__); - return module.exports; - } - var __webpack_exports__ = __webpack_require__(1); - module.exports = __webpack_exports__; - })();" - `); - }); - it('rejects if the compiler has an error', async () => { const error = new Error('Compiler error.'); const mock = getCompiler as jest.MockedFunction; @@ -355,7 +190,7 @@ describe('build', () => { }), })); - await expect(build(getMockConfig('webpack'))).rejects.toThrow(error); + await expect(build(getMockConfig())).rejects.toThrow(error); }); it('rejects if closing the compiler has an error', async () => { @@ -371,6 +206,6 @@ describe('build', () => { }), })); - await expect(build(getMockConfig('webpack'))).rejects.toThrow(error); + await expect(build(getMockConfig())).rejects.toThrow(error); }); }); diff --git a/packages/snaps-cli/src/commands/build/implementation.ts b/packages/snaps-cli/src/commands/build/implementation.ts index 07ed9b9655..457373e3a5 100644 --- a/packages/snaps-cli/src/commands/build/implementation.ts +++ b/packages/snaps-cli/src/commands/build/implementation.ts @@ -1,6 +1,6 @@ import type { Compiler } from 'webpack'; -import type { ProcessedWebpackConfig } from '../../config'; +import type { ProcessedConfig } from '../../config'; import type { WebpackOptions } from '../../webpack'; import { getCompiler } from '../../webpack'; @@ -12,7 +12,7 @@ import { getCompiler } from '../../webpack'; * @returns A promise that resolves when the bundle is built. */ export async function build( - config: ProcessedWebpackConfig, + config: ProcessedConfig, options?: WebpackOptions, ) { const compiler = await getCompiler(config, options); diff --git a/packages/snaps-cli/src/commands/build/index.test.ts b/packages/snaps-cli/src/commands/build/index.test.ts index a400072577..5ac62ef546 100644 --- a/packages/snaps-cli/src/commands/build/index.test.ts +++ b/packages/snaps-cli/src/commands/build/index.test.ts @@ -7,7 +7,7 @@ jest.mock('./build'); describe('build command', () => { it('calls the `buildHandler` function', async () => { - const config = getMockConfig('webpack'); + const config = getMockConfig(); // @ts-expect-error - Partial `YargsArgs` is fine for testing. await command.handler({ analyze: false, context: { config } }); diff --git a/packages/snaps-cli/src/commands/build/index.ts b/packages/snaps-cli/src/commands/build/index.ts index 1f80fa35fe..60058a97ae 100644 --- a/packages/snaps-cli/src/commands/build/index.ts +++ b/packages/snaps-cli/src/commands/build/index.ts @@ -10,18 +10,6 @@ const command = { builder: (yarg: yargs.Argv) => { yarg .option('analyze', builders.analyze) - .option('dist', builders.dist) - .option('eval', builders.eval) - .option('manifest', builders.manifest) - .option('outfileName', builders.outfileName) - .option('sourceMaps', builders.sourceMaps) - .option('src', builders.src) - .option('stripComments', builders.stripComments) - .option('transpilationMode', builders.transpilationMode) - .option('depsToTranspile', builders.depsToTranspile) - .option('writeManifest', builders.writeManifest) - .implies('writeManifest', 'manifest') - .implies('depsToTranspile', 'transpilationMode'); }, handler: async (argv: YargsArgs) => buildHandler(argv.context.config, argv.analyze), diff --git a/packages/snaps-cli/src/commands/eval/__test__/browserify/bad/eval.js b/packages/snaps-cli/src/commands/eval/__test__/browserify/bad/eval.js deleted file mode 100644 index 1cf39775e8..0000000000 --- a/packages/snaps-cli/src/commands/eval/__test__/browserify/bad/eval.js +++ /dev/null @@ -1,3 +0,0 @@ -// This file is used for the E2E eval test. - -throw new Error('Eval failed.'); diff --git a/packages/snaps-cli/src/commands/eval/__test__/browserify/bad/snap.config.ts b/packages/snaps-cli/src/commands/eval/__test__/browserify/bad/snap.config.ts deleted file mode 100644 index ae94d821ef..0000000000 --- a/packages/snaps-cli/src/commands/eval/__test__/browserify/bad/snap.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { SnapConfig } from '../../../../../config'; - -const config: SnapConfig = { - bundler: 'browserify', - cliOptions: { - bundle: './eval.js', - }, -}; - -export default config; diff --git a/packages/snaps-cli/src/commands/eval/__test__/browserify/good/eval.js b/packages/snaps-cli/src/commands/eval/__test__/browserify/good/eval.js deleted file mode 100644 index ee1f86fe2c..0000000000 --- a/packages/snaps-cli/src/commands/eval/__test__/browserify/good/eval.js +++ /dev/null @@ -1,127 +0,0 @@ -/* eslint-disable */ -// This file is used for the E2E eval test. - -(function (f) { - if (typeof exports === 'object' && typeof module !== 'undefined') { - module.exports = f(); - } else if (typeof define === 'function' && define.amd) { - define([], f); - } else { - let g; - if (typeof window !== 'undefined') { - g = window; - } else if (typeof global !== 'undefined') { - g = global; - } else if (typeof self !== 'undefined') { - g = self; - } else { - g = this; - } - g.snap = f(); - } -})(function () { - let define, module, exports; - return (function () { - /** - * - * @param e - * @param n - * @param t - */ - function r(e, n, t) { - /** - * - * @param i - * @param f - */ - function o(i, f) { - if (!n[i]) { - if (!e[i]) { - const c = typeof require === 'function' && require; - if (!f && c) { - return c(i, !0); - } - if (u) { - return u(i, !0); - } - const a = new Error(`Cannot find module '${i}'`); - throw ((a.code = 'MODULE_NOT_FOUND'), a); - } - const p = (n[i] = { - exports: {}, - }); - e[i][0].call( - p.exports, - function (r) { - const n = e[i][1][r]; - return o(n || r); - }, - p, - p.exports, - r, - e, - n, - t, - ); - } - return n[i].exports; - } - for ( - var u = typeof require === 'function' && require, i = 0; - i < t.length; - i++ - ) { - o(t[i]); - } - return o; - } - return r; - })()( - { - 1: [ - function (require, module, exports) { - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true, - }); - exports.onRpcRequest = void 0; - const _message = require('./message'); - const onRpcRequest = async ({ origin, request }) => { - switch (request.method) { - case 'hello': - return await snap.request({ - method: 'snap_notify', - params: { - type: 'inapp', - message: (0, _message.getMessage)(origin), - }, - }); - default: - throw new Error('Method not found.'); - } - }; - exports.onRpcRequest = onRpcRequest; - }, - { - './message': 2, - }, - ], - 2: [ - function (require, module, exports) { - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true, - }); - exports.getMessage = void 0; - const getMessage = (originString) => `Hello, ${originString}!`; - exports.getMessage = getMessage; - }, - {}, - ], - }, - {}, - [1], - )(1); -}); diff --git a/packages/snaps-cli/src/commands/eval/__test__/browserify/good/snap.config.ts b/packages/snaps-cli/src/commands/eval/__test__/browserify/good/snap.config.ts deleted file mode 100644 index ae94d821ef..0000000000 --- a/packages/snaps-cli/src/commands/eval/__test__/browserify/good/snap.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { SnapConfig } from '../../../../../config'; - -const config: SnapConfig = { - bundler: 'browserify', - cliOptions: { - bundle: './eval.js', - }, -}; - -export default config; diff --git a/packages/snaps-cli/src/commands/eval/__test__/webpack/bad/snap.config.ts b/packages/snaps-cli/src/commands/eval/__test__/webpack/bad/snap.config.ts index 2aaa1f3480..c36bc9657b 100644 --- a/packages/snaps-cli/src/commands/eval/__test__/webpack/bad/snap.config.ts +++ b/packages/snaps-cli/src/commands/eval/__test__/webpack/bad/snap.config.ts @@ -1,7 +1,6 @@ import type { SnapConfig } from '../../../../../config'; const config: SnapConfig = { - bundler: 'webpack', input: 'src/index.ts', output: { path: __dirname, diff --git a/packages/snaps-cli/src/commands/eval/__test__/webpack/good/snap.config.ts b/packages/snaps-cli/src/commands/eval/__test__/webpack/good/snap.config.ts index 2aaa1f3480..c36bc9657b 100644 --- a/packages/snaps-cli/src/commands/eval/__test__/webpack/good/snap.config.ts +++ b/packages/snaps-cli/src/commands/eval/__test__/webpack/good/snap.config.ts @@ -1,7 +1,6 @@ import type { SnapConfig } from '../../../../../config'; const config: SnapConfig = { - bundler: 'webpack', input: 'src/index.ts', output: { path: __dirname, diff --git a/packages/snaps-cli/src/commands/eval/__test__/webpack/snap.config.ts b/packages/snaps-cli/src/commands/eval/__test__/webpack/snap.config.ts index e5bbbdc949..03589b4df9 100644 --- a/packages/snaps-cli/src/commands/eval/__test__/webpack/snap.config.ts +++ b/packages/snaps-cli/src/commands/eval/__test__/webpack/snap.config.ts @@ -1,7 +1,6 @@ import type { SnapConfig } from '../../../../config'; const config: SnapConfig = { - bundler: 'webpack', input: 'src/index.ts', }; diff --git a/packages/snaps-cli/src/commands/eval/eval.e2e.test.ts b/packages/snaps-cli/src/commands/eval/eval.e2e.test.ts index 47f7d2f972..7625b28d09 100644 --- a/packages/snaps-cli/src/commands/eval/eval.e2e.test.ts +++ b/packages/snaps-cli/src/commands/eval/eval.e2e.test.ts @@ -1,7 +1,8 @@ -import type { TestRunner } from '@metamask/snaps-cli/test-utils'; -import { getCommandRunner } from '@metamask/snaps-cli/test-utils'; import { resolve } from 'path'; +import type { TestRunner } from '../../test-utils'; +import { getCommandRunner } from '../../test-utils'; + describe('mm-snap eval', () => { let runner: TestRunner; @@ -12,44 +13,31 @@ describe('mm-snap eval', () => { it.each([ { command: 'eval', - bundler: 'webpack', - }, - { - command: 'e', - bundler: 'webpack', - }, - { - command: 'eval', - bundler: 'browserify', }, { command: 'e', - bundler: 'browserify', }, - ])( - 'evaluates a $bundler snap using "mm-snap $command"', - async ({ command, bundler }) => { - runner = getCommandRunner( - command, - [], - resolve(__dirname, '__test__', bundler, 'good'), - ); + ])('evaluates a snap using "mm-snap $command"', async ({ command }) => { + runner = getCommandRunner( + command, + [], + resolve(__dirname, '__test__', 'webpack', 'good'), + ); - await runner.wait(); + await runner.wait(); - expect(runner.stderr).toStrictEqual([]); - expect(runner.stdout).toContainEqual( - expect.stringMatching(/Checking the input file\./u), - ); - expect(runner.stdout).toContainEqual( - expect.stringMatching(/Evaluating the snap bundle\./u), - ); - expect(runner.stdout).toContainEqual( - expect.stringMatching(/Snap bundle evaluated successfully\./u), - ); - expect(runner.exitCode).toBe(0); - }, - ); + expect(runner.stderr).toStrictEqual([]); + expect(runner.stdout).toContainEqual( + expect.stringMatching(/Checking the input file\./u), + ); + expect(runner.stdout).toContainEqual( + expect.stringMatching(/Evaluating the snap bundle\./u), + ); + expect(runner.stdout).toContainEqual( + expect.stringMatching(/Snap bundle evaluated successfully\./u), + ); + expect(runner.exitCode).toBe(0); + }); it.each(['eval', 'e'])( 'evaluates a snap using "mm-snap %s --input eval.js"', diff --git a/packages/snaps-cli/src/commands/eval/eval.test.ts b/packages/snaps-cli/src/commands/eval/eval.test.ts index 09f3af65bf..1af0fce494 100644 --- a/packages/snaps-cli/src/commands/eval/eval.test.ts +++ b/packages/snaps-cli/src/commands/eval/eval.test.ts @@ -1,10 +1,10 @@ -import { getMockConfig } from '@metamask/snaps-cli/test-utils'; import { DEFAULT_SNAP_BUNDLE } from '@metamask/snaps-utils/test-utils'; import { promises as fs } from 'fs'; import ora from 'ora'; import { evaluateHandler } from './eval'; import { evaluate } from './implementation'; +import { getMockConfig } from '../../test-utils'; jest.mock('fs'); jest.mock('./implementation'); @@ -19,7 +19,7 @@ describe('evaluateHandler', () => { jest.spyOn(process, 'cwd').mockReturnValue('/'); jest.spyOn(console, 'log').mockImplementation(); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', output: { path: '/foo', @@ -40,34 +40,11 @@ describe('evaluateHandler', () => { ); }); - it('evaluates the bundle using Browserify', async () => { - jest.spyOn(process, 'cwd').mockReturnValue('/'); - jest.spyOn(console, 'log').mockImplementation(); - - await evaluateHandler( - getMockConfig('browserify', { - cliOptions: { - bundle: '/foo/output.js', - }, - }), - ); - - expect(evaluate).toHaveBeenCalledWith( - expect.stringMatching(/.*output\.js.*/u), - ); - - const { mock } = ora as jest.MockedFunction; - const spinner = mock.results[0].value; - expect(spinner.succeed).toHaveBeenCalledWith( - 'Snap bundle evaluated successfully.', - ); - }); - it('evaluates the bundle using the --input flag', async () => { jest.spyOn(process, 'cwd').mockReturnValue('/'); jest.spyOn(console, 'log').mockImplementation(); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', output: { path: '/foo', @@ -92,7 +69,7 @@ describe('evaluateHandler', () => { jest.spyOn(process, 'cwd').mockReturnValue('/'); const log = jest.spyOn(console, 'error').mockImplementation(); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', output: { path: '/foo', @@ -116,7 +93,7 @@ describe('evaluateHandler', () => { const mock = evaluate as jest.MockedFunction; mock.mockRejectedValueOnce(new Error('Eval error.')); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', output: { path: '/foo', diff --git a/packages/snaps-cli/src/commands/eval/index.test.ts b/packages/snaps-cli/src/commands/eval/index.test.ts index 8065dbf32f..8428ff2450 100644 --- a/packages/snaps-cli/src/commands/eval/index.test.ts +++ b/packages/snaps-cli/src/commands/eval/index.test.ts @@ -7,7 +7,7 @@ jest.mock('./eval'); const getMockArgv = ({ bundle = 'dist/snap.js' } = {}) => { return { - context: { config: getMockConfig('webpack') }, + context: { config: getMockConfig() }, bundle, } as unknown as YargsArgs; }; diff --git a/packages/snaps-cli/src/commands/eval/index.ts b/packages/snaps-cli/src/commands/eval/index.ts index af3758131b..2c69f47fbe 100644 --- a/packages/snaps-cli/src/commands/eval/index.ts +++ b/packages/snaps-cli/src/commands/eval/index.ts @@ -8,10 +8,6 @@ const command = { command: ['eval', 'e'], desc: 'Attempt to evaluate snap bundle in SES', builder: (yarg: yargs.Argv) => { - // Browserify options. These are merged into the config object. - yarg.option('bundle', builders.bundle); - - // Webpack options. yarg.option('input', builders.input); }, handler: async (argv: YargsArgs) => diff --git a/packages/snaps-cli/src/commands/manifest/index.test.ts b/packages/snaps-cli/src/commands/manifest/index.test.ts index 237f234201..9c52a11c6e 100644 --- a/packages/snaps-cli/src/commands/manifest/index.test.ts +++ b/packages/snaps-cli/src/commands/manifest/index.test.ts @@ -7,7 +7,7 @@ jest.mock('./manifest'); const getMockArgv = () => { return { - context: { config: getMockConfig('webpack') }, + context: { config: getMockConfig() }, } as unknown as YargsArgs; }; diff --git a/packages/snaps-cli/src/commands/manifest/index.ts b/packages/snaps-cli/src/commands/manifest/index.ts index bf8a1308ca..6e107b3601 100644 --- a/packages/snaps-cli/src/commands/manifest/index.ts +++ b/packages/snaps-cli/src/commands/manifest/index.ts @@ -8,10 +8,6 @@ const command = { command: ['manifest', 'm'], desc: 'Validate the snap.manifest.json file', builder: (yarg: yargs.Argv) => { - // Browserify options. These are merged into the config object. - yarg.option('writeManifest', builders.writeManifest); - - // Webpack options. yarg.option('fix', builders.fix); }, handler: async (argv: YargsArgs) => diff --git a/packages/snaps-cli/src/commands/manifest/manifest.test.ts b/packages/snaps-cli/src/commands/manifest/manifest.test.ts index 7a18e20fa4..3bae2eb857 100644 --- a/packages/snaps-cli/src/commands/manifest/manifest.test.ts +++ b/packages/snaps-cli/src/commands/manifest/manifest.test.ts @@ -1,4 +1,3 @@ -import { getMockConfig } from '@metamask/snaps-cli/test-utils'; import { getSnapManifest } from '@metamask/snaps-utils/test-utils'; import { promises as fs } from 'fs'; import ora from 'ora'; @@ -6,6 +5,7 @@ import ora from 'ora'; import { manifest } from './implementation'; import * as implementation from './implementation'; import { manifestHandler } from './manifest'; +import { getMockConfig } from '../../test-utils'; jest.mock('fs'); jest.mock('./implementation'); @@ -22,7 +22,7 @@ describe('manifestHandler', () => { jest.spyOn(console, 'log').mockImplementation(); jest.spyOn(implementation, 'manifest').mockResolvedValue(true); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', manifest: { path: '/snap.manifest.json', @@ -45,11 +45,11 @@ describe('manifestHandler', () => { ); }); - it('fixes the manifest file when using Webpack', async () => { + it('fixes the manifest file', async () => { jest.spyOn(console, 'log').mockImplementation(); jest.spyOn(implementation, 'manifest').mockResolvedValue(true); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', manifest: { path: '/snap.manifest.json', @@ -74,37 +74,10 @@ describe('manifestHandler', () => { ); }); - it('fixes the manifest file when using Browserify', async () => { - jest.spyOn(process, 'cwd').mockReturnValue('/'); - jest.spyOn(console, 'log').mockImplementation(); - jest.spyOn(implementation, 'manifest').mockResolvedValue(true); - - const config = getMockConfig('browserify', { - cliOptions: { - writeManifest: true, - }, - }); - - await manifestHandler(config, {}); - - const { mock } = ora as jest.MockedFunction; - const spinner = mock.results[0].value; - - expect(manifest).toHaveBeenCalledWith( - expect.stringMatching(/.*snap\.manifest\.json.*/u), - true, - spinner, - ); - - expect(spinner.succeed).toHaveBeenCalledWith( - 'The snap manifest file is valid.', - ); - }); - it('logs a message if the manifest file does not exist', async () => { const log = jest.spyOn(console, 'error').mockImplementation(); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', manifest: { path: '/invalid.json', @@ -125,7 +98,7 @@ describe('manifestHandler', () => { jest.spyOn(console, 'log').mockImplementation(); jest.spyOn(implementation, 'manifest').mockResolvedValue(false); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', manifest: { path: '/snap.manifest.json', diff --git a/packages/snaps-cli/src/commands/manifest/manifest.ts b/packages/snaps-cli/src/commands/manifest/manifest.ts index d625a4c62c..48fc26fbe6 100644 --- a/packages/snaps-cli/src/commands/manifest/manifest.ts +++ b/packages/snaps-cli/src/commands/manifest/manifest.ts @@ -29,8 +29,8 @@ const steps: Steps = [ }, { name: 'Validating the snap manifest.', - task: async ({ input, config, options, spinner }) => { - const write = getWriteManifest(config, options); + task: async ({ input, options, spinner }) => { + const write = getWriteManifest(options); const valid = await manifest(input, write, spinner); if (valid) { @@ -43,16 +43,15 @@ const steps: Steps = [ /** * Get whether to write the manifest to disk. * - * @param config - The config object. * @param options - The options object. * @returns Whether to write the manifest to disk. */ -function getWriteManifest(config: ProcessedConfig, options: ManifestOptions) { +function getWriteManifest(options: ManifestOptions) { if (typeof options.fix === 'boolean') { return options.fix; } - return config.legacy?.writeManifest ?? false; + return false; } /** diff --git a/packages/snaps-cli/src/commands/serve/index.test.ts b/packages/snaps-cli/src/commands/serve/index.test.ts index d5c6ef56d0..f17700edd4 100644 --- a/packages/snaps-cli/src/commands/serve/index.test.ts +++ b/packages/snaps-cli/src/commands/serve/index.test.ts @@ -7,7 +7,7 @@ jest.mock('./serve'); const getMockArgv = () => { return { - context: { config: getMockConfig('webpack') }, + context: { config: getMockConfig() }, } as unknown as YargsArgs; }; diff --git a/packages/snaps-cli/src/commands/serve/index.ts b/packages/snaps-cli/src/commands/serve/index.ts index 7330faf12f..95de095587 100644 --- a/packages/snaps-cli/src/commands/serve/index.ts +++ b/packages/snaps-cli/src/commands/serve/index.ts @@ -8,7 +8,7 @@ const command = { command: ['serve', 's'], desc: 'Locally serve Snap file(s) for testing', builder: (yarg: yargs.Argv) => { - yarg.option('root', builders.root).option('port', builders.port); + yarg.option('port', builders.port); }, handler: async (argv: YargsArgs) => serveHandler(argv.context.config, { diff --git a/packages/snaps-cli/src/commands/serve/serve.e2e.test.ts b/packages/snaps-cli/src/commands/serve/serve.e2e.test.ts index 02ae71350a..60cea58e5c 100644 --- a/packages/snaps-cli/src/commands/serve/serve.e2e.test.ts +++ b/packages/snaps-cli/src/commands/serve/serve.e2e.test.ts @@ -1,7 +1,8 @@ -import type { TestRunner } from '@metamask/snaps-cli/test-utils'; -import { getCommandRunner } from '@metamask/snaps-cli/test-utils'; import fetch from 'cross-fetch'; +import type { TestRunner } from '../../test-utils'; +import { getCommandRunner } from '../../test-utils'; + describe('mm-snap serve', () => { let runner: TestRunner; diff --git a/packages/snaps-cli/src/commands/serve/serve.test.ts b/packages/snaps-cli/src/commands/serve/serve.test.ts index c7691969f7..2d1e6cbb76 100644 --- a/packages/snaps-cli/src/commands/serve/serve.test.ts +++ b/packages/snaps-cli/src/commands/serve/serve.test.ts @@ -6,7 +6,7 @@ jest.mock('../../webpack'); describe('serveHandler', () => { it('starts a server', async () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', server: { root: '/foo', @@ -36,38 +36,8 @@ describe('serveHandler', () => { ); }); - it('starts a server when using Browserify', async () => { - const config = getMockConfig('browserify', { - cliOptions: { - root: '/foo/browserify', - port: 4567, - }, - }); - - const listen = jest.fn().mockImplementation((port) => ({ port })); - const log = jest.spyOn(console, 'log').mockImplementation(); - const getServer = jest - .spyOn(webpack, 'getServer') - .mockImplementation(() => ({ - listen, - })); - - await serveHandler(config, { - port: config.server.port, - }); - - expect(process.exitCode).not.toBe(1); - expect(getServer).toHaveBeenCalled(); - expect(listen).toHaveBeenCalledWith(config.server.port); - expect(log).toHaveBeenCalledWith( - expect.stringContaining( - `The server is listening on http://localhost:${config.server.port}.`, - ), - ); - }); - it('starts a server on the specified port', async () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', server: { root: '/foo', diff --git a/packages/snaps-cli/src/commands/watch/implementation.test.ts b/packages/snaps-cli/src/commands/watch/implementation.test.ts index 1cfebecc43..af5caff0ec 100644 --- a/packages/snaps-cli/src/commands/watch/implementation.test.ts +++ b/packages/snaps-cli/src/commands/watch/implementation.test.ts @@ -64,7 +64,7 @@ describe('watch', () => { })); await watch( - getMockConfig('webpack', { + getMockConfig({ input: '/snap/input.js', }), ); @@ -87,7 +87,7 @@ describe('watch', () => { await expect( watch( - getMockConfig('webpack', { + getMockConfig({ input: '/snap/input.js', }), ), diff --git a/packages/snaps-cli/src/commands/watch/implementation.ts b/packages/snaps-cli/src/commands/watch/implementation.ts index 455ea8c16a..78ef8c90bf 100644 --- a/packages/snaps-cli/src/commands/watch/implementation.ts +++ b/packages/snaps-cli/src/commands/watch/implementation.ts @@ -2,7 +2,7 @@ import { assert } from '@metamask/utils'; import { basename } from 'path'; import type { Watching } from 'webpack'; -import type { ProcessedWebpackConfig } from '../../config'; +import type { ProcessedConfig } from '../../config'; import type { WebpackOptions } from '../../webpack'; import { getCompiler } from '../../webpack'; @@ -16,10 +16,7 @@ import { getCompiler } from '../../webpack'; * The promise resolves with a Webpack watching instance that can be used to * close the watcher. */ -export async function watch( - config: ProcessedWebpackConfig, - options?: WebpackOptions, -) { +export async function watch(config: ProcessedConfig, options?: WebpackOptions) { const compiler = await getCompiler(config, { evaluate: config.evaluate, watch: true, diff --git a/packages/snaps-cli/src/commands/watch/index.test.ts b/packages/snaps-cli/src/commands/watch/index.test.ts index 6cdce57907..c2a225939f 100644 --- a/packages/snaps-cli/src/commands/watch/index.test.ts +++ b/packages/snaps-cli/src/commands/watch/index.test.ts @@ -7,7 +7,7 @@ jest.mock('./watch'); const getMockArgv = () => { return { - context: { config: getMockConfig('webpack') }, + context: { config: getMockConfig() }, } as unknown as YargsArgs; }; diff --git a/packages/snaps-cli/src/commands/watch/index.ts b/packages/snaps-cli/src/commands/watch/index.ts index 8e1e499647..992a7a28e3 100644 --- a/packages/snaps-cli/src/commands/watch/index.ts +++ b/packages/snaps-cli/src/commands/watch/index.ts @@ -8,22 +8,7 @@ const command = { command: ['watch', 'w'], desc: 'Build Snap on change', builder: (yarg: yargs.Argv) => { - yarg - .option('src', builders.src) - .option('eval', builders.eval) - .option('dist', builders.dist) - .option('outfileName', builders.outfileName) - .option('sourceMaps', builders.sourceMaps) - .option('stripComments', builders.stripComments) - .option('transpilationMode', builders.transpilationMode) - .option('depsToTranspile', builders.depsToTranspile) - .option('manifest', builders.manifest) - .option('writeManifest', builders.writeManifest) - .option('serve', builders.serve) - .option('root', builders.root) - .option('port', builders.port) - .implies('writeManifest', 'manifest') - .implies('depsToTranspile', 'transpilationMode'); + yarg.option('port', builders.port); }, handler: async (argv: YargsArgs) => watchHandler(argv.context.config, { diff --git a/packages/snaps-cli/src/commands/watch/watch.test.ts b/packages/snaps-cli/src/commands/watch/watch.test.ts index e6de712b56..cb8b10a8f1 100644 --- a/packages/snaps-cli/src/commands/watch/watch.test.ts +++ b/packages/snaps-cli/src/commands/watch/watch.test.ts @@ -1,9 +1,9 @@ -import { getMockConfig } from '@metamask/snaps-cli/test-utils'; import { DEFAULT_SNAP_BUNDLE } from '@metamask/snaps-utils/test-utils'; import fs from 'fs'; import { watch } from './implementation'; import { watchHandler } from './watch'; +import { getMockConfig } from '../../test-utils'; import * as webpack from '../../webpack'; jest.mock('fs'); @@ -14,7 +14,7 @@ describe('watchHandler', () => { it('builds the snap and watches for changes', async () => { await fs.promises.writeFile('/input.js', DEFAULT_SNAP_BUNDLE); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', output: { path: '/foo', @@ -45,7 +45,7 @@ describe('watchHandler', () => { it('checks if the input file exists', async () => { const log = jest.spyOn(console, 'error').mockImplementation(); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'fake-input-file.js', }); @@ -70,7 +70,7 @@ describe('watchHandler', () => { listen, })); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', output: { path: '/foo', @@ -103,7 +103,7 @@ describe('watchHandler', () => { listen, })); - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: '/input.js', output: { path: '/foo', diff --git a/packages/snaps-cli/src/commands/watch/watch.ts b/packages/snaps-cli/src/commands/watch/watch.ts index 58d2b15a56..740894b989 100644 --- a/packages/snaps-cli/src/commands/watch/watch.ts +++ b/packages/snaps-cli/src/commands/watch/watch.ts @@ -1,7 +1,7 @@ import { isFile } from '@metamask/snaps-utils/node'; import { watch } from './implementation'; -import type { ProcessedConfig, ProcessedWebpackConfig } from '../../config'; +import type { ProcessedConfig } from '../../config'; import { CommandError } from '../../errors'; import type { Steps } from '../../utils'; import { executeSteps, info } from '../../utils'; @@ -15,7 +15,7 @@ type WatchOptions = { }; type WatchContext = { - config: ProcessedWebpackConfig; + config: ProcessedConfig; options: WatchOptions; }; diff --git a/packages/snaps-cli/src/config.test.ts b/packages/snaps-cli/src/config.test.ts index 6ca21c2a1e..4909a3df57 100644 --- a/packages/snaps-cli/src/config.test.ts +++ b/packages/snaps-cli/src/config.test.ts @@ -1,53 +1,24 @@ -import type { BrowserifyObject } from 'browserify'; -import { bold, green, red } from 'chalk'; +import { bold, red } from 'chalk'; import { resolve } from 'path'; -import { TranspilationModes } from './builders'; import { getConfig, getConfigByArgv, loadConfig, - mergeLegacyOptions, resolveConfig, } from './config'; import { getMockConfig } from './test-utils'; -import type { YargsArgs } from './types/yargs'; const CONFIG_PATH = resolve(__dirname, '__fixtures__', 'configs'); -const DEFAULT_CONFIG = getMockConfig('webpack'); -const MOCK_ARGV = {} as YargsArgs; +const DEFAULT_CONFIG = getMockConfig(); describe('getConfig', () => { - it('throws an error if `bundler` is not `browserify` or `webpack`', () => { - expect(() => getConfig({ bundler: 'foo' }, MOCK_ARGV)).toThrow( - `At path: ${bold('bundler')} — Expected the value to be one of: ${green( - '"browserify"', - )}, ${green('"webpack"')}, but received: ${red('"foo"')}.`, - ); - }); - - it('throws an error if `entry` is being used with `browserify`', () => { - expect(() => - getConfig( - { - bundler: 'browserify', - entry: 'foo', - }, - MOCK_ARGV, - ), - ).toThrow(`Unknown key: ${bold('entry')}, received: ${red('"foo"')}.`); - }); - it('throws an error if `cliOptions` is being used with `webpack`', () => { expect(() => - getConfig( - { - bundler: 'webpack', - input: 'foo', - cliOptions: { port: 8000 }, - }, - MOCK_ARGV, - ), + getConfig({ + input: 'foo', + cliOptions: { port: 8000 }, + }), ).toThrow(`Unknown key: ${bold('cliOptions')}, received:`); }); @@ -86,108 +57,32 @@ describe('getConfig', () => { }, {}, ])('returns a valid config for `%o`', (value) => { - const config = getConfig(value, MOCK_ARGV); + const config = getConfig(value); expect(config).toStrictEqual( - getMockConfig('webpack', { + getMockConfig({ input: resolve(process.cwd(), 'src', 'index.js'), }), ); - - expect(config.legacy).toBeUndefined(); - }); - - describe('browserify', () => { - it.each([ - { - bundler: 'browserify', - cliOptions: { - src: 'src/index.js', - port: 8081, - transpilationMode: TranspilationModes.LocalAndDeps, - depsToTranspile: ['foo', 'bar'], - }, - bundlerCustomizer: (browserify: BrowserifyObject) => { - browserify.plugin('foo'); - }, - }, - { - bundler: 'browserify', - cliOptions: { - src: 'src/index.js', - port: 8081, - }, - }, - { - bundler: 'browserify', - cliOptions: { - port: 8081, - }, - }, - { - bundler: 'browserify', - cliOptions: {}, - }, - { - bundler: 'browserify', - }, - ])('returns a valid config for `%o`', (value) => { - const config = getConfig(value, MOCK_ARGV); - - expect(config.legacy).toStrictEqual({ - bundlerCustomizer: value.bundlerCustomizer ?? undefined, - depsToTranspile: value.cliOptions?.depsToTranspile ?? [], - dist: resolve(process.cwd(), 'dist'), - eval: true, - manifest: true, - outfileName: 'bundle.js', - port: 8081, - root: process.cwd(), - serve: true, - sourceMaps: false, - src: resolve(process.cwd(), 'src', 'index.js'), - stripComments: true, - suppressWarnings: false, - transpilationMode: - value.cliOptions?.transpilationMode ?? TranspilationModes.LocalOnly, - verboseErrors: true, - writeManifest: true, - }); - }); - - it('throws when trying to use `depsToTranspile` with `transpilationMode` not set to `LocalAndDeps`', () => { - expect(() => - getConfig( - { - bundler: 'browserify', - cliOptions: { - depsToTranspile: ['foo', 'bar'], - transpilationMode: TranspilationModes.LocalOnly, - }, - }, - MOCK_ARGV, - ), - ).toThrow('Invalid Browserify CLI options.'); - }); }); }); describe('loadConfig', () => { it('loads an ESM-based config', async () => { - expect( - await loadConfig(resolve(CONFIG_PATH, 'esm.ts'), MOCK_ARGV), - ).toStrictEqual(DEFAULT_CONFIG); + expect(await loadConfig(resolve(CONFIG_PATH, 'esm.ts'))).toStrictEqual( + DEFAULT_CONFIG, + ); }); it('loads a CJS-based config', async () => { - expect( - await loadConfig(resolve(CONFIG_PATH, 'cjs.ts'), MOCK_ARGV), - ).toStrictEqual(DEFAULT_CONFIG); + expect(await loadConfig(resolve(CONFIG_PATH, 'cjs.ts'))).toStrictEqual( + DEFAULT_CONFIG, + ); }); it('throws an error if the config is invalid', async () => { await expect( - loadConfig(resolve(CONFIG_PATH, 'invalid.ts'), MOCK_ARGV), + loadConfig(resolve(CONFIG_PATH, 'invalid.ts')), ).rejects.toThrow( `Unknown key: ${bold('foo')}, received: ${red('"bar"')}.`, ); @@ -195,7 +90,7 @@ describe('loadConfig', () => { it('throws an error if the config is not JavaScript or TypeScript', async () => { await expect( - loadConfig(resolve(CONFIG_PATH, 'invalid.json'), MOCK_ARGV), + loadConfig(resolve(CONFIG_PATH, 'invalid.json')), ).rejects.toThrow( `Unable to load snap config file at "${resolve( CONFIG_PATH, @@ -208,7 +103,7 @@ describe('loadConfig', () => { describe('resolveConfig', () => { it('resolves a JavaScript config in the provided directory', async () => { expect( - await resolveConfig(resolve(CONFIG_PATH, 'javascript'), MOCK_ARGV), + await resolveConfig(resolve(CONFIG_PATH, 'javascript')), ).toStrictEqual({ ...DEFAULT_CONFIG, input: resolve(process.cwd(), 'src', 'index.js'), @@ -217,7 +112,7 @@ describe('resolveConfig', () => { it('resolves a TypeScript config in the provided directory', async () => { expect( - await resolveConfig(resolve(CONFIG_PATH, 'typescript'), MOCK_ARGV), + await resolveConfig(resolve(CONFIG_PATH, 'typescript')), ).toStrictEqual({ ...DEFAULT_CONFIG, input: resolve(process.cwd(), 'src', 'index.ts'), @@ -225,7 +120,7 @@ describe('resolveConfig', () => { }); it('throws an error if no config is found', async () => { - await expect(resolveConfig(process.cwd(), MOCK_ARGV)).rejects.toThrow( + await expect(resolveConfig(process.cwd())).rejects.toThrow( /Could not find a "snap\.config\.js" or "snap\.config\.ts" file in the current or specified directory \(".*"\)\./u, ); }); @@ -262,33 +157,3 @@ describe('getConfigByArgv', () => { ); }); }); - -describe('mergeLegacyOptions', () => { - it('merges the argv with the config', () => { - expect( - mergeLegacyOptions( - // @ts-expect-error - Partial `argv`. - { - src: 'src/index.ts', - port: 8000, - serve: false, - }, - { - cliOptions: { - src: 'src/index.js', - port: 9000, - writeManifest: true, - serve: true, - }, - }, - ), - ).toStrictEqual({ - cliOptions: { - port: 8000, - src: 'src/index.ts', - writeManifest: true, - serve: false, - }, - }); - }); -}); diff --git a/packages/snaps-cli/src/config.ts b/packages/snaps-cli/src/config.ts index fa41a590a6..048990a6ab 100644 --- a/packages/snaps-cli/src/config.ts +++ b/packages/snaps-cli/src/config.ts @@ -4,12 +4,10 @@ import { indent, isFile, SnapsStructError, - named, } from '@metamask/snaps-utils/node'; import { array, boolean, - create, defaulted, define, func, @@ -18,21 +16,17 @@ import { optional, record, string, - type, unknown, - empty, } from '@metamask/superstruct'; import type { Infer } from '@metamask/superstruct'; import { hasProperty } from '@metamask/utils'; import { transform } from '@swc/core'; -import type { BrowserifyObject } from 'browserify'; import { dim } from 'chalk'; import { readFile } from 'fs/promises'; import Module from 'module'; -import { basename, dirname, resolve } from 'path'; +import { dirname, resolve } from 'path'; import type { Configuration as WebpackConfiguration } from 'webpack'; -import { TranspilationModes } from './builders'; import { ConfigError } from './errors'; import { file } from './structs'; import type { YargsArgs } from './types/yargs'; @@ -40,174 +34,11 @@ import { CONFIG_FILE, TS_CONFIG_FILE } from './utils'; const CONFIG_FILES = [CONFIG_FILE, TS_CONFIG_FILE]; -/** - * The configuration for the Snaps CLI, stored as `snap.config.js` or - * `snap.config.ts` in the root of the project. - * - * @deprecated The Browserify bundler is deprecated and will be removed in a - * future release. Use the Webpack bundler instead. - */ -export type SnapBrowserifyConfig = { - /** - * The bundler to use to build the snap. For backwards compatibility, if not - * specified, Browserify will be used. However, the Browserify bundler is - * deprecated and will be removed in a future release, so it's recommended to - * use the Webpack bundler instead. - */ - bundler: 'browserify'; - - /** - * The options for the Snaps CLI. These are merged with the options passed to - * the CLI, with the CLI options taking precedence. - * - * @deprecated The Browserify bundler is deprecated and will be removed in a - * future release. Use the Webpack bundler instead. - */ - cliOptions?: { - /** - * The path to the snap bundle file. - * - * @default 'dist/bundle.js' - */ - bundle?: string; - - /** - * The directory to output the snap to. This is only used if `bundle` is - * not specified. - * - * @default 'dist' - */ - dist?: string; - - /** - * Whether to attempt to evaluate the snap in SES. This can catch some errors - * that would otherwise only be caught at runtime. - * - * @default true - */ - eval?: boolean; - - /** - * Whether to validate the snap manifest. - * - * @default true - */ - manifest?: boolean; - - /** - * The name of the bundle file. This is only used if `bundle` is not - * specified. - * - * @default 'bundle.js' - */ - outfileName?: string; - - /** - * The port to run the server on. - * - * @default 8081 - */ - port?: number; - - /** - * The root directory to serve the snap from. - * - * @default `process.cwd()` - */ - root?: string; - - /** - * Whether to generate source maps for the snap bundle. - * - * @default false - */ - sourceMaps?: boolean; - - /** - * The path to the snap entry point. - * - * @default 'src/index.js' - */ - src?: string; - - /** - * Whether to remove comments from the bundle. - * - * @default true - */ - stripComments?: boolean; - - /** - * Whether to suppress warnings. - * - * @default false - */ - suppressWarnings?: boolean; - - /** - * The transpilation mode to use, which determines which files are - * transpiled. - * - * - `'localAndDeps'`: Transpile the snap entry point and all dependencies. - * - `'localOnly'`: Transpile only the snap entry point. - * - `'none'`: Don't transpile any files. - * - * @default 'localOnly' - */ - transpilationMode?: 'localAndDeps' | 'localOnly' | 'none'; - - /** - * The dependencies to transpile when `transpilationMode` is set to - * `'localAndDeps'`. If not specified, all dependencies will be transpiled. - */ - depsToTranspile?: string[]; - - /** - * Whether to show original errors. - * - * @default true - */ - verboseErrors?: boolean; - - /** - * Whether to write the updated manifest to disk. - * - * @default true - */ - writeManifest?: boolean; - - /** - * Whether to serve the snap locally. - * - * @default true - */ - serve?: boolean; - }; - - /** - * A function that can be used to customize the Browserify instance used to - * build the snap. - * - * @param bundler - The Browserify instance. - * @deprecated The Browserify bundler is deprecated and will be removed in a - * future release. Use the Webpack bundler instead. - */ - bundlerCustomizer?: (bundler: BrowserifyObject) => void; -}; - /** * The configuration for the Snaps CLI, stored as `snap.config.js` or * `snap.config.ts` in the root of the project. */ -export type SnapWebpackConfig = { - /** - * The bundler to use to build the snap. For backwards compatibility, if not - * specified, Browserify will be used. However, the Browserify bundler is - * deprecated and will be removed in a future release, so it's recommended to - * use the Webpack bundler instead. - */ - bundler?: 'webpack'; - +export type SnapConfig = { /** * The path to the snap entry point. This should be a JavaScript or TypeScript * file. @@ -513,54 +344,6 @@ export type SnapWebpackConfig = { }; }; -/** - * The configuration for the Snaps CLI, stored as `snap.config.js` or - * `snap.config.ts` in the root of the project. - */ -export type SnapConfig = SnapBrowserifyConfig | SnapWebpackConfig; - -type SnapsBrowserifyBundlerCustomizerFunction = ( - bundler: BrowserifyObject, -) => void; - -// This struct is essentially the same as the `func` struct, but it's defined -// separately so that we include the function type in the inferred TypeScript -// type definitions. -const SnapsBrowserifyBundlerCustomizerFunctionStruct = - define( - 'function', - func().validator, - ); - -export const SnapsBrowserifyConfigStruct = object({ - bundler: literal('browserify'), - cliOptions: defaulted( - object({ - bundle: optional(file()), - dist: defaulted(file(), 'dist'), - eval: defaulted(boolean(), true), - manifest: defaulted(boolean(), true), - port: defaulted(number(), 8081), - outfileName: defaulted(string(), 'bundle.js'), - root: defaulted(file(), process.cwd()), - sourceMaps: defaulted(boolean(), false), - src: defaulted(file(), 'src/index.js'), - stripComments: defaulted(boolean(), true), - suppressWarnings: defaulted(boolean(), false), - transpilationMode: defaulted( - union([literal('localAndDeps'), literal('localOnly'), literal('none')]), - 'localOnly', - ), - depsToTranspile: defaulted(array(string()), []), - verboseErrors: defaulted(boolean(), true), - writeManifest: defaulted(boolean(), true), - serve: defaulted(boolean(), true), - }), - {}, - ), - bundlerCustomizer: optional(SnapsBrowserifyBundlerCustomizerFunctionStruct), -}); - type SnapsWebpackCustomizeWebpackConfigFunction = ( config: WebpackConfiguration, ) => WebpackConfiguration; @@ -574,8 +357,7 @@ const SnapsWebpackCustomizeWebpackConfigFunctionStruct = func().validator, ); -export const SnapsWebpackConfigStruct = object({ - bundler: defaulted(literal('webpack'), 'webpack'), +export const SnapsConfigStruct = object({ input: defaulted(file(), resolve(process.cwd(), 'src/index.js')), sourceMap: defaulted(union([boolean(), literal('inline')]), false), evaluate: defaulted(boolean(), true), @@ -690,90 +472,22 @@ export const SnapsWebpackConfigStruct = object({ ), }); -export const SnapsConfigStruct = type({ - bundler: defaulted( - union([literal('browserify'), literal('webpack')]), - 'webpack', - ), -}); - -export const LegacyOptionsStruct = union([ - named( - 'object with `transpilationMode` set to `localAndDeps` and `depsToTranspile` set to an array of strings', - type({ - depsToTranspile: array(string()), - transpilationMode: literal(TranspilationModes.LocalAndDeps), - writeManifest: boolean(), - bundlerCustomizer: optional( - SnapsBrowserifyBundlerCustomizerFunctionStruct, - ), - }), - ), - named( - 'object without `depsToTranspile`', - type({ - depsToTranspile: named('empty array', empty(array())), - transpilationMode: union([ - literal(TranspilationModes.LocalOnly), - literal(TranspilationModes.None), - ]), - writeManifest: boolean(), - bundlerCustomizer: optional( - SnapsBrowserifyBundlerCustomizerFunctionStruct, - ), - }), - ), -]); - -export type LegacyOptions = Infer; - -export type ProcessedBrowserifyConfig = Infer< - typeof SnapsBrowserifyConfigStruct ->; - -export type ProcessedWebpackConfig = Infer & { - /** - * The legacy Browserify config, if the bundler is Browserify. This is used - * to support the legacy config format. - */ - legacy?: LegacyOptions; -}; - -export type ProcessedConfig = ProcessedWebpackConfig; +export type ProcessedConfig = Infer; /** * Get a validated snap config. This validates the config and adds default * values for any missing properties. * * @param config - The config to validate. - * @param argv - The CLI arguments. * @returns The validated config. */ -export function getConfig(config: unknown, argv: YargsArgs): ProcessedConfig { +export function getConfig(config: unknown): ProcessedConfig { const prefix = 'The snap config file is invalid'; const suffix = dim( 'Refer to the documentation for more information: https://docs.metamask.io/snaps/reference/cli/options/', ); - const { bundler } = createFromStruct( - config, - SnapsConfigStruct, - prefix, - suffix, - ); - - if (bundler === 'browserify') { - const legacyConfig = createFromStruct( - config, - SnapsBrowserifyConfigStruct, - prefix, - suffix, - ); - - return getWebpackConfig(mergeLegacyOptions(argv, legacyConfig)); - } - - return createFromStruct(config, SnapsWebpackConfigStruct, prefix, suffix); + return createFromStruct(config, SnapsConfigStruct, prefix, suffix); } /** @@ -784,12 +498,11 @@ export function getConfig(config: unknown, argv: YargsArgs): ProcessedConfig { * `module.exports` or `export default`. * * @param path - The full path to the config file. - * @param argv - The CLI arguments. * @returns The validated config. * @throws If the config file is invalid, or if the config file does not have a * default export. */ -export async function loadConfig(path: string, argv: YargsArgs) { +export async function loadConfig(path: string) { try { const contents = await readFile(path, 'utf8'); const source = await transform(contents, { @@ -813,10 +526,10 @@ export async function loadConfig(path: string, argv: YargsArgs) { config._compile(source.code, path); if (!hasProperty(config.exports, 'default')) { - return getConfig(config.exports, argv); + return getConfig(config.exports); } - return getConfig(config.exports.default, argv); + return getConfig(config.exports.default); } catch (error) { if (error instanceof SnapsStructError) { throw new ConfigError(error.message); @@ -836,15 +549,14 @@ export async function loadConfig(path: string, argv: YargsArgs) { * * @param path - The path to resolve the snap config from. Defaults to the * current working directory. - * @param argv - The CLI arguments. * @returns The resolved and validated snap config. * @throws If a snap config could not be found. */ -export async function resolveConfig(path: string, argv: YargsArgs) { +export async function resolveConfig(path: string) { for (const configFile of CONFIG_FILES) { const filePath = resolve(path, configFile); if (await isFile(filePath)) { - return await loadConfig(filePath, argv); + return await loadConfig(filePath); } } @@ -873,118 +585,8 @@ export async function getConfigByArgv( ); } - return await loadConfig(argv.config, argv); + return await loadConfig(argv.config); } - return await resolveConfig(cwd, argv); -} - -/** - * Merge legacy CLI options into the config. This is used to support the legacy - * config format, where options can be specified both in the config file and - * through CLI flags. - * - * @param argv - The CLI arguments. - * @param config - The config to merge the CLI options into. - * @returns The config with the CLI options merged in. - * @deprecated This function is only used to support the legacy config format. - */ -export function mergeLegacyOptions( - argv: YargsArgs, - config: ProcessedBrowserifyConfig, -) { - const cliOptions = Object.keys(config.cliOptions).reduce< - ProcessedBrowserifyConfig['cliOptions'] - >((accumulator, key) => { - if (argv[key] !== undefined) { - return { - ...accumulator, - [key]: argv[key], - }; - } - - return accumulator; - }, config.cliOptions); - - return { - ...config, - cliOptions, - }; -} - -/** - * Get a Webpack config from a legacy browserify config. This is used to - * support the legacy config format, and convert it to the new format. - * - * @param legacyConfig - The legacy browserify config. - * @returns The Webpack config. - */ -export function getWebpackConfig( - legacyConfig: ProcessedBrowserifyConfig, -): ProcessedWebpackConfig { - const defaultConfig = create( - { bundler: 'webpack' }, - SnapsWebpackConfigStruct, - ); - - // The legacy config has two options for specifying the output path and - // filename: `bundle`, and `dist` + `outfileName`. If `bundle` is specified, - // we use that as the output path and filename. Otherwise, we use `dist` and - // `outfileName`. - const path = legacyConfig.cliOptions.bundle - ? dirname(legacyConfig.cliOptions.bundle) - : legacyConfig.cliOptions.dist; - - const filename = legacyConfig.cliOptions.bundle - ? basename(legacyConfig.cliOptions.bundle) - : legacyConfig.cliOptions.outfileName; - - return { - ...defaultConfig, - input: legacyConfig.cliOptions.src, - evaluate: legacyConfig.cliOptions.eval, - sourceMap: legacyConfig.cliOptions.sourceMaps, - output: { - path, - filename, - - // The legacy config has an option to remove comments from the bundle, but - // the terser plugin does this by default, so we only enable the terser if - // the legacy config has `stripComments` set to `true`. This is not a - // perfect solution, but it's the best we can do without breaking the - // legacy config. - minimize: legacyConfig.cliOptions.stripComments, - - // The legacy config does not have a `clean` option, so we default to - // `false` here. - clean: false, - }, - manifest: { - // The legacy config does not have a `manifest` option, so we default to - // `process.cwd()/snap.manifest.json`. - path: resolve(process.cwd(), 'snap.manifest.json'), - update: legacyConfig.cliOptions.writeManifest, - }, - server: { - enabled: legacyConfig.cliOptions.serve, - port: legacyConfig.cliOptions.port, - root: legacyConfig.cliOptions.root, - }, - stats: { - verbose: false, - - // These plugins are designed to be used with the modern config format, so - // we disable them for the legacy config format. - builtIns: false, - buffer: false, - }, - legacy: createFromStruct( - { - ...legacyConfig.cliOptions, - bundlerCustomizer: legacyConfig.bundlerCustomizer, - }, - LegacyOptionsStruct, - 'Invalid Browserify CLI options', - ), - }; + return await resolveConfig(cwd); } diff --git a/packages/snaps-cli/src/test-utils/config.ts b/packages/snaps-cli/src/test-utils/config.ts index 8276741b8a..54791f25b5 100644 --- a/packages/snaps-cli/src/test-utils/config.ts +++ b/packages/snaps-cli/src/test-utils/config.ts @@ -1,46 +1,39 @@ -import deepMerge from 'deepmerge'; - -import type { - LegacyOptions, - ProcessedBrowserifyConfig, - ProcessedWebpackConfig, -} from '../config'; +import type { ProcessedConfig } from '../config'; import { getConfig } from '../config'; const DEFAULT_OPTIONS = { - browserify: {}, - webpack: { - input: 'src/index.ts', - }, + input: 'src/index.ts', }; -type MockConfigResult = - Bundler extends 'browserify' - ? Omit & { - legacy: LegacyOptions; - } - : ProcessedWebpackConfig; +/** + * Recursively make all properties of a type optional. + * + * @example + * type Foo = { + * bar: { + * baz: string; + * } + * }; + * + * type PartialFoo = DeepPartial; + * // { + * // bar?: { + * // baz?: string; + * // } + * // } + */ +type DeepPartial = { + [Property in keyof Type]?: DeepPartial; +}; /** - * Get a mock config object. The mock config is generated from the given - * bundler type. + * Get a mock config object. * - * @param bundler - The bundler to use. * @param options - The options to use for the mock config. - * @returns The mock config object for the given bundler. + * @returns The mock config object. */ -export function getMockConfig< - Bundler extends 'browserify' | 'webpack', - Result = Bundler extends 'browserify' - ? ProcessedBrowserifyConfig - : ProcessedWebpackConfig, ->(bundler: Bundler, options?: Partial): MockConfigResult { - return getConfig( - deepMerge( - { bundler }, - options ?? (DEFAULT_OPTIONS[bundler] as Partial), - ), - // @ts-expect-error - Invalid `argv` type, but it's not used in tests. - {}, - ) as MockConfigResult; +export function getMockConfig( + options?: DeepPartial, +): ProcessedConfig { + return getConfig(options ?? (DEFAULT_OPTIONS as Partial)); } diff --git a/packages/snaps-cli/src/test-utils/e2e.ts b/packages/snaps-cli/src/test-utils/e2e.ts index cc1c324441..afbf526559 100644 --- a/packages/snaps-cli/src/test-utils/e2e.ts +++ b/packages/snaps-cli/src/test-utils/e2e.ts @@ -6,11 +6,6 @@ import { join } from 'path'; export const SNAP_DIR = join(__dirname, '../../../examples/packages/json-rpc'); -export const SNAP_BROWSERIFY_DIR = join( - __dirname, - '../../../examples/packages/browserify', -); - /** * A test runner for running CLI commands. */ diff --git a/packages/snaps-cli/src/utils/index.ts b/packages/snaps-cli/src/utils/index.ts index c2df5ea508..197faabb2f 100644 --- a/packages/snaps-cli/src/utils/index.ts +++ b/packages/snaps-cli/src/utils/index.ts @@ -1,6 +1,5 @@ export * from './cli'; export * from './errors'; -export * from './legacy'; export * from './logging'; export * from './path'; export * from './steps'; diff --git a/packages/snaps-cli/src/utils/legacy.test.ts b/packages/snaps-cli/src/utils/legacy.test.ts deleted file mode 100644 index 0b2fb89160..0000000000 --- a/packages/snaps-cli/src/utils/legacy.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { getMockConfig } from '@metamask/snaps-cli/test-utils'; - -import { - getDependencyRegExp, - processDependencies, - sanitizeDependencyPaths, -} from './legacy'; -import { TranspilationModes } from '../builders'; - -describe('processDependencies', () => { - it('returns an empty array when `transpilationMode` is not `localAndDeps`', () => { - const config = getMockConfig('browserify', { - cliOptions: { - transpilationMode: TranspilationModes.LocalOnly, - }, - }); - - const result = processDependencies(config.legacy); - expect(result).toStrictEqual([]); - }); - - it('returns an array with a regex when `transpilationMode` is `localAndDeps`', () => { - const config = getMockConfig('browserify', { - cliOptions: { - transpilationMode: TranspilationModes.LocalAndDeps, - depsToTranspile: ['@metamask/snaps'], - }, - }); - - const result = processDependencies(config.legacy); - expect(result).toStrictEqual([/\/node_modules\/(?!@metamask\/snaps)/u]); - }); - - it('returns an empty array when `depsToTranspile` is empty', () => { - const config = getMockConfig('browserify', { - cliOptions: { - transpilationMode: TranspilationModes.LocalAndDeps, - depsToTranspile: [], - }, - }); - - const result = processDependencies(config.legacy); - expect(result).toStrictEqual([]); - }); -}); - -describe('getDependencyRegExp', () => { - it('returns null when `depsToTranspile` is empty', () => { - const result = getDependencyRegExp([]); - expect(result).toBeNull(); - }); - - it('returns null when `depsToTranspile` includes a dot', () => { - const result = getDependencyRegExp(['@metamask/snaps', '.']); - expect(result).toBeNull(); - }); - - it('returns null when `depsToTranspile` is undefined', () => { - const result = getDependencyRegExp(undefined as any); - expect(result).toBeNull(); - }); - - it('returns a RegExp when `depsToTranspile` is not empty', () => { - const result = getDependencyRegExp(['@metamask/snaps']); - expect(result).toBeInstanceOf(RegExp); - }); - - it('returns a RegExp that matches the provided dependencies', () => { - const result = getDependencyRegExp(['@metamask/snaps', 'foo']); - expect(result?.test('/node_modules/@metamask/snaps/')).toBe(false); - expect(result?.test('/node_modules/foo/')).toBe(false); - expect(result?.test('/node_modules/bar/')).toBe(true); - }); -}); - -describe('sanitizeDependencyPaths', () => { - it('removes leading and trailing slashes', () => { - const result = sanitizeDependencyPaths(['/foo/', '/bar', 'baz/', 'qux']); - expect(result).toStrictEqual(['foo', 'bar', 'baz', 'qux']); - }); -}); diff --git a/packages/snaps-cli/src/utils/legacy.ts b/packages/snaps-cli/src/utils/legacy.ts deleted file mode 100644 index 68ca235923..0000000000 --- a/packages/snaps-cli/src/utils/legacy.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { TranspilationModes } from '../builders'; -import type { LegacyOptions } from '../config'; - -/** - * Get the dependencies to transpile, as well as the regular input file. - * - * If `transpilationMode` is not set to `localAndDeps`, this will return an - * empty array. - * - * @param config - The config object. - * @returns An array with regular expressions of dependencies that should be - * transpiled. - */ -export function processDependencies(config: LegacyOptions) { - const { depsToTranspile, transpilationMode } = config; - if (transpilationMode === TranspilationModes.LocalAndDeps) { - const regex = getDependencyRegExp(depsToTranspile); - if (regex !== null) { - return [regex]; - } - } - - return []; -} - -/** - * Processes a string of space delimited dependencies into one RegExp string. - * - * @param dependencies - An array of dependencies to add to the RegExp. - * @returns A RegExp object. - */ -export function getDependencyRegExp(dependencies: string[]): RegExp | null { - if (!dependencies || dependencies.includes('.') || !dependencies.length) { - return null; - } - - const paths: string[] = sanitizeDependencyPaths(dependencies); - return RegExp(`/node_modules/(?!${paths.join('|')})`, 'u'); -} - -/** - * Helper function to remove any leading and trailing slashes from dependency - * list. - * - * @param dependencies - An array of dependencies to sanitize. - * @returns An array of sanitized paths. - */ -export function sanitizeDependencyPaths(dependencies: string[]): string[] { - return dependencies.map((dependency) => { - return dependency.replace(/^[/\\]+/u, '').replace(/[/\\]+$/u, ''); - }); -} diff --git a/packages/snaps-cli/src/webpack/__snapshots__/config.test.ts.snap b/packages/snaps-cli/src/webpack/__snapshots__/config.test.ts.snap index e418d5dc33..796bf82972 100644 --- a/packages/snaps-cli/src/webpack/__snapshots__/config.test.ts.snap +++ b/packages/snaps-cli/src/webpack/__snapshots__/config.test.ts.snap @@ -2967,480 +2967,6 @@ exports[`getDefaultConfiguration returns the default Webpack configuration for t } `; -exports[`getDefaultConfiguration returns the default Webpack configuration for the given legacy CLI config 1`] = ` -{ - "devtool": false, - "entry": "/foo/bar/src/index.js", - "infrastructureLogging": { - "level": "none", - }, - "mode": "production", - "module": { - "rules": [ - { - "exclude": /node_modules/u, - "test": /\\\\\\.\\(js\\|jsx\\|mjs\\|cjs\\|ts\\|tsx\\)\\$/u, - "use": { - "loader": "/foo/bar/src/webpack/loaders/function.ts", - "options": { - "bundlerCustomizer": undefined, - "depsToTranspile": [], - "dist": "/foo/bar/dist", - "eval": true, - "fn": [Function], - "manifest": true, - "outfileName": "bundle.js", - "port": 8081, - "root": "/foo/bar", - "serve": true, - "sourceMaps": false, - "src": "/foo/bar/src/index.js", - "stripComments": true, - "suppressWarnings": false, - "transpilationMode": "localOnly", - "verboseErrors": true, - "writeManifest": true, - }, - }, - }, - { - "resolve": { - "fullySpecified": false, - }, - "test": /\\\\\\.m\\?js\\$/u, - }, - { - "test": /\\\\\\.svg\\$/u, - "type": "asset/source", - }, - { - "generator": { - "dataUrl": [Function], - }, - "test": /\\\\\\.png\\$/u, - "type": "asset/inline", - }, - { - "generator": { - "dataUrl": [Function], - }, - "test": /\\\\\\.jpe\\?g\\$/u, - "type": "asset/inline", - }, - false, - ], - }, - "optimization": { - "minimize": true, - "minimizer": [ - TerserPlugin { - "options": { - "exclude": undefined, - "extractComments": true, - "include": undefined, - "minimizer": { - "implementation": [Function], - "options": {}, - }, - "parallel": true, - "test": /\\\\\\.\\[cm\\]\\?js\\(\\\\\\?\\.\\*\\)\\?\\$/i, - }, - }, - ], - "nodeEnv": false, - }, - "output": { - "chunkFormat": "commonjs", - "clean": false, - "filename": "bundle.js", - "library": { - "name": "module.exports", - "type": "assign", - }, - "path": "/foo/bar/dist", - "publicPath": "/", - }, - "performance": { - "hints": false, - }, - "plugins": [ - SnapsWebpackPlugin { - "options": { - "eval": true, - "manifestPath": "/foo/bar/snap.manifest.json", - "writeManifest": true, - }, - }, - SnapsStatsPlugin { - "options": { - "verbose": false, - }, - }, - DefinePlugin { - "definitions": { - "process.env.DEBUG": ""false"", - "process.env.NODE_DEBUG": ""false"", - "process.env.NODE_ENV": ""production"", - }, - }, - ProgressPlugin { - "dependenciesCount": 10000, - "handler": [Function], - "modulesCount": 5000, - "percentBy": undefined, - "profile": false, - "showActiveModules": false, - "showDependencies": true, - "showEntries": true, - "showModules": true, - }, - SnapsBundleWarningsPlugin { - "options": { - "buffer": false, - "builtInResolver": false, - "builtIns": false, - }, - }, - ], - "resolve": { - "extensions": [ - ".js", - ".jsx", - ".mjs", - ".cjs", - ".ts", - ".tsx", - ], - "fallback": { - "buffer": false, - "fs": false, - "path": false, - }, - "plugins": [ - false, - ], - }, - "stats": "none", - "target": "browserslist:/foo/bar/.browserslistrc", -} -`; - -exports[`getDefaultConfiguration returns the default Webpack configuration for the given legacy CLI config 2`] = ` -{ - "devtool": false, - "entry": "/foo/bar/src/index.ts", - "infrastructureLogging": { - "level": "none", - }, - "mode": "production", - "module": { - "rules": [ - { - "exclude": /node_modules/u, - "test": /\\\\\\.\\(js\\|jsx\\|mjs\\|cjs\\|ts\\|tsx\\)\\$/u, - "use": { - "loader": "/foo/bar/src/webpack/loaders/function.ts", - "options": { - "bundlerCustomizer": undefined, - "depsToTranspile": [], - "dist": "/foo/bar/dist", - "eval": true, - "fn": [Function], - "manifest": true, - "outfileName": "bundle.js", - "port": 8081, - "root": "/foo/bar", - "serve": true, - "sourceMaps": false, - "src": "/foo/bar/src/index.ts", - "stripComments": true, - "suppressWarnings": false, - "transpilationMode": "localOnly", - "verboseErrors": true, - "writeManifest": true, - }, - }, - }, - { - "resolve": { - "fullySpecified": false, - }, - "test": /\\\\\\.m\\?js\\$/u, - }, - { - "test": /\\\\\\.svg\\$/u, - "type": "asset/source", - }, - { - "generator": { - "dataUrl": [Function], - }, - "test": /\\\\\\.png\\$/u, - "type": "asset/inline", - }, - { - "generator": { - "dataUrl": [Function], - }, - "test": /\\\\\\.jpe\\?g\\$/u, - "type": "asset/inline", - }, - false, - ], - }, - "optimization": { - "minimize": true, - "minimizer": [ - TerserPlugin { - "options": { - "exclude": undefined, - "extractComments": true, - "include": undefined, - "minimizer": { - "implementation": [Function], - "options": {}, - }, - "parallel": true, - "test": /\\\\\\.\\[cm\\]\\?js\\(\\\\\\?\\.\\*\\)\\?\\$/i, - }, - }, - ], - "nodeEnv": false, - }, - "output": { - "chunkFormat": "commonjs", - "clean": false, - "filename": "bundle.js", - "library": { - "name": "module.exports", - "type": "assign", - }, - "path": "/foo/bar/dist", - "publicPath": "/", - }, - "performance": { - "hints": false, - }, - "plugins": [ - SnapsWebpackPlugin { - "options": { - "eval": true, - "manifestPath": "/foo/bar/snap.manifest.json", - "writeManifest": true, - }, - }, - SnapsStatsPlugin { - "options": { - "verbose": false, - }, - }, - DefinePlugin { - "definitions": { - "process.env.DEBUG": ""false"", - "process.env.NODE_DEBUG": ""false"", - "process.env.NODE_ENV": ""production"", - }, - }, - ProgressPlugin { - "dependenciesCount": 10000, - "handler": [Function], - "modulesCount": 5000, - "percentBy": undefined, - "profile": false, - "showActiveModules": false, - "showDependencies": true, - "showEntries": true, - "showModules": true, - }, - SnapsBundleWarningsPlugin { - "options": { - "buffer": false, - "builtInResolver": false, - "builtIns": false, - }, - }, - ], - "resolve": { - "extensions": [ - ".js", - ".jsx", - ".mjs", - ".cjs", - ".ts", - ".tsx", - ], - "fallback": { - "buffer": false, - "fs": false, - "path": false, - }, - "plugins": [ - false, - ], - }, - "stats": "none", - "target": "browserslist:/foo/bar/.browserslistrc", -} -`; - -exports[`getDefaultConfiguration returns the default Webpack configuration for the given legacy CLI config 3`] = ` -{ - "devtool": false, - "entry": "/foo/bar/src/index.ts", - "infrastructureLogging": { - "level": "none", - }, - "mode": "production", - "module": { - "rules": [ - { - "exclude": /node_modules/u, - "test": /\\\\\\.\\(js\\|jsx\\|mjs\\|cjs\\|ts\\|tsx\\)\\$/u, - "use": { - "loader": "/foo/bar/src/webpack/loaders/function.ts", - "options": { - "bundlerCustomizer": undefined, - "depsToTranspile": [], - "dist": "/foo/bar/dist", - "eval": true, - "fn": [Function], - "manifest": true, - "outfileName": "bundle.js", - "port": 8081, - "root": "/foo/bar", - "serve": true, - "sourceMaps": false, - "src": "/foo/bar/src/index.ts", - "stripComments": false, - "suppressWarnings": false, - "transpilationMode": "localOnly", - "verboseErrors": true, - "writeManifest": true, - }, - }, - }, - { - "resolve": { - "fullySpecified": false, - }, - "test": /\\\\\\.m\\?js\\$/u, - }, - { - "test": /\\\\\\.svg\\$/u, - "type": "asset/source", - }, - { - "generator": { - "dataUrl": [Function], - }, - "test": /\\\\\\.png\\$/u, - "type": "asset/inline", - }, - { - "generator": { - "dataUrl": [Function], - }, - "test": /\\\\\\.jpe\\?g\\$/u, - "type": "asset/inline", - }, - false, - ], - }, - "optimization": { - "minimize": false, - "minimizer": [ - TerserPlugin { - "options": { - "exclude": undefined, - "extractComments": true, - "include": undefined, - "minimizer": { - "implementation": [Function], - "options": {}, - }, - "parallel": true, - "test": /\\\\\\.\\[cm\\]\\?js\\(\\\\\\?\\.\\*\\)\\?\\$/i, - }, - }, - ], - "nodeEnv": false, - }, - "output": { - "chunkFormat": "commonjs", - "clean": false, - "filename": "bundle.js", - "library": { - "name": "module.exports", - "type": "assign", - }, - "path": "/foo/bar/dist", - "publicPath": "/", - }, - "performance": { - "hints": false, - }, - "plugins": [ - SnapsWebpackPlugin { - "options": { - "eval": true, - "manifestPath": "/foo/bar/snap.manifest.json", - "writeManifest": true, - }, - }, - SnapsStatsPlugin { - "options": { - "verbose": false, - }, - }, - DefinePlugin { - "definitions": { - "process.env.DEBUG": ""false"", - "process.env.NODE_DEBUG": ""false"", - "process.env.NODE_ENV": ""production"", - }, - }, - ProgressPlugin { - "dependenciesCount": 10000, - "handler": [Function], - "modulesCount": 5000, - "percentBy": undefined, - "profile": false, - "showActiveModules": false, - "showDependencies": true, - "showEntries": true, - "showModules": true, - }, - SnapsBundleWarningsPlugin { - "options": { - "buffer": false, - "builtInResolver": false, - "builtIns": false, - }, - }, - ], - "resolve": { - "extensions": [ - ".js", - ".jsx", - ".mjs", - ".cjs", - ".ts", - ".tsx", - ], - "fallback": { - "buffer": false, - "fs": false, - "path": false, - }, - "plugins": [ - false, - ], - }, - "stats": "none", - "target": "browserslist:/foo/bar/.browserslistrc", -} -`; - exports[`getDefaultConfiguration returns the default Webpack configuration when \`analyze\` is \`true\` 1`] = ` { "devtool": false, diff --git a/packages/snaps-cli/src/webpack/compiler.test.ts b/packages/snaps-cli/src/webpack/compiler.test.ts index 33af977f50..940dea6b64 100644 --- a/packages/snaps-cli/src/webpack/compiler.test.ts +++ b/packages/snaps-cli/src/webpack/compiler.test.ts @@ -14,7 +14,7 @@ jest.mock('serve-handler', () => describe('getCompiler', () => { it('returns a Webpack compiler for the given config', async () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', }); @@ -28,7 +28,7 @@ describe('getCompiler', () => { }); it('modifies the Webpack config if a customizer is provided', async () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', customizeWebpackConfig: (webpackConfig: Configuration) => merge(webpackConfig, { diff --git a/packages/snaps-cli/src/webpack/compiler.ts b/packages/snaps-cli/src/webpack/compiler.ts index 7f51b9b2a5..79e340e817 100644 --- a/packages/snaps-cli/src/webpack/compiler.ts +++ b/packages/snaps-cli/src/webpack/compiler.ts @@ -2,7 +2,7 @@ import { webpack } from 'webpack'; import type { WebpackOptions } from './config'; import { getDefaultConfiguration } from './config'; -import type { ProcessedWebpackConfig } from '../config'; +import type { ProcessedConfig } from '../config'; /** * Get a Webpack compiler for the given config. @@ -12,7 +12,7 @@ import type { ProcessedWebpackConfig } from '../config'; * @returns The Webpack compiler. */ export async function getCompiler( - config: ProcessedWebpackConfig, + config: ProcessedConfig, options?: WebpackOptions, ) { const baseWebpackConfig = await getDefaultConfiguration(config, options); diff --git a/packages/snaps-cli/src/webpack/config.test.ts b/packages/snaps-cli/src/webpack/config.test.ts index bb00da03f6..be78e05810 100644 --- a/packages/snaps-cli/src/webpack/config.test.ts +++ b/packages/snaps-cli/src/webpack/config.test.ts @@ -42,7 +42,7 @@ describe('getDefaultConfiguration', () => { }); it.each([ - getMockConfig('webpack', { + getMockConfig({ input: 'src/index.js', output: { path: 'dist', @@ -51,7 +51,7 @@ describe('getDefaultConfiguration', () => { path: 'snap.manifest.json', }, }), - getMockConfig('webpack', { + getMockConfig({ input: 'src/index.ts', output: { path: 'dist', @@ -63,7 +63,7 @@ describe('getDefaultConfiguration', () => { verbose: true, }, }), - getMockConfig('webpack', { + getMockConfig({ input: 'src/index.ts', output: { path: 'dist', @@ -76,7 +76,7 @@ describe('getDefaultConfiguration', () => { }, sourceMap: 'inline', }), - getMockConfig('webpack', { + getMockConfig({ input: 'src/index.ts', output: { path: 'dist', @@ -93,7 +93,7 @@ describe('getDefaultConfiguration', () => { }, sourceMap: true, }), - getMockConfig('webpack', { + getMockConfig({ input: 'src/index.js', output: { path: 'dist', @@ -105,7 +105,7 @@ describe('getDefaultConfiguration', () => { wasm: true, }, }), - getMockConfig('webpack', { + getMockConfig({ input: 'src/index.js', output: { path: 'dist', @@ -115,7 +115,7 @@ describe('getDefaultConfiguration', () => { path: 'snap.manifest.json', }, }), - getMockConfig('webpack', { + getMockConfig({ input: 'src/index.js', output: { path: 'dist', @@ -126,7 +126,7 @@ describe('getDefaultConfiguration', () => { }, polyfills: false, }), - getMockConfig('webpack', { + getMockConfig({ input: 'src/index.js', output: { path: 'dist', @@ -137,7 +137,7 @@ describe('getDefaultConfiguration', () => { }, polyfills: true, }), - getMockConfig('webpack', { + getMockConfig({ input: 'src/index.js', output: { path: 'dist', @@ -150,7 +150,7 @@ describe('getDefaultConfiguration', () => { buffer: true, }, }), - getMockConfig('webpack', { + getMockConfig({ input: 'src/index.js', output: { path: 'dist', @@ -163,7 +163,7 @@ describe('getDefaultConfiguration', () => { images: false, }, }), - getMockConfig('webpack', { + getMockConfig({ input: 'src/index.js', output: { path: 'dist', @@ -175,7 +175,7 @@ describe('getDefaultConfiguration', () => { enabled: true, }, }), - getMockConfig('webpack', { + getMockConfig({ input: 'src/index.js', output: { path: 'dist', @@ -201,7 +201,7 @@ describe('getDefaultConfiguration', () => { ); it('returns the default Webpack configuration when `analyze` is `true`', async () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', output: { path: 'dist', @@ -219,42 +219,6 @@ describe('getDefaultConfiguration', () => { expect(normalizeConfig(output)).toMatchSnapshot(); }); - it.each([ - getMockConfig('browserify', { - cliOptions: { - src: 'src/index.js', - dist: 'dist', - outfileName: 'bundle.js', - root: '/foo/bar', - }, - }), - getMockConfig('browserify', { - cliOptions: { - src: 'src/index.ts', - dist: 'dist', - root: '/foo/bar', - }, - }), - getMockConfig('browserify', { - cliOptions: { - src: 'src/index.ts', - dist: 'dist', - root: '/foo/bar', - stripComments: false, - }, - }), - ])( - 'returns the default Webpack configuration for the given legacy CLI config', - async (config) => { - jest.spyOn(process, 'cwd').mockReturnValue('/foo/bar'); - - const output = await getDefaultConfiguration(config); - - // eslint-disable-next-line jest/no-restricted-matchers - expect(normalizeConfig(output)).toMatchSnapshot(); - }, - ); - it.each([ { evaluate: true, @@ -280,7 +244,7 @@ describe('getDefaultConfiguration', () => { ])( 'returns the default Webpack configuration for the given CLI config and options', async (options) => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.ts', output: { path: '/bar/baz', diff --git a/packages/snaps-cli/src/webpack/config.ts b/packages/snaps-cli/src/webpack/config.ts index 2e43985cb0..736a4a9f0f 100644 --- a/packages/snaps-cli/src/webpack/config.ts +++ b/packages/snaps-cli/src/webpack/config.ts @@ -23,7 +23,7 @@ import { getImageSVG, getProgressHandler, } from './utils'; -import type { ProcessedWebpackConfig } from '../config'; +import type { ProcessedConfig } from '../config'; export type WebpackOptions = { /** @@ -67,7 +67,7 @@ export type WebpackOptions = { * @returns The default Webpack configuration. */ export async function getDefaultConfiguration( - config: ProcessedWebpackConfig, + config: ProcessedConfig, options: WebpackOptions = { evaluate: config.evaluate, }, diff --git a/packages/snaps-cli/src/webpack/loaders/browserify.js b/packages/snaps-cli/src/webpack/loaders/browserify.js deleted file mode 100644 index a781e811c4..0000000000 --- a/packages/snaps-cli/src/webpack/loaders/browserify.js +++ /dev/null @@ -1,3 +0,0 @@ -// This file is used for end-to-end tests only. - -module.exports = require('./browserify.ts'); diff --git a/packages/snaps-cli/src/webpack/loaders/browserify.test.ts b/packages/snaps-cli/src/webpack/loaders/browserify.test.ts deleted file mode 100644 index d2d31c6ffc..0000000000 --- a/packages/snaps-cli/src/webpack/loaders/browserify.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { getMockConfig } from '@metamask/snaps-cli/test-utils'; -import { bytesToString } from '@metamask/utils'; - -import loader from './browserify'; - -describe('loader', () => { - it('bundles the contents with Browserify', async () => { - const config = getMockConfig('browserify'); - - const source = 'console.log("Hello, world!");'; - - const result = (await loader.call( - // @ts-expect-error - Partial `this` object. - { - getOptions: () => config.legacy, - }, - source, - undefined, - )) as Buffer; - - const sourceCode = bytesToString(result); - expect(sourceCode).toMatchInlineSnapshot(` - "(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.snap = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i { - const config = getMockConfig('browserify'); - - const source = 'console.log("Hello, world!";'; - - await expect( - loader.call( - // @ts-expect-error - Partial `this` object. - { - getOptions: () => config.legacy, - }, - source, - undefined, - ), - ).rejects.toThrow('Unexpected token, expected "," (1:27)'); - }); -}); diff --git a/packages/snaps-cli/src/webpack/loaders/browserify.ts b/packages/snaps-cli/src/webpack/loaders/browserify.ts deleted file mode 100644 index c361a4a7c2..0000000000 --- a/packages/snaps-cli/src/webpack/loaders/browserify.ts +++ /dev/null @@ -1,95 +0,0 @@ -import browserify from 'browserify'; -import { Readable } from 'readable-stream'; -import type { LoaderDefinitionFunction } from 'webpack'; - -import { TranspilationModes } from '../../builders'; -import type { LegacyOptions } from '../../config'; -import { processDependencies } from '../../utils'; -import { getBrowserslistTargets } from '../utils'; - -/** - * A Browserify loader for Webpack. This exists for backwards compatibility with - * the legacy configuration format, in order to support the `bundlerCustomizer` - * function. - * - * When this loader is used, the input file will be processed by Browserify, and - * written to disk by Webpack. Most processing will be handled by Browserify, so - * there are no benefits like tree-shaking. - * - * @param content - The input file contents as a string. - * @param sourceMap - The source map of the input file. - * @returns The Browserify loader. - */ -const loader: LoaderDefinitionFunction = async function ( - content, - sourceMap, -) { - const config = this.getOptions(); - - const { transpilationMode } = config; - - const bundler = browserify({ - extensions: ['.js', '.jsx', '.ts', '.tsx'], - debug: Boolean(sourceMap), - standalone: '', - }); - - if (transpilationMode !== TranspilationModes.None) { - const babelifyOptions = processDependencies(config); - - // We need to statically import all Browserify transforms, and all Babel - // presets and plugins, and calling `require` is the sanest way to do that. - /* eslint-disable @typescript-eslint/no-require-imports, n/global-require */ - bundler.transform(require('babelify'), { - global: transpilationMode === TranspilationModes.LocalAndDeps, - extensions: ['.js', '.jsx', '.ts', '.tsx'], - presets: [ - require('@babel/preset-typescript'), - [ - require('@babel/preset-env'), - { - targets: { - browsers: await getBrowserslistTargets(), - }, - }, - ], - ], - plugins: [ - require('@babel/plugin-transform-runtime'), - require('@babel/plugin-transform-class-properties'), - require('@babel/plugin-transform-private-methods'), - require('@babel/plugin-transform-class-static-block'), - require('@babel/plugin-transform-private-property-in-object'), - ], - ...(babelifyOptions as any), - }); - /* eslint-enable @typescript-eslint/no-require-imports, n/global-require */ - } - - config.bundlerCustomizer?.(bundler); - - // Browserify doesn't accept a string as an entry point, so we need to convert - // it to a stream. - const stream = new Readable(); - stream.push(content); - stream.push(null); - - bundler.add(stream, { - file: this.resourcePath, - }); - - return new Promise((resolve, reject) => { - bundler.bundle((bundleError, buffer: Buffer) => { - if (bundleError) { - reject(bundleError); - return; - } - - // Browserify inlines the source map, so we just pass the output buffer back - // to Webpack. - resolve(buffer); - }); - }); -}; - -export default loader; diff --git a/packages/snaps-cli/src/webpack/loaders/function.test.ts b/packages/snaps-cli/src/webpack/loaders/function.test.ts index 3574a4d242..0b497d15b3 100644 --- a/packages/snaps-cli/src/webpack/loaders/function.test.ts +++ b/packages/snaps-cli/src/webpack/loaders/function.test.ts @@ -1,6 +1,6 @@ import { resolve } from 'path'; -import loader, { getFunctionLoader } from './function'; +import loader, { getFunctionLoader, raw } from './function'; describe('getFunctionLoader', () => { it('returns a loader definition', () => { @@ -35,4 +35,10 @@ describe('loader', () => { expect(fn).toHaveBeenCalledWith('test'); }); + + describe('raw', () => { + it('is `true`', () => { + expect(raw).toBe(true); + }); + }); }); diff --git a/packages/snaps-cli/src/webpack/loaders/function.ts b/packages/snaps-cli/src/webpack/loaders/function.ts index 52434bddb5..d8db53c575 100644 --- a/packages/snaps-cli/src/webpack/loaders/function.ts +++ b/packages/snaps-cli/src/webpack/loaders/function.ts @@ -29,6 +29,11 @@ const loader: LoaderDefinitionFunction = function ( export default loader; +// By setting `raw` to `true`, we are telling Webpack to provide the source as a +// `Uint8Array` instead of converting it to a string. This allows us to avoid +// having to convert the source back to a `Uint8Array` in the loader. +export const raw = true; + /** * Get a loader that executes the given function. This is useful for executing * loaders without needing to pass a file to Webpack. @@ -51,12 +56,3 @@ export function getFunctionLoader( }, }; } - -// When running as CJS, we need to export the loader as a default export, since -// `tsup` exports it as `loader_default`. -// istanbul ignore next 3 -if (typeof module !== 'undefined' && process?.env?.NODE_ENV !== 'test') { - module.exports = loader; - module.exports.getFunctionLoader = getFunctionLoader; - module.exports.raw = true; -} diff --git a/packages/snaps-cli/src/webpack/loaders/index.ts b/packages/snaps-cli/src/webpack/loaders/index.ts index 7c3da56aff..b155aef3e9 100644 --- a/packages/snaps-cli/src/webpack/loaders/index.ts +++ b/packages/snaps-cli/src/webpack/loaders/index.ts @@ -1,3 +1,2 @@ export * from './function'; -export { default as browserify } from './browserify'; export { default as wasm } from './wasm'; diff --git a/packages/snaps-cli/src/webpack/server.test.ts b/packages/snaps-cli/src/webpack/server.test.ts index 2e9fc85ed5..bad04f8981 100644 --- a/packages/snaps-cli/src/webpack/server.test.ts +++ b/packages/snaps-cli/src/webpack/server.test.ts @@ -1,4 +1,3 @@ -import { getMockConfig } from '@metamask/snaps-cli/test-utils'; import { getSnapManifest } from '@metamask/snaps-utils/test-utils'; import fetch from 'cross-fetch'; import { promises as fs } from 'fs'; @@ -6,6 +5,7 @@ import http, { IncomingMessage, Server, ServerResponse } from 'http'; import serveMiddleware from 'serve-handler'; import { getAllowedPaths, getServer } from './server'; +import { getMockConfig } from '../test-utils'; jest.mock('fs'); jest.mock('serve-handler', () => @@ -16,7 +16,7 @@ jest.mock('serve-handler', () => describe('getAllowedPaths', () => { it('returns the allowed paths for a given config', () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', output: { path: '/foo/dist', @@ -38,7 +38,7 @@ describe('getAllowedPaths', () => { }); it('returns the allowed paths for a given config with auxiliary files', () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', output: { path: '/foo/dist', @@ -64,7 +64,7 @@ describe('getAllowedPaths', () => { }); it('returns the allowed paths for a given config with localization files', () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', output: { path: '/foo/dist', @@ -90,7 +90,7 @@ describe('getAllowedPaths', () => { }); it('returns the allowed paths for a given config with auxiliary files and localization files', () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', output: { path: '/foo/dist', @@ -119,7 +119,7 @@ describe('getAllowedPaths', () => { }); it('returns the allowed paths for a given config without an icon', () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', output: { path: '/foo/dist', @@ -148,7 +148,7 @@ describe('getServer', () => { }); it('creates a static server', async () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', server: { root: '/foo', @@ -168,7 +168,7 @@ describe('getServer', () => { }); it('listens to a specific port', async () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', server: { root: '/foo', @@ -185,7 +185,7 @@ describe('getServer', () => { }); it('listens to the port specified in the listen function', async () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', server: { root: '/foo', @@ -202,7 +202,7 @@ describe('getServer', () => { }); it('calls the serve middleware for allowed files', async () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', server: { root: '/foo', @@ -228,7 +228,7 @@ describe('getServer', () => { }); it('ignores query strings', async () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', server: { root: '/foo', @@ -256,7 +256,7 @@ describe('getServer', () => { }); it('responds with 404 for non-allowed files', async () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', server: { root: '/foo', @@ -277,7 +277,7 @@ describe('getServer', () => { }); it('throws if the port is already in use', async () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', server: { root: '/foo', @@ -299,7 +299,7 @@ describe('getServer', () => { }); it('throws if the server fails to close', async () => { - const config = getMockConfig('webpack', { + const config = getMockConfig({ input: 'src/index.js', server: { root: '/foo', diff --git a/packages/snaps-cli/src/webpack/utils.test.ts b/packages/snaps-cli/src/webpack/utils.test.ts index 464c2d7ef6..8d115e7bdf 100644 --- a/packages/snaps-cli/src/webpack/utils.test.ts +++ b/packages/snaps-cli/src/webpack/utils.test.ts @@ -1,6 +1,5 @@ import { dim } from 'chalk'; -import { browserify } from './loaders'; import { WEBPACK_FALLBACKS, getBrowserslistTargets, @@ -13,23 +12,12 @@ import { formatText, getImageSVG, } from './utils'; -import type { ProcessedWebpackConfig } from '../config'; +import type { ProcessedConfig } from '../config'; import { getMockConfig } from '../test-utils'; describe('getDefaultLoader', () => { - it('returns the Browserify loader if `legacy` is set', async () => { - const config = getMockConfig('browserify'); - expect(await getDefaultLoader(config)).toStrictEqual({ - loader: expect.stringContaining('function'), - options: { - ...config.legacy, - fn: browserify, - }, - }); - }); - - it('returns the SWC loader if `legacy` is not set', async () => { - const config = getMockConfig('webpack'); + it('returns the SWC loader', async () => { + const config = getMockConfig(); expect(await getDefaultLoader(config)).toStrictEqual({ loader: expect.stringContaining('swc-loader'), options: expect.any(Object), @@ -120,7 +108,7 @@ describe('getFallbacks', () => { const config = { buffer: true, crypto: false, - } as ProcessedWebpackConfig['polyfills']; + } as ProcessedConfig['polyfills']; const fallbacks = getFallbacks(config); diff --git a/packages/snaps-cli/src/webpack/utils.ts b/packages/snaps-cli/src/webpack/utils.ts index 822d6f9a7d..5f4ac1e8f0 100644 --- a/packages/snaps-cli/src/webpack/utils.ts +++ b/packages/snaps-cli/src/webpack/utils.ts @@ -7,8 +7,7 @@ import { dirname, resolve } from 'path'; import stripAnsi from 'strip-ansi'; import type { Configuration } from 'webpack'; -import { browserify, getFunctionLoader } from './loaders'; -import type { ProcessedWebpackConfig } from '../config'; +import type { ProcessedConfig } from '../config'; export const BROWSERSLIST_FILE = resolve( dirname(require.resolve('@metamask/snaps-cli/package.json')), @@ -54,32 +53,15 @@ export const WEBPACK_FALLBACKS = { * Get the default loader for JavaScript and TypeScript files, based on the * config object. * - * - If the `legacy` option is set, we use the custom `browserify` loader. This - * uses the legacy Browserify config to transpile the code. - * - Otherwise, we use the `swc-loader`. This is a Webpack loader that uses the - * `SWC` compiler, which is a much faster alternative to Babel and TypeScript's - * own compiler. + * We use the `swc-loader`, which is a Webpack loader that uses the `SWC` + * compiler, a much faster alternative to Babel and TypeScript's own compiler. * * @param config - The processed snap Webpack config. - * @param config.legacy - The legacy config object, if any. * @param config.sourceMap - Whether to generate source maps. * @see https://swc.rs/docs/usage/swc-loader * @returns The default loader. */ -export async function getDefaultLoader({ - legacy, - sourceMap, -}: ProcessedWebpackConfig) { - if (legacy) { - /** - * If the snap uses the legacy config, we use the custom `browserify` - * loader. This uses the legacy Browserify config to transpile the code. - * This is necessary for backwards compatibility with the - * `bundlerCustomizer` function. - */ - return getFunctionLoader(browserify, legacy); - } - +export async function getDefaultLoader({ sourceMap }: ProcessedConfig) { const targets = await getBrowserslistTargets(); return { /** @@ -193,7 +175,7 @@ export async function getDefaultLoader({ * @returns The Webpack devtool configuration. */ export function getDevTool( - sourceMap: ProcessedWebpackConfig['sourceMap'], + sourceMap: ProcessedConfig['sourceMap'], ): Configuration['devtool'] { if (sourceMap === 'inline') { return 'inline-source-map'; @@ -275,7 +257,7 @@ export function pluralize( * @param polyfills - The polyfill object from the snap config. * @returns The webpack fallback config. */ -export function getFallbacks(polyfills: ProcessedWebpackConfig['polyfills']): { +export function getFallbacks(polyfills: ProcessedConfig['polyfills']): { [index: string]: string | false; } { if (polyfills === true) { @@ -294,7 +276,7 @@ export function getFallbacks(polyfills: ProcessedWebpackConfig['polyfills']): { return Object.fromEntries( builtinModules.map((name) => [ name, - polyfills[name as keyof ProcessedWebpackConfig['polyfills']] + polyfills[name as keyof ProcessedConfig['polyfills']] ? WEBPACK_FALLBACKS[name as keyof typeof WEBPACK_FALLBACKS] : false, ]), diff --git a/packages/snaps-cli/tsconfig.build.json b/packages/snaps-cli/tsconfig.build.json index 8b4bb8a851..928035a654 100644 --- a/packages/snaps-cli/tsconfig.build.json +++ b/packages/snaps-cli/tsconfig.build.json @@ -15,7 +15,6 @@ ], "references": [ { "path": "../snaps-utils/tsconfig.build.json" }, - { "path": "../snaps-browserify-plugin/tsconfig.build.json" }, { "path": "../snaps-webpack-plugin/tsconfig.build.json" } ] } diff --git a/packages/snaps-cli/tsconfig.json b/packages/snaps-cli/tsconfig.json index be873d2de1..cafe82043a 100644 --- a/packages/snaps-cli/tsconfig.json +++ b/packages/snaps-cli/tsconfig.json @@ -7,7 +7,6 @@ "include": ["./src", "./src/**/*.json", "jest.setup.ts", "package.json"], "references": [ { "path": "../snaps-utils" }, - { "path": "../snaps-browserify-plugin" }, { "path": "../snaps-webpack-plugin" } ] } diff --git a/yarn.lock b/yarn.lock index 6df5ffd265..8188258d1f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1141,22 +1141,6 @@ __metadata: languageName: node linkType: hard -"@babel/plugin-transform-runtime@npm:^7.13.2": - version: 7.23.2 - resolution: "@babel/plugin-transform-runtime@npm:7.23.2" - dependencies: - "@babel/helper-module-imports": "npm:^7.22.15" - "@babel/helper-plugin-utils": "npm:^7.22.5" - babel-plugin-polyfill-corejs2: "npm:^0.4.6" - babel-plugin-polyfill-corejs3: "npm:^0.8.5" - babel-plugin-polyfill-regenerator: "npm:^0.5.3" - semver: "npm:^6.3.1" - peerDependencies: - "@babel/core": ^7.0.0-0 - checksum: 10/536c444c494a43c1de4eec8297242199a7e778a82f64a8203a15bec46af17757ad59b520ee1fb414a03100ae743b8a2ca8527b6c0e4cc3e05be9ac1361260a44 - languageName: node - linkType: hard - "@babel/plugin-transform-shorthand-properties@npm:^7.22.5": version: 7.22.5 resolution: "@babel/plugin-transform-shorthand-properties@npm:7.22.5" @@ -4168,31 +4152,6 @@ __metadata: languageName: node linkType: hard -"@metamask/browserify-example-snap@workspace:packages/examples/packages/browserify": - version: 0.0.0-use.local - resolution: "@metamask/browserify-example-snap@workspace:packages/examples/packages/browserify" - dependencies: - "@jest/globals": "npm:^29.5.0" - "@lavamoat/allow-scripts": "npm:^3.0.4" - "@metamask/auto-changelog": "npm:^5.0.1" - "@metamask/snaps-cli": "workspace:^" - "@metamask/snaps-jest": "workspace:^" - "@metamask/snaps-sdk": "workspace:^" - "@swc/core": "npm:1.3.78" - "@swc/jest": "npm:^0.2.26" - "@types/node": "npm:18.14.2" - deepmerge: "npm:^4.2.2" - depcheck: "npm:^1.4.7" - eslint: "npm:^9.11.0" - jest: "npm:^29.0.2" - jest-silent-reporter: "npm:^0.6.0" - prettier: "npm:^3.3.3" - rimraf: "npm:^4.1.2" - ts-node: "npm:^10.9.1" - typescript: "npm:~5.3.3" - languageName: unknown - linkType: soft - "@metamask/browserify-plugin-example-snap@workspace:packages/examples/packages/browserify-plugin": version: 0.0.0-use.local resolution: "@metamask/browserify-plugin-example-snap@workspace:packages/examples/packages/browserify-plugin" @@ -5413,14 +5372,6 @@ __metadata: version: 0.0.0-use.local resolution: "@metamask/snaps-cli@workspace:packages/snaps-cli" dependencies: - "@babel/core": "npm:^7.23.2" - "@babel/plugin-transform-class-properties": "npm:^7.22.5" - "@babel/plugin-transform-class-static-block": "npm:^7.22.11" - "@babel/plugin-transform-private-methods": "npm:^7.22.5" - "@babel/plugin-transform-private-property-in-object": "npm:^7.22.11" - "@babel/plugin-transform-runtime": "npm:^7.13.2" - "@babel/preset-env": "npm:^7.23.2" - "@babel/preset-typescript": "npm:^7.23.2" "@lavamoat/allow-scripts": "npm:^3.0.4" "@metamask/auto-changelog": "npm:^5.0.1" "@metamask/snaps-sdk": "workspace:^" @@ -5431,14 +5382,11 @@ __metadata: "@swc/core": "npm:1.3.78" "@swc/jest": "npm:^0.2.26" "@ts-bridge/cli": "npm:^0.6.1" - "@types/browserify": "npm:^12.0.37" "@types/jest": "npm:^27.5.1" "@types/node": "npm:18.14.2" "@types/serve-handler": "npm:^6.1.0" "@types/yargs": "npm:^17.0.24" assert: "npm:^2.0.0" - babelify: "npm:^10.0.0" - browserify: "npm:^17.0.0" browserify-zlib: "npm:^0.2.0" buffer: "npm:^6.0.3" chalk: "npm:^4.1.2" @@ -5487,7 +5435,7 @@ __metadata: webpack-merge: "npm:^5.9.0" yargs: "npm:^17.7.1" bin: - mm-snap: ./dist/main.cjs + mm-snap: ./dist/main.mjs languageName: unknown linkType: soft