@metamask/snaps-utils 3.2.0 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -1
- package/dist/cjs/handler-types.js +1 -0
- package/dist/cjs/handler-types.js.map +1 -1
- package/dist/cjs/handlers.js +13 -0
- package/dist/cjs/handlers.js.map +1 -1
- package/dist/cjs/index.browser.js +1 -0
- package/dist/cjs/index.browser.js.map +1 -1
- package/dist/cjs/index.js +1 -7
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/localization.js +113 -0
- package/dist/cjs/localization.js.map +1 -0
- package/dist/cjs/manifest/manifest.js +23 -9
- package/dist/cjs/manifest/manifest.js.map +1 -1
- package/dist/cjs/manifest/validation.js +3 -2
- package/dist/cjs/manifest/validation.js.map +1 -1
- package/dist/cjs/npm.js +16 -3
- package/dist/cjs/npm.js.map +1 -1
- package/dist/cjs/snaps.js.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/cjs/validation.js +2 -0
- package/dist/cjs/validation.js.map +1 -1
- package/dist/esm/handler-types.js +1 -0
- package/dist/esm/handler-types.js.map +1 -1
- package/dist/esm/handlers.js +10 -0
- package/dist/esm/handlers.js.map +1 -1
- package/dist/esm/index.browser.js +1 -0
- package/dist/esm/index.browser.js.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/localization.js +115 -0
- package/dist/esm/localization.js.map +1 -0
- package/dist/esm/manifest/manifest.js +30 -12
- package/dist/esm/manifest/manifest.js.map +1 -1
- package/dist/esm/manifest/validation.js +4 -3
- package/dist/esm/manifest/validation.js.map +1 -1
- package/dist/esm/npm.js +16 -3
- package/dist/esm/npm.js.map +1 -1
- package/dist/esm/snaps.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/esm/validation.js +2 -0
- package/dist/esm/validation.js.map +1 -1
- package/dist/types/handler-types.d.ts +2 -1
- package/dist/types/handlers.d.ts +46 -0
- package/dist/types/index.browser.d.ts +1 -0
- package/dist/types/index.d.ts +1 -1
- package/dist/types/localization.d.ts +143 -0
- package/dist/types/manifest/manifest.d.ts +15 -6
- package/dist/types/manifest/validation.d.ts +3 -0
- package/dist/types/snaps.d.ts +5 -0
- package/dist/types/types.d.ts +4 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [3.3.0]
|
|
10
|
+
### Added
|
|
11
|
+
- Add manifest localization functionality ([#1889](https://github.com/MetaMask/snaps/pull/1889))
|
|
12
|
+
- Add `OnHomePage` export ([#1896](https://github.com/MetaMask/snaps/pull/1896))
|
|
13
|
+
|
|
9
14
|
## [3.2.0]
|
|
10
15
|
### Added
|
|
11
16
|
- Add support for links in custom UI and notifications ([#1814](https://github.com/MetaMask/snaps/pull/1814))
|
|
@@ -71,7 +76,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
71
76
|
- The version of the package no longer needs to match the version of all other
|
|
72
77
|
MetaMask Snaps packages.
|
|
73
78
|
|
|
74
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.
|
|
79
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.3.0...HEAD
|
|
80
|
+
[3.3.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.2.0...@metamask/snaps-utils@3.3.0
|
|
75
81
|
[3.2.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.1.0...@metamask/snaps-utils@3.2.0
|
|
76
82
|
[3.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.0.0...@metamask/snaps-utils@3.1.0
|
|
77
83
|
[3.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@2.0.1...@metamask/snaps-utils@3.0.0
|
|
@@ -25,6 +25,7 @@ var HandlerType;
|
|
|
25
25
|
HandlerType["OnUpdate"] = 'onUpdate';
|
|
26
26
|
HandlerType["OnNameLookup"] = 'onNameLookup';
|
|
27
27
|
HandlerType["OnKeyringRequest"] = 'onKeyringRequest';
|
|
28
|
+
HandlerType["OnHomePage"] = 'onHomePage';
|
|
28
29
|
})(HandlerType || (HandlerType = {}));
|
|
29
30
|
const SNAP_EXPORT_NAMES = Object.values(HandlerType);
|
|
30
31
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/handler-types.ts"],"sourcesContent":["export enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n OnNameLookup = 'onNameLookup',\n OnKeyringRequest = 'onKeyringRequest',\n}\n\nexport type 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_EXPORT_NAMES = Object.values(HandlerType);\n"],"names":["SNAP_EXPORT_NAMES","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnInstall","OnUpdate","OnNameLookup","OnKeyringRequest","Object","values"],"mappings":";;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"sources":["../../src/handler-types.ts"],"sourcesContent":["export enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n OnNameLookup = 'onNameLookup',\n OnKeyringRequest = 'onKeyringRequest',\n OnHomePage = 'onHomePage',\n}\n\nexport type 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_EXPORT_NAMES = Object.values(HandlerType);\n"],"names":["SNAP_EXPORT_NAMES","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnInstall","OnUpdate","OnNameLookup","OnKeyringRequest","OnHomePage","Object","values"],"mappings":";;;;;;;;;;;;;;IAmCaA,iBAAiB;eAAjBA;;;IAnCN;UAAKC,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,mBAAgB;IAFNF,YAGVG,eAAY;IAHFH,YAIVI,eAAY;IAJFJ,YAKVK,cAAW;IALDL,YAMVM,kBAAe;IANLN,YAOVO,sBAAmB;IAPTP,YAQVQ,gBAAa;GARHR,gBAAAA;AAmCL,MAAMD,oBAAoBU,OAAOC,MAAM,CAACV"}
|
package/dist/cjs/handlers.js
CHANGED
|
@@ -17,6 +17,9 @@ _export(exports, {
|
|
|
17
17
|
},
|
|
18
18
|
OnTransactionResponseStruct: function() {
|
|
19
19
|
return OnTransactionResponseStruct;
|
|
20
|
+
},
|
|
21
|
+
OnHomePageResponseStruct: function() {
|
|
22
|
+
return OnHomePageResponseStruct;
|
|
20
23
|
}
|
|
21
24
|
});
|
|
22
25
|
const _snapsui = require("@metamask/snaps-ui");
|
|
@@ -71,6 +74,13 @@ const SNAP_EXPORTS = {
|
|
|
71
74
|
validator: (snapExport)=>{
|
|
72
75
|
return typeof snapExport === 'function';
|
|
73
76
|
}
|
|
77
|
+
},
|
|
78
|
+
[_handlertypes.HandlerType.OnHomePage]: {
|
|
79
|
+
type: _handlertypes.HandlerType.OnHomePage,
|
|
80
|
+
required: true,
|
|
81
|
+
validator: (snapExport)=>{
|
|
82
|
+
return typeof snapExport === 'function';
|
|
83
|
+
}
|
|
74
84
|
}
|
|
75
85
|
};
|
|
76
86
|
var SeverityLevel;
|
|
@@ -81,5 +91,8 @@ const OnTransactionResponseStruct = (0, _superstruct.object)({
|
|
|
81
91
|
content: _snapsui.ComponentStruct,
|
|
82
92
|
severity: (0, _superstruct.optional)((0, _superstruct.literal)(SeverityLevel.Critical))
|
|
83
93
|
});
|
|
94
|
+
const OnHomePageResponseStruct = (0, _superstruct.object)({
|
|
95
|
+
content: _snapsui.ComponentStruct
|
|
96
|
+
});
|
|
84
97
|
|
|
85
98
|
//# sourceMappingURL=handlers.js.map
|
package/dist/cjs/handlers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import { ComponentStruct } from '@metamask/snaps-ui';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport { literal, object, optional } from 'superstruct';\n\nimport type { SnapHandler } from './handler-types';\nimport { HandlerType } from './handler-types';\nimport type { AccountAddress, Caip2ChainId } from './namespace';\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\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.OnNameLookup]: {\n type: HandlerType.OnNameLookup,\n required: true,\n validator: (snapExport: unknown): snapExport is OnNameLookupHandler => {\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 [HandlerType.OnKeyringRequest]: {\n type: HandlerType.OnKeyringRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnKeyringRequestHandler => {\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 * Enum used to specify the severity level of content being returned from a transaction insight.\n */\nexport enum SeverityLevel {\n Critical = 'critical',\n}\n\nexport const OnTransactionResponseStruct = object({\n content: ComponentStruct,\n severity: optional(literal(SeverityLevel.Critical)),\n});\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 = Infer<typeof OnTransactionResponseStruct>;\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 * The `onKeyringRequest` handler. This is called by the MetaMask client for\n * privileged keyring actions.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of\n * another snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n */\nexport type OnKeyringRequestHandler<\n Params extends JsonRpcParams = JsonRpcParams,\n> = (args: {\n origin: string;\n request: JsonRpcRequest<Params>;\n}) => Promise<unknown>;\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 * The response from a snap's `onNameLookup` handler.\n *\n * @property resolvedAddress - The resolved address for a given domain.\n * @property resolvedDomain - The resolved domain for a given address.\n *\n *\n * If the snap has no resolved address/domain from its lookup, this should be `null`.\n */\nexport type OnNameLookupResponse =\n | {\n resolvedAddress: AccountAddress;\n resolvedDomain?: never;\n }\n | { resolvedDomain: string; resolvedAddress?: never }\n | null;\n\nexport type OnNameLookupArgs = {\n chainId: Caip2ChainId;\n} & ({ domain: string; address?: never } | { address: string; domain?: never });\n\n/**\n * The `onNameLookup` handler. This is called whenever content is entered\n * into the send to field for sending assets to an EOA address.\n *\n * @param args - The request arguments.\n * @param args.domain - The human-readable address that is to be resolved.\n * @param args.chainId - The CAIP-2 chain ID of the network the transaction is\n * being submitted to.\n * @param args.address - The address that is to be resolved.\n * @returns Resolved address/domain from the lookup. See {@link OnNameLookupResponse}.\n */\nexport type OnNameLookupHandler = (\n args: OnNameLookupArgs,\n) => Promise<OnNameLookupResponse>;\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":["SNAP_EXPORTS","OnTransactionResponseStruct","HandlerType","OnRpcRequest","type","required","validator","snapExport","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","SeverityLevel","Critical","object","content","ComponentStruct","severity","optional","literal"],"mappings":";;;;;;;;;;;;;;IAeaA,YAAY;eAAZA;;
|
|
1
|
+
{"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import { ComponentStruct } from '@metamask/snaps-ui';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport { literal, object, optional } from 'superstruct';\n\nimport type { SnapHandler } from './handler-types';\nimport { HandlerType } from './handler-types';\nimport type { AccountAddress, Caip2ChainId } from './namespace';\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\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.OnNameLookup]: {\n type: HandlerType.OnNameLookup,\n required: true,\n validator: (snapExport: unknown): snapExport is OnNameLookupHandler => {\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 [HandlerType.OnKeyringRequest]: {\n type: HandlerType.OnKeyringRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnKeyringRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnHomePage]: {\n type: HandlerType.OnHomePage,\n required: true,\n validator: (snapExport: unknown): snapExport is OnHomePageHandler => {\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 * Enum used to specify the severity level of content being returned from a transaction insight.\n */\nexport enum SeverityLevel {\n Critical = 'critical',\n}\n\nexport const OnTransactionResponseStruct = object({\n content: ComponentStruct,\n severity: optional(literal(SeverityLevel.Critical)),\n});\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 = Infer<typeof OnTransactionResponseStruct>;\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 * The `onKeyringRequest` handler. This is called by the MetaMask client for\n * privileged keyring actions.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of\n * another snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n */\nexport type OnKeyringRequestHandler<\n Params extends JsonRpcParams = JsonRpcParams,\n> = (args: {\n origin: string;\n request: JsonRpcRequest<Params>;\n}) => Promise<unknown>;\n\nexport type OnHomePageHandler = () => Promise<OnHomePageResponse>;\n\nexport const OnHomePageResponseStruct = object({\n content: ComponentStruct,\n});\n\nexport type OnHomePageResponse = Infer<typeof OnHomePageResponseStruct>;\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 * The response from a snap's `onNameLookup` handler.\n *\n * @property resolvedAddress - The resolved address for a given domain.\n * @property resolvedDomain - The resolved domain for a given address.\n *\n *\n * If the snap has no resolved address/domain from its lookup, this should be `null`.\n */\nexport type OnNameLookupResponse =\n | {\n resolvedAddress: AccountAddress;\n resolvedDomain?: never;\n }\n | { resolvedDomain: string; resolvedAddress?: never }\n | null;\n\nexport type OnNameLookupArgs = {\n chainId: Caip2ChainId;\n} & ({ domain: string; address?: never } | { address: string; domain?: never });\n\n/**\n * The `onNameLookup` handler. This is called whenever content is entered\n * into the send to field for sending assets to an EOA address.\n *\n * @param args - The request arguments.\n * @param args.domain - The human-readable address that is to be resolved.\n * @param args.chainId - The CAIP-2 chain ID of the network the transaction is\n * being submitted to.\n * @param args.address - The address that is to be resolved.\n * @returns Resolved address/domain from the lookup. See {@link OnNameLookupResponse}.\n */\nexport type OnNameLookupHandler = (\n args: OnNameLookupArgs,\n) => Promise<OnNameLookupResponse>;\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":["SNAP_EXPORTS","OnTransactionResponseStruct","OnHomePageResponseStruct","HandlerType","OnRpcRequest","type","required","validator","snapExport","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","OnHomePage","SeverityLevel","Critical","object","content","ComponentStruct","severity","optional","literal"],"mappings":";;;;;;;;;;;;;;IAeaA,YAAY;eAAZA;;IAkFAC,2BAA2B;eAA3BA;;IAmFAC,wBAAwB;eAAxBA;;;yBApLmB;6BAGU;8BAGd;AASrB,MAAMF,eAAe;IAC1B,CAACG,yBAAW,CAACC,YAAY,CAAC,EAAE;QAC1BC,MAAMF,yBAAW,CAACC,YAAY;QAC9BE,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACM,aAAa,CAAC,EAAE;QAC3BJ,MAAMF,yBAAW,CAACM,aAAa;QAC/BH,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACO,SAAS,CAAC,EAAE;QACvBL,MAAMF,yBAAW,CAACO,SAAS;QAC3BJ,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACQ,YAAY,CAAC,EAAE;QAC1BN,MAAMF,yBAAW,CAACQ,YAAY;QAC9BL,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACS,SAAS,CAAC,EAAE;QACvBP,MAAMF,yBAAW,CAACS,SAAS;QAC3BN,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACU,QAAQ,CAAC,EAAE;QACtBR,MAAMF,yBAAW,CAACU,QAAQ;QAC1BP,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACW,gBAAgB,CAAC,EAAE;QAC9BT,MAAMF,yBAAW,CAACW,gBAAgB;QAClCR,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACY,UAAU,CAAC,EAAE;QACxBV,MAAMF,yBAAW,CAACY,UAAU;QAC5BT,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;AACF;IAqBO;UAAKQ,aAAa;IAAbA,cACVC,cAAW;GADDD,kBAAAA;AAIL,MAAMf,8BAA8BiB,IAAAA,mBAAM,EAAC;IAChDC,SAASC,wBAAe;IACxBC,UAAUC,IAAAA,qBAAQ,EAACC,IAAAA,oBAAO,EAACP,cAAcC,QAAQ;AACnD;AAgFO,MAAMf,2BAA2BgB,IAAAA,mBAAM,EAAC;IAC7CC,SAASC,wBAAe;AAC1B"}
|
|
@@ -17,6 +17,7 @@ _export_star(require("./handler-types"), exports);
|
|
|
17
17
|
_export_star(require("./iframe"), exports);
|
|
18
18
|
_export_star(require("./json"), exports);
|
|
19
19
|
_export_star(require("./json-rpc"), exports);
|
|
20
|
+
_export_star(require("./localization"), exports);
|
|
20
21
|
_export_star(require("./logging"), exports);
|
|
21
22
|
_export_star(require("./manifest/index.browser"), exports);
|
|
22
23
|
_export_star(require("./namespace"), exports);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\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 './handler-types';\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":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
|
|
1
|
+
{"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\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 './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\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":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
|
package/dist/cjs/index.js
CHANGED
|
@@ -2,12 +2,6 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", {
|
|
3
3
|
value: true
|
|
4
4
|
});
|
|
5
|
-
Object.defineProperty(exports, "assertLinksAreSafe", {
|
|
6
|
-
enumerable: true,
|
|
7
|
-
get: function() {
|
|
8
|
-
return _snapsui.assertLinksAreSafe;
|
|
9
|
-
}
|
|
10
|
-
});
|
|
11
5
|
_export_star(require("./array"), exports);
|
|
12
6
|
_export_star(require("./auxiliary-files"), exports);
|
|
13
7
|
_export_star(require("./caveats"), exports);
|
|
@@ -25,6 +19,7 @@ _export_star(require("./handler-types"), exports);
|
|
|
25
19
|
_export_star(require("./iframe"), exports);
|
|
26
20
|
_export_star(require("./json"), exports);
|
|
27
21
|
_export_star(require("./json-rpc"), exports);
|
|
22
|
+
_export_star(require("./localization"), exports);
|
|
28
23
|
_export_star(require("./logging"), exports);
|
|
29
24
|
_export_star(require("./manifest"), exports);
|
|
30
25
|
_export_star(require("./mock"), exports);
|
|
@@ -39,7 +34,6 @@ _export_star(require("./types"), exports);
|
|
|
39
34
|
_export_star(require("./validation"), exports);
|
|
40
35
|
_export_star(require("./versions"), exports);
|
|
41
36
|
_export_star(require("./virtual-file"), exports);
|
|
42
|
-
const _snapsui = require("@metamask/snaps-ui");
|
|
43
37
|
function _export_star(from, to) {
|
|
44
38
|
Object.keys(from).forEach(function(k) {
|
|
45
39
|
if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) {
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\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 './handler-types';\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';\
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\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 './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\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":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
LOCALIZABLE_FIELDS: function() {
|
|
13
|
+
return LOCALIZABLE_FIELDS;
|
|
14
|
+
},
|
|
15
|
+
LocalizationFileStruct: function() {
|
|
16
|
+
return LocalizationFileStruct;
|
|
17
|
+
},
|
|
18
|
+
getValidatedLocalizationFiles: function() {
|
|
19
|
+
return getValidatedLocalizationFiles;
|
|
20
|
+
},
|
|
21
|
+
getLocalizationFile: function() {
|
|
22
|
+
return getLocalizationFile;
|
|
23
|
+
},
|
|
24
|
+
TRANSLATION_REGEX: function() {
|
|
25
|
+
return TRANSLATION_REGEX;
|
|
26
|
+
},
|
|
27
|
+
translate: function() {
|
|
28
|
+
return translate;
|
|
29
|
+
},
|
|
30
|
+
getLocalizedSnapManifest: function() {
|
|
31
|
+
return getLocalizedSnapManifest;
|
|
32
|
+
},
|
|
33
|
+
validateSnapManifestLocalizations: function() {
|
|
34
|
+
return validateSnapManifestLocalizations;
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
const _superstruct = require("superstruct");
|
|
38
|
+
const _errors = require("./errors");
|
|
39
|
+
const _json = require("./json");
|
|
40
|
+
const LOCALIZABLE_FIELDS = [
|
|
41
|
+
'description',
|
|
42
|
+
'proposedName'
|
|
43
|
+
];
|
|
44
|
+
const LocalizationFileStruct = (0, _superstruct.object)({
|
|
45
|
+
locale: (0, _superstruct.string)(),
|
|
46
|
+
messages: (0, _superstruct.record)((0, _superstruct.string)(), (0, _superstruct.object)({
|
|
47
|
+
message: (0, _superstruct.string)(),
|
|
48
|
+
description: (0, _superstruct.optional)((0, _superstruct.string)())
|
|
49
|
+
}))
|
|
50
|
+
});
|
|
51
|
+
function getValidatedLocalizationFiles(localizationFiles) {
|
|
52
|
+
for (const file of localizationFiles){
|
|
53
|
+
try {
|
|
54
|
+
file.result = (0, _superstruct.create)((0, _json.parseJson)(file.toString()), LocalizationFileStruct);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error instanceof _superstruct.StructError) {
|
|
57
|
+
throw new Error(`Failed to validate localization file "${file.path}": ${error.message}.`);
|
|
58
|
+
}
|
|
59
|
+
if (error instanceof SyntaxError) {
|
|
60
|
+
throw new Error(`Failed to parse localization file "${file.path}" as JSON.`);
|
|
61
|
+
}
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return localizationFiles;
|
|
66
|
+
}
|
|
67
|
+
function getLocalizationFile(locale, localizationFiles) {
|
|
68
|
+
const file = localizationFiles.find((localizationFile)=>localizationFile.locale === locale);
|
|
69
|
+
if (!file) {
|
|
70
|
+
return localizationFiles.find((localizationFile)=>localizationFile.locale === 'en');
|
|
71
|
+
}
|
|
72
|
+
return file;
|
|
73
|
+
}
|
|
74
|
+
const TRANSLATION_REGEX = /\{\{\s?([a-zA-Z0-9-_\s]+)\s?\}\}/gu;
|
|
75
|
+
function translate(value, file) {
|
|
76
|
+
const matches = value.matchAll(TRANSLATION_REGEX);
|
|
77
|
+
const array = Array.from(matches);
|
|
78
|
+
return array.reduce((result, [match, key])=>{
|
|
79
|
+
if (!file) {
|
|
80
|
+
throw new Error(`Failed to translate "${value}": No localization file found.`);
|
|
81
|
+
}
|
|
82
|
+
const translation = file.messages[key.trim()];
|
|
83
|
+
if (!translation) {
|
|
84
|
+
throw new Error(`Failed to translate "${value}": No translation found for "${key.trim()}" in "${file.locale}" file.`);
|
|
85
|
+
}
|
|
86
|
+
return result.replace(match, translation.message);
|
|
87
|
+
}, value);
|
|
88
|
+
}
|
|
89
|
+
function getLocalizedSnapManifest(snapManifest, locale, localizationFiles) {
|
|
90
|
+
const file = getLocalizationFile(locale, localizationFiles);
|
|
91
|
+
return LOCALIZABLE_FIELDS.reduce((manifest, field)=>{
|
|
92
|
+
const translation = translate(manifest[field], file);
|
|
93
|
+
return {
|
|
94
|
+
...manifest,
|
|
95
|
+
[field]: translation
|
|
96
|
+
};
|
|
97
|
+
}, snapManifest);
|
|
98
|
+
}
|
|
99
|
+
function validateSnapManifestLocalizations(snapManifest, localizationFiles) {
|
|
100
|
+
try {
|
|
101
|
+
// `translate` throws if the manifest cannot be localized, so we just attempt
|
|
102
|
+
// to translate the manifest using all localization files.
|
|
103
|
+
localizationFiles.filter((file)=>file.locale !== 'en').forEach((file)=>{
|
|
104
|
+
getLocalizedSnapManifest(snapManifest, file.locale, localizationFiles);
|
|
105
|
+
});
|
|
106
|
+
// The manifest must be localizable in English.
|
|
107
|
+
getLocalizedSnapManifest(snapManifest, 'en', localizationFiles);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
throw new Error(`Failed to localize Snap manifest: ${(0, _errors.getErrorMessage)(error)}`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
//# sourceMappingURL=localization.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/localization.ts"],"sourcesContent":["import type { Infer } from 'superstruct';\nimport {\n create,\n object,\n optional,\n record,\n string,\n StructError,\n} from 'superstruct';\n\nimport { getErrorMessage } from './errors';\nimport { parseJson } from './json';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport const LOCALIZABLE_FIELDS = ['description', 'proposedName'] as const;\n\nexport const LocalizationFileStruct = object({\n locale: string(),\n messages: record(\n string(),\n object({\n message: string(),\n description: optional(string()),\n }),\n ),\n});\n\nexport type LocalizationFile = Infer<typeof LocalizationFileStruct>;\n\n/**\n * Validate a list of localization files.\n *\n * @param localizationFiles - The localization files to validate.\n * @returns The validated localization files.\n * @throws If any of the files are considered invalid.\n */\nexport function getValidatedLocalizationFiles(\n localizationFiles: VirtualFile[],\n): VirtualFile<LocalizationFile>[] {\n for (const file of localizationFiles) {\n try {\n file.result = create(parseJson(file.toString()), LocalizationFileStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Failed to validate localization file \"${file.path}\": ${error.message}.`,\n );\n }\n\n if (error instanceof SyntaxError) {\n throw new Error(\n `Failed to parse localization file \"${file.path}\" as JSON.`,\n );\n }\n\n throw error;\n }\n }\n\n return localizationFiles as VirtualFile<LocalizationFile>[];\n}\n\n/**\n * Get the localization file for a given locale. If the locale is not found,\n * the English localization file will be returned.\n *\n * @param locale - The locale to use.\n * @param localizationFiles - The localization files to use.\n * @returns The localization file, or `undefined` if no localization file was\n * found.\n */\nexport function getLocalizationFile(\n locale: string,\n localizationFiles: LocalizationFile[],\n) {\n const file = localizationFiles.find(\n (localizationFile) => localizationFile.locale === locale,\n );\n\n if (!file) {\n return localizationFiles.find(\n (localizationFile) => localizationFile.locale === 'en',\n );\n }\n\n return file;\n}\n\nexport const TRANSLATION_REGEX = /\\{\\{\\s?([a-zA-Z0-9-_\\s]+)\\s?\\}\\}/gu;\n\n/**\n * Translate a string using a localization file. This will replace all instances\n * of `{{key}}` with the localized version of `key`.\n *\n * @param value - The string to translate.\n * @param file - The localization file to use, or `undefined` if no localization\n * file was found.\n * @returns The translated string.\n * @throws If the string contains a key that is not present in the localization\n * file, or if no localization file was found.\n */\nexport function translate(value: string, file: LocalizationFile | undefined) {\n const matches = value.matchAll(TRANSLATION_REGEX);\n const array = Array.from(matches);\n\n return array.reduce<string>((result, [match, key]) => {\n if (!file) {\n throw new Error(\n `Failed to translate \"${value}\": No localization file found.`,\n );\n }\n\n const translation = file.messages[key.trim()];\n if (!translation) {\n throw new Error(\n `Failed to translate \"${value}\": No translation found for \"${key.trim()}\" in \"${\n file.locale\n }\" file.`,\n );\n }\n\n return result.replace(match, translation.message);\n }, value);\n}\n\n/**\n * Get the localized Snap manifest for a given locale. This will replace all\n * localized strings in the manifest with the localized version.\n *\n * @param snapManifest - The Snap manifest to localize.\n * @param locale - The locale to use.\n * @param localizationFiles - The localization files to use.\n * @returns The localized Snap manifest.\n */\nexport function getLocalizedSnapManifest(\n snapManifest: SnapManifest,\n locale: string,\n localizationFiles: LocalizationFile[],\n) {\n const file = getLocalizationFile(locale, localizationFiles);\n\n return LOCALIZABLE_FIELDS.reduce((manifest, field) => {\n const translation = translate(manifest[field], file);\n return {\n ...manifest,\n [field]: translation,\n };\n }, snapManifest);\n}\n\n/**\n * Validate the localization files for a Snap manifest.\n *\n * @param snapManifest - The Snap manifest to validate.\n * @param localizationFiles - The localization files to validate.\n * @throws If the manifest cannot be localized.\n */\nexport function validateSnapManifestLocalizations(\n snapManifest: SnapManifest,\n localizationFiles: LocalizationFile[],\n) {\n try {\n // `translate` throws if the manifest cannot be localized, so we just attempt\n // to translate the manifest using all localization files.\n localizationFiles\n .filter((file) => file.locale !== 'en')\n .forEach((file) => {\n getLocalizedSnapManifest(snapManifest, file.locale, localizationFiles);\n });\n\n // The manifest must be localizable in English.\n getLocalizedSnapManifest(snapManifest, 'en', localizationFiles);\n } catch (error) {\n throw new Error(\n `Failed to localize Snap manifest: ${getErrorMessage(error)}`,\n );\n }\n}\n"],"names":["LOCALIZABLE_FIELDS","LocalizationFileStruct","getValidatedLocalizationFiles","getLocalizationFile","TRANSLATION_REGEX","translate","getLocalizedSnapManifest","validateSnapManifestLocalizations","object","locale","string","messages","record","message","description","optional","localizationFiles","file","result","create","parseJson","toString","error","StructError","Error","path","SyntaxError","find","localizationFile","value","matches","matchAll","array","Array","from","reduce","match","key","translation","trim","replace","snapManifest","manifest","field","filter","forEach","getErrorMessage"],"mappings":";;;;;;;;;;;IAeaA,kBAAkB;eAAlBA;;IAEAC,sBAAsB;eAAtBA;;IAoBGC,6BAA6B;eAA7BA;;IAmCAC,mBAAmB;eAAnBA;;IAiBHC,iBAAiB;eAAjBA;;IAaGC,SAAS;eAATA;;IAiCAC,wBAAwB;eAAxBA;;IAuBAC,iCAAiC;eAAjCA;;;6BAtJT;wBAEyB;sBACN;AAInB,MAAMP,qBAAqB;IAAC;IAAe;CAAe;AAE1D,MAAMC,yBAAyBO,IAAAA,mBAAM,EAAC;IAC3CC,QAAQC,IAAAA,mBAAM;IACdC,UAAUC,IAAAA,mBAAM,EACdF,IAAAA,mBAAM,KACNF,IAAAA,mBAAM,EAAC;QACLK,SAASH,IAAAA,mBAAM;QACfI,aAAaC,IAAAA,qBAAQ,EAACL,IAAAA,mBAAM;IAC9B;AAEJ;AAWO,SAASR,8BACdc,iBAAgC;IAEhC,KAAK,MAAMC,QAAQD,kBAAmB;QACpC,IAAI;YACFC,KAAKC,MAAM,GAAGC,IAAAA,mBAAM,EAACC,IAAAA,eAAS,EAACH,KAAKI,QAAQ,KAAKpB;QACnD,EAAE,OAAOqB,OAAO;YACd,IAAIA,iBAAiBC,wBAAW,EAAE;gBAChC,MAAM,IAAIC,MACR,CAAC,sCAAsC,EAAEP,KAAKQ,IAAI,CAAC,GAAG,EAAEH,MAAMT,OAAO,CAAC,CAAC,CAAC;YAE5E;YAEA,IAAIS,iBAAiBI,aAAa;gBAChC,MAAM,IAAIF,MACR,CAAC,mCAAmC,EAAEP,KAAKQ,IAAI,CAAC,UAAU,CAAC;YAE/D;YAEA,MAAMH;QACR;IACF;IAEA,OAAON;AACT;AAW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AA0D;QAC1DA,kBACG4B,MAAM,CAAC,CAAC3B,OAASA,KAAKR,MAAM,KAAK,MACjCoC,OAAO,CAAC,CAAC5B;YACRX,yBAAyBmC,cAAcxB,KAAKR,MAAM,EAAEO;QACtD;QAEF,+CAA+C;QAC/CV,yBAAyBmC,cAAc,MAAMzB;IAC/C,EAAE,OAAOM,OAAO;QACd,MAAM,IAAIE,MACR,CAAC,kCAAkC,EAAEsB,IAAAA,uBAAe,EAACxB,OAAO,CAAC;IAEjE;AACF"}
|
|
@@ -21,8 +21,11 @@ _export(exports, {
|
|
|
21
21
|
getSnapIcon: function() {
|
|
22
22
|
return getSnapIcon;
|
|
23
23
|
},
|
|
24
|
-
|
|
25
|
-
return
|
|
24
|
+
getSnapFilePaths: function() {
|
|
25
|
+
return getSnapFilePaths;
|
|
26
|
+
},
|
|
27
|
+
getSnapFiles: function() {
|
|
28
|
+
return getSnapFiles;
|
|
26
29
|
},
|
|
27
30
|
getWritableManifest: function() {
|
|
28
31
|
return getWritableManifest;
|
|
@@ -65,12 +68,15 @@ async function checkManifest(basePath, writeManifest = true, sourceCode, writeFi
|
|
|
65
68
|
const manifestFile = await (0, _fs1.readJsonFile)(manifestPath);
|
|
66
69
|
const unvalidatedManifest = manifestFile.result;
|
|
67
70
|
const packageFile = await (0, _fs1.readJsonFile)(_path.default.join(basePath, _types.NpmSnapFileNames.PackageJson));
|
|
71
|
+
const auxiliaryFilePaths = getSnapFilePaths(unvalidatedManifest, (manifest)=>manifest?.source?.files);
|
|
72
|
+
const localizationFilePaths = getSnapFilePaths(unvalidatedManifest, (manifest)=>manifest?.source?.locales);
|
|
68
73
|
const snapFiles = {
|
|
69
74
|
manifest: manifestFile,
|
|
70
75
|
packageJson: packageFile,
|
|
71
76
|
sourceCode: await getSnapSourceCode(basePath, unvalidatedManifest, sourceCode),
|
|
72
77
|
svgIcon: await getSnapIcon(basePath, unvalidatedManifest),
|
|
73
|
-
auxiliaryFiles: await
|
|
78
|
+
auxiliaryFiles: await getSnapFiles(basePath, auxiliaryFilePaths) ?? [],
|
|
79
|
+
localizationFiles: await getSnapFiles(basePath, localizationFilePaths) ?? []
|
|
74
80
|
};
|
|
75
81
|
let manifest;
|
|
76
82
|
try {
|
|
@@ -204,16 +210,23 @@ async function getSnapIcon(basePath, manifest) {
|
|
|
204
210
|
throw new Error(`Failed to read snap icon file: ${(0, _errors.getErrorMessage)(error)}`);
|
|
205
211
|
}
|
|
206
212
|
}
|
|
207
|
-
|
|
213
|
+
function getSnapFilePaths(manifest, selector) {
|
|
208
214
|
if (!(0, _utils.isPlainObject)(manifest)) {
|
|
209
215
|
return undefined;
|
|
210
216
|
}
|
|
211
|
-
const
|
|
212
|
-
|
|
217
|
+
const snapManifest = manifest;
|
|
218
|
+
const paths = selector(snapManifest);
|
|
219
|
+
if (!Array.isArray(paths)) {
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
return paths;
|
|
223
|
+
}
|
|
224
|
+
async function getSnapFiles(basePath, paths) {
|
|
225
|
+
if (!paths) {
|
|
213
226
|
return undefined;
|
|
214
227
|
}
|
|
215
228
|
try {
|
|
216
|
-
return await Promise.all(
|
|
229
|
+
return await Promise.all(paths.map(async (filePath)=>(0, _virtualfile.readVirtualFile)(_path.default.join(basePath, filePath), 'utf8')));
|
|
217
230
|
} catch (error) {
|
|
218
231
|
throw new Error(`Failed to read snap files: ${(0, _errors.getErrorMessage)(error)}`);
|
|
219
232
|
}
|
|
@@ -230,7 +243,7 @@ function getWritableManifest(manifest) {
|
|
|
230
243
|
}), {});
|
|
231
244
|
return writableManifest;
|
|
232
245
|
}
|
|
233
|
-
function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles }) {
|
|
246
|
+
function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles, localizationFiles }) {
|
|
234
247
|
const packageJsonName = packageJson.result.name;
|
|
235
248
|
const packageJsonVersion = packageJson.result.version;
|
|
236
249
|
const packageJsonRepository = packageJson.result.repository;
|
|
@@ -252,7 +265,8 @@ function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, a
|
|
|
252
265
|
manifest,
|
|
253
266
|
sourceCode,
|
|
254
267
|
svgIcon,
|
|
255
|
-
auxiliaryFiles
|
|
268
|
+
auxiliaryFiles,
|
|
269
|
+
localizationFiles
|
|
256
270
|
}, `"${_types.NpmSnapFileNames.Manifest}" "shasum" field does not match computed shasum.`);
|
|
257
271
|
}
|
|
258
272
|
|
|
@@ -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 { getErrorMessage } from '../errors';\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 auxiliaryFiles:\n (await getSnapAuxiliaryFiles(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(\n `Failed to read snap bundle file: ${getErrorMessage(error)}`,\n );\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: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the auxiliary files\n * and read them.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns A list of auxiliary files and their contents, if any.\n */\nexport async function getSnapAuxiliaryFiles(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile[] | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const filePaths = (manifest as Partial<SnapManifest>).source?.files;\n\n if (!filePaths) {\n return undefined;\n }\n\n try {\n return await Promise.all(\n filePaths.map(async (filePath) =>\n readVirtualFile(pathUtils.join(basePath, filePath), 'utf8'),\n ),\n );\n } catch (error) {\n throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);\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 * @param snapFiles.auxiliaryFiles - Any auxiliary files required by the snap at runtime.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\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, auxiliaryFiles },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["checkManifest","fixManifest","getSnapSourceCode","getSnapIcon","getSnapAuxiliaryFiles","getWritableManifest","validateNpmSnapManifest","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","basePath","writeManifest","sourceCode","writeFileFn","fs","writeFile","warnings","errors","updated","manifestPath","pathUtils","join","NpmSnapFileNames","Manifest","manifestFile","readJsonFile","unvalidatedManifest","result","packageFile","PackageJson","snapFiles","manifest","packageJson","svgIcon","auxiliaryFiles","validateNpmSnap","error","ProgrammaticallyFixableSnapError","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","SnapValidationFailureReason","length","attempts","nextValidationError","Error","assert","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","deepClone","undefined","ShasumMismatch","shasum","getSnapChecksum","assertExhaustive","isPlainObject","sourceFilePath","filePath","VirtualFile","path","virtualFile","readVirtualFile","getErrorMessage","iconPath","filePaths","files","Promise","all","map","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository","deepEqual","validateSnapShasum"],"mappings":";;;;;;;;;;;IAkEsBA,aAAa;eAAbA;;IA+INC,WAAW;eAAXA;;IA8CMC,iBAAiB;eAAjBA;;IA4CAC,WAAW;eAAXA;;IAkCAC,qBAAqB;eAArBA;;IAgCNC,mBAAmB;eAAnBA;;IA+BAC,uBAAuB;eAAvBA;;;uBA3YwC;sEAClC;oBACS;6DACT;2BAEI;wBACM;qBACH;qBACG;uBAKzB;uBAEuD;6BACjB;;;;;;AAG7C,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc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,MAAM,IAAInE,uCAAgC,CACxC,CAAC,CAAC,EAAEf,uBAAgB,CAACC,QAAQ,CAAC,wBAAwB,EAAEiF,uBAAuB,uBAAuB,EAAElF,uBAAgB,CAACO,WAAW,CAAC,oBAAoB,EAAEwE,mBAAmB,GAAG,CAAC,EAClLvD,kCAA2B,CAAC2B,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvD6B,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACC,IAAAA,sBAAS,EAACJ,uBAAuBG,qBAClC;QACA,MAAM,IAAIpE,uCAAgC,CACxC,CAAC,CAAC,EAAEf,uBAAgB,CAACC,QAAQ,CAAC,yCAAyC,EAAED,uBAAgB,CAACO,WAAW,CAAC,qBAAqB,CAAC,EAC5HiB,kCAA2B,CAAC4B,kBAAkB;IAElD;IAEAiC,IAAAA,yBAAkB,EAChB;QAAE5E;QAAUnB;QAAYqB;QAASC;IAAe,GAChD,CAAC,CAAC,EAAEZ,uBAAgB,CAACC,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 { getErrorMessage } from '../errors';\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 auxiliaryFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.files,\n );\n\n const localizationFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.locales,\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 auxiliaryFiles: (await getSnapFiles(basePath, auxiliaryFilePaths)) ?? [],\n localizationFiles:\n (await getSnapFiles(basePath, localizationFilePaths)) ?? [],\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(\n `Failed to read snap bundle file: ${getErrorMessage(error)}`,\n );\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: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Get an array of paths from an unvalidated Snap manifest.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param selector - A function that returns the paths to the files.\n * @returns The paths to the files, if any.\n */\nexport function getSnapFilePaths(\n manifest: Json,\n selector: (manifest: Partial<SnapManifest>) => string[] | undefined,\n) {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const snapManifest = manifest as Partial<SnapManifest>;\n const paths = selector(snapManifest);\n\n if (!Array.isArray(paths)) {\n return undefined;\n }\n\n return paths;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the files with the\n * given paths and read them.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param paths - The paths to the files.\n * @returns A list of auxiliary files and their contents, if any.\n */\nexport async function getSnapFiles(\n basePath: string,\n paths: string[] | undefined,\n): Promise<VirtualFile[] | undefined> {\n if (!paths) {\n return undefined;\n }\n\n try {\n return await Promise.all(\n paths.map(async (filePath) =>\n readVirtualFile(pathUtils.join(basePath, filePath), 'utf8'),\n ),\n );\n } catch (error) {\n throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);\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 * @param snapFiles.auxiliaryFiles - Any auxiliary files required by the snap at runtime.\n * @param snapFiles.localizationFiles - The Snap's localization files.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\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, auxiliaryFiles, localizationFiles },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["checkManifest","fixManifest","getSnapSourceCode","getSnapIcon","getSnapFilePaths","getSnapFiles","getWritableManifest","validateNpmSnapManifest","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","basePath","writeManifest","sourceCode","writeFileFn","fs","writeFile","warnings","errors","updated","manifestPath","pathUtils","join","NpmSnapFileNames","Manifest","manifestFile","readJsonFile","unvalidatedManifest","result","packageFile","PackageJson","auxiliaryFilePaths","manifest","files","localizationFilePaths","locales","snapFiles","packageJson","svgIcon","auxiliaryFiles","localizationFiles","validateNpmSnap","error","ProgrammaticallyFixableSnapError","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","SnapValidationFailureReason","length","attempts","nextValidationError","Error","assert","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","deepClone","undefined","ShasumMismatch","shasum","getSnapChecksum","assertExhaustive","isPlainObject","sourceFilePath","filePath","VirtualFile","path","virtualFile","readVirtualFile","getErrorMessage","iconPath","selector","snapManifest","paths","Array","isArray","Promise","all","map","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository","deepEqual","validateSnapShasum"],"mappings":";;;;;;;;;;;IAkEsBA,aAAa;eAAbA;;IA0JNC,WAAW;eAAXA;;IA8CMC,iBAAiB;eAAjBA;;IA4CAC,WAAW;eAAXA;;IAiCNC,gBAAgB;eAAhBA;;IA0BMC,YAAY;eAAZA;;IA0BNC,mBAAmB;eAAnBA;;IAgCAC,uBAAuB;eAAvBA;;;uBA1awC;sEAClC;oBACS;6DACT;2BAEI;wBACM;qBACH;qBACG;uBAKzB;uBAEuD;6BACjB;;;;;;AAG7C,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,iBAAiB;AACnB;AAqCO,eAAehB,cACpBiB,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB,EACnBC,cAAiCC,YAAE,CAACC,SAAS;IAE7C,MAAMC,WAAqB,EAAE;IAC7B,MAAMC,SAAmB,EAAE;IAE3B,IAAIC,UAAU;IAEd,MAAMC,eAAeC,aAAS,CAACC,IAAI,CAACX,UAAUY,uBAAgB,CAACC,QAAQ;IACvE,MAAMC,eAAe,MAAMC,IAAAA,iBAAY,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AItE,uCAAgC,CACxC,CAAC,CAAC,EAAEpB,uBAAgB,CAACC,QAAQ,CAAC,wBAAwB,EAAEyF,uBAAuB,uBAAuB,EAAE1F,uBAAgB,CAACO,WAAW,CAAC,oBAAoB,EAAEgF,mBAAmB,GAAG,CAAC,EAClL1D,kCAA2B,CAAC2B,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvDgC,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACC,IAAAA,sBAAS,EAACJ,uBAAuBG,qBAClC;QACA,MAAM,IAAIvE,uCAAgC,CACxC,CAAC,CAAC,EAAEpB,uBAAgB,CAACC,QAAQ,CAAC,yCAAyC,EAAED,uBAAgB,CAACO,WAAW,CAAC,qBAAqB,CAAC,EAC5HsB,kCAA2B,CAAC4B,kBAAkB;IAElD;IAEAoC,IAAAA,yBAAkB,EAChB;QAAEpF;QAAUnB;QAAYyB;QAASC;QAAgBC;IAAkB,GACnE,CAAC,CAAC,EAAEjB,uBAAgB,CAACC,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
|
|
@@ -156,7 +156,7 @@ const SnapAuxilaryFilesStruct = (0, _superstruct.array)((0, _superstruct.string)
|
|
|
156
156
|
const SnapManifestStruct = (0, _superstruct.object)({
|
|
157
157
|
version: _utils.VersionStruct,
|
|
158
158
|
description: (0, _superstruct.size)((0, _superstruct.string)(), 1, 280),
|
|
159
|
-
proposedName: (0, _superstruct.size)((0, _superstruct.
|
|
159
|
+
proposedName: (0, _superstruct.size)((0, _superstruct.string)(), 1, 214),
|
|
160
160
|
repository: (0, _superstruct.optional)((0, _superstruct.object)({
|
|
161
161
|
type: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity),
|
|
162
162
|
url: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity)
|
|
@@ -174,7 +174,8 @@ const SnapManifestStruct = (0, _superstruct.object)({
|
|
|
174
174
|
])
|
|
175
175
|
})
|
|
176
176
|
}),
|
|
177
|
-
files: (0, _superstruct.optional)(SnapAuxilaryFilesStruct)
|
|
177
|
+
files: (0, _superstruct.optional)(SnapAuxilaryFilesStruct),
|
|
178
|
+
locales: (0, _superstruct.optional)(SnapAuxilaryFilesStruct)
|
|
178
179
|
}),
|
|
179
180
|
initialPermissions: PermissionsStruct,
|
|
180
181
|
manifestVersion: (0, _superstruct.literal)('0.1'),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n pattern,\n refine,\n record,\n size,\n string,\n type,\n union,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { KeyringOriginsStruct, RpcOriginsStruct } from '../json-rpc';\nimport { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = array(ChainIdStruct);\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n 'endowment:name-lookup': optional(ChainIdsStruct),\n 'endowment:keyring': optional(KeyringOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = Infer<typeof PermissionsStruct>;\n\nexport const SnapAuxilaryFilesStruct = array(string());\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(\n pattern(\n string(),\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 1,\n 214,\n ),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n files: optional(SnapAuxilaryFilesStruct),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","ChainIdsStruct","PermissionsStruct","SnapAuxilaryFilesStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","ChainIdStruct","allowTransactionOrigin","boolean","jobs","CronjobSpecificationArrayStruct","RpcOriginsStruct","KeyringOriginsStruct","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","integer","snap_getEntropy","wallet_snap","VersionStruct","description","proposedName","pattern","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","union","literal","files","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IA0CaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,YAAY;eAAZA;;IAkBAC,kBAAkB;eAAlBA;;IASAC,oCAAoC;eAApCA;;IAMAC,iBAAiB;eAAjBA;;IAOAC,aAAa;eAAbA;;IAcAC,cAAc;eAAdA;;IAGAC,iBAAiB;eAAjBA;;IAoCAC,uBAAuB;eAAvBA;;IAEAC,kBAAkB;eAAlBA;;IA6CGC,cAAc;eAAdA;;IAUAC,oBAAoB;eAApBA;;IAiBAC,kBAAkB;eAAlBA;;;yBA9PwB;uBAMjC;6BAmBA;uBAEiB;yBACwB;yBACgB;yBACT;2BACzB;uBACD;uBACgB;AAE7C,+EAA+E;AAC/E,gCAAgC;AAChC,MAAMC,qBAA+B;IACnCC,0BAAiB;IACjBC,qCAA4B;CAC7B;AAEM,MAAMhB,uBAAiC;IAAC;CAAG;AAClD,MAAMiB,kBAA8BjB,qBAAqBkB,GAAG,CAAC,CAACC,WAAa;QACzE;QACA;QACA,CAAC,EAAEA,SAAS,CAAC,CAAC;KACf;AAEM,MAAMlB,kBAAkBmB,IAAAA,mBAAM,EACnCC,IAAAA,kBAAK,EAACC,IAAAA,mBAAM,MACZ,eACA,CAACC;IACC,IAAIA,KAAKC,MAAM,KAAK,GAAG;QACrB,OAAO;IACT;IAEA,IAAID,IAAI,CAAC,EAAE,KAAK,KAAK;QACnB,OAAO;IACT;IAEA,IAAIA,KAAKC,MAAM,GAAG,GAAG;QACnB,OAAO;IACT;IAEA,IAAID,KAAKE,KAAK,CAAC,GAAGC,IAAI,CAAC,CAACC,OAAS,CAACC,IAAAA,gCAAuB,EAACD,QAAQ;QAChE,OAAO;IACT;IAEA,IAAIb,mBAAmBe,QAAQ,CAACN,IAAI,CAAC,EAAE,GAAG;QACxC,OA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gB,CAACC,QAAQ,CAAC,YAAY,CAAC;AAE/C;AASO,SAAS/E,mBAAmBqB,KAAc;IAC/C,qEAAqE;IACrE,OAAO2D,IAAAA,mBAAM,EAAC3D,OAAOxB;AACvB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n refine,\n record,\n size,\n string,\n type,\n union,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { KeyringOriginsStruct, RpcOriginsStruct } from '../json-rpc';\nimport { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = array(ChainIdStruct);\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n 'endowment:name-lookup': optional(ChainIdsStruct),\n 'endowment:keyring': optional(KeyringOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = Infer<typeof PermissionsStruct>;\n\nexport const SnapAuxilaryFilesStruct = array(string());\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(string(), 1, 214),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n files: optional(SnapAuxilaryFilesStruct),\n locales: optional(SnapAuxilaryFilesStruct),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","ChainIdsStruct","PermissionsStruct","SnapAuxilaryFilesStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","ChainIdStruct","allowTransactionOrigin","boolean","jobs","CronjobSpecificationArrayStruct","RpcOriginsStruct","KeyringOriginsStruct","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","integer","snap_getEntropy","wallet_snap","VersionStruct","description","proposedName","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","union","literal","files","locales","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IAyCaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,YAAY;eAAZA;;IAkBAC,kBAAkB;eAAlBA;;IASAC,oCAAoC;eAApCA;;IAMA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