@metamask/utils 3.3.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/json.js CHANGED
@@ -2,11 +2,14 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validateJsonAndGetSize = exports.getJsonRpcIdValidator = exports.assertIsJsonRpcError = exports.isJsonRpcError = exports.assertIsJsonRpcFailure = exports.isJsonRpcFailure = exports.assertIsJsonRpcSuccess = exports.isJsonRpcSuccess = exports.assertIsJsonRpcResponse = exports.isJsonRpcResponse = exports.assertIsPendingJsonRpcResponse = exports.isPendingJsonRpcResponse = exports.JsonRpcResponseStruct = exports.JsonRpcFailureStruct = exports.JsonRpcSuccessStruct = exports.PendingJsonRpcResponseStruct = exports.assertIsJsonRpcRequest = exports.isJsonRpcRequest = exports.assertIsJsonRpcNotification = exports.isJsonRpcNotification = exports.JsonRpcNotificationStruct = exports.JsonRpcRequestStruct = exports.JsonRpcParamsStruct = exports.JsonRpcErrorStruct = exports.JsonRpcIdStruct = exports.JsonRpcVersionStruct = exports.jsonrpc2 = exports.isValidJson = exports.JsonStruct = void 0;
4
4
  const superstruct_1 = require("superstruct");
5
- const misc_1 = require("./misc");
6
5
  const assert_1 = require("./assert");
6
+ const misc_1 = require("./misc");
7
7
  exports.JsonStruct = (0, superstruct_1.define)('Json', (value) => {
8
8
  const [isValid] = validateJsonAndGetSize(value, true);
9
- return isValid;
9
+ if (!isValid) {
10
+ return 'Expected a valid JSON-serializable value';
11
+ }
12
+ return true;
10
13
  });
11
14
  /**
12
15
  * Check if the given value is a valid {@link Json} value, i.e., a value that is
@@ -31,7 +34,7 @@ exports.JsonRpcErrorStruct = (0, superstruct_1.object)({
31
34
  data: (0, superstruct_1.optional)(exports.JsonStruct),
32
35
  stack: (0, superstruct_1.optional)((0, superstruct_1.string)()),
33
36
  });
34
- exports.JsonRpcParamsStruct = (0, superstruct_1.optional)((0, superstruct_1.union)([(0, superstruct_1.object)(), (0, superstruct_1.array)()]));
37
+ exports.JsonRpcParamsStruct = (0, superstruct_1.optional)((0, superstruct_1.union)([(0, superstruct_1.record)((0, superstruct_1.string)(), exports.JsonStruct), (0, superstruct_1.array)(exports.JsonStruct)]));
35
38
  exports.JsonRpcRequestStruct = (0, superstruct_1.object)({
36
39
  id: exports.JsonRpcIdStruct,
37
40
  jsonrpc: exports.JsonRpcVersionStruct,
@@ -58,7 +61,9 @@ exports.isJsonRpcNotification = isJsonRpcNotification;
58
61
  * Defaults to {@link AssertionError}.
59
62
  * @throws If the given value is not a valid {@link JsonRpcNotification} object.
60
63
  */
