@metamask/snaps-utils 0.24.1 → 0.26.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/dist/caveats.d.ts +5 -1
- package/dist/caveats.js +4 -0
- package/dist/caveats.js.map +1 -1
- package/dist/eval-worker.js.map +1 -1
- package/dist/eval.js +1 -1
- package/dist/eval.js.map +1 -1
- package/dist/fs.js.map +1 -1
- package/dist/index.browser.d.ts +1 -1
- package/dist/index.browser.js +1 -1
- package/dist/index.browser.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/json-rpc.d.ts +19 -1
- package/dist/json-rpc.js +25 -1
- package/dist/json-rpc.js.map +1 -1
- package/dist/manifest/manifest.js +6 -6
- package/dist/manifest/manifest.js.map +1 -1
- package/dist/manifest/validation.d.ts +28 -2
- package/dist/manifest/validation.js +7 -3
- package/dist/manifest/validation.js.map +1 -1
- package/dist/mock.js +4 -1
- package/dist/mock.js.map +1 -1
- package/dist/namespace.d.ts +1 -1
- package/dist/namespace.js +4 -2
- package/dist/namespace.js.map +1 -1
- package/dist/notification.js +1 -1
- package/dist/notification.js.map +1 -1
- package/dist/npm.js.map +1 -1
- package/dist/object.js.map +1 -1
- package/dist/post-process.js +6 -4
- package/dist/post-process.js.map +1 -1
- package/dist/snaps.d.ts +7 -2
- package/dist/snaps.js +54 -5
- package/dist/snaps.js.map +1 -1
- package/dist/types.d.ts +31 -14
- package/dist/types.js +29 -9
- package/dist/types.js.map +1 -1
- package/dist/versions.d.ts +89 -12
- package/dist/versions.js +72 -17
- package/dist/versions.js.map +1 -1
- package/dist/virtual-file/VirtualFile.d.ts +33 -0
- package/dist/virtual-file/VirtualFile.js +62 -0
- package/dist/virtual-file/VirtualFile.js.map +1 -0
- package/dist/virtual-file/index.browser.d.ts +1 -0
- package/dist/virtual-file/index.browser.js +18 -0
- package/dist/virtual-file/index.browser.js.map +1 -0
- package/dist/virtual-file/index.d.ts +2 -0
- package/dist/virtual-file/index.js +19 -0
- package/dist/virtual-file/index.js.map +1 -0
- package/dist/virtual-file/toVirtualFile.d.ts +21 -0
- package/dist/virtual-file/toVirtualFile.js +33 -0
- package/dist/virtual-file/toVirtualFile.js.map +1 -0
- package/package.json +21 -17
- package/dist/url.d.ts +0 -7
- package/dist/url.js +0 -19
- package/dist/url.js.map +0 -1
package/dist/namespace.d.ts
CHANGED
package/dist/namespace.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.assertIsNamespacesObject = exports.isNamespacesObject = exports.isNamespace = exports.assertIsMultiChainRequest = exports.isMultiChainRequest = exports.assertIsConnectArguments = exports.isConnectArguments = exports.isAccountIdArray = exports.isAccountId = exports.isChainId = exports.isNamespaceId = exports.MultiChainRequestStruct = exports.RequestArgumentsStruct = exports.ConnectArgumentsStruct = exports.assertIsSession = exports.SessionStruct = exports.NamespacesStruct = exports.NamespaceIdStruct = exports.SessionNamespaceStruct = exports.RequestNamespaceStruct = exports.NamespaceStruct = exports.ChainStruct = exports.AccountIdArrayStruct = exports.AccountIdStruct = exports.ChainIdStruct = exports.LimitedString = exports.parseAccountId = exports.parseChainId = exports.ACCOUNT_ID_REGEX = exports.CHAIN_ID_REGEX = void 0;
|
|
4
|
-
const superstruct_1 = require("superstruct");
|
|
5
4
|
const utils_1 = require("@metamask/utils");
|
|
5
|
+
const superstruct_1 = require("superstruct");
|
|
6
6
|
exports.CHAIN_ID_REGEX = /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;
|
|
7
7
|
exports.ACCOUNT_ID_REGEX = /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;
|
|
8
8
|
/**
|
|
@@ -216,7 +216,9 @@ exports.isNamespacesObject = isNamespacesObject;
|
|
|
216
216
|
* {@link AssertionError}.
|
|
217
217
|
* @throws If the value is not a valid {@link Namespaces} object.
|
|
218
218
|
*/
|
|
219
|
-
function assertIsNamespacesObject(value,
|
|
219
|
+
function assertIsNamespacesObject(value,
|
|
220
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
221
|
+
ErrorWrapper) {
|
|
220
222
|
(0, utils_1.assertStruct)(value, exports.NamespacesStruct, 'Invalid namespaces object', ErrorWrapper);
|
|
221
223
|
}
|
|
222
224
|
exports.assertIsNamespacesObject = assertIsNamespacesObject;
|
package/dist/namespace.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"namespace.js","sourceRoot":"","sources":["../src/namespace.ts"],"names":[],"mappings":";;;AAAA,6CAcqB;AACrB,2CAIyB;AAEZ,QAAA,cAAc,GACzB,kEAAkE,CAAC;AAExD,QAAA,gBAAgB,GAC3B,mHAAmH,CAAC;AAEtH;;;;;;GAMG;AACH,SAAgB,YAAY,CAAC,OAAgB;IAI3C,MAAM,KAAK,GAAG,sBAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC3C,IAAI,CAAC,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAAM,CAAA,EAAE;QAClB,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;KACtC;IAED,OAAO;QACL,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAAS;QACjC,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAAS;KAClC,CAAC;AACJ,CAAC;AAbD,oCAaC;AAED;;;;;;GAMG;AACH,SAAgB,cAAc,CAAC,SAAoB;IAKjD,MAAM,KAAK,GAAG,wBAAgB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC/C,IAAI,CAAC,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAAM,CAAA,EAAE;QAClB,MAAM,IAAI,KAAK,CAAC,q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;IAC/C,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,wBAAgB,CAAC,CAAC;AACrC,CAAC;AAFD,gDAEC;AAED;;;;;;;GAOG;AACH,SAAgB,wBAAwB,CACtC,KAAc,EACd,YAAwC;IAExC,IAAA,oBAAY,EACV,KAAK,EACL,wBAAgB,EAChB,2BAA2B,EAC3B,YAAY,CACb,CAAC;AACJ,CAAC;AAVD,4DAUC","sourcesContent":["import {\n array,\n Infer,\n is,\n object,\n optional,\n pattern,\n record,\n size,\n string,\n omit,\n assign,\n partial,\n pick,\n} from 'superstruct';\nimport {\n JsonRpcRequestStruct,\n AssertionErrorConstructor,\n assertStruct,\n} from '@metamask/utils';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern(string(), CHAIN_ID_REGEX);\nexport type ChainId = `${string}:${string}`;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\nexport type AccountId = `${ChainId}:${string}`;\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\n\n/**\n * A chain descriptor.\n */\nexport const ChainStruct = object({\n id: ChainIdStruct,\n name: LimitedString,\n});\nexport type Chain = Infer<typeof ChainStruct>;\n\nexport const NamespaceStruct = object({\n /**\n * A list of supported chains in the namespace.\n */\n chains: array(ChainStruct),\n\n /**\n * A list of supported RPC methods on the namespace, that a DApp can call.\n */\n methods: optional(array(LimitedString)),\n\n /**\n * A list of supported RPC events on the namespace, that a DApp can listen to.\n */\n events: optional(array(LimitedString)),\n});\nexport type Namespace = Infer<typeof NamespaceStruct>;\n\nexport const RequestNamespaceStruct = assign(\n omit(NamespaceStruct, ['chains']),\n object({ chains: array(ChainIdStruct) }),\n);\nexport type RequestNamespace = Infer<typeof RequestNamespaceStruct>;\n\nexport const SessionNamespaceStruct = assign(\n RequestNamespaceStruct,\n object({ accounts: array(AccountIdStruct) }),\n);\nexport type SessionNamespace = Infer<typeof SessionNamespaceStruct>;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a chain ID.\n */\nexport const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);\nexport type NamespaceId = Infer<typeof NamespaceIdStruct>;\n\n/**\n * An object mapping CAIP-2 namespaces to their values.\n */\nexport const NamespacesStruct = record(NamespaceIdStruct, NamespaceStruct);\nexport type Namespaces = Infer<typeof NamespacesStruct>;\n\nexport const SessionStruct = object({\n namespaces: record(NamespaceIdStruct, SessionNamespaceStruct),\n});\nexport type Session = Infer<typeof SessionStruct>;\n\n/**\n * Asserts that the given value is a valid {@link Session}.\n *\n * @param value - The value to assert.\n * @throws If the value is not a valid {@link Session}.\n */\nexport function assertIsSession(value: unknown): asserts value is Session {\n assertStruct(value, SessionStruct, 'Invalid session');\n}\n\nexport const ConnectArgumentsStruct = object({\n requiredNamespaces: record(NamespaceIdStruct, RequestNamespaceStruct),\n});\nexport type ConnectArguments = Infer<typeof ConnectArgumentsStruct>;\n\nexport const RequestArgumentsStruct = assign(\n partial(pick(JsonRpcRequestStruct, ['id', 'jsonrpc'])),\n omit(JsonRpcRequestStruct, ['id', 'jsonrpc']),\n);\nexport type RequestArguments = Infer<typeof RequestArgumentsStruct>;\n\nexport const MultiChainRequestStruct = object({\n chainId: ChainIdStruct,\n request: RequestArgumentsStruct,\n});\nexport type MultiChainRequest = Infer<typeof MultiChainRequestStruct>;\n\n/**\n * Check if the given value is a CAIP-2 namespace ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 namespace ID.\n */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return is(value, NamespaceIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-2 chain ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 chain ID.\n */\nexport function isChainId(value: unknown): value is ChainId {\n return is(value, ChainIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-10 account ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-10 account ID.\n */\nexport function isAccountId(value: unknown): value is AccountId {\n return is(value, AccountIdStruct);\n}\n\n/**\n * Check if the given value is an array of CAIP-10 account IDs.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of CAIP-10 account IDs.\n */\nexport function isAccountIdArray(value: unknown): value is AccountId[] {\n return is(value, AccountIdArrayStruct);\n}\n\n/**\n * Check if the given value is a {@link ConnectArguments} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link ConnectArguments} object.\n */\nexport function isConnectArguments(value: unknown): value is ConnectArguments {\n return is(value, ConnectArgumentsStruct);\n}\n\n/**\n * Assert that the given value is a {@link ConnectArguments} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link ConnectArguments} object.\n */\nexport function assertIsConnectArguments(\n value: unknown,\n): asserts value is ConnectArguments {\n assertStruct(value, ConnectArgumentsStruct, 'Invalid connect arguments');\n}\n\n/**\n * Check if the given value is a {@link MultiChainRequest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link MultiChainRequest} object.\n */\nexport function isMultiChainRequest(\n value: unknown,\n): value is MultiChainRequest {\n return is(value, MultiChainRequestStruct);\n}\n\n/**\n * Assert that the given value is a {@link MultiChainRequest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link MultiChainRequest} object.\n */\nexport function assertIsMultiChainRequest(\n value: unknown,\n): asserts value is MultiChainRequest {\n assertStruct(value, MultiChainRequestStruct, 'Invalid request arguments');\n}\n\n/**\n * Check if a value is a {@link Namespace}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link Namespace}.\n */\nexport function isNamespace(value: unknown): value is Namespace {\n return is(value, NamespaceStruct);\n}\n\n/**\n * Check if a value is an object containing {@link Namespace}s.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid object containing namespaces.\n */\nexport function isNamespacesObject(value: unknown): value is Namespaces {\n return is(value, NamespacesStruct);\n}\n\n/**\n * Assert that the given value is a {@link Namespaces} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error wrapper to use. Defaults to\n * {@link AssertionError}.\n * @throws If the value is not a valid {@link Namespaces} object.\n */\nexport function assertIsNamespacesObject(\n value: unknown,\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is Namespaces {\n assertStruct(\n value,\n NamespacesStruct,\n 'Invalid namespaces object',\n ErrorWrapper,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"namespace.js","sourceRoot":"","sources":["../src/namespace.ts"],"names":[],"mappings":";;;AAAA,2CAIyB;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BAAkB,CAAC,KAAc;IAC/C,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,8BAAsB,CAAC,CAAC;AAC3C,CAAC;AAFD,gDAEC;AAED;;;;;GAKG;AACH,SAAgB,wBAAwB,CACtC,KAAc;IAEd,IAAA,oBAAY,EAAC,KAAK,EAAE,8BAAsB,EAAE,2BAA2B,CAAC,CAAC;AAC3E,CAAC;AAJD,4DAIC;AAED;;;;;GAKG;AACH,SAAgB,mBAAmB,CACjC,KAAc;IAEd,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,+BAAuB,CAAC,CAAC;AAC5C,CAAC;AAJD,kDAIC;AAED;;;;;GAKG;AACH,SAAgB,yBAAyB,CACvC,KAAc;IAEd,IAAA,oBAAY,EAAC,KAAK,EAAE,+BAAuB,EAAE,2BAA2B,CAAC,CAAC;AAC5E,CAAC;AAJD,8DAIC;AAED;;;;;GAKG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,uBAAe,CAAC,CAAC;AACpC,CAAC;AAFD,kCAEC;AAED;;;;;GAKG;AACH,SAAgB,kBAAkB,CAAC,KAAc;IAC/C,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,wBAAgB,CAAC,CAAC;AACrC,CAAC;AAFD,gDAEC;AAED;;;;;;;GAOG;AACH,SAAgB,wBAAwB,CACtC,KAAc;AACd,gEAAgE;AAChE,YAAwC;IAExC,IAAA,oBAAY,EACV,KAAK,EACL,wBAAgB,EAChB,2BAA2B,EAC3B,YAAY,CACb,CAAC;AACJ,CAAC;AAXD,4DAWC","sourcesContent":["import {\n JsonRpcRequestStruct,\n AssertionErrorConstructor,\n assertStruct,\n} from '@metamask/utils';\nimport {\n array,\n Infer,\n is,\n object,\n optional,\n pattern,\n record,\n size,\n string,\n omit,\n assign,\n partial,\n pick,\n} from 'superstruct';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern(string(), CHAIN_ID_REGEX);\nexport type ChainId = `${string}:${string}`;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\nexport type AccountId = `${ChainId}:${string}`;\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\n\n/**\n * A chain descriptor.\n */\nexport const ChainStruct = object({\n id: ChainIdStruct,\n name: LimitedString,\n});\nexport type Chain = Infer<typeof ChainStruct>;\n\nexport const NamespaceStruct = object({\n /**\n * A list of supported chains in the namespace.\n */\n chains: array(ChainStruct),\n\n /**\n * A list of supported RPC methods on the namespace, that a DApp can call.\n */\n methods: optional(array(LimitedString)),\n\n /**\n * A list of supported RPC events on the namespace, that a DApp can listen to.\n */\n events: optional(array(LimitedString)),\n});\nexport type Namespace = Infer<typeof NamespaceStruct>;\n\nexport const RequestNamespaceStruct = assign(\n omit(NamespaceStruct, ['chains']),\n object({ chains: array(ChainIdStruct) }),\n);\nexport type RequestNamespace = Infer<typeof RequestNamespaceStruct>;\n\nexport const SessionNamespaceStruct = assign(\n RequestNamespaceStruct,\n object({ accounts: array(AccountIdStruct) }),\n);\nexport type SessionNamespace = Infer<typeof SessionNamespaceStruct>;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a chain ID.\n */\nexport const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);\nexport type NamespaceId = Infer<typeof NamespaceIdStruct>;\n\n/**\n * An object mapping CAIP-2 namespaces to their values.\n */\nexport const NamespacesStruct = record(NamespaceIdStruct, NamespaceStruct);\nexport type Namespaces = Infer<typeof NamespacesStruct>;\n\nexport const SessionStruct = object({\n namespaces: record(NamespaceIdStruct, SessionNamespaceStruct),\n});\nexport type Session = Infer<typeof SessionStruct>;\n\n/**\n * Asserts that the given value is a valid {@link Session}.\n *\n * @param value - The value to assert.\n * @throws If the value is not a valid {@link Session}.\n */\nexport function assertIsSession(value: unknown): asserts value is Session {\n assertStruct(value, SessionStruct, 'Invalid session');\n}\n\nexport const ConnectArgumentsStruct = object({\n requiredNamespaces: record(NamespaceIdStruct, RequestNamespaceStruct),\n});\nexport type ConnectArguments = Infer<typeof ConnectArgumentsStruct>;\n\nexport const RequestArgumentsStruct = assign(\n partial(pick(JsonRpcRequestStruct, ['id', 'jsonrpc'])),\n omit(JsonRpcRequestStruct, ['id', 'jsonrpc']),\n);\nexport type RequestArguments = Infer<typeof RequestArgumentsStruct>;\n\nexport const MultiChainRequestStruct = object({\n chainId: ChainIdStruct,\n request: RequestArgumentsStruct,\n});\nexport type MultiChainRequest = Infer<typeof MultiChainRequestStruct>;\n\n/**\n * Check if the given value is a CAIP-2 namespace ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 namespace ID.\n */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return is(value, NamespaceIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-2 chain ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 chain ID.\n */\nexport function isChainId(value: unknown): value is ChainId {\n return is(value, ChainIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-10 account ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-10 account ID.\n */\nexport function isAccountId(value: unknown): value is AccountId {\n return is(value, AccountIdStruct);\n}\n\n/**\n * Check if the given value is an array of CAIP-10 account IDs.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of CAIP-10 account IDs.\n */\nexport function isAccountIdArray(value: unknown): value is AccountId[] {\n return is(value, AccountIdArrayStruct);\n}\n\n/**\n * Check if the given value is a {@link ConnectArguments} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link ConnectArguments} object.\n */\nexport function isConnectArguments(value: unknown): value is ConnectArguments {\n return is(value, ConnectArgumentsStruct);\n}\n\n/**\n * Assert that the given value is a {@link ConnectArguments} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link ConnectArguments} object.\n */\nexport function assertIsConnectArguments(\n value: unknown,\n): asserts value is ConnectArguments {\n assertStruct(value, ConnectArgumentsStruct, 'Invalid connect arguments');\n}\n\n/**\n * Check if the given value is a {@link MultiChainRequest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link MultiChainRequest} object.\n */\nexport function isMultiChainRequest(\n value: unknown,\n): value is MultiChainRequest {\n return is(value, MultiChainRequestStruct);\n}\n\n/**\n * Assert that the given value is a {@link MultiChainRequest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link MultiChainRequest} object.\n */\nexport function assertIsMultiChainRequest(\n value: unknown,\n): asserts value is MultiChainRequest {\n assertStruct(value, MultiChainRequestStruct, 'Invalid request arguments');\n}\n\n/**\n * Check if a value is a {@link Namespace}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link Namespace}.\n */\nexport function isNamespace(value: unknown): value is Namespace {\n return is(value, NamespaceStruct);\n}\n\n/**\n * Check if a value is an object containing {@link Namespace}s.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid object containing namespaces.\n */\nexport function isNamespacesObject(value: unknown): value is Namespaces {\n return is(value, NamespacesStruct);\n}\n\n/**\n * Assert that the given value is a {@link Namespaces} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error wrapper to use. Defaults to\n * {@link AssertionError}.\n * @throws If the value is not a valid {@link Namespaces} object.\n */\nexport function assertIsNamespacesObject(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is Namespaces {\n assertStruct(\n value,\n NamespacesStruct,\n 'Invalid namespaces object',\n ErrorWrapper,\n );\n}\n"]}
|
package/dist/notification.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.assertIsMetaMaskNotification = exports.isMetaMaskNotification = exports.MetaMaskNotificationStruct = exports.assertIsEvent = exports.isEvent = exports.EventStruct = void 0;
|
|
4
|
-
const superstruct_1 = require("superstruct");
|
|
5
4
|
const utils_1 = require("@metamask/utils");
|
|
5
|
+
const superstruct_1 = require("superstruct");
|
|
6
6
|
const namespace_1 = require("./namespace");
|
|
7
7
|
exports.EventStruct = (0, superstruct_1.object)({
|
|
8
8
|
name: (0, superstruct_1.string)(),
|
package/dist/notification.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"notification.js","sourceRoot":"","sources":["../src/notification.ts"],"names":[],"mappings":";;;AAAA,
|
|
1
|
+
{"version":3,"file":"notification.js","sourceRoot":"","sources":["../src/notification.ts"],"names":[],"mappings":";;;AAAA,2CAA+C;AAC/C,6CAA0E;AAE1E,2CAA4C;AAE/B,QAAA,WAAW,GAAG,IAAA,oBAAM,EAAC;IAChC,IAAI,EAAE,IAAA,oBAAM,GAAE;IACd,IAAI,EAAE,IAAA,qBAAO,GAAE;CAChB,CAAC,CAAC;AAIH;;;;;GAKG;AACH,SAAgB,OAAO,CAAC,KAAc;IACpC,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,mBAAW,CAAC,CAAC;AAChC,CAAC;AAFD,0BAEC;AAED;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,KAAc;IAC1C,IAAA,oBAAY,EAAC,KAAK,EAAE,mBAAW,EAAE,eAAe,CAAC,CAAC;AACpD,CAAC;AAFD,sCAEC;AAEY,QAAA,0BAA0B,GAAG,IAAA,oBAAM,EAAC;IAC/C,MAAM,EAAE,IAAA,qBAAO,EAAC,+BAA+B,CAAC;IAChD,MAAM,EAAE,IAAA,oBAAM,EAAC;QACb,OAAO,EAAE,yBAAa;QACtB,KAAK,EAAE,mBAAW;KACnB,CAAC;CACH,CAAC,CAAC;AAIH;;;;;GAKG;AACH,SAAgB,sBAAsB,CACpC,KAAc;IAEd,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,kCAA0B,CAAC,CAAC;AAC/C,CAAC;AAJD,wDAIC;AAED;;;;;GAKG;AACH,SAAgB,4BAA4B,CAC1C,KAAc;IAEd,IAAA,oBAAY,EAAC,KAAK,EAAE,kCAA0B,EAAE,sBAAsB,CAAC,CAAC;AAC1E,CAAC;AAJD,oEAIC","sourcesContent":["import { assertStruct } from '@metamask/utils';\nimport { Infer, is, literal, object, string, unknown } from 'superstruct';\n\nimport { ChainIdStruct } from './namespace';\n\nexport const EventStruct = object({\n name: string(),\n data: unknown(),\n});\n\nexport type Event = Infer<typeof EventStruct>;\n\n/**\n * Check if a value is a SIP-2 event.\n *\n * @param value - The value to check.\n * @returns Whether the value is a SIP-2 event.\n */\nexport function isEvent(value: unknown): value is Event {\n return is(value, EventStruct);\n}\n\n/**\n * Assert that a value is a SIP-2 event.\n *\n * @param value - The value to check.\n * @throws If the value is not a SIP-2 event.\n */\nexport function assertIsEvent(value: unknown): asserts value is Event {\n assertStruct(value, EventStruct, 'Invalid event');\n}\n\nexport const MetaMaskNotificationStruct = object({\n method: literal('multichainHack_metamask_event'),\n params: object({\n chainId: ChainIdStruct,\n event: EventStruct,\n }),\n});\n\nexport type MetaMaskNotification = Infer<typeof MetaMaskNotificationStruct>;\n\n/**\n * Check if a value is a SIP-2 notification.\n *\n * @param value - The value to check.\n * @returns Whether the value is a SIP-2 notification.\n */\nexport function isMetaMaskNotification(\n value: unknown,\n): value is MetaMaskNotification {\n return is(value, MetaMaskNotificationStruct);\n}\n\n/**\n * Assert that a value is a SIP-2 notification.\n *\n * @param value - The value to check.\n * @throws If the value is not a SIP-2 notification.\n */\nexport function assertIsMetaMaskNotification(\n value: unknown,\n): asserts value is MetaMaskNotification {\n assertStruct(value, MetaMaskNotificationStruct, 'Invalid notification');\n}\n"]}
|
package/dist/npm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"npm.js","sourceRoot":"","sources":["../src/npm.ts"],"names":[],"mappings":";;;AAAA,kDAA8D;AAC9D,
|
|
1
|
+
{"version":3,"file":"npm.js","sourceRoot":"","sources":["../src/npm.ts"],"names":[],"mappings":";;;AAAA,kDAA8D;AAC9D,sDAA6D;AAC7D,mCAKiB;AAEJ,QAAA,iBAAiB,GAAG,MAAO,CAAC;AAC5B,QAAA,sBAAsB,GAAG,GAAG,IAAI,CAAC,KAAK,CACjD,yBAAiB,GAAG,IAAI,CACzB,IAAI,CAAC;AAEO,QAAA,mBAAmB,GAAG;IACjC,UAAU;IACV,aAAa;IACb,YAAY;CACJ,CAAC;AAEE,QAAA,mBAAmB,GAAG;IACjC,QAAQ,EAAE,wBAAgB,CAAC,QAAQ;IAC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AAC;QACtB,QAAQ,EAAE,iBAAiB;QAC3B,WAAW,EAAE,oBAAoB;QACjC,UAAU;KACX,CAAC,CAAC;IAEH,IAAI,OAAO,EAAE;QACX,IAAI,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC,GAAG,yBAAiB,EAAE;YAC1D,MAAM,IAAI,KAAK,CACb,GACE,WAAW,aAAX,WAAW,cAAX,WAAW,GAAI,EACjB,sDAAsD,8BAAsB,GAAG,CAChF,CAAC;SACH;KACF;IAED,OAAO;QACL,QAAQ,EAAE,iBAAiB;QAC3B,WAAW,EAAE,oBAAoB;QACjC,UAAU;QACV,OAAO;KACR,CAAC;AACJ,CAAC;AAvDD,0CAuDC","sourcesContent":["import { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport {\n assertIsNpmSnapPackageJson,\n NpmSnapFileNames,\n SnapFiles,\n UnvalidatedSnapFiles,\n} from './types';\n\nexport const SVG_MAX_BYTE_SIZE = 100_000;\nexport const SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(\n SVG_MAX_BYTE_SIZE / 1000,\n)}kb`;\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): SnapFiles {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const { manifest, packageJson, sourceCode, svgIcon } = snapFiles as SnapFiles;\n try {\n assertIsSnapManifest(manifest);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedManifest = manifest;\n\n const { iconPath } = validatedManifest.source.location.npm;\n if (iconPath && !svgIcon) {\n throw new Error(`Missing file \"${iconPath}\".`);\n }\n\n try {\n assertIsNpmSnapPackageJson(packageJson);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedPackageJson = packageJson;\n\n validateNpmSnapManifest({\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n });\n\n if (svgIcon) {\n if (Buffer.byteLength(svgIcon, 'utf8') > SVG_MAX_BYTE_SIZE) {\n throw new Error(\n `${\n errorPrefix ?? ''\n }The specified SVG icon exceeds the maximum size of ${SVG_MAX_BYTE_SIZE_TEXT}.`,\n );\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n };\n}\n"]}
|
package/dist/object.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"object.js","sourceRoot":"","sources":["../src/object.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACI,MAAM,WAAW,GAAG,CACzB,OAA2C,EACvB,EAAE;IACtB,OAAO,OAAO,CAAC,MAAM,CACnB,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,iCAAM,GAAG,KAAE,CAAC,GAAG,CAAC,EAAE,KAAK,IAAG,EACjD,
|
|
1
|
+
{"version":3,"file":"object.js","sourceRoot":"","sources":["../src/object.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACI,MAAM,WAAW,GAAG,CACzB,OAA2C,EACvB,EAAE;IACtB,OAAO,OAAO,CAAC,MAAM,CACnB,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,iCAAM,GAAG,KAAE,CAAC,GAAG,CAAC,EAAE,KAAK,IAAG,EACjD,EAAE,CACH,CAAC;AACJ,CAAC,CAAC;AAPW,QAAA,WAAW,eAOtB","sourcesContent":["/**\n * An alternative implementation of `Object.fromEntries`, which works in older\n * browsers.\n *\n * @param entries - The entries to convert to an object.\n * @returns The object.\n */\nexport const fromEntries = <Key extends string, Value>(\n entries: readonly (readonly [Key, Value])[],\n): Record<Key, Value> => {\n return entries.reduce<Record<string, Value>>(\n (acc, [key, value]) => ({ ...acc, [key]: value }),\n {},\n );\n};\n"]}
|
package/dist/post-process.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.postProcessBundle = exports.PostProcessWarning = void 0;
|
|
4
|
-
|
|
4
|
+
// eslint-disable-next-line @typescript-eslint/no-shadow
|
|
5
5
|
const core_1 = require("@babel/core");
|
|
6
|
+
const types_1 = require("@babel/types");
|
|
6
7
|
var PostProcessWarning;
|
|
7
8
|
(function (PostProcessWarning) {
|
|
8
9
|
PostProcessWarning["UnsafeMathRandom"] = "`Math.random` was detected in the bundle. This is not a secure source of randomness.";
|
|
@@ -185,8 +186,9 @@ function postProcessBundle(code, { stripComments = true, sourceMap: sourceMaps,
|
|
|
185
186
|
// Replace `object.eval(foo)` with `(1, object.eval)(foo)`.
|
|
186
187
|
if (node.property.type === 'Identifier' &&
|
|
187
188
|
node.property.name === 'eval' &&
|
|
188
|
-
//
|
|
189
|
-
path.parent.type
|
|
189
|
+
// We only apply this to MemberExpressions that are the callee of CallExpression
|
|
190
|
+
path.parent.type === 'CallExpression' &&
|
|
191
|
+
path.parent.callee === node) {
|
|
190
192
|
path.replaceWith(objectEvalWrapper({
|
|
191
193
|
OBJECT: node.object,
|
|
192
194
|
REF: node.property,
|
|
@@ -246,7 +248,7 @@ function postProcessBundle(code, { stripComments = true, sourceMap: sourceMaps,
|
|
|
246
248
|
],
|
|
247
249
|
];
|
|
248
250
|
}, [[], []]);
|
|
249
|
-
path.replaceWith((0, types_1.templateLiteral)(replacementQuasis, replacementExpressions.filter((
|
|
251
|
+
path.replaceWith((0, types_1.templateLiteral)(replacementQuasis, replacementExpressions.filter((expression) => expression !== undefined)));
|
|
250
252
|
path.setData('visited', true);
|
|
251
253
|
},
|
|
252
254
|
StringLiteral(path) {
|
package/dist/post-process.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"post-process.js","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":";;;AAAA,wCAQsB;AACtB,sCAAgF;AAgDhF,IAAY,kBAEX;AAFD,WAAY,kBAAkB;IAC5B,+HAAyG,CAAA;AAC3G,CAAC,EAFW,kBAAkB,GAAlB,0BAAkB,KAAlB,0BAAkB,QAE7B;AAED,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAM,WAAW,GAAG,sCAAsC,CAAC;AAE3D,4EAA4E;AAC5E,cAAc;AACd,MAAM,sBAAsB,GAAG,IAAA,uBAAe,EAAC,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC;AAExE,MAAM,WAAW,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAEtC,CAAC,CAAC;AAEH,MAAM,iBAAiB,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAE5C,CAAC,CAAC;AAEH,MAAM,yBAAyB,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAEpD,CAAC,CAAC;AAEH;;;;;;;;;;;GAWG;AACH,SAAS,WAAW,CAAC,KAAa;IAChC,MAAM,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IACxC,OAAO,CACL,MAAM;QACJ,oEAAoE;QACpE,sEAAsE;SACrE,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,C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;oBACpF,kBAAkB,CACrB,CAAC;aACH;QACH,CAAC;KACF,CAAC;IAEF,IAAI;QACF,MAAM,IAAI,GAAG,IAAA,oBAAa,EAAC,IAAI,EAAE;YAC/B,kDAAkD;YAClD,UAAU,EAAE,KAAK;YAEjB,UAAU,EAAE;gBACV,sEAAsE;gBACtE,UAAU,EAAE,IAAI;gBAEhB,sEAAsE;gBACtE,wEAAwE;gBACxE,aAAa,EAAE,CAAC,aAAa;aAC9B;YAED,mEAAmE;YACnE,yEAAyE;YACzE,OAAO,EAAE,KAAK;YAEd,uEAAuE;YACvE,wEAAwE;YACxE,mEAAmE;YACnE,cAAc;YACd,UAAU;YAEV,OAAO,EAAE;gBACP,GAAG,EAAE,CAAC,CAAC;oBACL,GAAG;oBACH,OAAO;iBACR,CAAC;aACH;SACF,CAAC,CAAC;QAEH,IAAI,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,IAAI,CAAA,EAAE;YACf,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;SAC3C;QAED,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,SAAS,EAAE,IAAI,CAAC,GAAG;YACnB,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;SAC/B,CAAC;KACH;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;KACnE;AACH,CAAC;AAjQD,8CAiQC","sourcesContent":["import {\n binaryExpression,\n Expression,\n Identifier,\n stringLiteral,\n TemplateElement,\n templateElement,\n templateLiteral,\n} from '@babel/types';\nimport { transformSync, Node, Visitor, template, PluginObj } from '@babel/core';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the bundle. This is not a secure source of randomness.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // @ts-expect-error `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // If the expression is already wrapped we can ignore it\n path.parent.type !== 'SequenceExpression'\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi as TemplateElement],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...(tokens[0] as TemplateElement[])],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter((e) => e !== undefined),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const source = path.getSource();\n\n // Throw an error if HTML comments are used as a binary expression.\n if (source.includes('<!--') || source.includes('-->')) {\n throw new Error(\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.',\n );\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"post-process.js","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":";;;AAAA,wDAAwD;AACxD,sCAAgF;AAChF,wCAQsB;AAgDtB,IAAY,kBAEX;AAFD,WAAY,kBAAkB;IAC5B,+HAAyG,CAAA;AAC3G,CAAC,EAFW,kBAAkB,GAAlB,0BAAkB,KAAlB,0BAAkB,QAE7B;AAED,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAM,WAAW,GAAG,sCAAsC,CAAC;AAE3D,4EAA4E;AAC5E,cAAc;AACd,MAAM,sBAAsB,GAAG,IAAA,uBAAe,EAAC,EAAE,GAAG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ACf,SAAS,EAAE,IAAI,CAAC,GAAG;YACnB,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;SAC/B,CAAC;KACH;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;KACnE;AACH,CAAC;AApQD,8CAoQC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport { transformSync, Node, Visitor, template, PluginObj } from '@babel/core';\nimport {\n binaryExpression,\n Expression,\n Identifier,\n stringLiteral,\n TemplateElement,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the bundle. This is not a secure source of randomness.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // @ts-expect-error `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const source = path.getSource();\n\n // Throw an error if HTML comments are used as a binary expression.\n if (source.includes('<!--') || source.includes('-->')) {\n throw new Error(\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.',\n );\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"]}
|
package/dist/snaps.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { Json } from '@metamask/utils';
|
|
2
2
|
import { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';
|
|
3
|
+
import { Struct } from 'superstruct';
|
|
3
4
|
import { SnapManifest, SnapPermissions } from './manifest/validation';
|
|
4
5
|
import { SnapId, SnapIdPrefixes, SnapValidationFailureReason } from './types';
|
|
5
|
-
|
|
6
|
+
import { SemVerVersion } from './versions';
|
|
6
7
|
export declare const SNAP_PREFIX = "wallet_snap_";
|
|
7
8
|
export declare const SNAP_PREFIX_REGEX: RegExp;
|
|
8
9
|
export declare const PROPOSED_NAME_REGEX: RegExp;
|
|
@@ -93,7 +94,7 @@ export declare type Snap = {
|
|
|
93
94
|
/**
|
|
94
95
|
* The version of the Snap.
|
|
95
96
|
*/
|
|
96
|
-
version:
|
|
97
|
+
version: SemVerVersion;
|
|
97
98
|
/**
|
|
98
99
|
* The version history of the Snap.
|
|
99
100
|
* Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.
|
|
@@ -135,6 +136,10 @@ export declare type ValidatedSnapId = `local:${string}` | `npm:${string}`;
|
|
|
135
136
|
* @param errorMessage - The error message to throw if validation fails.
|
|
136
137
|
*/
|
|
137
138
|
export declare function validateSnapShasum(manifest: SnapManifest, sourceCode: string, errorMessage?: string): void;
|
|
139
|
+
export declare const LOCALHOST_HOSTNAMES: readonly ["localhost", "127.0.0.1", "[::1]"];
|
|
140
|
+
export declare const LocalSnapIdStruct: Struct<string, null>;
|
|
141
|
+
export declare const NpmSnapIdStruct: Struct<string, null>;
|
|
142
|
+
export declare const HttpSnapIdStruct: Struct<string, null>;
|
|
138
143
|
/**
|
|
139
144
|
* Extracts the snap prefix from a snap ID.
|
|
140
145
|
*
|
package/dist/snaps.js
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
2
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.isCaipChainId = exports.validateSnapId = exports.getSnapPermissionName = exports.getSnapPrefix = exports.validateSnapShasum = exports.getSnapSourceShasum = exports.ProgrammaticallyFixableSnapError = exports.SnapStatusEvents = exports.SnapStatus = exports.PROPOSED_NAME_REGEX = exports.SNAP_PREFIX_REGEX = exports.SNAP_PREFIX =
|
|
6
|
+
exports.isCaipChainId = exports.validateSnapId = exports.getSnapPermissionName = exports.getSnapPrefix = exports.HttpSnapIdStruct = exports.NpmSnapIdStruct = exports.LocalSnapIdStruct = exports.LOCALHOST_HOSTNAMES = exports.validateSnapShasum = exports.getSnapSourceShasum = exports.ProgrammaticallyFixableSnapError = exports.SnapStatusEvents = exports.SnapStatus = exports.PROPOSED_NAME_REGEX = exports.SNAP_PREFIX_REGEX = exports.SNAP_PREFIX = void 0;
|
|
7
|
+
const utils_1 = require("@metamask/utils");
|
|
4
8
|
const sha256_1 = require("@noble/hashes/sha256");
|
|
5
9
|
const base_1 = require("@scure/base");
|
|
10
|
+
const superstruct_1 = require("superstruct");
|
|
11
|
+
const validate_npm_package_name_1 = __importDefault(require("validate-npm-package-name"));
|
|
6
12
|
const types_1 = require("./types");
|
|
7
|
-
exports.LOCALHOST_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1']);
|
|
8
13
|
exports.SNAP_PREFIX = 'wallet_snap_';
|
|
9
14
|
exports.SNAP_PREFIX_REGEX = new RegExp(`^${exports.SNAP_PREFIX}`, 'u');
|
|
10
15
|
// This RegEx matches valid npm package names (with some exceptions) and space-
|
|
@@ -67,6 +72,50 @@ function validateSnapShasum(manifest, sourceCode, errorMessage = 'Invalid Snap m
|
|
|
67
72
|
}
|
|
68
73
|
}
|
|
69
74
|
exports.validateSnapShasum = validateSnapShasum;
|
|
75
|
+
exports.LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'];
|
|
76
|
+
const LocalSnapIdSubUrlStruct = (0, types_1.uri)({
|
|
77
|
+
protocol: (0, superstruct_1.enums)(['http:', 'https:']),
|
|
78
|
+
hostname: (0, superstruct_1.enums)(exports.LOCALHOST_HOSTNAMES),
|
|
79
|
+
hash: (0, superstruct_1.empty)((0, superstruct_1.string)()),
|
|
80
|
+
search: (0, superstruct_1.empty)((0, superstruct_1.string)()),
|
|
81
|
+
});
|
|
82
|
+
exports.LocalSnapIdStruct = (0, superstruct_1.refine)((0, superstruct_1.string)(), 'local Snap Id', (value) => {
|
|
83
|
+
if (!value.startsWith(types_1.SnapIdPrefixes.local)) {
|
|
84
|
+
return `Expected local Snap ID, got "${value}".`;
|
|
85
|
+
}
|
|
86
|
+
const [error] = (0, superstruct_1.validate)(value.slice(types_1.SnapIdPrefixes.local.length), LocalSnapIdSubUrlStruct);
|
|
87
|
+
return error !== null && error !== void 0 ? error : true;
|
|
88
|
+
});
|
|
89
|
+
exports.NpmSnapIdStruct = (0, superstruct_1.intersection)([
|
|
90
|
+
(0, superstruct_1.string)(),
|
|
91
|
+
(0, types_1.uri)({
|
|
92
|
+
protocol: (0, superstruct_1.literal)(types_1.SnapIdPrefixes.npm),
|
|
93
|
+
pathname: (0, superstruct_1.refine)((0, superstruct_1.string)(), 'package name', function* (value) {
|
|
94
|
+
const normalized = value.startsWith('/') ? value.slice(1) : value;
|
|
95
|
+
const { errors, validForNewPackages, warnings } = (0, validate_npm_package_name_1.default)(normalized);
|
|
96
|
+
if (!validForNewPackages) {
|
|
97
|
+
if (errors === undefined) {
|
|
98
|
+
(0, utils_1.assert)(warnings !== undefined);
|
|
99
|
+
yield* warnings;
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
yield* errors;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return true;
|
|
106
|
+
}),
|
|
107
|
+
search: (0, superstruct_1.empty)((0, superstruct_1.string)()),
|
|
108
|
+
hash: (0, superstruct_1.empty)((0, superstruct_1.string)()),
|
|
109
|
+
}),
|
|
110
|
+
]);
|
|
111
|
+
exports.HttpSnapIdStruct = (0, superstruct_1.intersection)([
|
|
112
|
+
(0, superstruct_1.string)(),
|
|
113
|
+
(0, types_1.uri)({
|
|
114
|
+
protocol: (0, superstruct_1.enums)(['http:', 'https:']),
|
|
115
|
+
search: (0, superstruct_1.empty)((0, superstruct_1.string)()),
|
|
116
|
+
hash: (0, superstruct_1.empty)((0, superstruct_1.string)()),
|
|
117
|
+
}),
|
|
118
|
+
]);
|
|
70
119
|
/**
|
|
71
120
|
* Extracts the snap prefix from a snap ID.
|
|
72
121
|
*
|
|
@@ -74,7 +123,7 @@ exports.validateSnapShasum = validateSnapShasum;
|
|
|
74
123
|
* @returns The snap prefix from a snap id, e.g. `npm:`.
|
|
75
124
|
*/
|
|
76
125
|
function getSnapPrefix(snapId) {
|
|
77
|
-
const prefix = Object.values(types_1.SnapIdPrefixes).find((
|
|
126
|
+
const prefix = Object.values(types_1.SnapIdPrefixes).find((possiblePrefix) => snapId.startsWith(possiblePrefix));
|
|
78
127
|
if (prefix !== undefined) {
|
|
79
128
|
return prefix;
|
|
80
129
|
}
|
|
@@ -99,14 +148,14 @@ exports.getSnapPermissionName = getSnapPermissionName;
|
|
|
99
148
|
*/
|
|
100
149
|
function validateSnapId(snapId) {
|
|
101
150
|
if (!snapId || typeof snapId !== 'string') {
|
|
102
|
-
throw new Error(`Invalid snap id. Not a string
|
|
151
|
+
throw new Error(`Invalid snap id. Not a string.`);
|
|
103
152
|
}
|
|
104
153
|
for (const prefix of Object.values(types_1.SnapIdPrefixes)) {
|
|
105
154
|
if (snapId.startsWith(prefix) && snapId.replace(prefix, '').length > 0) {
|
|
106
155
|
return;
|
|
107
156
|
}
|
|
108
157
|
}
|
|
109
|
-
throw new Error(`Invalid snap id. Unknown prefix. Received: "${snapId}"
|
|
158
|
+
throw new Error(`Invalid snap id. Unknown prefix. Received: "${snapId}".`);
|
|
110
159
|
}
|
|
111
160
|
exports.validateSnapId = validateSnapId;
|
|
112
161
|
/**
|
package/dist/snaps.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snaps.js","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;AACA,iDAA8C;AAC9C,sCAAqC;AAGrC,mCAA8E;AAEjE,QAAA,mBAAmB,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC,CAAC;AACjE,QAAA,WAAW,GAAG,cAAc,CAAC;AAE7B,QAAA,iBAAiB,GAAG,IAAI,MAAM,CAAC,IAAI,mBAAW,EAAE,EAAE,GAAG,CAAC,CAAC;AAEpE,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACtH,QAAA,mBAAmB,GAC9B,kHAAkH,CAAC;AAarH,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,uCAAyB,CAAA;IACzB,mCAAqB,CAAA;IACrB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;AACrB,CAAC,EANW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAMrB;AAED,IAAY,gBAKX;AALD,WAAY,gBAAgB;IAC1B,mCAAe,CAAA;IACf,iCAAa,CAAA;IACb,mCAAe,CAAA;IACf,qCAAiB,CAAA;AACnB,CAAC,EALW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAK3B;AAqGD;;;GAGG;AACH,MAAa,gCAAiC,SAAQ,KAAK;IAGzD,YAAY,OAAe,EAAE,MAAmC;QAC9D,KAAK,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c,CAAC,EAAE;QAClD,IAAI,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACtE,OAAO;SACR;KACF;IAED,MAAM,IAAI,KAAK,CAAC,+CAA+C,MAAM,GAAG,CAAC,CAAC;AAC5E,CAAC;AAdD,wCAcC;AAED;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,OAAgB;IAC5C,OAAO,CACL,OAAO,OAAO,KAAK,QAAQ;QAC3B,kEAAkE,CAAC,IAAI,CACrE,OAAO,CACR,CACF,CAAC;AACJ,CAAC;AAPD,sCAOC","sourcesContent":["import { Json } from '@metamask/utils';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { base64 } from '@scure/base';\nimport { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport { SnapManifest, SnapPermissions } from './manifest/validation';\nimport { SnapId, SnapIdPrefixes, SnapValidationFailureReason } from './types';\n\nexport const LOCALHOST_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1']);\nexport const SNAP_PREFIX = 'wallet_snap_';\n\nexport const SNAP_PREFIX_REGEX = new RegExp(`^${SNAP_PREFIX}`, 'u');\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport type BlockedSnapInfo = { infoUrl?: string; reason?: string };\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: string };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap & {\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n};\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: SnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockedSnapInfo;\n\n /**\n * The name of the permission used to invoke the Snap.\n */\n permissionName: string;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: string;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'permissionName'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of a Snap source code string.\n *\n * @param sourceCode - The UTF-8 string source code of a Snap.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapSourceShasum(sourceCode: string): string {\n return base64.encode(sha256(sourceCode));\n}\n\nexport type ValidatedSnapId = `local:${string}` | `npm:${string}`;\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of a snap source code string.\n *\n * @param manifest - The manifest whose shasum to validate.\n * @param sourceCode - The source code of the snap.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n manifest: SnapManifest,\n sourceCode: string,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (manifest.source.shasum !== getSnapSourceShasum(sourceCode)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((p) =>\n snapId.startsWith(p),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Computes the permission name of a snap from its snap ID.\n *\n * @param snapId - The snap ID.\n * @returns The permission name corresponding to the given snap ID.\n */\nexport function getSnapPermissionName(snapId: string): string {\n return SNAP_PREFIX + snapId;\n}\n\n/**\n * Asserts the provided object is a snapId with a supported prefix.\n *\n * @param snapId - The object to validate.\n * @throws {@link Error}. If the validation fails.\n */\nexport function validateSnapId(\n snapId: unknown,\n): asserts snapId is ValidatedSnapId {\n if (!snapId || typeof snapId !== 'string') {\n throw new Error(`Invalid snap id. Not a string. Received \"${snapId}\"`);\n }\n\n for (const prefix of Object.values(SnapIdPrefixes)) {\n if (snapId.startsWith(prefix) && snapId.replace(prefix, '').length > 0) {\n return;\n }\n }\n\n throw new Error(`Invalid snap id. Unknown prefix. Received: \"${snapId}\"`);\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"snaps.js","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAAA,2CAA+C;AAC/C,iDAA8C;AAC9C,sCAAqC;AAErC,6CASqB;AACrB,0FAA2D;AAG3D,mCAKiB;AAGJ,QAAA,WAAW,GAAG,cAAc,CAAC;AAE7B,QAAA,iBAAiB,GAAG,IAAI,MAAM,CAAC,IAAI,mBAAW,EAAE,EAAE,GAAG,CAAC,CAAC;AAEpE,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACtH,QAAA,mBAAmB,GAC9B,kHAAkH,CAAC;AAarH,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,uC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,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,sBAAc,CAAC,EAAE;QAClD,IAAI,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACtE,OAAO;SACR;KACF;IAED,MAAM,IAAI,KAAK,CAAC,+CAA+C,MAAM,IAAI,CAAC,CAAC;AAC7E,CAAC;AAdD,wCAcC;AAED;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,OAAgB;IAC5C,OAAO,CACL,OAAO,OAAO,KAAK,QAAQ;QAC3B,kEAAkE,CAAC,IAAI,CACrE,OAAO,CACR,CACF,CAAC;AACJ,CAAC;AAPD,sCAOC","sourcesContent":["import { assert, Json } from '@metamask/utils';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { base64 } from '@scure/base';\nimport { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport {\n empty,\n enums,\n intersection,\n literal,\n refine,\n string,\n Struct,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapManifest, SnapPermissions } from './manifest/validation';\nimport {\n SnapId,\n SnapIdPrefixes,\n SnapValidationFailureReason,\n uri,\n} from './types';\nimport { SemVerVersion } from './versions';\n\nexport const SNAP_PREFIX = 'wallet_snap_';\n\nexport const SNAP_PREFIX_REGEX = new RegExp(`^${SNAP_PREFIX}`, 'u');\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport type BlockedSnapInfo = { infoUrl?: string; reason?: string };\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: string };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap & {\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n};\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: SnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockedSnapInfo;\n\n /**\n * The name of the permission used to invoke the Snap.\n */\n permissionName: string;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'permissionName'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of a Snap source code string.\n *\n * @param sourceCode - The UTF-8 string source code of a Snap.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapSourceShasum(sourceCode: string): string {\n return base64.encode(sha256(sourceCode));\n}\n\nexport type ValidatedSnapId = `local:${string}` | `npm:${string}`;\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of a snap source code string.\n *\n * @param manifest - The manifest whose shasum to validate.\n * @param sourceCode - The source code of the snap.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n manifest: SnapManifest,\n sourceCode: string,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (manifest.source.shasum !== getSnapSourceShasum(sourceCode)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(string(), 'local Snap Id', (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local Snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n});\nexport const NpmSnapIdStruct = intersection([\n string(),\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n string(),\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Computes the permission name of a snap from its snap ID.\n *\n * @param snapId - The snap ID.\n * @returns The permission name corresponding to the given snap ID.\n */\nexport function getSnapPermissionName(snapId: string): string {\n return SNAP_PREFIX + snapId;\n}\n\n/**\n * Asserts the provided object is a snapId with a supported prefix.\n *\n * @param snapId - The object to validate.\n * @throws {@link Error}. If the validation fails.\n */\nexport function validateSnapId(\n snapId: unknown,\n): asserts snapId is ValidatedSnapId {\n if (!snapId || typeof snapId !== 'string') {\n throw new Error(`Invalid snap id. Not a string.`);\n }\n\n for (const prefix of Object.values(SnapIdPrefixes)) {\n if (snapId.startsWith(prefix) && snapId.replace(prefix, '').length > 0) {\n return;\n }\n }\n\n throw new Error(`Invalid snap id. Unknown prefix. Received: \"${snapId}\".`);\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,34 +1,30 @@
|
|
|
1
1
|
import { SnapFunctionExports, SnapKeyring as Keyring } from '@metamask/snaps-types';
|
|
2
2
|
import { Json } from '@metamask/utils';
|
|
3
|
-
import { Infer } from 'superstruct';
|
|
3
|
+
import { Infer, Struct } from 'superstruct';
|
|
4
4
|
import { SnapManifest } from './manifest/validation';
|
|
5
5
|
export declare enum NpmSnapFileNames {
|
|
6
6
|
PackageJson = "package.json",
|
|
7
7
|
Manifest = "snap.manifest.json"
|
|
8
8
|
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
*/
|
|
12
|
-
export declare const VersionStruct: import("superstruct").Struct<string, null>;
|
|
13
|
-
export declare const NameStruct: import("superstruct").Struct<string, null>;
|
|
14
|
-
export declare const NpmSnapPackageJsonStruct: import("superstruct").Struct<{
|
|
9
|
+
export declare const NameStruct: Struct<string, null>;
|
|
10
|
+
export declare const NpmSnapPackageJsonStruct: Struct<{
|
|
15
11
|
name: string;
|
|
16
|
-
version:
|
|
12
|
+
version: import("./versions").SemVerVersion;
|
|
17
13
|
repository?: {
|
|
18
14
|
type: string;
|
|
19
15
|
url: string;
|
|
20
16
|
} | undefined;
|
|
21
17
|
main?: string | undefined;
|
|
22
18
|
}, {
|
|
23
|
-
version: import("
|
|
24
|
-
name:
|
|
25
|
-
main:
|
|
26
|
-
repository:
|
|
19
|
+
version: Struct<import("./versions").SemVerVersion, null>;
|
|
20
|
+
name: Struct<string, null>;
|
|
21
|
+
main: Struct<string | undefined, null>;
|
|
22
|
+
repository: Struct<{
|
|
27
23
|
type: string;
|
|
28
24
|
url: string;
|
|
29
25
|
} | undefined, {
|
|
30
|
-
type:
|
|
31
|
-
url:
|
|
26
|
+
type: Struct<string, null>;
|
|
27
|
+
url: Struct<string, null>;
|
|
32
28
|
}>;
|
|
33
29
|
}>;
|
|
34
30
|
export declare type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> & Record<string, any>;
|
|
@@ -104,4 +100,25 @@ declare type ObjectParameters<Type extends Record<string, (...args: any[]) => un
|
|
|
104
100
|
declare type KeyringParameter<Fn> = Fn extends (...args: any[]) => unknown ? Parameters<Fn> : never;
|
|
105
101
|
declare type KeyringParameters = KeyringParameter<Keyring[keyof Keyring]>;
|
|
106
102
|
export declare type SnapExportsParameters = ObjectParameters<SnapFunctionExports> | KeyringParameters;
|
|
103
|
+
declare const brand: unique symbol;
|
|
104
|
+
export declare type Opaque<Base, Brand extends symbol> = Base & {
|
|
105
|
+
[brand]: Brand;
|
|
106
|
+
};
|
|
107
|
+
declare type UriOptions<T extends string> = {
|
|
108
|
+
protocol?: Struct<T>;
|
|
109
|
+
hash?: Struct<T>;
|
|
110
|
+
port?: Struct<T>;
|
|
111
|
+
hostname?: Struct<T>;
|
|
112
|
+
pathname?: Struct<T>;
|
|
113
|
+
search?: Struct<T>;
|
|
114
|
+
};
|
|
115
|
+
export declare const uri: (opts?: UriOptions<any>) => Struct<string | URL, null>;
|
|
116
|
+
/**
|
|
117
|
+
* Returns whether a given value is a valid URL.
|
|
118
|
+
*
|
|
119
|
+
* @param url - The value to check.
|
|
120
|
+
* @param opts - Optional constraints for url checking.
|
|
121
|
+
* @returns Whether `url` is valid URL or not.
|
|
122
|
+
*/
|
|
123
|
+
export declare function isValidUrl(url: unknown, opts?: UriOptions<any>): url is string | URL;
|
|
107
124
|
export {};
|