@metamask/utils 9.2.1 → 10.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -1
- package/dist/caip-types.cjs +33 -1
- package/dist/caip-types.cjs.map +1 -1
- package/dist/caip-types.d.cts +28 -0
- package/dist/caip-types.d.cts.map +1 -1
- package/dist/caip-types.d.mts +28 -0
- package/dist/caip-types.d.mts.map +1 -1
- package/dist/caip-types.mjs +30 -0
- package/dist/caip-types.mjs.map +1 -1
- package/dist/json.cjs +42 -15
- package/dist/json.cjs.map +1 -1
- package/dist/json.d.cts.map +1 -1
- package/dist/json.d.mts.map +1 -1
- package/dist/json.mjs +43 -16
- package/dist/json.mjs.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [10.0.0]
|
|
10
|
+
### Changed
|
|
11
|
+
- **BREAKING:** Drop support for Node.js versions 16, 21 ([#212](https://github.com/MetaMask/utils/pull/212))
|
|
12
|
+
- Improve JSON validation performance ([#218](https://github.com/MetaMask/utils/pull/218))
|
|
13
|
+
|
|
14
|
+
## [9.3.0]
|
|
15
|
+
### Added
|
|
16
|
+
- Add support for CAIP-19 ([#183](https://github.com/MetaMask/utils/pull/183))
|
|
17
|
+
- Add `Bip122` member to `KnownCaipNamespace` ([#213](https://github.com/MetaMask/utils/pull/213))
|
|
18
|
+
|
|
9
19
|
## [9.2.1]
|
|
10
20
|
### Fixed
|
|
11
21
|
- Fix wrong types for CAIP-2 and CAIP-10 structs ([#210](https://github.com/MetaMask/utils/pull/210))
|
|
@@ -259,7 +269,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
259
269
|
### Added
|
|
260
270
|
- Initial release
|
|
261
271
|
|
|
262
|
-
[Unreleased]: https://github.com/MetaMask/utils/compare/
|
|
272
|
+
[Unreleased]: https://github.com/MetaMask/utils/compare/v10.0.0...HEAD
|
|
273
|
+
[10.0.0]: https://github.com/MetaMask/utils/compare/v9.3.0...v10.0.0
|
|
274
|
+
[9.3.0]: https://github.com/MetaMask/utils/compare/v9.2.1...v9.3.0
|
|
263
275
|
[9.2.1]: https://github.com/MetaMask/utils/compare/v9.2.0...v9.2.1
|
|
264
276
|
[9.2.0]: https://github.com/MetaMask/utils/compare/v9.1.0...v9.2.0
|
|
265
277
|
[9.1.0]: https://github.com/MetaMask/utils/compare/v9.0.0...v9.1.0
|
package/dist/caip-types.cjs
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.toCaipChainId = exports.parseCaipAccountId = exports.parseCaipChainId = exports.isCaipAccountAddress = exports.isCaipAccountId = exports.isCaipReference = exports.isCaipNamespace = exports.isCaipChainId = exports.KnownCaipNamespace = exports.CaipAccountAddressStruct = exports.CaipAccountIdStruct = exports.CaipReferenceStruct = exports.CaipNamespaceStruct = exports.CaipChainIdStruct = exports.CAIP_ACCOUNT_ADDRESS_REGEX = exports.CAIP_ACCOUNT_ID_REGEX = exports.CAIP_REFERENCE_REGEX = exports.CAIP_NAMESPACE_REGEX = exports.CAIP_CHAIN_ID_REGEX = void 0;
|
|
3
|
+
exports.toCaipChainId = exports.parseCaipAccountId = exports.parseCaipChainId = exports.isCaipAssetId = exports.isCaipAssetType = exports.isCaipAccountAddress = exports.isCaipAccountId = exports.isCaipReference = exports.isCaipNamespace = exports.isCaipChainId = exports.KnownCaipNamespace = exports.CaipAssetIdStruct = exports.CaipAssetTypeStruct = exports.CaipAccountAddressStruct = exports.CaipAccountIdStruct = exports.CaipReferenceStruct = exports.CaipNamespaceStruct = exports.CaipChainIdStruct = exports.CAIP_ASSET_ID_REGEX = exports.CAIP_ASSET_TYPE_REGEX = exports.CAIP_ACCOUNT_ADDRESS_REGEX = exports.CAIP_ACCOUNT_ID_REGEX = exports.CAIP_REFERENCE_REGEX = exports.CAIP_NAMESPACE_REGEX = exports.CAIP_CHAIN_ID_REGEX = void 0;
|
|
4
4
|
const superstruct_1 = require("@metamask/superstruct");
|
|
5
5
|
exports.CAIP_CHAIN_ID_REGEX = /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32})$/u;
|
|
6
6
|
exports.CAIP_NAMESPACE_REGEX = /^[-a-z0-9]{3,8}$/u;
|
|
7
7
|
exports.CAIP_REFERENCE_REGEX = /^[-_a-zA-Z0-9]{1,32}$/u;
|
|
8
8
|
exports.CAIP_ACCOUNT_ID_REGEX = /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32})):(?<accountAddress>[-.%a-zA-Z0-9]{1,128})$/u;
|
|
9
9
|
exports.CAIP_ACCOUNT_ADDRESS_REGEX = /^[-.%a-zA-Z0-9]{1,128}$/u;
|
|
10
|
+
exports.CAIP_ASSET_TYPE_REGEX = /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32}))\/(?<assetNamespace>[-a-z0-9]{3,8}):(?<assetReference>[-.%a-zA-Z0-9]{1,128})$/u;
|
|
11
|
+
exports.CAIP_ASSET_ID_REGEX = /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32}))\/(?<assetNamespace>[-a-z0-9]{3,8}):(?<assetReference>[-.%a-zA-Z0-9]{1,128})\/(?<tokenId>[-.%a-zA-Z0-9]{1,78})$/u;
|
|
10
12
|
/**
|
|
11
13
|
* A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
|
|
12
14
|
*/
|
|
@@ -27,9 +29,19 @@ exports.CaipAccountIdStruct = (0, superstruct_1.pattern)((0, superstruct_1.strin
|
|
|
27
29
|
* A CAIP-10 account address, i.e., the third part of the CAIP account ID.
|
|
28
30
|
*/
|
|
29
31
|
exports.CaipAccountAddressStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), exports.CAIP_ACCOUNT_ADDRESS_REGEX);
|
|
32
|
+
/**
|
|
33
|
+
* A CAIP-19 asset type identifier, i.e., a human-readable type of asset identifier.
|
|
34
|
+
*/
|
|
35
|
+
exports.CaipAssetTypeStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), exports.CAIP_ASSET_TYPE_REGEX);
|
|
36
|
+
/**
|
|
37
|
+
* A CAIP-19 asset ID identifier, i.e., a human-readable type of asset ID.
|
|
38
|
+
*/
|
|
39
|
+
exports.CaipAssetIdStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), exports.CAIP_ASSET_ID_REGEX);
|
|
30
40
|
/** Known CAIP namespaces. */
|
|
31
41
|
var KnownCaipNamespace;
|
|
32
42
|
(function (KnownCaipNamespace) {
|
|
43
|
+
/** BIP-122 (Bitcoin) compatible chains. */
|
|
44
|
+
KnownCaipNamespace["Bip122"] = "bip122";
|
|
33
45
|
/** EIP-155 compatible chains. */
|
|
34
46
|
KnownCaipNamespace["Eip155"] = "eip155";
|
|
35
47
|
KnownCaipNamespace["Wallet"] = "wallet";
|
|
@@ -84,6 +96,26 @@ function isCaipAccountAddress(value) {
|
|
|
84
96
|
return (0, superstruct_1.is)(value, exports.CaipAccountAddressStruct);
|
|
85
97
|
}
|
|
86
98
|
exports.isCaipAccountAddress = isCaipAccountAddress;
|
|
99
|
+
/**
|
|
100
|
+
* Check if the given value is a {@link CaipAssetType}.
|
|
101
|
+
*
|
|
102
|
+
* @param value - The value to check.
|
|
103
|
+
* @returns Whether the value is a {@link CaipAssetType}.
|
|
104
|
+
*/
|
|
105
|
+
function isCaipAssetType(value) {
|
|
106
|
+
return (0, superstruct_1.is)(value, exports.CaipAssetTypeStruct);
|
|
107
|
+
}
|
|
108
|
+
exports.isCaipAssetType = isCaipAssetType;
|
|
109
|
+
/**
|
|
110
|
+
* Check if the given value is a {@link CaipAssetId}.
|
|
111
|
+
*
|
|
112
|
+
* @param value - The value to check.
|
|
113
|
+
* @returns Whether the value is a {@link CaipAssetId}.
|
|
114
|
+
*/
|
|
115
|
+
function isCaipAssetId(value) {
|
|
116
|
+
return (0, superstruct_1.is)(value, exports.CaipAssetIdStruct);
|
|
117
|
+
}
|
|
118
|
+
exports.isCaipAssetId = isCaipAssetId;
|
|
87
119
|
/**
|
|
88
120
|
* Parse a CAIP-2 chain ID to an object containing the namespace and reference.
|
|
89
121
|
* This validates the CAIP-2 chain ID before parsing it.
|
package/dist/caip-types.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"caip-types.cjs","sourceRoot":"","sources":["../src/caip-types.ts"],"names":[],"mappings":";;;AAAA,uDAA4D;AAG/C,QAAA,mBAAmB,GAC9B,mEAAmE,CAAC;AAEzD,QAAA,oBAAoB,GAAG,mBAAmB,CAAC;AAE3C,QAAA,oBAAoB,GAAG,wBAAwB,CAAC;AAEhD,QAAA,qBAAqB,GAChC,wHAAwH,CAAC;AAE9G,QAAA,0BAA0B,GAAG,0BAA0B,CAAC;AAErE;;GAEG;AACU,QAAA,iBAAiB,GAAG,IAAA,qBAAO,EACtC,IAAA,oBAAM,GAAE,EACR,2BAAmB,CACS,CAAC;AAG/B;;GAEG;AACU,QAAA,mBAAmB,GAAG,IAAA,qBAAO,EAAC,IAAA,oBAAM,GAAE,EAAE,4BAAoB,CAAC,CAAC;AAG3E;;GAEG;AACU,QAAA,mBAAmB,GAAG,IAAA,qBAAO,EAAC,IAAA,oBAAM,GAAE,EAAE,4BAAoB,CAAC,CAAC;AAG3E;;GAEG;AACU,QAAA,mBAAmB,GAAG,IAAA,qBAAO,EACxC,IAAA,oBAAM,GAAE,EACR,6BAAqB,CACS,CAAC;AAGjC;;GAEG;AACU,QAAA,wBAAwB,GAAG,IAAA,qBAAO,EAC7C,IAAA,oBAAM,GAAE,EACR,kCAA0B,CAC3B,CAAC;AAGF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AMG;AACH,SAAgB,kBAAkB,CAAC,aAA4B;IAK7D,MAAM,KAAK,GAAG,6BAAqB,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;IACxD,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE;QAClB,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;KAC7C;IAED,OAAO;QACL,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,cAAoC;QAC1D,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,OAAsB;QAC5C,KAAK,EAAE;YACL,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAA0B;YAClD,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAA0B;SACnD;KACF,CAAC;AACJ,CAAC;AAlBD,gDAkBC;AAED;;;;;;;;;;;;;;GAcG;AACH,SAAgB,aAAa,CAC3B,SAAwB,EACxB,SAAwB;IAExB,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,EAAE;QAC/B,MAAM,IAAI,KAAK,CACb,oCAAoC,4BAAoB,CAAC,QAAQ,EAAE,EAAE,CACtE,CAAC;KACH;IAED,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,EAAE;QAC/B,MAAM,IAAI,KAAK,CACb,oCAAoC,4BAAoB,CAAC,QAAQ,EAAE,EAAE,CACtE,CAAC;KACH;IAED,OAAO,GAAG,SAAS,IAAI,SAAS,EAAE,CAAC;AACrC,CAAC;AAjBD,sCAiBC","sourcesContent":["import { is, pattern, string } from '@metamask/superstruct';\nimport type { Infer, Struct } from '@metamask/superstruct';\n\nexport const CAIP_CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32})$/u;\n\nexport const CAIP_NAMESPACE_REGEX = /^[-a-z0-9]{3,8}$/u;\n\nexport const CAIP_REFERENCE_REGEX = /^[-_a-zA-Z0-9]{1,32}$/u;\n\nexport const CAIP_ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32})):(?<accountAddress>[-.%a-zA-Z0-9]{1,128})$/u;\n\nexport const CAIP_ACCOUNT_ADDRESS_REGEX = /^[-.%a-zA-Z0-9]{1,128}$/u;\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const CaipChainIdStruct = pattern(\n string(),\n CAIP_CHAIN_ID_REGEX,\n) as Struct<CaipChainId, null>;\nexport type CaipChainId = `${string}:${string}`;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a CAIP chain ID.\n */\nexport const CaipNamespaceStruct = pattern(string(), CAIP_NAMESPACE_REGEX);\nexport type CaipNamespace = Infer<typeof CaipNamespaceStruct>;\n\n/**\n * A CAIP-2 reference, i.e., the second part of a CAIP chain ID.\n */\nexport const CaipReferenceStruct = pattern(string(), CAIP_REFERENCE_REGEX);\nexport type CaipReference = Infer<typeof CaipReferenceStruct>;\n\n/**\n * A CAIP-10 account ID, i.e., a human-readable namespace, reference, and account address.\n */\nexport const CaipAccountIdStruct = pattern(\n string(),\n CAIP_ACCOUNT_ID_REGEX,\n) as Struct<CaipAccountId, null>;\nexport type CaipAccountId = `${string}:${string}:${string}`;\n\n/**\n * A CAIP-10 account address, i.e., the third part of the CAIP account ID.\n */\nexport const CaipAccountAddressStruct = pattern(\n string(),\n CAIP_ACCOUNT_ADDRESS_REGEX,\n);\nexport type CaipAccountAddress = Infer<typeof CaipAccountAddressStruct>;\n\n/** Known CAIP namespaces. */\nexport enum KnownCaipNamespace {\n /** EIP-155 compatible chains. */\n Eip155 = 'eip155',\n Wallet = 'wallet',\n}\n\n/**\n * Check if the given value is a {@link CaipChainId}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipChainId}.\n */\nexport function isCaipChainId(value: unknown): value is CaipChainId {\n return is(value, CaipChainIdStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipNamespace}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipNamespace}.\n */\nexport function isCaipNamespace(value: unknown): value is CaipNamespace {\n return is(value, CaipNamespaceStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipReference}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipReference}.\n */\nexport function isCaipReference(value: unknown): value is CaipReference {\n return is(value, CaipReferenceStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipAccountId}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipAccountId}.\n */\nexport function isCaipAccountId(value: unknown): value is CaipAccountId {\n return is(value, CaipAccountIdStruct);\n}\n\n/**\n * Check if a value is a {@link CaipAccountAddress}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link CaipAccountAddress}.\n */\nexport function isCaipAccountAddress(\n value: unknown,\n): value is CaipAccountAddress {\n return is(value, CaipAccountAddressStruct);\n}\n\n/**\n * Parse a CAIP-2 chain ID to an object containing the namespace and reference.\n * This validates the CAIP-2 chain ID before parsing it.\n *\n * @param caipChainId - The CAIP-2 chain ID to validate and parse.\n * @returns The parsed CAIP-2 chain ID.\n */\nexport function parseCaipChainId(caipChainId: CaipChainId): {\n namespace: CaipNamespace;\n reference: CaipReference;\n} {\n const match = CAIP_CHAIN_ID_REGEX.exec(caipChainId);\n if (!match?.groups) {\n throw new Error('Invalid CAIP chain ID.');\n }\n\n return {\n namespace: match.groups.namespace as CaipNamespace,\n reference: match.groups.reference as CaipReference,\n };\n}\n\n/**\n * Parse an CAIP-10 account ID to an object containing the chain ID, parsed chain ID, and account address.\n * This validates the CAIP-10 account ID before parsing it.\n *\n * @param caipAccountId - The CAIP-10 account ID to validate and parse.\n * @returns The parsed CAIP-10 account ID.\n */\nexport function parseCaipAccountId(caipAccountId: CaipAccountId): {\n address: CaipAccountAddress;\n chainId: CaipChainId;\n chain: { namespace: CaipNamespace; reference: CaipReference };\n} {\n const match = CAIP_ACCOUNT_ID_REGEX.exec(caipAccountId);\n if (!match?.groups) {\n throw new Error('Invalid CAIP account ID.');\n }\n\n return {\n address: match.groups.accountAddress as CaipAccountAddress,\n chainId: match.groups.chainId as CaipChainId,\n chain: {\n namespace: match.groups.namespace as CaipNamespace,\n reference: match.groups.reference as CaipReference,\n },\n };\n}\n\n/**\n * Chain ID as defined per the CAIP-2\n * {@link https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md}.\n *\n * It defines a way to uniquely identify any blockchain in a human-readable\n * way.\n *\n * @param namespace - The standard (ecosystem) of similar blockchains.\n * @param reference - Identify of a blockchain within a given namespace.\n * @throws {@link Error}\n * This exception is thrown if the inputs does not comply with the CAIP-2\n * syntax specification\n * {@link https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md#syntax}.\n * @returns A CAIP chain ID.\n */\nexport function toCaipChainId(\n namespace: CaipNamespace,\n reference: CaipReference,\n): CaipChainId {\n if (!isCaipNamespace(namespace)) {\n throw new Error(\n `Invalid \"namespace\", must match: ${CAIP_NAMESPACE_REGEX.toString()}`,\n );\n }\n\n if (!isCaipReference(reference)) {\n throw new Error(\n `Invalid \"reference\", must match: ${CAIP_REFERENCE_REGEX.toString()}`,\n );\n }\n\n return `${namespace}:${reference}`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"caip-types.cjs","sourceRoot":"","sources":["../src/caip-types.ts"],"names":[],"mappings":";;;AAAA,uDAA4D;AAG/C,QAAA,mBAAmB,GAC9B,mEAAmE,CAAC;AAEzD,QAAA,oBAAoB,GAAG,mBAAmB,CAAC;AAE3C,QAAA,oBAAoB,GAAG,wBAAwB,CAAC;AAEhD,QAAA,qBAAqB,GAChC,wHAAwH,CAAC;AAE9G,QAAA,0BAA0B,GAAG,0BAA0B,CAAC;AAExD,QAAA,qBAAqB,GAChC,2JAA2J,CAAC;AAEjJ,QAAA,mBAAmB,GAC9B,6LAA6L,CAAC;AAEhM;;GAEG;AACU,QAAA,iBAAiB,GAAG,IAAA,qBAAO,EACtC,IAAA,oBAAM,GAAE,EACR,2BAAmB,CACS,CAAC;A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AM,CAAC,OAAsB;QAC5C,KAAK,EAAE;YACL,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAA0B;YAClD,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAA0B;SACnD;KACF,CAAC;AACJ,CAAC;AAlBD,gDAkBC;AAED;;;;;;;;;;;;;;GAcG;AACH,SAAgB,aAAa,CAC3B,SAAwB,EACxB,SAAwB;IAExB,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,EAAE;QAC/B,MAAM,IAAI,KAAK,CACb,oCAAoC,4BAAoB,CAAC,QAAQ,EAAE,EAAE,CACtE,CAAC;KACH;IAED,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,EAAE;QAC/B,MAAM,IAAI,KAAK,CACb,oCAAoC,4BAAoB,CAAC,QAAQ,EAAE,EAAE,CACtE,CAAC;KACH;IAED,OAAO,GAAG,SAAS,IAAI,SAAS,EAAE,CAAC;AACrC,CAAC;AAjBD,sCAiBC","sourcesContent":["import { is, pattern, string } from '@metamask/superstruct';\nimport type { Infer, Struct } from '@metamask/superstruct';\n\nexport const CAIP_CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32})$/u;\n\nexport const CAIP_NAMESPACE_REGEX = /^[-a-z0-9]{3,8}$/u;\n\nexport const CAIP_REFERENCE_REGEX = /^[-_a-zA-Z0-9]{1,32}$/u;\n\nexport const CAIP_ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32})):(?<accountAddress>[-.%a-zA-Z0-9]{1,128})$/u;\n\nexport const CAIP_ACCOUNT_ADDRESS_REGEX = /^[-.%a-zA-Z0-9]{1,128}$/u;\n\nexport const CAIP_ASSET_TYPE_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32}))\\/(?<assetNamespace>[-a-z0-9]{3,8}):(?<assetReference>[-.%a-zA-Z0-9]{1,128})$/u;\n\nexport const CAIP_ASSET_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32}))\\/(?<assetNamespace>[-a-z0-9]{3,8}):(?<assetReference>[-.%a-zA-Z0-9]{1,128})\\/(?<tokenId>[-.%a-zA-Z0-9]{1,78})$/u;\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const CaipChainIdStruct = pattern(\n string(),\n CAIP_CHAIN_ID_REGEX,\n) as Struct<CaipChainId, null>;\nexport type CaipChainId = `${string}:${string}`;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a CAIP chain ID.\n */\nexport const CaipNamespaceStruct = pattern(string(), CAIP_NAMESPACE_REGEX);\nexport type CaipNamespace = Infer<typeof CaipNamespaceStruct>;\n\n/**\n * A CAIP-2 reference, i.e., the second part of a CAIP chain ID.\n */\nexport const CaipReferenceStruct = pattern(string(), CAIP_REFERENCE_REGEX);\nexport type CaipReference = Infer<typeof CaipReferenceStruct>;\n\n/**\n * A CAIP-10 account ID, i.e., a human-readable namespace, reference, and account address.\n */\nexport const CaipAccountIdStruct = pattern(\n string(),\n CAIP_ACCOUNT_ID_REGEX,\n) as Struct<CaipAccountId, null>;\nexport type CaipAccountId = `${string}:${string}:${string}`;\n\n/**\n * A CAIP-10 account address, i.e., the third part of the CAIP account ID.\n */\nexport const CaipAccountAddressStruct = pattern(\n string(),\n CAIP_ACCOUNT_ADDRESS_REGEX,\n);\nexport type CaipAccountAddress = Infer<typeof CaipAccountAddressStruct>;\n\n/**\n * A CAIP-19 asset type identifier, i.e., a human-readable type of asset identifier.\n */\nexport const CaipAssetTypeStruct = pattern(\n string(),\n CAIP_ASSET_TYPE_REGEX,\n) as Struct<CaipAssetType, null>;\nexport type CaipAssetType = `${string}:${string}/${string}:${string}`;\n\n/**\n * A CAIP-19 asset ID identifier, i.e., a human-readable type of asset ID.\n */\nexport const CaipAssetIdStruct = pattern(\n string(),\n CAIP_ASSET_ID_REGEX,\n) as Struct<CaipAssetId, null>;\nexport type CaipAssetId = `${string}:${string}/${string}:${string}/${string}`;\n\n/** Known CAIP namespaces. */\nexport enum KnownCaipNamespace {\n /** BIP-122 (Bitcoin) compatible chains. */\n Bip122 = 'bip122',\n /** EIP-155 compatible chains. */\n Eip155 = 'eip155',\n Wallet = 'wallet',\n}\n\n/**\n * Check if the given value is a {@link CaipChainId}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipChainId}.\n */\nexport function isCaipChainId(value: unknown): value is CaipChainId {\n return is(value, CaipChainIdStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipNamespace}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipNamespace}.\n */\nexport function isCaipNamespace(value: unknown): value is CaipNamespace {\n return is(value, CaipNamespaceStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipReference}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipReference}.\n */\nexport function isCaipReference(value: unknown): value is CaipReference {\n return is(value, CaipReferenceStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipAccountId}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipAccountId}.\n */\nexport function isCaipAccountId(value: unknown): value is CaipAccountId {\n return is(value, CaipAccountIdStruct);\n}\n\n/**\n * Check if a value is a {@link CaipAccountAddress}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link CaipAccountAddress}.\n */\nexport function isCaipAccountAddress(\n value: unknown,\n): value is CaipAccountAddress {\n return is(value, CaipAccountAddressStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipAssetType}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipAssetType}.\n */\nexport function isCaipAssetType(value: unknown): value is CaipAssetType {\n return is(value, CaipAssetTypeStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipAssetId}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipAssetId}.\n */\nexport function isCaipAssetId(value: unknown): value is CaipAssetId {\n return is(value, CaipAssetIdStruct);\n}\n\n/**\n * Parse a CAIP-2 chain ID to an object containing the namespace and reference.\n * This validates the CAIP-2 chain ID before parsing it.\n *\n * @param caipChainId - The CAIP-2 chain ID to validate and parse.\n * @returns The parsed CAIP-2 chain ID.\n */\nexport function parseCaipChainId(caipChainId: CaipChainId): {\n namespace: CaipNamespace;\n reference: CaipReference;\n} {\n const match = CAIP_CHAIN_ID_REGEX.exec(caipChainId);\n if (!match?.groups) {\n throw new Error('Invalid CAIP chain ID.');\n }\n\n return {\n namespace: match.groups.namespace as CaipNamespace,\n reference: match.groups.reference as CaipReference,\n };\n}\n\n/**\n * Parse an CAIP-10 account ID to an object containing the chain ID, parsed chain ID, and account address.\n * This validates the CAIP-10 account ID before parsing it.\n *\n * @param caipAccountId - The CAIP-10 account ID to validate and parse.\n * @returns The parsed CAIP-10 account ID.\n */\nexport function parseCaipAccountId(caipAccountId: CaipAccountId): {\n address: CaipAccountAddress;\n chainId: CaipChainId;\n chain: { namespace: CaipNamespace; reference: CaipReference };\n} {\n const match = CAIP_ACCOUNT_ID_REGEX.exec(caipAccountId);\n if (!match?.groups) {\n throw new Error('Invalid CAIP account ID.');\n }\n\n return {\n address: match.groups.accountAddress as CaipAccountAddress,\n chainId: match.groups.chainId as CaipChainId,\n chain: {\n namespace: match.groups.namespace as CaipNamespace,\n reference: match.groups.reference as CaipReference,\n },\n };\n}\n\n/**\n * Chain ID as defined per the CAIP-2\n * {@link https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md}.\n *\n * It defines a way to uniquely identify any blockchain in a human-readable\n * way.\n *\n * @param namespace - The standard (ecosystem) of similar blockchains.\n * @param reference - Identify of a blockchain within a given namespace.\n * @throws {@link Error}\n * This exception is thrown if the inputs does not comply with the CAIP-2\n * syntax specification\n * {@link https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md#syntax}.\n * @returns A CAIP chain ID.\n */\nexport function toCaipChainId(\n namespace: CaipNamespace,\n reference: CaipReference,\n): CaipChainId {\n if (!isCaipNamespace(namespace)) {\n throw new Error(\n `Invalid \"namespace\", must match: ${CAIP_NAMESPACE_REGEX.toString()}`,\n );\n }\n\n if (!isCaipReference(reference)) {\n throw new Error(\n `Invalid \"reference\", must match: ${CAIP_REFERENCE_REGEX.toString()}`,\n );\n }\n\n return `${namespace}:${reference}`;\n}\n"]}
|
package/dist/caip-types.d.cts
CHANGED
|
@@ -4,6 +4,8 @@ export declare const CAIP_NAMESPACE_REGEX: RegExp;
|
|
|
4
4
|
export declare const CAIP_REFERENCE_REGEX: RegExp;
|
|
5
5
|
export declare const CAIP_ACCOUNT_ID_REGEX: RegExp;
|
|
6
6
|
export declare const CAIP_ACCOUNT_ADDRESS_REGEX: RegExp;
|
|
7
|
+
export declare const CAIP_ASSET_TYPE_REGEX: RegExp;
|
|
8
|
+
export declare const CAIP_ASSET_ID_REGEX: RegExp;
|
|
7
9
|
/**
|
|
8
10
|
* A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
|
|
9
11
|
*/
|
|
@@ -29,8 +31,20 @@ export type CaipAccountId = `${string}:${string}:${string}`;
|
|
|
29
31
|
*/
|
|
30
32
|
export declare const CaipAccountAddressStruct: Struct<string, null>;
|
|
31
33
|
export type CaipAccountAddress = Infer<typeof CaipAccountAddressStruct>;
|
|
34
|
+
/**
|
|
35
|
+
* A CAIP-19 asset type identifier, i.e., a human-readable type of asset identifier.
|
|
36
|
+
*/
|
|
37
|
+
export declare const CaipAssetTypeStruct: Struct<`${string}:${string}/${string}:${string}`, null>;
|
|
38
|
+
export type CaipAssetType = `${string}:${string}/${string}:${string}`;
|
|
39
|
+
/**
|
|
40
|
+
* A CAIP-19 asset ID identifier, i.e., a human-readable type of asset ID.
|
|
41
|
+
*/
|
|
42
|
+
export declare const CaipAssetIdStruct: Struct<`${string}:${string}/${string}:${string}/${string}`, null>;
|
|
43
|
+
export type CaipAssetId = `${string}:${string}/${string}:${string}/${string}`;
|
|
32
44
|
/** Known CAIP namespaces. */
|
|
33
45
|
export declare enum KnownCaipNamespace {
|
|
46
|
+
/** BIP-122 (Bitcoin) compatible chains. */
|
|
47
|
+
Bip122 = "bip122",
|
|
34
48
|
/** EIP-155 compatible chains. */
|
|
35
49
|
Eip155 = "eip155",
|
|
36
50
|
Wallet = "wallet"
|
|
@@ -70,6 +84,20 @@ export declare function isCaipAccountId(value: unknown): value is CaipAccountId;
|
|
|
70
84
|
* @returns True if the value is a valid {@link CaipAccountAddress}.
|
|
71
85
|
*/
|
|
72
86
|
export declare function isCaipAccountAddress(value: unknown): value is CaipAccountAddress;
|
|
87
|
+
/**
|
|
88
|
+
* Check if the given value is a {@link CaipAssetType}.
|
|
89
|
+
*
|
|
90
|
+
* @param value - The value to check.
|
|
91
|
+
* @returns Whether the value is a {@link CaipAssetType}.
|
|
92
|
+
*/
|
|
93
|
+
export declare function isCaipAssetType(value: unknown): value is CaipAssetType;
|
|
94
|
+
/**
|
|
95
|
+
* Check if the given value is a {@link CaipAssetId}.
|
|
96
|
+
*
|
|
97
|
+
* @param value - The value to check.
|
|
98
|
+
* @returns Whether the value is a {@link CaipAssetId}.
|
|
99
|
+
*/
|
|
100
|
+
export declare function isCaipAssetId(value: unknown): value is CaipAssetId;
|
|
73
101
|
/**
|
|
74
102
|
* Parse a CAIP-2 chain ID to an object containing the namespace and reference.
|
|
75
103
|
* This validates the CAIP-2 chain ID before parsing it.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"caip-types.d.cts","sourceRoot":"","sources":["../src/caip-types.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,8BAA8B;AAE3D,eAAO,MAAM,mBAAmB,QACqC,CAAC;AAEtE,eAAO,MAAM,oBAAoB,QAAsB,CAAC;AAExD,eAAO,MAAM,oBAAoB,QAA2B,CAAC;AAE7D,eAAO,MAAM,qBAAqB,QACwF,CAAC;A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,IAAI,aAAa,CAEtE;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,WAAW,CAElE;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,WAAW,GAAG;IAC1D,SAAS,EAAE,aAAa,CAAC;IACzB,SAAS,EAAE,aAAa,CAAC;CAC1B,CAUA;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,aAAa,EAAE,aAAa,GAAG;IAChE,OAAO,EAAE,kBAAkB,CAAC;IAC5B,OAAO,EAAE,WAAW,CAAC;IACrB,KAAK,EAAE;QAAE,SAAS,EAAE,aAAa,CAAC;QAAC,SAAS,EAAE,aAAa,CAAA;KAAE,CAAC;CAC/D,CAcA;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,aAAa,CAC3B,SAAS,EAAE,aAAa,EACxB,SAAS,EAAE,aAAa,GACvB,WAAW,CAcb"}
|
package/dist/caip-types.d.mts
CHANGED
|
@@ -4,6 +4,8 @@ export declare const CAIP_NAMESPACE_REGEX: RegExp;
|
|
|
4
4
|
export declare const CAIP_REFERENCE_REGEX: RegExp;
|
|
5
5
|
export declare const CAIP_ACCOUNT_ID_REGEX: RegExp;
|
|
6
6
|
export declare const CAIP_ACCOUNT_ADDRESS_REGEX: RegExp;
|
|
7
|
+
export declare const CAIP_ASSET_TYPE_REGEX: RegExp;
|
|
8
|
+
export declare const CAIP_ASSET_ID_REGEX: RegExp;
|
|
7
9
|
/**
|
|
8
10
|
* A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
|
|
9
11
|
*/
|
|
@@ -29,8 +31,20 @@ export type CaipAccountId = `${string}:${string}:${string}`;
|
|
|
29
31
|
*/
|
|
30
32
|
export declare const CaipAccountAddressStruct: Struct<string, null>;
|
|
31
33
|
export type CaipAccountAddress = Infer<typeof CaipAccountAddressStruct>;
|
|
34
|
+
/**
|
|
35
|
+
* A CAIP-19 asset type identifier, i.e., a human-readable type of asset identifier.
|
|
36
|
+
*/
|
|
37
|
+
export declare const CaipAssetTypeStruct: Struct<`${string}:${string}/${string}:${string}`, null>;
|
|
38
|
+
export type CaipAssetType = `${string}:${string}/${string}:${string}`;
|
|
39
|
+
/**
|
|
40
|
+
* A CAIP-19 asset ID identifier, i.e., a human-readable type of asset ID.
|
|
41
|
+
*/
|
|
42
|
+
export declare const CaipAssetIdStruct: Struct<`${string}:${string}/${string}:${string}/${string}`, null>;
|
|
43
|
+
export type CaipAssetId = `${string}:${string}/${string}:${string}/${string}`;
|
|
32
44
|
/** Known CAIP namespaces. */
|
|
33
45
|
export declare enum KnownCaipNamespace {
|
|
46
|
+
/** BIP-122 (Bitcoin) compatible chains. */
|
|
47
|
+
Bip122 = "bip122",
|
|
34
48
|
/** EIP-155 compatible chains. */
|
|
35
49
|
Eip155 = "eip155",
|
|
36
50
|
Wallet = "wallet"
|
|
@@ -70,6 +84,20 @@ export declare function isCaipAccountId(value: unknown): value is CaipAccountId;
|
|
|
70
84
|
* @returns True if the value is a valid {@link CaipAccountAddress}.
|
|
71
85
|
*/
|
|
72
86
|
export declare function isCaipAccountAddress(value: unknown): value is CaipAccountAddress;
|
|
87
|
+
/**
|
|
88
|
+
* Check if the given value is a {@link CaipAssetType}.
|
|
89
|
+
*
|
|
90
|
+
* @param value - The value to check.
|
|
91
|
+
* @returns Whether the value is a {@link CaipAssetType}.
|
|
92
|
+
*/
|
|
93
|
+
export declare function isCaipAssetType(value: unknown): value is CaipAssetType;
|
|
94
|
+
/**
|
|
95
|
+
* Check if the given value is a {@link CaipAssetId}.
|
|
96
|
+
*
|
|
97
|
+
* @param value - The value to check.
|
|
98
|
+
* @returns Whether the value is a {@link CaipAssetId}.
|
|
99
|
+
*/
|
|
100
|
+
export declare function isCaipAssetId(value: unknown): value is CaipAssetId;
|
|
73
101
|
/**
|
|
74
102
|
* Parse a CAIP-2 chain ID to an object containing the namespace and reference.
|
|
75
103
|
* This validates the CAIP-2 chain ID before pars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BAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAEtE;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAEtE;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,OAAO,GACb,KAAK,IAAI,kBAAkB,CAE7B;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAEtE;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,WAAW,CAElE;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,WAAW,GAAG;IAC1D,SAAS,EAAE,aAAa,CAAC;IACzB,SAAS,EAAE,aAAa,CAAC;CAC1B,CAUA;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,aAAa,EAAE,aAAa,GAAG;IAChE,OAAO,EAAE,kBAAkB,CAAC;IAC5B,OAAO,EAAE,WAAW,CAAC;IACrB,KAAK,EAAE;QAAE,SAAS,EAAE,aAAa,CAAC;QAAC,SAAS,EAAE,aAAa,CAAA;KAAE,CAAC;CAC/D,CAcA;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,aAAa,CAC3B,SAAS,EAAE,aAAa,EACxB,SAAS,EAAE,aAAa,GACvB,WAAW,CAcb"}
|
package/dist/caip-types.mjs
CHANGED
|
@@ -4,6 +4,8 @@ export const CAIP_NAMESPACE_REGEX = /^[-a-z0-9]{3,8}$/u;
|
|
|
4
4
|
export const CAIP_REFERENCE_REGEX = /^[-_a-zA-Z0-9]{1,32}$/u;
|
|
5
5
|
export const CAIP_ACCOUNT_ID_REGEX = /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32})):(?<accountAddress>[-.%a-zA-Z0-9]{1,128})$/u;
|
|
6
6
|
export const CAIP_ACCOUNT_ADDRESS_REGEX = /^[-.%a-zA-Z0-9]{1,128}$/u;
|
|
7
|
+
export const CAIP_ASSET_TYPE_REGEX = /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32}))\/(?<assetNamespace>[-a-z0-9]{3,8}):(?<assetReference>[-.%a-zA-Z0-9]{1,128})$/u;
|
|
8
|
+
export const CAIP_ASSET_ID_REGEX = /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32}))\/(?<assetNamespace>[-a-z0-9]{3,8}):(?<assetReference>[-.%a-zA-Z0-9]{1,128})\/(?<tokenId>[-.%a-zA-Z0-9]{1,78})$/u;
|
|
7
9
|
/**
|
|
8
10
|
* A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
|
|
9
11
|
*/
|
|
@@ -24,9 +26,19 @@ export const CaipAccountIdStruct = pattern(string(), CAIP_ACCOUNT_ID_REGEX);
|
|
|
24
26
|
* A CAIP-10 account address, i.e., the third part of the CAIP account ID.
|
|
25
27
|
*/
|
|
26
28
|
export const CaipAccountAddressStruct = pattern(string(), CAIP_ACCOUNT_ADDRESS_REGEX);
|
|
29
|
+
/**
|
|
30
|
+
* A CAIP-19 asset type identifier, i.e., a human-readable type of asset identifier.
|
|
31
|
+
*/
|
|
32
|
+
export const CaipAssetTypeStruct = pattern(string(), CAIP_ASSET_TYPE_REGEX);
|
|
33
|
+
/**
|
|
34
|
+
* A CAIP-19 asset ID identifier, i.e., a human-readable type of asset ID.
|
|
35
|
+
*/
|
|
36
|
+
export const CaipAssetIdStruct = pattern(string(), CAIP_ASSET_ID_REGEX);
|
|
27
37
|
/** Known CAIP namespaces. */
|
|
28
38
|
export var KnownCaipNamespace;
|
|
29
39
|
(function (KnownCaipNamespace) {
|
|
40
|
+
/** BIP-122 (Bitcoin) compatible chains. */
|
|
41
|
+
KnownCaipNamespace["Bip122"] = "bip122";
|
|
30
42
|
/** EIP-155 compatible chains. */
|
|
31
43
|
KnownCaipNamespace["Eip155"] = "eip155";
|
|
32
44
|
KnownCaipNamespace["Wallet"] = "wallet";
|
|
@@ -76,6 +88,24 @@ export function isCaipAccountId(value) {
|
|
|
76
88
|
export function isCaipAccountAddress(value) {
|
|
77
89
|
return is(value, CaipAccountAddressStruct);
|
|
78
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* Check if the given value is a {@link CaipAssetType}.
|
|
93
|
+
*
|
|
94
|
+
* @param value - The value to check.
|
|
95
|
+
* @returns Whether the value is a {@link CaipAssetType}.
|
|
96
|
+
*/
|
|
97
|
+
export function isCaipAssetType(value) {
|
|
98
|
+
return is(value, CaipAssetTypeStruct);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Check if the given value is a {@link CaipAssetId}.
|
|
102
|
+
*
|
|
103
|
+
* @param value - The value to check.
|
|
104
|
+
* @returns Whether the value is a {@link CaipAssetId}.
|
|
105
|
+
*/
|
|
106
|
+
export function isCaipAssetId(value) {
|
|
107
|
+
return is(value, CaipAssetIdStruct);
|
|
108
|
+
}
|
|
79
109
|
/**
|
|
80
110
|
* Parse a CAIP-2 chain ID to an object containing the namespace and reference.
|
|
81
111
|
* This validates the CAIP-2 chain ID before parsing it.
|
package/dist/caip-types.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"caip-types.mjs","sourceRoot":"","sources":["../src/caip-types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,8BAA8B;AAG5D,MAAM,CAAC,MAAM,mBAAmB,GAC9B,mEAAmE,CAAC;AAEtE,MAAM,CAAC,MAAM,oBAAoB,GAAG,mBAAmB,CAAC;AAExD,MAAM,CAAC,MAAM,oBAAoB,GAAG,wBAAwB,CAAC;AAE7D,MAAM,CAAC,MAAM,qBAAqB,GAChC,wHAAwH,CAAC;AAE3H,MAAM,CAAC,MA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AoC,oBAAoB,CAAC,QAAQ,EAAE,EAAE,CACtE,CAAC;KACH;IAED,OAAO,GAAG,SAAS,IAAI,SAAS,EAAE,CAAC;AACrC,CAAC","sourcesContent":["import { is, pattern, string } from '@metamask/superstruct';\nimport type { Infer, Struct } from '@metamask/superstruct';\n\nexport const CAIP_CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32})$/u;\n\nexport const CAIP_NAMESPACE_REGEX = /^[-a-z0-9]{3,8}$/u;\n\nexport const CAIP_REFERENCE_REGEX = /^[-_a-zA-Z0-9]{1,32}$/u;\n\nexport const CAIP_ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32})):(?<accountAddress>[-.%a-zA-Z0-9]{1,128})$/u;\n\nexport const CAIP_ACCOUNT_ADDRESS_REGEX = /^[-.%a-zA-Z0-9]{1,128}$/u;\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const CaipChainIdStruct = pattern(\n string(),\n CAIP_CHAIN_ID_REGEX,\n) as Struct<CaipChainId, null>;\nexport type CaipChainId = `${string}:${string}`;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a CAIP chain ID.\n */\nexport const CaipNamespaceStruct = pattern(string(), CAIP_NAMESPACE_REGEX);\nexport type CaipNamespace = Infer<typeof CaipNamespaceStruct>;\n\n/**\n * A CAIP-2 reference, i.e., the second part of a CAIP chain ID.\n */\nexport const CaipReferenceStruct = pattern(string(), CAIP_REFERENCE_REGEX);\nexport type CaipReference = Infer<typeof CaipReferenceStruct>;\n\n/**\n * A CAIP-10 account ID, i.e., a human-readable namespace, reference, and account address.\n */\nexport const CaipAccountIdStruct = pattern(\n string(),\n CAIP_ACCOUNT_ID_REGEX,\n) as Struct<CaipAccountId, null>;\nexport type CaipAccountId = `${string}:${string}:${string}`;\n\n/**\n * A CAIP-10 account address, i.e., the third part of the CAIP account ID.\n */\nexport const CaipAccountAddressStruct = pattern(\n string(),\n CAIP_ACCOUNT_ADDRESS_REGEX,\n);\nexport type CaipAccountAddress = Infer<typeof CaipAccountAddressStruct>;\n\n/** Known CAIP namespaces. */\nexport enum KnownCaipNamespace {\n /** EIP-155 compatible chains. */\n Eip155 = 'eip155',\n Wallet = 'wallet',\n}\n\n/**\n * Check if the given value is a {@link CaipChainId}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipChainId}.\n */\nexport function isCaipChainId(value: unknown): value is CaipChainId {\n return is(value, CaipChainIdStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipNamespace}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipNamespace}.\n */\nexport function isCaipNamespace(value: unknown): value is CaipNamespace {\n return is(value, CaipNamespaceStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipReference}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipReference}.\n */\nexport function isCaipReference(value: unknown): value is CaipReference {\n return is(value, CaipReferenceStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipAccountId}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipAccountId}.\n */\nexport function isCaipAccountId(value: unknown): value is CaipAccountId {\n return is(value, CaipAccountIdStruct);\n}\n\n/**\n * Check if a value is a {@link CaipAccountAddress}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link CaipAccountAddress}.\n */\nexport function isCaipAccountAddress(\n value: unknown,\n): value is CaipAccountAddress {\n return is(value, CaipAccountAddressStruct);\n}\n\n/**\n * Parse a CAIP-2 chain ID to an object containing the namespace and reference.\n * This validates the CAIP-2 chain ID before parsing it.\n *\n * @param caipChainId - The CAIP-2 chain ID to validate and parse.\n * @returns The parsed CAIP-2 chain ID.\n */\nexport function parseCaipChainId(caipChainId: CaipChainId): {\n namespace: CaipNamespace;\n reference: CaipReference;\n} {\n const match = CAIP_CHAIN_ID_REGEX.exec(caipChainId);\n if (!match?.groups) {\n throw new Error('Invalid CAIP chain ID.');\n }\n\n return {\n namespace: match.groups.namespace as CaipNamespace,\n reference: match.groups.reference as CaipReference,\n };\n}\n\n/**\n * Parse an CAIP-10 account ID to an object containing the chain ID, parsed chain ID, and account address.\n * This validates the CAIP-10 account ID before parsing it.\n *\n * @param caipAccountId - The CAIP-10 account ID to validate and parse.\n * @returns The parsed CAIP-10 account ID.\n */\nexport function parseCaipAccountId(caipAccountId: CaipAccountId): {\n address: CaipAccountAddress;\n chainId: CaipChainId;\n chain: { namespace: CaipNamespace; reference: CaipReference };\n} {\n const match = CAIP_ACCOUNT_ID_REGEX.exec(caipAccountId);\n if (!match?.groups) {\n throw new Error('Invalid CAIP account ID.');\n }\n\n return {\n address: match.groups.accountAddress as CaipAccountAddress,\n chainId: match.groups.chainId as CaipChainId,\n chain: {\n namespace: match.groups.namespace as CaipNamespace,\n reference: match.groups.reference as CaipReference,\n },\n };\n}\n\n/**\n * Chain ID as defined per the CAIP-2\n * {@link https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md}.\n *\n * It defines a way to uniquely identify any blockchain in a human-readable\n * way.\n *\n * @param namespace - The standard (ecosystem) of similar blockchains.\n * @param reference - Identify of a blockchain within a given namespace.\n * @throws {@link Error}\n * This exception is thrown if the inputs does not comply with the CAIP-2\n * syntax specification\n * {@link https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md#syntax}.\n * @returns A CAIP chain ID.\n */\nexport function toCaipChainId(\n namespace: CaipNamespace,\n reference: CaipReference,\n): CaipChainId {\n if (!isCaipNamespace(namespace)) {\n throw new Error(\n `Invalid \"namespace\", must match: ${CAIP_NAMESPACE_REGEX.toString()}`,\n );\n }\n\n if (!isCaipReference(reference)) {\n throw new Error(\n `Invalid \"reference\", must match: ${CAIP_REFERENCE_REGEX.toString()}`,\n );\n }\n\n return `${namespace}:${reference}`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"caip-types.mjs","sourceRoot":"","sources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KAC3C;IAED,OAAO;QACL,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAA0B;QAClD,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAA0B;KACnD,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAAC,aAA4B;IAK7D,MAAM,KAAK,GAAG,qBAAqB,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;IACxD,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE;QAClB,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;KAC7C;IAED,OAAO;QACL,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,cAAoC;QAC1D,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,OAAsB;QAC5C,KAAK,EAAE;YACL,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAA0B;YAClD,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAA0B;SACnD;KACF,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,aAAa,CAC3B,SAAwB,EACxB,SAAwB;IAExB,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,EAAE;QAC/B,MAAM,IAAI,KAAK,CACb,oCAAoC,oBAAoB,CAAC,QAAQ,EAAE,EAAE,CACtE,CAAC;KACH;IAED,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,EAAE;QAC/B,MAAM,IAAI,KAAK,CACb,oCAAoC,oBAAoB,CAAC,QAAQ,EAAE,EAAE,CACtE,CAAC;KACH;IAED,OAAO,GAAG,SAAS,IAAI,SAAS,EAAE,CAAC;AACrC,CAAC","sourcesContent":["import { is, pattern, string } from '@metamask/superstruct';\nimport type { Infer, Struct } from '@metamask/superstruct';\n\nexport const CAIP_CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32})$/u;\n\nexport const CAIP_NAMESPACE_REGEX = /^[-a-z0-9]{3,8}$/u;\n\nexport const CAIP_REFERENCE_REGEX = /^[-_a-zA-Z0-9]{1,32}$/u;\n\nexport const CAIP_ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32})):(?<accountAddress>[-.%a-zA-Z0-9]{1,128})$/u;\n\nexport const CAIP_ACCOUNT_ADDRESS_REGEX = /^[-.%a-zA-Z0-9]{1,128}$/u;\n\nexport const CAIP_ASSET_TYPE_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32}))\\/(?<assetNamespace>[-a-z0-9]{3,8}):(?<assetReference>[-.%a-zA-Z0-9]{1,128})$/u;\n\nexport const CAIP_ASSET_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32}))\\/(?<assetNamespace>[-a-z0-9]{3,8}):(?<assetReference>[-.%a-zA-Z0-9]{1,128})\\/(?<tokenId>[-.%a-zA-Z0-9]{1,78})$/u;\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const CaipChainIdStruct = pattern(\n string(),\n CAIP_CHAIN_ID_REGEX,\n) as Struct<CaipChainId, null>;\nexport type CaipChainId = `${string}:${string}`;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a CAIP chain ID.\n */\nexport const CaipNamespaceStruct = pattern(string(), CAIP_NAMESPACE_REGEX);\nexport type CaipNamespace = Infer<typeof CaipNamespaceStruct>;\n\n/**\n * A CAIP-2 reference, i.e., the second part of a CAIP chain ID.\n */\nexport const CaipReferenceStruct = pattern(string(), CAIP_REFERENCE_REGEX);\nexport type CaipReference = Infer<typeof CaipReferenceStruct>;\n\n/**\n * A CAIP-10 account ID, i.e., a human-readable namespace, reference, and account address.\n */\nexport const CaipAccountIdStruct = pattern(\n string(),\n CAIP_ACCOUNT_ID_REGEX,\n) as Struct<CaipAccountId, null>;\nexport type CaipAccountId = `${string}:${string}:${string}`;\n\n/**\n * A CAIP-10 account address, i.e., the third part of the CAIP account ID.\n */\nexport const CaipAccountAddressStruct = pattern(\n string(),\n CAIP_ACCOUNT_ADDRESS_REGEX,\n);\nexport type CaipAccountAddress = Infer<typeof CaipAccountAddressStruct>;\n\n/**\n * A CAIP-19 asset type identifier, i.e., a human-readable type of asset identifier.\n */\nexport const CaipAssetTypeStruct = pattern(\n string(),\n CAIP_ASSET_TYPE_REGEX,\n) as Struct<CaipAssetType, null>;\nexport type CaipAssetType = `${string}:${string}/${string}:${string}`;\n\n/**\n * A CAIP-19 asset ID identifier, i.e., a human-readable type of asset ID.\n */\nexport const CaipAssetIdStruct = pattern(\n string(),\n CAIP_ASSET_ID_REGEX,\n) as Struct<CaipAssetId, null>;\nexport type CaipAssetId = `${string}:${string}/${string}:${string}/${string}`;\n\n/** Known CAIP namespaces. */\nexport enum KnownCaipNamespace {\n /** BIP-122 (Bitcoin) compatible chains. */\n Bip122 = 'bip122',\n /** EIP-155 compatible chains. */\n Eip155 = 'eip155',\n Wallet = 'wallet',\n}\n\n/**\n * Check if the given value is a {@link CaipChainId}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipChainId}.\n */\nexport function isCaipChainId(value: unknown): value is CaipChainId {\n return is(value, CaipChainIdStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipNamespace}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipNamespace}.\n */\nexport function isCaipNamespace(value: unknown): value is CaipNamespace {\n return is(value, CaipNamespaceStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipReference}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipReference}.\n */\nexport function isCaipReference(value: unknown): value is CaipReference {\n return is(value, CaipReferenceStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipAccountId}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipAccountId}.\n */\nexport function isCaipAccountId(value: unknown): value is CaipAccountId {\n return is(value, CaipAccountIdStruct);\n}\n\n/**\n * Check if a value is a {@link CaipAccountAddress}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link CaipAccountAddress}.\n */\nexport function isCaipAccountAddress(\n value: unknown,\n): value is CaipAccountAddress {\n return is(value, CaipAccountAddressStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipAssetType}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipAssetType}.\n */\nexport function isCaipAssetType(value: unknown): value is CaipAssetType {\n return is(value, CaipAssetTypeStruct);\n}\n\n/**\n * Check if the given value is a {@link CaipAssetId}.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link CaipAssetId}.\n */\nexport function isCaipAssetId(value: unknown): value is CaipAssetId {\n return is(value, CaipAssetIdStruct);\n}\n\n/**\n * Parse a CAIP-2 chain ID to an object containing the namespace and reference.\n * This validates the CAIP-2 chain ID before parsing it.\n *\n * @param caipChainId - The CAIP-2 chain ID to validate and parse.\n * @returns The parsed CAIP-2 chain ID.\n */\nexport function parseCaipChainId(caipChainId: CaipChainId): {\n namespace: CaipNamespace;\n reference: CaipReference;\n} {\n const match = CAIP_CHAIN_ID_REGEX.exec(caipChainId);\n if (!match?.groups) {\n throw new Error('Invalid CAIP chain ID.');\n }\n\n return {\n namespace: match.groups.namespace as CaipNamespace,\n reference: match.groups.reference as CaipReference,\n };\n}\n\n/**\n * Parse an CAIP-10 account ID to an object containing the chain ID, parsed chain ID, and account address.\n * This validates the CAIP-10 account ID before parsing it.\n *\n * @param caipAccountId - The CAIP-10 account ID to validate and parse.\n * @returns The parsed CAIP-10 account ID.\n */\nexport function parseCaipAccountId(caipAccountId: CaipAccountId): {\n address: CaipAccountAddress;\n chainId: CaipChainId;\n chain: { namespace: CaipNamespace; reference: CaipReference };\n} {\n const match = CAIP_ACCOUNT_ID_REGEX.exec(caipAccountId);\n if (!match?.groups) {\n throw new Error('Invalid CAIP account ID.');\n }\n\n return {\n address: match.groups.accountAddress as CaipAccountAddress,\n chainId: match.groups.chainId as CaipChainId,\n chain: {\n namespace: match.groups.namespace as CaipNamespace,\n reference: match.groups.reference as CaipReference,\n },\n };\n}\n\n/**\n * Chain ID as defined per the CAIP-2\n * {@link https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md}.\n *\n * It defines a way to uniquely identify any blockchain in a human-readable\n * way.\n *\n * @param namespace - The standard (ecosystem) of similar blockchains.\n * @param reference - Identify of a blockchain within a given namespace.\n * @throws {@link Error}\n * This exception is thrown if the inputs does not comply with the CAIP-2\n * syntax specification\n * {@link https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md#syntax}.\n * @returns A CAIP chain ID.\n */\nexport function toCaipChainId(\n namespace: CaipNamespace,\n reference: CaipReference,\n): CaipChainId {\n if (!isCaipNamespace(namespace)) {\n throw new Error(\n `Invalid \"namespace\", must match: ${CAIP_NAMESPACE_REGEX.toString()}`,\n );\n }\n\n if (!isCaipReference(reference)) {\n throw new Error(\n `Invalid \"reference\", must match: ${CAIP_REFERENCE_REGEX.toString()}`,\n );\n }\n\n return `${namespace}:${reference}`;\n}\n"]}
|
package/dist/json.cjs
CHANGED
|
@@ -67,28 +67,55 @@ function exactOptional(struct) {
|
|
|
67
67
|
}
|
|
68
68
|
exports.exactOptional = exactOptional;
|
|
69
69
|
/**
|
|
70
|
-
*
|
|
71
|
-
* `number()` struct does not check if the value is finite.
|
|
70
|
+
* Validate an unknown input to be valid JSON.
|
|
72
71
|
*
|
|
73
|
-
*
|
|
72
|
+
* Useful for constructing JSON structs.
|
|
73
|
+
*
|
|
74
|
+
* @param json - An unknown value.
|
|
75
|
+
* @returns True if the value is valid JSON, otherwise false.
|
|
74
76
|
*/
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
77
|
+
function validateJson(json) {
|
|
78
|
+
if (json === null || typeof json === 'boolean' || typeof json === 'string') {
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
if (typeof json === 'number' && Number.isFinite(json)) {
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
if (typeof json === 'object') {
|
|
85
|
+
let every = true;
|
|
86
|
+
if (Array.isArray(json)) {
|
|
87
|
+
// Ignoring linting error since for-of is significantly slower than a normal for-loop
|
|
88
|
+
// and performance is important in this specific function.
|
|
89
|
+
// eslint-disable-next-line @typescript-eslint/prefer-for-of
|
|
90
|
+
for (let i = 0; i < json.length; i++) {
|
|
91
|
+
if (!validateJson(json[i])) {
|
|
92
|
+
every = false;
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return every;
|
|
97
|
+
}
|
|
98
|
+
const entries = Object.entries(json);
|
|
99
|
+
// Ignoring linting errors since for-of is significantly slower than a normal for-loop
|
|
100
|
+
// and performance is important in this specific function.
|
|
101
|
+
// eslint-disable-next-line @typescript-eslint/prefer-for-of
|
|
102
|
+
for (let i = 0; i < entries.length; i++) {
|
|
103
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
104
|
+
if (typeof entries[i][0] !== 'string' || !validateJson(entries[i][1])) {
|
|
105
|
+
every = false;
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return every;
|
|
110
|
+
}
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
78
113
|
/**
|
|
79
114
|
* A struct to check if the given value is a valid JSON-serializable value.
|
|
80
115
|
*
|
|
81
116
|
* Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.
|
|
82
117
|
*/
|
|
83
|
-
|
|
84
|
-
exports.UnsafeJsonStruct = (0, superstruct_1.union)([
|
|
85
|
-
(0, superstruct_1.literal)(null),
|
|
86
|
-
(0, superstruct_1.boolean)(),
|
|
87
|
-
finiteNumber(),
|
|
88
|
-
(0, superstruct_1.string)(),
|
|
89
|
-
(0, superstruct_1.array)((0, superstruct_1.lazy)(() => exports.UnsafeJsonStruct)),
|
|
90
|
-
(0, superstruct_1.record)((0, superstruct_1.string)(), (0, superstruct_1.lazy)(() => exports.UnsafeJsonStruct)),
|
|
91
|
-
]);
|
|
118
|
+
exports.UnsafeJsonStruct = (0, superstruct_1.define)('JSON', (json) => validateJson(json));
|
|
92
119
|
/**
|
|
93
120
|
* A struct to check if the given value is a valid JSON-serializable value.
|
|
94
121
|
*
|
package/dist/json.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.cjs","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":";;;AAAA,uDAoB+B;AAU/B,yCAAwC;AACxC,qCAAqC;AAgDrC;;;;;;GAMG;AACI,MAAM,MAAM,GAAG,CACpB,MAAc,EACc,EAAE;AAC9B,0EAA0E;AAC1E,2EAA2E;AAC3E,2DAA2D;AAC3D,IAAA,oBAAiB,EAAC,MAAM,CAA0C,CAAC;AANxD,QAAA,MAAM,UAMkD;AAOrE;;;;;;;GAOG;AACH,SAAS,WAAW,CAAC,EAAE,IAAI,EAAE,MAAM,EAAW;IAC5C,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACpC,OAAO,IAAA,kBAAW,EAAC,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;AACvD,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,SAAgB,aAAa,CAC3B,MAA4B;IAE5B,OAAO,IAAI,oBAAM,CAAoC;QACnD,GAAG,MAAM;QAET,IAAI,EAAE,YAAY,MAAM,CAAC,IAAI,EAAE;QAC/B,SAAS,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CAC5B,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,OAAO,CAAC;QAE3D,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CAC1B,CAAC,WAAW,CAAC,OAAO,CAAC,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C,CAAC,CAAC;YACnE,CAAC,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,iBAAiB,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YAChE,CAAC,UAAU,IAAI,EAAE,KAAK,IAAI,CAAC,CAC9B,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAxBD,sDAwBC","sourcesContent":["import {\n any,\n array,\n boolean,\n coerce,\n create,\n define,\n integer,\n is,\n lazy,\n literal,\n nullable,\n number,\n object as superstructObject,\n optional,\n record,\n string,\n union,\n unknown,\n Struct,\n} from '@metamask/superstruct';\nimport type {\n Context,\n Infer,\n ObjectSchema,\n Simplify,\n Optionalize,\n} from '@metamask/superstruct';\n\nimport type { AssertionErrorConstructor } from './assert';\nimport { assertStruct } from './assert';\nimport { hasProperty } from './misc';\n\n/**\n * Any JSON-compatible value.\n */\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [prop: string]: Json };\n\n/**\n * A helper type to make properties with `undefined` in their type optional, but\n * not `undefined` itself.\n *\n * @example\n * ```ts\n * type Foo = ObjectOptional<{ foo: string | undefined }>;\n * // Foo is equivalent to { foo?: string }\n * ```\n */\nexport type ObjectOptional<Schema extends Record<string, unknown>> = {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? Key\n : never]?: Schema[Key] extends ExactOptionalGuard & infer Original\n ? Original\n : never;\n} & {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? never\n : Key]: Schema[Key];\n};\n\n/**\n * An object type with support for exact optionals. This is used by the `object`\n * struct. This uses the {@link ObjectOptional} helper to make properties with\n * `undefined` in their type optional, but not `undefined` itself.\n */\nexport type ObjectType<Schema extends ObjectSchema> = Simplify<\n ObjectOptional<\n Optionalize<{\n [Key in keyof Schema]: Infer<Schema[Key]>;\n }>\n >\n>;\n\n/**\n * A struct to check if the given value is a valid object, with support for\n * {@link exactOptional} types.\n *\n * @param schema - The schema of the object.\n * @returns A struct to check if the given value is an object.\n */\nexport const object = <Schema extends ObjectSchema>(\n schema: Schema,\n): Struct<ObjectType<Schema>> =>\n // The type is slightly different from a regular object struct, because we\n // want to make properties with `undefined` in their type optional, but not\n // `undefined` itself. This means that we need a type cast.\n superstructObject(schema) as unknown as Struct<ObjectType<Schema>>;\n\ndeclare const exactOptionalSymbol: unique symbol;\ntype ExactOptionalGuard = {\n _exactOptionalGuard?: typeof exactOptionalSymbol;\n};\n\n/**\n * Check the last field of a path is present.\n *\n * @param context - The context to check.\n * @param context.path - The path to check.\n * @param context.branch - The branch to check.\n * @returns Whether the last field of a path is present.\n */\nfunction hasOptional({ path, branch }: Context): boolean {\n const field = path[path.length - 1];\n return hasProperty(branch[branch.length - 2], field);\n}\n\n/**\n * A struct which allows the property of an object to be absent, or to be present\n * as long as it's valid and not set to `undefined`.\n *\n * This struct should be used in conjunction with the {@link object} from this\n * library, to get proper type inference.\n *\n * @param struct - The struct to check the value against, if present.\n * @returns A struct to check if the given value is valid, or not present.\n * @example\n * ```ts\n * const struct = object({\n * foo: exactOptional(string()),\n * bar: exactOptional(number()),\n * baz: optional(boolean()),\n * qux: unknown(),\n * });\n *\n * type Type = Infer<typeof struct>;\n * // Type is equivalent to:\n * // {\n * // foo?: string;\n * // bar?: number;\n * // baz?: boolean | undefined;\n * // qux: unknown;\n * // }\n * ```\n */\nexport function exactOptional<Type, Schema>(\n struct: Struct<Type, Schema>,\n): Struct<Type & ExactOptionalGuard, Schema> {\n return new Struct<Type & ExactOptionalGuard, Schema>({\n ...struct,\n\n type: `optional ${struct.type}`,\n validator: (value, context) =>\n !hasOptional(context) || struct.validator(value, context),\n\n refiner: (value, context) =>\n !hasOptional(context) || struct.refiner(value as Type, context),\n });\n}\n\n/**\n * A struct to check if the given value is finite number. Superstruct's\n * `number()` struct does not check if the value is finite.\n *\n * @returns A struct to check if the given value is finite number.\n */\nconst finiteNumber = () =>\n define<number>('finite number', (value) => {\n return is(value, number()) && Number.isFinite(value);\n });\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.\n */\n// We cannot infer the type of the struct, because it is recursive.\nexport const UnsafeJsonStruct: Struct<Json> = union([\n literal(null),\n boolean(),\n finiteNumber(),\n string(),\n array(lazy(() => UnsafeJsonStruct)),\n record(\n string(),\n lazy(() => UnsafeJsonStruct),\n ),\n]);\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * This struct sanitizes the value before validating it, so that it is safe to\n * use with untrusted input.\n */\nexport const JsonStruct = coerce(UnsafeJsonStruct, any(), (value) => {\n assertStruct(value, UnsafeJsonStruct);\n return JSON.parse(\n JSON.stringify(value, (propKey, propValue) => {\n // Strip __proto__ and constructor properties to prevent prototype pollution.\n if (propKey === '__proto__' || propKey === 'constructor') {\n return undefined;\n }\n return propValue;\n }),\n );\n});\n\n/**\n * Check if the given value is a valid {@link Json} value, i.e., a value that is\n * serializable to JSON.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link Json} value.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n getSafeJson(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate and return sanitized JSON.\n *\n * Note:\n * This function uses sanitized JsonStruct for validation\n * that applies stringify and then parse of a value provided\n * to ensure that there are no getters which can have side effects\n * that can cause security issues.\n *\n * @param value - JSON structure to be processed.\n * @returns Sanitized JSON structure.\n */\nexport function getSafeJson<Type extends Json = Json>(value: unknown): Type {\n return create(value, JsonStruct) as Type;\n}\n\n/**\n * Get the size of a JSON value in bytes. This also validates the value.\n *\n * @param value - The JSON value to get the size of.\n * @returns The size of the JSON value in bytes.\n */\nexport function getJsonSize(value: unknown): number {\n assertStruct(value, JsonStruct, 'Invalid JSON value');\n\n const json = JSON.stringify(value);\n return new TextEncoder().encode(json).byteLength;\n}\n\n/**\n * The string '2.0'.\n */\nexport const jsonrpc2 = '2.0' as const;\nexport const JsonRpcVersionStruct = literal(jsonrpc2);\n\n/**\n * A String specifying the version of the JSON-RPC protocol.\n * MUST be exactly \"2.0\".\n */\nexport type JsonRpcVersion2 = typeof jsonrpc2;\n\nexport const JsonRpcIdStruct = nullable(union([number(), string()]));\n\n/**\n * An identifier established by the Client that MUST contain a String, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts.\n */\nexport type JsonRpcId = Infer<typeof JsonRpcIdStruct>;\n\nexport const JsonRpcErrorStruct = object({\n code: integer(),\n message: string(),\n data: exactOptional(JsonStruct),\n stack: exactOptional(string()),\n});\n\n/**\n * Mark a certain key of a type as optional.\n */\nexport type OptionalField<\n Type extends Record<string, unknown>,\n Key extends keyof Type,\n> = Omit<Type, Key> & Partial<Pick<Type, Key>>;\n\n/**\n * A JSON-RPC error object.\n *\n * Note that TypeScript infers `unknown | undefined` as `unknown`, meaning that\n * the `data` field is not optional. To make it optional, we use the\n * `OptionalField` helper, to explicitly make it optional.\n */\nexport type JsonRpcError = OptionalField<\n Infer<typeof JsonRpcErrorStruct>,\n 'data'\n>;\n\nexport const JsonRpcParamsStruct: Struct<Json[] | Record<string, Json>, null> =\n union([record(string(), JsonStruct), array(JsonStruct)]);\n\nexport type JsonRpcParams = Json[] | Record<string, Json>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\nexport type InferWithParams<\n Type extends Struct<any>,\n Params extends JsonRpcParams,\n> = Infer<Type> & {\n params?: Params;\n};\n\n/**\n * A JSON-RPC request object.\n */\nexport type JsonRpcRequest<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcRequestStruct, Params>;\n\nexport const JsonRpcNotificationStruct = object({\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\n/**\n * A JSON-RPC notification object.\n */\nexport type JsonRpcNotification<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcNotificationStruct, Params>;\n\n/**\n * Check if the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcNotification}\n * object.\n */\nexport function isJsonRpcNotification(\n value: unknown,\n): value is JsonRpcNotification {\n return is(value, JsonRpcNotificationStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcNotification} object.\n */\nexport function assertIsJsonRpcNotification(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcNotification {\n assertStruct(\n value,\n JsonRpcNotificationStruct,\n 'Invalid JSON-RPC notification',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcRequest} object.\n */\nexport function isJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n return is(value, JsonRpcRequestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The JSON-RPC request or notification to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcRequest} object.\n */\nexport function assertIsJsonRpcRequest(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcRequest {\n assertStruct(\n value,\n JsonRpcRequestStruct,\n 'Invalid JSON-RPC request',\n ErrorWrapper,\n );\n}\n\nexport const PendingJsonRpcResponseStruct = superstructObject({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: optional(unknown()),\n error: optional(JsonRpcErrorStruct),\n});\n\n/**\n * A JSON-RPC response object that has not yet been resolved.\n */\nexport type PendingJsonRpcResponse<Result extends Json> = Omit<\n Infer<typeof PendingJsonRpcResponseStruct>,\n 'result'\n> & {\n result?: Result;\n};\n\nexport const JsonRpcSuccessStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: JsonStruct,\n});\n\n/**\n * A successful JSON-RPC response object.\n */\nexport type JsonRpcSuccess<Result extends Json> = Omit<\n Infer<typeof JsonRpcSuccessStruct>,\n 'result'\n> & {\n result: Result;\n};\n\nexport const JsonRpcFailureStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n error: JsonRpcErrorStruct as Struct<JsonRpcError>,\n});\n\n/**\n * A failed JSON-RPC response object.\n */\nexport type JsonRpcFailure = Infer<typeof JsonRpcFailureStruct>;\n\nexport const JsonRpcResponseStruct = union([\n JsonRpcSuccessStruct,\n JsonRpcFailureStruct,\n]);\n\n/**\n * A JSON-RPC response object. Must be checked to determine whether it's a\n * success or failure.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcResponse<Result extends Json> =\n | JsonRpcSuccess<Result>\n | JsonRpcFailure;\n\n/**\n * Type guard to check whether specified JSON-RPC response is a\n * {@link PendingJsonRpcResponse}.\n *\n * @param response - The JSON-RPC response to check.\n * @returns Whether the specified JSON-RPC response is pending.\n */\nexport function isPendingJsonRpcResponse(\n response: unknown,\n): response is PendingJsonRpcResponse<Json> {\n return is(response, PendingJsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link PendingJsonRpcResponse} object.\n *\n * @param response - The JSON-RPC response to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link PendingJsonRpcResponse}\n * object.\n */\nexport function assertIsPendingJsonRpcResponse(\n response: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts response is PendingJsonRpcResponse<Json> {\n assertStruct(\n response,\n PendingJsonRpcResponseStruct,\n 'Invalid pending JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Type guard to check if a value is a {@link JsonRpcResponse}.\n *\n * @param response - The object to check.\n * @returns Whether the object is a JsonRpcResponse.\n */\nexport function isJsonRpcResponse(\n response: unknown,\n): response is JsonRpcResponse<Json> {\n return is(response, JsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcResponse} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcResponse} object.\n */\nexport function assertIsJsonRpcResponse(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcResponse<Json> {\n assertStruct(\n value,\n JsonRpcResponseStruct,\n 'Invalid JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcSuccess} object.\n */\nexport function isJsonRpcSuccess(\n value: unknown,\n): value is JsonRpcSuccess<Json> {\n return is(value, JsonRpcSuccessStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcSuccess} object.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcSuccess<Json> {\n assertStruct(\n value,\n JsonRpcSuccessStruct,\n 'Invalid JSON-RPC success response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcFailure} object.\n */\nexport function isJsonRpcFailure(value: unknown): value is JsonRpcFailure {\n return is(value, JsonRpcFailureStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcFailure} object.\n */\nexport function assertIsJsonRpcFailure(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcFailure {\n assertStruct(\n value,\n JsonRpcFailureStruct,\n 'Invalid JSON-RPC failure response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcError} object.\n */\nexport function isJsonRpcError(value: unknown): value is JsonRpcError {\n return is(value, JsonRpcErrorStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcError} object.\n */\nexport function assertIsJsonRpcError(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcError {\n assertStruct(\n value,\n JsonRpcErrorStruct,\n 'Invalid JSON-RPC error',\n ErrorWrapper,\n );\n}\n\ntype JsonRpcValidatorOptions = {\n permitEmptyString?: boolean;\n permitFractions?: boolean;\n permitNull?: boolean;\n};\n\n/**\n * Gets a function for validating JSON-RPC request / response `id` values.\n *\n * By manipulating the options of this factory, you can control the behavior\n * of the resulting validator for some edge cases. This is useful because e.g.\n * `null` should sometimes but not always be permitted.\n *\n * Note that the empty string (`''`) is always permitted by the JSON-RPC\n * specification, but that kind of sucks and you may want to forbid it in some\n * instances anyway.\n *\n * For more details, see the\n * [JSON-RPC Specification](https://www.jsonrpc.org/specification).\n *\n * @param options - An options object.\n * @param options.permitEmptyString - Whether the empty string (i.e. `''`)\n * should be treated as a valid ID. Default: `true`\n * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)\n * should be treated as valid IDs. Default: `false`\n * @param options.permitNull - Whether `null` should be treated as a valid ID.\n * Default: `true`\n * @returns The JSON-RPC ID validator function.\n */\nexport function getJsonRpcIdValidator(options?: JsonRpcValidatorOptions) {\n const { permitEmptyString, permitFractions, permitNull } = {\n permitEmptyString: true,\n permitFractions: false,\n permitNull: true,\n ...options,\n };\n\n /**\n * Type guard for {@link JsonRpcId}.\n *\n * @param id - The JSON-RPC ID value to check.\n * @returns Whether the given ID is valid per the options given to the\n * factory.\n */\n const isValidJsonRpcId = (id: unknown): id is JsonRpcId => {\n return Boolean(\n (typeof id === 'number' && (permitFractions || Number.isInteger(id))) ||\n (typeof id === 'string' && (permitEmptyString || id.length > 0)) ||\n (permitNull && id === null),\n );\n };\n\n return isValidJsonRpcId;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"json.cjs","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":";;;AAAA,uDAkB+B;AAU/B,yCAAwC;AACxC,qCAAqC;AAgDrC;;;;;;GAMG;AACI,MAAM,MAAM,GAAG,CACpB,MAAc,EACc,EAAE;AAC9B,0EAA0E;AAC1E,2EAA2E;AAC3E,2DAA2D;AAC3D,IAAA,oBAAiB,EAAC,MAAM,CAA0C,CAAC;AANxD,QAAA,MAAM,UAMkD;AAOrE;;;;;;;GAOG;AACH,SAAS,WAAW,CAAC,EAAE,IAAI,EAAE,MAAM,EAAW;IAC5C,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACpC,OAAO,IAAA,kBAAW,EAAC,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;AACvD,CAA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CAAC;YAChE,CAAC,UAAU,IAAI,EAAE,KAAK,IAAI,CAAC,CAC9B,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAxBD,sDAwBC","sourcesContent":["import {\n any,\n array,\n coerce,\n create,\n define,\n integer,\n is,\n literal,\n nullable,\n number,\n object as superstructObject,\n optional,\n record,\n string,\n union,\n unknown,\n Struct,\n} from '@metamask/superstruct';\nimport type {\n Context,\n Infer,\n ObjectSchema,\n Simplify,\n Optionalize,\n} from '@metamask/superstruct';\n\nimport type { AssertionErrorConstructor } from './assert';\nimport { assertStruct } from './assert';\nimport { hasProperty } from './misc';\n\n/**\n * Any JSON-compatible value.\n */\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [prop: string]: Json };\n\n/**\n * A helper type to make properties with `undefined` in their type optional, but\n * not `undefined` itself.\n *\n * @example\n * ```ts\n * type Foo = ObjectOptional<{ foo: string | undefined }>;\n * // Foo is equivalent to { foo?: string }\n * ```\n */\nexport type ObjectOptional<Schema extends Record<string, unknown>> = {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? Key\n : never]?: Schema[Key] extends ExactOptionalGuard & infer Original\n ? Original\n : never;\n} & {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? never\n : Key]: Schema[Key];\n};\n\n/**\n * An object type with support for exact optionals. This is used by the `object`\n * struct. This uses the {@link ObjectOptional} helper to make properties with\n * `undefined` in their type optional, but not `undefined` itself.\n */\nexport type ObjectType<Schema extends ObjectSchema> = Simplify<\n ObjectOptional<\n Optionalize<{\n [Key in keyof Schema]: Infer<Schema[Key]>;\n }>\n >\n>;\n\n/**\n * A struct to check if the given value is a valid object, with support for\n * {@link exactOptional} types.\n *\n * @param schema - The schema of the object.\n * @returns A struct to check if the given value is an object.\n */\nexport const object = <Schema extends ObjectSchema>(\n schema: Schema,\n): Struct<ObjectType<Schema>> =>\n // The type is slightly different from a regular object struct, because we\n // want to make properties with `undefined` in their type optional, but not\n // `undefined` itself. This means that we need a type cast.\n superstructObject(schema) as unknown as Struct<ObjectType<Schema>>;\n\ndeclare const exactOptionalSymbol: unique symbol;\ntype ExactOptionalGuard = {\n _exactOptionalGuard?: typeof exactOptionalSymbol;\n};\n\n/**\n * Check the last field of a path is present.\n *\n * @param context - The context to check.\n * @param context.path - The path to check.\n * @param context.branch - The branch to check.\n * @returns Whether the last field of a path is present.\n */\nfunction hasOptional({ path, branch }: Context): boolean {\n const field = path[path.length - 1];\n return hasProperty(branch[branch.length - 2], field);\n}\n\n/**\n * A struct which allows the property of an object to be absent, or to be present\n * as long as it's valid and not set to `undefined`.\n *\n * This struct should be used in conjunction with the {@link object} from this\n * library, to get proper type inference.\n *\n * @param struct - The struct to check the value against, if present.\n * @returns A struct to check if the given value is valid, or not present.\n * @example\n * ```ts\n * const struct = object({\n * foo: exactOptional(string()),\n * bar: exactOptional(number()),\n * baz: optional(boolean()),\n * qux: unknown(),\n * });\n *\n * type Type = Infer<typeof struct>;\n * // Type is equivalent to:\n * // {\n * // foo?: string;\n * // bar?: number;\n * // baz?: boolean | undefined;\n * // qux: unknown;\n * // }\n * ```\n */\nexport function exactOptional<Type, Schema>(\n struct: Struct<Type, Schema>,\n): Struct<Type & ExactOptionalGuard, Schema> {\n return new Struct<Type & ExactOptionalGuard, Schema>({\n ...struct,\n\n type: `optional ${struct.type}`,\n validator: (value, context) =>\n !hasOptional(context) || struct.validator(value, context),\n\n refiner: (value, context) =>\n !hasOptional(context) || struct.refiner(value as Type, context),\n });\n}\n\n/**\n * Validate an unknown input to be valid JSON.\n *\n * Useful for constructing JSON structs.\n *\n * @param json - An unknown value.\n * @returns True if the value is valid JSON, otherwise false.\n */\nfunction validateJson(json: unknown): boolean {\n if (json === null || typeof json === 'boolean' || typeof json === 'string') {\n return true;\n }\n\n if (typeof json === 'number' && Number.isFinite(json)) {\n return true;\n }\n\n if (typeof json === 'object') {\n let every = true;\n if (Array.isArray(json)) {\n // Ignoring linting error since for-of is significantly slower than a normal for-loop\n // and performance is important in this specific function.\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < json.length; i++) {\n if (!validateJson(json[i])) {\n every = false;\n break;\n }\n }\n return every;\n }\n\n const entries = Object.entries(json);\n // Ignoring linting errors since for-of is significantly slower than a normal for-loop\n // and performance is important in this specific function.\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < entries.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n if (typeof entries[i]![0] !== 'string' || !validateJson(entries[i]![1])) {\n every = false;\n break;\n }\n }\n return every;\n }\n\n return false;\n}\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.\n */\nexport const UnsafeJsonStruct: Struct<Json> = define('JSON', (json) =>\n validateJson(json),\n);\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * This struct sanitizes the value before validating it, so that it is safe to\n * use with untrusted input.\n */\nexport const JsonStruct = coerce(UnsafeJsonStruct, any(), (value) => {\n assertStruct(value, UnsafeJsonStruct);\n return JSON.parse(\n JSON.stringify(value, (propKey, propValue) => {\n // Strip __proto__ and constructor properties to prevent prototype pollution.\n if (propKey === '__proto__' || propKey === 'constructor') {\n return undefined;\n }\n return propValue;\n }),\n );\n});\n\n/**\n * Check if the given value is a valid {@link Json} value, i.e., a value that is\n * serializable to JSON.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link Json} value.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n getSafeJson(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate and return sanitized JSON.\n *\n * Note:\n * This function uses sanitized JsonStruct for validation\n * that applies stringify and then parse of a value provided\n * to ensure that there are no getters which can have side effects\n * that can cause security issues.\n *\n * @param value - JSON structure to be processed.\n * @returns Sanitized JSON structure.\n */\nexport function getSafeJson<Type extends Json = Json>(value: unknown): Type {\n return create(value, JsonStruct) as Type;\n}\n\n/**\n * Get the size of a JSON value in bytes. This also validates the value.\n *\n * @param value - The JSON value to get the size of.\n * @returns The size of the JSON value in bytes.\n */\nexport function getJsonSize(value: unknown): number {\n assertStruct(value, JsonStruct, 'Invalid JSON value');\n\n const json = JSON.stringify(value);\n return new TextEncoder().encode(json).byteLength;\n}\n\n/**\n * The string '2.0'.\n */\nexport const jsonrpc2 = '2.0' as const;\nexport const JsonRpcVersionStruct = literal(jsonrpc2);\n\n/**\n * A String specifying the version of the JSON-RPC protocol.\n * MUST be exactly \"2.0\".\n */\nexport type JsonRpcVersion2 = typeof jsonrpc2;\n\nexport const JsonRpcIdStruct = nullable(union([number(), string()]));\n\n/**\n * An identifier established by the Client that MUST contain a String, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts.\n */\nexport type JsonRpcId = Infer<typeof JsonRpcIdStruct>;\n\nexport const JsonRpcErrorStruct = object({\n code: integer(),\n message: string(),\n data: exactOptional(JsonStruct),\n stack: exactOptional(string()),\n});\n\n/**\n * Mark a certain key of a type as optional.\n */\nexport type OptionalField<\n Type extends Record<string, unknown>,\n Key extends keyof Type,\n> = Omit<Type, Key> & Partial<Pick<Type, Key>>;\n\n/**\n * A JSON-RPC error object.\n *\n * Note that TypeScript infers `unknown | undefined` as `unknown`, meaning that\n * the `data` field is not optional. To make it optional, we use the\n * `OptionalField` helper, to explicitly make it optional.\n */\nexport type JsonRpcError = OptionalField<\n Infer<typeof JsonRpcErrorStruct>,\n 'data'\n>;\n\nexport const JsonRpcParamsStruct: Struct<Json[] | Record<string, Json>, null> =\n union([record(string(), JsonStruct), array(JsonStruct)]);\n\nexport type JsonRpcParams = Json[] | Record<string, Json>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\nexport type InferWithParams<\n Type extends Struct<any>,\n Params extends JsonRpcParams,\n> = Infer<Type> & {\n params?: Params;\n};\n\n/**\n * A JSON-RPC request object.\n */\nexport type JsonRpcRequest<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcRequestStruct, Params>;\n\nexport const JsonRpcNotificationStruct = object({\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\n/**\n * A JSON-RPC notification object.\n */\nexport type JsonRpcNotification<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcNotificationStruct, Params>;\n\n/**\n * Check if the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcNotification}\n * object.\n */\nexport function isJsonRpcNotification(\n value: unknown,\n): value is JsonRpcNotification {\n return is(value, JsonRpcNotificationStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcNotification} object.\n */\nexport function assertIsJsonRpcNotification(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcNotification {\n assertStruct(\n value,\n JsonRpcNotificationStruct,\n 'Invalid JSON-RPC notification',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcRequest} object.\n */\nexport function isJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n return is(value, JsonRpcRequestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The JSON-RPC request or notification to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcRequest} object.\n */\nexport function assertIsJsonRpcRequest(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcRequest {\n assertStruct(\n value,\n JsonRpcRequestStruct,\n 'Invalid JSON-RPC request',\n ErrorWrapper,\n );\n}\n\nexport const PendingJsonRpcResponseStruct = superstructObject({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: optional(unknown()),\n error: optional(JsonRpcErrorStruct),\n});\n\n/**\n * A JSON-RPC response object that has not yet been resolved.\n */\nexport type PendingJsonRpcResponse<Result extends Json> = Omit<\n Infer<typeof PendingJsonRpcResponseStruct>,\n 'result'\n> & {\n result?: Result;\n};\n\nexport const JsonRpcSuccessStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: JsonStruct,\n});\n\n/**\n * A successful JSON-RPC response object.\n */\nexport type JsonRpcSuccess<Result extends Json> = Omit<\n Infer<typeof JsonRpcSuccessStruct>,\n 'result'\n> & {\n result: Result;\n};\n\nexport const JsonRpcFailureStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n error: JsonRpcErrorStruct as Struct<JsonRpcError>,\n});\n\n/**\n * A failed JSON-RPC response object.\n */\nexport type JsonRpcFailure = Infer<typeof JsonRpcFailureStruct>;\n\nexport const JsonRpcResponseStruct = union([\n JsonRpcSuccessStruct,\n JsonRpcFailureStruct,\n]);\n\n/**\n * A JSON-RPC response object. Must be checked to determine whether it's a\n * success or failure.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcResponse<Result extends Json> =\n | JsonRpcSuccess<Result>\n | JsonRpcFailure;\n\n/**\n * Type guard to check whether specified JSON-RPC response is a\n * {@link PendingJsonRpcResponse}.\n *\n * @param response - The JSON-RPC response to check.\n * @returns Whether the specified JSON-RPC response is pending.\n */\nexport function isPendingJsonRpcResponse(\n response: unknown,\n): response is PendingJsonRpcResponse<Json> {\n return is(response, PendingJsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link PendingJsonRpcResponse} object.\n *\n * @param response - The JSON-RPC response to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link PendingJsonRpcResponse}\n * object.\n */\nexport function assertIsPendingJsonRpcResponse(\n response: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts response is PendingJsonRpcResponse<Json> {\n assertStruct(\n response,\n PendingJsonRpcResponseStruct,\n 'Invalid pending JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Type guard to check if a value is a {@link JsonRpcResponse}.\n *\n * @param response - The object to check.\n * @returns Whether the object is a JsonRpcResponse.\n */\nexport function isJsonRpcResponse(\n response: unknown,\n): response is JsonRpcResponse<Json> {\n return is(response, JsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcResponse} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcResponse} object.\n */\nexport function assertIsJsonRpcResponse(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcResponse<Json> {\n assertStruct(\n value,\n JsonRpcResponseStruct,\n 'Invalid JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcSuccess} object.\n */\nexport function isJsonRpcSuccess(\n value: unknown,\n): value is JsonRpcSuccess<Json> {\n return is(value, JsonRpcSuccessStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcSuccess} object.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcSuccess<Json> {\n assertStruct(\n value,\n JsonRpcSuccessStruct,\n 'Invalid JSON-RPC success response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcFailure} object.\n */\nexport function isJsonRpcFailure(value: unknown): value is JsonRpcFailure {\n return is(value, JsonRpcFailureStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcFailure} object.\n */\nexport function assertIsJsonRpcFailure(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcFailure {\n assertStruct(\n value,\n JsonRpcFailureStruct,\n 'Invalid JSON-RPC failure response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcError} object.\n */\nexport function isJsonRpcError(value: unknown): value is JsonRpcError {\n return is(value, JsonRpcErrorStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcError} object.\n */\nexport function assertIsJsonRpcError(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcError {\n assertStruct(\n value,\n JsonRpcErrorStruct,\n 'Invalid JSON-RPC error',\n ErrorWrapper,\n );\n}\n\ntype JsonRpcValidatorOptions = {\n permitEmptyString?: boolean;\n permitFractions?: boolean;\n permitNull?: boolean;\n};\n\n/**\n * Gets a function for validating JSON-RPC request / response `id` values.\n *\n * By manipulating the options of this factory, you can control the behavior\n * of the resulting validator for some edge cases. This is useful because e.g.\n * `null` should sometimes but not always be permitted.\n *\n * Note that the empty string (`''`) is always permitted by the JSON-RPC\n * specification, but that kind of sucks and you may want to forbid it in some\n * instances anyway.\n *\n * For more details, see the\n * [JSON-RPC Specification](https://www.jsonrpc.org/specification).\n *\n * @param options - An options object.\n * @param options.permitEmptyString - Whether the empty string (i.e. `''`)\n * should be treated as a valid ID. Default: `true`\n * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)\n * should be treated as valid IDs. Default: `false`\n * @param options.permitNull - Whether `null` should be treated as a valid ID.\n * Default: `true`\n * @returns The JSON-RPC ID validator function.\n */\nexport function getJsonRpcIdValidator(options?: JsonRpcValidatorOptions) {\n const { permitEmptyString, permitFractions, permitNull } = {\n permitEmptyString: true,\n permitFractions: false,\n permitNull: true,\n ...options,\n };\n\n /**\n * Type guard for {@link JsonRpcId}.\n *\n * @param id - The JSON-RPC ID value to check.\n * @returns Whether the given ID is valid per the options given to the\n * factory.\n */\n const isValidJsonRpcId = (id: unknown): id is JsonRpcId => {\n return Boolean(\n (typeof id === 'number' && (permitFractions || Number.isInteger(id))) ||\n (typeof id === 'string' && (permitEmptyString || id.length > 0)) ||\n (permitNull && id === null),\n );\n };\n\n return isValidJsonRpcId;\n}\n"]}
|
package/dist/json.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.d.cts","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"json.d.cts","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":"AAAA,OAAO,EAiBL,MAAM,EACP,8BAA8B;AAC/B,OAAO,KAAK,EAEV,KAAK,EACL,YAAY,E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AOxC;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,OAAO,GACb,KAAK,IAAI,cAAc,CAAC,IAAI,CAAC,CAE/B;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,OAAO,EAEd,YAAY,CAAC,EAAE,yBAAyB,GACvC,OAAO,CAAC,KAAK,IAAI,cAAc,CAAC,IAAI,CAAC,CAOvC;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,cAAc,CAExE;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,OAAO,EAEd,YAAY,CAAC,EAAE,yBAAyB,GACvC,OAAO,CAAC,KAAK,IAAI,cAAc,CAOjC;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,YAAY,CAEpE;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,OAAO,EAEd,YAAY,CAAC,EAAE,yBAAyB,GACvC,OAAO,CAAC,KAAK,IAAI,YAAY,CAO/B;AAED,KAAK,uBAAuB,GAAG;IAC7B,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,CAAC,EAAE,uBAAuB,QAevC,OAAO,kCAStC"}
|
package/dist/json.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.d.mts","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"json.d.mts","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":"AAAA,OAAO,EAiBL,MAAM,EAC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ACvC,OAAO,CAAC,KAAK,IAAI,eAAe,CAAC,IAAI,CAAC,CAOxC;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,OAAO,GACb,KAAK,IAAI,cAAc,CAAC,IAAI,CAAC,CAE/B;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,OAAO,EAEd,YAAY,CAAC,EAAE,yBAAyB,GACvC,OAAO,CAAC,KAAK,IAAI,cAAc,CAAC,IAAI,CAAC,CAOvC;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,cAAc,CAExE;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,OAAO,EAEd,YAAY,CAAC,EAAE,yBAAyB,GACvC,OAAO,CAAC,KAAK,IAAI,cAAc,CAOjC;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,YAAY,CAEpE;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,OAAO,EAEd,YAAY,CAAC,EAAE,yBAAyB,GACvC,OAAO,CAAC,KAAK,IAAI,YAAY,CAO/B;AAED,KAAK,uBAAuB,GAAG;IAC7B,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,CAAC,EAAE,uBAAuB,QAevC,OAAO,kCAStC"}
|
package/dist/json.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { any, array,
|
|
1
|
+
import { any, array, coerce, create, define, integer, is, literal, nullable, number, object as superstructObject, optional, record, string, union, unknown, Struct } from "@metamask/superstruct";
|
|
2
2
|
import { assertStruct } from "./assert.mjs";
|
|
3
3
|
import { hasProperty } from "./misc.mjs";
|
|
4
4
|
/**
|
|
@@ -62,28 +62,55 @@ export function exactOptional(struct) {
|
|
|
62
62
|
});
|
|
63
63
|
}
|
|
64
64
|
/**
|
|
65
|
-
*
|
|
66
|
-
* `number()` struct does not check if the value is finite.
|
|
65
|
+
* Validate an unknown input to be valid JSON.
|
|
67
66
|
*
|
|
68
|
-
*
|
|
67
|
+
* Useful for constructing JSON structs.
|
|
68
|
+
*
|
|
69
|
+
* @param json - An unknown value.
|
|
70
|
+
* @returns True if the value is valid JSON, otherwise false.
|
|
69
71
|
*/
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
72
|
+
function validateJson(json) {
|
|
73
|
+
if (json === null || typeof json === 'boolean' || typeof json === 'string') {
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
if (typeof json === 'number' && Number.isFinite(json)) {
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
if (typeof json === 'object') {
|
|
80
|
+
let every = true;
|
|
81
|
+
if (Array.isArray(json)) {
|
|
82
|
+
// Ignoring linting error since for-of is significantly slower than a normal for-loop
|
|
83
|
+
// and performance is important in this specific function.
|
|
84
|
+
// eslint-disable-next-line @typescript-eslint/prefer-for-of
|
|
85
|
+
for (let i = 0; i < json.length; i++) {
|
|
86
|
+
if (!validateJson(json[i])) {
|
|
87
|
+
every = false;
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return every;
|
|
92
|
+
}
|
|
93
|
+
const entries = Object.entries(json);
|
|
94
|
+
// Ignoring linting errors since for-of is significantly slower than a normal for-loop
|
|
95
|
+
// and performance is important in this specific function.
|
|
96
|
+
// eslint-disable-next-line @typescript-eslint/prefer-for-of
|
|
97
|
+
for (let i = 0; i < entries.length; i++) {
|
|
98
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
99
|
+
if (typeof entries[i][0] !== 'string' || !validateJson(entries[i][1])) {
|
|
100
|
+
every = false;
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return every;
|
|
105
|
+
}
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
73
108
|
/**
|
|
74
109
|
* A struct to check if the given value is a valid JSON-serializable value.
|
|
75
110
|
*
|
|
76
111
|
* Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.
|
|
77
112
|
*/
|
|
78
|
-
|
|
79
|
-
export const UnsafeJsonStruct = union([
|
|
80
|
-
literal(null),
|
|
81
|
-
boolean(),
|
|
82
|
-
finiteNumber(),
|
|
83
|
-
string(),
|
|
84
|
-
array(lazy(() => UnsafeJsonStruct)),
|
|
85
|
-
record(string(), lazy(() => UnsafeJsonStruct)),
|
|
86
|
-
]);
|
|
113
|
+
export const UnsafeJsonStruct = define('JSON', (json) => validateJson(json));
|
|
87
114
|
/**
|
|
88
115
|
* A struct to check if the given value is a valid JSON-serializable value.
|
|
89
116
|
*
|
package/dist/json.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.mjs","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EACH,KAAK,EACL,OAAO,EACP,MAAM,EACN,MAAM,EACN,MAAM,EACN,OAAO,EACP,EAAE,EACF,IAAI,EACJ,OAAO,EACP,QAAQ,EACR,MAAM,EACN,MAAM,IAAI,iBAAiB,EAC3B,QAAQ,EACR,MAAM,EACN,MAAM,EACN,KAAK,EACL,OAAO,EACP,MAAM,EACP,8BAA8B;AAU/B,OAAO,EAAE,YAAY,EAAE,qBAAiB;AACxC,OAAO,EAAE,WAAW,EAAE,mBAAe;AAgDrC;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CACpB,MAAc,EACc,EAAE;AAC9B,0EAA0E;AAC1E,2EAA2E;AAC3E,2DAA2D;AAC3D,iBAAiB,CAAC,MAAM,CAA0C,CAAC;AAOrE;;;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AAE,IAAI;QACvB,eAAe,EAAE,KAAK;QACtB,UAAU,EAAE,IAAI;QAChB,GAAG,OAAO;KACX,CAAC;IAEF;;;;;;OAMG;IACH,MAAM,gBAAgB,GAAG,CAAC,EAAW,EAAmB,EAAE;QACxD,OAAO,OAAO,CACZ,CAAC,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,eAAe,IAAI,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;YACnE,CAAC,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,iBAAiB,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YAChE,CAAC,UAAU,IAAI,EAAE,KAAK,IAAI,CAAC,CAC9B,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO,gBAAgB,CAAC;AAC1B,CAAC","sourcesContent":["import {\n any,\n array,\n boolean,\n coerce,\n create,\n define,\n integer,\n is,\n lazy,\n literal,\n nullable,\n number,\n object as superstructObject,\n optional,\n record,\n string,\n union,\n unknown,\n Struct,\n} from '@metamask/superstruct';\nimport type {\n Context,\n Infer,\n ObjectSchema,\n Simplify,\n Optionalize,\n} from '@metamask/superstruct';\n\nimport type { AssertionErrorConstructor } from './assert';\nimport { assertStruct } from './assert';\nimport { hasProperty } from './misc';\n\n/**\n * Any JSON-compatible value.\n */\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [prop: string]: Json };\n\n/**\n * A helper type to make properties with `undefined` in their type optional, but\n * not `undefined` itself.\n *\n * @example\n * ```ts\n * type Foo = ObjectOptional<{ foo: string | undefined }>;\n * // Foo is equivalent to { foo?: string }\n * ```\n */\nexport type ObjectOptional<Schema extends Record<string, unknown>> = {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? Key\n : never]?: Schema[Key] extends ExactOptionalGuard & infer Original\n ? Original\n : never;\n} & {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? never\n : Key]: Schema[Key];\n};\n\n/**\n * An object type with support for exact optionals. This is used by the `object`\n * struct. This uses the {@link ObjectOptional} helper to make properties with\n * `undefined` in their type optional, but not `undefined` itself.\n */\nexport type ObjectType<Schema extends ObjectSchema> = Simplify<\n ObjectOptional<\n Optionalize<{\n [Key in keyof Schema]: Infer<Schema[Key]>;\n }>\n >\n>;\n\n/**\n * A struct to check if the given value is a valid object, with support for\n * {@link exactOptional} types.\n *\n * @param schema - The schema of the object.\n * @returns A struct to check if the given value is an object.\n */\nexport const object = <Schema extends ObjectSchema>(\n schema: Schema,\n): Struct<ObjectType<Schema>> =>\n // The type is slightly different from a regular object struct, because we\n // want to make properties with `undefined` in their type optional, but not\n // `undefined` itself. This means that we need a type cast.\n superstructObject(schema) as unknown as Struct<ObjectType<Schema>>;\n\ndeclare const exactOptionalSymbol: unique symbol;\ntype ExactOptionalGuard = {\n _exactOptionalGuard?: typeof exactOptionalSymbol;\n};\n\n/**\n * Check the last field of a path is present.\n *\n * @param context - The context to check.\n * @param context.path - The path to check.\n * @param context.branch - The branch to check.\n * @returns Whether the last field of a path is present.\n */\nfunction hasOptional({ path, branch }: Context): boolean {\n const field = path[path.length - 1];\n return hasProperty(branch[branch.length - 2], field);\n}\n\n/**\n * A struct which allows the property of an object to be absent, or to be present\n * as long as it's valid and not set to `undefined`.\n *\n * This struct should be used in conjunction with the {@link object} from this\n * library, to get proper type inference.\n *\n * @param struct - The struct to check the value against, if present.\n * @returns A struct to check if the given value is valid, or not present.\n * @example\n * ```ts\n * const struct = object({\n * foo: exactOptional(string()),\n * bar: exactOptional(number()),\n * baz: optional(boolean()),\n * qux: unknown(),\n * });\n *\n * type Type = Infer<typeof struct>;\n * // Type is equivalent to:\n * // {\n * // foo?: string;\n * // bar?: number;\n * // baz?: boolean | undefined;\n * // qux: unknown;\n * // }\n * ```\n */\nexport function exactOptional<Type, Schema>(\n struct: Struct<Type, Schema>,\n): Struct<Type & ExactOptionalGuard, Schema> {\n return new Struct<Type & ExactOptionalGuard, Schema>({\n ...struct,\n\n type: `optional ${struct.type}`,\n validator: (value, context) =>\n !hasOptional(context) || struct.validator(value, context),\n\n refiner: (value, context) =>\n !hasOptional(context) || struct.refiner(value as Type, context),\n });\n}\n\n/**\n * A struct to check if the given value is finite number. Superstruct's\n * `number()` struct does not check if the value is finite.\n *\n * @returns A struct to check if the given value is finite number.\n */\nconst finiteNumber = () =>\n define<number>('finite number', (value) => {\n return is(value, number()) && Number.isFinite(value);\n });\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.\n */\n// We cannot infer the type of the struct, because it is recursive.\nexport const UnsafeJsonStruct: Struct<Json> = union([\n literal(null),\n boolean(),\n finiteNumber(),\n string(),\n array(lazy(() => UnsafeJsonStruct)),\n record(\n string(),\n lazy(() => UnsafeJsonStruct),\n ),\n]);\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * This struct sanitizes the value before validating it, so that it is safe to\n * use with untrusted input.\n */\nexport const JsonStruct = coerce(UnsafeJsonStruct, any(), (value) => {\n assertStruct(value, UnsafeJsonStruct);\n return JSON.parse(\n JSON.stringify(value, (propKey, propValue) => {\n // Strip __proto__ and constructor properties to prevent prototype pollution.\n if (propKey === '__proto__' || propKey === 'constructor') {\n return undefined;\n }\n return propValue;\n }),\n );\n});\n\n/**\n * Check if the given value is a valid {@link Json} value, i.e., a value that is\n * serializable to JSON.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link Json} value.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n getSafeJson(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate and return sanitized JSON.\n *\n * Note:\n * This function uses sanitized JsonStruct for validation\n * that applies stringify and then parse of a value provided\n * to ensure that there are no getters which can have side effects\n * that can cause security issues.\n *\n * @param value - JSON structure to be processed.\n * @returns Sanitized JSON structure.\n */\nexport function getSafeJson<Type extends Json = Json>(value: unknown): Type {\n return create(value, JsonStruct) as Type;\n}\n\n/**\n * Get the size of a JSON value in bytes. This also validates the value.\n *\n * @param value - The JSON value to get the size of.\n * @returns The size of the JSON value in bytes.\n */\nexport function getJsonSize(value: unknown): number {\n assertStruct(value, JsonStruct, 'Invalid JSON value');\n\n const json = JSON.stringify(value);\n return new TextEncoder().encode(json).byteLength;\n}\n\n/**\n * The string '2.0'.\n */\nexport const jsonrpc2 = '2.0' as const;\nexport const JsonRpcVersionStruct = literal(jsonrpc2);\n\n/**\n * A String specifying the version of the JSON-RPC protocol.\n * MUST be exactly \"2.0\".\n */\nexport type JsonRpcVersion2 = typeof jsonrpc2;\n\nexport const JsonRpcIdStruct = nullable(union([number(), string()]));\n\n/**\n * An identifier established by the Client that MUST contain a String, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts.\n */\nexport type JsonRpcId = Infer<typeof JsonRpcIdStruct>;\n\nexport const JsonRpcErrorStruct = object({\n code: integer(),\n message: string(),\n data: exactOptional(JsonStruct),\n stack: exactOptional(string()),\n});\n\n/**\n * Mark a certain key of a type as optional.\n */\nexport type OptionalField<\n Type extends Record<string, unknown>,\n Key extends keyof Type,\n> = Omit<Type, Key> & Partial<Pick<Type, Key>>;\n\n/**\n * A JSON-RPC error object.\n *\n * Note that TypeScript infers `unknown | undefined` as `unknown`, meaning that\n * the `data` field is not optional. To make it optional, we use the\n * `OptionalField` helper, to explicitly make it optional.\n */\nexport type JsonRpcError = OptionalField<\n Infer<typeof JsonRpcErrorStruct>,\n 'data'\n>;\n\nexport const JsonRpcParamsStruct: Struct<Json[] | Record<string, Json>, null> =\n union([record(string(), JsonStruct), array(JsonStruct)]);\n\nexport type JsonRpcParams = Json[] | Record<string, Json>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\nexport type InferWithParams<\n Type extends Struct<any>,\n Params extends JsonRpcParams,\n> = Infer<Type> & {\n params?: Params;\n};\n\n/**\n * A JSON-RPC request object.\n */\nexport type JsonRpcRequest<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcRequestStruct, Params>;\n\nexport const JsonRpcNotificationStruct = object({\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\n/**\n * A JSON-RPC notification object.\n */\nexport type JsonRpcNotification<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcNotificationStruct, Params>;\n\n/**\n * Check if the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcNotification}\n * object.\n */\nexport function isJsonRpcNotification(\n value: unknown,\n): value is JsonRpcNotification {\n return is(value, JsonRpcNotificationStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcNotification} object.\n */\nexport function assertIsJsonRpcNotification(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcNotification {\n assertStruct(\n value,\n JsonRpcNotificationStruct,\n 'Invalid JSON-RPC notification',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcRequest} object.\n */\nexport function isJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n return is(value, JsonRpcRequestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The JSON-RPC request or notification to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcRequest} object.\n */\nexport function assertIsJsonRpcRequest(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcRequest {\n assertStruct(\n value,\n JsonRpcRequestStruct,\n 'Invalid JSON-RPC request',\n ErrorWrapper,\n );\n}\n\nexport const PendingJsonRpcResponseStruct = superstructObject({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: optional(unknown()),\n error: optional(JsonRpcErrorStruct),\n});\n\n/**\n * A JSON-RPC response object that has not yet been resolved.\n */\nexport type PendingJsonRpcResponse<Result extends Json> = Omit<\n Infer<typeof PendingJsonRpcResponseStruct>,\n 'result'\n> & {\n result?: Result;\n};\n\nexport const JsonRpcSuccessStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: JsonStruct,\n});\n\n/**\n * A successful JSON-RPC response object.\n */\nexport type JsonRpcSuccess<Result extends Json> = Omit<\n Infer<typeof JsonRpcSuccessStruct>,\n 'result'\n> & {\n result: Result;\n};\n\nexport const JsonRpcFailureStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n error: JsonRpcErrorStruct as Struct<JsonRpcError>,\n});\n\n/**\n * A failed JSON-RPC response object.\n */\nexport type JsonRpcFailure = Infer<typeof JsonRpcFailureStruct>;\n\nexport const JsonRpcResponseStruct = union([\n JsonRpcSuccessStruct,\n JsonRpcFailureStruct,\n]);\n\n/**\n * A JSON-RPC response object. Must be checked to determine whether it's a\n * success or failure.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcResponse<Result extends Json> =\n | JsonRpcSuccess<Result>\n | JsonRpcFailure;\n\n/**\n * Type guard to check whether specified JSON-RPC response is a\n * {@link PendingJsonRpcResponse}.\n *\n * @param response - The JSON-RPC response to check.\n * @returns Whether the specified JSON-RPC response is pending.\n */\nexport function isPendingJsonRpcResponse(\n response: unknown,\n): response is PendingJsonRpcResponse<Json> {\n return is(response, PendingJsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link PendingJsonRpcResponse} object.\n *\n * @param response - The JSON-RPC response to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link PendingJsonRpcResponse}\n * object.\n */\nexport function assertIsPendingJsonRpcResponse(\n response: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts response is PendingJsonRpcResponse<Json> {\n assertStruct(\n response,\n PendingJsonRpcResponseStruct,\n 'Invalid pending JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Type guard to check if a value is a {@link JsonRpcResponse}.\n *\n * @param response - The object to check.\n * @returns Whether the object is a JsonRpcResponse.\n */\nexport function isJsonRpcResponse(\n response: unknown,\n): response is JsonRpcResponse<Json> {\n return is(response, JsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcResponse} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcResponse} object.\n */\nexport function assertIsJsonRpcResponse(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcResponse<Json> {\n assertStruct(\n value,\n JsonRpcResponseStruct,\n 'Invalid JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcSuccess} object.\n */\nexport function isJsonRpcSuccess(\n value: unknown,\n): value is JsonRpcSuccess<Json> {\n return is(value, JsonRpcSuccessStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcSuccess} object.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcSuccess<Json> {\n assertStruct(\n value,\n JsonRpcSuccessStruct,\n 'Invalid JSON-RPC success response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcFailure} object.\n */\nexport function isJsonRpcFailure(value: unknown): value is JsonRpcFailure {\n return is(value, JsonRpcFailureStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcFailure} object.\n */\nexport function assertIsJsonRpcFailure(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcFailure {\n assertStruct(\n value,\n JsonRpcFailureStruct,\n 'Invalid JSON-RPC failure response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcError} object.\n */\nexport function isJsonRpcError(value: unknown): value is JsonRpcError {\n return is(value, JsonRpcErrorStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcError} object.\n */\nexport function assertIsJsonRpcError(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcError {\n assertStruct(\n value,\n JsonRpcErrorStruct,\n 'Invalid JSON-RPC error',\n ErrorWrapper,\n );\n}\n\ntype JsonRpcValidatorOptions = {\n permitEmptyString?: boolean;\n permitFractions?: boolean;\n permitNull?: boolean;\n};\n\n/**\n * Gets a function for validating JSON-RPC request / response `id` values.\n *\n * By manipulating the options of this factory, you can control the behavior\n * of the resulting validator for some edge cases. This is useful because e.g.\n * `null` should sometimes but not always be permitted.\n *\n * Note that the empty string (`''`) is always permitted by the JSON-RPC\n * specification, but that kind of sucks and you may want to forbid it in some\n * instances anyway.\n *\n * For more details, see the\n * [JSON-RPC Specification](https://www.jsonrpc.org/specification).\n *\n * @param options - An options object.\n * @param options.permitEmptyString - Whether the empty string (i.e. `''`)\n * should be treated as a valid ID. Default: `true`\n * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)\n * should be treated as valid IDs. Default: `false`\n * @param options.permitNull - Whether `null` should be treated as a valid ID.\n * Default: `true`\n * @returns The JSON-RPC ID validator function.\n */\nexport function getJsonRpcIdValidator(options?: JsonRpcValidatorOptions) {\n const { permitEmptyString, permitFractions, permitNull } = {\n permitEmptyString: true,\n permitFractions: false,\n permitNull: true,\n ...options,\n };\n\n /**\n * Type guard for {@link JsonRpcId}.\n *\n * @param id - The JSON-RPC ID value to check.\n * @returns Whether the given ID is valid per the options given to the\n * factory.\n */\n const isValidJsonRpcId = (id: unknown): id is JsonRpcId => {\n return Boolean(\n (typeof id === 'number' && (permitFractions || Number.isInteger(id))) ||\n (typeof id === 'string' && (permitEmptyString || id.length > 0)) ||\n (permitNull && id === null),\n );\n };\n\n return isValidJsonRpcId;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"json.mjs","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EACH,KAAK,EACL,MAAM,EACN,MAAM,EACN,MAAM,EACN,OAAO,EACP,EAAE,EACF,OAAO,EACP,QAAQ,EACR,MAAM,EACN,MAAM,IAAI,iBAAiB,EAC3B,QAAQ,EACR,MAAM,EACN,MAAM,EACN,KAAK,EACL,OAAO,EACP,MAAM,EACP,8BAA8B;AAU/B,OAAO,EAA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I,CAAC,eAAe,IAAI,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;YACnE,CAAC,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,iBAAiB,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YAChE,CAAC,UAAU,IAAI,EAAE,KAAK,IAAI,CAAC,CAC9B,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO,gBAAgB,CAAC;AAC1B,CAAC","sourcesContent":["import {\n any,\n array,\n coerce,\n create,\n define,\n integer,\n is,\n literal,\n nullable,\n number,\n object as superstructObject,\n optional,\n record,\n string,\n union,\n unknown,\n Struct,\n} from '@metamask/superstruct';\nimport type {\n Context,\n Infer,\n ObjectSchema,\n Simplify,\n Optionalize,\n} from '@metamask/superstruct';\n\nimport type { AssertionErrorConstructor } from './assert';\nimport { assertStruct } from './assert';\nimport { hasProperty } from './misc';\n\n/**\n * Any JSON-compatible value.\n */\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [prop: string]: Json };\n\n/**\n * A helper type to make properties with `undefined` in their type optional, but\n * not `undefined` itself.\n *\n * @example\n * ```ts\n * type Foo = ObjectOptional<{ foo: string | undefined }>;\n * // Foo is equivalent to { foo?: string }\n * ```\n */\nexport type ObjectOptional<Schema extends Record<string, unknown>> = {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? Key\n : never]?: Schema[Key] extends ExactOptionalGuard & infer Original\n ? Original\n : never;\n} & {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? never\n : Key]: Schema[Key];\n};\n\n/**\n * An object type with support for exact optionals. This is used by the `object`\n * struct. This uses the {@link ObjectOptional} helper to make properties with\n * `undefined` in their type optional, but not `undefined` itself.\n */\nexport type ObjectType<Schema extends ObjectSchema> = Simplify<\n ObjectOptional<\n Optionalize<{\n [Key in keyof Schema]: Infer<Schema[Key]>;\n }>\n >\n>;\n\n/**\n * A struct to check if the given value is a valid object, with support for\n * {@link exactOptional} types.\n *\n * @param schema - The schema of the object.\n * @returns A struct to check if the given value is an object.\n */\nexport const object = <Schema extends ObjectSchema>(\n schema: Schema,\n): Struct<ObjectType<Schema>> =>\n // The type is slightly different from a regular object struct, because we\n // want to make properties with `undefined` in their type optional, but not\n // `undefined` itself. This means that we need a type cast.\n superstructObject(schema) as unknown as Struct<ObjectType<Schema>>;\n\ndeclare const exactOptionalSymbol: unique symbol;\ntype ExactOptionalGuard = {\n _exactOptionalGuard?: typeof exactOptionalSymbol;\n};\n\n/**\n * Check the last field of a path is present.\n *\n * @param context - The context to check.\n * @param context.path - The path to check.\n * @param context.branch - The branch to check.\n * @returns Whether the last field of a path is present.\n */\nfunction hasOptional({ path, branch }: Context): boolean {\n const field = path[path.length - 1];\n return hasProperty(branch[branch.length - 2], field);\n}\n\n/**\n * A struct which allows the property of an object to be absent, or to be present\n * as long as it's valid and not set to `undefined`.\n *\n * This struct should be used in conjunction with the {@link object} from this\n * library, to get proper type inference.\n *\n * @param struct - The struct to check the value against, if present.\n * @returns A struct to check if the given value is valid, or not present.\n * @example\n * ```ts\n * const struct = object({\n * foo: exactOptional(string()),\n * bar: exactOptional(number()),\n * baz: optional(boolean()),\n * qux: unknown(),\n * });\n *\n * type Type = Infer<typeof struct>;\n * // Type is equivalent to:\n * // {\n * // foo?: string;\n * // bar?: number;\n * // baz?: boolean | undefined;\n * // qux: unknown;\n * // }\n * ```\n */\nexport function exactOptional<Type, Schema>(\n struct: Struct<Type, Schema>,\n): Struct<Type & ExactOptionalGuard, Schema> {\n return new Struct<Type & ExactOptionalGuard, Schema>({\n ...struct,\n\n type: `optional ${struct.type}`,\n validator: (value, context) =>\n !hasOptional(context) || struct.validator(value, context),\n\n refiner: (value, context) =>\n !hasOptional(context) || struct.refiner(value as Type, context),\n });\n}\n\n/**\n * Validate an unknown input to be valid JSON.\n *\n * Useful for constructing JSON structs.\n *\n * @param json - An unknown value.\n * @returns True if the value is valid JSON, otherwise false.\n */\nfunction validateJson(json: unknown): boolean {\n if (json === null || typeof json === 'boolean' || typeof json === 'string') {\n return true;\n }\n\n if (typeof json === 'number' && Number.isFinite(json)) {\n return true;\n }\n\n if (typeof json === 'object') {\n let every = true;\n if (Array.isArray(json)) {\n // Ignoring linting error since for-of is significantly slower than a normal for-loop\n // and performance is important in this specific function.\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < json.length; i++) {\n if (!validateJson(json[i])) {\n every = false;\n break;\n }\n }\n return every;\n }\n\n const entries = Object.entries(json);\n // Ignoring linting errors since for-of is significantly slower than a normal for-loop\n // and performance is important in this specific function.\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < entries.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n if (typeof entries[i]![0] !== 'string' || !validateJson(entries[i]![1])) {\n every = false;\n break;\n }\n }\n return every;\n }\n\n return false;\n}\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.\n */\nexport const UnsafeJsonStruct: Struct<Json> = define('JSON', (json) =>\n validateJson(json),\n);\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * This struct sanitizes the value before validating it, so that it is safe to\n * use with untrusted input.\n */\nexport const JsonStruct = coerce(UnsafeJsonStruct, any(), (value) => {\n assertStruct(value, UnsafeJsonStruct);\n return JSON.parse(\n JSON.stringify(value, (propKey, propValue) => {\n // Strip __proto__ and constructor properties to prevent prototype pollution.\n if (propKey === '__proto__' || propKey === 'constructor') {\n return undefined;\n }\n return propValue;\n }),\n );\n});\n\n/**\n * Check if the given value is a valid {@link Json} value, i.e., a value that is\n * serializable to JSON.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link Json} value.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n getSafeJson(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate and return sanitized JSON.\n *\n * Note:\n * This function uses sanitized JsonStruct for validation\n * that applies stringify and then parse of a value provided\n * to ensure that there are no getters which can have side effects\n * that can cause security issues.\n *\n * @param value - JSON structure to be processed.\n * @returns Sanitized JSON structure.\n */\nexport function getSafeJson<Type extends Json = Json>(value: unknown): Type {\n return create(value, JsonStruct) as Type;\n}\n\n/**\n * Get the size of a JSON value in bytes. This also validates the value.\n *\n * @param value - The JSON value to get the size of.\n * @returns The size of the JSON value in bytes.\n */\nexport function getJsonSize(value: unknown): number {\n assertStruct(value, JsonStruct, 'Invalid JSON value');\n\n const json = JSON.stringify(value);\n return new TextEncoder().encode(json).byteLength;\n}\n\n/**\n * The string '2.0'.\n */\nexport const jsonrpc2 = '2.0' as const;\nexport const JsonRpcVersionStruct = literal(jsonrpc2);\n\n/**\n * A String specifying the version of the JSON-RPC protocol.\n * MUST be exactly \"2.0\".\n */\nexport type JsonRpcVersion2 = typeof jsonrpc2;\n\nexport const JsonRpcIdStruct = nullable(union([number(), string()]));\n\n/**\n * An identifier established by the Client that MUST contain a String, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts.\n */\nexport type JsonRpcId = Infer<typeof JsonRpcIdStruct>;\n\nexport const JsonRpcErrorStruct = object({\n code: integer(),\n message: string(),\n data: exactOptional(JsonStruct),\n stack: exactOptional(string()),\n});\n\n/**\n * Mark a certain key of a type as optional.\n */\nexport type OptionalField<\n Type extends Record<string, unknown>,\n Key extends keyof Type,\n> = Omit<Type, Key> & Partial<Pick<Type, Key>>;\n\n/**\n * A JSON-RPC error object.\n *\n * Note that TypeScript infers `unknown | undefined` as `unknown`, meaning that\n * the `data` field is not optional. To make it optional, we use the\n * `OptionalField` helper, to explicitly make it optional.\n */\nexport type JsonRpcError = OptionalField<\n Infer<typeof JsonRpcErrorStruct>,\n 'data'\n>;\n\nexport const JsonRpcParamsStruct: Struct<Json[] | Record<string, Json>, null> =\n union([record(string(), JsonStruct), array(JsonStruct)]);\n\nexport type JsonRpcParams = Json[] | Record<string, Json>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\nexport type InferWithParams<\n Type extends Struct<any>,\n Params extends JsonRpcParams,\n> = Infer<Type> & {\n params?: Params;\n};\n\n/**\n * A JSON-RPC request object.\n */\nexport type JsonRpcRequest<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcRequestStruct, Params>;\n\nexport const JsonRpcNotificationStruct = object({\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\n/**\n * A JSON-RPC notification object.\n */\nexport type JsonRpcNotification<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcNotificationStruct, Params>;\n\n/**\n * Check if the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcNotification}\n * object.\n */\nexport function isJsonRpcNotification(\n value: unknown,\n): value is JsonRpcNotification {\n return is(value, JsonRpcNotificationStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcNotification} object.\n */\nexport function assertIsJsonRpcNotification(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcNotification {\n assertStruct(\n value,\n JsonRpcNotificationStruct,\n 'Invalid JSON-RPC notification',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcRequest} object.\n */\nexport function isJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n return is(value, JsonRpcRequestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The JSON-RPC request or notification to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcRequest} object.\n */\nexport function assertIsJsonRpcRequest(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcRequest {\n assertStruct(\n value,\n JsonRpcRequestStruct,\n 'Invalid JSON-RPC request',\n ErrorWrapper,\n );\n}\n\nexport const PendingJsonRpcResponseStruct = superstructObject({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: optional(unknown()),\n error: optional(JsonRpcErrorStruct),\n});\n\n/**\n * A JSON-RPC response object that has not yet been resolved.\n */\nexport type PendingJsonRpcResponse<Result extends Json> = Omit<\n Infer<typeof PendingJsonRpcResponseStruct>,\n 'result'\n> & {\n result?: Result;\n};\n\nexport const JsonRpcSuccessStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: JsonStruct,\n});\n\n/**\n * A successful JSON-RPC response object.\n */\nexport type JsonRpcSuccess<Result extends Json> = Omit<\n Infer<typeof JsonRpcSuccessStruct>,\n 'result'\n> & {\n result: Result;\n};\n\nexport const JsonRpcFailureStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n error: JsonRpcErrorStruct as Struct<JsonRpcError>,\n});\n\n/**\n * A failed JSON-RPC response object.\n */\nexport type JsonRpcFailure = Infer<typeof JsonRpcFailureStruct>;\n\nexport const JsonRpcResponseStruct = union([\n JsonRpcSuccessStruct,\n JsonRpcFailureStruct,\n]);\n\n/**\n * A JSON-RPC response object. Must be checked to determine whether it's a\n * success or failure.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcResponse<Result extends Json> =\n | JsonRpcSuccess<Result>\n | JsonRpcFailure;\n\n/**\n * Type guard to check whether specified JSON-RPC response is a\n * {@link PendingJsonRpcResponse}.\n *\n * @param response - The JSON-RPC response to check.\n * @returns Whether the specified JSON-RPC response is pending.\n */\nexport function isPendingJsonRpcResponse(\n response: unknown,\n): response is PendingJsonRpcResponse<Json> {\n return is(response, PendingJsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link PendingJsonRpcResponse} object.\n *\n * @param response - The JSON-RPC response to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link PendingJsonRpcResponse}\n * object.\n */\nexport function assertIsPendingJsonRpcResponse(\n response: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts response is PendingJsonRpcResponse<Json> {\n assertStruct(\n response,\n PendingJsonRpcResponseStruct,\n 'Invalid pending JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Type guard to check if a value is a {@link JsonRpcResponse}.\n *\n * @param response - The object to check.\n * @returns Whether the object is a JsonRpcResponse.\n */\nexport function isJsonRpcResponse(\n response: unknown,\n): response is JsonRpcResponse<Json> {\n return is(response, JsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcResponse} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcResponse} object.\n */\nexport function assertIsJsonRpcResponse(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcResponse<Json> {\n assertStruct(\n value,\n JsonRpcResponseStruct,\n 'Invalid JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcSuccess} object.\n */\nexport function isJsonRpcSuccess(\n value: unknown,\n): value is JsonRpcSuccess<Json> {\n return is(value, JsonRpcSuccessStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcSuccess} object.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcSuccess<Json> {\n assertStruct(\n value,\n JsonRpcSuccessStruct,\n 'Invalid JSON-RPC success response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcFailure} object.\n */\nexport function isJsonRpcFailure(value: unknown): value is JsonRpcFailure {\n return is(value, JsonRpcFailureStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcFailure} object.\n */\nexport function assertIsJsonRpcFailure(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcFailure {\n assertStruct(\n value,\n JsonRpcFailureStruct,\n 'Invalid JSON-RPC failure response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcError} object.\n */\nexport function isJsonRpcError(value: unknown): value is JsonRpcError {\n return is(value, JsonRpcErrorStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcError} object.\n */\nexport function assertIsJsonRpcError(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcError {\n assertStruct(\n value,\n JsonRpcErrorStruct,\n 'Invalid JSON-RPC error',\n ErrorWrapper,\n );\n}\n\ntype JsonRpcValidatorOptions = {\n permitEmptyString?: boolean;\n permitFractions?: boolean;\n permitNull?: boolean;\n};\n\n/**\n * Gets a function for validating JSON-RPC request / response `id` values.\n *\n * By manipulating the options of this factory, you can control the behavior\n * of the resulting validator for some edge cases. This is useful because e.g.\n * `null` should sometimes but not always be permitted.\n *\n * Note that the empty string (`''`) is always permitted by the JSON-RPC\n * specification, but that kind of sucks and you may want to forbid it in some\n * instances anyway.\n *\n * For more details, see the\n * [JSON-RPC Specification](https://www.jsonrpc.org/specification).\n *\n * @param options - An options object.\n * @param options.permitEmptyString - Whether the empty string (i.e. `''`)\n * should be treated as a valid ID. Default: `true`\n * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)\n * should be treated as valid IDs. Default: `false`\n * @param options.permitNull - Whether `null` should be treated as a valid ID.\n * Default: `true`\n * @returns The JSON-RPC ID validator function.\n */\nexport function getJsonRpcIdValidator(options?: JsonRpcValidatorOptions) {\n const { permitEmptyString, permitFractions, permitNull } = {\n permitEmptyString: true,\n permitFractions: false,\n permitNull: true,\n ...options,\n };\n\n /**\n * Type guard for {@link JsonRpcId}.\n *\n * @param id - The JSON-RPC ID value to check.\n * @returns Whether the given ID is valid per the options given to the\n * factory.\n */\n const isValidJsonRpcId = (id: unknown): id is JsonRpcId => {\n return Boolean(\n (typeof id === 'number' && (permitFractions || Number.isInteger(id))) ||\n (typeof id === 'string' && (permitEmptyString || id.length > 0)) ||\n (permitNull && id === null),\n );\n };\n\n return isValidJsonRpcId;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/utils",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "10.0.0",
|
|
4
4
|
"description": "Various JavaScript/TypeScript utilities of wide relevance to the MetaMask codebase",
|
|
5
5
|
"homepage": "https://github.com/MetaMask/utils#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -83,7 +83,7 @@
|
|
|
83
83
|
"@ts-bridge/shims": "^0.1.1",
|
|
84
84
|
"@types/jest": "^28.1.7",
|
|
85
85
|
"@types/jest-when": "^3.5.3",
|
|
86
|
-
"@types/node": "
|
|
86
|
+
"@types/node": "~18.18.14",
|
|
87
87
|
"@types/uuid": "^9.0.8",
|
|
88
88
|
"@typescript-eslint/eslint-plugin": "^5.43.0",
|
|
89
89
|
"@typescript-eslint/parser": "^5.43.0",
|
|
@@ -110,7 +110,7 @@
|
|
|
110
110
|
},
|
|
111
111
|
"packageManager": "yarn@3.2.3",
|
|
112
112
|
"engines": {
|
|
113
|
-
"node": "
|
|
113
|
+
"node": "^18.18 || ^20.14 || >=22"
|
|
114
114
|
},
|
|
115
115
|
"publishConfig": {
|
|
116
116
|
"access": "public",
|