@metamask/snaps-cli 0.11.1 → 0.14.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 +17 -1
- package/dist/cli.js +1 -4
- package/dist/cli.js.map +1 -1
- package/dist/cmds/build/buildHandler.js +1 -1
- package/dist/cmds/build/buildHandler.js.map +1 -1
- package/dist/cmds/build/bundle.d.ts +1 -0
- package/dist/cmds/build/bundle.js +14 -5
- package/dist/cmds/build/bundle.js.map +1 -1
- package/dist/cmds/build/utils.d.ts +2 -18
- package/dist/cmds/build/utils.js +4 -66
- package/dist/cmds/build/utils.js.map +1 -1
- package/dist/cmds/eval/eval-worker.js +5 -1
- package/dist/cmds/eval/eval-worker.js.map +1 -1
- package/dist/cmds/eval/mock.d.ts +1 -0
- package/dist/cmds/eval/mock.js +7 -6
- package/dist/cmds/eval/mock.js.map +1 -1
- package/dist/cmds/init/index.js +5 -1
- package/dist/cmds/init/index.js.map +1 -1
- package/dist/cmds/init/initHandler.js +1 -1
- package/dist/cmds/init/initHandler.js.map +1 -1
- package/dist/cmds/init/initUtils.js +1 -0
- package/dist/cmds/init/initUtils.js.map +1 -1
- package/dist/cmds/manifest/index.js +1 -1
- package/dist/cmds/manifest/index.js.map +1 -1
- package/dist/cmds/manifest/manifestHandler.js +7 -18
- package/dist/cmds/manifest/manifestHandler.js.map +1 -1
- package/dist/cmds/watch/watchHandler.js +1 -1
- package/dist/cmds/watch/watchHandler.js.map +1 -1
- package/dist/utils/readline.d.ts +1 -0
- package/dist/utils/readline.js +5 -1
- package/dist/utils/readline.js.map +1 -1
- package/package.json +4 -3
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.14.0]
|
|
10
|
+
### Changed
|
|
11
|
+
- **BREAKING:** Increase TypeScript compilation target to ES2020 ([#449](https://github.com/MetaMask/snaps-skunkworks/pull/449))
|
|
12
|
+
- This should not be breaking for consumers on any non-deprecated browser or Node.js version.
|
|
13
|
+
|
|
14
|
+
## [0.13.0]
|
|
15
|
+
### Changed
|
|
16
|
+
- No changes this release.
|
|
17
|
+
|
|
18
|
+
## [0.12.0]
|
|
19
|
+
### Changed
|
|
20
|
+
- No changes this release.
|
|
21
|
+
|
|
9
22
|
## [0.11.1]
|
|
10
23
|
### Changed
|
|
11
24
|
- No changes this release.
|
|
@@ -165,7 +178,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
165
178
|
- Example snaps ([#72](https://github.com/MetaMask/snaps-skunkworks/pull/72))
|
|
166
179
|
- The examples now live in their own package, [`@metamask/snap-examples`](https://npmjs.com/package/@metamask/snap-examples).
|
|
167
180
|
|
|
168
|
-
[Unreleased]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.
|
|
181
|
+
[Unreleased]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.14.0...HEAD
|
|
182
|
+
[0.14.0]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.13.0...v0.14.0
|
|
183
|
+
[0.13.0]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.12.0...v0.13.0
|
|
184
|
+
[0.12.0]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.11.1...v0.12.0
|
|
169
185
|
[0.11.1]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.11.0...v0.11.1
|
|
170
186
|
[0.11.0]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.10.7...v0.11.0
|
|
171
187
|
[0.10.7]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.10.6...v0.10.7
|
package/dist/cli.js
CHANGED
|
@@ -32,10 +32,7 @@ function cli(argv, commands) {
|
|
|
32
32
|
(0, utils_1.sanitizeInputs)(yargsArgv);
|
|
33
33
|
}), true)
|
|
34
34
|
.fail((msg, err, _yargs) => {
|
|
35
|
-
|
|
36
|
-
if ((err === null || err === void 0 ? void 0 : err.stack) && global.snaps.verboseErrors) {
|
|
37
|
-
console.error(err.stack);
|
|
38
|
-
}
|
|
35
|
+
(0, utils_1.logError)(msg, err);
|
|
39
36
|
process.exitCode = 1;
|
|
40
37
|
})
|
|
41
38
|
.demandCommand(1, 'You must specify at least one command.')
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;;;;;AAAA,kDAAyC;AAEzC,0DAAkC;AAClC,
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;;;;;AAAA,kDAAyC;AAEzC,0DAAkC;AAClC,mCAMiB;AAEjB,SAAgB,GAAG,CAAC,IAAc,EAAE,QAAa;IAC/C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC9B,oEAAoE;IACpE,IAAA,eAAK,EAAC,OAAO,CAAC;SACX,UAAU,CAAC,SAAS,CAAC;SACrB,KAAK,CAAC,+BAA+B,CAAC;SAEtC,OAAO,CAAC,SAAS,EAAE,sDAAsD,CAAC;SAC1E,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,IAAA,mBAAW,EAAC,IAAA,kBAAU,GAAE,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,CAAC,CAAC;QAC7D,IAAA,sBAAc,EAAC,SAAS,CAAC,CAAC;QAC1B,IAAA,sBAAc,EAAC,SAAS,CAAC,CAAC;IAC5B,CAAC,CAAQ,EACT,IAAI,CACL;SAEA,IAAI,CAAC,CAAC,GAAW,EAAE,GAAU,EAAE,MAAM,EAAE,EAAE;QACxC,IAAA,gBAAQ,EAAC,GAAG,EAAE,GAAG,CAAC,CAAC;QACnB,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;AApDD,kBAoDC","sourcesContent":["import yargs, { Arguments } from 'yargs';\nimport yargsType from 'yargs/yargs';\nimport builders from './builders';\nimport {\n applyConfig,\n loadConfig,\n sanitizeInputs,\n setSnapGlobals,\n logError,\n} 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 .scriptName('mm-snap')\n .usage('Usage: $0 <command> [options]')\n\n .example('$0 init', `\\tInitialize a snap project in the current directory`)\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(loadConfig(), rawArgv, yargsArgv, yargsInstance);\n setSnapGlobals(yargsArgv);\n sanitizeInputs(yargsArgv);\n }) as any,\n true,\n )\n\n .fail((msg: string, err: Error, _yargs) => {\n logError(msg, err);\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"]}
|
|
@@ -26,7 +26,7 @@ async function build(argv) {
|
|
|
26
26
|
const outfilePath = (0, utils_1.getOutfilePath)(dist, outfileName);
|
|
27
27
|
const result = await (0, bundle_1.bundle)(src, outfilePath, argv, (0, utils_1.loadConfig)().bundlerCustomizer);
|
|
28
28
|
if (result && argv.eval) {
|
|
29
|
-
await (0, evalHandler_1.snapEval)(
|
|
29
|
+
await (0, evalHandler_1.snapEval)({ ...argv, bundle: outfilePath });
|
|
30
30
|
}
|
|
31
31
|
if (argv.manifest) {
|
|
32
32
|
await (0, manifestHandler_1.manifestHandler)(argv);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildHandler.js","sourceRoot":"","sources":["../../../src/cmds/build/buildHandler.ts"],"names":[],"mappings":";;;AACA,uCAMqB;AACrB,qDAA+C;AAC/C,iEAA8D;AAC9D,qCAAkC;AAElC;;;;;;;;;;GAUG;AACI,KAAK,UAAU,KAAK,CAAC,IAAe;IACzC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;IACxC,IAAI,WAAW,EAAE;QACf,IAAA,2BAAmB,EAAC,WAAqB,CAAC,CAAC;KAC5C;IACD,MAAM,IAAA,wBAAgB,EAAC,GAAG,CAAC,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AI,CAAC,CAAC;KAC7B;AACH,CAAC;AAtBD,sBAsBC","sourcesContent":["import { YargsArgs } from '../../types/yargs';\nimport {\n getOutfilePath,\n loadConfig,\n validateDirPath,\n validateFilePath,\n validateOutfileName,\n} from '../../utils';\nimport { snapEval } from '../eval/evalHandler';\nimport { manifestHandler } from '../manifest/manifestHandler';\nimport { bundle } from './bundle';\n\n/**\n * Builds all files in the given source directory to the given destination\n * directory.\n *\n * Creates destination directory if it doesn't exist.\n *\n * @param argv - argv from Yargs\n * @param argv.src - The source file path\n * @param argv.dist - The output directory path\n * @param argv.outfileName - The output file name\n */\nexport async function build(argv: YargsArgs): Promise<void> {\n const { src, dist, outfileName } = argv;\n if (outfileName) {\n validateOutfileName(outfileName as string);\n }\n await validateFilePath(src);\n await validateDirPath(dist, true);\n\n const outfilePath = getOutfilePath(dist, outfileName as string);\n const result = await bundle(\n src,\n outfilePath,\n argv,\n loadConfig().bundlerCustomizer,\n );\n if (result && argv.eval) {\n await snapEval({ ...argv, bundle: outfilePath });\n }\n\n if (argv.manifest) {\n await manifestHandler(argv);\n }\n}\n"]}
|
|
@@ -9,5 +9,6 @@ import { YargsArgs } from '../../types/yargs';
|
|
|
9
9
|
* @param argv.sourceMaps - Whether to output sourcemaps.
|
|
10
10
|
* @param argv.stripComments - Whether to remove comments from code.
|
|
11
11
|
* @param argv.transpilationMode - The Babel transpilation mode.
|
|
12
|
+
* @param bundlerTransform
|
|
12
13
|
*/
|
|
13
14
|
export declare function bundle(src: string, dest: string, argv: YargsArgs, bundlerTransform?: (bundler: BrowserifyObject) => void): Promise<boolean>;
|
|
@@ -19,6 +19,7 @@ const utils_1 = require("./utils");
|
|
|
19
19
|
* @param argv.sourceMaps - Whether to output sourcemaps.
|
|
20
20
|
* @param argv.stripComments - Whether to remove comments from code.
|
|
21
21
|
* @param argv.transpilationMode - The Babel transpilation mode.
|
|
22
|
+
* @param bundlerTransform
|
|
22
23
|
*/
|
|
23
24
|
function bundle(src, dest, argv, bundlerTransform) {
|
|
24
25
|
const { sourceMaps: debug, transpilationMode } = argv;
|
|
@@ -26,7 +27,9 @@ function bundle(src, dest, argv, bundlerTransform) {
|
|
|
26
27
|
return new Promise((resolve, _reject) => {
|
|
27
28
|
const bundler = (0, browserify_1.default)(src, { debug });
|
|
28
29
|
if (transpilationMode !== builders_1.TranspilationModes.none) {
|
|
29
|
-
bundler.transform(require('babelify'),
|
|
30
|
+
bundler.transform(require('babelify'), {
|
|
31
|
+
global: transpilationMode === builders_1.TranspilationModes.localAndDeps,
|
|
32
|
+
presets: [
|
|
30
33
|
[
|
|
31
34
|
require('@babel/preset-env'),
|
|
32
35
|
{
|
|
@@ -35,22 +38,28 @@ function bundle(src, dest, argv, bundlerTransform) {
|
|
|
35
38
|
},
|
|
36
39
|
},
|
|
37
40
|
],
|
|
38
|
-
],
|
|
41
|
+
],
|
|
42
|
+
plugins: [
|
|
39
43
|
require('@babel/plugin-transform-runtime'),
|
|
40
44
|
require('@babel/plugin-proposal-class-properties'),
|
|
41
45
|
require('@babel/plugin-proposal-object-rest-spread'),
|
|
42
46
|
require('@babel/plugin-proposal-optional-chaining'),
|
|
43
47
|
require('@babel/plugin-proposal-nullish-coalescing-operator'),
|
|
44
|
-
]
|
|
48
|
+
],
|
|
49
|
+
...babelifyOptions,
|
|
50
|
+
});
|
|
45
51
|
}
|
|
46
|
-
bundlerTransform
|
|
52
|
+
bundlerTransform?.(bundler);
|
|
53
|
+
bundler.plugin('@metamask/snaps-browserify-plugin', {
|
|
54
|
+
stripComments: argv.stripComments,
|
|
55
|
+
transformHtmlComments: argv.transformHtmlComments,
|
|
56
|
+
});
|
|
47
57
|
bundler.bundle(async (bundleError, bundleBuffer) => await (0, utils_1.writeBundleFile)({
|
|
48
58
|
bundleError,
|
|
49
59
|
bundleBuffer,
|
|
50
60
|
src,
|
|
51
61
|
dest,
|
|
52
62
|
resolve,
|
|
53
|
-
argv,
|
|
54
63
|
}));
|
|
55
64
|
});
|
|
56
65
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundle.js","sourceRoot":"","sources":["../../../src/cmds/build/bundle.ts"],"names":[],"mappings":";;;;;;AAAA,4DAA0D;AAC1D,6CAAoD;AAEpD,mCAA+D;AAE/D,+EAA+E;AAC/E,mEAAmE;AACnE,mHAAmH;AAEnH
|
|
1
|
+
{"version":3,"file":"bundle.js","sourceRoot":"","sources":["../../../src/cmds/build/bundle.ts"],"names":[],"mappings":";;;;;;AAAA,4DAA0D;AAC1D,6CAAoD;AAEpD,mCAA+D;AAE/D,+EAA+E;AAC/E,mEAAmE;AACnE,mHAAmH;AAEnH;;;;;;;;;;GAUG;AACH,SAAgB,MAAM,CACpB,GAAW,EACX,IAAY,EACZ,IAAe,EACf,gBAAsD;IAEtD,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC;IACtD,MAAM,eAAe,GAAG,IAAA,2BAAmB,EAAC,IAAW,CAAC,CAAC;IACzD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE;QACtC,MAAM,OAAO,GAAG,IAAA,oBAAU,EAAC,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAE3C,IAAI,iBAAiB,KAAK,6BAAkB,CAAC,IAAI,EAAE;YACjD,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE;gBACrC,MAAM,EAAE,iBAAiB,KAAK,6BAAkB,CAAC,YAAY;gBAC7D,OAAO,EAAE;oBACP;wBACE,OAAO,CAAC,mBAAmB,CAAC;wBAC5B;4BACE,OAAO,EAAE;gCACP,QAAQ,EAAE,CAAC,cAAc,EAAE,eAAe,CAAC;6BAC5C;yBACF;qBACF;iBACF;gBACD,OAAO,EAAE;oBACP,OAAO,CAAC,iCAAiC,CAAC;oBAC1C,OAAO,CAAC,yCAAyC,CAAC;oBAClD,OAAO,CAAC,2CAA2C,CAAC;oBACpD,OAAO,CAAC,0CAA0C,CAAC;oBACnD,OAAO,CAAC,oDAAoD,CAAC;iBAC9D;gBACD,GAAI,eAAuB;aAC5B,CAAC,CAAC;SACJ;QAED,gBAAgB,EAAE,CAAC,OAAO,CAAC,CAAC;QAE5B,OAAO,CAAC,MAAM,CAAC,mCAAmC,EAAE;YAClD,aAAa,EAAE,IAAI,CAAC,aAAa;YACjC,qBAAqB,EAAE,IAAI,CAAC,qBAAqB;SAClD,CAAC,CAAC;QAEH,OAAO,CAAC,MAAM,CACZ,KAAK,EAAE,WAAW,EAAE,YAAoB,EAAE,EAAE,CAC1C,MAAM,IAAA,uBAAe,EAAC;YACpB,WAAW;YACX,YAAY;YACZ,GAAG;YACH,IAAI;YACJ,OAAO;SACR,CAAC,CACL,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AArDD,wBAqDC","sourcesContent":["import browserify, { BrowserifyObject } from 'browserify';\nimport { TranspilationModes } from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { processDependencies, writeBundleFile } from './utils';\n\n// We need to statically import all Browserify transforms and all Babel presets\n// and plugins, and calling `require` is the sanest way to do that.\n/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */\n\n/**\n * Builds a Snap bundle JS 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 * @param argv.transpilationMode - The Babel transpilation mode.\n * @param bundlerTransform\n */\nexport function bundle(\n src: string,\n dest: string,\n argv: YargsArgs,\n bundlerTransform?: (bundler: BrowserifyObject) => void,\n): Promise<boolean> {\n const { sourceMaps: debug, transpilationMode } = argv;\n const babelifyOptions = processDependencies(argv as any);\n return new Promise((resolve, _reject) => {\n const bundler = browserify(src, { debug });\n\n if (transpilationMode !== TranspilationModes.none) {\n bundler.transform(require('babelify'), {\n global: transpilationMode === TranspilationModes.localAndDeps,\n presets: [\n [\n require('@babel/preset-env'),\n {\n targets: {\n browsers: ['chrome >= 66', 'firefox >= 68'],\n },\n },\n ],\n ],\n plugins: [\n require('@babel/plugin-transform-runtime'),\n require('@babel/plugin-proposal-class-properties'),\n require('@babel/plugin-proposal-object-rest-spread'),\n require('@babel/plugin-proposal-optional-chaining'),\n require('@babel/plugin-proposal-nullish-coalescing-operator'),\n ],\n ...(babelifyOptions as any),\n });\n }\n\n bundlerTransform?.(bundler);\n\n bundler.plugin('@metamask/snaps-browserify-plugin', {\n stripComments: argv.stripComments,\n transformHtmlComments: argv.transformHtmlComments,\n });\n\n bundler.bundle(\n async (bundleError, bundleBuffer: Buffer) =>\n await writeBundleFile({\n bundleError,\n bundleBuffer,\n src,\n dest,\n resolve,\n }),\n );\n });\n}\n"]}
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
-
import {
|
|
2
|
+
import { YargsArgs } from '../../types/yargs';
|
|
3
3
|
declare type WriteBundleFileArgs = {
|
|
4
4
|
bundleError: Error;
|
|
5
5
|
bundleBuffer: Buffer;
|
|
6
6
|
src: string;
|
|
7
7
|
dest: string;
|
|
8
8
|
resolve: (value: boolean) => void;
|
|
9
|
-
argv: YargsArgs;
|
|
10
9
|
};
|
|
11
10
|
/**
|
|
12
11
|
* Performs postprocessing on the bundle contents and writes them to disk.
|
|
@@ -21,23 +20,8 @@ declare type WriteBundleFileArgs = {
|
|
|
21
20
|
* @param options.dest - The destination file path.
|
|
22
21
|
* @param options.resolve - A {@link Promise} resolution function, so that we
|
|
23
22
|
* can use promises and `async`/`await` even though Browserify uses callbacks.
|
|
24
|
-
* @param options.argv - The Yargs `argv` object.
|
|
25
23
|
*/
|
|
26
|
-
export declare function writeBundleFile({ bundleError, bundleBuffer, src, dest, resolve,
|
|
27
|
-
/**
|
|
28
|
-
* Postprocesses a JavaScript bundle string such that it can be evaluated in SES.
|
|
29
|
-
* Currently:
|
|
30
|
-
* - converts certain dot notation to string notation (for indexing)
|
|
31
|
-
* - makes all direct calls to eval indirect
|
|
32
|
-
* - wraps original bundle in anonymous function
|
|
33
|
-
* - handles certain Babel-related edge cases
|
|
34
|
-
*
|
|
35
|
-
* @param bundleString - The bundle string
|
|
36
|
-
* @param options - post process options
|
|
37
|
-
* @param options.stripComments
|
|
38
|
-
* @returns - The postprocessed bundle string
|
|
39
|
-
*/
|
|
40
|
-
export declare function postProcess(bundleString: string | null, options?: Partial<Option>): string | null;
|
|
24
|
+
export declare function writeBundleFile({ bundleError, bundleBuffer, src, dest, resolve, }: WriteBundleFileArgs): Promise<void>;
|
|
41
25
|
/**
|
|
42
26
|
* Processes dependencies and updates argv with an options object
|
|
43
27
|
* @param argv
|
package/dist/cmds/build/utils.js
CHANGED
|
@@ -1,11 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.processInvalidTranspilation = exports.sanitizeDependencyPaths = exports.getDependencyRegExp = exports.processDependencies = exports.
|
|
3
|
+
exports.processInvalidTranspilation = exports.sanitizeDependencyPaths = exports.getDependencyRegExp = exports.processDependencies = exports.writeBundleFile = void 0;
|
|
7
4
|
const fs_1 = require("fs");
|
|
8
|
-
const strip_comments_1 = __importDefault(require("@chainsafe/strip-comments"));
|
|
9
5
|
const misc_1 = require("../../utils/misc");
|
|
10
6
|
const builders_1 = require("../../builders");
|
|
11
7
|
/**
|
|
@@ -21,20 +17,14 @@ const builders_1 = require("../../builders");
|
|
|
21
17
|
* @param options.dest - The destination file path.
|
|
22
18
|
* @param options.resolve - A {@link Promise} resolution function, so that we
|
|
23
19
|
* can use promises and `async`/`await` even though Browserify uses callbacks.
|
|
24
|
-
* @param options.argv - The Yargs `argv` object.
|
|
25
20
|
*/
|
|
26
|
-
async function writeBundleFile({ bundleError, bundleBuffer, src, dest, resolve,
|
|
21
|
+
async function writeBundleFile({ bundleError, bundleBuffer, src, dest, resolve, }) {
|
|
27
22
|
if (bundleError) {
|
|
28
23
|
await (0, misc_1.writeError)('Build error:', bundleError.message, bundleError);
|
|
29
24
|
}
|
|
30
25
|
try {
|
|
31
|
-
await fs_1.promises.writeFile(dest,
|
|
32
|
-
|
|
33
|
-
transformHtmlComments: argv.transformHtmlComments,
|
|
34
|
-
}));
|
|
35
|
-
if (bundleBuffer) {
|
|
36
|
-
console.log(`Build success: '${src}' bundled as '${dest}'!`);
|
|
37
|
-
}
|
|
26
|
+
await fs_1.promises.writeFile(dest, bundleBuffer?.toString());
|
|
27
|
+
console.log(`Build success: '${src}' bundled as '${dest}'!`);
|
|
38
28
|
resolve(true);
|
|
39
29
|
}
|
|
40
30
|
catch (error) {
|
|
@@ -42,58 +32,6 @@ async function writeBundleFile({ bundleError, bundleBuffer, src, dest, resolve,
|
|
|
42
32
|
}
|
|
43
33
|
}
|
|
44
34
|
exports.writeBundleFile = writeBundleFile;
|
|
45
|
-
/**
|
|
46
|
-
* Postprocesses a JavaScript bundle string such that it can be evaluated in SES.
|
|
47
|
-
* Currently:
|
|
48
|
-
* - converts certain dot notation to string notation (for indexing)
|
|
49
|
-
* - makes all direct calls to eval indirect
|
|
50
|
-
* - wraps original bundle in anonymous function
|
|
51
|
-
* - handles certain Babel-related edge cases
|
|
52
|
-
*
|
|
53
|
-
* @param bundleString - The bundle string
|
|
54
|
-
* @param options - post process options
|
|
55
|
-
* @param options.stripComments
|
|
56
|
-
* @returns - The postprocessed bundle string
|
|
57
|
-
*/
|
|
58
|
-
function postProcess(bundleString, options = {}) {
|
|
59
|
-
if (typeof bundleString !== 'string') {
|
|
60
|
-
return null;
|
|
61
|
-
}
|
|
62
|
-
let processedString = bundleString.trim();
|
|
63
|
-
if (options.stripComments) {
|
|
64
|
-
processedString = (0, strip_comments_1.default)(processedString);
|
|
65
|
-
}
|
|
66
|
-
// Break up tokens that could be parsed as HTML comment terminators.
|
|
67
|
-
// The regular expressions below are written strangely so as to avoid the
|
|
68
|
-
// appearance of such tokens in our source code.
|
|
69
|
-
// Ref: https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md
|
|
70
|
-
// This aggressive hack may change the behavior of programs that contain HTML
|
|
71
|
-
// comment terminators in string literals.
|
|
72
|
-
if (options.transformHtmlComments) {
|
|
73
|
-
processedString = processedString.replace(new RegExp(`<!${'--'}`, 'gu'), '< !--');
|
|
74
|
-
processedString = processedString.replace(new RegExp(`${'--'}>`, 'gu'), '-- >');
|
|
75
|
-
}
|
|
76
|
-
// stuff.eval(otherStuff) => (1, stuff.eval)(otherStuff)
|
|
77
|
-
processedString = processedString.replace(/((?:\b[\w\d]*[\])]?\.)+eval)(\([^)]*\))/gu, '(1, $1)$2');
|
|
78
|
-
// If we don't do the above, the below causes syntax errors if it encounters
|
|
79
|
-
// things of the form: "something.eval(stuff)"
|
|
80
|
-
// eval(stuff) => (1, eval)(stuff)
|
|
81
|
-
processedString = processedString.replace(/(\b)(eval)(\([^)]*\))/gu, '$1(1, $2)$3');
|
|
82
|
-
// Browserify provides the Buffer global as an argument to modules that use
|
|
83
|
-
// it, but this does not work in SES. Since we pass in Buffer as an endowment,
|
|
84
|
-
// we can simply remove the argument.
|
|
85
|
-
processedString = processedString.replace(/^\(function \(Buffer\)\{$/gmu, '(function (){');
|
|
86
|
-
if (processedString.length === 0) {
|
|
87
|
-
throw new Error(`Bundled code is empty after postprocessing.`);
|
|
88
|
-
}
|
|
89
|
-
// handle some cases by declaring missing globals
|
|
90
|
-
// Babel regeneratorRuntime
|
|
91
|
-
if (processedString.indexOf('regeneratorRuntime') !== -1) {
|
|
92
|
-
processedString = `var regeneratorRuntime;\n${processedString}`;
|
|
93
|
-
}
|
|
94
|
-
return processedString;
|
|
95
|
-
}
|
|
96
|
-
exports.postProcess = postProcess;
|
|
97
35
|
/**
|
|
98
36
|
* Processes dependencies and updates argv with an options object
|
|
99
37
|
* @param argv
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/cmds/build/utils.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/cmds/build/utils.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AACpC,2CAA8C;AAE9C,6CAAoD;AAUpD;;;;;;;;;;;;;GAaG;AACI,KAAK,UAAU,eAAe,CAAC,EACpC,WAAW,EACX,YAAY,EACZ,GAAG,EACH,IAAI,EACJ,OAAO,GACa;IACpB,IAAI,WAAW,EAAE;QACf,MAAM,IAAA,iBAAU,EAAC,cAAc,EAAE,WAAW,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;KACpE;IAED,IAAI;QACF,MAAM,aAAE,CAAC,SAAS,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC,CAAC;QACnD,OAAO,CAAC,GAAG,CAAC,mBAAmB,GAAG,iBAAiB,IAAI,IAAI,CAAC,CAAC;QAC7D,OAAO,CAAC,IAAI,CAAC,CAAC;KACf;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAA,iBAAU,EAAC,cAAc,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;KAC9D;AACH,CAAC;AAlBD,0CAkBC;AAED;;;GAGG;AACH,SAAgB,mBAAmB,CAAC,IAAe;IACjD,MAAM,EAAE,eAAe,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC;IACpD,MAAM,eAAe,GAAwB,EAAE,CAAC;IAChD,IAAI,iBAAiB,KAAK,6BAAkB,CAAC,YAAY,EAAE;QACzD,MAAM,SAAS,GAAG,mBAAmB,CAAC,eAA2B,CAAC,CAAC;QACnE,IAAI,SAAS,KAAK,IAAI,EAAE;YACtB,eAAe,CAAC,MAAM,GAAG,CAAC,SAAS,CAAC,CAAC;SACtC;KACF;IACD,OAAO,eAAe,CAAC;AACzB,CAAC;AAVD,kDAUC;AAED;;;;GAIG;AACH,SAAgB,mBAAmB,CAAC,YAAsB;IACxD,IAAI,MAAM,GAAkB,IAAI,CAAC;IACjC,IAAI,CAAC,YAAY,IAAI,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE;QACvE,OAAO,MAAM,CAAC;KACf;IACD,MAAM,KAAK,GAAa,uBAAuB,CAAC,YAAY,CAAC,CAAC;IAC9D,MAAM,GAAG,oBAAoB,KAAK,CAAC,KAAK,EAAE,EAAE,CAAC;IAC7C,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,MAAM,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;IAChD,MAAM,IAAI,IAAI,CAAC;IACf,OAAO,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAC7B,CAAC;AAVD,kDAUC;AAED;;;;GAIG;AACH,SAAgB,uBAAuB,CAAC,YAAsB;IAC5D,OAAO,YAAY,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE;QACrC,OAAO,UAAU,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IACpE,CAAC,CAAC,CAAC;AACL,CAAC;AAJD,0DAIC;AAED,SAAgB,2BAA2B,CAAC,IAAe;IACzD,IACE,IAAI,CAAC,eAAe;QACpB,IAAI,CAAC,iBAAiB,KAAK,6BAAkB,CAAC,YAAY,EAC1D;QACA,MAAM,IAAI,KAAK,CACb,2FAA2F,CAC5F,CAAC;KACH;AACH,CAAC;AATD,kEASC","sourcesContent":["import { promises as fs } from 'fs';\nimport { writeError } from '../../utils/misc';\nimport { YargsArgs } from '../../types/yargs';\nimport { TranspilationModes } from '../../builders';\n\ntype WriteBundleFileArgs = {\n bundleError: Error;\n bundleBuffer: Buffer;\n src: string;\n dest: string;\n resolve: (value: boolean) => void;\n};\n\n/**\n * Performs postprocessing on the bundle contents and writes them to disk.\n * Intended to be used in the callback passed to the Browserify `.bundle()`\n * call.\n *\n * @param options - Options bag.\n * @param options.bundleError - Any error received from Browserify.\n * @param options.bundleBuffer - The {@link Buffer} with the bundle contents\n * from Browserify.\n * @param options.src - The source file path.\n * @param options.dest - The destination file path.\n * @param options.resolve - A {@link Promise} resolution function, so that we\n * can use promises and `async`/`await` even though Browserify uses callbacks.\n */\nexport async function writeBundleFile({\n bundleError,\n bundleBuffer,\n src,\n dest,\n resolve,\n}: WriteBundleFileArgs) {\n if (bundleError) {\n await writeError('Build error:', bundleError.message, bundleError);\n }\n\n try {\n await fs.writeFile(dest, bundleBuffer?.toString());\n console.log(`Build success: '${src}' bundled as '${dest}'!`);\n resolve(true);\n } catch (error) {\n await writeError('Write error:', error.message, error, dest);\n }\n}\n\n/**\n * Processes dependencies and updates argv with an options object\n * @param argv\n */\nexport function processDependencies(argv: YargsArgs) {\n const { depsToTranspile, transpilationMode } = argv;\n const babelifyOptions: Record<string, any> = {};\n if (transpilationMode === TranspilationModes.localAndDeps) {\n const regexpStr = getDependencyRegExp(depsToTranspile as string[]);\n if (regexpStr !== null) {\n babelifyOptions.ignore = [regexpStr];\n }\n }\n return babelifyOptions;\n}\n\n/**\n * Processes a string of space delimited dependencies into one regex string\n * @param dependencies\n * @returns a regexp string\n */\nexport function getDependencyRegExp(dependencies: string[]): RegExp | null {\n let regexp: string | null = null;\n if (!dependencies || dependencies.includes('.') || !dependencies.length) {\n return regexp;\n }\n const paths: string[] = sanitizeDependencyPaths(dependencies);\n regexp = `/node_modules/(?!${paths.shift()}`;\n paths.forEach((path) => (regexp += `|${path}`));\n regexp += '/)';\n return RegExp(regexp, 'u');\n}\n\n/**\n * Helper function remove any leading and trailing slashes from dependency list\n * @param dependencies\n * @returns an array of sanitized paths\n */\nexport function sanitizeDependencyPaths(dependencies: string[]): string[] {\n return dependencies.map((dependency) => {\n return dependency.replace(/^[/\\\\]+/u, '').replace(/[/\\\\]+$/u, '');\n });\n}\n\nexport function processInvalidTranspilation(argv: YargsArgs) {\n if (\n argv.depsToTranspile &&\n argv.transpilationMode !== TranspilationModes.localAndDeps\n ) {\n throw new Error(\n '\"depsToTranspile\" can only be specified if \"transpilationMode\" is set to \"localAndDeps\" .',\n );\n }\n}\n"]}
|
|
@@ -21,6 +21,10 @@ if (worker_threads_1.parentPort !== null) {
|
|
|
21
21
|
}
|
|
22
22
|
function getMockEndowments() {
|
|
23
23
|
const endowments = (0, mock_1.generateMockEndowments)();
|
|
24
|
-
return
|
|
24
|
+
return {
|
|
25
|
+
...endowments,
|
|
26
|
+
window: endowments,
|
|
27
|
+
self: endowments,
|
|
28
|
+
};
|
|
25
29
|
}
|
|
26
30
|
//# sourceMappingURL=eval-worker.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eval-worker.js","sourceRoot":"","sources":["../../../src/cmds/eval/eval-worker.ts"],"names":[],"mappings":";;AAAA,mDAA4C;AAC5C,2BAAkC;AAClC,iCAAgD;AAEhD,uDAAuD;AACvD,wBAAsB;AAItB,QAAQ,CAAC;IACP,aAAa,EAAE,QAAQ;IACvB,WAAW,EAAE,QAAQ;IACrB,UAAU,EAAE,QAAQ;IACpB,UAAU,EAAE,QAAQ;IACpB,cAAc,EAAE,QAAQ;CACzB,CAAC,CAAC;AAEH,IAAI,2BAAU,KAAK,IAAI,EAAE;IACvB,2BAAU,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAiC,EAAE,EAAE;QAC7D,MAAM,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC;QAEjC,IAAI,WAAW,CAAC,iBAAiB,EAAE,CAAC,CAAC,QAAQ,CAC3C,IAAA,iBAAY,EAAC,YAAY,EAAE,MAAM,CAAC,CACnC,CAAC;QACF,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,8BAA8B;IACzE,CAAC,CAAC,CAAC;CACJ;AAED,SAAS,iBAAiB;IACxB,MAAM,UAAU,GAAG,IAAA,6BAAsB,GAAE,CAAC;IAC5C,
|
|
1
|
+
{"version":3,"file":"eval-worker.js","sourceRoot":"","sources":["../../../src/cmds/eval/eval-worker.ts"],"names":[],"mappings":";;AAAA,mDAA4C;AAC5C,2BAAkC;AAClC,iCAAgD;AAEhD,uDAAuD;AACvD,wBAAsB;AAItB,QAAQ,CAAC;IACP,aAAa,EAAE,QAAQ;IACvB,WAAW,EAAE,QAAQ;IACrB,UAAU,EAAE,QAAQ;IACpB,UAAU,EAAE,QAAQ;IACpB,cAAc,EAAE,QAAQ;CACzB,CAAC,CAAC;AAEH,IAAI,2BAAU,KAAK,IAAI,EAAE;IACvB,2BAAU,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAiC,EAAE,EAAE;QAC7D,MAAM,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC;QAEjC,IAAI,WAAW,CAAC,iBAAiB,EAAE,CAAC,CAAC,QAAQ,CAC3C,IAAA,iBAAY,EAAC,YAAY,EAAE,MAAM,CAAC,CACnC,CAAC;QACF,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,8BAA8B;IACzE,CAAC,CAAC,CAAC;CACJ;AAED,SAAS,iBAAiB;IACxB,MAAM,UAAU,GAAG,IAAA,6BAAsB,GAAE,CAAC;IAC5C,OAAO;QACL,GAAG,UAAU;QACb,MAAM,EAAE,UAAU;QAClB,IAAI,EAAE,UAAU;KACjB,CAAC;AACJ,CAAC","sourcesContent":["import { parentPort } from 'worker_threads';\nimport { readFileSync } from 'fs';\nimport { generateMockEndowments } from './mock';\n\n// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n});\n\nif (parentPort !== null) {\n parentPort.on('message', (message: { snapFilePath: string }) => {\n const { snapFilePath } = message;\n\n new Compartment(getMockEndowments()).evaluate(\n readFileSync(snapFilePath, 'utf8'),\n );\n setTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n });\n}\n\nfunction getMockEndowments() {\n const endowments = generateMockEndowments();\n return {\n ...endowments,\n window: endowments,\n self: endowments,\n };\n}\n"]}
|
package/dist/cmds/eval/mock.d.ts
CHANGED
package/dist/cmds/eval/mock.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.generateMockEndowments = exports.ALL_APIS = void 0;
|
|
6
|
+
exports.generateMockEndowments = exports.isConstructor = exports.ALL_APIS = void 0;
|
|
7
7
|
const events_1 = __importDefault(require("events"));
|
|
8
8
|
const crypto_1 = __importDefault(require("crypto"));
|
|
9
9
|
const snap_controllers_1 = require("@metamask/snap-controllers");
|
|
@@ -15,7 +15,8 @@ function getMockSnapProvider() {
|
|
|
15
15
|
mockProvider.request = async () => true;
|
|
16
16
|
return mockProvider;
|
|
17
17
|
}
|
|
18
|
-
const isConstructor = (value) =>
|
|
18
|
+
const isConstructor = (value) => Boolean(typeof value?.prototype?.constructor?.name === 'string');
|
|
19
|
+
exports.isConstructor = isConstructor;
|
|
19
20
|
const mockFunction = () => true;
|
|
20
21
|
class MockClass {
|
|
21
22
|
}
|
|
@@ -37,16 +38,16 @@ const mockWindow = {
|
|
|
37
38
|
SubtleCrypto: MockClass,
|
|
38
39
|
};
|
|
39
40
|
const generateMockEndowment = (key) => {
|
|
40
|
-
const globalValue =
|
|
41
|
+
const globalValue = globalThis[key];
|
|
41
42
|
// Default exposed APIs don't need to be mocked
|
|
42
43
|
if (globalValue && snap_controllers_1.DEFAULT_ENDOWMENTS.includes(key)) {
|
|
43
44
|
return globalValue;
|
|
44
45
|
}
|
|
45
46
|
// Fall back to mockWindow for certain APIs not exposed in global in Node.JS
|
|
46
|
-
const globalOrMocked = globalValue
|
|
47
|
+
const globalOrMocked = globalValue ?? mockWindow[key];
|
|
47
48
|
const type = typeof globalOrMocked;
|
|
48
49
|
const isFunction = type === 'function';
|
|
49
|
-
if (isFunction && isConstructor(globalOrMocked)) {
|
|
50
|
+
if (isFunction && (0, exports.isConstructor)(globalOrMocked)) {
|
|
50
51
|
return generateMockClass(globalOrMocked);
|
|
51
52
|
}
|
|
52
53
|
else if (isFunction || !globalOrMocked) {
|
|
@@ -56,7 +57,7 @@ const generateMockEndowment = (key) => {
|
|
|
56
57
|
return globalOrMocked;
|
|
57
58
|
};
|
|
58
59
|
const generateMockEndowments = () => {
|
|
59
|
-
return exports.ALL_APIS.reduce((acc, cur) => (
|
|
60
|
+
return exports.ALL_APIS.reduce((acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }), { wallet: getMockSnapProvider() });
|
|
60
61
|
};
|
|
61
62
|
exports.generateMockEndowments = generateMockEndowments;
|
|
62
63
|
//# sourceMappingURL=mock.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mock.js","sourceRoot":"","sources":["../../../src/cmds/eval/mock.ts"],"names":[],"mappings":";;;;;;AAAA,oDAAkC;AAClC,oDAA4B;AAC5B,iEAAgE;AAEhE,MAAM,YAAY,GAAG,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;AAE/B,QAAA,QAAQ,GAAa,CAAC,GAAG,qCAAkB,EAAE,GAAG,YAAY,CAAC,CAAC;AAO3E,SAAS,mBAAmB;IAC1B,MAAM,YAAY,GAAG,IAAI,gBAAY,EAA+B,CAAC;IACrE,YAAY,CAAC,yBAAyB,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC;IACpD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AEF,8IAA8I;AAC9I,MAAM,UAAU,GAAG;IACjB,SAAS,EAAE,SAAS;IACpB,MAAM,EAAN,gBAAM;IACN,YAAY,EAAE,SAAS;CACxB,CAAC;AAEF,MAAM,qBAAqB,GAAG,CAAC,GAAW,EAAE,EAAE;IAC5C,MAAM,WAAW,GAAI,UAAkB,CAAC,GAAG,CAAC,CAAC;IAE7C,+CAA+C;IAC/C,IAAI,WAAW,IAAI,qCAAkB,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;QACnD,OAAO,WAAW,CAAC;KACpB;IAED,4EAA4E;IAC5E,MAAM,cAAc,GAAG,WAAW,IAAK,UAAkB,CAAC,GAAG,CAAC,CAAC;IAE/D,MAAM,IAAI,GAAG,OAAO,cAAc,CAAC;IACnC,MAAM,UAAU,GAAG,IAAI,KAAK,UAAU,CAAC;IACvC,IAAI,UAAU,IAAI,IAAA,qBAAa,EAAC,cAAc,CAAC,EAAE;QAC/C,OAAO,iBAAiB,CAAC,cAAc,CAAC,CAAC;KAC1C;SAAM,IAAI,UAAU,IAAI,CAAC,cAAc,EAAE;QACxC,qCAAqC;QACrC,OAAO,YAAY,CAAC;KACrB;IACD,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAEK,MAAM,sBAAsB,GAAG,GAAG,EAAE;IACzC,OAAO,gBAAQ,CAAC,MAAM,CACpB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,qBAAqB,CAAC,GAAG,CAAC,EAAE,CAAC,EAC7D,EAAE,MAAM,EAAE,mBAAmB,EAAE,EAAE,CAClC,CAAC;AACJ,CAAC,CAAC;AALW,QAAA,sBAAsB,0BAKjC","sourcesContent":["import EventEmitter from 'events';\nimport crypto from 'crypto';\nimport { DEFAULT_ENDOWMENTS } from '@metamask/snap-controllers';\n\nconst NETWORK_APIS = ['fetch', 'WebSocket'];\n\nexport const ALL_APIS: string[] = [...DEFAULT_ENDOWMENTS, ...NETWORK_APIS];\n\ntype MockSnapProvider = EventEmitter & {\n registerRpcMessageHandler: () => any;\n request: () => Promise<any>;\n};\n\nfunction getMockSnapProvider(): MockSnapProvider {\n const mockProvider = new EventEmitter() as Partial<MockSnapProvider>;\n mockProvider.registerRpcMessageHandler = () => true;\n mockProvider.request = async () => true;\n return mockProvider as MockSnapProvider;\n}\n\nexport const isConstructor = (value: any) =>\n Boolean(typeof value?.prototype?.constructor?.name === 'string');\n\nconst mockFunction = () => true;\nclass MockClass {}\n\nconst handler = {\n construct(Target: any, args: any[]): any {\n return new Proxy(new Target(...args), handler);\n },\n get(_target: any, _prop: any) {\n return mockFunction;\n },\n};\n\nconst generateMockClass = (value: any) => {\n return new Proxy(value, handler);\n};\n\n// Things not currently auto-mocked because of NodeJS, by adding them here we have types for them and can use that to generate mocks if needed\nconst mockWindow = {\n WebSocket: MockClass,\n crypto,\n SubtleCrypto: MockClass,\n};\n\nconst generateMockEndowment = (key: string) => {\n const globalValue = (globalThis as any)[key];\n\n // Default exposed APIs don't need to be mocked\n if (globalValue && DEFAULT_ENDOWMENTS.includes(key)) {\n return globalValue;\n }\n\n // Fall back to mockWindow for certain APIs not exposed in global in Node.JS\n const globalOrMocked = globalValue ?? (mockWindow as any)[key];\n\n const type = typeof globalOrMocked;\n const isFunction = type === 'function';\n if (isFunction && isConstructor(globalOrMocked)) {\n return generateMockClass(globalOrMocked);\n } else if (isFunction || !globalOrMocked) {\n // Fall back to function mock for now\n return mockFunction;\n }\n return globalOrMocked;\n};\n\nexport const generateMockEndowments = () => {\n return ALL_APIS.reduce<Record<string, any>>(\n (acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }),\n { wallet: getMockSnapProvider() },\n );\n};\n"]}
|
package/dist/cmds/init/index.js
CHANGED
|
@@ -8,7 +8,11 @@ const initHandler_1 = require("./initHandler");
|
|
|
8
8
|
async function init(argv) {
|
|
9
9
|
console.log();
|
|
10
10
|
const newArgs = await (0, initHandler_1.initHandler)(argv);
|
|
11
|
-
await (0, buildHandler_1.build)(
|
|
11
|
+
await (0, buildHandler_1.build)({
|
|
12
|
+
...newArgs,
|
|
13
|
+
manifest: false,
|
|
14
|
+
eval: true,
|
|
15
|
+
});
|
|
12
16
|
await (0, initHandler_1.updateManifestShasum)();
|
|
13
17
|
console.log('\nSnap project successfully initiated!');
|
|
14
18
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/init/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,wDAA8C;AAC9C,+CAAkE;AAelE,KAAK,UAAU,IAAI,CAAC,IAAe;IACjC,OAAO,CAAC,GAAG,EAAE,CAAC;IACd,MAAM,OAAO,GAAG,MAAM,IAAA,yBAAW,EAAC,IAAI,CAAC,CAAC;IAExC,MAAM,IAAA,oBAAK,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/init/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,wDAA8C;AAC9C,+CAAkE;AAelE,KAAK,UAAU,IAAI,CAAC,IAAe;IACjC,OAAO,CAAC,GAAG,EAAE,CAAC;IACd,MAAM,OAAO,GAAG,MAAM,IAAA,yBAAW,EAAC,IAAI,CAAC,CAAC;IAExC,MAAM,IAAA,oBAAK,EAAC;QACV,GAAG,OAAO;QACV,QAAQ,EAAE,KAAK;QACf,IAAI,EAAE,IAAI;KACX,CAAC,CAAC;IAEH,MAAM,IAAA,kCAAoB,GAAE,CAAC;IAE7B,OAAO,CAAC,GAAG,CAAC,wCAAwC,CAAC,CAAC;AACxD,CAAC;AA1BD,iBAAS;IACP,OAAO,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC;IACtB,IAAI,EAAE,yBAAyB;IAC/B,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI;aACD,MAAM,CAAC,KAAK,EAAE,kBAAQ,CAAC,GAAG,CAAC;aAC3B,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC;aAC7B,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC;aAC7B,MAAM,CAAC,aAAa,EAAE,kBAAQ,CAAC,WAAW,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,EAAE,CAAC,IAAe,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;CACzC,CAAC","sourcesContent":["import yargs from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { build } from '../build/buildHandler';\nimport { initHandler, updateManifestShasum } from './initHandler';\n\nexport = {\n command: ['init', 'i'],\n desc: 'Initialize Snap package',\n builder: (yarg: yargs.Argv) => {\n yarg\n .option('src', builders.src)\n .option('dist', builders.dist)\n .option('port', builders.port)\n .option('outfileName', builders.outfileName);\n },\n handler: (argv: YargsArgs) => init(argv),\n};\n\nasync function init(argv: YargsArgs): Promise<void> {\n console.log();\n const newArgs = await initHandler(argv);\n\n await build({\n ...newArgs,\n manifest: false,\n eval: true,\n });\n\n await updateManifestShasum();\n\n console.log('\\nSnap project successfully initiated!');\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initHandler.js","sourceRoot":"","sources":["../../../src/cmds/init/initHandler.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAoC;AACpC,gDAA6B;AAC7B,iEAIoC;AACpC,oDAA4B;AAE5B,uCAMqB;AACrB,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,IAAA,4BAAgB,GAAE,CAAC;IAE7C,MAAM,IAAA,mCAAuB,GAAE,CAAC;IAEhC,OAAO,CAAC,GAAG,CAAC,qBAAqB,mCAAgB,CAAC,QAAQ,QAAQ,CAAC,CAAC;IAEpE,MAAM,C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;IAC7D,MAAM,aAAE,CAAC,SAAS,CAChB,mCAAgB,CAAC,QAAQ,EACzB,IAAI,CAAC,SAAS,CAAC,IAAA,qCAAmB,EAAC,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 {\n closePrompt,\n CONFIG_FILE,\n logError,\n readJsonFile,\n SnapConfig,\n} 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 const defaultConfig: SnapConfig = {\n cliOptions: newArgs,\n };\n const defaultConfigFile = `module.exports = ${JSON.stringify(\n defaultConfig,\n null,\n 2,\n )}\n `;\n await fs.writeFile(CONFIG_FILE, defaultConfigFile);\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"]}
|
|
@@ -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;AAE1B,uCAQqB;AAErB;;GAEG;AACH,MAAM,kBAAkB,GAAG,8CAA8C,CAAC;AAE1E,MAAM,uBAAuB,GAAG,4BAA4B,CAAC;AAE7D;;;;;;GAMG;AACI,KAAK,UAAU,gBAAgB;IAGpC,IAAI,IAAA,eAAU,EAAC,wBAAgB,CAAC,WAAW,CAAC,EAAE;QAC5C,OAAO,CAAC,GAAG,CACT,qCAAqC,wBAAgB,CAAC,WAAW,MAAM,CACxE,CAAC;QAEF,IAAI;YACF,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a,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"]}
|
|
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,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,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,IAAA,cAAM,EAAC;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 iconPath: 'icon.svg',\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"]}
|
|
@@ -9,7 +9,7 @@ module.exports = {
|
|
|
9
9
|
command: ['manifest', 'm'],
|
|
10
10
|
desc: 'Validate the snap.manifest.json file',
|
|
11
11
|
builder: (yarg) => {
|
|
12
|
-
yarg.option('writeManifest',
|
|
12
|
+
yarg.option('writeManifest', { ...builders_1.default.writeManifest, alias: ['fix'] });
|
|
13
13
|
},
|
|
14
14
|
handler: async (argv) => {
|
|
15
15
|
try {
|
|
@@ -1 +1 @@
|
|
|
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,
|
|
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,EAAE,EAAE,GAAG,kBAAQ,CAAC,aAAa,EAAE,KAAK,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,IAAe,EAAE,EAAE;QACjC,IAAI;YACF,MAAM,IAAA,iCAAe,EAAC,IAAI,CAAC,CAAC;SAC7B;QAAC,OAAO,GAAG,EAAE;YACZ,IAAA,gBAAQ,EAAC,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"]}
|
|
@@ -1,15 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __rest = (this && this.__rest) || function (s, e) {
|
|
3
|
-
var t = {};
|
|
4
|
-
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
5
|
-
t[p] = s[p];
|
|
6
|
-
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
7
|
-
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
8
|
-
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
9
|
-
t[p[i]] = s[p[i]];
|
|
10
|
-
}
|
|
11
|
-
return t;
|
|
12
|
-
};
|
|
13
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
3
|
exports.getWritableManifest = exports.manifestHandler = void 0;
|
|
15
4
|
const fs_1 = require("fs");
|
|
@@ -33,12 +22,12 @@ const ManifestSortOrder = {
|
|
|
33
22
|
* @param argv - The Yargs `argv` object.
|
|
34
23
|
*/
|
|
35
24
|
async function manifestHandler({ writeManifest, }) {
|
|
36
|
-
var _a, _b, _c;
|
|
37
25
|
let didUpdate = false;
|
|
38
26
|
let hasWarnings = false;
|
|
39
27
|
const unvalidatedManifest = await readSnapJsonFile(utils_1.NpmSnapFileNames.Manifest);
|
|
40
28
|
const iconPath = unvalidatedManifest && typeof unvalidatedManifest === 'object'
|
|
41
|
-
?
|
|
29
|
+
? unvalidatedManifest.source?.location?.npm
|
|
30
|
+
?.iconPath
|
|
42
31
|
: undefined;
|
|
43
32
|
const snapFiles = {
|
|
44
33
|
manifest: unvalidatedManifest,
|
|
@@ -61,7 +50,7 @@ async function manifestHandler({ writeManifest, }) {
|
|
|
61
50
|
for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {
|
|
62
51
|
manifest = fixManifest(partiallyValidatedFiles, error);
|
|
63
52
|
try {
|
|
64
|
-
(0, utils_1.validateNpmSnapManifest)(
|
|
53
|
+
(0, utils_1.validateNpmSnapManifest)({ ...partiallyValidatedFiles, manifest }, errorPrefix);
|
|
65
54
|
isInvalid = false;
|
|
66
55
|
}
|
|
67
56
|
catch (nextValidationError) {
|
|
@@ -142,10 +131,10 @@ async function readSnapJsonFile(snapJsonFileName) {
|
|
|
142
131
|
* @returns The contents of the bundle file, if any.
|
|
143
132
|
*/
|
|
144
133
|
async function getSnapSourceCode(manifest) {
|
|
145
|
-
var _a, _b, _c;
|
|
146
134
|
if (manifest && typeof manifest === 'object' && !Array.isArray(manifest)) {
|
|
147
135
|
/* istanbul ignore next: optional chaining */
|
|
148
|
-
const sourceFilePath =
|
|
136
|
+
const sourceFilePath = manifest.source?.location
|
|
137
|
+
?.npm?.filePath;
|
|
149
138
|
try {
|
|
150
139
|
return sourceFilePath
|
|
151
140
|
? await fs_1.promises.readFile(sourceFilePath, 'utf8')
|
|
@@ -200,8 +189,8 @@ function fixManifest(snapFiles, error) {
|
|
|
200
189
|
* @returns The disk-ready manifest.
|
|
201
190
|
*/
|
|
202
191
|
function getWritableManifest(manifest) {
|
|
203
|
-
const { repository
|
|
204
|
-
return Object.keys(repository ?
|
|
192
|
+
const { repository, ...remaining } = manifest;
|
|
193
|
+
return Object.keys(repository ? { ...remaining, repository } : remaining)
|
|
205
194
|
.sort((a, b) => ManifestSortOrder[a] - ManifestSortOrder[b])
|
|
206
195
|
.reduce((outManifest, key) => {
|
|
207
196
|
outManifest[key] = manifest[key];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifestHandler.js","sourceRoot":"","sources":["../../../src/cmds/manifest/manifestHandler.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,2BAAoC;AAEpC,uEASqD;AACrD,uCAAsD;AAGtD,MAAM,WAAW,GAAG,kBAAkB,CAAC;AAEvC,MAAM,iBAAiB,GAAuC;IAC5D,OAAO,EAAE,CAAC;IACV,YAAY,EAAE,CAAC;IACf,WAAW,EAAE,CAAC;IACd,UAAU,EAAE,CAAC;IACb,MAAM,EAAE,CAAC;IACT,kBAAkB,EAAE,CAAC;IACrB,eAAe,EAAE,CAAC;CACnB,CAAC;AAEF;;;;;;GAMG;AACI,KAAK,UAAU,eAAe,CAAC,EACpC,aAAa,GACH;;IACV,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,WAAW,GAAG,KAAK,CAAC;IAExB,MAAM,mBAAmB,GAAG,MAAM,gBAAgB,CAAC,wBAAgB,CAAC,QAAQ,CAAC,CAAC;IAE9E,MAAM,QAAQ,GACZ,mBAAmB,IAAI,OAAO,mBAAmB,KAAK,QAAQ;QAC5D,CAAC,CAAC,MAAA,MAAA,MAAC,mBAA6C,CAAC,MAAM,0CAAE,QAAQ,0CAAE,GAAG,0CAChE,QAAQ;QACd,CAAC,CAAC,SAAS,CAAC;IAEhB,MAAM,SAAS,GAAyB;QACtC,QAAQ,EAAE,mBAAmB;QAC7B,WAAW,EAAE,MAAM,gBAAgB,CAAC,wBAAgB,CAAC,WAAW,CAAC;QACjE,UAAU,EAAE,MAAM,iBAAiB,CAAC,mBAAmB,CAAC;QACxD,OAAO,EAAE,QAAQ,IAAI,CAAC,MAAM,aAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;KAC3D,CAAC;IAEF,IAAI,QAAkC,CA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AC,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC;YAC3C,MAAM;QAER,KAAK,mCAA2B,CAAC,kBAAkB;YACjD,YAAY,CAAC,UAAU,GAAG,WAAW,CAAC,UAAU;gBAC9C,CAAC,CAAC,IAAA,iBAAS,EAAC,WAAW,CAAC,UAAU,CAAC;gBACnC,CAAC,CAAC,IAAI,CAAC;YACT,MAAM;QAER,KAAK,mCAA2B,CAAC,cAAc;YAC7C,YAAY,CAAC,MAAM,CAAC,MAAM,GAAG,IAAA,2BAAmB,EAAC,UAAU,CAAC,CAAC;YAC7D,MAAM;QAER,0BAA0B;QAC1B;YACE,gDAAgD;YAChD,MAAM,aAAa,GAAU,KAAK,CAAC,MAAM,CAAC;YAC1C,MAAM,IAAI,KAAK,CACb,4CAA4C,aAAa,GAAG,CAC7D,CAAC;KACL;IAED,OAAO,YAAY,CAAC;AACtB,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,mBAAmB,CAAC,QAAsB;IACxD,MAAM,EAAE,UAAU,KAAmB,QAAQ,EAAtB,SAAS,UAAK,QAAQ,EAAvC,cAA4B,CAAW,CAAC;IAC9C,OACE,MAAM,CAAC,IAAI,CACT,UAAU,CAAC,CAAC,iCAAM,SAAS,KAAE,UAAU,IAAG,CAAC,CAAC,SAAS,CAExD;SACE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,iBAAiB,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC;SAC3D,MAAM,CAAC,CAAC,WAAW,EAAE,GAAG,EAAE,EAAE;QAC1B,WAAmB,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC1C,OAAO,WAAW,CAAC;IACrB,CAAC,EAAE,EAAkB,CAAC,CAAC;AAC3B,CAAC;AAZD,kDAYC","sourcesContent":["import { promises as fs } from 'fs';\nimport type { Json, SnapManifest } from '@metamask/snap-controllers';\nimport {\n NpmSnapFileNames,\n UnvalidatedSnapFiles,\n validateNpmSnap,\n validateNpmSnapManifest,\n getSnapSourceShasum,\n ProgrammaticallyFixableSnapError,\n SnapValidationFailureReason,\n SnapFiles,\n} from '@metamask/snap-controllers/dist/snaps/utils';\nimport { deepClone, readJsonFile } from '../../utils';\nimport { YargsArgs } from '../../types/yargs';\n\nconst errorPrefix = 'Manifest Error: ';\n\nconst ManifestSortOrder: Record<keyof SnapManifest, number> = {\n version: 1,\n proposedName: 2,\n description: 2,\n repository: 3,\n source: 4,\n initialPermissions: 5,\n manifestVersion: 6,\n};\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param argv - The Yargs `argv` object.\n */\nexport async function manifestHandler({\n writeManifest,\n}: YargsArgs): Promise<void> {\n let didUpdate = false;\n let hasWarnings = false;\n\n const unvalidatedManifest = await readSnapJsonFile(NpmSnapFileNames.Manifest);\n\n const iconPath =\n unvalidatedManifest && typeof unvalidatedManifest === 'object'\n ? (unvalidatedManifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath\n : undefined;\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: unvalidatedManifest,\n packageJson: await readSnapJsonFile(NpmSnapFileNames.PackageJson),\n sourceCode: await getSnapSourceCode(unvalidatedManifest),\n svgIcon: iconPath && (await fs.readFile(iconPath, 'utf8')),\n };\n\n let manifest: SnapManifest | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles, errorPrefix));\n } catch (error) {\n if (writeManifest && error instanceof ProgrammaticallyFixableSnapError) {\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the SnapValidationFailureReason enum, so we only\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(partiallyValidatedFiles, error);\n\n try {\n validateNpmSnapManifest(\n { ...partiallyValidatedFiles, manifest },\n errorPrefix,\n );\n\n isInvalid = false;\n } catch (nextValidationError) {\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal Error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n }\n }\n\n didUpdate = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript doesn't see that the 'manifest' variable must be of type\n // SnapManifest at this point, so we cast it.\n const validatedManifest = manifest as SnapManifest;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n logManifestWarning(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n // Validation complete, finish work and notify user.\n\n if (writeManifest) {\n try {\n await fs.writeFile(\n NpmSnapFileNames.Manifest,\n `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\\n`,\n );\n\n if (didUpdate) {\n console.log(`Manifest: Updated snap.manifest.json`);\n }\n } catch (error) {\n throw new Error(\n `${errorPrefix}Failed to update snap.manifest.json: ${error.message}`,\n );\n }\n }\n\n if (hasWarnings) {\n console.log(\n `Manifest Warning: Validation of snap.manifest.json completed with warnings. See above.`,\n );\n } else {\n console.log(`Manifest Success: Validated snap.manifest.json!`);\n }\n\n function logManifestWarning(message: string) {\n if (!global.snaps.suppressWarnings) {\n hasWarnings = true;\n console.warn(`Manifest Warning: ${message}`);\n }\n }\n}\n\n/**\n * Utility function for reading `package.json` or the Snap manifest file.\n * These are assumed to be in the current working directory.\n *\n * @param snapJsonFileName - The name of the file to read.\n * @returns The parsed JSON file.\n */\nasync function readSnapJsonFile(\n snapJsonFileName: NpmSnapFileNames,\n): Promise<Json> {\n try {\n return await readJsonFile(snapJsonFileName);\n } catch (error) {\n if (error.code === 'ENOENT') {\n throw new Error(\n `${errorPrefix}Could not find '${snapJsonFileName}'. Please ensure that ` +\n `you are running the command in the project root directory.`,\n );\n }\n throw new Error(`${errorPrefix}${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the bundle file, if any.\n */\nasync function getSnapSourceCode(manifest: Json): Promise<string | undefined> {\n if (manifest && typeof manifest === 'object' && !Array.isArray(manifest)) {\n /* istanbul ignore next: optional chaining */\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n try {\n return sourceFilePath\n ? await fs.readFile(sourceFilePath, 'utf8')\n : undefined;\n } catch (error) {\n throw new Error(\n `Manifest Error: Failed to read Snap bundle file: ${error.message}`,\n );\n }\n }\n return undefined;\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nfunction fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): SnapManifest {\n const { manifest, packageJson, sourceCode } = snapFiles;\n const manifestCopy = deepClone(manifest);\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.repository\n ? deepClone(packageJson.repository)\n : null;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapSourceShasum(sourceCode);\n break;\n\n /* istanbul ignore next */\n default:\n // eslint-disable-next-line no-case-declarations\n const failureReason: never = error.reason;\n throw new Error(\n `Unrecognized validation failure reason: '${failureReason}'`,\n );\n }\n\n return manifestCopy;\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n return (\n Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[]\n )\n .sort((a, b) => ManifestSortOrder[a] - ManifestSortOrder[b])\n .reduce((outManifest, key) => {\n (outManifest as any)[key] = manifest[key];\n return outManifest;\n }, {} as SnapManifest);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"manifestHandler.js","sourceRoot":"","sources":["../../../src/cmds/manifest/manifestHandler.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AAEpC,uEASqD;AACrD,uCAAsD;AAGtD,MAAM,WAAW,GAAG,kBAAkB,CAAC;AAEvC,MAAM,iBAAiB,GAAuC;IAC5D,OAAO,EAAE,CAAC;IACV,YAAY,EAAE,CAAC;IACf,WAAW,EAAE,CAAC;IACd,UAAU,EAAE,CAAC;IACb,MAAM,EAAE,CAAC;IACT,kBAAkB,EAAE,CAAC;IACrB,eAAe,EAAE,CAAC;CACnB,CAAC;AAEF;;;;;;GAMG;AACI,KAAK,UAAU,eAAe,CAAC,EACpC,aAAa,GACH;IACV,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,WAAW,GAAG,KAAK,CAAC;IAExB,MAAM,mBAAmB,GAAG,MAAM,gBAAgB,CAAC,wBAAgB,CAAC,QAAQ,CAAC,CAAC;IAE9E,MAAM,QAAQ,GACZ,mBAAmB,IAAI,OAAO,mBAAmB,KAAK,QAAQ;QAC5D,CAAC,CAAE,mBAA6C,CAAC,MAAM,EAAE,QAAQ,EAAE,GAAG;YAClE,EA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G,iBAAiB,CAAC,CAAC,CAAC,CAAC;SAC3D,MAAM,CAAC,CAAC,WAAW,EAAE,GAAG,EAAE,EAAE;QAC1B,WAAmB,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC1C,OAAO,WAAW,CAAC;IACrB,CAAC,EAAE,EAAkB,CAAC,CAAC;AAC3B,CAAC;AAZD,kDAYC","sourcesContent":["import { promises as fs } from 'fs';\nimport type { Json, SnapManifest } from '@metamask/snap-controllers';\nimport {\n NpmSnapFileNames,\n UnvalidatedSnapFiles,\n validateNpmSnap,\n validateNpmSnapManifest,\n getSnapSourceShasum,\n ProgrammaticallyFixableSnapError,\n SnapValidationFailureReason,\n SnapFiles,\n} from '@metamask/snap-controllers/dist/snaps/utils';\nimport { deepClone, readJsonFile } from '../../utils';\nimport { YargsArgs } from '../../types/yargs';\n\nconst errorPrefix = 'Manifest Error: ';\n\nconst ManifestSortOrder: Record<keyof SnapManifest, number> = {\n version: 1,\n proposedName: 2,\n description: 2,\n repository: 3,\n source: 4,\n initialPermissions: 5,\n manifestVersion: 6,\n};\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param argv - The Yargs `argv` object.\n */\nexport async function manifestHandler({\n writeManifest,\n}: YargsArgs): Promise<void> {\n let didUpdate = false;\n let hasWarnings = false;\n\n const unvalidatedManifest = await readSnapJsonFile(NpmSnapFileNames.Manifest);\n\n const iconPath =\n unvalidatedManifest && typeof unvalidatedManifest === 'object'\n ? (unvalidatedManifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath\n : undefined;\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: unvalidatedManifest,\n packageJson: await readSnapJsonFile(NpmSnapFileNames.PackageJson),\n sourceCode: await getSnapSourceCode(unvalidatedManifest),\n svgIcon: iconPath && (await fs.readFile(iconPath, 'utf8')),\n };\n\n let manifest: SnapManifest | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles, errorPrefix));\n } catch (error) {\n if (writeManifest && error instanceof ProgrammaticallyFixableSnapError) {\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the SnapValidationFailureReason enum, so we only\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(partiallyValidatedFiles, error);\n\n try {\n validateNpmSnapManifest(\n { ...partiallyValidatedFiles, manifest },\n errorPrefix,\n );\n\n isInvalid = false;\n } catch (nextValidationError) {\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal Error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n }\n }\n\n didUpdate = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript doesn't see that the 'manifest' variable must be of type\n // SnapManifest at this point, so we cast it.\n const validatedManifest = manifest as SnapManifest;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n logManifestWarning(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n // Validation complete, finish work and notify user.\n\n if (writeManifest) {\n try {\n await fs.writeFile(\n NpmSnapFileNames.Manifest,\n `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\\n`,\n );\n\n if (didUpdate) {\n console.log(`Manifest: Updated snap.manifest.json`);\n }\n } catch (error) {\n throw new Error(\n `${errorPrefix}Failed to update snap.manifest.json: ${error.message}`,\n );\n }\n }\n\n if (hasWarnings) {\n console.log(\n `Manifest Warning: Validation of snap.manifest.json completed with warnings. See above.`,\n );\n } else {\n console.log(`Manifest Success: Validated snap.manifest.json!`);\n }\n\n function logManifestWarning(message: string) {\n if (!global.snaps.suppressWarnings) {\n hasWarnings = true;\n console.warn(`Manifest Warning: ${message}`);\n }\n }\n}\n\n/**\n * Utility function for reading `package.json` or the Snap manifest file.\n * These are assumed to be in the current working directory.\n *\n * @param snapJsonFileName - The name of the file to read.\n * @returns The parsed JSON file.\n */\nasync function readSnapJsonFile(\n snapJsonFileName: NpmSnapFileNames,\n): Promise<Json> {\n try {\n return await readJsonFile(snapJsonFileName);\n } catch (error) {\n if (error.code === 'ENOENT') {\n throw new Error(\n `${errorPrefix}Could not find '${snapJsonFileName}'. Please ensure that ` +\n `you are running the command in the project root directory.`,\n );\n }\n throw new Error(`${errorPrefix}${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the bundle file, if any.\n */\nasync function getSnapSourceCode(manifest: Json): Promise<string | undefined> {\n if (manifest && typeof manifest === 'object' && !Array.isArray(manifest)) {\n /* istanbul ignore next: optional chaining */\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n try {\n return sourceFilePath\n ? await fs.readFile(sourceFilePath, 'utf8')\n : undefined;\n } catch (error) {\n throw new Error(\n `Manifest Error: Failed to read Snap bundle file: ${error.message}`,\n );\n }\n }\n return undefined;\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nfunction fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): SnapManifest {\n const { manifest, packageJson, sourceCode } = snapFiles;\n const manifestCopy = deepClone(manifest);\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.repository\n ? deepClone(packageJson.repository)\n : null;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapSourceShasum(sourceCode);\n break;\n\n /* istanbul ignore next */\n default:\n // eslint-disable-next-line no-case-declarations\n const failureReason: never = error.reason;\n throw new Error(\n `Unrecognized validation failure reason: '${failureReason}'`,\n );\n }\n\n return manifestCopy;\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n return (\n Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[]\n )\n .sort((a, b) => ManifestSortOrder[a] - ManifestSortOrder[b])\n .reduce((outManifest, key) => {\n (outManifest as any)[key] = manifest[key];\n return outManifest;\n }, {} as SnapManifest);\n}\n"]}
|
|
@@ -40,7 +40,7 @@ async function watch(argv) {
|
|
|
40
40
|
await (0, manifestHandler_1.manifestHandler)(argv);
|
|
41
41
|
}
|
|
42
42
|
if (shouldEval) {
|
|
43
|
-
await (0, evalHandler_1.snapEval)(
|
|
43
|
+
await (0, evalHandler_1.snapEval)({ ...argv, bundle: outfilePath });
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
46
|
catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"watchHandler.js","sourceRoot":"","sources":["../../../src/cmds/watch/watchHandler.ts"],"names":[],"mappings":";;;;;;AAAA,wDAAgC;AAEhC,uCAOq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,EACN,SACE,IAAI,KAAK,SAAS;gBAChB,CAAC,CAAC,sBAAsB;gBACxB,CAAC,CAAC,qBAAqB,IAAI,GAC/B,GAAG,EACH,KAAK,CACN,CAAC;SACH;IACH,CAAC,CAAC;IAEF,kBAAQ;SACL,KAAK,CAAC,OAAO,EAAE;QACd,aAAa,EAAE,IAAI;QACnB,OAAO,EAAE;YACP,oBAAoB;YACpB,MAAM,IAAI,KAAK;YACf,YAAY;YACZ,aAAa;YACb,cAAc;YACd,cAAc;YACd,0BAA0B;YAC1B,CAAC,GAAW,EAAE,EAAE,CAAC,GAAG,KAAK,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC;SACpD;KACF,CAAC;SAED,EAAE,CAAC,OAAO,EAAE,SAAS,CAAC;SACtB,EAAE,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,eAAe,IAAI,EAAE,CAAC,CAAC;SAC3D,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,iBAAiB,IAAI,EAAE,CAAC,CAAC;SAChE,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,IAAI,EAAE,CAAC,CAAC;SAC5D,EAAE,CAAC,OAAO,EAAE,CAAC,KAAY,EAAE,EAAE;QAC5B,IAAA,gBAAQ,EAAC,kBAAkB,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC;IACrD,CAAC,CAAC;SAED,GAAG,CAAC,OAAO,CAAC,CAAC;IAEhB,OAAO,CAAC,GAAG,CAAC,aAAa,OAAO,kBAAkB,CAAC,CAAC;AACtD,CAAC;AAhED,sBAgEC","sourcesContent":["import chokidar from 'chokidar';\nimport { YargsArgs } from '../../types/yargs';\nimport {\n getOutfilePath,\n loadConfig,\n logError,\n validateDirPath,\n validateFilePath,\n validateOutfileName,\n} from '../../utils';\nimport { bundle } from '../build/bundle';\nimport { snapEval } from '../eval/evalHandler';\nimport { manifestHandler } from '../manifest/manifestHandler';\n\n/**\n * Watch a directory and its subdirectories for changes, and build when files\n * are added or changed.\n *\n * Ignores 'node_modules' and dotfiles.\n * Creates destination directory if it doesn't exist.\n *\n * @param argv - arguments as an object generated by yargs\n * @param argv.src - The source file path\n * @param argv.dist - The output directory path\n * @param argv.'outfileName' - The output file name\n */\nexport async function watch(argv: YargsArgs): Promise<void> {\n const { dist, eval: shouldEval, manifest, outfileName, src } = argv;\n if (outfileName) {\n validateOutfileName(outfileName as string);\n }\n await validateFilePath(src);\n await validateDirPath(dist, true);\n const rootDir =\n src.indexOf('/') === -1 ? '.' : src.substring(0, src.lastIndexOf('/') + 1);\n const outfilePath = getOutfilePath(dist, outfileName as string);\n\n const buildSnap = async (path?: string, logMessage?: string) => {\n if (logMessage !== undefined) {\n console.log(logMessage);\n }\n\n try {\n await bundle(src, outfilePath, argv, loadConfig().bundlerCustomizer);\n\n if (manifest) {\n await manifestHandler(argv);\n }\n\n if (shouldEval) {\n await snapEval({ ...argv, bundle: outfilePath });\n }\n } catch (error) {\n logError(\n `Error ${\n path === undefined\n ? 'during initial build'\n : `while processing \"${path}\"`\n }.`,\n error,\n );\n }\n };\n\n chokidar\n .watch(rootDir, {\n ignoreInitial: true,\n ignored: [\n '**/node_modules/**',\n `**/${dist}/**`,\n `**/test/**`,\n `**/tests/**`,\n `**/*.test.js`,\n `**/*.test.ts`,\n /* istanbul ignore next */\n (str: string) => str !== '.' && str.startsWith('.'),\n ],\n })\n\n .on('ready', buildSnap)\n .on('add', (path) => buildSnap(path, `File added: ${path}`))\n .on('change', (path) => buildSnap(path, `File changed: ${path}`))\n .on('unlink', (path) => console.log(`File removed: ${path}`))\n .on('error', (error: Error) => {\n logError(`Watcher error: ${error.message}`, error);\n })\n\n .add(rootDir);\n\n console.log(`Watching '${rootDir}' for changes...`);\n}\n"]}
|
package/dist/utils/readline.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ declare type PromptArgs = {
|
|
|
6
6
|
shouldClose?: boolean;
|
|
7
7
|
readlineInterface?: readline.Interface;
|
|
8
8
|
};
|
|
9
|
+
export declare function openPrompt(): void;
|
|
9
10
|
export declare function prompt({ question, defaultValue, shouldClose, readlineInterface, }: PromptArgs): Promise<string>;
|
|
10
11
|
export declare function closePrompt(readlineInterface?: readline.Interface): void;
|
|
11
12
|
export {};
|
package/dist/utils/readline.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.closePrompt = exports.prompt = void 0;
|
|
6
|
+
exports.closePrompt = exports.prompt = exports.openPrompt = void 0;
|
|
7
7
|
const readline_1 = __importDefault(require("readline"));
|
|
8
8
|
let singletonReadlineInterface;
|
|
9
9
|
function openPrompt() {
|
|
@@ -12,6 +12,7 @@ function openPrompt() {
|
|
|
12
12
|
output: process.stdout,
|
|
13
13
|
});
|
|
14
14
|
}
|
|
15
|
+
exports.openPrompt = openPrompt;
|
|
15
16
|
function prompt({ question, defaultValue, shouldClose, readlineInterface = singletonReadlineInterface, }) {
|
|
16
17
|
let _readlineInterface = readlineInterface;
|
|
17
18
|
if (!_readlineInterface) {
|
|
@@ -41,6 +42,9 @@ function closePrompt(readlineInterface = singletonReadlineInterface) {
|
|
|
41
42
|
if (readlineInterface) {
|
|
42
43
|
readlineInterface.close();
|
|
43
44
|
}
|
|
45
|
+
else {
|
|
46
|
+
throw new Error('You are attempting to close a non existent prompt.');
|
|
47
|
+
}
|
|
44
48
|
}
|
|
45
49
|
exports.closePrompt = closePrompt;
|
|
46
50
|
//# sourceMappingURL=readline.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readline.js","sourceRoot":"","sources":["../../src/utils/readline.ts"],"names":[],"mappings":";;;;;;AAAA,wDAAgC;AAEhC,IAAI,0BAA8C,CAAC;AASnD,
|
|
1
|
+
{"version":3,"file":"readline.js","sourceRoot":"","sources":["../../src/utils/readline.ts"],"names":[],"mappings":";;;;;;AAAA,wDAAgC;AAEhC,IAAI,0BAA8C,CAAC;AASnD,SAAgB,UAAU;IACxB,0BAA0B,GAAG,kBAAQ,CAAC,eAAe,CAAC;QACpD,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,MAAM,EAAE,OAAO,CAAC,MAAM;KACvB,CAAC,CAAC;AACL,CAAC;AALD,gCAKC;AAED,SAAgB,MAAM,CAAC,EACrB,QAAQ,EACR,YAAY,EACZ,WAAW,EACX,iBAAiB,GAAG,0BAA0B,GACnC;IACX,IAAI,kBAAkB,GAAG,iBAAiB,CAAC;IAC3C,IAAI,CAAC,kBAAkB,EAAE;QACvB,UAAU,EAAE,CAAC;QACb,kBAAkB,GAAG,0BAA0B,CAAC;KACjD;IAED,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE;QACtC,IAAI,WAAW,GAAG,GAAG,QAAQ,GAAG,CAAC;QACjC,IAAI,YAAY,EAAE;YAChB,WAAW,IAAI,IAAI,YAAY,IAAI,CAAC;SACrC;QAED,kBAAkB,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,MAAc,EAAE,EAAE;YAC1D,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE;gBAC7B,IAAI,YAAY,KAAK,SAAS,EAAE;oBAC9B,OAAO,CAAC,YAAY,CAAC,CAAC;iBACvB;aACF;YACD,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;YACvB,IAAI,WAAW,EAAE;gBACf,kBAAkB,CAAC,KAAK,EAAE,CAAC;aAC5B;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AA9BD,wBA8BC;AAED,SAAgB,WAAW,CACzB,iBAAiB,GAAG,0BAA0B;IAE9C,IAAI,iBAAiB,EAAE;QACrB,iBAAiB,CAAC,KAAK,EAAE,CAAC;KAC3B;SAAM;QACL,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;KACvE;AACH,CAAC;AARD,kCAQC","sourcesContent":["import readline from 'readline';\n\nlet singletonReadlineInterface: readline.Interface;\n\ntype PromptArgs = {\n question: string;\n defaultValue?: string;\n shouldClose?: boolean;\n readlineInterface?: readline.Interface;\n};\n\nexport function openPrompt(): void {\n singletonReadlineInterface = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n}\n\nexport function prompt({\n question,\n defaultValue,\n shouldClose,\n readlineInterface = singletonReadlineInterface,\n}: PromptArgs): Promise<string> {\n let _readlineInterface = readlineInterface;\n if (!_readlineInterface) {\n openPrompt();\n _readlineInterface = singletonReadlineInterface;\n }\n\n return new Promise((resolve, _reject) => {\n let queryString = `${question} `;\n if (defaultValue) {\n queryString += `(${defaultValue}) `;\n }\n\n _readlineInterface.question(queryString, (answer: string) => {\n if (!answer || !answer.trim()) {\n if (defaultValue !== undefined) {\n resolve(defaultValue);\n }\n }\n resolve(answer.trim());\n if (shouldClose) {\n _readlineInterface.close();\n }\n });\n });\n}\n\nexport function closePrompt(\n readlineInterface = singletonReadlineInterface,\n): void {\n if (readlineInterface) {\n readlineInterface.close();\n } else {\n throw new Error('You are attempting to close a non existent prompt.');\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "A CLI for developing MetaMask Snaps.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"build:post-tsc": "yarn build:chmod && yarn build:readme",
|
|
27
27
|
"build:clean": "yarn clean && yarn build",
|
|
28
28
|
"build:watch": "tsc-watch --onSuccess 'yarn build:chmod'",
|
|
29
|
-
"clean": "rimraf dist/* src/**/*__GENERATED__*",
|
|
29
|
+
"clean": "rimraf *.tsbuildinfo dist/* src/**/*__GENERATED__*",
|
|
30
30
|
"test": "yarn build:init-template && jest",
|
|
31
31
|
"posttest": "jest-it-up",
|
|
32
32
|
"test:watch": "yarn test --watch",
|
|
@@ -47,7 +47,8 @@
|
|
|
47
47
|
"@babel/plugin-transform-runtime": "^7.16.7",
|
|
48
48
|
"@babel/preset-env": "^7.16.7",
|
|
49
49
|
"@chainsafe/strip-comments": "^1.0.5",
|
|
50
|
-
"@metamask/snap-controllers": "^0.
|
|
50
|
+
"@metamask/snap-controllers": "^0.14.0",
|
|
51
|
+
"@metamask/snaps-browserify-plugin": "^0.14.0",
|
|
51
52
|
"babelify": "^10.0.0",
|
|
52
53
|
"browserify": "^17.0.0",
|
|
53
54
|
"chokidar": "^3.0.2",
|