@metamask/utils 3.0.1 → 3.0.3

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 CHANGED
@@ -6,6 +6,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [3.0.3]
10
+ ### Fixed
11
+ - Allow omitting JSON-RPC params when params can be undefined ([#29](https://github.com/MetaMask/utils/pull/29))
12
+
13
+ ## [3.0.2]
14
+ ### Fixed
15
+ - Bump `superstruct` to ^0.16.5 ([#26](https://github.com/MetaMask/utils/pull/26))
16
+ - `superstruct`s 0.16.1 through 0.16.4 were not compatible with Node 14; this restores that compatibility.
17
+
9
18
  ## [3.0.1]
10
19
  ### Fixed
11
20
  - Promote `@types/debug` from development dependencies to production dependencies ([#23](https://github.com/MetaMask/utils/pull/23))
@@ -54,7 +63,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
54
63
  ### Added
55
64
  - Initial release
56
65
 
57
- [Unreleased]: https://github.com/MetaMask/utils/compare/v3.0.1...HEAD
66
+ [Unreleased]: https://github.com/MetaMask/utils/compare/v3.0.3...HEAD
67
+ [3.0.3]: https://github.com/MetaMask/utils/compare/v3.0.2...v3.0.3
68
+ [3.0.2]: https://github.com/MetaMask/utils/compare/v3.0.1...v3.0.2
58
69
  [3.0.1]: https://github.com/MetaMask/utils/compare/v3.0.0...v3.0.1
59
70
  [3.0.0]: https://github.com/MetaMask/utils/compare/v2.1.0...v3.0.0
60
71
  [2.1.0]: https://github.com/MetaMask/utils/compare/v2.0.0...v2.1.0
package/dist/json.d.ts CHANGED
@@ -59,9 +59,11 @@ export declare const JsonRpcRequestStruct: Struct<{
59
59
  method: Struct<string, null>;
60
60
  params: Struct<unknown[] | Record<string, unknown> | undefined, null>;
61
61
  }>;
62
- export declare type InferWithParams<Type extends Struct<any, unknown>, Params extends JsonRpcParams> = Omit<Infer<Type>, 'params'> & {
62
+ export declare type InferWithParams<Type extends Struct<any, unknown>, Params extends JsonRpcParams> = Omit<Infer<Type>, 'params'> & (keyof Params extends undefined ? {
63
+ params?: Params;
64
+ } : {
63
65
  params: Params;
64
- };
66
+ });
65
67
  /**
66
68
  * A JSON-RPC request object.
67
69
  */
package/dist/json.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"json.js","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":";;;;;;AAAA,sEAAwC;AACxC,6CAkBqB;AACrB,iCAKgB;AAEhB;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,KAAc;IACxC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,SAAS,IAAI,KAAK,CAAC;AAC3E,CAAC;AAED,4EAA4E;AAC/D,QAAA,UAAU,GAAiB,IAAA,mBAAK,EAAC;IAC5C,IAAA,qBAAO,EAAC,IAAI,CAAC;IACb,IAAA,qBAAO,GAAE;IACT,IAAA,oBAAM,GAAE;IACR,IAAA,oBAAM,GAAE;IACR,IAAA,kBAAI,EAAC,GAAG,EAAE,CAAC,IAAA,mBAAK,EAAC,kBAAU,CAAC,CAAC;IAC7B,IAAA,kBAAI,EAAC,GAAG,EAAE,CAAC,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,kBAAU,CAAC,CAAC;CACzC,CAAC,CAAC;AAaH;;;;;GAKG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,IAAI;QACF,OAAO,IAAA,yBAAS,EAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KAC5D;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAND,kCAMC;AAED;;GAEG;AACU,QAAA,QAAQ,GAAG,KAAc,CAAC;AAC1B,QAAA,oBAAoB,GAAG,IAAA,qBAAO,EAAC,gBA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;wBACd,OAAO,GAAG,CAAC;qBACZ;oBAED,qDAAqD;oBACrD,uDAAuD;oBACvD,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;wBAClC,CAAC,CAAC,CAAC;wBACH,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,eAAQ,CAAC,KAAK,GAAG,eAAQ,CAAC,KAAK,GAAG,CAAC,CAAC;oBAErD,MAAM,SAAS,GAAG,GAAG,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,eAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;oBAE5D,OAAO,GAAG,GAAG,OAAO,GAAG,IAAI,GAAG,SAAS,CAAC;gBAC1C,CAAC;gBACD,mEAAmE;gBACnE,+BAA+B;gBAC/B,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,eAAQ,CAAC,OAAO,GAAG,CAAC,CACtC;aACF,CAAC;SACH;QAAC,OAAO,CAAC,EAAE;YACV,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;SACnB;IACH,CAAC;IAED,OAAO,uBAAuB,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAAC;AAC9D,CAAC;AA9ID,wDA8IC","sourcesContent":["import deepEqual from 'fast-deep-equal';\nimport {\n array,\n assert,\n boolean,\n Infer,\n is,\n lazy,\n literal,\n nullable,\n number,\n object,\n omit,\n optional,\n record,\n string,\n Struct,\n union,\n unknown,\n} from 'superstruct';\nimport {\n calculateNumberSize,\n calculateStringSize,\n isPlainObject,\n JsonSize,\n} from './misc';\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `message` property, such as an instance of Error.\n *\n * @param error - The object to check.\n * @returns True or false, depending on the result.\n */\nfunction isErrorWithMessage(error: unknown): error is { message: string } {\n return typeof error === 'object' && error !== null && 'message' in error;\n}\n\n// Note: This struct references itself, so TypeScript cannot infer the type.\nexport const JsonStruct: Struct<Json> = union([\n literal(null),\n boolean(),\n number(),\n string(),\n lazy(() => array(JsonStruct)),\n lazy(() => record(string(), JsonStruct)),\n]);\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 * Type guard for {@link Json}.\n *\n * @param value - The value to check.\n * @returns Whether the value is valid JSON.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n return deepEqual(value, JSON.parse(JSON.stringify(value)));\n } catch (_) {\n return false;\n }\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: number(),\n message: string(),\n data: optional(unknown()),\n stack: optional(string()),\n});\n\n/**\n * A JSON-RPC error object.\n */\nexport type JsonRpcError = Infer<typeof JsonRpcErrorStruct>;\n\nexport const JsonRpcParamsStruct = optional(union([object(), array()]));\n\nexport type JsonRpcParams = Infer<typeof JsonRpcParamsStruct>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: JsonRpcParamsStruct,\n});\n\nexport type InferWithParams<\n Type extends Struct<any, unknown>,\n Params extends JsonRpcParams\n> = Omit<Infer<Type>, 'params'> & {\n params: Params;\n};\n\n/**\n * A JSON-RPC request object.\n */\nexport type JsonRpcRequest<Params extends JsonRpcParams> = InferWithParams<\n typeof JsonRpcRequestStruct,\n Params\n>;\n\nexport const JsonRpcNotificationStruct = omit(JsonRpcRequestStruct, ['id']);\n\n/**\n * A JSON-RPC notification object.\n */\nexport type JsonRpcNotification<Params extends JsonRpcParams> = InferWithParams<\n typeof JsonRpcNotificationStruct,\n Params\n>;\n\n/**\n * Type guard to narrow a JSON-RPC request or notification object to a\n * notification.\n *\n * @param requestOrNotification - The JSON-RPC request or notification to check.\n * @returns Whether the specified JSON-RPC message is a notification.\n */\nexport function isJsonRpcNotification(\n requestOrNotification: unknown,\n): requestOrNotification is JsonRpcNotification<JsonRpcParams> {\n return is(requestOrNotification, JsonRpcNotificationStruct);\n}\n\n/**\n * Assertion type guard to narrow a JSON-RPC request or notification object to a\n * notification.\n *\n * @param requestOrNotification - The JSON-RPC request or notification to check.\n */\nexport function assertIsJsonRpcNotification(\n requestOrNotification: unknown,\n): asserts requestOrNotification is JsonRpcNotification<JsonRpcParams> {\n try {\n assert(requestOrNotification, JsonRpcNotificationStruct);\n } catch (error) {\n const message = isErrorWithMessage(error) ? error.message : error;\n throw new Error(`Not a JSON-RPC notification: ${message}.`);\n }\n}\n\n/**\n * Type guard to narrow a JSON-RPC request or notification object to a request.\n *\n * @param requestOrNotification - The JSON-RPC request or notification to check.\n * @returns Whether the specified JSON-RPC message is a request.\n */\nexport function isJsonRpcRequest(\n requestOrNotification: unknown,\n): requestOrNotification is JsonRpcRequest<JsonRpcParams> {\n return is(requestOrNotification, JsonRpcRequestStruct);\n}\n\n/**\n * Assertion type guard to narrow a JSON-RPC request or notification object to a\n * request.\n *\n * @param requestOrNotification - The JSON-RPC request or notification to check.\n */\nexport function assertIsJsonRpcRequest(\n requestOrNotification: unknown,\n): asserts requestOrNotification is JsonRpcRequest<JsonRpcParams> {\n try {\n assert(requestOrNotification, JsonRpcRequestStruct);\n } catch (error) {\n const message = isErrorWithMessage(error) ? error.message : error;\n throw new Error(`Not a JSON-RPC request: ${message}.`);\n }\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,\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 if a value is a 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 * Type assertion to check if a value is a JsonRpcResponse.\n *\n * @param response - The response to check.\n */\nexport function assertIsJsonRpcResponse(\n response: unknown,\n): asserts response is JsonRpcResponse<Json> {\n try {\n assert(response, JsonRpcResponseStruct);\n } catch (error) {\n const message = isErrorWithMessage(error) ? error.message : error;\n throw new Error(`Not a JSON-RPC response: ${message}.`);\n }\n}\n\n/**\n * Type guard to narrow a JsonRpcResponse object to a success (or failure).\n *\n * @param response - The response object to check.\n * @returns Whether the response object is a success.\n */\nexport function isJsonRpcSuccess(\n response: unknown,\n): response is JsonRpcSuccess<Json> {\n return is(response, JsonRpcSuccessStruct);\n}\n\n/**\n * Type assertion to narrow a JsonRpcResponse object to a success (or failure).\n *\n * @param response - The response object to check.\n */\nexport function assertIsJsonRpcSuccess(\n response: unknown,\n): asserts response is JsonRpcSuccess<Json> {\n try {\n assert(response, JsonRpcSuccessStruct);\n } catch (error) {\n const message = isErrorWithMessage(error) ? error.message : error;\n throw new Error(`Not a successful JSON-RPC response: ${message}.`);\n }\n}\n\n/**\n * Type guard to narrow a JsonRpcResponse object to a failure (or success).\n *\n * @param response - The response object to check.\n * @returns Whether the response object is a failure, i.e. has an `error`\n * property.\n */\nexport function isJsonRpcFailure(\n response: unknown,\n): response is JsonRpcFailure {\n return is(response, JsonRpcFailureStruct);\n}\n\n/**\n * Type assertion to narrow a JsonRpcResponse object to a failure (or success).\n *\n * @param response - The response object to check.\n */\nexport function assertIsJsonRpcFailure(\n response: unknown,\n): asserts response is JsonRpcFailure {\n try {\n assert(response, JsonRpcFailureStruct);\n } catch (error) {\n const message = isErrorWithMessage(error) ? error.message : error;\n throw new Error(`Not a failed JSON-RPC response: ${message}.`);\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\n/**\n * Checks whether a value is JSON serializable and counts the total number\n * of bytes needed to store the serialized version of the value.\n *\n * @param jsObject - Potential JSON serializable object.\n * @param skipSizingProcess - Skip JSON size calculation (default: false).\n * @returns Tuple [isValid, plainTextSizeInBytes] containing a boolean that signals whether\n * the value was serializable and a number of bytes that it will use when serialized to JSON.\n */\nexport function validateJsonAndGetSize(\n jsObject: unknown,\n skipSizingProcess = false,\n): [isValid: boolean, plainTextSizeInBytes: number] {\n const seenObjects = new Set();\n /**\n * Checks whether a value is JSON serializable and counts the total number\n * of bytes needed to store the serialized version of the value.\n *\n * This function assumes the encoding of the JSON is done in UTF-8.\n *\n * @param value - Potential JSON serializable value.\n * @param skipSizing - Skip JSON size calculation (default: false).\n * @returns Tuple [isValid, plainTextSizeInBytes] containing a boolean that signals whether\n * the value was serializable and a number of bytes that it will use when serialized to JSON.\n */\n function getJsonSerializableInfo(\n value: unknown,\n skipSizing: boolean,\n ): [isValid: boolean, plainTextSizeInBytes: number] {\n if (value === undefined) {\n // Return zero for undefined, since these are omitted from JSON serialization\n return [true, 0];\n } else if (value === null) {\n // Return already specified constant size for null (special object)\n return [true, skipSizing ? 0 : JsonSize.Null];\n }\n\n // Check and calculate sizes for basic (and some special) types\n const typeOfValue = typeof value;\n try {\n if (typeOfValue === 'function') {\n return [false, 0];\n } else if (typeOfValue === 'string' || value instanceof String) {\n return [\n true,\n skipSizing\n ? 0\n : calculateStringSize(value as string) + JsonSize.Quote * 2,\n ];\n } else if (typeOfValue === 'boolean' || value instanceof Boolean) {\n if (skipSizing) {\n return [true, 0];\n }\n // eslint-disable-next-line eqeqeq\n return [true, value == true ? JsonSize.True : JsonSize.False];\n } else if (typeOfValue === 'number' || value instanceof Number) {\n if (skipSizing) {\n return [true, 0];\n }\n return [true, calculateNumberSize(value as number)];\n } else if (value instanceof Date) {\n if (skipSizing) {\n return [true, 0];\n }\n return [\n true,\n // Note: Invalid dates will serialize to null\n isNaN(value.getDate())\n ? JsonSize.Null\n : JsonSize.Date + JsonSize.Quote * 2,\n ];\n }\n } catch (_) {\n return [false, 0];\n }\n\n // If object is not plain and cannot be serialized properly,\n // stop here and return false for serialization\n if (!isPlainObject(value) && !Array.isArray(value)) {\n return [false, 0];\n }\n\n // Circular object detection (handling)\n // Check if the same object already exists\n if (seenObjects.has(value)) {\n return [false, 0];\n }\n // Add new object to the seen objects set\n // Only the plain objects should be added (Primitive types are skipped)\n seenObjects.add(value);\n\n // Continue object decomposition\n try {\n return [\n true,\n Object.entries(value).reduce(\n (sum, [key, nestedValue], idx, arr) => {\n // Recursively process next nested object or primitive type\n // eslint-disable-next-line prefer-const\n let [valid, size] = getJsonSerializableInfo(\n nestedValue,\n skipSizing,\n );\n if (!valid) {\n throw new Error(\n 'JSON validation did not pass. Validation process stopped.',\n );\n }\n\n // Circular object detection\n // Once a child node is visited and processed remove it from the set.\n // This will prevent false positives with the same adjacent objects.\n seenObjects.delete(value);\n\n if (skipSizing) {\n return 0;\n }\n\n // If the size is 0, the value is undefined and undefined in an array\n // when serialized will be replaced with null\n if (size === 0 && Array.isArray(value)) {\n size = JsonSize.Null;\n }\n\n // If the size is 0, that means the object is undefined and\n // the rest of the object structure will be omitted\n if (size === 0) {\n return sum;\n }\n\n // Objects will have be serialized with \"key\": value,\n // therefore we include the key in the calculation here\n const keySize = Array.isArray(value)\n ? 0\n : key.length + JsonSize.Comma + JsonSize.Colon * 2;\n\n const separator = idx < arr.length - 1 ? JsonSize.Comma : 0;\n\n return sum + keySize + size + separator;\n },\n // Starts at 2 because the serialized JSON string data (plain text)\n // will minimally contain {}/[]\n skipSizing ? 0 : JsonSize.Wrapper * 2,\n ),\n ];\n } catch (_) {\n return [false, 0];\n }\n }\n\n return getJsonSerializableInfo(jsObject, skipSizingProcess);\n}\n"]}
1
+ {"version":3,"file":"json.js","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":";;;;;;AAAA,sEAAwC;AACxC,6CAkBqB;AACrB,iCAKgB;AAEhB;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,KAAc;IACxC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,SAAS,IAAI,KAAK,CAAC;AAC3E,CAAC;AAED,4EAA4E;AAC/D,QAAA,UAAU,GAAiB,IAAA,mBAAK,EAAC;IAC5C,IAAA,qBAAO,EAAC,IAAI,CAAC;IACb,IAAA,qBAAO,GAAE;IACT,IAAA,oBAAM,GAAE;IACR,IAAA,oBAAM,GAAE;IACR,IAAA,kBAAI,EAAC,GAAG,EAAE,CAAC,IAAA,mBAAK,EAAC,kBAAU,CAAC,CAAC;IAC7B,IAAA,kBAAI,EAAC,GAAG,EAAE,CAAC,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,kBAAU,CAAC,CAAC;CACzC,CAAC,CAAC;AAaH;;;;;GAKG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,IAAI;QACF,OAAO,IAAA,yBAAS,EAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KAC5D;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAND,kCAMC;AAED;;GAEG;AACU,QAAA,QAAQ,GAAG,KAAc,CAAC;AAC1B,QAAA,oBAAoB,GAAG,IAAA,qBAAO,EAAC,gBAAQ,CAAC,CAAC;AAQzC,QAAA,eAAe,GAAG,IAAA,sBAAQ,EAAC,IAAA,mBAAK,EAAC,CAAC,IAAA,oBAAM,GAAE,EAAE,IAAA,oBAAM,GAAE,CAAC,CAAC,CAAC,CAAC;AAUxD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AAC,GAAG,CAAC,MAAM,GAAG,eAAQ,CAAC,KAAK,GAAG,eAAQ,CAAC,KAAK,GAAG,CAAC,CAAC;oBAErD,MAAM,SAAS,GAAG,GAAG,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,eAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;oBAE5D,OAAO,GAAG,GAAG,OAAO,GAAG,IAAI,GAAG,SAAS,CAAC;gBAC1C,CAAC;gBACD,mEAAmE;gBACnE,+BAA+B;gBAC/B,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,eAAQ,CAAC,OAAO,GAAG,CAAC,CACtC;aACF,CAAC;SACH;QAAC,OAAO,CAAC,EAAE;YACV,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;SACnB;IACH,CAAC;IAED,OAAO,uBAAuB,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAAC;AAC9D,CAAC;AA9ID,wDA8IC","sourcesContent":["import deepEqual from 'fast-deep-equal';\nimport {\n array,\n assert,\n boolean,\n Infer,\n is,\n lazy,\n literal,\n nullable,\n number,\n object,\n omit,\n optional,\n record,\n string,\n Struct,\n union,\n unknown,\n} from 'superstruct';\nimport {\n calculateNumberSize,\n calculateStringSize,\n isPlainObject,\n JsonSize,\n} from './misc';\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `message` property, such as an instance of Error.\n *\n * @param error - The object to check.\n * @returns True or false, depending on the result.\n */\nfunction isErrorWithMessage(error: unknown): error is { message: string } {\n return typeof error === 'object' && error !== null && 'message' in error;\n}\n\n// Note: This struct references itself, so TypeScript cannot infer the type.\nexport const JsonStruct: Struct<Json> = union([\n literal(null),\n boolean(),\n number(),\n string(),\n lazy(() => array(JsonStruct)),\n lazy(() => record(string(), JsonStruct)),\n]);\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 * Type guard for {@link Json}.\n *\n * @param value - The value to check.\n * @returns Whether the value is valid JSON.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n return deepEqual(value, JSON.parse(JSON.stringify(value)));\n } catch (_) {\n return false;\n }\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: number(),\n message: string(),\n data: optional(unknown()),\n stack: optional(string()),\n});\n\n/**\n * A JSON-RPC error object.\n */\nexport type JsonRpcError = Infer<typeof JsonRpcErrorStruct>;\n\nexport const JsonRpcParamsStruct = optional(union([object(), array()]));\n\nexport type JsonRpcParams = Infer<typeof JsonRpcParamsStruct>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: JsonRpcParamsStruct,\n});\n\nexport type InferWithParams<\n Type extends Struct<any, unknown>,\n Params extends JsonRpcParams\n> = Omit<Infer<Type>, 'params'> &\n (keyof Params extends undefined\n ? {\n params?: Params;\n }\n : {\n params: Params;\n });\n\n/**\n * A JSON-RPC request object.\n */\nexport type JsonRpcRequest<Params extends JsonRpcParams> = InferWithParams<\n typeof JsonRpcRequestStruct,\n Params\n>;\n\nexport const JsonRpcNotificationStruct = omit(JsonRpcRequestStruct, ['id']);\n\n/**\n * A JSON-RPC notification object.\n */\nexport type JsonRpcNotification<Params extends JsonRpcParams> = InferWithParams<\n typeof JsonRpcNotificationStruct,\n Params\n>;\n\n/**\n * Type guard to narrow a JSON-RPC request or notification object to a\n * notification.\n *\n * @param requestOrNotification - The JSON-RPC request or notification to check.\n * @returns Whether the specified JSON-RPC message is a notification.\n */\nexport function isJsonRpcNotification(\n requestOrNotification: unknown,\n): requestOrNotification is JsonRpcNotification<JsonRpcParams> {\n return is(requestOrNotification, JsonRpcNotificationStruct);\n}\n\n/**\n * Assertion type guard to narrow a JSON-RPC request or notification object to a\n * notification.\n *\n * @param requestOrNotification - The JSON-RPC request or notification to check.\n */\nexport function assertIsJsonRpcNotification(\n requestOrNotification: unknown,\n): asserts requestOrNotification is JsonRpcNotification<JsonRpcParams> {\n try {\n assert(requestOrNotification, JsonRpcNotificationStruct);\n } catch (error) {\n const message = isErrorWithMessage(error) ? error.message : error;\n throw new Error(`Not a JSON-RPC notification: ${message}.`);\n }\n}\n\n/**\n * Type guard to narrow a JSON-RPC request or notification object to a request.\n *\n * @param requestOrNotification - The JSON-RPC request or notification to check.\n * @returns Whether the specified JSON-RPC message is a request.\n */\nexport function isJsonRpcRequest(\n requestOrNotification: unknown,\n): requestOrNotification is JsonRpcRequest<JsonRpcParams> {\n return is(requestOrNotification, JsonRpcRequestStruct);\n}\n\n/**\n * Assertion type guard to narrow a JSON-RPC request or notification object to a\n * request.\n *\n * @param requestOrNotification - The JSON-RPC request or notification to check.\n */\nexport function assertIsJsonRpcRequest(\n requestOrNotification: unknown,\n): asserts requestOrNotification is JsonRpcRequest<JsonRpcParams> {\n try {\n assert(requestOrNotification, JsonRpcRequestStruct);\n } catch (error) {\n const message = isErrorWithMessage(error) ? error.message : error;\n throw new Error(`Not a JSON-RPC request: ${message}.`);\n }\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,\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 if a value is a 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 * Type assertion to check if a value is a JsonRpcResponse.\n *\n * @param response - The response to check.\n */\nexport function assertIsJsonRpcResponse(\n response: unknown,\n): asserts response is JsonRpcResponse<Json> {\n try {\n assert(response, JsonRpcResponseStruct);\n } catch (error) {\n const message = isErrorWithMessage(error) ? error.message : error;\n throw new Error(`Not a JSON-RPC response: ${message}.`);\n }\n}\n\n/**\n * Type guard to narrow a JsonRpcResponse object to a success (or failure).\n *\n * @param response - The response object to check.\n * @returns Whether the response object is a success.\n */\nexport function isJsonRpcSuccess(\n response: unknown,\n): response is JsonRpcSuccess<Json> {\n return is(response, JsonRpcSuccessStruct);\n}\n\n/**\n * Type assertion to narrow a JsonRpcResponse object to a success (or failure).\n *\n * @param response - The response object to check.\n */\nexport function assertIsJsonRpcSuccess(\n response: unknown,\n): asserts response is JsonRpcSuccess<Json> {\n try {\n assert(response, JsonRpcSuccessStruct);\n } catch (error) {\n const message = isErrorWithMessage(error) ? error.message : error;\n throw new Error(`Not a successful JSON-RPC response: ${message}.`);\n }\n}\n\n/**\n * Type guard to narrow a JsonRpcResponse object to a failure (or success).\n *\n * @param response - The response object to check.\n * @returns Whether the response object is a failure, i.e. has an `error`\n * property.\n */\nexport function isJsonRpcFailure(\n response: unknown,\n): response is JsonRpcFailure {\n return is(response, JsonRpcFailureStruct);\n}\n\n/**\n * Type assertion to narrow a JsonRpcResponse object to a failure (or success).\n *\n * @param response - The response object to check.\n */\nexport function assertIsJsonRpcFailure(\n response: unknown,\n): asserts response is JsonRpcFailure {\n try {\n assert(response, JsonRpcFailureStruct);\n } catch (error) {\n const message = isErrorWithMessage(error) ? error.message : error;\n throw new Error(`Not a failed JSON-RPC response: ${message}.`);\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\n/**\n * Checks whether a value is JSON serializable and counts the total number\n * of bytes needed to store the serialized version of the value.\n *\n * @param jsObject - Potential JSON serializable object.\n * @param skipSizingProcess - Skip JSON size calculation (default: false).\n * @returns Tuple [isValid, plainTextSizeInBytes] containing a boolean that signals whether\n * the value was serializable and a number of bytes that it will use when serialized to JSON.\n */\nexport function validateJsonAndGetSize(\n jsObject: unknown,\n skipSizingProcess = false,\n): [isValid: boolean, plainTextSizeInBytes: number] {\n const seenObjects = new Set();\n /**\n * Checks whether a value is JSON serializable and counts the total number\n * of bytes needed to store the serialized version of the value.\n *\n * This function assumes the encoding of the JSON is done in UTF-8.\n *\n * @param value - Potential JSON serializable value.\n * @param skipSizing - Skip JSON size calculation (default: false).\n * @returns Tuple [isValid, plainTextSizeInBytes] containing a boolean that signals whether\n * the value was serializable and a number of bytes that it will use when serialized to JSON.\n */\n function getJsonSerializableInfo(\n value: unknown,\n skipSizing: boolean,\n ): [isValid: boolean, plainTextSizeInBytes: number] {\n if (value === undefined) {\n // Return zero for undefined, since these are omitted from JSON serialization\n return [true, 0];\n } else if (value === null) {\n // Return already specified constant size for null (special object)\n return [true, skipSizing ? 0 : JsonSize.Null];\n }\n\n // Check and calculate sizes for basic (and some special) types\n const typeOfValue = typeof value;\n try {\n if (typeOfValue === 'function') {\n return [false, 0];\n } else if (typeOfValue === 'string' || value instanceof String) {\n return [\n true,\n skipSizing\n ? 0\n : calculateStringSize(value as string) + JsonSize.Quote * 2,\n ];\n } else if (typeOfValue === 'boolean' || value instanceof Boolean) {\n if (skipSizing) {\n return [true, 0];\n }\n // eslint-disable-next-line eqeqeq\n return [true, value == true ? JsonSize.True : JsonSize.False];\n } else if (typeOfValue === 'number' || value instanceof Number) {\n if (skipSizing) {\n return [true, 0];\n }\n return [true, calculateNumberSize(value as number)];\n } else if (value instanceof Date) {\n if (skipSizing) {\n return [true, 0];\n }\n return [\n true,\n // Note: Invalid dates will serialize to null\n isNaN(value.getDate())\n ? JsonSize.Null\n : JsonSize.Date + JsonSize.Quote * 2,\n ];\n }\n } catch (_) {\n return [false, 0];\n }\n\n // If object is not plain and cannot be serialized properly,\n // stop here and return false for serialization\n if (!isPlainObject(value) && !Array.isArray(value)) {\n return [false, 0];\n }\n\n // Circular object detection (handling)\n // Check if the same object already exists\n if (seenObjects.has(value)) {\n return [false, 0];\n }\n // Add new object to the seen objects set\n // Only the plain objects should be added (Primitive types are skipped)\n seenObjects.add(value);\n\n // Continue object decomposition\n try {\n return [\n true,\n Object.entries(value).reduce(\n (sum, [key, nestedValue], idx, arr) => {\n // Recursively process next nested object or primitive type\n // eslint-disable-next-line prefer-const\n let [valid, size] = getJsonSerializableInfo(\n nestedValue,\n skipSizing,\n );\n if (!valid) {\n throw new Error(\n 'JSON validation did not pass. Validation process stopped.',\n );\n }\n\n // Circular object detection\n // Once a child node is visited and processed remove it from the set.\n // This will prevent false positives with the same adjacent objects.\n seenObjects.delete(value);\n\n if (skipSizing) {\n return 0;\n }\n\n // If the size is 0, the value is undefined and undefined in an array\n // when serialized will be replaced with null\n if (size === 0 && Array.isArray(value)) {\n size = JsonSize.Null;\n }\n\n // If the size is 0, that means the object is undefined and\n // the rest of the object structure will be omitted\n if (size === 0) {\n return sum;\n }\n\n // Objects will have be serialized with \"key\": value,\n // therefore we include the key in the calculation here\n const keySize = Array.isArray(value)\n ? 0\n : key.length + JsonSize.Comma + JsonSize.Colon * 2;\n\n const separator = idx < arr.length - 1 ? JsonSize.Comma : 0;\n\n return sum + keySize + size + separator;\n },\n // Starts at 2 because the serialized JSON string data (plain text)\n // will minimally contain {}/[]\n skipSizing ? 0 : JsonSize.Wrapper * 2,\n ),\n ];\n } catch (_) {\n return [false, 0];\n }\n }\n\n return getJsonSerializableInfo(jsObject, skipSizingProcess);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/utils",
3
- "version": "3.0.1",
3
+ "version": "3.0.3",
4
4
  "description": "Various JavaScript/TypeScript utilities of wide relevance to the MetaMask codebase.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -30,7 +30,7 @@
30
30
  "@types/debug": "^4.1.7",
31
31
  "debug": "^4.3.4",
32
32
  "fast-deep-equal": "^3.1.3",
33
- "superstruct": "^0.16.0"
33
+ "superstruct": "^0.16.5"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@lavamoat/allow-scripts": "^1.0.5",