@metamask/snaps-utils 0.37.1-flask.1 → 0.38.0-flask.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -282
- package/dist/cjs/enum.js +2 -2
- package/dist/cjs/enum.js.map +1 -1
- package/dist/cjs/errors.js +19 -0
- package/dist/cjs/errors.js.map +1 -0
- package/dist/cjs/eval-worker.js.map +1 -1
- package/dist/cjs/eval.js +54 -6
- package/dist/cjs/eval.js.map +1 -1
- package/dist/cjs/handlers.js +59 -0
- package/dist/cjs/handlers.js.map +1 -1
- package/dist/cjs/index.browser.js +3 -0
- package/dist/cjs/index.browser.js.map +1 -1
- package/dist/cjs/index.js +3 -0
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/manifest/manifest.js +4 -4
- package/dist/cjs/manifest/manifest.js.map +1 -1
- package/dist/cjs/snaps.js.map +1 -1
- package/dist/cjs/strings.js +21 -0
- package/dist/cjs/strings.js.map +1 -0
- package/dist/cjs/structs.js +163 -0
- package/dist/cjs/structs.js.map +1 -0
- package/dist/cjs/types.js +2 -10
- package/dist/cjs/types.js.map +1 -1
- package/dist/esm/enum.js +1 -1
- package/dist/esm/enum.js.map +1 -1
- package/dist/esm/errors.js +17 -0
- package/dist/esm/errors.js.map +1 -0
- package/dist/esm/eval-worker.js.map +1 -1
- package/dist/esm/eval.js +43 -3
- package/dist/esm/eval.js.map +1 -1
- package/dist/esm/handlers.js +45 -1
- package/dist/esm/handlers.js.map +1 -1
- package/dist/esm/index.browser.js +3 -0
- package/dist/esm/index.browser.js.map +1 -1
- package/dist/esm/index.js +3 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/manifest/manifest.js +5 -4
- package/dist/esm/manifest/manifest.js.map +1 -1
- package/dist/esm/snaps.js.map +1 -1
- package/dist/esm/strings.js +11 -0
- package/dist/esm/strings.js.map +1 -0
- package/dist/esm/structs.js +230 -0
- package/dist/esm/structs.js.map +1 -0
- package/dist/esm/types.js +2 -7
- package/dist/esm/types.js.map +1 -1
- package/dist/types/enum.d.ts +1 -1
- package/dist/types/errors.d.ts +10 -0
- package/dist/types/eval.d.ts +9 -1
- package/dist/types/handlers.d.ts +82 -6
- package/dist/types/index.browser.d.ts +3 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/manifest/manifest.d.ts +3 -1
- package/dist/types/snaps.d.ts +5 -6
- package/dist/types/strings.d.ts +8 -0
- package/dist/types/structs.d.ts +158 -0
- package/dist/types/types.d.ts +1 -5
- package/package.json +6 -5
package/dist/esm/eval.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/eval.ts"],"sourcesContent":["import { fork } from 'child_process';\nimport { join } from 'path';\n\nimport { validateFilePath } from './fs';\n\n/**\n * Spawn a new process 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 async function evalBundle(bundlePath: string): Promise<
|
|
1
|
+
{"version":3,"sources":["../../src/eval.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\nimport { fork } from 'child_process';\nimport { join } from 'path';\n\nimport { validateFilePath } from './fs';\n\nexport type EvalOutput = {\n stdout: string;\n stderr: string;\n};\n\nexport class SnapEvalError extends Error {\n readonly output: EvalOutput;\n\n constructor(message: string, output: EvalOutput) {\n super(message);\n\n this.name = 'SnapEvalError';\n this.output = output;\n }\n}\n\n/**\n * Spawn a new process 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 async function evalBundle(bundlePath: string): Promise<EvalOutput> {\n await validateFilePath(bundlePath);\n\n return new Promise((resolve, reject) => {\n const worker = fork(join(__dirname, 'eval-worker.js'), [bundlePath], {\n // To avoid printing the output of the worker to the console, we set\n // `stdio` to `pipe` and handle the output ourselves.\n stdio: 'pipe',\n });\n\n let stdout = '';\n let stderr = '';\n\n assert(worker.stdout, '`stdout` should be defined.');\n assert(worker.stderr, '`stderr` should be defined.');\n\n worker.stdout.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n worker.stderr.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n worker.on('exit', (exitCode: number) => {\n const output = {\n stdout,\n stderr,\n };\n\n if (exitCode === 0) {\n return resolve(output);\n }\n\n return reject(\n new SnapEvalError(\n `Process exited with non-zero exit code: ${exitCode}.`,\n output,\n ),\n );\n });\n });\n}\n"],"names":["assert","fork","join","validateFilePath","SnapEvalError","Error","constructor","message","output","name","evalBundle","bundlePath","Promise","resolve","reject","worker","__dirname","stdio","stdout","stderr","on","data","toString","exitCode"],"mappings":";;;;;;;;;;;;;AAAA,SAASA,MAAM,QAAQ,kBAAkB;AACzC,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,IAAI,QAAQ,OAAO;AAE5B,SAASC,gBAAgB,QAAQ,OAAO;AAOxC,OAAO,MAAMC,sBAAsBC;IAGjCC,YAAYC,OAAe,EAAEC,MAAkB,CAAE;QAC/C,KAAK,CAACD;QAHR,uBAASC,UAAT,KAAA;QAKE,IAAI,CAACC,IAAI,GAAG;QACZ,IAAI,CAACD,MAAM,GAAGA;IAChB;AACF;AAEA;;;;;;CAMC,GACD,OAAO,eAAeE,WAAWC,UAAkB;IACjD,MAAMR,iBAAiBQ;IAEvB,OAAO,IAAIC,QAAQ,CAACC,SAASC;QAC3B,MAAMC,SAASd,KAAKC,KAAKc,WAAW,mBAAmB;YAACL;SAAW,EAAE;YACnE,oEAAoE;YACpE,qDAAqD;YACrDM,OAAO;QACT;QAEA,IAAIC,SAAS;QACb,IAAIC,SAAS;QAEbnB,OAAOe,OAAOG,MAAM,EAAE;QACtBlB,OAAOe,OAAOI,MAAM,EAAE;QAEtBJ,OAAOG,MAAM,CAACE,EAAE,CAAC,QAAQ,CAACC;YACxBH,UAAUG,KAAKC,QAAQ;QACzB;QAEAP,OAAOI,MAAM,CAACC,EAAE,CAAC,QAAQ,CAACC;YACxBF,UAAUE,KAAKC,QAAQ;QACzB;QAEAP,OAAOK,EAAE,CAAC,QAAQ,CAACG;YACjB,MAAMf,SAAS;gBACbU;gBACAC;YACF;YAEA,IAAII,aAAa,GAAG;gBAClB,OAAOV,QAAQL;YACjB;YAEA,OAAOM,OACL,IAAIV,cACF,CAAC,wCAAwC,EAAEmB,SAAS,CAAC,CAAC,EACtDf;QAGN;IACF;AACF"}
|
package/dist/esm/handlers.js
CHANGED
|
@@ -1,3 +1,47 @@
|
|
|
1
|
-
export
|
|
1
|
+
export var HandlerType;
|
|
2
|
+
(function(HandlerType) {
|
|
3
|
+
HandlerType["OnRpcRequest"] = 'onRpcRequest';
|
|
4
|
+
HandlerType["OnTransaction"] = 'onTransaction';
|
|
5
|
+
HandlerType["OnCronjob"] = 'onCronjob';
|
|
6
|
+
HandlerType["OnInstall"] = 'onInstall';
|
|
7
|
+
HandlerType["OnUpdate"] = 'onUpdate';
|
|
8
|
+
})(HandlerType || (HandlerType = {}));
|
|
9
|
+
export const SNAP_EXPORTS = {
|
|
10
|
+
[HandlerType.OnRpcRequest]: {
|
|
11
|
+
type: HandlerType.OnRpcRequest,
|
|
12
|
+
required: true,
|
|
13
|
+
validator: (snapExport)=>{
|
|
14
|
+
return typeof snapExport === 'function';
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
[HandlerType.OnTransaction]: {
|
|
18
|
+
type: HandlerType.OnTransaction,
|
|
19
|
+
required: true,
|
|
20
|
+
validator: (snapExport)=>{
|
|
21
|
+
return typeof snapExport === 'function';
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
[HandlerType.OnCronjob]: {
|
|
25
|
+
type: HandlerType.OnCronjob,
|
|
26
|
+
required: true,
|
|
27
|
+
validator: (snapExport)=>{
|
|
28
|
+
return typeof snapExport === 'function';
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
[HandlerType.OnInstall]: {
|
|
32
|
+
type: HandlerType.OnInstall,
|
|
33
|
+
required: false,
|
|
34
|
+
validator: (snapExport)=>{
|
|
35
|
+
return typeof snapExport === 'function';
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
[HandlerType.OnUpdate]: {
|
|
39
|
+
type: HandlerType.OnUpdate,
|
|
40
|
+
required: false,
|
|
41
|
+
validator: (snapExport)=>{
|
|
42
|
+
return typeof snapExport === 'function';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
};
|
|
2
46
|
|
|
3
47
|
//# sourceMappingURL=handlers.js.map
|
package/dist/esm/handlers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import type { Component } from '@metamask/snaps-ui';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\n\n/**\n * The `onRpcRequest` handler. This is called whenever a JSON-RPC request is\n * made to the snap.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of another\n * snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n * @returns The JSON-RPC response. This must be a JSON-serializable value.\n */\nexport type OnRpcRequestHandler
|
|
1
|
+
{"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import type { Component } from '@metamask/snaps-ui';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nexport enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n}\n\ntype SnapHandler = {\n /**\n * The type of handler.\n */\n type: HandlerType;\n\n /**\n * Whether the handler is required, i.e., whether the request will fail if the\n * handler is called, but the snap does not export it.\n *\n * This is primarily used for the lifecycle handlers, which are optional.\n */\n required: boolean;\n\n /**\n * Validate the given snap export. This should return a type guard for the\n * handler type.\n *\n * @param snapExport - The export to validate.\n * @returns Whether the export is valid.\n */\n validator: (snapExport: unknown) => boolean;\n};\n\nexport const SNAP_EXPORTS = {\n [HandlerType.OnRpcRequest]: {\n type: HandlerType.OnRpcRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnRpcRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnTransaction]: {\n type: HandlerType.OnTransaction,\n required: true,\n validator: (snapExport: unknown): snapExport is OnTransactionHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnCronjob]: {\n type: HandlerType.OnCronjob,\n required: true,\n validator: (snapExport: unknown): snapExport is OnCronjobHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnInstall]: {\n type: HandlerType.OnInstall,\n required: false,\n validator: (snapExport: unknown): snapExport is OnInstallHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnUpdate]: {\n type: HandlerType.OnUpdate,\n required: false,\n validator: (snapExport: unknown): snapExport is OnUpdateHandler => {\n return typeof snapExport === 'function';\n },\n },\n} as const;\n\n/**\n * The `onRpcRequest` handler. This is called whenever a JSON-RPC request is\n * made to the snap.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of another\n * snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n * @returns The JSON-RPC response. This must be a JSON-serializable value.\n */\nexport type OnRpcRequestHandler<Params extends JsonRpcParams = JsonRpcParams> =\n (args: {\n origin: string;\n request: JsonRpcRequest<Params>;\n }) => Promise<unknown>;\n\n/**\n * The response from a snap's `onTransaction` handler.\n *\n * @property content - A custom UI component, that will be shown in MetaMask. Can be created using `@metamask/snaps-ui`.\n *\n * If the snap has no insights about the transaction, this should be `null`.\n */\nexport type OnTransactionResponse = {\n content: Component | null;\n};\n\n/**\n * The `onTransaction` handler. This is called whenever a transaction is\n * submitted to the snap. It can return insights about the transaction, which\n * will be displayed to the user.\n *\n * @param args - The request arguments.\n * @param args.transaction - The transaction object.\n * @param args.chainId - The CAIP-2 chain ID of the network the transaction is\n * being submitted to.\n * @param args.transactionOrigin - The origin of the transaction. This is the\n * URL of the dapp that submitted the transaction.\n * @returns Insights about the transaction. See {@link OnTransactionResponse}.\n */\n// TODO: Improve type.\nexport type OnTransactionHandler = (args: {\n transaction: { [key: string]: Json };\n chainId: string;\n transactionOrigin?: string;\n}) => Promise<OnTransactionResponse>;\n\n/**\n * The `onCronjob` handler. This is called on a regular interval, as defined by\n * the snap's manifest.\n *\n * @param args - The request arguments.\n * @param args.request - The JSON-RPC request sent to the snap.\n */\nexport type OnCronjobHandler<Params extends JsonRpcParams = JsonRpcParams> =\n (args: { request: JsonRpcRequest<Params> }) => Promise<unknown>;\n\n/**\n * A handler that can be used for the lifecycle hooks.\n */\nexport type LifecycleEventHandler = (args: {\n request: JsonRpcRequest;\n}) => Promise<unknown>;\n\n/**\n * The `onInstall` handler. This is called after the snap is installed.\n *\n * This type is an alias for {@link LifecycleEventHandler}.\n */\nexport type OnInstallHandler = LifecycleEventHandler;\n\n/**\n * The `onUpdate` handler. This is called after the snap is updated.\n *\n * This type is an alias for {@link LifecycleEventHandler}.\n */\nexport type OnUpdateHandler = LifecycleEventHandler;\n\n/**\n * Utility type for getting the handler function type from a handler type.\n */\nexport type HandlerFunction<Type extends SnapHandler> =\n Type['validator'] extends (snapExport: unknown) => snapExport is infer Handler\n ? Handler\n : never;\n\n/**\n * All the function-based handlers that a snap can implement.\n */\nexport type SnapFunctionExports = {\n [Key in keyof typeof SNAP_EXPORTS]?: HandlerFunction<\n typeof SNAP_EXPORTS[Key]\n >;\n};\n\n/**\n * All handlers that a snap can implement.\n */\nexport type SnapExports = SnapFunctionExports;\n"],"names":["HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnInstall","OnUpdate","SNAP_EXPORTS","type","required","validator","snapExport"],"mappings":"WAGO;UAAKA,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,mBAAgB;IAFNF,YAGVG,eAAY;IAHFH,YAIVI,eAAY;IAJFJ,YAKVK,cAAW;GALDL,gBAAAA;AAgCZ,OAAO,MAAMM,eAAe;IAC1B,CAACN,YAAYC,YAAY,CAAC,EAAE;QAC1BM,MAAMP,YAAYC,YAAY;QAC9BO,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACV,YAAYE,aAAa,CAAC,EAAE;QAC3BK,MAAMP,YAAYE,aAAa;QAC/BM,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACV,YAAYG,SAAS,CAAC,EAAE;QACvBI,MAAMP,YAAYG,SAAS;QAC3BK,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACV,YAAYI,SAAS,CAAC,EAAE;QACvBG,MAAMP,YAAYI,SAAS;QAC3BI,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACV,YAAYK,QAAQ,CAAC,EAAE;QACtBE,MAAMP,YAAYK,QAAQ;QAC1BG,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;AACF,EAAW"}
|
|
@@ -6,6 +6,7 @@ export * from './deep-clone';
|
|
|
6
6
|
export * from './default-endowments';
|
|
7
7
|
export * from './entropy';
|
|
8
8
|
export * from './enum';
|
|
9
|
+
export * from './errors';
|
|
9
10
|
export * from './handlers';
|
|
10
11
|
export * from './iframe';
|
|
11
12
|
export * from './json';
|
|
@@ -15,6 +16,8 @@ export * from './manifest/index.browser';
|
|
|
15
16
|
export * from './namespace';
|
|
16
17
|
export * from './path';
|
|
17
18
|
export * from './snaps';
|
|
19
|
+
export * from './strings';
|
|
20
|
+
export * from './structs';
|
|
18
21
|
export * from './types';
|
|
19
22
|
export * from './validation';
|
|
20
23
|
export * from './versions';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,2BAA2B;AACzC,cAAc,cAAc;AAC5B,cAAc,SAAS;AACvB,cAAc,UAAU;AACxB,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,+BAA+B"}
|
|
1
|
+
{"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './errors';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,WAAW;AACzB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,2BAA2B;AACzC,cAAc,cAAc;AAC5B,cAAc,SAAS;AACvB,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,+BAA+B"}
|
package/dist/esm/index.js
CHANGED
|
@@ -7,6 +7,7 @@ export * from './default-endowments';
|
|
|
7
7
|
export * from './entropy';
|
|
8
8
|
export * from './enum';
|
|
9
9
|
export * from './eval';
|
|
10
|
+
export * from './errors';
|
|
10
11
|
export * from './fs';
|
|
11
12
|
export * from './handlers';
|
|
12
13
|
export * from './iframe';
|
|
@@ -20,6 +21,8 @@ export * from './npm';
|
|
|
20
21
|
export * from './path';
|
|
21
22
|
export * from './post-process';
|
|
22
23
|
export * from './snaps';
|
|
24
|
+
export * from './strings';
|
|
25
|
+
export * from './structs';
|
|
23
26
|
export * from './types';
|
|
24
27
|
export * from './validation';
|
|
25
28
|
export * from './versions';
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './eval';\nexport * from './fs';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,SAAS;AACvB,cAAc,OAAO;AACrB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,SAAS;AACvB,cAAc,cAAc;AAC5B,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,iBAAiB;AAC/B,cAAc,UAAU;AACxB,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,iBAAiB"}
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './eval';\nexport * from './errors';\nexport * from './fs';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":"AAAA,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,eAAe;AAC7B,cAAc,uBAAuB;AACrC,cAAc,YAAY;AAC1B,cAAc,SAAS;AACvB,cAAc,SAAS;AACvB,cAAc,WAAW;AACzB,cAAc,OAAO;AACrB,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,SAAS;AACvB,cAAc,cAAc;AAC5B,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,iBAAiB;AAC/B,cAAc,UAAU;AACxB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,UAAU;AACxB,cAAc,eAAe;AAC7B,cAAc,aAAa;AAC3B,cAAc,iBAAiB"}
|
|
@@ -26,9 +26,10 @@ const MANIFEST_SORT_ORDER = {
|
|
|
26
26
|
* @param basePath - The path to the folder with the manifest files.
|
|
27
27
|
* @param writeManifest - Whether to write the fixed manifest to disk.
|
|
28
28
|
* @param sourceCode - The source code of the Snap.
|
|
29
|
+
* @param writeFileFn - The function to use to write the manifest to disk.
|
|
29
30
|
* @returns Whether the manifest was updated, and an array of warnings that
|
|
30
31
|
* were encountered during processing of the manifest files.
|
|
31
|
-
*/ export async function checkManifest(basePath, writeManifest = true, sourceCode) {
|
|
32
|
+
*/ export async function checkManifest(basePath, writeManifest = true, sourceCode, writeFileFn = fs.writeFile) {
|
|
32
33
|
const warnings = [];
|
|
33
34
|
const errors = [];
|
|
34
35
|
let updated = false;
|
|
@@ -99,7 +100,7 @@ const MANIFEST_SORT_ORDER = {
|
|
|
99
100
|
try {
|
|
100
101
|
const newManifest = `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\n`;
|
|
101
102
|
if (updated || newManifest !== manifestFile.value) {
|
|
102
|
-
await
|
|
103
|
+
await writeFileFn(pathUtils.join(basePath, NpmSnapFileNames.Manifest), newManifest);
|
|
103
104
|
}
|
|
104
105
|
} catch (error) {
|
|
105
106
|
// Note: This error isn't pushed to the errors array, because it's not an
|
|
@@ -172,7 +173,7 @@ const MANIFEST_SORT_ORDER = {
|
|
|
172
173
|
const virtualFile = await readVirtualFile(pathUtils.join(basePath, sourceFilePath), 'utf8');
|
|
173
174
|
return virtualFile;
|
|
174
175
|
} catch (error) {
|
|
175
|
-
throw new Error(`Failed to read
|
|
176
|
+
throw new Error(`Failed to read snap bundle file: ${error.message}`);
|
|
176
177
|
}
|
|
177
178
|
}
|
|
178
179
|
/**
|
|
@@ -194,7 +195,7 @@ const MANIFEST_SORT_ORDER = {
|
|
|
194
195
|
const virtualFile = await readVirtualFile(pathUtils.join(basePath, iconPath), 'utf8');
|
|
195
196
|
return virtualFile;
|
|
196
197
|
} catch (error) {
|
|
197
|
-
throw new Error(`Failed to read
|
|
198
|
+
throw new Error(`Failed to read snap icon file: ${error.message}`);
|
|
198
199
|
}
|
|
199
200
|
}
|
|
200
201
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\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 basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\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 let currentError = error;\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 // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n validateNpmSnapManifest({ ...partiallyValidatedFiles, manifest });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = 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 errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\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 warnings.push(\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 if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await fs.writeFile(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\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 */\nexport function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): VirtualFile<SnapManifest> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\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 basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap bundle file: ${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap icon file: ${error.message}`);\n }\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\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an npm Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n validateSnapShasum(\n { manifest, sourceCode, svgIcon },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["assertExhaustive","assert","isPlainObject","deepEqual","promises","fs","pathUtils","deepClone","readJsonFile","validateNpmSnap","getSnapChecksum","ProgrammaticallyFixableSnapError","validateSnapShasum","NpmSnapFileNames","SnapValidationFailureReason","readVirtualFile","VirtualFile","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","checkManifest","basePath","writeManifest","sourceCode","warnings","errors","updated","manifestPath","join","Manifest","manifestFile","unvalidatedManifest","result","packageFile","PackageJson","snapFiles","manifest","packageJson","getSnapSourceCode","svgIcon","getSnapIcon","error","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","length","attempts","fixManifest","validateNpmSnapManifest","nextValidationError","Error","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","getWritableManifest","value","writeFile","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","undefined","ShasumMismatch","shasum","sourceFilePath","filePath","path","virtualFile","iconPath","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","man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uE,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvDiB,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACtG,UAAUmG,uBAAuBG,qBAClC;QACA,MAAM,IAAI9F,iCACR,CAAC,CAAC,EAAEE,iBAAiBsB,QAAQ,CAAC,yCAAyC,EAAEtB,iBAAiB2B,WAAW,CAAC,qBAAqB,CAAC,EAC5H1B,4BAA4BwE,kBAAkB;IAElD;IAEA1E,mBACE;QAAE8B;QAAUb;QAAYgB;IAAQ,GAChC,CAAC,CAAC,EAAEhC,iBAAiBsB,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\nexport type WriteFileFunction = (path: string, data: string) => Promise<void>;\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 basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @param writeFileFn - The function to use to write the manifest to disk.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n writeFileFn: WriteFileFunction = fs.writeFile,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\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 let currentError = error;\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 // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n validateNpmSnapManifest({ ...partiallyValidatedFiles, manifest });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = 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 errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\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 warnings.push(\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 if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await writeFileFn(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\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 */\nexport function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): VirtualFile<SnapManifest> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\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 basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap bundle file: ${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap icon file: ${error.message}`);\n }\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\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an npm Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n validateSnapShasum(\n { manifest, sourceCode, svgIcon },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["assertExhaustive","assert","isPlainObject","deepEqual","promises","fs","pathUtils","deepClone","readJsonFile","validateNpmSnap","getSnapChecksum","ProgrammaticallyFixableSnapError","validateSnapShasum","NpmSnapFileNames","SnapValidationFailureReason","readVirtualFile","VirtualFile","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","checkManifest","basePath","writeManifest","sourceCode","writeFileFn","writeFile","warnings","errors","updated","manifestPath","join","Manifest","manifestFile","unvalidatedManifest","result","packageFile","PackageJson","snapFiles","manifest","packageJson","getSnapSourceCode","svgIcon","getSnapIcon","error","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","length","attempts","fixManifest","validateNpmSnapManifest","nextValidationError","Error","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","getWritableManifest","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","undefined","ShasumMismatch","shasum","sourceFilePath","filePath","path","virtualFile","iconPath","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository"],"mappings":"AACA,SAASA,gBAAgB,EAAEC,MAAM,EAAEC,aAAa,QAAQ,kBAAkB;AAC1E,OAAOC,eAAe,kBAAkB;AACxC,SAASC,YAAYC,EAAE,QAAQ,KAAK;AACpC,OAAOC,eAAe,OAAO;AAE7B,SAASC,SAAS,QAAQ,gBAAgB;AAC1C,SAASC,YAAY,QAAQ,QAAQ;AACrC,SAASC,eAAe,QAAQ,SAAS;AACzC,SACEC,eAAe,EACfC,gCAAgC,EAChCC,kBAAkB,QACb,WAAW;AAElB,SAASC,gBAAgB,EAAEC,2BAA2B,QAAQ,WAAW;AACzE,SAASC,eAAe,EAAEC,WAAW,QAAQ,kBAAkB;AAG/D,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,iBAAiB;AACnB;AAyBA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeC,cACpBC,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB,EACnBC,cAAiCzB,GAAG0B,SAAS;IAE7C,MAAMC,WAAqB,EAAE;IAC7B,MAAMC,SAAmB,EAAE;IAE3B,IAAIC,UAAU;IAEd,MAAMC,eAAe7B,UAAU8B,IAAI,CAACT,UAAUd,iBAAiBwB,QAAQ;IACvE,MAAMC,eAAe,MAAM9B,aAAa2B;IACxC,MAAMI,sBAAsBD,aAAaE,MAAM;IAE/C,MAAMC,cAAc,MAAMjC,aACxBF,UAAU8B,IAAI,CAACT,UAAUd,iBAAiB6B,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AAiB,EAAE2D,gBAAgB,GAAG,CAAC,EACtKvF,4BAA4BmE,YAAY;IAE5C;IAEA,IAAIqB,uBAAuBG,wBAAwB;QACjD,MAAM,IAAI9F,iCACR,CAAC,CAAC,EAAEE,iBAAiBwB,QAAQ,CAAC,wBAAwB,EAAEoE,uBAAuB,uBAAuB,EAAE5F,iBAAiB6B,WAAW,CAAC,oBAAoB,EAAE4D,mBAAmB,GAAG,CAAC,EAClLxF,4BAA4BwE,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvDiB,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACvG,UAAUoG,uBAAuBG,qBAClC;QACA,MAAM,IAAI/F,iCACR,CAAC,CAAC,EAAEE,iBAAiBwB,QAAQ,CAAC,yCAAyC,EAAExB,iBAAiB6B,WAAW,CAAC,qBAAqB,CAAC,EAC5H5B,4BAA4ByE,kBAAkB;IAElD;IAEA3E,mBACE;QAAEgC;QAAUf;QAAYkB;IAAQ,GAChC,CAAC,CAAC,EAAElC,iBAAiBwB,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
|
package/dist/esm/snaps.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { Json, SemVerVersion, Opaque } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport type { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { SnapFiles, SnapId, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: ValidatedSnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap & {\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n};\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): string {\n const { manifest, sourceCode, svgIcon } = files;\n const all = [getChecksummableManifest(manifest), sourceCode, svgIcon].filter(\n (file) => file !== undefined,\n );\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"],"names":["assert","isObject","assertStruct","base64","stableStringify","empty","enums","intersection","literal","pattern","refine","string","union","validate","validateNPMPackage","SnapCaveatType","checksumFiles","SnapIdPrefixes","SnapValidationFailureReason","uri","PROPOSED_NAME_REGEX","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","ProgrammaticallyFixableSnapError","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","getSnapChecksum","files","sourceCode","svgIcon","all","filter","file","undefined","encode","validateSnapShasum","errorMessage","ShasumMismatch","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdSubUrlStruct","protocol","hostname","hash","search","LocalSnapIdStruct","startsWith","local","error","slice","length","NpmSnapIdStruct","npm","pathname","normalized","errors","validForNewPackages","warnings","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","snapId","prefix","Object","values","find","possiblePrefix","stripSnapPrefix","replace","assertIsValidSnapId","isCaipChainId","chainId","test","isSnapPermitted","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapIds","verifyRequestedSnapPermissions","requestedPermissions","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;AAOA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,YAAY,QAAQ,kBAAkB;AACjE,SAASC,MAAM,QAAQ,cAAc;AAErC,OAAOC,qBAAqB,6BAA6B;AAEzD,SACEC,KAAK,EACLC,KAAK,EACLC,YAAY,EACZC,OAAO,EACPC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,QAAQ,QACH,cAAc;AACrB,OAAOC,wBAAwB,4BAA4B;AAE3D,SAASC,cAAc,QAAQ,YAAY;AAC3C,SAASC,aAAa,QAAQ,aAAa;AAG3C,SAASC,cAAc,EAAEC,2BAA2B,EAAEC,GAAG,QAAQ,UAAU;AAG3E,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACnI,OAAO,MAAMC,sBACX,mHAAmH;WAW9G;UAAKC,UAAU;IAAVA,WACVC,gBAAa;IADHD,WAEVE,cAAW;IAFDF,WAGVG,aAAU;IAHAH,WAIVI,aAAU;IAJAJ,WAKVK,aAAU;GALAL,eAAAA;WAQL;UAAKM,gBAAgB;IAAhBA,iBACVC,WAAQ;IADED,iBAEVE,UAAO;IAFGF,iBAGVG,WAAQ;IAHEH,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hD,MAAM,CAAC,gCAAgC,EAAE+C,OAAO,CAAC,CAAC;AAC9D;AAEA;;;;;CAKC,GACD,OAAO,SAASM,gBAAgBN,MAAc;IAC5C,OAAOA,OAAOO,OAAO,CAACR,cAAcC,SAAS;AAC/C;AAEA;;;;;CAKC,GACD,OAAO,SAASQ,oBACd5C,KAAc;IAEd1C,aAAa0C,OAAOkC,cAAc;AACpC;AAEA;;;;;CAKC,GACD,OAAO,SAASW,cAAcC,OAAgB;IAC5C,OACE,OAAOA,YAAY,YACnB,+EAAmEC,IAAI,CACrED;AAGN;AAEA;;;;;;CAMC,GACD,OAAO,SAASE,gBACdC,WAAqD,EACrDb,MAAc;IAEd,OAAOc,QAEH,AACGD,CAAAA,aAAaE,aAAaC,SAASZ,KAClC,CAACa,SAAWA,OAAOC,IAAI,KAAKnF,eAAeoF,OAAO,KAC/C,CAAC,CAAA,EACNvD,KAAK,EACN,CAACoC,OAAO;AAEf;AAEA;;;;;;CAMC,GACD,OAAO,SAASoB,+BACdC,oBAA6B;IAE7BrG,OACEC,SAASoG,uBACT;IAGF,MAAM,EAAEN,aAAaO,oBAAoB,EAAE,GAAGD;IAE9CrG,OACEC,SAASqG,uBACT;IAGF,MAAM,EAAEN,OAAO,EAAE,GAAGM;IAEpBtG,OACEuG,MAAMC,OAAO,CAACR,YAAYA,QAAQ3B,MAAM,KAAK,GAC7C;IAGF,MAAM,CAAC4B,OAAO,GAAGD;IAEjBhG,OACEC,SAASgG,WACPA,OAAOC,IAAI,KAAKnF,eAAeoF,OAAO,IACtClG,SAASgG,OAAOrD,KAAK,GACvB,CAAC,8CAA8C,EAAE7B,eAAeoF,OAAO,CAAC,QAAQ,CAAC;AAErF"}
|
|
1
|
+
{"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { Json, SemVerVersion, Opaque } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport type { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { SnapFiles, SnapId, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: ValidatedSnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): string {\n const { manifest, sourceCode, svgIcon } = files;\n const all = [getChecksummableManifest(manifest), sourceCode, svgIcon].filter(\n (file) => file !== undefined,\n );\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"],"names":["assert","isObject","assertStruct","base64","stableStringify","empty","enums","intersection","literal","pattern","refine","string","union","validate","validateNPMPackage","SnapCaveatType","checksumFiles","SnapIdPrefixes","SnapValidationFailureReason","uri","PROPOSED_NAME_REGEX","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","ProgrammaticallyFixableSnapError","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","getSnapChecksum","files","sourceCode","svgIcon","all","filter","file","undefined","encode","validateSnapShasum","errorMessage","ShasumMismatch","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdSubUrlStruct","protocol","hostname","hash","search","LocalSnapIdStruct","startsWith","local","error","slice","length","NpmSnapIdStruct","npm","pathname","normalized","errors","validForNewPackages","warnings","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","snapId","prefix","Object","values","find","possiblePrefix","stripSnapPrefix","replace","assertIsValidSnapId","isCaipChainId","chainId","test","isSnapPermitted","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapIds","verifyRequestedSnapPermissions","requestedPermissions","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;AAOA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,YAAY,QAAQ,kBAAkB;AACjE,SAASC,MAAM,QAAQ,cAAc;AAErC,OAAOC,qBAAqB,6BAA6B;AAEzD,SACEC,KAAK,EACLC,KAAK,EACLC,YAAY,EACZC,OAAO,EACPC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,QAAQ,QACH,cAAc;AACrB,OAAOC,wBAAwB,4BAA4B;AAE3D,SAASC,cAAc,QAAQ,YAAY;AAC3C,SAASC,aAAa,QAAQ,aAAa;AAG3C,SAASC,cAAc,EAAEC,2BAA2B,EAAEC,GAAG,QAAQ,UAAU;AAG3E,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3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KAAKnF,eAAeoF,OAAO,IACtClG,SAASgG,OAAOrD,KAAK,GACvB,CAAC,8CAA8C,EAAE7B,eAAeoF,OAAO,CAAC,QAAQ,CAAC;AAErF"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Indent a message by adding a number of spaces to the beginning of each line.
|
|
3
|
+
*
|
|
4
|
+
* @param message - The message to indent.
|
|
5
|
+
* @param spaces - The number of spaces to indent by. Defaults to 2.
|
|
6
|
+
* @returns The indented message.
|
|
7
|
+
*/ export function indent(message, spaces = 2) {
|
|
8
|
+
return message.replace(/^/gmu, ' '.repeat(spaces));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=strings.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/strings.ts"],"sourcesContent":["/**\n * Indent a message by adding a number of spaces to the beginning of each line.\n *\n * @param message - The message to indent.\n * @param spaces - The number of spaces to indent by. Defaults to 2.\n * @returns The indented message.\n */\nexport function indent(message: string, spaces = 2) {\n return message.replace(/^/gmu, ' '.repeat(spaces));\n}\n"],"names":["indent","message","spaces","replace","repeat"],"mappings":"AAAA;;;;;;CAMC,GACD,OAAO,SAASA,OAAOC,OAAe,EAAEC,SAAS,CAAC;IAChD,OAAOD,QAAQE,OAAO,CAAC,QAAQ,IAAIC,MAAM,CAACF;AAC5C"}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import { isObject } from '@metamask/utils';
|
|
2
|
+
import { bold, green, red } from 'chalk';
|
|
3
|
+
import { resolve } from 'path';
|
|
4
|
+
import { Struct, StructError, define, literal as superstructLiteral, union as superstructUnion, create, string, coerce } from 'superstruct';
|
|
5
|
+
import { indent } from './strings';
|
|
6
|
+
/**
|
|
7
|
+
* A wrapper of `superstruct`'s `literal` struct that also defines the name of
|
|
8
|
+
* the struct as the literal value.
|
|
9
|
+
*
|
|
10
|
+
* This is useful for improving the error messages returned by `superstruct`.
|
|
11
|
+
* For example, instead of returning an error like:
|
|
12
|
+
*
|
|
13
|
+
* ```
|
|
14
|
+
* Expected the value to satisfy a union of `literal | literal`, but received: \"baz\"
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* This struct will return an error like:
|
|
18
|
+
*
|
|
19
|
+
* ```
|
|
20
|
+
* Expected the value to satisfy a union of `"foo" | "bar"`, but received: \"baz\"
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* @param value - The literal value.
|
|
24
|
+
* @returns The `superstruct` struct, which validates that the value is equal
|
|
25
|
+
* to the literal value.
|
|
26
|
+
*/ export function literal(value) {
|
|
27
|
+
return define(JSON.stringify(value), superstructLiteral(value).validator);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* A wrapper of `superstruct`'s `union` struct that also defines the schema as
|
|
31
|
+
* the union of the schemas of the structs.
|
|
32
|
+
*
|
|
33
|
+
* This is useful for improving the error messages returned by `superstruct`.
|
|
34
|
+
*
|
|
35
|
+
* @param structs - The structs to union.
|
|
36
|
+
* @param structs."0" - The first struct.
|
|
37
|
+
* @param structs."1" - The remaining structs.
|
|
38
|
+
* @returns The `superstruct` struct, which validates that the value satisfies
|
|
39
|
+
* one of the structs.
|
|
40
|
+
*/ export function union([head, ...tail]) {
|
|
41
|
+
const struct = superstructUnion([
|
|
42
|
+
head,
|
|
43
|
+
...tail
|
|
44
|
+
]);
|
|
45
|
+
return new Struct({
|
|
46
|
+
...struct,
|
|
47
|
+
schema: [
|
|
48
|
+
head,
|
|
49
|
+
...tail
|
|
50
|
+
]
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* A wrapper of `superstruct`'s `string` struct that coerces a value to a string
|
|
55
|
+
* and resolves it relative to the current working directory. This is useful
|
|
56
|
+
* for specifying file paths in a configuration file, as it allows the user to
|
|
57
|
+
* use both relative and absolute paths.
|
|
58
|
+
*
|
|
59
|
+
* @returns The `superstruct` struct, which validates that the value is a
|
|
60
|
+
* string, and resolves it relative to the current working directory.
|
|
61
|
+
* @example
|
|
62
|
+
* ```ts
|
|
63
|
+
* const config = struct({
|
|
64
|
+
* file: file(),
|
|
65
|
+
* // ...
|
|
66
|
+
* });
|
|
67
|
+
*
|
|
68
|
+
* const value = create({ file: 'path/to/file' }, config);
|
|
69
|
+
* console.log(value.file); // /process/cwd/path/to/file
|
|
70
|
+
* ```
|
|
71
|
+
*/ export function file() {
|
|
72
|
+
return coerce(string(), string(), (value)=>{
|
|
73
|
+
return resolve(process.cwd(), value);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Define a struct, and also define the name of the struct as the given name.
|
|
78
|
+
*
|
|
79
|
+
* This is useful for improving the error messages returned by `superstruct`.
|
|
80
|
+
*
|
|
81
|
+
* @param name - The name of the struct.
|
|
82
|
+
* @param struct - The struct.
|
|
83
|
+
* @returns The struct.
|
|
84
|
+
*/ export function named(name, struct) {
|
|
85
|
+
return new Struct({
|
|
86
|
+
...struct,
|
|
87
|
+
type: name
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
export class SnapsStructError extends StructError {
|
|
91
|
+
constructor(struct, prefix, suffix, failure, failures){
|
|
92
|
+
super(failure, failures);
|
|
93
|
+
this.name = 'SnapsStructError';
|
|
94
|
+
this.message = `${prefix}.\n\n${getStructErrorMessage(struct, [
|
|
95
|
+
...failures()
|
|
96
|
+
])}${suffix ? `\n\n${suffix}` : ''}`;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Converts an array to a generator function that yields the items in the
|
|
101
|
+
* array.
|
|
102
|
+
*
|
|
103
|
+
* @param array - The array.
|
|
104
|
+
* @returns A generator function.
|
|
105
|
+
* @yields The items in the array.
|
|
106
|
+
*/ export function* arrayToGenerator(array) {
|
|
107
|
+
for (const item of array){
|
|
108
|
+
yield item;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Returns a `SnapsStructError` with the given prefix and suffix.
|
|
113
|
+
*
|
|
114
|
+
* @param options - The options.
|
|
115
|
+
* @param options.struct - The struct that caused the error.
|
|
116
|
+
* @param options.prefix - The prefix to add to the error message.
|
|
117
|
+
* @param options.suffix - The suffix to add to the error message. Defaults to
|
|
118
|
+
* an empty string.
|
|
119
|
+
* @param options.error - The `superstruct` error to wrap.
|
|
120
|
+
* @returns The `SnapsStructError`.
|
|
121
|
+
*/ export function getError({ struct, prefix, suffix = '', error }) {
|
|
122
|
+
return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()));
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* A wrapper of `superstruct`'s `create` function that throws a
|
|
126
|
+
* `SnapsStructError` instead of a `StructError`. This is useful for improving
|
|
127
|
+
* the error messages returned by `superstruct`.
|
|
128
|
+
*
|
|
129
|
+
* @param value - The value to validate.
|
|
130
|
+
* @param struct - The `superstruct` struct to validate the value against.
|
|
131
|
+
* @param prefix - The prefix to add to the error message.
|
|
132
|
+
* @param suffix - The suffix to add to the error message. Defaults to an empty
|
|
133
|
+
* string.
|
|
134
|
+
* @returns The validated value.
|
|
135
|
+
*/ export function createFromStruct(value, struct, prefix, suffix = '') {
|
|
136
|
+
try {
|
|
137
|
+
return create(value, struct);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (error instanceof StructError) {
|
|
140
|
+
throw getError({
|
|
141
|
+
struct,
|
|
142
|
+
prefix,
|
|
143
|
+
suffix,
|
|
144
|
+
error
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Get a struct from a failure path.
|
|
152
|
+
*
|
|
153
|
+
* @param struct - The struct.
|
|
154
|
+
* @param path - The failure path.
|
|
155
|
+
* @returns The struct at the failure path.
|
|
156
|
+
*/ export function getStructFromPath(struct, path) {
|
|
157
|
+
return path.reduce((result, key)=>{
|
|
158
|
+
if (isObject(struct.schema) && struct.schema[key]) {
|
|
159
|
+
return struct.schema[key];
|
|
160
|
+
}
|
|
161
|
+
return result;
|
|
162
|
+
}, struct);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Get the union struct names from a struct.
|
|
166
|
+
*
|
|
167
|
+
* @param struct - The struct.
|
|
168
|
+
* @returns The union struct names, or `null` if the struct is not a union
|
|
169
|
+
* struct.
|
|
170
|
+
*/ export function getUnionStructNames(struct) {
|
|
171
|
+
if (Array.isArray(struct.schema)) {
|
|
172
|
+
return struct.schema.map(({ type })=>green(type));
|
|
173
|
+
}
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Get a error prefix from a `superstruct` failure. This is useful for
|
|
178
|
+
* formatting the error message returned by `superstruct`.
|
|
179
|
+
*
|
|
180
|
+
* @param failure - The `superstruct` failure.
|
|
181
|
+
* @returns The error prefix.
|
|
182
|
+
*/ export function getStructErrorPrefix(failure) {
|
|
183
|
+
if (failure.type === 'never' || failure.path.length === 0) {
|
|
184
|
+
return '';
|
|
185
|
+
}
|
|
186
|
+
return `At path: ${bold(failure.path.join('.'))} — `;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Get a string describing the failure. This is similar to the `message`
|
|
190
|
+
* property of `superstruct`'s `Failure` type, but formats the value in a more
|
|
191
|
+
* readable way.
|
|
192
|
+
*
|
|
193
|
+
* @param struct - The struct that caused the failure.
|
|
194
|
+
* @param failure - The `superstruct` failure.
|
|
195
|
+
* @returns A string describing the failure.
|
|
196
|
+
*/ export function getStructFailureMessage(struct, failure) {
|
|
197
|
+
const received = red(JSON.stringify(failure.value));
|
|
198
|
+
const prefix = getStructErrorPrefix(failure);
|
|
199
|
+
if (failure.type === 'union') {
|
|
200
|
+
const childStruct = getStructFromPath(struct, failure.path);
|
|
201
|
+
const unionNames = getUnionStructNames(childStruct);
|
|
202
|
+
if (unionNames) {
|
|
203
|
+
return `${prefix}Expected the value to be one of: ${unionNames.join(', ')}, but received: ${received}.`;
|
|
204
|
+
}
|
|
205
|
+
return `${prefix}${failure.message}.`;
|
|
206
|
+
}
|
|
207
|
+
if (failure.type === 'literal') {
|
|
208
|
+
// Superstruct's failure does not provide information about which literal
|
|
209
|
+
// value was expected, so we need to parse the message to get the literal.
|
|
210
|
+
const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${green('$1')}\`,`).replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);
|
|
211
|
+
return `${prefix}${message}.`;
|
|
212
|
+
}
|
|
213
|
+
if (failure.type === 'never') {
|
|
214
|
+
return `Unknown key: ${bold(failure.path.join('.'))}, received: ${received}.`;
|
|
215
|
+
}
|
|
216
|
+
return `${prefix}Expected a value of type ${green(failure.type)}, but received: ${received}.`;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Get a string describing the errors. This formats all the errors in a
|
|
220
|
+
* human-readable way.
|
|
221
|
+
*
|
|
222
|
+
* @param struct - The struct that caused the failures.
|
|
223
|
+
* @param failures - The `superstruct` failures.
|
|
224
|
+
* @returns A string describing the errors.
|
|
225
|
+
*/ export function getStructErrorMessage(struct, failures) {
|
|
226
|
+
const formattedFailures = failures.map((failure)=>indent(`• ${getStructFailureMessage(struct, failure)}`));
|
|
227
|
+
return formattedFailures.join('\n');
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
//# sourceMappingURL=structs.js.map
|