@metamask/snaps-cli 0.15.0 → 0.18.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/README.md +4 -2
- package/dist/builders.d.ts +6 -0
- package/dist/builders.js +20 -1
- package/dist/builders.js.map +1 -1
- package/dist/cli.d.ts +7 -0
- package/dist/cli.js +8 -0
- package/dist/cli.js.map +1 -1
- package/dist/cmds/build/buildHandler.d.ts +4 -4
- package/dist/cmds/build/buildHandler.js +5 -5
- package/dist/cmds/build/buildHandler.js.map +1 -1
- package/dist/cmds/build/bundle.d.ts +4 -2
- package/dist/cmds/build/bundle.js +15 -14
- package/dist/cmds/build/bundle.js.map +1 -1
- package/dist/cmds/build/utils.d.ts +21 -8
- package/dist/cmds/build/utils.js +22 -9
- package/dist/cmds/build/utils.js.map +1 -1
- package/dist/cmds/eval/eval-worker.js +17 -14
- package/dist/cmds/eval/eval-worker.js.map +1 -1
- package/dist/cmds/eval/evalHandler.d.ts +7 -0
- package/dist/cmds/eval/evalHandler.js +7 -0
- package/dist/cmds/eval/evalHandler.js.map +1 -1
- package/dist/cmds/eval/mock.d.ts +11 -0
- package/dist/cmds/eval/mock.js +39 -4
- package/dist/cmds/eval/mock.js.map +1 -1
- package/dist/cmds/eval/workerEval.d.ts +7 -0
- package/dist/cmds/eval/workerEval.js +11 -6
- package/dist/cmds/eval/workerEval.js.map +1 -1
- package/dist/cmds/init/index.js +14 -6
- package/dist/cmds/init/index.js.map +1 -1
- package/dist/cmds/init/init-template.json +5 -1
- package/dist/cmds/init/initHandler.d.ts +11 -0
- package/dist/cmds/init/initHandler.js +39 -4
- package/dist/cmds/init/initHandler.js.map +1 -1
- package/dist/cmds/init/initUtils.d.ts +21 -4
- package/dist/cmds/init/initUtils.js +55 -7
- 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.d.ts +1 -0
- package/dist/cmds/manifest/manifestHandler.js +24 -7
- package/dist/cmds/manifest/manifestHandler.js.map +1 -1
- package/dist/cmds/serve/index.js +2 -44
- package/dist/cmds/serve/index.js.map +1 -1
- package/dist/cmds/serve/serveHandler.d.ts +10 -0
- package/dist/cmds/serve/serveHandler.js +51 -0
- package/dist/cmds/serve/serveHandler.js.map +1 -0
- package/dist/cmds/serve/serveUtils.d.ts +17 -0
- package/dist/cmds/serve/serveUtils.js +17 -0
- package/dist/cmds/serve/serveUtils.js.map +1 -1
- package/dist/cmds/watch/index.js +3 -0
- package/dist/cmds/watch/index.js.map +1 -1
- package/dist/cmds/watch/watchHandler.d.ts +4 -4
- package/dist/cmds/watch/watchHandler.js +13 -7
- package/dist/cmds/watch/watchHandler.js.map +1 -1
- package/dist/utils/fs.d.ts +5 -5
- package/dist/utils/fs.js +5 -5
- package/dist/utils/fs.js.map +1 -1
- package/dist/utils/misc.d.ts +16 -13
- package/dist/utils/misc.js +16 -13
- package/dist/utils/misc.js.map +1 -1
- package/dist/utils/readline.d.ts +25 -0
- package/dist/utils/readline.js +25 -0
- package/dist/utils/readline.js.map +1 -1
- package/dist/utils/snap-config.d.ts +15 -0
- package/dist/utils/snap-config.js +15 -1
- package/dist/utils/snap-config.js.map +1 -1
- package/dist/utils/validate-fs.d.ts +19 -18
- package/dist/utils/validate-fs.js +21 -20
- package/dist/utils/validate-fs.js.map +1 -1
- package/package.json +16 -15
- package/CHANGELOG.md +0 -217
package/dist/cmds/eval/mock.js
CHANGED
|
@@ -9,14 +9,29 @@ const crypto_1 = __importDefault(require("crypto"));
|
|
|
9
9
|
const snap_controllers_1 = require("@metamask/snap-controllers");
|
|
10
10
|
const NETWORK_APIS = ['fetch', 'WebSocket'];
|
|
11
11
|
exports.ALL_APIS = [...snap_controllers_1.DEFAULT_ENDOWMENTS, ...NETWORK_APIS];
|
|
12
|
+
/**
|
|
13
|
+
* Get a mock snap provider, that always returns `true` for requests.
|
|
14
|
+
*
|
|
15
|
+
* @returns A mocked snap provider.
|
|
16
|
+
*/
|
|
12
17
|
function getMockSnapProvider() {
|
|
13
18
|
const mockProvider = new events_1.default();
|
|
14
|
-
mockProvider.registerRpcMessageHandler = () => true;
|
|
15
19
|
mockProvider.request = async () => true;
|
|
16
20
|
return mockProvider;
|
|
17
21
|
}
|
|
18
|
-
|
|
22
|
+
/**
|
|
23
|
+
* Check if a value is a constructor.
|
|
24
|
+
*
|
|
25
|
+
* @param value - The value to check.
|
|
26
|
+
* @returns `true` if the value is a constructor, or `false` otherwise.
|
|
27
|
+
*/
|
|
28
|
+
const isConstructor = (value) => { var _a, _b; return Boolean(typeof ((_b = (_a = value === null || value === void 0 ? void 0 : value.prototype) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) === 'string'); };
|
|
19
29
|
exports.isConstructor = isConstructor;
|
|
30
|
+
/**
|
|
31
|
+
* A function that always returns `true`.
|
|
32
|
+
*
|
|
33
|
+
* @returns `true`.
|
|
34
|
+
*/
|
|
20
35
|
const mockFunction = () => true;
|
|
21
36
|
class MockClass {
|
|
22
37
|
}
|
|
@@ -28,6 +43,13 @@ const handler = {
|
|
|
28
43
|
return mockFunction;
|
|
29
44
|
},
|
|
30
45
|
};
|
|
46
|
+
/**
|
|
47
|
+
* Generate a mock class for a given value. The value is wrapped in a Proxy, and
|
|
48
|
+
* all methods are replaced with a mock function.
|
|
49
|
+
*
|
|
50
|
+
* @param value - The value to mock.
|
|
51
|
+
* @returns A mock class.
|
|
52
|
+
*/
|
|
31
53
|
const generateMockClass = (value) => {
|
|
32
54
|
return new Proxy(value, handler);
|
|
33
55
|
};
|
|
@@ -37,6 +59,14 @@ const mockWindow = {
|
|
|
37
59
|
crypto: crypto_1.default,
|
|
38
60
|
SubtleCrypto: MockClass,
|
|
39
61
|
};
|
|
62
|
+
/**
|
|
63
|
+
* Generate a mock endowment for a certain class or function on the `globalThis`
|
|
64
|
+
* object.
|
|
65
|
+
*
|
|
66
|
+
* @param key - The key to generate the mock endowment for.
|
|
67
|
+
* @returns A mocked class or function. If the key is part of the default
|
|
68
|
+
* endowments, the original value is returned.
|
|
69
|
+
*/
|
|
40
70
|
const generateMockEndowment = (key) => {
|
|
41
71
|
const globalValue = globalThis[key];
|
|
42
72
|
// Default exposed APIs don't need to be mocked
|
|
@@ -44,7 +74,7 @@ const generateMockEndowment = (key) => {
|
|
|
44
74
|
return globalValue;
|
|
45
75
|
}
|
|
46
76
|
// Fall back to mockWindow for certain APIs not exposed in global in Node.JS
|
|
47
|
-
const globalOrMocked = globalValue
|
|
77
|
+
const globalOrMocked = globalValue !== null && globalValue !== void 0 ? globalValue : mockWindow[key];
|
|
48
78
|
const type = typeof globalOrMocked;
|
|
49
79
|
const isFunction = type === 'function';
|
|
50
80
|
if (isFunction && (0, exports.isConstructor)(globalOrMocked)) {
|
|
@@ -56,8 +86,13 @@ const generateMockEndowment = (key) => {
|
|
|
56
86
|
}
|
|
57
87
|
return globalOrMocked;
|
|
58
88
|
};
|
|
89
|
+
/**
|
|
90
|
+
* Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.
|
|
91
|
+
*
|
|
92
|
+
* @returns A map of endowments.
|
|
93
|
+
*/
|
|
59
94
|
const generateMockEndowments = () => {
|
|
60
|
-
return exports.ALL_APIS.reduce((acc, cur) => ({
|
|
95
|
+
return exports.ALL_APIS.reduce((acc, cur) => (Object.assign(Object.assign({}, acc), { [cur]: generateMockEndowment(cur) })), { wallet: getMockSnapProvider() });
|
|
61
96
|
};
|
|
62
97
|
exports.generateMockEndowments = generateMockEndowments;
|
|
63
98
|
//# 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,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-controllers';\n\nconst NETWORK_APIS = ['fetch', 'WebSocket'];\n\nexport const ALL_APIS: string[] = [...DEFAULT_ENDOWMENTS, ...NETWORK_APIS];\n\ntype MockSnapProvider = EventEmitter & {\n request: () => Promise<any>;\n};\n\n/**\n * Get a mock snap provider, that always returns `true` for requests.\n *\n * @returns A mocked snap provider.\n */\nfunction getMockSnapProvider(): MockSnapProvider {\n const mockProvider = new EventEmitter() as Partial<MockSnapProvider>;\n mockProvider.request = async () => true;\n return mockProvider as MockSnapProvider;\n}\n\n/**\n * Check if a value is a constructor.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nexport const isConstructor = (value: any) =>\n Boolean(typeof value?.prototype?.constructor?.name === 'string');\n\n/**\n * A function that always returns `true`.\n *\n * @returns `true`.\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\n/**\n * Generate a mock class for a given value. The value is wrapped in a Proxy, and\n * all methods are replaced with a mock function.\n *\n * @param value - The value to mock.\n * @returns A mock class.\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\n/**\n * Generate a mock endowment for a certain class or function on the `globalThis`\n * object.\n *\n * @param key - The key to generate the mock endowment for.\n * @returns A mocked class or function. If the key is part of the default\n * endowments, the original value is returned.\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\n/**\n * Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.\n *\n * @returns A map of endowments.\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"]}
|
|
@@ -1 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spawn a new worker thread to run the provided bundle in.
|
|
3
|
+
*
|
|
4
|
+
* @param bundlePath - The path to the bundle to run.
|
|
5
|
+
* @returns `null` if the worker ran successfully.
|
|
6
|
+
* @throws If the worker failed to run successfully.
|
|
7
|
+
*/
|
|
1
8
|
export declare function workerEval(bundlePath: string): Promise<null>;
|
|
@@ -4,26 +4,31 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.workerEval = void 0;
|
|
7
|
-
const
|
|
7
|
+
const child_process_1 = require("child_process");
|
|
8
8
|
const path_1 = __importDefault(require("path"));
|
|
9
|
+
/**
|
|
10
|
+
* Spawn a new worker thread to run the provided bundle in.
|
|
11
|
+
*
|
|
12
|
+
* @param bundlePath - The path to the bundle to run.
|
|
13
|
+
* @returns `null` if the worker ran successfully.
|
|
14
|
+
* @throws If the worker failed to run successfully.
|
|
15
|
+
*/
|
|
9
16
|
function workerEval(bundlePath) {
|
|
10
17
|
return new Promise((resolve) => {
|
|
11
|
-
|
|
12
|
-
.on('exit', (exitCode) => {
|
|
18
|
+
(0, child_process_1.fork)(getEvalWorkerPath(), [bundlePath]).on('exit', (exitCode) => {
|
|
13
19
|
if (exitCode === 0) {
|
|
14
20
|
resolve(null);
|
|
15
21
|
}
|
|
16
22
|
else {
|
|
17
23
|
throw new Error(`Worker exited abnormally! Code: ${exitCode}`);
|
|
18
24
|
}
|
|
19
|
-
})
|
|
20
|
-
.postMessage({
|
|
21
|
-
snapFilePath: bundlePath,
|
|
22
25
|
});
|
|
23
26
|
});
|
|
24
27
|
}
|
|
25
28
|
exports.workerEval = workerEval;
|
|
26
29
|
/**
|
|
30
|
+
* Get the path to the eval worker file.
|
|
31
|
+
*
|
|
27
32
|
* @returns The path to the eval worker file.
|
|
28
33
|
*/
|
|
29
34
|
function getEvalWorkerPath() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workerEval.js","sourceRoot":"","sources":["../../../src/cmds/eval/workerEval.ts"],"names":[],"mappings":";;;;;;AAAA,
|
|
1
|
+
{"version":3,"file":"workerEval.js","sourceRoot":"","sources":["../../../src/cmds/eval/workerEval.ts"],"names":[],"mappings":";;;;;;AAAA,iDAAqC;AACrC,gDAA6B;AAE7B;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,UAAkB;IAC3C,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,IAAA,oBAAI,EAAC,iBAAiB,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,QAAgB,EAAE,EAAE;YACtE,IAAI,QAAQ,KAAK,CAAC,EAAE;gBAClB,OAAO,CAAC,IAAI,CAAC,CAAC;aACf;iBAAM;gBACL,MAAM,IAAI,KAAK,CAAC,mCAAmC,QAAQ,EAAE,CAAC,CAAC;aAChE;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAVD,gCAUC;AAED;;;;GAIG;AACH,SAAS,iBAAiB;IACxB,OAAO,cAAS,CAAC,IAAI,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import { fork } from 'child_process';\nimport pathUtils from 'path';\n\n/**\n * Spawn a new worker thread to run the provided bundle in.\n *\n * @param bundlePath - The path to the bundle to run.\n * @returns `null` if the worker ran successfully.\n * @throws If the worker failed to run successfully.\n */\nexport function workerEval(bundlePath: string): Promise<null> {\n return new Promise((resolve) => {\n fork(getEvalWorkerPath(), [bundlePath]).on('exit', (exitCode: number) => {\n if (exitCode === 0) {\n resolve(null);\n } else {\n throw new Error(`Worker exited abnormally! Code: ${exitCode}`);\n }\n });\n });\n}\n\n/**\n * Get the path to the eval worker file.\n *\n * @returns The path to the eval worker file.\n */\nfunction getEvalWorkerPath(): string {\n return pathUtils.join(__dirname, 'eval-worker.js');\n}\n"]}
|
package/dist/cmds/init/index.js
CHANGED
|
@@ -5,14 +5,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
const builders_1 = __importDefault(require("../../builders"));
|
|
6
6
|
const buildHandler_1 = require("../build/buildHandler");
|
|
7
7
|
const initHandler_1 = require("./initHandler");
|
|
8
|
+
const initUtils_1 = require("./initUtils");
|
|
9
|
+
/**
|
|
10
|
+
* The main entrypoint for the init command. This calls the init handler to
|
|
11
|
+
* initialize the snap package, builds the snap, and then updates the manifest
|
|
12
|
+
* with the shasum of the built snap.
|
|
13
|
+
*
|
|
14
|
+
* @param argv - The Yargs arguments object.
|
|
15
|
+
*/
|
|
8
16
|
async function init(argv) {
|
|
9
17
|
console.log();
|
|
10
18
|
const newArgs = await (0, initHandler_1.initHandler)(argv);
|
|
11
|
-
await (0, buildHandler_1.build)({
|
|
12
|
-
...newArgs,
|
|
13
|
-
manifest: false,
|
|
14
|
-
eval: true,
|
|
15
|
-
});
|
|
19
|
+
await (0, buildHandler_1.build)(Object.assign(Object.assign({}, newArgs), { manifest: false, eval: true }));
|
|
16
20
|
await (0, initHandler_1.updateManifestShasum)();
|
|
17
21
|
console.log('\nSnap project successfully initiated!');
|
|
18
22
|
}
|
|
@@ -24,7 +28,11 @@ module.exports = {
|
|
|
24
28
|
.option('src', builders_1.default.src)
|
|
25
29
|
.option('dist', builders_1.default.dist)
|
|
26
30
|
.option('port', builders_1.default.port)
|
|
27
|
-
.option('outfileName', builders_1.default.outfileName)
|
|
31
|
+
.option('outfileName', builders_1.default.outfileName)
|
|
32
|
+
.option('template', builders_1.default.template)
|
|
33
|
+
.middleware(((yargsArgv) => {
|
|
34
|
+
(0, initUtils_1.correctDefaultArgs)(yargsArgv);
|
|
35
|
+
}), true);
|
|
28
36
|
},
|
|
29
37
|
handler: (argv) => init(argv),
|
|
30
38
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/init/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,wDAA8C;AAC9C,+CAAkE;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/init/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,wDAA8C;AAC9C,+CAAkE;AAClE,2CAAiD;AAsBjD;;;;;;GAMG;AACH,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,kCACN,OAAO,KACV,QAAQ,EAAE,KAAK,EACf,IAAI,EAAE,IAAI,IACV,CAAC;IAEH,MAAM,IAAA,kCAAoB,GAAE,CAAC;IAE7B,OAAO,CAAC,GAAG,CAAC,wCAAwC,CAAC,CAAC;AACxD,CAAC;AAxCD,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;aAC3C,MAAM,CAAC,UAAU,EAAE,kBAAQ,CAAC,QAAQ,CAAC;aACrC,UAAU,CACT,CAAC,CAAC,SAAoB,EAAE,EAAE;YACxB,IAAA,8BAAkB,EAAC,SAAS,CAAC,CAAC;QAChC,CAAC,CAAQ,EACT,IAAI,CACL,CAAC;IACN,CAAC;IACD,OAAO,EAAE,CAAC,IAAe,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;CACzC,CAAC","sourcesContent":["import yargs, { Arguments } from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { build } from '../build/buildHandler';\nimport { initHandler, updateManifestShasum } from './initHandler';\nimport { correctDefaultArgs } from './initUtils';\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 .option('template', builders.template)\n .middleware(\n ((yargsArgv: Arguments) => {\n correctDefaultArgs(yargsArgv);\n }) as any,\n true,\n );\n },\n handler: (argv: YargsArgs) => init(argv),\n};\n\n/**\n * The main entrypoint for the init command. This calls the init handler to\n * initialize the snap package, builds the snap, and then updates the manifest\n * with the shasum of the built snap.\n *\n * @param argv - The Yargs arguments object.\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,4 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"html": "<!doctype html>\n<html>\n <head>\n <title>Hello, Snaps!</title>\n <link rel=\"icon\" type=\"image/svg\" href=\"./images/icon.svg\"/>\n </head>\n\n <body>\n <h1>Hello, Snaps!</h1>\n <details>\n <summary>Instructions</summary>\n <ul>\n <li>First, click \"Connect\". Then, try out the other buttons!</li>\n <li>Please note that:</li>\n <ul>\n <li>\n The <code>snap.manifest.json</code> and <code>package.json</code> must be located in the server root directory..\n </li>\n <li>\n The Snap bundle must be hosted at the location specified by the <code>location</code> field of <code>snap.manifest.json</code>.\n </li>\n </ul>\n </ul>\n </details>\n <br/>\n\n <button class=\"connect\">Connect</button>\n <button class=\"sendHello\">Send Hello</button>\n </body>\n\n <script>\n const snapId = `local:${window.location.href}`;\n\n const connectButton = document.querySelector('button.connect')\n const sendButton = document.querySelector('button.sendHello')\n\n connectButton.addEventListener('click', connect)\n sendButton.addEventListener('click', send)\n\n // here we get permissions to interact with and install the snap\n async function connect () {\n await ethereum.request({\n method: 'wallet_enable',\n params: [{\n wallet_snap: { [snapId]: {} },\n }]\n })\n }\n\n // here we call the snap's \"hello\" method\n async function send () {\n try {\n const response = await ethereum.request({\n method: 'wallet_invokeSnap',\n params: [snapId, {\n method: 'hello'\n }]\n })\n } catch (err) {\n console.error(err)\n alert('Problem happened: ' + err.message || err)\n }\n }\n </script>\n</html>\n",
|
|
3
|
-
"source": "
|
|
3
|
+
"source": "module.exports.onRpcRequest = async ({ origin, request }) => {\n switch (request.method) {\n case 'hello':\n return wallet.request({\n method: 'snap_confirm',\n params: [\n {\n prompt: `Hello, ${origin}!`,\n description:\n 'This custom confirmation is just for display purposes.',\n textAreaContent:\n 'But you can edit the snap source code to make it do something, if you want to!',\n },\n ],\n });\n default:\n throw new Error('Method not found.');\n }\n};\n",
|
|
4
|
+
"typescriptHtml": "<!doctype html>\n<html>\n </head>\n <title>Hello, Snaps!</title>\n <link rel=\"icon\" type=\"image/svg\" href=\"./images/icon.svg\"/>\n </head>\n\n <body>\n <h1>Hello, Snaps!</h1>\n <details>\n <summary>Instructions</summary>\n <ul>\n <li>First, click \"Connect\". Then, try out the other buttons!</li>\n <li>Please note that:</li>\n <ul>\n <li>\n The <code>snap.manifest.json</code> and <code>package.json</code> must be located in the server root directory...\n </li>\n <li>\n The Snap bundle must be hosted at the location specified by the <code>location</code> field of <code>snap.manifest.json</code>.\n </li>\n </ul>\n </ul>\n </details>\n <br/>\n\n <button class=\"connect\">Connect</button>\n <button class=\"sendHello\">Send Hello</button>\n </body>\n\n <script>\n const snapId = `local:${window.location.href}`;\n\n const connectButton = document.querySelector('button.connect')\n const sendButton = document.querySelector('button.sendHello')\n\n connectButton.addEventListener('click', connect)\n sendButton.addEventListener('click', send)\n\n // here we get permissions to interact with and install the snap\n async function connect () {\n await ethereum.request({\n method: 'wallet_enable',\n params: [{\n wallet_snap: { [snapId]: {} },\n }]\n })\n }\n\n // here we call the snap's \"hello\" method\n async function send () {\n try {\n await ethereum.request({\n method: 'wallet_invokeSnap',\n params: [snapId, {\n method: 'hello'\n }]\n })\n } catch (err) {\n console.error(err)\n alert('Problem happened: ' + err.message || err)\n }\n }\n </script>\n</html>\n",
|
|
5
|
+
"typescriptSource": "import { OnRpcRequestHandler } from '@metamask/snap-types';\n\nexport const onRpcRequest: OnRpcRequestHandler = ({ origin, request }) => {\n switch (request.method) {\n case 'hello':\n return wallet.request({\n method: 'snap_confirm',\n params: [\n {\n prompt: `Hello, ${origin}!`,\n description:\n 'This custom confirmation is just for display purposes.',\n textAreaContent:\n 'But you can edit the snap source code to make it do something, if you want to!',\n },\n ],\n });\n default:\n throw new Error('Method not found.');\n }\n};\n",
|
|
6
|
+
"typescriptConfig": "{\n \"extends\": \"../../../../tsconfig.packages.json\",\n \"compilerOptions\": {\n \"typeRoots\": [\"../../../../node_modules/@types\"]\n },\n \"files\": [\"./node_modules/@metamask/snap-types/global.d.ts\"],\n \"include\": [\"src\"]\n}\n",
|
|
7
|
+
"icon": "<svg width=\"24\" height=\"25\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M17.037 0H6.975C2.605 0 0 2.617 0 6.987v10.05c0 4.37 2.605 6.975 6.975 6.975h10.05c4.37 0 6.975-2.605 6.975-6.976V6.988C24.012 2.617 21.407 0 17.037 0ZM11.49 17.757c0 .36-.18.684-.492.876a.975.975 0 0 1-.54.156 1.11 1.11 0 0 1-.469-.108l-4.202-2.1a1.811 1.811 0 0 1-.985-1.61v-3.973c0-.36.18-.685.493-.877a1.04 1.04 0 0 1 1.008-.048l4.202 2.101a1.8 1.8 0 0 1 .997 1.609v3.974h-.012Zm-.252-6.423L6.723 8.896a1.045 1.045 0 0 1-.528-.924c0-.384.204-.744.528-.924l4.515-2.438a1.631 1.631 0 0 1 1.524 0l4.515 2.438c.324.18.528.528.528.924s-.204.744-.528.924l-4.515 2.438c-.24.132-.504.192-.768.192a1.54 1.54 0 0 1-.756-.192Zm7.972 3.638c0 .684-.385 1.308-.997 1.608l-4.202 2.101c-.144.072-.3.108-.468.108a.975.975 0 0 1-.54-.156 1.017 1.017 0 0 1-.493-.876v-3.974c0-.684.384-1.309.997-1.609l4.202-2.101a1.04 1.04 0 0 1 1.008.048c.313.192.493.516.493.877v3.974Z\" fill=\"#24272A\"/></svg>"
|
|
4
8
|
}
|
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
import { YargsArgs } from '../../types/yargs';
|
|
2
|
+
/**
|
|
3
|
+
* Creates a new snap package, based on one of the provided templates. This
|
|
4
|
+
* creates all the necessary files, like `package.json`, `snap.config.js`, etc.
|
|
5
|
+
* to start developing a snap.
|
|
6
|
+
*
|
|
7
|
+
* @param argv - The Yargs arguments object.
|
|
8
|
+
* @returns The Yargs arguments augmented with the new `dist`, `outfileName` and
|
|
9
|
+
* `src` properties.
|
|
10
|
+
* @throws If initialization of the snap package failed.
|
|
11
|
+
*/
|
|
2
12
|
export declare function initHandler(argv: YargsArgs): Promise<{
|
|
3
13
|
[x: string]: unknown;
|
|
4
14
|
sourceMaps: boolean;
|
|
@@ -9,6 +19,7 @@ export declare function initHandler(argv: YargsArgs): Promise<{
|
|
|
9
19
|
src: string;
|
|
10
20
|
eval: boolean;
|
|
11
21
|
outfileName: string;
|
|
22
|
+
serve: boolean;
|
|
12
23
|
_?: (string | number)[] | undefined;
|
|
13
24
|
$0?: string | undefined;
|
|
14
25
|
}>;
|
|
@@ -12,9 +12,19 @@ const utils_1 = require("../../utils");
|
|
|
12
12
|
const manifestHandler_1 = require("../manifest/manifestHandler");
|
|
13
13
|
const init_template_json_1 = __importDefault(require("./init-template.json"));
|
|
14
14
|
const initUtils_1 = require("./initUtils");
|
|
15
|
+
/**
|
|
16
|
+
* Creates a new snap package, based on one of the provided templates. This
|
|
17
|
+
* creates all the necessary files, like `package.json`, `snap.config.js`, etc.
|
|
18
|
+
* to start developing a snap.
|
|
19
|
+
*
|
|
20
|
+
* @param argv - The Yargs arguments object.
|
|
21
|
+
* @returns The Yargs arguments augmented with the new `dist`, `outfileName` and
|
|
22
|
+
* `src` properties.
|
|
23
|
+
* @throws If initialization of the snap package failed.
|
|
24
|
+
*/
|
|
15
25
|
async function initHandler(argv) {
|
|
16
26
|
console.log(`MetaMask Snaps: Initialize\n`);
|
|
17
|
-
const packageJson = await (0, initUtils_1.asyncPackageInit)();
|
|
27
|
+
const packageJson = await (0, initUtils_1.asyncPackageInit)(argv);
|
|
18
28
|
await (0, initUtils_1.prepareWorkingDirectory)();
|
|
19
29
|
console.log(`\nInit: Building '${snap_controllers_1.NpmSnapFileNames.Manifest}'...\n`);
|
|
20
30
|
const [snapManifest, _newArgs] = await (0, initUtils_1.buildSnapManifest)(argv, packageJson);
|
|
@@ -24,6 +34,7 @@ async function initHandler(argv) {
|
|
|
24
34
|
sorted[key] = _newArgs[key];
|
|
25
35
|
return sorted;
|
|
26
36
|
}, {});
|
|
37
|
+
const isTypeScript = (0, initUtils_1.isTemplateTypescript)(argv.template);
|
|
27
38
|
try {
|
|
28
39
|
await fs_1.promises.writeFile(snap_controllers_1.NpmSnapFileNames.Manifest, `${JSON.stringify(snapManifest, null, 2)}\n`);
|
|
29
40
|
}
|
|
@@ -38,7 +49,7 @@ async function initHandler(argv) {
|
|
|
38
49
|
if (path_1.default.basename(src) !== src) {
|
|
39
50
|
await (0, mkdirp_1.default)(path_1.default.dirname(src));
|
|
40
51
|
}
|
|
41
|
-
await fs_1.promises.writeFile(src, init_template_json_1.default.source);
|
|
52
|
+
await fs_1.promises.writeFile(src, isTypeScript ? init_template_json_1.default.typescriptSource : init_template_json_1.default.source);
|
|
42
53
|
console.log(`Init: Created '${src}'.`);
|
|
43
54
|
}
|
|
44
55
|
catch (err) {
|
|
@@ -47,13 +58,24 @@ async function initHandler(argv) {
|
|
|
47
58
|
}
|
|
48
59
|
// Write index.html
|
|
49
60
|
try {
|
|
50
|
-
await fs_1.promises.writeFile('index.html', init_template_json_1.default.html);
|
|
61
|
+
await fs_1.promises.writeFile('index.html', isTypeScript ? init_template_json_1.default.typescriptHtml : init_template_json_1.default.html);
|
|
51
62
|
console.log(`Init: Created 'index.html'.`);
|
|
52
63
|
}
|
|
53
64
|
catch (err) {
|
|
54
65
|
(0, utils_1.logError)(`Init Error: Failed to write 'index.html'.`, err);
|
|
55
66
|
throw err;
|
|
56
67
|
}
|
|
68
|
+
// Write tsconfig.json
|
|
69
|
+
if (isTypeScript) {
|
|
70
|
+
try {
|
|
71
|
+
await fs_1.promises.writeFile('tsconfig.json', init_template_json_1.default.typescriptConfig);
|
|
72
|
+
console.log(`Init: Created 'tsconfig.json'.`);
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
(0, utils_1.logError)(`Init Error: Failed to write 'tsconfig.json'.`, err);
|
|
76
|
+
throw err;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
57
79
|
// Write config file
|
|
58
80
|
try {
|
|
59
81
|
const defaultConfig = {
|
|
@@ -68,8 +90,21 @@ async function initHandler(argv) {
|
|
|
68
90
|
(0, utils_1.logError)(`Init Error: Failed to write '${utils_1.CONFIG_FILE}'.`, err);
|
|
69
91
|
throw err;
|
|
70
92
|
}
|
|
93
|
+
// Write icon
|
|
94
|
+
const iconPath = 'images/icon.svg';
|
|
95
|
+
try {
|
|
96
|
+
if (path_1.default.basename(iconPath) !== iconPath) {
|
|
97
|
+
await (0, mkdirp_1.default)(path_1.default.dirname(iconPath));
|
|
98
|
+
}
|
|
99
|
+
await fs_1.promises.writeFile(iconPath, init_template_json_1.default.icon);
|
|
100
|
+
console.log(`Init: Created '${iconPath}'.`);
|
|
101
|
+
}
|
|
102
|
+
catch (err) {
|
|
103
|
+
(0, utils_1.logError)(`Init Error: Failed to write '${iconPath}'.`, err);
|
|
104
|
+
throw err;
|
|
105
|
+
}
|
|
71
106
|
(0, utils_1.closePrompt)();
|
|
72
|
-
return {
|
|
107
|
+
return Object.assign(Object.assign({}, argv), newArgs);
|
|
73
108
|
}
|
|
74
109
|
exports.initHandler = initHandler;
|
|
75
110
|
/**
|
|
@@ -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;
|
|
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;AAElE,8EAA4C;AAC5C,2CAKqB;AAErB;;;;;;;;;GASG;AACI,KAAK,UAAU,WAAW,CAAC,IAAe;IAC/C,OAAO,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;IAE5C,MAAM,WAAW,GAAG,MAAM,IAAA,4BAAgB,EAAC,IAAI,CAAC,CAAC;IAEjD,MAAM,IAAA,mCAAuB,GAAE,CAAC;IAEhC,OAAO,CAAC,GAAG,CAAC,qBAAqB,mCAAgB,CAAC,QAAQ,QAAQ,CAAC,CAAC;IAEpE,MAAM,CAAC,YAAY,EAAE,QAAQ,CAAC,GAAG,MAAM,IAAA,6BAAiB,EAAC,IAAI,EAAE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QACF,IAAI,cAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,KAAK,QAAQ,EAAE;YAC7C,MAAM,IAAA,gBAAM,EAAC,cAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;SAC3C;QACD,MAAM,aAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,4BAAQ,CAAC,IAAI,CAAC,CAAC;QAE5C,OAAO,CAAC,GAAG,CAAC,kBAAkB,QAAQ,IAAI,CAAC,CAAC;KAC7C;IAAC,OAAO,GAAG,EAAE;QACZ,IAAA,gBAAQ,EAAC,gCAAgC,QAAQ,IAAI,EAAE,GAAG,CAAC,CAAC;QAC5D,MAAM,GAAG,CAAC;KACX;IAED,IAAA,mBAAW,GAAE,CAAC;IACd,uCAAY,IAAI,GAAK,OAAO,EAAG;AACjC,CAAC;AA/GD,kCA+GC;AAED;;;GAGG;AACI,KAAK,UAAU,oBAAoB;IACxC,MAAM,QAAQ,GAAG,CAAC,MAAM,IAAA,oBAAY,EAClC,mCAAgB,CAAC,QAAQ,CAC1B,CAAiB,CAAC;IAEnB,MAAM,cAAc,GAAG,MAAM,aAAE,CAAC,QAAQ,CACtC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,EACrC,MAAM,CACP,CAAC;IAEF,QAAQ,CAAC,MAAM,CAAC,MAAM,GAAG,IAAA,sCAAmB,EAAC,cAAc,CAAC,CAAC;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 { TemplateType } from '../../builders';\nimport template from './init-template.json';\nimport {\n asyncPackageInit,\n buildSnapManifest,\n isTemplateTypescript,\n prepareWorkingDirectory,\n} from './initUtils';\n\n/**\n * Creates a new snap package, based on one of the provided templates. This\n * creates all the necessary files, like `package.json`, `snap.config.js`, etc.\n * to start developing a snap.\n *\n * @param argv - The Yargs arguments object.\n * @returns The Yargs arguments augmented with the new `dist`, `outfileName` and\n * `src` properties.\n * @throws If initialization of the snap package failed.\n */\nexport async function initHandler(argv: YargsArgs) {\n console.log(`MetaMask Snaps: Initialize\\n`);\n\n const packageJson = await asyncPackageInit(argv);\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 const isTypeScript = isTemplateTypescript(argv.template as TemplateType);\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\n try {\n if (pathUtils.basename(src) !== src) {\n await mkdirp(pathUtils.dirname(src));\n }\n\n await fs.writeFile(\n src,\n isTypeScript ? template.typescriptSource : template.source,\n );\n\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(\n 'index.html',\n isTypeScript ? template.typescriptHtml : template.html,\n );\n\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 tsconfig.json\n if (isTypeScript) {\n try {\n await fs.writeFile('tsconfig.json', template.typescriptConfig);\n console.log(`Init: Created 'tsconfig.json'.`);\n } catch (err) {\n logError(`Init Error: Failed to write 'tsconfig.json'.`, err);\n throw err;\n }\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 // Write icon\n const iconPath = 'images/icon.svg';\n try {\n if (pathUtils.basename(iconPath) !== iconPath) {\n await mkdirp(pathUtils.dirname(iconPath));\n }\n await fs.writeFile(iconPath, template.icon);\n\n console.log(`Init: Created '${iconPath}'.`);\n } catch (err) {\n logError(`Init Error: Failed to write '${iconPath}'.`, 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,21 +1,23 @@
|
|
|
1
1
|
import { NpmSnapPackageJson, SnapManifest } from '@metamask/snap-controllers/dist/snaps';
|
|
2
|
+
import { Arguments } from 'yargs';
|
|
2
3
|
import { YargsArgs } from '../../types/yargs';
|
|
4
|
+
import { TemplateType } from '../../builders';
|
|
3
5
|
/**
|
|
4
6
|
* Initializes a `package.json` file for a Snap project. Will attempt to read
|
|
5
7
|
* and parse the existing file if it already exists, otherwise will intialize
|
|
6
8
|
* a brand new one.
|
|
7
9
|
*
|
|
10
|
+
* @param argv - Yargs arguments object.
|
|
8
11
|
* @returns The contents of the `package.json` file.
|
|
9
12
|
*/
|
|
10
|
-
export declare function asyncPackageInit(): Promise<Readonly<NpmSnapPackageJson>>;
|
|
13
|
+
export declare function asyncPackageInit(argv: YargsArgs): Promise<Readonly<NpmSnapPackageJson>>;
|
|
11
14
|
/**
|
|
12
15
|
* Interactively constructs a Snap manifest file by prompting the user.
|
|
13
16
|
*
|
|
14
17
|
* @param argv - The `yargs` `argv` object.
|
|
15
18
|
* @param packageJson - The `package.json` object.
|
|
16
|
-
* @
|
|
17
|
-
*
|
|
18
|
-
* with properties to match the manifest.
|
|
19
|
+
* @returns A tuple of the resulting Snap manifest object and a new `argv`
|
|
20
|
+
* object with properties to match the manifest.
|
|
19
21
|
*/
|
|
20
22
|
export declare function buildSnapManifest(argv: YargsArgs, packageJson: NpmSnapPackageJson): Promise<[SnapManifest, {
|
|
21
23
|
dist: string;
|
|
@@ -27,3 +29,18 @@ export declare function buildSnapManifest(argv: YargsArgs, packageJson: NpmSnapP
|
|
|
27
29
|
* by the initialization process, and asks the user whether to continue if so.
|
|
28
30
|
*/
|
|
29
31
|
export declare function prepareWorkingDirectory(): Promise<void>;
|
|
32
|
+
/**
|
|
33
|
+
* In case when TypeScript version is used, default source file
|
|
34
|
+
* will be updated if previous was not correct.
|
|
35
|
+
*
|
|
36
|
+
* @param yargsArgv - The Yargs arguments object.
|
|
37
|
+
* @returns Modified Yargs arguments object.
|
|
38
|
+
*/
|
|
39
|
+
export declare function correctDefaultArgs(yargsArgv: Arguments): Arguments;
|
|
40
|
+
/**
|
|
41
|
+
* Check if template argument is TemplateType.TypeScript.
|
|
42
|
+
*
|
|
43
|
+
* @param templateType - TemplateType value of the template argument passed from CLI.
|
|
44
|
+
* @returns True or false.
|
|
45
|
+
*/
|
|
46
|
+
export declare function isTemplateTypescript(templateType: TemplateType): boolean;
|
|
@@ -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.prepareWorkingDirectory = exports.buildSnapManifest = exports.asyncPackageInit = void 0;
|
|
6
|
+
exports.isTemplateTypescript = exports.correctDefaultArgs = exports.prepareWorkingDirectory = exports.buildSnapManifest = exports.asyncPackageInit = void 0;
|
|
7
7
|
const fs_1 = require("fs");
|
|
8
8
|
const path_1 = __importDefault(require("path"));
|
|
9
9
|
const snaps_1 = require("@metamask/snap-controllers/dist/snaps");
|
|
@@ -11,6 +11,7 @@ const init_package_json_1 = __importDefault(require("init-package-json"));
|
|
|
11
11
|
const mkdirp_1 = __importDefault(require("mkdirp"));
|
|
12
12
|
const slash_1 = __importDefault(require("slash"));
|
|
13
13
|
const utils_1 = require("../../utils");
|
|
14
|
+
const builders_1 = require("../../builders");
|
|
14
15
|
/**
|
|
15
16
|
* This is a placeholder shasum that will be replaced at the end of the init command.
|
|
16
17
|
*/
|
|
@@ -21,9 +22,10 @@ const NPM_PUBLIC_REGISTRY_URL = 'https://registry.npmjs.org';
|
|
|
21
22
|
* and parse the existing file if it already exists, otherwise will intialize
|
|
22
23
|
* a brand new one.
|
|
23
24
|
*
|
|
25
|
+
* @param argv - Yargs arguments object.
|
|
24
26
|
* @returns The contents of the `package.json` file.
|
|
25
27
|
*/
|
|
26
|
-
async function asyncPackageInit() {
|
|
28
|
+
async function asyncPackageInit(argv) {
|
|
27
29
|
if ((0, fs_1.existsSync)(snaps_1.NpmSnapFileNames.PackageJson)) {
|
|
28
30
|
console.log(`Init: Attempting to use existing '${snaps_1.NpmSnapFileNames.PackageJson}'...`);
|
|
29
31
|
try {
|
|
@@ -44,7 +46,9 @@ async function asyncPackageInit() {
|
|
|
44
46
|
}
|
|
45
47
|
// Run 'npm init'
|
|
46
48
|
return new Promise((resolve, reject) => {
|
|
47
|
-
(0, init_package_json_1.default)(process.cwd(), '', {
|
|
49
|
+
(0, init_package_json_1.default)(process.cwd(), '', {
|
|
50
|
+
'init.main': argv.src,
|
|
51
|
+
}, (err, data) => {
|
|
48
52
|
if (err) {
|
|
49
53
|
reject(err);
|
|
50
54
|
}
|
|
@@ -57,10 +61,22 @@ async function asyncPackageInit() {
|
|
|
57
61
|
exports.asyncPackageInit = asyncPackageInit;
|
|
58
62
|
const YES = 'yes';
|
|
59
63
|
const YES_VALUES = new Set([YES, 'y']);
|
|
64
|
+
/**
|
|
65
|
+
* Checks if user input provided over a prompt is "yes", i.e., if the value is
|
|
66
|
+
* truthy and in the {@link YES_VALUES} set.
|
|
67
|
+
*
|
|
68
|
+
* @param userInput - The user input to check.
|
|
69
|
+
* @returns `true` if the user input is "yes", `false` otherwise.
|
|
70
|
+
*/
|
|
60
71
|
function isYes(userInput) {
|
|
61
72
|
return userInput && YES_VALUES.has(userInput.toLowerCase());
|
|
62
73
|
}
|
|
63
74
|
const DEFAULT_PERMISSION_KEY = 'snap_confirm';
|
|
75
|
+
/**
|
|
76
|
+
* Get the default permissions to write to the snap manifest.
|
|
77
|
+
*
|
|
78
|
+
* @returns An object containing the default permissions.
|
|
79
|
+
*/
|
|
64
80
|
const getDefaultPermissions = () => {
|
|
65
81
|
return { [DEFAULT_PERMISSION_KEY]: {} };
|
|
66
82
|
};
|
|
@@ -69,9 +85,8 @@ const getDefaultPermissions = () => {
|
|
|
69
85
|
*
|
|
70
86
|
* @param argv - The `yargs` `argv` object.
|
|
71
87
|
* @param packageJson - The `package.json` object.
|
|
72
|
-
* @
|
|
73
|
-
*
|
|
74
|
-
* with properties to match the manifest.
|
|
88
|
+
* @returns A tuple of the resulting Snap manifest object and a new `argv`
|
|
89
|
+
* object with properties to match the manifest.
|
|
75
90
|
*/
|
|
76
91
|
async function buildSnapManifest(argv, packageJson) {
|
|
77
92
|
const { outfileName } = argv;
|
|
@@ -176,6 +191,13 @@ async function buildSnapManifest(argv, packageJson) {
|
|
|
176
191
|
}
|
|
177
192
|
}
|
|
178
193
|
return endSnapManifest();
|
|
194
|
+
/**
|
|
195
|
+
* Get the final snap manifest object and return it, along with the dist and
|
|
196
|
+
* file names.
|
|
197
|
+
*
|
|
198
|
+
* @returns A tuple of the resulting snap manifest object and an object
|
|
199
|
+
* containing the dist and file names.
|
|
200
|
+
*/
|
|
179
201
|
function endSnapManifest() {
|
|
180
202
|
const manifest = {
|
|
181
203
|
version: packageJson.version,
|
|
@@ -191,7 +213,7 @@ async function buildSnapManifest(argv, packageJson) {
|
|
|
191
213
|
filePath: (0, slash_1.default)(path_1.default.join(dist, outfileName)),
|
|
192
214
|
packageName: packageJson.name,
|
|
193
215
|
registry: NPM_PUBLIC_REGISTRY_URL,
|
|
194
|
-
iconPath: 'icon.svg',
|
|
216
|
+
iconPath: 'images/icon.svg',
|
|
195
217
|
},
|
|
196
218
|
},
|
|
197
219
|
},
|
|
@@ -241,4 +263,30 @@ async function prepareWorkingDirectory() {
|
|
|
241
263
|
}
|
|
242
264
|
}
|
|
243
265
|
exports.prepareWorkingDirectory = prepareWorkingDirectory;
|
|
266
|
+
/**
|
|
267
|
+
* In case when TypeScript version is used, default source file
|
|
268
|
+
* will be updated if previous was not correct.
|
|
269
|
+
*
|
|
270
|
+
* @param yargsArgv - The Yargs arguments object.
|
|
271
|
+
* @returns Modified Yargs arguments object.
|
|
272
|
+
*/
|
|
273
|
+
function correctDefaultArgs(yargsArgv) {
|
|
274
|
+
if (yargsArgv.template === builders_1.TemplateType.TypeScript &&
|
|
275
|
+
yargsArgv.src === 'src/index.js') {
|
|
276
|
+
yargsArgv.src = 'src/index.ts';
|
|
277
|
+
yargsArgv.s = 'src/index.ts';
|
|
278
|
+
}
|
|
279
|
+
return yargsArgv;
|
|
280
|
+
}
|
|
281
|
+
exports.correctDefaultArgs = correctDefaultArgs;
|
|
282
|
+
/**
|
|
283
|
+
* Check if template argument is TemplateType.TypeScript.
|
|
284
|
+
*
|
|
285
|
+
* @param templateType - TemplateType value of the template argument passed from CLI.
|
|
286
|
+
* @returns True or false.
|
|
287
|
+
*/
|
|
288
|
+
function isTemplateTypescript(templateType) {
|
|
289
|
+
return templateType === builders_1.TemplateType.TypeScript;
|
|
290
|
+
}
|
|
291
|
+
exports.isTemplateTypescript = isTemplateTypescript;
|
|
244
292
|
//# sourceMappingURL=initUtils.js.map
|