61
- function assertIsJsonRpcNotification(value, ErrorWrapper) {
64
+ function assertIsJsonRpcNotification(value,
65
+ // eslint-disable-next-line @typescript-eslint/naming-convention
66
+ ErrorWrapper) {
62
67
  (0, assert_1.assertStruct)(value, exports.JsonRpcNotificationStruct, 'Invalid JSON-RPC notification', ErrorWrapper);
63
68
  }
64
69
  exports.assertIsJsonRpcNotification = assertIsJsonRpcNotification;
@@ -80,7 +85,9 @@ exports.isJsonRpcRequest = isJsonRpcRequest;
80
85
  * Defaults to {@link AssertionError}.
81
86
  * @throws If the given value is not a valid {@link JsonRpcRequest} object.
82
87
  */
83
- function assertIsJsonRpcRequest(value, ErrorWrapper) {
88
+ function assertIsJsonRpcRequest(value,
89
+ // eslint-disable-next-line @typescript-eslint/naming-convention
90
+ ErrorWrapper) {
84
91
  (0, assert_1.assertStruct)(value, exports.JsonRpcRequestStruct, 'Invalid JSON-RPC request', ErrorWrapper);
85
92
  }
86
93
  exports.assertIsJsonRpcRequest = assertIsJsonRpcRequest;
@@ -124,7 +131,9 @@ exports.isPendingJsonRpcResponse = isPendingJsonRpcResponse;
124
131
  * @throws If the given value is not a valid {@link PendingJsonRpcResponse}
125
132
  * object.
126
133
  */
127
- function assertIsPendingJsonRpcResponse(response, ErrorWrapper) {
134
+ function assertIsPendingJsonRpcResponse(response,
135
+ // eslint-disable-next-line @typescript-eslint/naming-convention
136
+ ErrorWrapper) {
128
137
  (0, assert_1.assertStruct)(response, exports.PendingJsonRpcResponseStruct, 'Invalid pending JSON-RPC response', ErrorWrapper);
129
138
  }
130
139
  exports.assertIsPendingJsonRpcResponse = assertIsPendingJsonRpcResponse;
@@ -146,7 +155,9 @@ exports.isJsonRpcResponse = isJsonRpcResponse;
146
155
  * Defaults to {@link AssertionError}.
147
156
  * @throws If the given value is not a valid {@link JsonRpcResponse} object.
148
157
  */
149
- function assertIsJsonRpcResponse(value, ErrorWrapper) {
158
+ function assertIsJsonRpcResponse(value,
159
+ // eslint-disable-next-line @typescript-eslint/naming-convention
160
+ ErrorWrapper) {
150
161
  (0, assert_1.assertStruct)(value, exports.JsonRpcResponseStruct, 'Invalid JSON-RPC response', ErrorWrapper);
151
162
  }
152
163
  exports.assertIsJsonRpcResponse = assertIsJsonRpcResponse;
@@ -168,7 +179,9 @@ exports.isJsonRpcSuccess = isJsonRpcSuccess;
168
179
  * Defaults to {@link AssertionError}.
169
180
  * @throws If the given value is not a valid {@link JsonRpcSuccess} object.
170
181
  */
171
- function assertIsJsonRpcSuccess(value, ErrorWrapper) {
182
+ function assertIsJsonRpcSuccess(value,
183
+ // eslint-disable-next-line @typescript-eslint/naming-convention
184
+ ErrorWrapper) {
172
185
  (0, assert_1.assertStruct)(value, exports.JsonRpcSuccessStruct, 'Invalid JSON-RPC success response', ErrorWrapper);
173
186
  }
174
187
  exports.assertIsJsonRpcSuccess = assertIsJsonRpcSuccess;
@@ -190,7 +203,9 @@ exports.isJsonRpcFailure = isJsonRpcFailure;
190
203
  * Defaults to {@link AssertionError}.
191
204
  * @throws If the given value is not a valid {@link JsonRpcFailure} object.
192
205
  */
193
- function assertIsJsonRpcFailure(value, ErrorWrapper) {
206
+ function assertIsJsonRpcFailure(value,
207
+ // eslint-disable-next-line @typescript-eslint/naming-convention
208
+ ErrorWrapper) {
194
209
  (0, assert_1.assertStruct)(value, exports.JsonRpcFailureStruct, 'Invalid JSON-RPC failure response', ErrorWrapper);
195
210
  }
196
211
  exports.assertIsJsonRpcFailure = assertIsJsonRpcFailure;
@@ -212,7 +227,9 @@ exports.isJsonRpcError = isJsonRpcError;
212
227
  * Defaults to {@link AssertionError}.
213
228
  * @throws If the given value is not a valid {@link JsonRpcError} object.
214
229
  */
215
- function assertIsJsonRpcError(value, ErrorWrapper) {
230
+ function assertIsJsonRpcError(value,
231
+ // eslint-disable-next-line @typescript-eslint/naming-convention
232
+ ErrorWrapper) {
216
233
  (0, assert_1.assertStruct)(value, exports.JsonRpcErrorStruct, 'Invalid JSON-RPC error', ErrorWrapper);
217
234
  }
218
235
  exports.assertIsJsonRpcError = assertIsJsonRpcError;
package/dist/json.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"json.js","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":";;;AAAA,6CAgBqB;AACrB,iCAKgB;AAChB,qCAAmE;AAEtD,QAAA,UAAU,GAAG,IAAA,oBAAM,EAAO,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;IACvD,MAAM,CAAC,OAAO,CAAC,GAAG,sBAAsB,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACtD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC,CAAC;AAaH;;;;;;GAMG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,kBAAU,CAAC,CAAC;AAC/B,CAAC;AAFD,kCAEC;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,QAAA,kBAAkB,GAAG,IAAA,oBAAM,EAAC;IACvC,IAAI,EAA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AAO,CAAC,EAAE;YACV,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;SACnB;IACH,CAAC;IAED,OAAO,uBAAuB,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAAC;AAC9D,CAAC;AAjID,wDAiIC","sourcesContent":["import {\n array,\n define,\n Infer,\n integer,\n is,\n literal,\n nullable,\n number,\n object,\n omit,\n optional,\n string,\n Struct,\n union,\n unknown,\n} from 'superstruct';\nimport {\n calculateNumberSize,\n calculateStringSize,\n isPlainObject,\n JsonSize,\n} from './misc';\nimport { AssertionErrorConstructor, assertStruct } from './assert';\n\nexport const JsonStruct = define<Json>('Json', (value) => {\n const [isValid] = validateJsonAndGetSize(value, true);\n return isValid;\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 * 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 return is(value, JsonStruct);\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: optional(JsonStruct),\n stack: optional(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 = 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 * 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<JsonRpcParams> {\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 ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcNotification<JsonRpcParams> {\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(\n value: unknown,\n): value is JsonRpcRequest<JsonRpcParams> {\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 ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcRequest<JsonRpcParams> {\n assertStruct(\n value,\n JsonRpcRequestStruct,\n 'Invalid JSON-RPC request',\n ErrorWrapper,\n );\n}\n\nexport const PendingJsonRpcResponseStruct = object({\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 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 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 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 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 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\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 [false, 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 // 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,6CAiBqB;AAErB,qCAAmE;AACnE,iCAKgB;AAEH,QAAA,UAAU,GAAG,IAAA,oBAAM,EAAO,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;IACvD,MAAM,CAAC,OAAO,CAAC,GAAG,sBAAsB,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACtD,IAAI,CAAC,OAAO,EAAE;QACZ,OAAO,0CAA0C,CAAC;KACnD;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CAAC,CA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;wBACd,OAAO,CAAC,CAAC;qBACV;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;AAjID,wDAiIC","sourcesContent":["import {\n array,\n define,\n Infer,\n integer,\n is,\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';\n\nimport { AssertionErrorConstructor, assertStruct } from './assert';\nimport {\n calculateNumberSize,\n calculateStringSize,\n isPlainObject,\n JsonSize,\n} from './misc';\n\nexport const JsonStruct = define<Json>('Json', (value) => {\n const [isValid] = validateJsonAndGetSize(value, true);\n if (!isValid) {\n return 'Expected a valid JSON-serializable value';\n }\n return true;\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 * 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 return is(value, JsonStruct);\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: optional(JsonStruct),\n stack: optional(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 = optional(\n union([record(string(), JsonStruct), array(JsonStruct)]),\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>,\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 = JsonRpcParams> =\n InferWithParams<typeof JsonRpcRequestStruct, Params>;\n\nexport const JsonRpcNotificationStruct = omit(JsonRpcRequestStruct, ['id']);\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 = object({\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\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 [false, 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 // 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"]}
@@ -55,8 +55,8 @@ const a = { a: 0 };
55
55
  (0, tsd_1.expectNotAssignable)(a);
56
56
  // The Json type gets confused by classes. This class instance is valid Json,
57
57
  // but it's incompatible with the Json type.
58
- class B {
58
+ class Foo {
59
59
  }
60
- const b = new B();
61
- (0, tsd_1.expectNotAssignable)(b);
60
+ const foo = new Foo();
61
+ (0, tsd_1.expectNotAssignable)(foo);
62
62
  //# sourceMappingURL=json.test-d.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"json.test-d.js","sourceRoot":"","sources":["../src/json.test-d.ts"],"names":[],"mappings":";AAAA,mEAAmE;;AAEnE,6BAA4D;AAG5D,cAAc;AAEd,IAAA,sBAAgB,EAAO,IAAI,CAAC,CAAC;AAE7B,IAAA,sBAAgB,EAAO,KAAK,CAAC,CAAC;AAE9B,IAAA,sBAAgB,EAAO,EAAE,CAAC,CAAC;AAE3B,IAAA,sBAAgB,EAAO,CAAC,CAAC,CAAC;AAE1B,IAAA,sBAAgB,EAAO,EAAE,CAAC,CAAC;AAE3B,IAAA,sBAAgB,EAAO,EAAE,CAAC,CAAC;AAE3B,IAAA,sBAAgB,EAAO,CAAC,CAAC,CAAC,CAAC,CAAC;AAE5B,IAA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AAC,CAAC,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/consistent-type-definitions */\n\nimport { expectAssignable, expectNotAssignable } from 'tsd';\nimport type { Json } from '.';\n\n// Valid Json:\n\nexpectAssignable<Json>(null);\n\nexpectAssignable<Json>(false);\n\nexpectAssignable<Json>('');\n\nexpectAssignable<Json>(0);\n\nexpectAssignable<Json>([]);\n\nexpectAssignable<Json>({});\n\nexpectAssignable<Json>([0]);\n\nexpectAssignable<Json>({ a: 0 });\n\nexpectAssignable<Json>({ deeply: [{ nested: 1 }, 'mixed', 'types', 0] });\n\nexpectAssignable<Json>(['array', { nested: { mixed: true, types: null } }, 0]);\n\ntype JsonCompatibleType = {\n c: number;\n};\nconst jsonCompatibleType: JsonCompatibleType = { c: 0 };\nexpectAssignable<Json>(jsonCompatibleType);\n\n// Invalid Json:\n\nexpectNotAssignable<Json>(undefined);\n\nexpectNotAssignable<Json>(new Date());\n\nexpectNotAssignable<Json>(() => 0);\n\nexpectNotAssignable<Json>(new Set());\n\nexpectNotAssignable<Json>(new Map());\n\nexpectNotAssignable<Json>(Symbol('test'));\n\nexpectNotAssignable<Json>({ a: new Date() });\n\nexpectNotAssignable<Json>(5 as number | undefined);\n\ninterface InterfaceWithOptionalProperty {\n a?: number;\n}\nconst interfaceWithOptionalProperty: InterfaceWithOptionalProperty = { a: 0 };\nexpectNotAssignable<Json>(interfaceWithOptionalProperty);\n\ninterface InterfaceWithDate {\n a: Date;\n}\nconst interfaceWithDate: InterfaceWithDate = { a: new Date() };\nexpectNotAssignable<Json>(interfaceWithDate);\n\ninterface InterfaceWithOptionalDate {\n a?: Date;\n}\nconst interfaceWithOptionalDate: InterfaceWithOptionalDate = { a: new Date() };\nexpectNotAssignable<Json>(interfaceWithOptionalDate);\n\ninterface InterfaceWithUndefinedTypeUnion {\n a: number | undefined;\n}\nconst interfaceWithUndefinedTypeUnion: InterfaceWithUndefinedTypeUnion = {\n a: 0,\n};\nexpectNotAssignable<Json>(interfaceWithUndefinedTypeUnion);\n\ninterface InterfaceWithFunction {\n a: () => number;\n}\nconst interfaceWithFunction: InterfaceWithFunction = { a: () => 0 };\nexpectNotAssignable<Json>(interfaceWithFunction);\n\ntype TypeWithDate = {\n a: Date;\n};\nconst typeWithDate: TypeWithDate = { a: new Date() };\nexpectNotAssignable<Json>(typeWithDate);\n\ntype TypeWithOptionalDate = {\n a?: Date;\n};\nconst typeWithOptionalDate: TypeWithOptionalDate = { a: new Date() };\nexpectNotAssignable<Json>(typeWithOptionalDate);\n\ntype TypeWithUndefinedTypeUnion = {\n a: number | undefined;\n};\nconst typeWithUndefinedTypeUnion: TypeWithUndefinedTypeUnion = {\n a: 0,\n};\nexpectNotAssignable<Json>(typeWithUndefinedTypeUnion);\n\ntype TypeWithFunction = {\n a: () => number;\n};\nconst typeWithFunction: TypeWithFunction = { a: () => 0 };\nexpectNotAssignable<Json>(typeWithFunction);\n\ntype TypeWithOptionalProperty = {\n a?: number | undefined;\n};\nconst typeWithOptionalProperty: TypeWithOptionalProperty = { a: undefined };\nexpectNotAssignable<Json>(typeWithOptionalProperty);\n\n// Edge cases:\n\n// The Json type doesn't protect against the `any` type.\nexpectAssignable<Json>(null as any);\n\n// The Json type gets confused by interfaces. This interface is valid Json,\n// but it's incompatible with the Json type.\ninterface A {\n a: number;\n}\nconst a: A = { a: 0 };\nexpectNotAssignable<Json>(a);\n\n// The Json type gets confused by classes. This class instance is valid Json,\n// but it's incompatible with the Json type.\nclass B {\n a!: number;\n}\nconst b = new B();\nexpectNotAssignable<Json>(b);\n"]}
1
+ {"version":3,"file":"json.test-d.js","sourceRoot":"","sources":["../src/json.test-d.ts"],"names":[],"mappings":";AAAA,mEAAmE;;AAEnE,6BAA4D;AAI5D,cAAc;AAEd,IAAA,sBAAgB,EAAO,IAAI,CAAC,CAAC;AAE7B,IAAA,sBAAgB,EAAO,KAAK,CAAC,CAAC;AAE9B,IAAA,sBAAgB,EAAO,EAAE,CAAC,CAAC;AAE3B,IAAA,sBAAgB,EAA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AAC;AACtB,IAAA,yBAAmB,EAAO,CAAC,CAAC,CAAC;AAE7B,6EAA6E;AAC7E,4CAA4C;AAC5C,MAAM,GAAG;CAER;AACD,MAAM,GAAG,GAAG,IAAI,GAAG,EAAE,CAAC;AACtB,IAAA,yBAAmB,EAAO,GAAG,CAAC,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/consistent-type-definitions */\n\nimport { expectAssignable, expectNotAssignable } from 'tsd';\n\nimport type { Json } from '.';\n\n// Valid Json:\n\nexpectAssignable<Json>(null);\n\nexpectAssignable<Json>(false);\n\nexpectAssignable<Json>('');\n\nexpectAssignable<Json>(0);\n\nexpectAssignable<Json>([]);\n\nexpectAssignable<Json>({});\n\nexpectAssignable<Json>([0]);\n\nexpectAssignable<Json>({ a: 0 });\n\nexpectAssignable<Json>({ deeply: [{ nested: 1 }, 'mixed', 'types', 0] });\n\nexpectAssignable<Json>(['array', { nested: { mixed: true, types: null } }, 0]);\n\ntype JsonCompatibleType = {\n c: number;\n};\nconst jsonCompatibleType: JsonCompatibleType = { c: 0 };\nexpectAssignable<Json>(jsonCompatibleType);\n\n// Invalid Json:\n\nexpectNotAssignable<Json>(undefined);\n\nexpectNotAssignable<Json>(new Date());\n\nexpectNotAssignable<Json>(() => 0);\n\nexpectNotAssignable<Json>(new Set());\n\nexpectNotAssignable<Json>(new Map());\n\nexpectNotAssignable<Json>(Symbol('test'));\n\nexpectNotAssignable<Json>({ a: new Date() });\n\nexpectNotAssignable<Json>(5 as number | undefined);\n\ninterface InterfaceWithOptionalProperty {\n a?: number;\n}\nconst interfaceWithOptionalProperty: InterfaceWithOptionalProperty = { a: 0 };\nexpectNotAssignable<Json>(interfaceWithOptionalProperty);\n\ninterface InterfaceWithDate {\n a: Date;\n}\nconst interfaceWithDate: InterfaceWithDate = { a: new Date() };\nexpectNotAssignable<Json>(interfaceWithDate);\n\ninterface InterfaceWithOptionalDate {\n a?: Date;\n}\nconst interfaceWithOptionalDate: InterfaceWithOptionalDate = { a: new Date() };\nexpectNotAssignable<Json>(interfaceWithOptionalDate);\n\ninterface InterfaceWithUndefinedTypeUnion {\n a: number | undefined;\n}\nconst interfaceWithUndefinedTypeUnion: InterfaceWithUndefinedTypeUnion = {\n a: 0,\n};\nexpectNotAssignable<Json>(interfaceWithUndefinedTypeUnion);\n\ninterface InterfaceWithFunction {\n a: () => number;\n}\nconst interfaceWithFunction: InterfaceWithFunction = { a: () => 0 };\nexpectNotAssignable<Json>(interfaceWithFunction);\n\ntype TypeWithDate = {\n a: Date;\n};\nconst typeWithDate: TypeWithDate = { a: new Date() };\nexpectNotAssignable<Json>(typeWithDate);\n\ntype TypeWithOptionalDate = {\n a?: Date;\n};\nconst typeWithOptionalDate: TypeWithOptionalDate = { a: new Date() };\nexpectNotAssignable<Json>(typeWithOptionalDate);\n\ntype TypeWithUndefinedTypeUnion = {\n a: number | undefined;\n};\nconst typeWithUndefinedTypeUnion: TypeWithUndefinedTypeUnion = {\n a: 0,\n};\nexpectNotAssignable<Json>(typeWithUndefinedTypeUnion);\n\ntype TypeWithFunction = {\n a: () => number;\n};\nconst typeWithFunction: TypeWithFunction = { a: () => 0 };\nexpectNotAssignable<Json>(typeWithFunction);\n\ntype TypeWithOptionalProperty = {\n a?: number | undefined;\n};\nconst typeWithOptionalProperty: TypeWithOptionalProperty = { a: undefined };\nexpectNotAssignable<Json>(typeWithOptionalProperty);\n\n// Edge cases:\n\n// The Json type doesn't protect against the `any` type.\nexpectAssignable<Json>(null as any);\n\n// The Json type gets confused by interfaces. This interface is valid Json,\n// but it's incompatible with the Json type.\ninterface A {\n a: number;\n}\nconst a: A = { a: 0 };\nexpectNotAssignable<Json>(a);\n\n// The Json type gets confused by classes. This class instance is valid Json,\n// but it's incompatible with the Json type.\nclass Foo {\n a!: number;\n}\nconst foo = new Foo();\nexpectNotAssignable<Json>(foo);\n"]}
package/dist/number.js CHANGED
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.hexToBigInt = exports.hexToNumber = exports.bigIntToHex = exports.numberToHex = void 0;
4
- const hex_1 = require("./hex");
5
4
  const assert_1 = require("./assert");
5
+ const hex_1 = require("./hex");
6
6
  /**
7
7
  * Convert a number to a hexadecimal string. This verifies that the number is a
8
8
  * non-negative safe integer.
@@ -1 +1 @@
1
- {"version":3,"file":"number.js","sourceRoot":"","sources":["../src/number.ts"],"names":[],"mappings":";;;AAAA,+BAAiD;AACjD,qCAAkC;AAElC;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,WAAW,GAAG,CAAC,KAAa,EAAU,EAAE;IACnD,IAAA,eAAM,EAAC,OAAO,KAAK,KAAK,QAAQ,EAAE,yBAAyB,CAAC,CAAC;IAC7D,IAAA,eAAM,EAAC,KAAK,IAAI,CAAC,EAAE,sCAAsC,CAAC,CAAC;IAC3D,IAAA,eAAM,EACJ,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,EAC3B,yDAAyD,CAC1D,CAAC;IAEF,OAAO,IAAA,WAAK,EAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;AACnC,CAAC,CAAC;AATW,QAAA,WAAW,eAStB;AAEF;;;;;;;;;;;;;;;GAeG;AACI,MAAM,WAAW,GAAG,CAAC,KAAa,EAAU,EAAE;IACnD,IAAA,eAAM,EAAC,OAAO,KAAK,KAAK,QAAQ,EAAE,yBAAyB,CAAC,CAAC;IAC7D,IAAA,eAAM,EAAC,KAAK,IAAI,CAAC,EAAE,sCAAsC,CAAC,CAAC;IAE3D,OAAO,IAAA,WAAK,EAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;AACnC,CAAC,CAAC;AALW,QAAA,WAAW,eAKtB;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACI,MAAM,WAAW,GAAG,CAAC,KAAa,EAAU,EAAE;IACnD,IAAA,uBAAiB,EAAC,KAAK,CAAC,CAAC;IAEzB,2EAA2E;IAC3E,kEAAkE;IAClE,MAAM,WAAW,GAAG,QAAQ,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAExC,IAAA,eAAM,EACJ,MAAM,CAAC,aAAa,CAAC,WAAW,CAAC,EACjC,yDAAyD,CAC1D,CAAC;IAEF,OAAO,WAAW,CAAC;AACrB,CAAC,CAAC;AAbW,QAAA,WAAW,eAatB;AAEF;;;;;;;;;;;;;;;GAeG;AACI,MAAM,WAAW,GAAG,CAAC,KAAa,EAAU,EAAE;IACnD,IAAA,uBAAiB,EAAC,KAAK,CAAC,CAAC;IAEzB,2EAA2E;IAC3E,OAAO,MAAM,CAAC,IAAA,WAAK,EAAC,KAAK,CAAC,CAAC,CAAC;AAC9B,CAAC,CAAC;AALW,QAAA,WAAW,eAKtB","sourcesContent":["import { add0x, assertIsHexString } from './hex';\nimport { assert } from './assert';\n\n/**\n * Convert a number to a hexadecimal string. This verifies that the number is a\n * non-negative safe integer.\n *\n * To convert a `bigint` to a hexadecimal string instead, use\n * {@link bigIntToHex}.\n *\n * @example\n * ```typescript\n * numberToHex(0); // '0x0'\n * numberToHex(1); // '0x1'\n * numberToHex(16); // '0x10'\n * ```\n * @param value - The number to convert to a hexadecimal string.\n * @returns The hexadecimal string, with the \"0x\"-prefix.\n * @throws If the number is not a non-negative safe integer.\n */\nexport const numberToHex = (value: number): string => {\n assert(typeof value === 'number', 'Value must be a number.');\n assert(value >= 0, 'Value must be a non-negative number.');\n assert(\n Number.isSafeInteger(value),\n 'Value is not a safe integer. Use `bigIntToHex` instead.',\n );\n\n return add0x(value.toString(16));\n};\n\n/**\n * Convert a `bigint` to a hexadecimal string. This verifies that the `bigint`\n * is a non-negative integer.\n *\n * To convert a number to a hexadecimal string instead, use {@link numberToHex}.\n *\n * @example\n * ```typescript\n * bigIntToHex(0n); // '0x0'\n * bigIntToHex(1n); // '0x1'\n * bigIntToHex(16n); // '0x10'\n * ```\n * @param value - The `bigint` to convert to a hexadecimal string.\n * @returns The hexadecimal string, with the \"0x\"-prefix.\n * @throws If the `bigint` is not a non-negative integer.\n */\nexport const bigIntToHex = (value: bigint): string => {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(value >= 0, 'Value must be a non-negative bigint.');\n\n return add0x(value.toString(16));\n};\n\n/**\n * Convert a hexadecimal string to a number. This verifies that the string is a\n * valid hex string, and that the resulting number is a safe integer. Both\n * \"0x\"-prefixed and unprefixed strings are supported.\n *\n * To convert a hexadecimal string to a `bigint` instead, use\n * {@link hexToBigInt}.\n *\n * @example\n * ```typescript\n * hexToNumber('0x0'); // 0\n * hexToNumber('0x1'); // 1\n * hexToNumber('0x10'); // 16\n * ```\n * @param value - The hexadecimal string to convert to a number.\n * @returns The number.\n * @throws If the value is not a valid hexadecimal string, or if the resulting\n * number is not a safe integer.\n */\nexport const hexToNumber = (value: string): number => {\n assertIsHexString(value);\n\n // `parseInt` accepts values without the \"0x\"-prefix, whereas `Number` does\n // not. Using this is slightly faster than `Number(add0x(value))`.\n const numberValue = parseInt(value, 16);\n\n assert(\n Number.isSafeInteger(numberValue),\n 'Value is not a safe integer. Use `hexToBigInt` instead.',\n );\n\n return numberValue;\n};\n\n/**\n * Convert a hexadecimal string to a `bigint`. This verifies that the string is\n * a valid hex string. Both \"0x\"-prefixed and unprefixed strings are supported.\n *\n * To convert a hexadecimal string to a number instead, use {@link hexToNumber}.\n *\n * @example\n * ```typescript\n * hexToBigInt('0x0'); // 0n\n * hexToBigInt('0x1'); // 1n\n * hexToBigInt('0x10'); // 16n\n * ```\n * @param value - The hexadecimal string to convert to a `bigint`.\n * @returns The `bigint`.\n * @throws If the value is not a valid hexadecimal string.\n */\nexport const hexToBigInt = (value: string): bigint => {\n assertIsHexString(value);\n\n // The `BigInt` constructor requires the \"0x\"-prefix to parse a hex string.\n return BigInt(add0x(value));\n};\n"]}
1
+ {"version":3,"file":"number.js","sourceRoot":"","sources":["../src/number.ts"],"names":[],"mappings":";;;AAAA,qCAAkC;AAClC,+BAAiD;AAEjD;;;;;;;;;;;;;;;;GAg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AAK,CAAC,CAAC;IAEzB,2EAA2E;IAC3E,OAAO,MAAM,CAAC,IAAA,WAAK,EAAC,KAAK,CAAC,CAAC,CAAC;AAC9B,CAAC,CAAC;AALW,QAAA,WAAW,eAKtB","sourcesContent":["import { assert } from './assert';\nimport { add0x, assertIsHexString } from './hex';\n\n/**\n * Convert a number to a hexadecimal string. This verifies that the number is a\n * non-negative safe integer.\n *\n * To convert a `bigint` to a hexadecimal string instead, use\n * {@link bigIntToHex}.\n *\n * @example\n * ```typescript\n * numberToHex(0); // '0x0'\n * numberToHex(1); // '0x1'\n * numberToHex(16); // '0x10'\n * ```\n * @param value - The number to convert to a hexadecimal string.\n * @returns The hexadecimal string, with the \"0x\"-prefix.\n * @throws If the number is not a non-negative safe integer.\n */\nexport const numberToHex = (value: number): string => {\n assert(typeof value === 'number', 'Value must be a number.');\n assert(value >= 0, 'Value must be a non-negative number.');\n assert(\n Number.isSafeInteger(value),\n 'Value is not a safe integer. Use `bigIntToHex` instead.',\n );\n\n return add0x(value.toString(16));\n};\n\n/**\n * Convert a `bigint` to a hexadecimal string. This verifies that the `bigint`\n * is a non-negative integer.\n *\n * To convert a number to a hexadecimal string instead, use {@link numberToHex}.\n *\n * @example\n * ```typescript\n * bigIntToHex(0n); // '0x0'\n * bigIntToHex(1n); // '0x1'\n * bigIntToHex(16n); // '0x10'\n * ```\n * @param value - The `bigint` to convert to a hexadecimal string.\n * @returns The hexadecimal string, with the \"0x\"-prefix.\n * @throws If the `bigint` is not a non-negative integer.\n */\nexport const bigIntToHex = (value: bigint): string => {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(value >= 0, 'Value must be a non-negative bigint.');\n\n return add0x(value.toString(16));\n};\n\n/**\n * Convert a hexadecimal string to a number. This verifies that the string is a\n * valid hex string, and that the resulting number is a safe integer. Both\n * \"0x\"-prefixed and unprefixed strings are supported.\n *\n * To convert a hexadecimal string to a `bigint` instead, use\n * {@link hexToBigInt}.\n *\n * @example\n * ```typescript\n * hexToNumber('0x0'); // 0\n * hexToNumber('0x1'); // 1\n * hexToNumber('0x10'); // 16\n * ```\n * @param value - The hexadecimal string to convert to a number.\n * @returns The number.\n * @throws If the value is not a valid hexadecimal string, or if the resulting\n * number is not a safe integer.\n */\nexport const hexToNumber = (value: string): number => {\n assertIsHexString(value);\n\n // `parseInt` accepts values without the \"0x\"-prefix, whereas `Number` does\n // not. Using this is slightly faster than `Number(add0x(value))`.\n const numberValue = parseInt(value, 16);\n\n assert(\n Number.isSafeInteger(numberValue),\n 'Value is not a safe integer. Use `hexToBigInt` instead.',\n );\n\n return numberValue;\n};\n\n/**\n * Convert a hexadecimal string to a `bigint`. This verifies that the string is\n * a valid hex string. Both \"0x\"-prefixed and unprefixed strings are supported.\n *\n * To convert a hexadecimal string to a number instead, use {@link hexToNumber}.\n *\n * @example\n * ```typescript\n * hexToBigInt('0x0'); // 0n\n * hexToBigInt('0x1'); // 1n\n * hexToBigInt('0x10'); // 16n\n * ```\n * @param value - The hexadecimal string to convert to a `bigint`.\n * @returns The `bigint`.\n * @throws If the value is not a valid hexadecimal string.\n */\nexport const hexToBigInt = (value: string): bigint => {\n assertIsHexString(value);\n\n // The `BigInt` constructor requires the \"0x\"-prefix to parse a hex string.\n return BigInt(add0x(value));\n};\n"]}
@@ -0,0 +1,5 @@
1
+ declare const brand: unique symbol;
2
+ export declare type Opaque<Base, Brand extends symbol> = Base & {
3
+ [brand]: Brand;
4
+ };
5
+ export {};
package/dist/opaque.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=opaque.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opaque.js","sourceRoot":"","sources":["../src/opaque.ts"],"names":[],"mappings":"","sourcesContent":["// We use a symbol property name instead of { _type: Brand }, because that would show up in IDE suggestions,\n// while internal symbols do not.\ndeclare const brand: unique symbol;\nexport type Opaque<Base, Brand extends symbol> = Base & { [brand]: Brand };\n"]}
@@ -0,0 +1,100 @@
1
+ import { Struct } from 'superstruct';
2
+ import { Opaque } from './opaque';
3
+ /**
4
+ * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for SemVer ranges.
5
+ *
6
+ * @example Use {@link assertIsSemVerRange} and {@link isValidSemVerRange} to cast to proper type.
7
+ * ```typescript
8
+ * const unsafeRange: string = dataFromUser();
9
+ * assertIsSemVerRange(unsafeRange);
10
+ * unsafeRange
11
+ * // ^? SemVerRange
12
+ * ```
13
+ * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.
14
+ * ```typescript
15
+ * const unsafeRange: string = dataFromUser();
16
+ * unsafeRange as SemVerRange;
17
+ * // ^? SemVerRange
18
+ * ```
19
+ * @see {@link assertIsSemVerRange}
20
+ * @see {@link isValidSemVerRange}
21
+ */
22
+ export declare type SemVerRange = Opaque<string, typeof semVerRange>;
23
+ declare const semVerRange: unique symbol;
24
+ /**
25
+ * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for singular SemVer version.
26
+ *
27
+ * @example Use {@link assertIsSemVerVersion} and {@link isValidSemVerVersion} to cast to proper type.
28
+ * ```typescript
29
+ * const unsafeVersion: string = dataFromUser();
30
+ * assertIsSemVerVersion(unsafeRange);
31
+ * unsafeVersion
32
+ * // ^? SemVerVersion
33
+ * ```
34
+ * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.
35
+ * ```typescript
36
+ * const unsafeVersion: string = dataFromUser();
37
+ * unsafeRange as SemVerVersion;
38
+ * // ^? SemVerVersion
39
+ * ```
40
+ * @see {@link assertIsSemVerVersion}
41
+ * @see {@link isValidSemVerVersion}
42
+ */
43
+ export declare type SemVerVersion = Opaque<string, typeof semVerVersion>;
44
+ declare const semVerVersion: unique symbol;
45
+ /**
46
+ * A struct for validating a version string.
47
+ */
48
+ export declare const VersionStruct: Struct<SemVerVersion, null>;
49
+ export declare const VersionRangeStruct: Struct<SemVerRange, null>;
50
+ /**
51
+ * Checks whether a SemVer version is valid.
52
+ *
53
+ * @param version - A potential version.
54
+ * @returns `true` if the version is valid, and `false` otherwise.
55
+ */
56
+ export declare function isValidSemVerVersion(version: unknown): version is SemVerVersion;
57
+ /**
58
+ * Checks whether a SemVer version range is valid.
59
+ *
60
+ * @param versionRange - A potential version range.
61
+ * @returns `true` if the version range is valid, and `false` otherwise.
62
+ */
63
+ export declare function isValidSemVerRange(versionRange: unknown): versionRange is SemVerRange;
64
+ /**
65
+ * Asserts that a value is a valid concrete SemVer version.
66
+ *
67
+ * @param version - A potential SemVer concrete version.
68
+ */
69
+ export declare function assertIsSemVerVersion(version: unknown): asserts version is SemVerVersion;
70
+ /**
71
+ * Asserts that a value is a valid SemVer range.
72
+ *
73
+ * @param range - A potential SemVer range.
74
+ */
75
+ export declare function assertIsSemVerRange(range: unknown): asserts range is SemVerRange;
76
+ /**
77
+ * Checks whether a SemVer version is greater than another.
78
+ *
79
+ * @param version1 - The left-hand version.
80
+ * @param version2 - The right-hand version.
81
+ * @returns `version1 > version2`.
82
+ */
83
+ export declare function gtVersion(version1: SemVerVersion, version2: SemVerVersion): boolean;
84
+ /**
85
+ * Checks whether a SemVer version is greater than all possibilities in a range.
86
+ *
87
+ * @param version - A SemvVer version.
88
+ * @param range - The range to check against.
89
+ * @returns `version > range`.
90
+ */
91
+ export declare function gtRange(version: SemVerVersion, range: SemVerRange): boolean;
92
+ /**
93
+ * Returns whether a SemVer version satisfies a SemVer range.
94
+ *
95
+ * @param version - The SemVer version to check.
96
+ * @param versionRange - The SemVer version range to check against.
97
+ * @returns Whether the version satisfied the version range.
98
+ */
99
+ export declare function satisfiesVersionRange(version: SemVerVersion, versionRange: SemVerRange): boolean;
100
+ export {};
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.satisfiesVersionRange = exports.gtRange = exports.gtVersion = exports.assertIsSemVerRange = exports.assertIsSemVerVersion = exports.isValidSemVerRange = exports.isValidSemVerVersion = exports.VersionRangeStruct = exports.VersionStruct = void 0;
4
+ const semver_1 = require("semver");
5
+ const superstruct_1 = require("superstruct");
6
+ const assert_1 = require("./assert");
7
+ /**
8
+ * A struct for validating a version string.
9
+ */
10
+ exports.VersionStruct = (0, superstruct_1.refine)((0, superstruct_1.string)(), 'Version', (value) => {
11
+ if ((0, semver_1.valid)(value) === null) {
12
+ return `Expected SemVer version, got "${value}"`;
13
+ }
14
+ return true;
15
+ });
16
+ exports.VersionRangeStruct = (0, superstruct_1.refine)((0, superstruct_1.string)(), 'Version range', (value) => {
17
+ if ((0, semver_1.validRange)(value) === null) {
18
+ return `Expected SemVer range, got "${value}"`;
19
+ }
20
+ return true;
21
+ });
22
+ /**
23
+ * Checks whether a SemVer version is valid.
24
+ *
25
+ * @param version - A potential version.
26
+ * @returns `true` if the version is valid, and `false` otherwise.
27
+ */
28
+ function isValidSemVerVersion(version) {
29
+ return (0, superstruct_1.is)(version, exports.VersionStruct);
30
+ }
31
+ exports.isValidSemVerVersion = isValidSemVerVersion;
32
+ /**
33
+ * Checks whether a SemVer version range is valid.
34
+ *
35
+ * @param versionRange - A potential version range.
36
+ * @returns `true` if the version range is valid, and `false` otherwise.
37
+ */
38
+ function isValidSemVerRange(versionRange) {
39
+ return (0, superstruct_1.is)(versionRange, exports.VersionRangeStruct);
40
+ }
41
+ exports.isValidSemVerRange = isValidSemVerRange;
42
+ /**
43
+ * Asserts that a value is a valid concrete SemVer version.
44
+ *
45
+ * @param version - A potential SemVer concrete version.
46
+ */
47
+ function assertIsSemVerVersion(version) {
48
+ (0, assert_1.assertStruct)(version, exports.VersionStruct);
49
+ }
50
+ exports.assertIsSemVerVersion = assertIsSemVerVersion;
51
+ /**
52
+ * Asserts that a value is a valid SemVer range.
53
+ *
54
+ * @param range - A potential SemVer range.
55
+ */
56
+ function assertIsSemVerRange(range) {
57
+ (0, assert_1.assertStruct)(range, exports.VersionRangeStruct);
58
+ }
59
+ exports.assertIsSemVerRange = assertIsSemVerRange;
60
+ /**
61
+ * Checks whether a SemVer version is greater than another.
62
+ *
63
+ * @param version1 - The left-hand version.
64
+ * @param version2 - The right-hand version.
65
+ * @returns `version1 > version2`.
66
+ */
67
+ function gtVersion(version1, version2) {
68
+ return (0, semver_1.gt)(version1, version2);
69
+ }
70
+ exports.gtVersion = gtVersion;
71
+ /**
72
+ * Checks whether a SemVer version is greater than all possibilities in a range.
73
+ *
74
+ * @param version - A SemvVer version.
75
+ * @param range - The range to check against.
76
+ * @returns `version > range`.
77
+ */
78
+ function gtRange(version, range) {
79
+ return (0, semver_1.gtr)(version, range);
80
+ }
81
+ exports.gtRange = gtRange;
82
+ /**
83
+ * Returns whether a SemVer version satisfies a SemVer range.
84
+ *
85
+ * @param version - The SemVer version to check.
86
+ * @param versionRange - The SemVer version range to check against.
87
+ * @returns Whether the version satisfied the version range.
88
+ */
89
+ function satisfiesVersionRange(version, versionRange) {
90
+ return (0, semver_1.satisfies)(version, versionRange, {
91
+ includePrerelease: true,
92
+ });
93
+ }
94
+ exports.satisfiesVersionRange = satisfiesVersionRange;
95
+ //# sourceMappingURL=versions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"versions.js","sourceRoot":"","sources":["../src/versions.ts"],"names":[],"mappings":";;;AAAA,mCAMgB;AAChB,6CAAyD;AAEzD,qCAAwC;AA+CxC;;GAEG;AACU,QAAA,aAAa,GAAG,IAAA,oBAAM,EACjC,IAAA,oBAAM,GAA4C,EAClD,SAAS,EACT,CAAC,KAAK,EAAE,EAAE;IACR,IAAI,IAAA,cAAkB,EAAC,KAAK,CAAC,KAAK,IAAI,EAAE;QACtC,OAAO,iCAAiC,KAAK,GAAG,CAAC;KAClD;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CACF,CAAC;AAEW,QAAA,kBAAkB,GAAG,IAAA,oBAAM,EACtC,IAAA,oBAAM,GAA0C,EAChD,eAAe,EACf,CAAC,KAAK,EAAE,EAAE;IACR,IAAI,IAAA,mBAAgB,EAAC,KAAK,CAAC,KAAK,IAAI,EAAE;QACpC,OAAO,+BAA+B,KAAK,GAAG,CAAC;KAChD;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CACF,CAAC;AAEF;;;;;GAKG;AACH,SAAgB,oBAAoB,CAClC,OAAgB;IAEhB,OAAO,IAAA,gBAAE,EAAC,OAAO,EAAE,qBAAa,CAAC,CAAC;AACpC,CAAC;AAJD,oDAIC;AAED;;;;;GAKG;AACH,SAAgB,kBAAkB,CAChC,YAAqB;IAErB,OAAO,IAAA,gBAAE,EAAC,YAAY,EAAE,0BAAkB,CAAC,CAAC;AAC9C,CAAC;AAJD,gDAIC;AAED;;;;GAIG;AACH,SAAgB,qBAAqB,CACnC,OAAgB;IAEhB,IAAA,qBAAY,EAAC,OAAO,EAAE,qBAAa,CAAC,CAAC;AACvC,CAAC;AAJD,sDAIC;AAED;;;;GAIG;AACH,SAAgB,mBAAmB,CACjC,KAAc;IAEd,IAAA,qBAAY,EAAC,KAAK,EAAE,0BAAkB,CAAC,CAAC;AAC1C,CAAC;AAJD,kDAIC;AAED;;;;;;GAMG;AACH,SAAgB,SAAS,CACvB,QAAuB,EACvB,QAAuB;IAEvB,OAAO,IAAA,WAAQ,EAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;AACtC,CAAC;AALD,8BAKC;AAED;;;;;;GAMG;AACH,SAAgB,OAAO,CAAC,OAAsB,EAAE,KAAkB;IAChE,OAAO,IAAA,YAAS,EAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AACnC,CAAC;AAFD,0BAEC;AAED;;;;;;GAMG;AACH,SAAgB,qBAAqB,CACnC,OAAsB,EACtB,YAAyB;IAEzB,OAAO,IAAA,kBAAe,EAAC,OAAO,EAAE,YAAY,EAAE;QAC5C,iBAAiB,EAAE,IAAI;KACxB,CAAC,CAAC;AACL,CAAC;AAPD,sDAOC","sourcesContent":["import {\n gt as gtSemver,\n gtr as gtrSemver,\n satisfies as satisfiesSemver,\n valid as validSemVerVersion,\n validRange as validSemVerRange,\n} from 'semver';\nimport { is, refine, string, Struct } from 'superstruct';\n\nimport { assertStruct } from './assert';\nimport { Opaque } from './opaque';\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for SemVer ranges.\n *\n * @example Use {@link assertIsSemVerRange} and {@link isValidSemVerRange} to cast to proper type.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * assertIsSemVerRange(unsafeRange);\n * unsafeRange\n * // ^? SemVerRange\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * unsafeRange as SemVerRange;\n * // ^? SemVerRange\n * ```\n * @see {@link assertIsSemVerRange}\n * @see {@link isValidSemVerRange}\n */\nexport type SemVerRange = Opaque<string, typeof semVerRange>;\ndeclare const semVerRange: unique symbol;\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for singular SemVer version.\n *\n * @example Use {@link assertIsSemVerVersion} and {@link isValidSemVerVersion} to cast to proper type.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * assertIsSemVerVersion(unsafeRange);\n * unsafeVersion\n * // ^? SemVerVersion\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * unsafeRange as SemVerVersion;\n * // ^? SemVerVersion\n * ```\n * @see {@link assertIsSemVerVersion}\n * @see {@link isValidSemVerVersion}\n */\nexport type SemVerVersion = Opaque<string, typeof semVerVersion>;\ndeclare const semVerVersion: unique symbol;\n\n/**\n * A struct for validating a version string.\n */\nexport const VersionStruct = refine<SemVerVersion, null>(\n string() as unknown as Struct<SemVerVersion, null>,\n 'Version',\n (value) => {\n if (validSemVerVersion(value) === null) {\n return `Expected SemVer version, got \"${value}\"`;\n }\n return true;\n },\n);\n\nexport const VersionRangeStruct = refine<SemVerRange, null>(\n string() as unknown as Struct<SemVerRange, null>,\n 'Version range',\n (value) => {\n if (validSemVerRange(value) === null) {\n return `Expected SemVer range, got \"${value}\"`;\n }\n return true;\n },\n);\n\n/**\n * Checks whether a SemVer version is valid.\n *\n * @param version - A potential version.\n * @returns `true` if the version is valid, and `false` otherwise.\n */\nexport function isValidSemVerVersion(\n version: unknown,\n): version is SemVerVersion {\n return is(version, VersionStruct);\n}\n\n/**\n * Checks whether a SemVer version range is valid.\n *\n * @param versionRange - A potential version range.\n * @returns `true` if the version range is valid, and `false` otherwise.\n */\nexport function isValidSemVerRange(\n versionRange: unknown,\n): versionRange is SemVerRange {\n return is(versionRange, VersionRangeStruct);\n}\n\n/**\n * Asserts that a value is a valid concrete SemVer version.\n *\n * @param version - A potential SemVer concrete version.\n */\nexport function assertIsSemVerVersion(\n version: unknown,\n): asserts version is SemVerVersion {\n assertStruct(version, VersionStruct);\n}\n\n/**\n * Asserts that a value is a valid SemVer range.\n *\n * @param range - A potential SemVer range.\n */\nexport function assertIsSemVerRange(\n range: unknown,\n): asserts range is SemVerRange {\n assertStruct(range, VersionRangeStruct);\n}\n\n/**\n * Checks whether a SemVer version is greater than another.\n *\n * @param version1 - The left-hand version.\n * @param version2 - The right-hand version.\n * @returns `version1 > version2`.\n */\nexport function gtVersion(\n version1: SemVerVersion,\n version2: SemVerVersion,\n): boolean {\n return gtSemver(version1, version2);\n}\n\n/**\n * Checks whether a SemVer version is greater than all possibilities in a range.\n *\n * @param version - A SemvVer version.\n * @param range - The range to check against.\n * @returns `version > range`.\n */\nexport function gtRange(version: SemVerVersion, range: SemVerRange): boolean {\n return gtrSemver(version, range);\n}\n\n/**\n * Returns whether a SemVer version satisfies a SemVer range.\n *\n * @param version - The SemVer version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns Whether the version satisfied the version range.\n */\nexport function satisfiesVersionRange(\n version: SemVerVersion,\n versionRange: SemVerRange,\n): boolean {\n return satisfiesSemver(version, versionRange, {\n includePrerelease: true,\n });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/utils",
3
- "version": "3.3.0",
3
+ "version": "3.4.0",
4
4
  "description": "Various JavaScript/TypeScript utilities of wide relevance to the MetaMask codebase.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -15,13 +15,12 @@
15
15
  "scripts": {
16
16
  "build": "tsc --project tsconfig.build.json",
17
17
  "build:clean": "rimraf dist && yarn build",
18
- "docs": "typedoc",
19
- "docs:publish": "typedoc --cleanOutputDir false --gitRevision \"v$(jq -r .version < ./package.json)\"",
18
+ "build:docs": "typedoc",
20
19
  "lint": "yarn lint:eslint && yarn lint:misc --check",
21
20
  "lint:eslint": "eslint . --cache --ext js,ts",
22
21
  "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write",
23
- "lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' '**/*.yml' --ignore-path .gitignore",
24
- "prepublishOnly": "yarn build:clean && yarn lint && yarn test",
22
+ "lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' '**/*.yml' '!.yarnrc.yml' --ignore-path .gitignore --no-error-on-unmatched-pattern",
23
+ "prepack": "./scripts/prepack.sh",
25
24
  "test": "yarn test:source && yarn test:types",
26
25
  "test:source": "jest",
27
26
  "test:types": "tsd",
@@ -33,35 +32,36 @@
33
32
  "dependencies": {
34
33
  "@types/debug": "^4.1.7",
35
34
  "debug": "^4.3.4",
35
+ "semver": "^7.3.8",
36
36
  "superstruct": "^0.16.7"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@lavamoat/allow-scripts": "^2.0.3",
40
40
  "@metamask/auto-changelog": "^2.3.0",
41
- "@metamask/eslint-config": "^9.0.0",
42
- "@metamask/eslint-config-jest": "^9.0.0",
43
- "@metamask/eslint-config-nodejs": "^9.0.0",
44
- "@metamask/eslint-config-typescript": "^9.0.1",
41
+ "@metamask/eslint-config": "^11.0.1",
42
+ "@metamask/eslint-config-jest": "^11.0.0",
43
+ "@metamask/eslint-config-nodejs": "^11.0.1",
44
+ "@metamask/eslint-config-typescript": "^11.0.0",
45
45
  "@types/jest": "^28.1.7",
46
- "@typescript-eslint/eslint-plugin": "^4.21.0",
47
- "@typescript-eslint/parser": "^4.21.0",
48
- "eslint": "^7.23.0",
49
- "eslint-config-prettier": "^8.1.0",
50
- "eslint-plugin-import": "^2.22.1",
51
- "eslint-plugin-jest": "^24.3.4",
52
- "eslint-plugin-jsdoc": "^36.1.0",
46
+ "@typescript-eslint/eslint-plugin": "^5.42.1",
47
+ "@typescript-eslint/parser": "^5.42.1",
48
+ "eslint": "^8.27.0",
49
+ "eslint-config-prettier": "^8.5.0",
50
+ "eslint-plugin-import": "^2.26.0",
51
+ "eslint-plugin-jest": "^27.1.5",
52
+ "eslint-plugin-jsdoc": "^39.6.2",
53
53
  "eslint-plugin-node": "^11.1.0",
54
- "eslint-plugin-prettier": "^3.3.1",
55
- "jest": "^28.1.0",
54
+ "eslint-plugin-prettier": "^4.2.1",
55
+ "jest": "^29.2.2",
56
56
  "json-bigint": "^1.0.0",
57
- "prettier": "^2.2.1",
57
+ "prettier": "^2.7.1",
58
58
  "prettier-plugin-packagejson": "^2.2.11",
59
59
  "rimraf": "^3.0.2",
60
60
  "stdio-mock": "^1.2.0",
61
- "ts-jest": "^28.0.8",
61
+ "ts-jest": "^29.0.3",
62
62
  "tsd": "^0.24.1",
63
63
  "typedoc": "^0.23.10",
64
- "typescript": "~4.7.4"
64
+ "typescript": "~4.8.4"
65
65
  },
66
66
  "packageManager": "yarn@3.2.3",
67
67
  "engines": {