@metamask/snaps-cli 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.8.0]
10
+ ### Changed
11
+ - Update template snap created by `mm-snap init` ([#195](https://github.com/MetaMask/snaps-skunkworks/pull/195))
12
+ - Exit by throwing errors instead of calling `process.exit` ([#190](https://github.com/MetaMask/snaps-skunkworks/pull/190))
13
+
14
+ ## [0.7.0]
15
+ ### Added
16
+ - ESM support for `mm-snap build` ([#185](https://github.com/MetaMask/snaps-skunkworks/pull/185))
17
+ - The `build` command can now handle snap source code that includes ESM import / export statements. They will be transpiled to their CommonJS equivalents via Babel.
18
+
19
+ ### Fixed
20
+ - Fix `mm-snap init` `src` default value ([#186](https://github.com/MetaMask/snaps-skunkworks/pull/186))
21
+ - It now correctly defaults to `src/index.js` instead of just `index.js`.
22
+ - Fix comment stripping ([#189](https://github.com/MetaMask/snaps-skunkworks/pull/189))
23
+ - Comments wouldn't be stripped under certain circumstances due to a RegEx error, details [here](https://github.com/jonschlinkert/strip-comments/pull/49).
24
+
25
+ ## [0.6.3]
26
+ ### Changed
27
+ - No changes this release.
28
+
29
+ ## [0.6.2]
30
+ ### Changed
31
+ - No changes this release.
32
+
9
33
  ## [0.6.1]
10
34
  ### Fixed
11
35
  - `mm-snap init` Snap `snap_confirm` call ([#168](https://github.com/MetaMask/snaps-skunkworks/pull/168))
@@ -65,7 +89,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
65
89
  - Example snaps ([#72](https://github.com/MetaMask/snaps-skunkworks/pull/72))
66
90
  - The examples now live in their own package, [`@metamask/snap-examples`](https://npmjs.com/package/@metamask/snap-examples).
67
91
 
68
- [Unreleased]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.6.1...HEAD
92
+ [Unreleased]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.8.0...HEAD
93
+ [0.8.0]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.7.0...v0.8.0
94
+ [0.7.0]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.6.3...v0.7.0
95
+ [0.6.3]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.6.2...v0.6.3
96
+ [0.6.2]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.6.1...v0.6.2
69
97
  [0.6.1]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.6.0...v0.6.1
70
98
  [0.6.0]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.5.0...v0.6.0
71
99
  [0.5.0]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.4.0...v0.5.0
package/README.md CHANGED
@@ -35,12 +35,12 @@ Here's an example manifest:
35
35
 
36
36
  ```json
37
37
  {
38
- "version": "0.2.2",
39
- "proposedName": "@metamask/example-snap",
40
- "description": "An example snap.",
38
+ "version": "0.7.0",
39
+ "proposedName": "@metamask/template-snap",
40
+ "description": "A MetaMask Snap template.",
41
41
  "repository": {
42
42
  "type": "git",
43
- "url": "https://github.com/MetaMask/example-snap.git"
43
+ "url": "https://github.com/MetaMask/template-snap.git"
44
44
  },
45
45
  "source": {
46
46
  "shasum": "w3FltkDjKQZiPwM+AThnmypt0OFF7hj4ycg/kxxv+nU=",
@@ -48,7 +48,7 @@ Here's an example manifest:
48
48
  "npm": {
49
49
  "filePath": "dist/bundle.js",
50
50
  "iconPath": "images/icon.svg",
51
- "packageName": "@metamask/example-snap",
51
+ "packageName": "@metamask/template-snap",
52
52
  "registry": "https://registry.npmjs.org/"
53
53
  }
54
54
  }
package/dist/cli.js CHANGED
@@ -5,8 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.cli = void 0;
7
7
  const yargs_1 = __importDefault(require("yargs"));
8
- const utils_1 = require("./utils");
9
8
  const builders_1 = __importDefault(require("./builders"));
9
+ const utils_1 = require("./utils");
10
10
  function cli(argv, commands) {
11
11
  const rawArgv = argv.slice(2);
12
12
  // eslint-disable-next-line @typescript-eslint/no-unused-expressions
@@ -35,7 +35,7 @@ function cli(argv, commands) {
35
35
  if ((err === null || err === void 0 ? void 0 : err.stack) && global.snaps.verboseErrors) {
36
36
  console.error(err.stack);
37
37
  }
38
- process.exit(1);
38
+ process.exitCode = 1;
39
39
  })
40
40
  .demandCommand(1, 'You must specify at least one command.')
41
41
  .help()
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;;;;;AAAA,kDAAyC;AAGzC,mCAAsE;AACtE,0DAAkC;AAElC,SAAgB,GAAG,CAAC,IAAc,EAAE,QAAa;IAC/C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC9B,oEAAoE;IACpE,eAAK,CAAC,OAAO,CAAC;SACX,KAAK,CAAC,+BAA+B,CAAC;SAEtC,OAAO,CAAC,SAAS,EAAE,wCAAwC,CAAC;SAC5D,OAAO,CACN,iCAAiC,EACjC,6CAA6C,CAC9C;SACA,OAAO,CACN,4CAA4C,EAC5C,2CAA2C,CAC5C;SACA,OAAO,CAAC,iBAAiB,EAAE,uCAAuC,CAAC;SACnE,OAAO,CAAC,yBAAyB,EAAE,uCAAuC,CAAC;SAC3E,OAAO,CACN,iCAAiC,EACjC,gGAAgG,CACjG;SAEA,OAAO,CAAC,QAAQ,CAAC;SAEjB,MAAM,CAAC,eAAe,EAAE,kBAAQ,CAAC,aAAa,CAAC;SAE/C,MAAM,CAAC,kBAAkB,EAAE,kBAAQ,CAAC,gBAAgB,CAAC;SAErD,MAAM,EAAE;QAET,gEAAgE;QAChE,+EAA+E;QAC/E,0FAA0F;SACzF,UAAU,CACT,CAAC,CAAC,SAAoB,EAAE,aAA+B,EAAE,EAAE;QACzD,mBAAW,CAAC,OAAO,EAAE,SAAS,EAAE,aAAa,CAAC,CAAC;QAC/C,sBAAc,CAAC,SAAS,CAAC,CAAC;QAC1B,sBAAc,CAAC,SAAS,CAAC,CAAC;IAC5B,CAAC,CAAQ,EACT,IAAI,CACL;SAEA,IAAI,CAAC,CAAC,GAAW,EAAE,GAAU,EAAE,MAAM,EAAE,EAAE;QACxC,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC;QAClC,IAAI,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,KAAK,KAAI,MAAM,CAAC,KAAK,CAAC,aAAa,EAAE;YAC5C,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;SAC1B;QACD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC;SAED,aAAa,CAAC,CAAC,EAAE,wCAAwC,CAAC;SAE1D,IAAI,EAAE;SACN,KAAK,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC;AAC7B,CAAC;AAtDD,kBAsDC","sourcesContent":["import yargs, { Arguments } from 'yargs';\nimport yargsType from 'yargs/yargs';\n\nimport { applyConfig, sanitizeInputs, setSnapGlobals } from './utils';\nimport builders from './builders';\n\nexport function cli(argv: string[], commands: any): void {\n const rawArgv = argv.slice(2);\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n yargs(rawArgv)\n .usage('Usage: $0 <command> [options]')\n\n .example('$0 init', `\\tInitialize Snap package from scratch`)\n .example(\n '$0 build -s src/index.js -d out',\n `\\tBuild 'src/index.js' as './out/bundle.js'`,\n )\n .example(\n '$0 build -s src/index.js -d out -n snap.js',\n `\\tBuild 'src/index.js' as './out/snap.js'`,\n )\n .example('$0 serve -r out', `\\tServe files in './out' on port 8080`)\n .example('$0 serve -r out -p 9000', `\\tServe files in './out' on port 9000`)\n .example(\n '$0 watch -s src/index.js -d out',\n `\\tRebuild './out/bundle.js' on changes to files in 'src/index.js' parent and child directories`,\n )\n\n .command(commands)\n\n .option('verboseErrors', builders.verboseErrors)\n\n .option('suppressWarnings', builders.suppressWarnings)\n\n .strict()\n\n // Typecast: The @types/yargs type for .middleware is incorrect.\n // yargs middleware functions receive the yargs instance as a second parameter.\n // ref: https://yargs.js.org/docs/#api-reference-middlewarecallbacks-applybeforevalidation\n .middleware(\n ((yargsArgv: Arguments, yargsInstance: typeof yargsType) => {\n applyConfig(rawArgv, yargsArgv, yargsInstance);\n setSnapGlobals(yargsArgv);\n sanitizeInputs(yargsArgv);\n }) as any,\n true,\n )\n\n .fail((msg: string, err: Error, _yargs) => {\n console.error(msg || err.message);\n if (err?.stack && global.snaps.verboseErrors) {\n console.error(err.stack);\n }\n process.exit(1);\n })\n\n .demandCommand(1, 'You must specify at least one command.')\n\n .help()\n .alias('help', 'h').argv;\n}\n"]}
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;;;;;AAAA,kDAAyC;AAEzC,0DAAkC;AAClC,mCAAsE;AAEtE,SAAgB,GAAG,CAAC,IAAc,EAAE,QAAa;IAC/C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC9B,oEAAoE;IACpE,eAAK,CAAC,OAAO,CAAC;SACX,KAAK,CAAC,+BAA+B,CAAC;SAEtC,OAAO,CAAC,SAAS,EAAE,wCAAwC,CAAC;SAC5D,OAAO,CACN,iCAAiC,EACjC,6CAA6C,CAC9C;SACA,OAAO,CACN,4CAA4C,EAC5C,2CAA2C,CAC5C;SACA,OAAO,CAAC,iBAAiB,EAAE,uCAAuC,CAAC;SACnE,OAAO,CAAC,yBAAyB,EAAE,uCAAuC,CAAC;SAC3E,OAAO,CACN,iCAAiC,EACjC,gGAAgG,CACjG;SAEA,OAAO,CAAC,QAAQ,CAAC;SAEjB,MAAM,CAAC,eAAe,EAAE,kBAAQ,CAAC,aAAa,CAAC;SAE/C,MAAM,CAAC,kBAAkB,EAAE,kBAAQ,CAAC,gBAAgB,CAAC;SAErD,MAAM,EAAE;QAET,gEAAgE;QAChE,+EAA+E;QAC/E,0FAA0F;SACzF,UAAU,CACT,CAAC,CAAC,SAAoB,EAAE,aAA+B,EAAE,EAAE;QACzD,mBAAW,CAAC,OAAO,EAAE,SAAS,EAAE,aAAa,CAAC,CAAC;QAC/C,sBAAc,CAAC,SAAS,CAAC,CAAC;QAC1B,sBAAc,CAAC,SAAS,CAAC,CAAC;IAC5B,CAAC,CAAQ,EACT,IAAI,CACL;SAEA,IAAI,CAAC,CAAC,GAAW,EAAE,GAAU,EAAE,MAAM,EAAE,EAAE;QACxC,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC;QAClC,IAAI,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,KAAK,KAAI,MAAM,CAAC,KAAK,CAAC,aAAa,EAAE;YAC5C,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;SAC1B;QACD,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC;SAED,aAAa,CAAC,CAAC,EAAE,wCAAwC,CAAC;SAE1D,IAAI,EAAE;SACN,KAAK,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC;AAC7B,CAAC;AAtDD,kBAsDC","sourcesContent":["import yargs, { Arguments } from 'yargs';\nimport yargsType from 'yargs/yargs';\nimport builders from './builders';\nimport { applyConfig, sanitizeInputs, setSnapGlobals } from './utils';\n\nexport function cli(argv: string[], commands: any): void {\n const rawArgv = argv.slice(2);\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n yargs(rawArgv)\n .usage('Usage: $0 <command> [options]')\n\n .example('$0 init', `\\tInitialize Snap package from scratch`)\n .example(\n '$0 build -s src/index.js -d out',\n `\\tBuild 'src/index.js' as './out/bundle.js'`,\n )\n .example(\n '$0 build -s src/index.js -d out -n snap.js',\n `\\tBuild 'src/index.js' as './out/snap.js'`,\n )\n .example('$0 serve -r out', `\\tServe files in './out' on port 8080`)\n .example('$0 serve -r out -p 9000', `\\tServe files in './out' on port 9000`)\n .example(\n '$0 watch -s src/index.js -d out',\n `\\tRebuild './out/bundle.js' on changes to files in 'src/index.js' parent and child directories`,\n )\n\n .command(commands)\n\n .option('verboseErrors', builders.verboseErrors)\n\n .option('suppressWarnings', builders.suppressWarnings)\n\n .strict()\n\n // Typecast: The @types/yargs type for .middleware is incorrect.\n // yargs middleware functions receive the yargs instance as a second parameter.\n // ref: https://yargs.js.org/docs/#api-reference-middlewarecallbacks-applybeforevalidation\n .middleware(\n ((yargsArgv: Arguments, yargsInstance: typeof yargsType) => {\n applyConfig(rawArgv, yargsArgv, yargsInstance);\n setSnapGlobals(yargsArgv);\n sanitizeInputs(yargsArgv);\n }) as any,\n true,\n )\n\n .fail((msg: string, err: Error, _yargs) => {\n console.error(msg || err.message);\n if (err?.stack && global.snaps.verboseErrors) {\n console.error(err.stack);\n }\n process.exitCode = 1;\n })\n\n .demandCommand(1, 'You must specify at least one command.')\n\n .help()\n .alias('help', 'h').argv;\n}\n"]}
@@ -19,7 +19,27 @@ function bundle(src, dest, argv) {
19
19
  const { sourceMaps: debug } = argv;
20
20
  return new Promise((resolve, _reject) => {
21
21
  const bundleStream = bundleUtils_1.createBundleStream(dest);
22
- browserify_1.default(src, { debug }).bundle(async (bundleError, bundleBuffer) => await bundleUtils_1.closeBundleStream({
22
+ browserify_1.default(src, { debug })
23
+ .transform('babelify', {
24
+ presets: [
25
+ [
26
+ '@babel/preset-env',
27
+ {
28
+ targets: {
29
+ browsers: ['chrome >= 66', 'firefox >= 68'],
30
+ },
31
+ },
32
+ ],
33
+ ],
34
+ plugins: [
35
+ '@babel/plugin-transform-runtime',
36
+ '@babel/plugin-proposal-class-properties',
37
+ '@babel/plugin-proposal-object-rest-spread',
38
+ '@babel/plugin-proposal-optional-chaining',
39
+ '@babel/plugin-proposal-nullish-coalescing-operator',
40
+ ],
41
+ })
42
+ .bundle(async (bundleError, bundleBuffer) => await bundleUtils_1.closeBundleStream({
23
43
  bundleError,
24
44
  bundleBuffer,
25
45
  bundleStream,
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.js","sourceRoot":"","sources":["../../../src/cmds/build/bundle.ts"],"names":[],"mappings":";;;;;;AAAA,4DAAoC;AAEpC,+CAAsE;AAEtE;;;;;;;;GAQG;AACH,SAAgB,MAAM,CACpB,GAAW,EACX,IAAY,EACZ,IAAe;IAEf,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;IAEnC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE;QACtC,MAAM,YAAY,GAAG,gCAAkB,CAAC,IAAI,CAAC,CAAC;QAC9C,oBAAU,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC,MAAM,CAC/B,KAAK,EAAE,WAAW,EAAE,YAAoB,EAAE,EAAE,CAC1C,MAAM,+BAAiB,CAAC;YACtB,WAAW;YACX,YAAY;YACZ,YAAY;YACZ,GAAG;YACH,IAAI;YACJ,OAAO;YACP,IAAI;SACL,CAAC,CACL,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAtBD,wBAsBC","sourcesContent":["import browserify from 'browserify';\nimport { YargsArgs } from '../../types/yargs';\nimport { createBundleStream, closeBundleStream } from './bundleUtils';\n\n/**\n * Builds a Snap bundle JSON file from its JavaScript source.\n *\n * @param src - The source file path\n * @param dest - The destination file path\n * @param argv - arguments as an object generated by yargs\n * @param argv.sourceMaps - Whether to output sourcemaps\n * @param argv.stripComments - Whether to remove comments from code\n */\nexport function bundle(\n src: string,\n dest: string,\n argv: YargsArgs,\n): Promise<boolean> {\n const { sourceMaps: debug } = argv;\n\n return new Promise((resolve, _reject) => {\n const bundleStream = createBundleStream(dest);\n browserify(src, { debug }).bundle(\n async (bundleError, bundleBuffer: Buffer) =>\n await closeBundleStream({\n bundleError,\n bundleBuffer,\n bundleStream,\n src,\n dest,\n resolve,\n argv,\n }),\n );\n });\n}\n"]}
1
+ {"version":3,"file":"bundle.js","sourceRoot":"","sources":["../../../src/cmds/build/bundle.ts"],"names":[],"mappings":";;;;;;AAAA,4DAAoC;AAEpC,+CAAsE;AAEtE;;;;;;;;GAQG;AACH,SAAgB,MAAM,CACpB,GAAW,EACX,IAAY,EACZ,IAAe;IAEf,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;IAEnC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE;QACtC,MAAM,YAAY,GAAG,gCAAkB,CAAC,IAAI,CAAC,CAAC;QAC9C,oBAAU,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC;aACvB,SAAS,CAAC,UAAU,EAAE;YACrB,OAAO,EAAE;gBACP;oBACE,mBAAmB;oBACnB;wBACE,OAAO,EAAE;4BACP,QAAQ,EAAE,CAAC,cAAc,EAAE,eAAe,CAAC;yBAC5C;qBACF;iBACF;aACF;YACD,OAAO,EAAE;gBACP,iCAAiC;gBACjC,yCAAyC;gBACzC,2CAA2C;gBAC3C,0CAA0C;gBAC1C,oDAAoD;aACrD;SACF,CAAC;aACD,MAAM,CACL,KAAK,EAAE,WAAW,EAAE,YAAoB,EAAE,EAAE,CAC1C,MAAM,+BAAiB,CAAC;YACtB,WAAW;YACX,YAAY;YACZ,YAAY;YACZ,GAAG;YACH,IAAI;YACJ,OAAO;YACP,IAAI;SACL,CAAC,CACL,CAAC;IACN,CAAC,CAAC,CAAC;AACL,CAAC;AA1CD,wBA0CC","sourcesContent":["import browserify from 'browserify';\nimport { YargsArgs } from '../../types/yargs';\nimport { createBundleStream, closeBundleStream } from './bundleUtils';\n\n/**\n * Builds a Snap bundle JSON file from its JavaScript source.\n *\n * @param src - The source file path\n * @param dest - The destination file path\n * @param argv - arguments as an object generated by yargs\n * @param argv.sourceMaps - Whether to output sourcemaps\n * @param argv.stripComments - Whether to remove comments from code\n */\nexport function bundle(\n src: string,\n dest: string,\n argv: YargsArgs,\n): Promise<boolean> {\n const { sourceMaps: debug } = argv;\n\n return new Promise((resolve, _reject) => {\n const bundleStream = createBundleStream(dest);\n browserify(src, { debug })\n .transform('babelify', {\n presets: [\n [\n '@babel/preset-env',\n {\n targets: {\n browsers: ['chrome >= 66', 'firefox >= 68'],\n },\n },\n ],\n ],\n plugins: [\n '@babel/plugin-transform-runtime',\n '@babel/plugin-proposal-class-properties',\n '@babel/plugin-proposal-object-rest-spread',\n '@babel/plugin-proposal-optional-chaining',\n '@babel/plugin-proposal-nullish-coalescing-operator',\n ],\n })\n .bundle(\n async (bundleError, bundleBuffer: Buffer) =>\n await closeBundleStream({\n bundleError,\n bundleBuffer,\n bundleStream,\n src,\n dest,\n resolve,\n argv,\n }),\n );\n });\n}\n"]}
@@ -5,7 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.postProcess = exports.closeBundleStream = exports.createBundleStream = void 0;
7
7
  const fs_1 = require("fs");
8
- const strip_comments_1 = __importDefault(require("strip-comments"));
8
+ const strip_comments_1 = __importDefault(require("@nodefactory/strip-comments"));
9
9
  const misc_1 = require("../../utils/misc");
10
10
  /**
11
11
  * Opens a stream to write the destination file path.
@@ -1 +1 @@
1
- {"version":3,"file":"bundleUtils.js","sourceRoot":"","sources":["../../../src/cmds/build/bundleUtils.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAuC;AACvC,oEAA2C;AAC3C,2CAA8C;AAG9C;;;;;GAKG;AACH,SAAgB,kBAAkB,CAAC,IAAY;IAC7C,MAAM,MAAM,GAAG,sBAAiB,CAAC,IAAI,EAAE;QACrC,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,MAAM;KACjB,CAAC,CAAC;IACH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE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AG,eAAe,CAAC,OAAO,CACvC,2CAA2C,EAC3C,WAAW,CACZ,CAAC;IAEF,4EAA4E;IAC5E,8CAA8C;IAC9C,kCAAkC;IAClC,eAAe,GAAG,eAAe,CAAC,OAAO,CACvC,yBAAyB,EACzB,aAAa,CACd,CAAC;IAEF,2EAA2E;IAC3E,8EAA8E;IAC9E,qCAAqC;IACrC,eAAe,GAAG,eAAe,CAAC,OAAO,CACvC,8BAA8B,EAC9B,eAAe,CAChB,CAAC;IAEF,IAAI,eAAe,CAAC,MAAM,KAAK,CAAC,EAAE;QAChC,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;KAChE;IAED,iDAAiD;IACjD,2BAA2B;IAC3B,IAAI,eAAe,CAAC,OAAO,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC,EAAE;QACxD,eAAe,GAAG,4BAA4B,eAAe,EAAE,CAAC;KACjE;IAED,OAAO,eAAe,CAAC;AACzB,CAAC;AA/CD,kCA+CC","sourcesContent":["import { createWriteStream } from 'fs';\nimport stripComments from 'strip-comments';\nimport { writeError } from '../../utils/misc';\nimport { Option, YargsArgs } from '../../types/yargs';\n\n/**\n * Opens a stream to write the destination file path.\n *\n * @param dest - The output file path\n * @returns - The stream\n */\nexport function createBundleStream(dest: string): NodeJS.WritableStream {\n const stream = createWriteStream(dest, {\n autoClose: false,\n encoding: 'utf8',\n });\n stream.on('error', (err) => {\n writeError('Write error:', err.message, err, dest);\n });\n return stream;\n}\n\ntype CloseStreamArgs = {\n bundleError: Error;\n bundleBuffer: Buffer;\n bundleStream: NodeJS.WritableStream;\n src: string;\n dest: string;\n resolve: (value: boolean) => void;\n argv: YargsArgs;\n};\n\n/**\n * Postprocesses the bundle string and closes the write stream.\n *\n * @param stream - The write stream\n * @param bundleString - The bundle string\n * @param options - post process options\n * @param options.stripComments\n */\nexport async function closeBundleStream({\n bundleError,\n bundleBuffer,\n bundleStream,\n src,\n dest,\n resolve,\n argv,\n}: CloseStreamArgs) {\n if (bundleError) {\n await writeError('Build error:', bundleError.message, bundleError);\n }\n\n try {\n bundleStream.end(\n postProcess(bundleBuffer ? bundleBuffer.toString() : null, {\n stripComments: argv.stripComments,\n }) as string,\n );\n\n if (bundleBuffer) {\n console.log(`Build success: '${src}' bundled as '${dest}'!`);\n }\n resolve(true);\n } catch (closeError) {\n await writeError('Write error:', closeError.message, closeError, dest);\n }\n}\n\n/**\n * Postprocesses a JavaScript bundle string such that it can be evaluated in SES.\n * Currently:\n * - converts certain dot notation to string notation (for indexing)\n * - makes all direct calls to eval indirect\n * - wraps original bundle in anonymous function\n * - handles certain Babel-related edge cases\n *\n * @param bundleString - The bundle string\n * @param options - post process options\n * @param options.stripComments\n * @returns - The postprocessed bundle string\n */\nexport function postProcess(\n bundleString: string | null,\n options: Partial<Option> = {},\n): string | null {\n if (typeof bundleString !== 'string') {\n return null;\n }\n\n let processedString = bundleString.trim();\n\n if (options.stripComments) {\n processedString = stripComments(processedString);\n }\n\n // stuff.eval(otherStuff) => (1, stuff.eval)(otherStuff)\n processedString = processedString.replace(\n /((?:\\b[\\w\\d]*[\\])]?\\.)+eval)(\\([^)]*\\))/gu,\n '(1, $1)$2',\n );\n\n // if we don't do the above, the below causes syntax errors if it encounters\n // things of the form: \"something.eval(stuff)\"\n // eval(stuff) => (1, eval)(stuff)\n processedString = processedString.replace(\n /(\\b)(eval)(\\([^)]*\\))/gu,\n '$1(1, $2)$3',\n );\n\n // Browserify provides the Buffer global as an argument to modules that use\n // it, but this does not work in SES. Since we pass in Buffer as an endowment,\n // we can simply remove the argument.\n processedString = processedString.replace(\n /^\\(function \\(Buffer\\)\\{$/gmu,\n '(function (){',\n );\n\n if (processedString.length === 0) {\n throw new Error(`Bundled code is empty after postprocessing.`);\n }\n\n // handle some cases by declaring missing globals\n // Babel regeneratorRuntime\n if (processedString.indexOf('regeneratorRuntime') !== -1) {\n processedString = `var regeneratorRuntime;\\n${processedString}`;\n }\n\n return processedString;\n}\n"]}
1
+ {"version":3,"file":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BC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,WAAW,CACzB,YAA2B,EAC3B,UAA2B,EAAE;IAE7B,IAAI,OAAO,YAAY,KAAK,QAAQ,EAAE;QACpC,OAAO,IAAI,CAAC;KACb;IAED,IAAI,eAAe,GAAG,YAAY,CAAC,IAAI,EAAE,CAAC;IAE1C,IAAI,OAAO,CAAC,aAAa,EAAE;QACzB,eAAe,GAAG,wBAAa,CAAC,eAAe,CAAC,CAAC;KAClD;IAED,wDAAwD;IACxD,eAAe,GAAG,eAAe,CAAC,OAAO,CACvC,2CAA2C,EAC3C,WAAW,CACZ,CAAC;IAEF,4EAA4E;IAC5E,8CAA8C;IAC9C,kCAAkC;IAClC,eAAe,GAAG,eAAe,CAAC,OAAO,CACvC,yBAAyB,EACzB,aAAa,CACd,CAAC;IAEF,2EAA2E;IAC3E,8EAA8E;IAC9E,qCAAqC;IACrC,eAAe,GAAG,eAAe,CAAC,OAAO,CACvC,8BAA8B,EAC9B,eAAe,CAChB,CAAC;IAEF,IAAI,eAAe,CAAC,MAAM,KAAK,CAAC,EAAE;QAChC,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;KAChE;IAED,iDAAiD;IACjD,2BAA2B;IAC3B,IAAI,eAAe,CAAC,OAAO,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC,EAAE;QACxD,eAAe,GAAG,4BAA4B,eAAe,EAAE,CAAC;KACjE;IAED,OAAO,eAAe,CAAC;AACzB,CAAC;AA/CD,kCA+CC","sourcesContent":["import { createWriteStream } from 'fs';\nimport stripComments from '@nodefactory/strip-comments';\nimport { writeError } from '../../utils/misc';\nimport { Option, YargsArgs } from '../../types/yargs';\n\n/**\n * Opens a stream to write the destination file path.\n *\n * @param dest - The output file path\n * @returns - The stream\n */\nexport function createBundleStream(dest: string): NodeJS.WritableStream {\n const stream = createWriteStream(dest, {\n autoClose: false,\n encoding: 'utf8',\n });\n stream.on('error', (err) => {\n writeError('Write error:', err.message, err, dest);\n });\n return stream;\n}\n\ntype CloseStreamArgs = {\n bundleError: Error;\n bundleBuffer: Buffer;\n bundleStream: NodeJS.WritableStream;\n src: string;\n dest: string;\n resolve: (value: boolean) => void;\n argv: YargsArgs;\n};\n\n/**\n * Postprocesses the bundle string and closes the write stream.\n *\n * @param stream - The write stream\n * @param bundleString - The bundle string\n * @param options - post process options\n * @param options.stripComments\n */\nexport async function closeBundleStream({\n bundleError,\n bundleBuffer,\n bundleStream,\n src,\n dest,\n resolve,\n argv,\n}: CloseStreamArgs) {\n if (bundleError) {\n await writeError('Build error:', bundleError.message, bundleError);\n }\n\n try {\n bundleStream.end(\n postProcess(bundleBuffer ? bundleBuffer.toString() : null, {\n stripComments: argv.stripComments,\n }) as string,\n );\n\n if (bundleBuffer) {\n console.log(`Build success: '${src}' bundled as '${dest}'!`);\n }\n resolve(true);\n } catch (closeError) {\n await writeError('Write error:', closeError.message, closeError, dest);\n }\n}\n\n/**\n * Postprocesses a JavaScript bundle string such that it can be evaluated in SES.\n * Currently:\n * - converts certain dot notation to string notation (for indexing)\n * - makes all direct calls to eval indirect\n * - wraps original bundle in anonymous function\n * - handles certain Babel-related edge cases\n *\n * @param bundleString - The bundle string\n * @param options - post process options\n * @param options.stripComments\n * @returns - The postprocessed bundle string\n */\nexport function postProcess(\n bundleString: string | null,\n options: Partial<Option> = {},\n): string | null {\n if (typeof bundleString !== 'string') {\n return null;\n }\n\n let processedString = bundleString.trim();\n\n if (options.stripComments) {\n processedString = stripComments(processedString);\n }\n\n // stuff.eval(otherStuff) => (1, stuff.eval)(otherStuff)\n processedString = processedString.replace(\n /((?:\\b[\\w\\d]*[\\])]?\\.)+eval)(\\([^)]*\\))/gu,\n '(1, $1)$2',\n );\n\n // if we don't do the above, the below causes syntax errors if it encounters\n // things of the form: \"something.eval(stuff)\"\n // eval(stuff) => (1, eval)(stuff)\n processedString = processedString.replace(\n /(\\b)(eval)(\\([^)]*\\))/gu,\n '$1(1, $2)$3',\n );\n\n // Browserify provides the Buffer global as an argument to modules that use\n // it, but this does not work in SES. Since we pass in Buffer as an endowment,\n // we can simply remove the argument.\n processedString = processedString.replace(\n /^\\(function \\(Buffer\\)\\{$/gmu,\n '(function (){',\n );\n\n if (processedString.length === 0) {\n throw new Error(`Bundled code is empty after postprocessing.`);\n }\n\n // handle some cases by declaring missing globals\n // Babel regeneratorRuntime\n if (processedString.indexOf('regeneratorRuntime') !== -1) {\n processedString = `var regeneratorRuntime;\\n${processedString}`;\n }\n\n return processedString;\n}\n"]}
@@ -1,2 +1,2 @@
1
1
  import { YargsArgs } from '../../types/yargs';
2
- export declare function snapEval(argv: YargsArgs): Promise<boolean>;
2
+ export declare function snapEval(argv: YargsArgs): Promise<void>;
@@ -9,11 +9,10 @@ async function snapEval(argv) {
9
9
  try {
10
10
  await workerEval_1.workerEval(bundlePath);
11
11
  console.log(`Eval Success: evaluated '${bundlePath}' in SES!`);
12
- return true;
13
12
  }
14
13
  catch (err) {
15
14
  utils_1.logError(`Snap evaluation error: ${err.message}`, err);
16
- process.exit(1);
15
+ throw err;
17
16
  }
18
17
  }
19
18
  exports.snapEval = snapEval;
@@ -1 +1 @@
1
- {"version":3,"file":"evalHandler.js","sourceRoot":"","sources":["../../../src/cmds/eval/evalHandler.ts"],"names":[],"mappings":";;;AACA,uCAAyD;AACzD,6CAA0C;AAEnC,KAAK,UAAU,QAAQ,CAAC,IAAe;IAC5C,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC;IACpC,MAAM,wBAAgB,CAAC,UAAoB,CAAC,CAAC;IAC7C,IAAI;QACF,MAAM,uBAAU,CAAC,UAAoB,CAAC,CAAC;QACvC,OAAO,CAAC,GAAG,CAAC,4BAA4B,UAAU,WAAW,CAAC,CAAC;QAC/D,OAAO,IAAI,CAAC;KACb;IAAC,OAAO,GAAG,EAAE;QACZ,gBAAQ,CAAC,0BAA0B,GAAG,CAAC,OAAO,EAAE,EAAE,GAAG,CAAC,CAAC;QACvD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;KACjB;AACH,CAAC;AAXD,4BAWC","sourcesContent":["import { YargsArgs } from '../../types/yargs';\nimport { logError, validateFilePath } from '../../utils';\nimport { workerEval } from './workerEval';\n\nexport async function snapEval(argv: YargsArgs): Promise<boolean> {\n const { bundle: bundlePath } = argv;\n await validateFilePath(bundlePath as string);\n try {\n await workerEval(bundlePath as string);\n console.log(`Eval Success: evaluated '${bundlePath}' in SES!`);\n return true;\n } catch (err) {\n logError(`Snap evaluation error: ${err.message}`, err);\n process.exit(1);\n }\n}\n"]}
1
+ {"version":3,"file":"evalHandler.js","sourceRoot":"","sources":["../../../src/cmds/eval/evalHandler.ts"],"names":[],"mappings":";;;AACA,uCAAyD;AACzD,6CAA0C;AAEnC,KAAK,UAAU,QAAQ,CAAC,IAAe;IAC5C,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC;IACpC,MAAM,wBAAgB,CAAC,UAAoB,CAAC,CAAC;IAC7C,IAAI;QACF,MAAM,uBAAU,CAAC,UAAoB,CAAC,CAAC;QACvC,OAAO,CAAC,GAAG,CAAC,4BAA4B,UAAU,WAAW,CAAC,CAAC;KAChE;IAAC,OAAO,GAAG,EAAE;QACZ,gBAAQ,CAAC,0BAA0B,GAAG,CAAC,OAAO,EAAE,EAAE,GAAG,CAAC,CAAC;QACvD,MAAM,GAAG,CAAC;KACX;AACH,CAAC;AAVD,4BAUC","sourcesContent":["import { YargsArgs } from '../../types/yargs';\nimport { logError, validateFilePath } from '../../utils';\nimport { workerEval } from './workerEval';\n\nexport async function snapEval(argv: YargsArgs): Promise<void> {\n const { bundle: bundlePath } = argv;\n await validateFilePath(bundlePath as string);\n try {\n await workerEval(bundlePath as string);\n console.log(`Eval Success: evaluated '${bundlePath}' in SES!`);\n } catch (err) {\n logError(`Snap evaluation error: ${err.message}`, err);\n throw err;\n }\n}\n"]}
@@ -4,6 +4,6 @@ declare const _default: {
4
4
  command: string[];
5
5
  desc: string;
6
6
  builder: (yarg: yargs.Argv) => void;
7
- handler: (argv: YargsArgs) => Promise<boolean>;
7
+ handler: (argv: YargsArgs) => Promise<void>;
8
8
  };
9
9
  export = _default;
@@ -1,12 +1,7 @@
1
- declare const commands: ({
1
+ declare const commands: {
2
2
  command: string[];
3
3
  desc: string;
4
4
  builder: (yarg: import("yargs").Argv<{}>) => void;
5
5
  handler: (argv: import("../types/yargs").YargsArgs) => Promise<void>;
6
- } | {
7
- command: string[];
8
- desc: string;
9
- builder: (yarg: import("yargs").Argv<{}>) => void;
10
- handler: (argv: import("../types/yargs").YargsArgs) => Promise<boolean>;
11
- })[];
6
+ }[];
12
7
  export default commands;
@@ -1,4 +1,4 @@
1
1
  {
2
- "html": "<!doctype html>\n<html>\n </head>\n <title>Hello, Snaps!</title>\n </head>\n\n <body>\n <h1>Hello, Snaps!</h1>\n <details>\n <summary>Instructions</summary>\n <ul>\n <li>First, click \"Connect\". Then, try out the other buttons!</li>\n <li>Please note that:</li>\n <ul>\n <li>\n The <code>snap.manifest.json</code> and <code>package.json</code> must be located in located in the server root directory..\n </li>\n <li>\n The Snap bundle must be hosted at the location specified by the <code>location</code> field of <code>snap.manifest.json</code>.\n </li>\n </ul>\n </ul>\n </details>\n <br/>\n\n <button class=\"connect\">Connect</button>\n <button class=\"sendHello\">Send Hello</button>\n </body>\n\n <script>\n\n // When developing locally, we identify Snaps like this\n const snapId = `local:${window.location.href}`;\n\n const connectButton = document.querySelector('button.connect')\n const sendButton = document.querySelector('button.sendHello')\n\n connectButton.addEventListener('click', connect)\n sendButton.addEventListener('click', send)\n\n // here we get permissions to interact with and install the snap\n async function connect () {\n await ethereum.request({\n method: 'wallet_enable',\n params: [{\n wallet_snap: { [snapId]: {} },\n }]\n })\n }\n\n // here we call the snap's \"hello\" method\n async function send () {\n try {\n const response = await ethereum.request({\n method: 'wallet_invokeSnap',\n params: [snapId, {\n method: 'hello'\n }]\n })\n } catch (err) {\n console.error(err)\n alert('Problem happened: ' + err.message || err)\n }\n }\n\n </script>\n</html>\n",
3
- "source": "wallet.registerRpcMessageHandler(async (originString, requestObject) => {\n switch (requestObject.method) {\n case 'hello':\n return wallet.request({\n method: 'snap_confirm',\n params: [{ prompt: `Hello, ${originString}!` }],\n });\n default:\n throw new Error('Method not found.');\n }\n});\n"
2
+ "html": "<!doctype html>\n<html>\n </head>\n <title>Hello, Snaps!</title>\n <link rel=\"icon\" type=\"image/svg\" href=\"./images/icon.svg\"/>\n </head>\n\n <body>\n <h1>Hello, Snaps!</h1>\n <details>\n <summary>Instructions</summary>\n <ul>\n <li>First, click \"Connect\". Then, try out the other buttons!</li>\n <li>Please note that:</li>\n <ul>\n <li>\n The <code>snap.manifest.json</code> and <code>package.json</code> must be located in located in the server root directory..\n </li>\n <li>\n The Snap bundle must be hosted at the location specified by the <code>location</code> field of <code>snap.manifest.json</code>.\n </li>\n </ul>\n </ul>\n </details>\n <br/>\n\n <button class=\"connect\">Connect</button>\n <button class=\"sendHello\">Send Hello</button>\n </body>\n\n <script>\n const snapId = `local:${window.location.href}`;\n\n const connectButton = document.querySelector('button.connect')\n const sendButton = document.querySelector('button.sendHello')\n\n connectButton.addEventListener('click', connect)\n sendButton.addEventListener('click', send)\n\n // here we get permissions to interact with and install the snap\n async function connect () {\n await ethereum.request({\n method: 'wallet_enable',\n params: [{\n wallet_snap: { [snapId]: {} },\n }]\n })\n }\n\n // here we call the snap's \"hello\" method\n async function send () {\n try {\n const response = await ethereum.request({\n method: 'wallet_invokeSnap',\n params: [snapId, {\n method: 'hello'\n }]\n })\n } catch (err) {\n console.error(err)\n alert('Problem happened: ' + err.message || err)\n }\n }\n </script>\n</html>\n",
3
+ "source": "wallet.registerRpcMessageHandler(async (originString, requestObject) => {\n switch (requestObject.method) {\n case 'hello':\n return wallet.request({\n method: 'snap_confirm',\n params: [\n {\n prompt: `Hello, ${originString}!`,\n description:\n 'This custom confirmation is just for display purposes.',\n textAreaContent:\n 'But you can edit the snap source code to make it do something, if you want to!',\n },\n ],\n });\n default:\n throw new Error('Method not found.');\n }\n});\n"
4
4
  }
@@ -6,8 +6,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.updateManifestShasum = exports.initHandler = void 0;
7
7
  const fs_1 = require("fs");
8
8
  const path_1 = __importDefault(require("path"));
9
- const mkdirp_1 = __importDefault(require("mkdirp"));
10
9
  const snap_controllers_1 = require("@metamask/snap-controllers");
10
+ const mkdirp_1 = __importDefault(require("mkdirp"));
11
11
  const utils_1 = require("../../utils");
12
12
  const manifestHandler_1 = require("../manifest/manifestHandler");
13
13
  const init_template_json_1 = __importDefault(require("./init-template.json"));
@@ -29,7 +29,7 @@ async function initHandler(argv) {
29
29
  }
30
30
  catch (err) {
31
31
  utils_1.logError(`Init Error: Failed to write '${snap_controllers_1.NpmSnapFileNames.Manifest}'.`, err);
32
- process.exit(1);
32
+ throw err;
33
33
  }
34
34
  console.log(`\nInit: Created '${snap_controllers_1.NpmSnapFileNames.Manifest}'.`);
35
35
  // Write main .js entry file
@@ -43,7 +43,7 @@ async function initHandler(argv) {
43
43
  }
44
44
  catch (err) {
45
45
  utils_1.logError(`Init Error: Failed to write '${src}'.`, err);
46
- process.exit(1);
46
+ throw err;
47
47
  }
48
48
  // Write index.html
49
49
  try {
@@ -52,7 +52,7 @@ async function initHandler(argv) {
52
52
  }
53
53
  catch (err) {
54
54
  utils_1.logError(`Init Error: Failed to write 'index.html'.`, err);
55
- process.exit(1);
55
+ throw err;
56
56
  }
57
57
  // Write config file
58
58
  try {
@@ -61,7 +61,7 @@ async function initHandler(argv) {
61
61
  }
62
62
  catch (err) {
63
63
  utils_1.logError(`Init Error: Failed to write '${utils_1.CONFIG_FILE}'.`, err);
64
- process.exit(1);
64
+ throw err;
65
65
  }
66
66
  utils_1.closePrompt();
67
67
  return Object.assign(Object.assign({}, argv), newArgs);
@@ -1 +1 @@
1
- {"version":3,"file":"initHandler.js","sourceRoot":"","sources":["../../../src/cmds/init/initHandler.ts"],"names":[],"mappings":";;;;;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,MAAM,oBAAY,CAClC,mCAAgB,CAAC,QAAQ,CAC1B,CAAiB,CAAC;IAEnB,MAAM,cAAc,GAAG,MAAM,aAAE,CAAC,QAAQ,CACtC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,EACrC,MAAM,CACP,CAAC;IAEF,QAAQ,CAAC,MAAM,CAAC,MAAM,GAAG,sCAAmB,CAAC,cAAc,CAAC,CAAC;IAC7D,MAAM,aAAE,CAAC,SAAS,CAChB,mCAAgB,CAAC,QAAQ,EACzB,IAAI,CAAC,SAAS,CAAC,qCAAmB,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CACvD,CAAC;AACJ,CAAC;AAfD,oDAeC","sourcesContent":["import { promises as fs } from 'fs';\nimport pathUtils from 'path';\nimport mkdirp from 'mkdirp';\nimport {\n getSnapSourceShasum,\n NpmSnapFileNames,\n SnapManifest,\n} from '@metamask/snap-controllers';\nimport { CONFIG_FILE, logError, closePrompt, readJsonFile } from '../../utils';\nimport { YargsArgs } from '../../types/yargs';\nimport { getWritableManifest } from '../manifest/manifestHandler';\nimport template from './init-template.json';\nimport {\n asyncPackageInit,\n prepareWorkingDirectory,\n buildSnapManifest,\n} from './initUtils';\n\nexport async function initHandler(argv: YargsArgs) {\n console.log(`MetaMask Snaps: Initialize\\n`);\n\n const packageJson = await asyncPackageInit();\n\n await prepareWorkingDirectory();\n\n console.log(`\\nInit: Building '${NpmSnapFileNames.Manifest}'...\\n`);\n\n const [snapManifest, _newArgs] = await buildSnapManifest(argv, packageJson);\n\n const newArgs = Object.keys(_newArgs)\n .sort()\n .reduce((sorted, key) => {\n sorted[key] = _newArgs[key as keyof typeof _newArgs];\n return sorted;\n }, {} as YargsArgs);\n\n try {\n await fs.writeFile(\n NpmSnapFileNames.Manifest,\n `${JSON.stringify(snapManifest, null, 2)}\\n`,\n );\n } catch (err) {\n logError(\n `Init Error: Failed to write '${NpmSnapFileNames.Manifest}'.`,\n err,\n );\n process.exit(1);\n }\n\n console.log(`\\nInit: Created '${NpmSnapFileNames.Manifest}'.`);\n\n // Write main .js entry file\n const { src } = newArgs;\n try {\n if (pathUtils.basename(src) !== src) {\n await mkdirp(pathUtils.dirname(src));\n }\n\n await fs.writeFile(src, template.source);\n console.log(`Init: Created '${src}'.`);\n } catch (err) {\n logError(`Init Error: Failed to write '${src}'.`, err);\n process.exit(1);\n }\n\n // Write index.html\n try {\n await fs.writeFile('index.html', template.html);\n console.log(`Init: Created 'index.html'.`);\n } catch (err) {\n logError(`Init Error: Failed to write 'index.html'.`, err);\n process.exit(1);\n }\n\n // Write config file\n try {\n await fs.writeFile(CONFIG_FILE, JSON.stringify(newArgs, null, 2));\n console.log(`Init: Wrote '${CONFIG_FILE}' config file`);\n } catch (err) {\n logError(`Init Error: Failed to write '${CONFIG_FILE}'.`, err);\n process.exit(1);\n }\n\n closePrompt();\n return { ...argv, ...newArgs };\n}\n\n/**\n * This updates the Snap shasum value of the manifest after building the Snap\n * during the init command.\n */\nexport async function updateManifestShasum() {\n const manifest = (await readJsonFile(\n NpmSnapFileNames.Manifest,\n )) as SnapManifest;\n\n const bundleContents = await fs.readFile(\n manifest.source.location.npm.filePath,\n 'utf8',\n );\n\n manifest.source.shasum = getSnapSourceShasum(bundleContents);\n await fs.writeFile(\n NpmSnapFileNames.Manifest,\n JSON.stringify(getWritableManifest(manifest), null, 2),\n );\n}\n"]}
1
+ {"version":3,"file":"initHandler.js","sourceRoot":"","sources":["../../../src/cmds/init/initHandler.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAoC;AACpC,gDAA6B;AAC7B,iEAIoC;AACpC,oDAA4B;AAE5B,uCAA+E;AAC/E,iEAAkE;AAClE,8EAA4C;AAC5C,2CAIqB;AAEd,KAAK,UAAU,WAAW,CAAC,IAAe;IAC/C,OAAO,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;IAE5C,MAAM,WAAW,GAAG,MAAM,4BAAgB,EAAE,CAAC;IAE7C,M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B,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CACvD,CAAC;AACJ,CAAC;AAfD,oDAeC","sourcesContent":["import { promises as fs } from 'fs';\nimport pathUtils from 'path';\nimport {\n getSnapSourceShasum,\n NpmSnapFileNames,\n SnapManifest,\n} from '@metamask/snap-controllers';\nimport mkdirp from 'mkdirp';\nimport { YargsArgs } from '../../types/yargs';\nimport { closePrompt, CONFIG_FILE, logError, readJsonFile } from '../../utils';\nimport { getWritableManifest } from '../manifest/manifestHandler';\nimport template from './init-template.json';\nimport {\n asyncPackageInit,\n buildSnapManifest,\n prepareWorkingDirectory,\n} from './initUtils';\n\nexport async function initHandler(argv: YargsArgs) {\n console.log(`MetaMask Snaps: Initialize\\n`);\n\n const packageJson = await asyncPackageInit();\n\n await prepareWorkingDirectory();\n\n console.log(`\\nInit: Building '${NpmSnapFileNames.Manifest}'...\\n`);\n\n const [snapManifest, _newArgs] = await buildSnapManifest(argv, packageJson);\n\n const newArgs = Object.keys(_newArgs)\n .sort()\n .reduce((sorted, key) => {\n sorted[key] = _newArgs[key as keyof typeof _newArgs];\n return sorted;\n }, {} as YargsArgs);\n\n try {\n await fs.writeFile(\n NpmSnapFileNames.Manifest,\n `${JSON.stringify(snapManifest, null, 2)}\\n`,\n );\n } catch (err) {\n logError(\n `Init Error: Failed to write '${NpmSnapFileNames.Manifest}'.`,\n err,\n );\n throw err;\n }\n\n console.log(`\\nInit: Created '${NpmSnapFileNames.Manifest}'.`);\n\n // Write main .js entry file\n const { src } = newArgs;\n try {\n if (pathUtils.basename(src) !== src) {\n await mkdirp(pathUtils.dirname(src));\n }\n\n await fs.writeFile(src, template.source);\n console.log(`Init: Created '${src}'.`);\n } catch (err) {\n logError(`Init Error: Failed to write '${src}'.`, err);\n throw err;\n }\n\n // Write index.html\n try {\n await fs.writeFile('index.html', template.html);\n console.log(`Init: Created 'index.html'.`);\n } catch (err) {\n logError(`Init Error: Failed to write 'index.html'.`, err);\n throw err;\n }\n\n // Write config file\n try {\n await fs.writeFile(CONFIG_FILE, JSON.stringify(newArgs, null, 2));\n console.log(`Init: Wrote '${CONFIG_FILE}' config file`);\n } catch (err) {\n logError(`Init Error: Failed to write '${CONFIG_FILE}'.`, err);\n throw err;\n }\n\n closePrompt();\n return { ...argv, ...newArgs };\n}\n\n/**\n * This updates the Snap shasum value of the manifest after building the Snap\n * during the init command.\n */\nexport async function updateManifestShasum() {\n const manifest = (await readJsonFile(\n NpmSnapFileNames.Manifest,\n )) as SnapManifest;\n\n const bundleContents = await fs.readFile(\n manifest.source.location.npm.filePath,\n 'utf8',\n );\n\n manifest.source.shasum = getSnapSourceShasum(bundleContents);\n await fs.writeFile(\n NpmSnapFileNames.Manifest,\n JSON.stringify(getWritableManifest(manifest), null, 2),\n );\n}\n"]}
@@ -34,13 +34,13 @@ async function asyncPackageInit() {
34
34
  }
35
35
  catch (error) {
36
36
  utils_1.logError(`Init Error: Could not parse '${snaps_1.NpmSnapFileNames.PackageJson}'. Please verify that the file is correctly formatted and try again.`, error);
37
- process.exit(1);
37
+ throw error;
38
38
  }
39
39
  }
40
40
  // Exit if yarn.lock is found, or we'll be in trouble
41
41
  if (fs_1.existsSync('yarn.lock')) {
42
42
  utils_1.logError(`Init Error: Found a 'yarn.lock' file but no '${snaps_1.NpmSnapFileNames.PackageJson}'. Please run 'yarn init' and try again.`);
43
- process.exit(1);
43
+ throw new Error('Already existing yarn.lock file found');
44
44
  }
45
45
  // Run 'npm init'
46
46
  return new Promise((resolve, reject) => {
@@ -101,7 +101,7 @@ async function buildSnapManifest(argv, packageJson) {
101
101
  }
102
102
  catch (err) {
103
103
  utils_1.logError(`Init Error: ${err.message}`, err);
104
- process.exit(1);
104
+ throw err;
105
105
  }
106
106
  let invalidProposedName = true;
107
107
  while (invalidProposedName) {
@@ -235,7 +235,7 @@ async function prepareWorkingDirectory() {
235
235
  const shouldContinue = continueInput && isYes(continueInput);
236
236
  if (!shouldContinue) {
237
237
  console.log(`Init: Exiting...`);
238
- process.exit(1);
238
+ throw new Error('User refused to continue');
239
239
  }
240
240
  }
241
241
  }
@@ -1 +1 @@
1
- {"version":3,"file":"initUtils.js","sourceRoot":"","sources":["../../../src/cmds/init/initUtils.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAgD;AAChD,gDAA6B;AAC7B,iEAM+C;AAC/C,0EAAgD;AAChD,oDAA4B;AAC5B,kDAA0B;AAC1B,uCAQqB;AAGrB;;GAEG;AACH,MAAM,kBAAkB,GAAG,8CAA8C,CAAC;AAE1E,MAAM,uBAAuB,GAAG,4BAA4B,CAAC;AAE7D;;;;;;GAMG;AACI,KAAK,UAAU,gBAAgB;IAGpC,IAAI,eAAU,CAAC,wBAAgB,CAAC,WAAW,CAAC,EAAE;QAC5C,OAAO,CAAC,GAAG,CACT,qCAAqC,wBAAgB,CAAC,WAAW,MAAM,CACxE,CAAC;QAEF,IAAI;YACF,MAAM,WAAW,GAAG,MAAM,oBAAY,CAAC,wBAAgB,CAAC,WAAW,CAAC,CAAC;YACrE,4BAAoB,CAAC,wBAAgB,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;YAEhE,OAAO,CAAC,GAAG,CACT,8BAA8B,wBAAgB,CAAC,WAAW,IAAI,CAC/D,CAAC;YACF,OAAO,WAAiC,CAAC;SAC1C;QAAC,OAAO,KAAK,EAAE;YACd,gBAAQ,CACN,gCAAgC,wBAAgB,CAAC,WAAW,sEAAsE,EAClI,KAAK,CACN,CAAC;YACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;SACjB;KACF;IAED,qDAAqD;IACrD,IAAI,eAAU,CAAC,WAAW,CAAC,EAAE;QAC3B,gBAAQ,CACN,gDAAgD,wBAAgB,CAAC,WAAW,0CAA0C,CACvH,CAAC;QACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;KACjB;IAED,iBAAiB;IACjB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,2BAAe,C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CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CACrC,CAAC;IAEF,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE;QAC5B,kBAAU,CACR,0EAA0E,aAAa,CAAC,MAAM,CAC5F,CAAC,OAAO,EAAE,WAAW,EAAE,EAAE;YACvB,OAAO,GAAG,OAAO,KAAK,WAAW,IAAI,CAAC;QACxC,CAAC,EACD,EAAE,CACH,EAAE,CACJ,CAAC;QAEF,MAAM,aAAa,GAAG,MAAM,cAAM,CAAC;YACjC,QAAQ,EAAE,WAAW;YACrB,YAAY,EAAE,GAAG;SAClB,CAAC,CAAC;QACH,MAAM,cAAc,GAAG,aAAa,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;QAE7D,IAAI,CAAC,cAAc,EAAE;YACnB,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;YAChC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;SACjB;KACF;AACH,CAAC;AA1BD,0DA0BC","sourcesContent":["import { promises as fs, existsSync } from 'fs';\nimport pathUtils from 'path';\nimport {\n NpmSnapPackageJson,\n SnapManifest,\n NpmSnapFileNames,\n validateSnapJsonFile,\n PROPOSED_NAME_REGEX,\n} from '@metamask/snap-controllers/dist/snaps';\nimport initPackageJson from 'init-package-json';\nimport mkdirp from 'mkdirp';\nimport slash from 'slash';\nimport {\n CONFIG_FILE,\n deepClone,\n logError,\n logWarning,\n prompt,\n readJsonFile,\n trimPathString,\n} from '../../utils';\nimport { YargsArgs } from '../../types/yargs';\n\n/**\n * This is a placeholder shasum that will be replaced at the end of the init command.\n */\nconst PLACEHOLDER_SHASUM = '2QqUxo5joo4kKKr7yiCjdYsZOZcIFBnIBEdwU9Yx7+M=';\n\nconst NPM_PUBLIC_REGISTRY_URL = 'https://registry.npmjs.org';\n\n/**\n * Initializes a `package.json` file for a Snap project. Will attempt to read\n * and parse the existing file if it already exists, otherwise will intialize\n * a brand new one.\n *\n * @returns The contents of the `package.json` file.\n */\nexport async function asyncPackageInit(): Promise<\n Readonly<NpmSnapPackageJson>\n> {\n if (existsSync(NpmSnapFileNames.PackageJson)) {\n console.log(\n `Init: Attempting to use existing '${NpmSnapFileNames.PackageJson}'...`,\n );\n\n try {\n const packageJson = await readJsonFile(NpmSnapFileNames.PackageJson);\n validateSnapJsonFile(NpmSnapFileNames.PackageJson, packageJson);\n\n console.log(\n `Init: Successfully parsed '${NpmSnapFileNames.PackageJson}'!`,\n );\n return packageJson as NpmSnapPackageJson;\n } catch (error) {\n logError(\n `Init Error: Could not parse '${NpmSnapFileNames.PackageJson}'. Please verify that the file is correctly formatted and try again.`,\n error,\n );\n process.exit(1);\n }\n }\n\n // Exit if yarn.lock is found, or we'll be in trouble\n if (existsSync('yarn.lock')) {\n logError(\n `Init Error: Found a 'yarn.lock' file but no '${NpmSnapFileNames.PackageJson}'. Please run 'yarn init' and try again.`,\n );\n process.exit(1);\n }\n\n // Run 'npm init'\n return new Promise((resolve, reject) => {\n initPackageJson(process.cwd(), '', {}, (err, data) => {\n if (err) {\n reject(err);\n } else {\n resolve(data);\n }\n });\n });\n}\n\nconst YES = 'yes';\nconst YES_VALUES = new Set([YES, 'y']);\n\nfunction isYes(userInput: string | undefined) {\n return userInput && YES_VALUES.has(userInput.toLowerCase());\n}\n\nconst DEFAULT_PERMISSION_KEY = 'snap_confirm';\nconst getDefaultPermissions = () => {\n return { [DEFAULT_PERMISSION_KEY]: {} };\n};\n\n/**\n * Interactively constructs a Snap manifest file by prompting the user.\n *\n * @param argv - The `yargs` `argv` object.\n * @param packageJson - The `package.json` object.\n * @param shasum - The shasum of the Snap source file.\n * @returns A tuple of the resulting Snap manifest object and a new `argv` object\n * with properties to match the manifest.\n */\nexport async function buildSnapManifest(\n argv: YargsArgs,\n packageJson: NpmSnapPackageJson,\n): Promise<[SnapManifest, { dist: string; outfileName: string; src: string }]> {\n const { outfileName } = argv;\n let { dist } = argv;\n let initialPermissions: Record<string, unknown> = getDefaultPermissions();\n let { description, name: proposedName } = packageJson;\n\n if (!description) {\n description = `The ${proposedName} Snap.`;\n }\n\n try {\n const userInput = await prompt({\n question: `Use default Snap manifest values?`,\n defaultValue: YES,\n shouldClose: false,\n });\n\n if (isYes(userInput)) {\n console.log('Using default values...');\n try {\n await mkdirp(dist);\n } catch (err) {\n logError(\n `Init Error: Could not write default 'dist' '${dist}'. Maybe check your local ${CONFIG_FILE} file?`,\n );\n throw err;\n }\n return endSnapManifest();\n }\n } catch (err) {\n logError(`Init Error: ${err.message}`, err);\n process.exit(1);\n }\n\n let invalidProposedName = true;\n while (invalidProposedName) {\n // eslint-disable-next-line require-atomic-updates\n proposedName = await prompt({\n question: `Proposed Snap name:`,\n defaultValue: proposedName,\n });\n\n if (\n proposedName.length > 0 &&\n proposedName.length <= 214 &&\n PROPOSED_NAME_REGEX.test(proposedName)\n ) {\n invalidProposedName = false;\n } else {\n logError(\n `The proposed name must adhere to npm package naming conventions, except that capital letters are allowed. For details, see: https://docs.npmjs.com/cli/v6/configuring-npm/package-json#name`,\n );\n }\n }\n\n let invalidDescription = true;\n while (invalidDescription) {\n // eslint-disable-next-line require-atomic-updates\n description = await prompt({\n question: `Description:`,\n defaultValue: description,\n });\n\n if (description.length === 0 || description.length <= 280) {\n invalidDescription = false;\n } else {\n logError(\n `The description must be a non-empty string less than or equal to 280 characters.`,\n );\n }\n }\n\n let invalidDist = true;\n while (invalidDist) {\n // eslint-disable-next-line require-atomic-updates\n dist = await prompt({ question: `Output directory:`, defaultValue: dist });\n try {\n dist = trimPathString(dist);\n await mkdirp(dist);\n invalidDist = false;\n } catch (distError) {\n logError(\n `Unable to create directory '${dist}'. Ensure that the path is valid and try again.`,\n distError,\n );\n }\n }\n\n let invalidPermissions = true;\n while (invalidPermissions) {\n const inputPermissions = await prompt({\n // We add the parenthetical default value ourselves\n question: `Initial permissions: [perm1 perm2 ...] ([snap_confirm])`,\n });\n\n if (\n !inputPermissions ||\n inputPermissions.trim() === DEFAULT_PERMISSION_KEY\n ) {\n break;\n }\n\n try {\n initialPermissions = inputPermissions\n .split(' ')\n .reduce((allPermissions, permission) => {\n if (\n typeof permission === 'string' &&\n permission.match(/^[\\w\\d_:]+$/iu)\n ) {\n allPermissions[permission] = {};\n } else {\n throw new Error(`Invalid permission: ${permission}`);\n }\n return allPermissions;\n }, {} as Record<string, unknown>);\n\n invalidPermissions = false;\n } catch (err) {\n logError(\n `Invalid permissions '${inputPermissions}'.\\nThe permissions must be specified as a space-separated list of strings with only characters, digits, underscores ('_'), and colons (':').`,\n err,\n );\n }\n }\n\n return endSnapManifest();\n\n function endSnapManifest(): [\n SnapManifest,\n {\n dist: string;\n outfileName: string;\n src: string;\n },\n ] {\n const manifest = {\n version: packageJson.version,\n description,\n proposedName,\n repository: packageJson.repository\n ? deepClone(packageJson.repository)\n : null,\n source: {\n shasum: PLACEHOLDER_SHASUM,\n location: {\n npm: {\n filePath: slash(pathUtils.join(dist, outfileName)),\n packageName: packageJson.name,\n registry: NPM_PUBLIC_REGISTRY_URL,\n } as const,\n },\n },\n initialPermissions,\n manifestVersion: '0.1' as const,\n };\n\n try {\n validateSnapJsonFile(NpmSnapFileNames.Manifest, manifest);\n } catch (error) {\n /* istanbul ignore next */\n throw new Error(\n `Internal Error: Validation of constructed manifest failed. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n return [\n manifest,\n { dist, outfileName, src: packageJson.main || 'src/index.js' },\n ];\n }\n}\n\nconst INIT_FILE_NAMES = new Set([\n 'src',\n 'index.html',\n CONFIG_FILE,\n 'dist',\n NpmSnapFileNames.Manifest,\n]);\n\n/**\n * Checks whether any files in the current working directory will be overwritten\n * by the initialization process, and asks the user whether to continue if so.\n */\nexport async function prepareWorkingDirectory(): Promise<void> {\n const existingFiles = (await fs.readdir(process.cwd())).filter((item) =>\n INIT_FILE_NAMES.has(item.toString()),\n );\n\n if (existingFiles.length > 0) {\n logWarning(\n `\\nInit Warning: Existing files and/or directories may be overwritten:\\n${existingFiles.reduce(\n (message, currentFile) => {\n return `${message}\\t${currentFile}\\n`;\n },\n '',\n )}`,\n );\n\n const continueInput = await prompt({\n question: `Continue?`,\n defaultValue: YES,\n });\n const shouldContinue = continueInput && isYes(continueInput);\n\n if (!shouldContinue) {\n console.log(`Init: Exiting...`);\n process.exit(1);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"initUtils.js","sourceRoot":"","sources":["../../../src/cmds/init/initUtils.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAgD;AAChD,gDAA6B;AAC7B,iEAM+C;AAC/C,0EAAgD;AAChD,oDAA4B;AAC5B,kDAA0B;AAE1B,uCAQqB;AAErB;;GAEG;AACH,MAAM,kBAAkB,GAAG,8CAA8C,CAAC;AAE1E,MAAM,uBAAuB,GAAG,4BAA4B,CAAC;AAE7D;;;;;;GAMG;AACI,KAAK,UAAU,gBAAgB;IAGpC,IAAI,eAAU,CAAC,wBAAgB,CAAC,WAAW,CAAC,EAAE;QAC5C,OAAO,CAAC,GAAG,CACT,qCAAqC,wBAAgB,CAAC,WAAW,MAAM,CACxE,CAAC;QAEF,IAAI;YACF,MAAM,WAAW,GAAG,MAAM,oBAAY,CAAC,wBAAgB,CAAC,WAAW,CAAC,CAAC;YACrE,4BAAoB,CAAC,wBAAgB,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;YAEhE,OAAO,CAAC,GAAG,CACT,8BAA8B,wBAAgB,CAAC,WAAW,IAAI,CAC/D,CAAC;YACF,OAAO,WAAiC,CAAC;SAC1C;QAAC,OAAO,KAAK,EAAE;YACd,gBAAQ,CACN,gCAAgC,wBAAgB,CAAC,WAAW,sEAAsE,EAClI,KAAK,CACN,CAAC;YACF,MAAM,KAAK,CAAC;SACb;KACF;IAED,qDAAqD;IACrD,IAAI,eAAU,CAAC,WAAW,CAAC,EAAE;QAC3B,gBAAQ,CACN,gDAAgD,wBAAgB,CAAC,WAAW,0CAA0C,CACvH,CAAC;QACF,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC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AAC,GAAG,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CACtE,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CACrC,CAAC;IAEF,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE;QAC5B,kBAAU,CACR,0EAA0E,aAAa,CAAC,MAAM,CAC5F,CAAC,OAAO,EAAE,WAAW,EAAE,EAAE;YACvB,OAAO,GAAG,OAAO,KAAK,WAAW,IAAI,CAAC;QACxC,CAAC,EACD,EAAE,CACH,EAAE,CACJ,CAAC;QAEF,MAAM,aAAa,GAAG,MAAM,cAAM,CAAC;YACjC,QAAQ,EAAE,WAAW;YACrB,YAAY,EAAE,GAAG;SAClB,CAAC,CAAC;QACH,MAAM,cAAc,GAAG,aAAa,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;QAE7D,IAAI,CAAC,cAAc,EAAE;YACnB,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;YAChC,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;SAC7C;KACF;AACH,CAAC;AA1BD,0DA0BC","sourcesContent":["import { existsSync, promises as fs } from 'fs';\nimport pathUtils from 'path';\nimport {\n NpmSnapFileNames,\n NpmSnapPackageJson,\n PROPOSED_NAME_REGEX,\n SnapManifest,\n validateSnapJsonFile,\n} from '@metamask/snap-controllers/dist/snaps';\nimport initPackageJson from 'init-package-json';\nimport mkdirp from 'mkdirp';\nimport slash from 'slash';\nimport { YargsArgs } from '../../types/yargs';\nimport {\n CONFIG_FILE,\n deepClone,\n logError,\n logWarning,\n prompt,\n readJsonFile,\n trimPathString,\n} from '../../utils';\n\n/**\n * This is a placeholder shasum that will be replaced at the end of the init command.\n */\nconst PLACEHOLDER_SHASUM = '2QqUxo5joo4kKKr7yiCjdYsZOZcIFBnIBEdwU9Yx7+M=';\n\nconst NPM_PUBLIC_REGISTRY_URL = 'https://registry.npmjs.org';\n\n/**\n * Initializes a `package.json` file for a Snap project. Will attempt to read\n * and parse the existing file if it already exists, otherwise will intialize\n * a brand new one.\n *\n * @returns The contents of the `package.json` file.\n */\nexport async function asyncPackageInit(): Promise<\n Readonly<NpmSnapPackageJson>\n> {\n if (existsSync(NpmSnapFileNames.PackageJson)) {\n console.log(\n `Init: Attempting to use existing '${NpmSnapFileNames.PackageJson}'...`,\n );\n\n try {\n const packageJson = await readJsonFile(NpmSnapFileNames.PackageJson);\n validateSnapJsonFile(NpmSnapFileNames.PackageJson, packageJson);\n\n console.log(\n `Init: Successfully parsed '${NpmSnapFileNames.PackageJson}'!`,\n );\n return packageJson as NpmSnapPackageJson;\n } catch (error) {\n logError(\n `Init Error: Could not parse '${NpmSnapFileNames.PackageJson}'. Please verify that the file is correctly formatted and try again.`,\n error,\n );\n throw error;\n }\n }\n\n // Exit if yarn.lock is found, or we'll be in trouble\n if (existsSync('yarn.lock')) {\n logError(\n `Init Error: Found a 'yarn.lock' file but no '${NpmSnapFileNames.PackageJson}'. Please run 'yarn init' and try again.`,\n );\n throw new Error('Already existing yarn.lock file found');\n }\n\n // Run 'npm init'\n return new Promise((resolve, reject) => {\n initPackageJson(process.cwd(), '', {}, (err, data) => {\n if (err) {\n reject(err);\n } else {\n resolve(data);\n }\n });\n });\n}\n\nconst YES = 'yes';\nconst YES_VALUES = new Set([YES, 'y']);\n\nfunction isYes(userInput: string | undefined) {\n return userInput && YES_VALUES.has(userInput.toLowerCase());\n}\n\nconst DEFAULT_PERMISSION_KEY = 'snap_confirm';\nconst getDefaultPermissions = () => {\n return { [DEFAULT_PERMISSION_KEY]: {} };\n};\n\n/**\n * Interactively constructs a Snap manifest file by prompting the user.\n *\n * @param argv - The `yargs` `argv` object.\n * @param packageJson - The `package.json` object.\n * @param shasum - The shasum of the Snap source file.\n * @returns A tuple of the resulting Snap manifest object and a new `argv` object\n * with properties to match the manifest.\n */\nexport async function buildSnapManifest(\n argv: YargsArgs,\n packageJson: NpmSnapPackageJson,\n): Promise<[SnapManifest, { dist: string; outfileName: string; src: string }]> {\n const { outfileName } = argv;\n let { dist } = argv;\n let initialPermissions: Record<string, unknown> = getDefaultPermissions();\n let { description, name: proposedName } = packageJson;\n\n if (!description) {\n description = `The ${proposedName} Snap.`;\n }\n\n try {\n const userInput = await prompt({\n question: `Use default Snap manifest values?`,\n defaultValue: YES,\n shouldClose: false,\n });\n\n if (isYes(userInput)) {\n console.log('Using default values...');\n try {\n await mkdirp(dist);\n } catch (err) {\n logError(\n `Init Error: Could not write default 'dist' '${dist}'. Maybe check your local ${CONFIG_FILE} file?`,\n );\n throw err;\n }\n return endSnapManifest();\n }\n } catch (err) {\n logError(`Init Error: ${err.message}`, err);\n throw err;\n }\n\n let invalidProposedName = true;\n while (invalidProposedName) {\n // eslint-disable-next-line require-atomic-updates\n proposedName = await prompt({\n question: `Proposed Snap name:`,\n defaultValue: proposedName,\n });\n\n if (\n proposedName.length > 0 &&\n proposedName.length <= 214 &&\n PROPOSED_NAME_REGEX.test(proposedName)\n ) {\n invalidProposedName = false;\n } else {\n logError(\n `The proposed name must adhere to npm package naming conventions, except that capital letters are allowed. For details, see: https://docs.npmjs.com/cli/v6/configuring-npm/package-json#name`,\n );\n }\n }\n\n let invalidDescription = true;\n while (invalidDescription) {\n // eslint-disable-next-line require-atomic-updates\n description = await prompt({\n question: `Description:`,\n defaultValue: description,\n });\n\n if (description.length === 0 || description.length <= 280) {\n invalidDescription = false;\n } else {\n logError(\n `The description must be a non-empty string less than or equal to 280 characters.`,\n );\n }\n }\n\n let invalidDist = true;\n while (invalidDist) {\n // eslint-disable-next-line require-atomic-updates\n dist = await prompt({ question: `Output directory:`, defaultValue: dist });\n try {\n dist = trimPathString(dist);\n await mkdirp(dist);\n invalidDist = false;\n } catch (distError) {\n logError(\n `Unable to create directory '${dist}'. Ensure that the path is valid and try again.`,\n distError,\n );\n }\n }\n\n let invalidPermissions = true;\n while (invalidPermissions) {\n const inputPermissions = await prompt({\n // We add the parenthetical default value ourselves\n question: `Initial permissions: [perm1 perm2 ...] ([snap_confirm])`,\n });\n\n if (\n !inputPermissions ||\n inputPermissions.trim() === DEFAULT_PERMISSION_KEY\n ) {\n break;\n }\n\n try {\n initialPermissions = inputPermissions\n .split(' ')\n .reduce((allPermissions, permission) => {\n if (\n typeof permission === 'string' &&\n permission.match(/^[\\w\\d_:]+$/iu)\n ) {\n allPermissions[permission] = {};\n } else {\n throw new Error(`Invalid permission: ${permission}`);\n }\n return allPermissions;\n }, {} as Record<string, unknown>);\n\n invalidPermissions = false;\n } catch (err) {\n logError(\n `Invalid permissions '${inputPermissions}'.\\nThe permissions must be specified as a space-separated list of strings with only characters, digits, underscores ('_'), and colons (':').`,\n err,\n );\n }\n }\n\n return endSnapManifest();\n\n function endSnapManifest(): [\n SnapManifest,\n {\n dist: string;\n outfileName: string;\n src: string;\n },\n ] {\n const manifest = {\n version: packageJson.version,\n description,\n proposedName,\n repository: packageJson.repository\n ? deepClone(packageJson.repository)\n : null,\n source: {\n shasum: PLACEHOLDER_SHASUM,\n location: {\n npm: {\n filePath: slash(pathUtils.join(dist, outfileName)),\n packageName: packageJson.name,\n registry: NPM_PUBLIC_REGISTRY_URL,\n } as const,\n },\n },\n initialPermissions,\n manifestVersion: '0.1' as const,\n };\n\n try {\n validateSnapJsonFile(NpmSnapFileNames.Manifest, manifest);\n } catch (error) {\n /* istanbul ignore next */\n throw new Error(\n `Internal Error: Validation of constructed manifest failed. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n return [\n manifest,\n { dist, outfileName, src: packageJson.main || 'src/index.js' },\n ];\n }\n}\n\nconst INIT_FILE_NAMES = new Set([\n 'src',\n 'index.html',\n CONFIG_FILE,\n 'dist',\n NpmSnapFileNames.Manifest,\n]);\n\n/**\n * Checks whether any files in the current working directory will be overwritten\n * by the initialization process, and asks the user whether to continue if so.\n */\nexport async function prepareWorkingDirectory(): Promise<void> {\n const existingFiles = (await fs.readdir(process.cwd())).filter((item) =>\n INIT_FILE_NAMES.has(item.toString()),\n );\n\n if (existingFiles.length > 0) {\n logWarning(\n `\\nInit Warning: Existing files and/or directories may be overwritten:\\n${existingFiles.reduce(\n (message, currentFile) => {\n return `${message}\\t${currentFile}\\n`;\n },\n '',\n )}`,\n );\n\n const continueInput = await prompt({\n question: `Continue?`,\n defaultValue: YES,\n });\n const shouldContinue = continueInput && isYes(continueInput);\n\n if (!shouldContinue) {\n console.log(`Init: Exiting...`);\n throw new Error('User refused to continue');\n }\n }\n}\n"]}
@@ -17,7 +17,7 @@ module.exports = {
17
17
  }
18
18
  catch (err) {
19
19
  utils_1.logError(err.message, err);
20
- process.exit(1);
20
+ throw err;
21
21
  }
22
22
  },
23
23
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/manifest/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AACtC,uCAAuC;AAEvC,uDAAoD;AAEpD,iBAAS;IACP,OAAO,EAAE,CAAC,UAAU,EAAE,GAAG,CAAC;IAC1B,IAAI,EAAE,sCAAsC;IAC5C,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI,CAAC,MAAM,CAAC,eAAe,kCAAO,kBAAQ,CAAC,aAAa,KAAE,KAAK,EAAE,CAAC,KAAK,CAAC,IAAG,CAAC;IAC9E,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,IAAe,EAAE,EAAE;QACjC,IAAI;YACF,MAAM,iCAAe,CAAC,IAAI,CAAC,CAAC;SAC7B;QAAC,OAAO,GAAG,EAAE;YACZ,gBAAQ,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;YAC3B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;SACjB;IACH,CAAC;CACF,CAAC","sourcesContent":["import yargs from 'yargs';\nimport builders from '../../builders';\nimport { logError } from '../../utils';\nimport { YargsArgs } from '../../types/yargs';\nimport { manifestHandler } from './manifestHandler';\n\nexport = {\n command: ['manifest', 'm'],\n desc: 'Validate the snap.manifest.json file',\n builder: (yarg: yargs.Argv) => {\n yarg.option('writeManifest', { ...builders.writeManifest, alias: ['fix'] });\n },\n handler: async (argv: YargsArgs) => {\n try {\n await manifestHandler(argv);\n } catch (err) {\n logError(err.message, err);\n process.exit(1);\n }\n },\n};\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/manifest/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,uCAAuC;AACvC,uDAAoD;AAEpD,iBAAS;IACP,OAAO,EAAE,CAAC,UAAU,EAAE,GAAG,CAAC;IAC1B,IAAI,EAAE,sCAAsC;IAC5C,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI,CAAC,MAAM,CAAC,eAAe,kCAAO,kBAAQ,CAAC,aAAa,KAAE,KAAK,EAAE,CAAC,KAAK,CAAC,IAAG,CAAC;IAC9E,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,IAAe,EAAE,EAAE;QACjC,IAAI;YACF,MAAM,iCAAe,CAAC,IAAI,CAAC,CAAC;SAC7B;QAAC,OAAO,GAAG,EAAE;YACZ,gBAAQ,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;YAC3B,MAAM,GAAG,CAAC;SACX;IACH,CAAC;CACF,CAAC","sourcesContent":["import yargs from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { logError } from '../../utils';\nimport { manifestHandler } from './manifestHandler';\n\nexport = {\n command: ['manifest', 'm'],\n desc: 'Validate the snap.manifest.json file',\n builder: (yarg: yargs.Argv) => {\n yarg.option('writeManifest', { ...builders.writeManifest, alias: ['fix'] });\n },\n handler: async (argv: YargsArgs) => {\n try {\n await manifestHandler(argv);\n } catch (err) {\n logError(err.message, err);\n throw err;\n }\n },\n};\n"]}
@@ -39,11 +39,11 @@ async function serve(argv) {
39
39
  server.on('request', (request) => serveUtils_1.logRequest(request));
40
40
  server.on('error', (error) => {
41
41
  serveUtils_1.logServerError(error, argv.port);
42
- process.exit(1);
42
+ process.exitCode = 1;
43
43
  });
44
44
  server.on('close', () => {
45
45
  console.log('Server closed');
46
- process.exit(1);
46
+ process.exitCode = 1;
47
47
  });
48
48
  }
49
49
  module.exports = {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/serve/index.ts"],"names":[],"mappings":";;;;AAAA,gDAAwB;AACxB,kEAAyC;AAEzC,8DAAsC;AAEtC,uCAA8C;AAC9C,6CAA8E;AAW9E;;;;;;;GAOG;AACH,KAAK,UAAU,KAAK,CAAC,IAAe;IAClC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAErC,MAAM,uBAAe,CAAC,OAAiB,EAAE,IAAI,CAAC,CAAC;IAE/C,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;IAEpC,MAAM,MAAM,GAAG,cAAI,CAAC,YAAY,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;QAClD,MAAM,uBAAY,CAAC,GAAG,EAAE,GAAG,EAAE;YAC3B,MAAM,EAAE,OAAiB;YACzB,OAAO,EAAE;gBACP;oBACE,MAAM,EAAE,MAAM;oBACd,OAAO,EAAE;wBACP;4BACE,GAAG,EAAE,eAAe;4BACpB,KAAK,EAAE,UAAU;yBAClB;qBACF;iBACF;aACF;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,EAAE,GAAG,EAAE,CAAC,+BAAkB,CAAC,IAAI,CAAC,CAAC,CAAC;IAExD,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,uBAAU,CAAC,OAAO,CAAC,CAAC,CAAC;IAEvD,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;QAC3B,2BAAc,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QACjC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;QACtB,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;QAC7B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAtDD,iBAAS;IACP,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC;IACvB,IAAI,EAAE,wCAAwC;IAC9C,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,EAAE,CAAC,IAAe,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC;CAC1C,CAAC","sourcesContent":["import http from 'http';\nimport serveHandler from 'serve-handler';\nimport yargs from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { validateDirPath } from '../../utils';\nimport { logServerError, logServerListening, logRequest } from './serveUtils';\n\nexport = {\n command: ['serve', 's'],\n desc: 'Locally serve Snap file(s) for testing',\n builder: (yarg: yargs.Argv) => {\n yarg.option('root', builders.root).option('port', builders.port);\n },\n handler: (argv: YargsArgs) => serve(argv),\n};\n\n/**\n * Starts a local, static HTTP server on the given port with the given root\n * directory.\n *\n * @param argv - arguments as an object generated by yargs\n * @param argv.root - The root directory path string\n * @param argv.port - The server port\n */\nasync function serve(argv: YargsArgs): Promise<void> {\n const { port, root: rootDir } = argv;\n\n await validateDirPath(rootDir as string, true);\n\n console.log(`\\nStarting server...`);\n\n const server = http.createServer(async (req, res) => {\n await serveHandler(req, res, {\n public: rootDir as string,\n headers: [\n {\n source: '**/*',\n headers: [\n {\n key: 'Cache-Control',\n value: 'no-cache',\n },\n ],\n },\n ],\n });\n });\n\n server.listen({ port }, () => logServerListening(port));\n\n server.on('request', (request) => logRequest(request));\n\n server.on('error', (error) => {\n logServerError(error, argv.port);\n process.exit(1);\n });\n\n server.on('close', () => {\n console.log('Server closed');\n process.exit(1);\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/serve/index.ts"],"names":[],"mappings":";;;;AAAA,gDAAwB;AACxB,kEAAyC;AAEzC,8DAAsC;AAEtC,uCAA8C;AAC9C,6CAA8E;AAW9E;;;;;;;GAOG;AACH,KAAK,UAAU,KAAK,CAAC,IAAe;IAClC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAErC,MAAM,uBAAe,CAAC,OAAiB,EAAE,IAAI,CAAC,CAAC;IAE/C,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;IAEpC,MAAM,MAAM,GAAG,cAAI,CAAC,YAAY,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;QAClD,MAAM,uBAAY,CAAC,GAAG,EAAE,GAAG,EAAE;YAC3B,MAAM,EAAE,OAAiB;YACzB,OAAO,EAAE;gBACP;oBACE,MAAM,EAAE,MAAM;oBACd,OAAO,EAAE;wBACP;4BACE,GAAG,EAAE,eAAe;4BACpB,KAAK,EAAE,UAAU;yBAClB;qBACF;iBACF;aACF;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,EAAE,GAAG,EAAE,CAAC,+BAAkB,CAAC,IAAI,CAAC,CAAC,CAAC;IAExD,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,uBAAU,CAAC,OAAO,CAAC,CAAC,CAAC;IAEvD,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;QAC3B,2BAAc,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QACjC,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;QACtB,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;QAC7B,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC;AAtDD,iBAAS;IACP,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC;IACvB,IAAI,EAAE,wCAAwC;IAC9C,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,EAAE,CAAC,IAAe,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC;CAC1C,CAAC","sourcesContent":["import http from 'http';\nimport serveHandler from 'serve-handler';\nimport yargs from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { validateDirPath } from '../../utils';\nimport { logRequest, logServerError, logServerListening } from './serveUtils';\n\nexport = {\n command: ['serve', 's'],\n desc: 'Locally serve Snap file(s) for testing',\n builder: (yarg: yargs.Argv) => {\n yarg.option('root', builders.root).option('port', builders.port);\n },\n handler: (argv: YargsArgs) => serve(argv),\n};\n\n/**\n * Starts a local, static HTTP server on the given port with the given root\n * directory.\n *\n * @param argv - arguments as an object generated by yargs\n * @param argv.root - The root directory path string\n * @param argv.port - The server port\n */\nasync function serve(argv: YargsArgs): Promise<void> {\n const { port, root: rootDir } = argv;\n\n await validateDirPath(rootDir as string, true);\n\n console.log(`\\nStarting server...`);\n\n const server = http.createServer(async (req, res) => {\n await serveHandler(req, res, {\n public: rootDir as string,\n headers: [\n {\n source: '**/*',\n headers: [\n {\n key: 'Cache-Control',\n value: 'no-cache',\n },\n ],\n },\n ],\n });\n });\n\n server.listen({ port }, () => logServerListening(port));\n\n server.on('request', (request) => logRequest(request));\n\n server.on('error', (error) => {\n logServerError(error, argv.port);\n process.exitCode = 1;\n });\n\n server.on('close', () => {\n console.log('Server closed');\n process.exitCode = 1;\n });\n}\n"]}
package/dist/utils/fs.js CHANGED
@@ -27,7 +27,7 @@ async function isDirectory(pathString, createDir) {
27
27
  }
28
28
  catch (mkdirError) {
29
29
  misc_1.logError(`Directory '${pathString}' could not be created.`, mkdirError);
30
- process.exit(1);
30
+ throw mkdirError;
31
31
  }
32
32
  }
33
33
  return false;
@@ -1 +1 @@
1
- {"version":3,"file":"fs.js","sourceRoot":"","sources":["../../src/utils/fs.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AAEpC,iCAAkC;AAElC;;;;;;;GAOG;AACI,KAAK,UAAU,WAAW,CAC/B,UAAkB,EAClB,SAAkB;IAElB,IAAI;QACF,MAAM,KAAK,GAAG,MAAM,aAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACxC,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;KAC5B;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE;YAC3B,IAAI,CAAC,SAAS,EAAE;gBACd,OAAO,KAAK,CAAC;aACd;YAED,IAAI;gBACF,MAAM,aAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;gBAC3B,OAAO,IAAI,CAAC;aACb;YAAC,OAAO,UAAU,EAAE;gBACnB,eAAQ,CAAC,cAAc,UAAU,yBAAyB,EAAE,UAAU,CAAC,CAAC;gBACxE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;aACjB;SACF;QACD,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAvBD,kCAuBC;AAED;;;;;GAKG;AACI,KAAK,UAAU,MAAM,CAAC,UAAkB;IAC7C,IAAI;QACF,MAAM,KAAK,GAAG,MAAM,aAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACxC,OAAO,KAAK,CAAC,MAAM,EAAE,CAAC;KACvB;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAPD,wBAOC;AAED;;;;;GAKG;AACI,KAAK,UAAU,YAAY,CAAC,UAAkB;IACnD,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;QACjC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;KAC/D;IAED,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,aAAE,CAAC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;AAC3D,CAAC;AAND,oCAMC","sourcesContent":["import { promises as fs } from 'fs';\nimport type { Json } from '@metamask/snap-controllers';\nimport { logError } from './misc';\n\n/**\n * Checks whether the given path string resolves to an existing directory, and\n * optionally creates the directory if it doesn't exist.\n *\n * @param pathString - The path string to check\n * @param createDir - Whether to create the directory if it doesn't exist\n * @returns - Whether the given path is an existing directory\n */\nexport async function isDirectory(\n pathString: string,\n createDir: boolean,\n): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isDirectory();\n } catch (error) {\n if (error.code === 'ENOENT') {\n if (!createDir) {\n return false;\n }\n\n try {\n await fs.mkdir(pathString);\n return true;\n } catch (mkdirError) {\n logError(`Directory '${pathString}' could not be created.`, mkdirError);\n process.exit(1);\n }\n }\n return false;\n }\n}\n\n/**\n * Checks whether the given path string resolves to an existing file.\n *\n * @param pathString - The path string to check\n * @returns Whether the given path is an existing file\n */\nexport async function isFile(pathString: string): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isFile();\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Reads a `.json` file, parses its contents, and returns them.\n *\n * @param pathString - The path to the JSON file.\n * @returns The parsed contents of the JSON file.\n */\nexport async function readJsonFile(pathString: string): Promise<Json> {\n if (!pathString.endsWith('.json')) {\n throw new Error('The specified file must be a \".json\" file.');\n }\n\n return JSON.parse(await fs.readFile(pathString, 'utf8'));\n}\n"]}
1
+ {"version":3,"file":"fs.js","sourceRoot":"","sources":["../../src/utils/fs.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AAEpC,iCAAkC;AAElC;;;;;;;GAOG;AACI,KAAK,UAAU,WAAW,CAC/B,UAAkB,EAClB,SAAkB;IAElB,IAAI;QACF,MAAM,KAAK,GAAG,MAAM,aAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACxC,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;KAC5B;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE;YAC3B,IAAI,CAAC,SAAS,EAAE;gBACd,OAAO,KAAK,CAAC;aACd;YAED,IAAI;gBACF,MAAM,aAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;gBAC3B,OAAO,IAAI,CAAC;aACb;YAAC,OAAO,UAAU,EAAE;gBACnB,eAAQ,CAAC,cAAc,UAAU,yBAAyB,EAAE,UAAU,CAAC,CAAC;gBACxE,MAAM,UAAU,CAAC;aAClB;SACF;QACD,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAvBD,kCAuBC;AAED;;;;;GAKG;AACI,KAAK,UAAU,MAAM,CAAC,UAAkB;IAC7C,IAAI;QACF,MAAM,KAAK,GAAG,MAAM,aAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACxC,OAAO,KAAK,CAAC,MAAM,EAAE,CAAC;KACvB;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAPD,wBAOC;AAED;;;;;GAKG;AACI,KAAK,UAAU,YAAY,CAAC,UAAkB;IACnD,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;QACjC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;KAC/D;IAED,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,aAAE,CAAC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;AAC3D,CAAC;AAND,oCAMC","sourcesContent":["import { promises as fs } from 'fs';\nimport type { Json } from '@metamask/snap-controllers';\nimport { logError } from './misc';\n\n/**\n * Checks whether the given path string resolves to an existing directory, and\n * optionally creates the directory if it doesn't exist.\n *\n * @param pathString - The path string to check\n * @param createDir - Whether to create the directory if it doesn't exist\n * @returns - Whether the given path is an existing directory\n */\nexport async function isDirectory(\n pathString: string,\n createDir: boolean,\n): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isDirectory();\n } catch (error) {\n if (error.code === 'ENOENT') {\n if (!createDir) {\n return false;\n }\n\n try {\n await fs.mkdir(pathString);\n return true;\n } catch (mkdirError) {\n logError(`Directory '${pathString}' could not be created.`, mkdirError);\n throw mkdirError;\n }\n }\n return false;\n }\n}\n\n/**\n * Checks whether the given path string resolves to an existing file.\n *\n * @param pathString - The path string to check\n * @returns Whether the given path is an existing file\n */\nexport async function isFile(pathString: string): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isFile();\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Reads a `.json` file, parses its contents, and returns them.\n *\n * @param pathString - The path to the JSON file.\n * @returns The parsed contents of the JSON file.\n */\nexport async function readJsonFile(pathString: string): Promise<Json> {\n if (!pathString.endsWith('.json')) {\n throw new Error('The specified file must be a \".json\" file.');\n }\n\n return JSON.parse(await fs.readFile(pathString, 'utf8'));\n}\n"]}
@@ -122,6 +122,8 @@ async function writeError(prefix, msg, err, destFilePath) {
122
122
  }
123
123
  // unless the watcher is active, exit
124
124
  if (!global.snaps.isWatching) {
125
+ // TODO(ritave): Remove process exit and change into collapse of functions
126
+ // https://github.com/MetaMask/snaps-skunkworks/issues/81
125
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G,MAAM,CAAC;IAC7B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;QACzB,eAAe,IAAI,GAAG,CAAC;KACxB;IAED,QAAQ,CAAC,eAAe,GAAG,GAAG,EAAE,GAAG,CAAC,CAAC;IACrC,IAAI;QACF,IAAI,YAAY,EAAE;YAChB,MAAM,aAAU,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;SACvC;KACF;IAAC,OAAO,WAAW,EAAE;QACpB,QAAQ,CAAC,GAAG,eAAe,gCAAgC,EAAE,WAAW,CAAC,CAAC;KAC3E;IAED,qCAAqC;IACrC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE;QAC5B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;KACjB;AACH,CAAC;AAxBD,gCAwBC;AAED;;;;;;GAMG;AACH,SAAgB,cAAc,CAAC,UAAkB;IAC/C,OAAO,UAAU,CAAC,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC;AACnD,CAAC;AAFD,wCAEC","sourcesContent":["import { promises as filesystem } from 'fs';\nimport path from 'path';\nimport rfdc from 'rfdc';\nimport { Arguments } from 'yargs';\n\nexport const deepClone = rfdc({ proto: false, circles: false });\n\nexport const permRequestKeys = [\n '@context',\n 'id',\n 'parentCapability',\n 'invoker',\n 'date',\n 'caveats',\n 'proof',\n];\n\nexport const CONFIG_FILE = 'snap.config.json';\n\n// CLI arguments whose values are file paths\nconst pathArguments = new Set([\n 'src',\n 's',\n 'dist',\n 'd',\n 'bundle',\n 'b',\n 'root',\n 'r',\n]);\n\n/**\n * Sets global variable snaps which tracks user settings:\n * watch mode activation, verbose errors messages, and whether to suppress warnings.\n *\n * @param argv - arguments as an object generated by yargs\n */\nexport function setSnapGlobals(argv: Arguments) {\n if (['w', 'watch'].includes(argv._[0] as string)) {\n global.snaps.isWatching = true;\n } else {\n global.snaps.isWatching = false;\n }\n\n if (Object.prototype.hasOwnProperty.call(argv, 'verboseErrors')) {\n global.snaps.verboseErrors = Boolean(argv.verboseErrors);\n }\n\n if (Object.prototype.hasOwnProperty.call(argv, 'suppressWarnings')) {\n global.snaps.suppressWarnings = Boolean(argv.suppressWarnings);\n }\n}\n\n/**\n * Sanitizes inputs. Currently normalizes \"./\" paths to \".\".\n * Yargs handles other path normalization as specified in builders.\n *\n * @param argv - arguments as an object generated by yargs\n */\nexport function sanitizeInputs(argv: Arguments) {\n Object.keys(argv).forEach((key) => {\n if (typeof argv[key] === 'string') {\n // Node's path.normalize() does not do this\n if (argv[key] === './') {\n argv[key] = '.';\n }\n\n if (pathArguments.has(key)) {\n argv[key] = path.normalize(argv[key] as string);\n }\n }\n });\n}\n\n/**\n * Logs an error message to console. Logs original error if it exists and\n * the verboseErrors global is true.\n *\n * @param msg - The error message\n * @param err - The original error\n */\nexport function logError(msg: string, err?: Error): void {\n console.error(msg);\n if (err && global.snaps.verboseErrors) {\n console.error(err);\n }\n}\n\n/**\n * Logs a warning message to console.\n *\n * @param msg - The warning message\n */\nexport function logWarning(msg: string, error?: Error): void {\n if (msg && !global.snaps.suppressWarnings) {\n console.warn(msg);\n if (error && global.snaps.verboseErrors) {\n console.error(error);\n }\n }\n}\n\n/**\n * Logs an error, attempts to unlink the destination file, and exits.\n *\n * @param prefix - The message prefix\n * @param msg - The error message\n * @param err - The original error\n * @param destFilePath - The output file path\n */\nexport async function writeError(\n prefix: string,\n msg: string,\n err: Error,\n destFilePath?: string,\n): Promise<void> {\n let processedPrefix = prefix;\n if (!prefix.endsWith(' ')) {\n processedPrefix += ' ';\n }\n\n logError(processedPrefix + msg, err);\n try {\n if (destFilePath) {\n await filesystem.unlink(destFilePath);\n }\n } catch (unlinkError) {\n logError(`${processedPrefix}Failed to unlink mangled file.`, unlinkError);\n }\n\n // unless the watcher is active, exit\n if (!global.snaps.isWatching) {\n process.exit(1);\n }\n}\n\n/**\n * Trims leading and trailing periods \".\" and forward slashes \"/\" from the\n * given path string.\n *\n * @param pathString - The path string to trim.\n * @returns - The trimmed path string.\n */\nexport function trimPathString(pathString: string): string {\n return pathString.replace(/^[./]+|[./]+$/gu, '');\n}\n"]}
1
+ {"version":3,"file":"misc.js","sourceRoot":"","sources":["../../src/utils/misc.ts"],"names":[],"mappings":";;;;;;AAAA,2BAA4C;AAC5C,gDAAwB;AACxB,gDAAwB;AAGX,QAAA,SAAS,GAAG,cAAI,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;AAEnD,QAAA,eAAe,GAAG;IAC7B,UAAU;IACV,IAAI;IACJ,kBAAkB;IAClB,SAAS;IACT,MAAM;IACN,SAAS;IACT,OAAO;CACR,CAAC;AAEW,QAAA,WAAW,GAAG,kBAAkB,CAAC;AAE9C,4CAA4C;AAC5C,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC;IAC5B,KAAK;IACL,GAAG;IACH,MAAM;IACN,GAAG;IACH,QAAQ;IACR,GAAG;IACH,MAAM;IACN,GAAG;CACJ,CAAC,CAAC;AAEH;;;;;GAKG;AACH,SAAgB,cAAc,CAAC,IAAe;IAC5C,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAW,CAAC,EAAE;QAChD,MAAM,CAAC,KAAK,CAAC,UAAU,GAAG,IAAI,CAAC;KAChC;SAAM;QACL,MAAM,CAAC,KAAK,CAAC,UAAU,GAAG,KAAK,CAAC;KACjC;IAED,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,eAAe,CAAC,EAAE;QAC/D,MAAM,CAAC,KAAK,CAAC,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;KAC1D;IAED,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,kBAAkB,CAAC,EAAE;QAClE,MAAM,CAAC,KAAK,CAAC,gBAAgB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AAW,EACX,GAAU,EACV,YAAqB;IAErB,IAAI,eAAe,GAAG,MAAM,CAAC;IAC7B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;QACzB,eAAe,IAAI,GAAG,CAAC;KACxB;IAED,QAAQ,CAAC,eAAe,GAAG,GAAG,EAAE,GAAG,CAAC,CAAC;IACrC,IAAI;QACF,IAAI,YAAY,EAAE;YAChB,MAAM,aAAU,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;SACvC;KACF;IAAC,OAAO,WAAW,EAAE;QACpB,QAAQ,CAAC,GAAG,eAAe,gCAAgC,EAAE,WAAW,CAAC,CAAC;KAC3E;IAED,qCAAqC;IACrC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE;QAC5B,0EAA0E;QAC1E,uEAAuE;QACvE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;KACjB;AACH,CAAC;AA1BD,gCA0BC;AAED;;;;;;GAMG;AACH,SAAgB,cAAc,CAAC,UAAkB;IAC/C,OAAO,UAAU,CAAC,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC;AACnD,CAAC;AAFD,wCAEC","sourcesContent":["import { promises as filesystem } from 'fs';\nimport path from 'path';\nimport rfdc from 'rfdc';\nimport { Arguments } from 'yargs';\n\nexport const deepClone = rfdc({ proto: false, circles: false });\n\nexport const permRequestKeys = [\n '@context',\n 'id',\n 'parentCapability',\n 'invoker',\n 'date',\n 'caveats',\n 'proof',\n];\n\nexport const CONFIG_FILE = 'snap.config.json';\n\n// CLI arguments whose values are file paths\nconst pathArguments = new Set([\n 'src',\n 's',\n 'dist',\n 'd',\n 'bundle',\n 'b',\n 'root',\n 'r',\n]);\n\n/**\n * Sets global variable snaps which tracks user settings:\n * watch mode activation, verbose errors messages, and whether to suppress warnings.\n *\n * @param argv - arguments as an object generated by yargs\n */\nexport function setSnapGlobals(argv: Arguments) {\n if (['w', 'watch'].includes(argv._[0] as string)) {\n global.snaps.isWatching = true;\n } else {\n global.snaps.isWatching = false;\n }\n\n if (Object.prototype.hasOwnProperty.call(argv, 'verboseErrors')) {\n global.snaps.verboseErrors = Boolean(argv.verboseErrors);\n }\n\n if (Object.prototype.hasOwnProperty.call(argv, 'suppressWarnings')) {\n global.snaps.suppressWarnings = Boolean(argv.suppressWarnings);\n }\n}\n\n/**\n * Sanitizes inputs. Currently normalizes \"./\" paths to \".\".\n * Yargs handles other path normalization as specified in builders.\n *\n * @param argv - arguments as an object generated by yargs\n */\nexport function sanitizeInputs(argv: Arguments) {\n Object.keys(argv).forEach((key) => {\n if (typeof argv[key] === 'string') {\n // Node's path.normalize() does not do this\n if (argv[key] === './') {\n argv[key] = '.';\n }\n\n if (pathArguments.has(key)) {\n argv[key] = path.normalize(argv[key] as string);\n }\n }\n });\n}\n\n/**\n * Logs an error message to console. Logs original error if it exists and\n * the verboseErrors global is true.\n *\n * @param msg - The error message\n * @param err - The original error\n */\nexport function logError(msg: string, err?: Error): void {\n console.error(msg);\n if (err && global.snaps.verboseErrors) {\n console.error(err);\n }\n}\n\n/**\n * Logs a warning message to console.\n *\n * @param msg - The warning message\n */\nexport function logWarning(msg: string, error?: Error): void {\n if (msg && !global.snaps.suppressWarnings) {\n console.warn(msg);\n if (error && global.snaps.verboseErrors) {\n console.error(error);\n }\n }\n}\n\n/**\n * Logs an error, attempts to unlink the destination file, and exits.\n *\n * @param prefix - The message prefix\n * @param msg - The error message\n * @param err - The original error\n * @param destFilePath - The output file path\n */\nexport async function writeError(\n prefix: string,\n msg: string,\n err: Error,\n destFilePath?: string,\n): Promise<void> {\n let processedPrefix = prefix;\n if (!prefix.endsWith(' ')) {\n processedPrefix += ' ';\n }\n\n logError(processedPrefix + msg, err);\n try {\n if (destFilePath) {\n await filesystem.unlink(destFilePath);\n }\n } catch (unlinkError) {\n logError(`${processedPrefix}Failed to unlink mangled file.`, unlinkError);\n }\n\n // unless the watcher is active, exit\n if (!global.snaps.isWatching) {\n // TODO(ritave): Remove process exit and change into collapse of functions\n // https://github.com/MetaMask/snaps-skunkworks/issues/81\n process.exit(1);\n }\n}\n\n/**\n * Trims leading and trailing periods \".\" and forward slashes \"/\" from the\n * given path string.\n *\n * @param pathString - The path string to trim.\n * @returns - The trimmed path string.\n */\nexport function trimPathString(pathString: string): string {\n return pathString.replace(/^[./]+|[./]+$/gu, '');\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"snap-config.js","sourceRoot":"","sources":["../../src/utils/snap-config.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAkC;AAGlC,gEAAsC;AACtC,2DAAmC;AACnC,iCAAkC;AAClC,wBAAgC;AAEhC,8EAA8E;AAC9E,6BAA6B;AAC7B,EAAE;AACF,wEAAwE;AACxE,4DAA4D;AAE5D;;;;;;GAMG;AACH,SAAgB,WAAW,CACzB,WAAqB,EACrB,SAAoB,EACpB,aAA2B;IAE3B,uEAAuE;IACvE,wEAAwE;IACxE,6EAA6E;IAC7E,+BAA+B;IAC/B,EAAE;IACF,8EAA8E;IAC9E,2EAA2E;IAC3E,oBAAoB;IACpB,EAAE;IACF,6EAA6E;IAC7E,qBAAqB;IACrB,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,GACpC,aACD,CAAC,UAAU,EAGX,CAAC;IAEF,MAAM,iBAAiB,GAAG,sBAAU,CAAC,WAAW,EAAE;QAChD,KAAK,EAAE,OAAO;KACf,CAA4B,CAAC;IAC9B,OAAO,iBAAiB,CAAC,CAAC,CAAC,CAAC,mCAAmC;IAE/D,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IAErD,MAAM,YAAY,GAAG,CAAC,GAAW,EAAW,EAAE;QAC5C,OAAO,CACL,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC;YACvB,CAAC,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,iBAAiB,EAAE,GA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ments } from 'yargs';\nimport yargs from 'yargs/yargs';\nimport yargsParse from 'yargs-parser';\nimport builders from '../builders';\nimport { logError } from './misc';\nimport { CONFIG_FILE } from '.';\n\n// Note that the below function is necessary because yarg's .config() function\n// leaves much to be desired.\n//\n// In particular, it will set all properties included in the config file\n// regardless of the command, which fails during validation.\n\n/**\n * Attempts to read configuration options for package.json and the config file,\n * and apply them to argv if they weren't already set.\n *\n * Arguments are only set per the snap-cli config file if they were not specified\n * on the command line.\n */\nexport function applyConfig(\n processArgv: string[],\n yargsArgv: Arguments,\n yargsInstance: typeof yargs,\n): void {\n // Instances of yargs has a number of undocumented functions, including\n // getOptions. This function returns an object with properties \"key\" and\n // \"alias\", which specify the options associated with the current command and\n // their aliases, respectively.\n //\n // We leverage this to ensure that the config is only applied to args that are\n // valid for the current command, and that weren't specified by the user on\n // the command line.\n //\n // If we set args that aren't valid for the current command, yargs will error\n // during validation.\n const { alias: aliases, key: options } = (\n yargsInstance as any\n ).getOptions() as {\n alias: Record<string, string[]>;\n key: Record<string, unknown>;\n };\n\n const parsedProcessArgv = yargsParse(processArgv, {\n alias: aliases,\n }) as Record<string, unknown>;\n delete parsedProcessArgv._; // irrelevant yargs parser artifact\n\n const commandOptions = new Set(Object.keys(options));\n\n const shouldSetArg = (key: string): boolean => {\n return (\n commandOptions.has(key) &&\n !Object.prototype.hasOwnProperty.call(parsedProcessArgv, key)\n );\n };\n\n // Now, we attempt to read and apply config from the config file, if any.\n let cfg: Record<string, unknown> = {};\n try {\n cfg = JSON.parse(readFileSync(CONFIG_FILE, 'utf8'));\n } catch (err) {\n if (err.code === 'ENOENT') {\n // If there's no config file, we're done here.\n return;\n }\n\n logError(\n `Error: \"${CONFIG_FILE}\" exists but could not be parsed. Ensure your config file is valid JSON and try again.`,\n err,\n );\n process.exit(1);\n }\n\n if (cfg && typeof cfg === 'object' && !Array.isArray(cfg)) {\n for (const key of Object.keys(cfg)) {\n if (Object.hasOwnProperty.call(builders, key)) {\n if (shouldSetArg(key)) {\n yargsArgv[key] = cfg[key];\n }\n } else {\n logError(\n `Error: Encountered unrecognized config property \"${key}\" in config file \"${CONFIG_FILE}\". Remove the property and try again.`,\n );\n process.exit(1);\n }\n }\n } else {\n const cfgType = cfg === null ? 'null' : typeof cfg;\n\n logError(\n `Error: The config file must consist of a top-level JSON object. Received \"${cfgType}\" from \"${CONFIG_FILE}\". Fix your config file and try again.`,\n );\n process.exit(1);\n }\n}\n"]}
1
+ {"version":3,"file":"snap-config.js","sourceRoot":"","sources":["../../src/utils/snap-config.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAkC;AAElC,gEAAsC;AAEtC,2DAAmC;AACnC,iCAAkC;AAClC,wBAAgC;AAEhC,8EAA8E;AAC9E,6BAA6B;AAC7B,EAAE;AACF,wEAAwE;AACxE,4DAA4D;AAE5D;;;;;;GAMG;AACH,SAAgB,WAAW,CACzB,WAAqB,EACrB,SAAoB,EACpB,aAA2B;IAE3B,uEAAuE;IACvE,wEAAwE;IACxE,6EAA6E;IAC7E,+BAA+B;IAC/B,EAAE;IACF,8EAA8E;IAC9E,2EAA2E;IAC3E,oBAAoB;IACpB,EAAE;IACF,6EAA6E;IAC7E,qBAAqB;IACrB,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,GACpC,aACD,CAAC,UAAU,EAGX,CAAC;IAEF,MAAM,iBAAiB,GAAG,sBAAU,CAAC,WAAW,EAAE;QAChD,KAAK,EAAE,OAAO;KACf,CAA4B,CAAC;IAC9B,OAAO,iBAAiB,CAAC,CAAC,CAAC,CAAC,mCAAmC;IAE/D,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IAErD,MAAM,YAAY,GAAG,CAAC,GAAW,EAAW,EAAE;QAC5C,OAAO,CACL,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC;YACvB,CAAC,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IA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import { readFileSync } from 'fs';\nimport { Arguments } from 'yargs';\nimport yargsParse from 'yargs-parser';\nimport yargs from 'yargs/yargs';\nimport builders from '../builders';\nimport { logError } from './misc';\nimport { CONFIG_FILE } from '.';\n\n// Note that the below function is necessary because yarg's .config() function\n// leaves much to be desired.\n//\n// In particular, it will set all properties included in the config file\n// regardless of the command, which fails during validation.\n\n/**\n * Attempts to read configuration options for package.json and the config file,\n * and apply them to argv if they weren't already set.\n *\n * Arguments are only set per the snap-cli config file if they were not specified\n * on the command line.\n */\nexport function applyConfig(\n processArgv: string[],\n yargsArgv: Arguments,\n yargsInstance: typeof yargs,\n): void {\n // Instances of yargs has a number of undocumented functions, including\n // getOptions. This function returns an object with properties \"key\" and\n // \"alias\", which specify the options associated with the current command and\n // their aliases, respectively.\n //\n // We leverage this to ensure that the config is only applied to args that are\n // valid for the current command, and that weren't specified by the user on\n // the command line.\n //\n // If we set args that aren't valid for the current command, yargs will error\n // during validation.\n const { alias: aliases, key: options } = (\n yargsInstance as any\n ).getOptions() as {\n alias: Record<string, string[]>;\n key: Record<string, unknown>;\n };\n\n const parsedProcessArgv = yargsParse(processArgv, {\n alias: aliases,\n }) as Record<string, unknown>;\n delete parsedProcessArgv._; // irrelevant yargs parser artifact\n\n const commandOptions = new Set(Object.keys(options));\n\n const shouldSetArg = (key: string): boolean => {\n return (\n commandOptions.has(key) &&\n !Object.prototype.hasOwnProperty.call(parsedProcessArgv, key)\n );\n };\n\n // Now, we attempt to read and apply config from the config file, if any.\n let cfg: Record<string, unknown> = {};\n try {\n cfg = JSON.parse(readFileSync(CONFIG_FILE, 'utf8'));\n } catch (err) {\n if (err.code === 'ENOENT') {\n // If there's no config file, we're done here.\n return;\n }\n\n logError(\n `Error: \"${CONFIG_FILE}\" exists but could not be parsed. Ensure your config file is valid JSON and try again.`,\n err,\n );\n process.exit(1);\n }\n\n if (cfg && typeof cfg === 'object' && !Array.isArray(cfg)) {\n for (const key of Object.keys(cfg)) {\n if (Object.hasOwnProperty.call(builders, key)) {\n if (shouldSetArg(key)) {\n yargsArgv[key] = cfg[key];\n }\n } else {\n logError(\n `Error: Encountered unrecognized config property \"${key}\" in config file \"${CONFIG_FILE}\". Remove the property and try again.`,\n );\n process.exit(1);\n }\n }\n } else {\n const cfgType = cfg === null ? 'null' : typeof cfg;\n\n logError(\n `Error: The config file must consist of a top-level JSON object. Received \"${cfgType}\" from \"${CONFIG_FILE}\". Fix your config file and try again.`,\n );\n process.exit(1);\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-cli",
3
- "version": "0.6.1",
3
+ "version": "0.8.0",
4
4
  "description": "A CLI for developing MetaMask Snaps.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,7 +21,7 @@
21
21
  "build:chmod": "chmod +x ./dist/main.js",
22
22
  "build": "yarn build:init-template && yarn build:typescript && yarn build:chmod",
23
23
  "build:pre-tsc": "echo 'N/A'",
24
- "build:post-tsc": "./scripts/publish-prep.sh",
24
+ "build:post-tsc": "yarn build:init-template && yarn build:chmod",
25
25
  "build:clean": "yarn clean && yarn build",
26
26
  "build:watch": "tsc-watch --onSuccess 'yarn build:chmod'",
27
27
  "clean": "rimraf dist/*",
@@ -36,7 +36,16 @@
36
36
  "publish": "../../scripts/publish-package.sh"
37
37
  },
38
38
  "dependencies": {
39
- "@metamask/snap-controllers": "^0.6.1",
39
+ "@babel/core": "^7.16.7",
40
+ "@babel/plugin-proposal-class-properties": "^7.16.7",
41
+ "@babel/plugin-proposal-nullish-coalescing-operator": "^7.16.7",
42
+ "@babel/plugin-proposal-object-rest-spread": "^7.16.7",
43
+ "@babel/plugin-proposal-optional-chaining": "^7.16.7",
44
+ "@babel/plugin-transform-runtime": "^7.16.7",
45
+ "@babel/preset-env": "^7.16.7",
46
+ "@metamask/snap-controllers": "^0.8.0",
47
+ "@nodefactory/strip-comments": "^1.0.2",
48
+ "babelify": "^10.0.0",
40
49
  "browserify": "^17.0.0",
41
50
  "chokidar": "^3.0.2",
42
51
  "fast-deep-equal": "^2.0.1",
@@ -47,7 +56,6 @@
47
56
  "serve-handler": "^6.1.1",
48
57
  "ses": "^0.15.3",
49
58
  "slash": "^3.0.0",
50
- "strip-comments": "^2.0.1",
51
59
  "yargs": "^16.2.0",
52
60
  "yargs-parser": "^20.2.2"
53
61
  },
@@ -66,7 +74,6 @@
66
74
  "@types/node": "^14.14.25",
67
75
  "@types/rimraf": "^3.0.0",
68
76
  "@types/serve-handler": "^6.1.0",
69
- "@types/strip-comments": "^2.0.0",
70
77
  "@types/yargs": "^15.0.12",
71
78
  "@typescript-eslint/eslint-plugin": "^4.28.1",
72
79
  "@typescript-eslint/parser": "^4.28.1",
@@ -77,7 +84,9 @@
77
84
  "eslint-plugin-jest": "^24.4.0",
78
85
  "eslint-plugin-node": "^11.1.0",
79
86
  "eslint-plugin-prettier": "^3.4.0",
87
+ "execa": "^5.1.1",
80
88
  "jest": "^26.6.3",
89
+ "patch-package": "^6.4.7",
81
90
  "prettier": "^2.3.2",
82
91
  "rimraf": "^3.0.2",
83
92
  "ts-jest": "^26.5.6",