@metamask/utils 3.0.3 → 3.2.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.d.ts CHANGED
@@ -33,8 +33,8 @@ export declare const JsonRpcIdStruct: Struct<string | number | null, null>;
33
33
  export declare type JsonRpcId = Infer<typeof JsonRpcIdStruct>;
34
34
  export declare const JsonRpcErrorStruct: Struct<{
35
35
  code: number;
36
- message: string;
37
36
  data: unknown;
37
+ message: string;
38
38
  stack?: string | undefined;
39
39
  }, {
40
40
  code: Struct<number, null>;
@@ -42,16 +42,24 @@ export declare const JsonRpcErrorStruct: Struct<{
42
42
  data: Struct<unknown, null>;
43
43
  stack: Struct<string | undefined, null>;
44
44
  }>;
45
+ /**
46
+ * Mark a certain key of a type as optional.
47
+ */
48
+ export declare type OptionalField<Type extends Record<string, unknown>, Key extends keyof Type> = Omit<Type, Key> & Partial<Pick<Type, Key>>;
45
49
  /**
46
50
  * A JSON-RPC error object.
51
+ *
52
+ * Note that TypeScript infers `unknown | undefined` as `unknown`, meaning that
53
+ * the `data` field is not optional. To make it optional, we use the
54
+ * `OptionalField` helper, to explicitly make it optional.
47
55
  */
48
- export declare type JsonRpcError = Infer<typeof JsonRpcErrorStruct>;
56
+ export declare type JsonRpcError = OptionalField<Infer<typeof JsonRpcErrorStruct>, 'data'>;
49
57
  export declare const JsonRpcParamsStruct: Struct<unknown[] | Record<string, unknown> | undefined, null>;
50
58
  export declare type JsonRpcParams = Infer<typeof JsonRpcParamsStruct>;
51
59
  export declare const JsonRpcRequestStruct: Struct<{
52
60
  id: string | number | null;
53
- jsonrpc: "2.0";
54
61
  method: string;
62
+ jsonrpc: "2.0";
55
63
  params?: unknown[] | Record<string, unknown> | undefined;
56
64
  }, {
57
65
  id: Struct<string | number | null, null>;
@@ -69,8 +77,8 @@ export declare type InferWithParams<Type extends Struct<any, unknown>, Params ex
69
77
  */
70
78
  export declare type JsonRpcRequest<Params extends JsonRpcParams> = InferWithParams<typeof JsonRpcRequestStruct, Params>;
71
79
  export declare const JsonRpcNotificationStruct: Struct<{
72
- jsonrpc: "2.0";
73
80
  method: string;
81
+ jsonrpc: "2.0";
74
82
  params?: unknown[] | Record<string, unknown> | undefined;
75
83
  }, Omit<{
76
84
  id: Struct<string | number | null, null>;
@@ -83,34 +91,67 @@ export declare const JsonRpcNotificationStruct: Struct<{
83
91
  */
84
92
  export declare type JsonRpcNotification<Params extends JsonRpcParams> = InferWithParams<typeof JsonRpcNotificationStruct, Params>;
85
93
  /**
86
- * Type guard to narrow a JSON-RPC request or notification object to a
87
- * notification.
94
+ * Type guard to narrow a {@link JsonRpcRequest} or
95
+ * {@link JsonRpcNotification} object to a {@link JsonRpcNotification}.
88
96
  *
89
97
  * @param requestOrNotification - The JSON-RPC request or notification to check.
90
98
  * @returns Whether the specified JSON-RPC message is a notification.
91
99
  */
92
100
  export declare function isJsonRpcNotification(requestOrNotification: unknown): requestOrNotification is JsonRpcNotification<JsonRpcParams>;
93
101
  /**
94
- * Assertion type guard to narrow a JSON-RPC request or notification object to a
95
- * notification.
102
+ * Assertion type guard to narrow a {@link JsonRpcRequest} or
103
+ * {@link JsonRpcNotification} object to a {@link JsonRpcNotification}.
96
104
  *
97
105
  * @param requestOrNotification - The JSON-RPC request or notification to check.
98
106
  */
99
107
  export declare function assertIsJsonRpcNotification(requestOrNotification: unknown): asserts requestOrNotification is JsonRpcNotification<JsonRpcParams>;
100
108
  /**
101
- * Type guard to narrow a JSON-RPC request or notification object to a request.
109
+ * Type guard to narrow a {@link JsonRpcRequest} or @link JsonRpcNotification}
110
+ * object to a {@link JsonRpcRequest}.
102
111
  *
103
112
  * @param requestOrNotification - The JSON-RPC request or notification to check.
104
113
  * @returns Whether the specified JSON-RPC message is a request.
105
114
  */
106
115
  export declare function isJsonRpcRequest(requestOrNotification: unknown): requestOrNotification is JsonRpcRequest<JsonRpcParams>;
107
116
  /**
108
- * Assertion type guard to narrow a JSON-RPC request or notification object to a
109
- * request.
117
+ * Assertion type guard to narrow a {@link JsonRpcRequest} or
118
+ * {@link JsonRpcNotification} object to a {@link JsonRpcRequest}.
110
119
  *
111
120
  * @param requestOrNotification - The JSON-RPC request or notification to check.
112
121
  */
113
122
  export declare function assertIsJsonRpcRequest(requestOrNotification: unknown): asserts requestOrNotification is JsonRpcRequest<JsonRpcParams>;
123
+ export declare const PendingJsonRpcResponseStruct: Struct<{
124
+ id: string | number | null;
125
+ jsonrpc: "2.0";
126
+ result: unknown;
127
+ error?: {
128
+ code: number;
129
+ data: unknown;
130
+ message: string;
131
+ stack?: string | undefined;
132
+ } | undefined;
133
+ }, {
134
+ id: Struct<string | number | null, null>;
135
+ jsonrpc: Struct<"2.0", "2.0">;
136
+ result: Struct<unknown, null>;
137
+ error: Struct<{
138
+ code: number;
139
+ data: unknown;
140
+ message: string;
141
+ stack?: string | undefined;
142
+ } | undefined, {
143
+ code: Struct<number, null>;
144
+ message: Struct<string, null>;
145
+ data: Struct<unknown, null>;
146
+ stack: Struct<string | undefined, null>;
147
+ }>;
148
+ }>;
149
+ /**
150
+ * A JSON-RPC response object that has not yet been resolved.
151
+ */
152
+ export declare type PendingJsonRpcResponse<Result extends Json> = Omit<Infer<typeof PendingJsonRpcResponseStruct>, 'result'> & {
153
+ result?: Result;
154
+ };
114
155
  export declare const JsonRpcSuccessStruct: Struct<{
115
156
  id: string | number | null;
116
157
  jsonrpc: "2.0";
@@ -127,28 +168,13 @@ export declare type JsonRpcSuccess<Result extends Json> = Omit<Infer<typeof Json
127
168
  result: Result;
128
169
  };
129
170
  export declare const JsonRpcFailureStruct: Struct<{
171
+ error: JsonRpcError;
130
172
  id: string | number | null;
131
173
  jsonrpc: "2.0";
132
- error: {
133
- code: number;
134
- message: string;
135
- data: unknown;
136
- stack?: string | undefined;
137
- };
138
174
  }, {
139
175
  id: Struct<string | number | null, null>;
140
176
  jsonrpc: Struct<"2.0", "2.0">;
141
- error: Struct<{
142
- code: number;
143
- message: string;
144
- data: unknown;
145
- stack?: string | undefined;
146
- }, {
147
- code: Struct<number, null>;
148
- message: Struct<string, null>;
149
- data: Struct<unknown, null>;
150
- stack: Struct<string | undefined, null>;
151
- }>;
177
+ error: Struct<JsonRpcError, unknown>;
152
178
  }>;
153
179
  /**
154
180
  * A failed JSON-RPC response object.
@@ -159,14 +185,9 @@ export declare const JsonRpcResponseStruct: Struct<{
159
185
  jsonrpc: "2.0";
160
186
  result: Json;
161
187
  } | {
188
+ error: JsonRpcError;
162
189
  id: string | number | null;
163
190
  jsonrpc: "2.0";
164
- error: {
165
- code: number;
166
- message: string;
167
- data: unknown;
168
- stack?: string | undefined;
169
- };
170
191
  }, null>;
171
192
  /**
172
193
  * A JSON-RPC response object. Must be checked to determine whether it's a
@@ -176,33 +197,52 @@ export declare const JsonRpcResponseStruct: Struct<{
176
197
  */
177
198
  export declare type JsonRpcResponse<Result extends Json> = JsonRpcSuccess<Result> | JsonRpcFailure;
178
199
  /**
179
- * Type guard to check if a value is a JsonRpcResponse.
200
+ * Type guard to check whether specified JSON-RPC response is a
201
+ * {@link PendingJsonRpcResponse}.
202
+ *
203
+ * @param response - The JSON-RPC response to check.
204
+ * @returns Whether the specified JSON-RPC response is pending.
205
+ */
206
+ export declare function isPendingJsonRpcResponse(response: unknown): response is PendingJsonRpcResponse<Json>;
207
+ /**
208
+ * Assert that the specified JSON-RPC response is a
209
+ * {@link PendingJsonRpcResponse}.
210
+ *
211
+ * @param response - The JSON-RPC response to check.
212
+ * @throws If the specified JSON-RPC response is not pending.
213
+ */
214
+ export declare function assertIsPendingJsonRpcResponse(response: unknown): asserts response is PendingJsonRpcResponse<Json>;
215
+ /**
216
+ * Type guard to check if a value is a {@link JsonRpcResponse}.
180
217
  *
181
218
  * @param response - The object to check.
182
219
  * @returns Whether the object is a JsonRpcResponse.
183
220
  */
184
221
  export declare function isJsonRpcResponse(response: unknown): response is JsonRpcResponse<Json>;
185
222
  /**
186
- * Type assertion to check if a value is a JsonRpcResponse.
223
+ * Type assertion to check if a value is a {@link JsonRpcResponse}.
187
224
  *
188
225
  * @param response - The response to check.
189
226
  */
190
227
  export declare function assertIsJsonRpcResponse(response: unknown): asserts response is JsonRpcResponse<Json>;
191
228
  /**
192
- * Type guard to narrow a JsonRpcResponse object to a success (or failure).
229
+ * Type guard to narrow a {@link JsonRpcResponse} object to a success
230
+ * (or failure).
193
231
  *
194
232
  * @param response - The response object to check.
195
233
  * @returns Whether the response object is a success.
196
234
  */
197
235
  export declare function isJsonRpcSuccess(response: unknown): response is JsonRpcSuccess<Json>;
198
236
  /**
199
- * Type assertion to narrow a JsonRpcResponse object to a success (or failure).
237
+ * Type assertion to narrow a {@link JsonRpcResponse} object to a success
238
+ * (or failure).
200
239
  *
201
240
  * @param response - The response object to check.
202
241
  */
203
242
  export declare function assertIsJsonRpcSuccess(response: unknown): asserts response is JsonRpcSuccess<Json>;
204
243
  /**
205
- * Type guard to narrow a JsonRpcResponse object to a failure (or success).
244
+ * Type guard to narrow a {@link JsonRpcResponse} object to a failure
245
+ * (or success).
206
246
  *
207
247
  * @param response - The response object to check.
208
248
  * @returns Whether the response object is a failure, i.e. has an `error`
@@ -210,7 +250,8 @@ export declare function assertIsJsonRpcSuccess(response: unknown): asserts respo
210
250
  */
211
251
  export declare function isJsonRpcFailure(response: unknown): response is JsonRpcFailure;
212
252
  /**
213
- * Type assertion to narrow a JsonRpcResponse object to a failure (or success).
253
+ * Type assertion to narrow a {@link JsonRpcResponse} object to a failure
254
+ * (or success).
214
255
  *
215
256
  * @param response - The response object to check.
216
257
  */
package/dist/json.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.validateJsonAndGetSize = exports.getJsonRpcIdValidator = exports.assertIsJsonRpcFailure = exports.isJsonRpcFailure = exports.assertIsJsonRpcSuccess = exports.isJsonRpcSuccess = exports.assertIsJsonRpcResponse = exports.isJsonRpcResponse = exports.JsonRpcResponseStruct = exports.JsonRpcFailureStruct = exports.JsonRpcSuccessStruct = 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;
6
+ exports.validateJsonAndGetSize = exports.getJsonRpcIdValidator = 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;
7
7
  const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
8
8
  const superstruct_1 = require("superstruct");
9
9
  const misc_1 = require("./misc");
@@ -62,8 +62,8 @@ exports.JsonRpcRequestStruct = (0, superstruct_1.object)({
62
62
  });
63
63
  exports.JsonRpcNotificationStruct = (0, superstruct_1.omit)(exports.JsonRpcRequestStruct, ['id']);
64
64
  /**
65
- * Type guard to narrow a JSON-RPC request or notification object to a
66
- * notification.
65
+ * Type guard to narrow a {@link JsonRpcRequest} or
66
+ * {@link JsonRpcNotification} object to a {@link JsonRpcNotification}.
67
67
  *
68
68
  * @param requestOrNotification - The JSON-RPC request or notification to check.
69
69
  * @returns Whether the specified JSON-RPC message is a notification.
@@ -73,8 +73,8 @@ function isJsonRpcNotification(requestOrNotification) {
73
73
  }
74
74
  exports.isJsonRpcNotification = isJsonRpcNotification;
75
75
  /**
76
- * Assertion type guard to narrow a JSON-RPC request or notification object to a
77
- * notification.
76
+ * Assertion type guard to narrow a {@link JsonRpcRequest} or
77
+ * {@link JsonRpcNotification} object to a {@link JsonRpcNotification}.
78
78
  *
79
79
  * @param requestOrNotification - The JSON-RPC request or notification to check.
80
80
  */
@@ -89,7 +89,8 @@ function assertIsJsonRpcNotification(requestOrNotification) {
89
89
  }
90
90
  exports.assertIsJsonRpcNotification = assertIsJsonRpcNotification;
91
91
  /**
92
- * Type guard to narrow a JSON-RPC request or notification object to a request.
92
+ * Type guard to narrow a {@link JsonRpcRequest} or @link JsonRpcNotification}
93
+ * object to a {@link JsonRpcRequest}.
93
94
  *
94
95
  * @param requestOrNotification - The JSON-RPC request or notification to check.
95
96
  * @returns Whether the specified JSON-RPC message is a request.
@@ -99,8 +100,8 @@ function isJsonRpcRequest(requestOrNotification) {
99
100
  }
100
101
  exports.isJsonRpcRequest = isJsonRpcRequest;
101
102
  /**
102
- * Assertion type guard to narrow a JSON-RPC request or notification object to a
103
- * request.
103
+ * Assertion type guard to narrow a {@link JsonRpcRequest} or
104
+ * {@link JsonRpcNotification} object to a {@link JsonRpcRequest}.
104
105
  *
105
106
  * @param requestOrNotification - The JSON-RPC request or notification to check.
106
107
  */
@@ -114,6 +115,12 @@ function assertIsJsonRpcRequest(requestOrNotification) {
114
115
  }
115
116
  }
116
117
  exports.assertIsJsonRpcRequest = assertIsJsonRpcRequest;
118
+ exports.PendingJsonRpcResponseStruct = (0, superstruct_1.object)({
119
+ id: exports.JsonRpcIdStruct,
120
+ jsonrpc: exports.JsonRpcVersionStruct,
121
+ result: (0, superstruct_1.optional)((0, superstruct_1.unknown)()),
122
+ error: (0, superstruct_1.optional)(exports.JsonRpcErrorStruct),
123
+ });
117
124
  exports.JsonRpcSuccessStruct = (0, superstruct_1.object)({
118
125
  id: exports.JsonRpcIdStruct,
119
126
  jsonrpc: exports.JsonRpcVersionStruct,
@@ -129,7 +136,35 @@ exports.JsonRpcResponseStruct = (0, superstruct_1.union)([
129
136
  exports.JsonRpcFailureStruct,
130
137
  ]);
131
138
  /**
132
- * Type guard to check if a value is a JsonRpcResponse.
139
+ * Type guard to check whether specified JSON-RPC response is a
140
+ * {@link PendingJsonRpcResponse}.
141
+ *
142
+ * @param response - The JSON-RPC response to check.
143
+ * @returns Whether the specified JSON-RPC response is pending.
144
+ */
145
+ function isPendingJsonRpcResponse(response) {
146
+ return (0, superstruct_1.is)(response, exports.PendingJsonRpcResponseStruct);
147
+ }
148
+ exports.isPendingJsonRpcResponse = isPendingJsonRpcResponse;
149
+ /**
150
+ * Assert that the specified JSON-RPC response is a
151
+ * {@link PendingJsonRpcResponse}.
152
+ *
153
+ * @param response - The JSON-RPC response to check.
154
+ * @throws If the specified JSON-RPC response is not pending.
155
+ */
156
+ function assertIsPendingJsonRpcResponse(response) {
157
+ try {
158
+ (0, superstruct_1.assert)(response, exports.PendingJsonRpcResponseStruct);
159
+ }
160
+ catch (error) {
161
+ const message = isErrorWithMessage(error) ? error.message : error;
162
+ throw new Error(`Not a pending JSON-RPC response: ${message}.`);
163
+ }
164
+ }
165
+ exports.assertIsPendingJsonRpcResponse = assertIsPendingJsonRpcResponse;
166
+ /**
167
+ * Type guard to check if a value is a {@link JsonRpcResponse}.
133
168
  *
134
169
  * @param response - The object to check.
135
170
  * @returns Whether the object is a JsonRpcResponse.
@@ -139,7 +174,7 @@ function isJsonRpcResponse(response) {
139
174
  }
140
175
  exports.isJsonRpcResponse = isJsonRpcResponse;
141
176
  /**
142
- * Type assertion to check if a value is a JsonRpcResponse.
177
+ * Type assertion to check if a value is a {@link JsonRpcResponse}.
143
178
  *
144
179
  * @param response - The response to check.
145
180
  */
@@ -154,7 +189,8 @@ function assertIsJsonRpcResponse(response) {
154
189
  }
155
190
  exports.assertIsJsonRpcResponse = assertIsJsonRpcResponse;
156
191
  /**
157
- * Type guard to narrow a JsonRpcResponse object to a success (or failure).
192
+ * Type guard to narrow a {@link JsonRpcResponse} object to a success
193
+ * (or failure).
158
194
  *
159
195
  * @param response - The response object to check.
160
196
  * @returns Whether the response object is a success.
@@ -164,7 +200,8 @@ function isJsonRpcSuccess(response) {
164
200
  }
165
201
  exports.isJsonRpcSuccess = isJsonRpcSuccess;
166
202
  /**
167
- * Type assertion to narrow a JsonRpcResponse object to a success (or failure).
203
+ * Type assertion to narrow a {@link JsonRpcResponse} object to a success
204
+ * (or failure).
168
205
  *
169
206
  * @param response - The response object to check.
170
207
  */
@@ -179,7 +216,8 @@ function assertIsJsonRpcSuccess(response) {
179
216
  }
180
217
  exports.assertIsJsonRpcSuccess = assertIsJsonRpcSuccess;
181
218
  /**
182
- * Type guard to narrow a JsonRpcResponse object to a failure (or success).
219
+ * Type guard to narrow a {@link JsonRpcResponse} object to a failure
220
+ * (or success).
183
221
  *
184
222
  * @param response - The response object to check.
185
223
  * @returns Whether the response object is a failure, i.e. has an `error`
@@ -190,7 +228,8 @@ function isJsonRpcFailure(response) {
190
228
  }
191
229
  exports.isJsonRpcFailure = isJsonRpcFailure;
192
230
  /**
193
- * Type assertion to narrow a JsonRpcResponse object to a failure (or success).
231
+ * Type assertion to narrow a {@link JsonRpcResponse} object to a failure
232
+ * (or success).
194
233
  *
195
234
  * @param response - The response object to check.
196
235
  */
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,Q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AAC,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"]}
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;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eAAQ,CAAC,IAAI,CAAC;qBACtB;oBAED,2DAA2D;oBAC3D,mDAAmD;oBACnD,IAAI,IAAI,KAAK,CAAC,EAAE;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 * 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 * Type guard to narrow a {@link JsonRpcRequest} or\n * {@link JsonRpcNotification} object to a {@link JsonRpcNotification}.\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 {@link JsonRpcRequest} or\n * {@link JsonRpcNotification} object to a {@link JsonRpcNotification}.\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 {@link JsonRpcRequest} or @link JsonRpcNotification}\n * object to a {@link JsonRpcRequest}.\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 {@link JsonRpcRequest} or\n * {@link JsonRpcNotification} object to a {@link JsonRpcRequest}.\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 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 specified JSON-RPC response is a\n * {@link PendingJsonRpcResponse}.\n *\n * @param response - The JSON-RPC response to check.\n * @throws If the specified JSON-RPC response is not pending.\n */\nexport function assertIsPendingJsonRpcResponse(\n response: unknown,\n): asserts response is PendingJsonRpcResponse<Json> {\n try {\n assert(response, PendingJsonRpcResponseStruct);\n } catch (error) {\n const message = isErrorWithMessage(error) ? error.message : error;\n throw new Error(`Not a pending JSON-RPC response: ${message}.`);\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 * Type assertion to check if a value is a {@link 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 {@link JsonRpcResponse} object to a success\n * (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 {@link JsonRpcResponse} object to a success\n * (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 {@link JsonRpcResponse} object to a failure\n * (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 {@link JsonRpcResponse} object to a failure\n * (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"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ /* eslint-disable @typescript-eslint/consistent-type-definitions */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const tsd_1 = require("tsd");
5
+ // Valid Json:
6
+ (0, tsd_1.expectAssignable)(null);
7
+ (0, tsd_1.expectAssignable)(false);
8
+ (0, tsd_1.expectAssignable)('');
9
+ (0, tsd_1.expectAssignable)(0);
10
+ (0, tsd_1.expectAssignable)([]);
11
+ (0, tsd_1.expectAssignable)({});
12
+ (0, tsd_1.expectAssignable)([0]);
13
+ (0, tsd_1.expectAssignable)({ a: 0 });
14
+ (0, tsd_1.expectAssignable)({ deeply: [{ nested: 1 }, 'mixed', 'types', 0] });
15
+ (0, tsd_1.expectAssignable)(['array', { nested: { mixed: true, types: null } }, 0]);
16
+ const jsonCompatibleType = { c: 0 };
17
+ (0, tsd_1.expectAssignable)(jsonCompatibleType);
18
+ // Invalid Json:
19
+ (0, tsd_1.expectNotAssignable)(undefined);
20
+ (0, tsd_1.expectNotAssignable)(new Date());
21
+ (0, tsd_1.expectNotAssignable)(() => 0);
22
+ (0, tsd_1.expectNotAssignable)(new Set());
23
+ (0, tsd_1.expectNotAssignable)(new Map());
24
+ (0, tsd_1.expectNotAssignable)(Symbol('test'));
25
+ (0, tsd_1.expectNotAssignable)({ a: new Date() });
26
+ (0, tsd_1.expectNotAssignable)(5);
27
+ const interfaceWithOptionalProperty = { a: 0 };
28
+ (0, tsd_1.expectNotAssignable)(interfaceWithOptionalProperty);
29
+ const interfaceWithDate = { a: new Date() };
30
+ (0, tsd_1.expectNotAssignable)(interfaceWithDate);
31
+ const interfaceWithOptionalDate = { a: new Date() };
32
+ (0, tsd_1.expectNotAssignable)(interfaceWithOptionalDate);
33
+ const interfaceWithUndefinedTypeUnion = {
34
+ a: 0,
35
+ };
36
+ (0, tsd_1.expectNotAssignable)(interfaceWithUndefinedTypeUnion);
37
+ const interfaceWithFunction = { a: () => 0 };
38
+ (0, tsd_1.expectNotAssignable)(interfaceWithFunction);
39
+ const typeWithDate = { a: new Date() };
40
+ (0, tsd_1.expectNotAssignable)(typeWithDate);
41
+ const typeWithOptionalDate = { a: new Date() };
42
+ (0, tsd_1.expectNotAssignable)(typeWithOptionalDate);
43
+ const typeWithUndefinedTypeUnion = {
44
+ a: 0,
45
+ };
46
+ (0, tsd_1.expectNotAssignable)(typeWithUndefinedTypeUnion);
47
+ const typeWithFunction = { a: () => 0 };
48
+ (0, tsd_1.expectNotAssignable)(typeWithFunction);
49
+ const typeWithOptionalProperty = { a: undefined };
50
+ (0, tsd_1.expectNotAssignable)(typeWithOptionalProperty);
51
+ // Edge cases:
52
+ // The Json type doesn't protect against the `any` type.
53
+ (0, tsd_1.expectAssignable)(null);
54
+ const a = { a: 0 };
55
+ (0, tsd_1.expectNotAssignable)(a);
56
+ // The Json type gets confused by classes. This class instance is valid Json,
57
+ // but it's incompatible with the Json type.
58
+ class B {
59
+ }
60
+ const b = new B();
61
+ (0, tsd_1.expectNotAssignable)(b);
62
+ //# sourceMappingURL=json.test-d.js.map
@@ -0,0 +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,CA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EN;AACD,MAAM,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC;AAClB,IAAA,yBAAmB,EAAO,CAAC,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"]}
package/dist/misc.js CHANGED
@@ -64,6 +64,7 @@ var JsonSize;
64
64
  JsonSize[JsonSize["False"] = 5] = "False";
65
65
  JsonSize[JsonSize["Quote"] = 1] = "Quote";
66
66
  JsonSize[JsonSize["Colon"] = 1] = "Colon";
67
+ // eslint-disable-next-line @typescript-eslint/no-shadow
67
68
  JsonSize[JsonSize["Date"] = 24] = "Date";
68
69
  })(JsonSize = exports.JsonSize || (exports.JsonSize = {}));
69
70
  /**
package/dist/misc.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"misc.js","sourceRoot":"","sources":["../src/misc.ts"],"names":[],"mappings":";AAAA,EAAE;AACF,QAAQ;AACR,EAAE;;;AAsCF,EAAE;AACF,cAAc;AACd,EAAE;AAEF;;;;;;GAMG;AACH,SAAgB,eAAe,CAC7B,KAAgB;IAEhB,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AAClD,CAAC;AAJD,0CAIC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,KAAc;IAC9C,OAAO,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC;AAC/C,CAAC;AAFD,8CAEC;AAED;;;;;;GAMG;AACH,SAAgB,QAAQ,CAAC,KAAc;IACrC,OAAO,OAAO,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAFD,4BAEC;AAED,EAAE;AACF,0BAA0B;AAC1B,EAAE;AAEF;;;;;;;GAOG;AACI,MAAM,WAAW,GAAG,CACzB,MAAqB,EACrB,IAA8B,EACrB,EAAE,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAH1C,QAAA,WAAW,eAG+B;AAIvD;;GAEG;AACH,IAAY,QASX;AATD,WAAY,QAAQ;IAClB,uCAAQ,CAAA;IACR,yCAAS,CAAA;IACT,6CAAW,CAAA;IACX,uCAAQ,CAAA;IACR,yCAAS,CAAA;IACT,yCAAS,CAAA;IACT,yCAAS,CAAA;IACT,wCAAS,CAAA;AACX,CAAC,EATW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QASnB;AAED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CAAC;AACjC,CAAC;AAFD,kDAEC","sourcesContent":["//\n// Types\n//\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template ObjectValue - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n ObjectValue extends Record<string, unknown>,\n TargetKey extends keyof ObjectValue\n> = {\n -readonly [Key in keyof Pick<ObjectValue, TargetKey>]: ObjectValue[Key];\n} &\n {\n [Key in keyof Omit<ObjectValue, TargetKey>]: ObjectValue[Key];\n };\n\n/**\n * Useful for representing some value that _might_ be present and / or complete.\n *\n * @template Value - The value that might be present or complete.\n */\nexport type PartialOrAbsent<Value> = Partial<Value> | null | undefined;\n\n/**\n * Like {@link Array}, but always non-empty.\n *\n * @template Element - The non-empty array member type.\n */\nexport type NonEmptyArray<Element> = [Element, ...Element[]];\n\n/**\n * A JavaScript object that is not `null`, a function, or an array. The object\n * can still be an instance of a class.\n */\nexport type RuntimeObject = Record<number | string | symbol, unknown>;\n\n//\n// Type Guards\n//\n\n/**\n * A {@link NonEmptyArray} type guard.\n *\n * @template Element - The non-empty array member type.\n * @param value - The value to check.\n * @returns Whether the value is a non-empty array.\n */\nexport function isNonEmptyArray<Element>(\n value: Element[],\n): value is NonEmptyArray<Element> {\n return Array.isArray(value) && value.length > 0;\n}\n\n/**\n * Type guard for \"nullishness\".\n *\n * @param value - Any value.\n * @returns `true` if the value is null or undefined, `false` otherwise.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/**\n * A type guard for {@link RuntimeObject}.\n *\n * @param value - The value to check.\n * @returns Whether the specified value has a runtime type of `object` and is\n * neither `null` nor an `Array`.\n */\nexport function isObject(value: unknown): value is RuntimeObject {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n//\n// Other utility functions\n//\n\n/**\n * An alias for {@link Object.hasOwnProperty}.\n *\n * @param object - The object to check.\n * @param name - The property name to check for.\n * @returns Whether the specified object has an own property with the specified\n * name, regardless of whether it is enumerable or not.\n */\nexport const hasProperty = (\n object: RuntimeObject,\n name: string | number | symbol,\n): boolean => Object.hasOwnProperty.call(object, name);\n\nexport type PlainObject = Record<number | string | symbol, unknown>;\n\n/**\n * Predefined sizes (in Bytes) of specific parts of JSON structure.\n */\nexport enum JsonSize {\n Null = 4,\n Comma = 1,\n Wrapper = 1,\n True = 4,\n False = 5,\n Quote = 1,\n Colon = 1,\n Date = 24,\n}\n\n/**\n * Regular expression with pattern matching for (special) escaped characters.\n */\nexport const ESCAPE_CHARACTERS_REGEXP = /\"|\\\\|\\n|\\r|\\t/gu;\n\n/**\n * Check if the value is plain object.\n *\n * @param value - Value to be checked.\n * @returns True if an object is the plain JavaScript object,\n * false if the object is not plain (e.g. function).\n */\nexport function isPlainObject(value: unknown): value is PlainObject {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n try {\n let proto = value;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n\n return Object.getPrototypeOf(value) === proto;\n } catch (_) {\n return false;\n }\n}\n\n/**\n * Check if character is ASCII.\n *\n * @param character - Character.\n * @returns True if a character code is ASCII, false if not.\n */\nexport function isASCII(character: string) {\n return character.charCodeAt(0) <= 127;\n}\n\n/**\n * Calculate string size.\n *\n * @param value - String value to calculate size.\n * @returns Number of bytes used to store whole string value.\n */\nexport function calculateStringSize(value: string): number {\n const size = value.split('').reduce((total, character) => {\n if (isASCII(character)) {\n return total + 1;\n }\n return total + 2;\n }, 0);\n\n // Also detect characters that need backslash escape\n return size + (value.match(ESCAPE_CHARACTERS_REGEXP) ?? []).length;\n}\n\n/**\n * Calculate size of a number ofter JSON serialization.\n *\n * @param value - Number value to calculate size.\n * @returns Number of bytes used to store whole number in JSON.\n */\nexport function calculateNumberSize(value: number): number {\n return value.toString().length;\n}\n"]}
1
+ {"version":3,"file":"misc.js","sourceRoot":"","sources":["../src/misc.ts"],"names":[],"mappings":";AAAA,EAAE;AACF,QAAQ;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KACd;IAED,IAAI;QACF,IAAI,KAAK,GAAG,KAAK,CAAC;QAClB,OAAO,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,KAAK,IAAI,EAAE;YAC5C,KAAK,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;SACtC;QAED,OAAO,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,KAAK,KAAK,CAAC;KAC/C;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAfD,sCAeC;AAED;;;;;GAKG;AACH,SAAgB,OAAO,CAAC,SAAiB;IACvC,OAAO,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC;AACxC,CAAC;AAFD,0BAEC;AAED;;;;;GAKG;AACH,SAAgB,mBAAmB,CAAC,KAAa;;IAC/C,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE;QACvD,IAAI,OAAO,CAAC,SAAS,CAAC,EAAE;YACtB,OAAO,KAAK,GAAG,CAAC,CAAC;SAClB;QACD,OAAO,KAAK,GAAG,CAAC,CAAC;IACnB,CAAC,EAAE,CAAC,CAAC,CAAC;IAEN,oDAAoD;IACpD,OAAO,IAAI,GAAG,CAAC,MAAA,KAAK,CAAC,KAAK,CAAC,gCAAwB,CAAC,mCAAI,EAAE,CAAC,CAAC,MAAM,CAAC;AACrE,CAAC;AAVD,kDAUC;AAED;;;;;GAKG;AACH,SAAgB,mBAAmB,CAAC,KAAa;IAC/C,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC,MAAM,CAAC;AACjC,CAAC;AAFD,kDAEC","sourcesContent":["//\n// Types\n//\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template ObjectValue - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n ObjectValue extends Record<string, unknown>,\n TargetKey extends keyof ObjectValue,\n> = {\n -readonly [Key in keyof Pick<ObjectValue, TargetKey>]: ObjectValue[Key];\n} & {\n [Key in keyof Omit<ObjectValue, TargetKey>]: ObjectValue[Key];\n};\n\n/**\n * Useful for representing some value that _might_ be present and / or complete.\n *\n * @template Value - The value that might be present or complete.\n */\nexport type PartialOrAbsent<Value> = Partial<Value> | null | undefined;\n\n/**\n * Like {@link Array}, but always non-empty.\n *\n * @template Element - The non-empty array member type.\n */\nexport type NonEmptyArray<Element> = [Element, ...Element[]];\n\n/**\n * A JavaScript object that is not `null`, a function, or an array. The object\n * can still be an instance of a class.\n */\nexport type RuntimeObject = Record<number | string | symbol, unknown>;\n\n//\n// Type Guards\n//\n\n/**\n * A {@link NonEmptyArray} type guard.\n *\n * @template Element - The non-empty array member type.\n * @param value - The value to check.\n * @returns Whether the value is a non-empty array.\n */\nexport function isNonEmptyArray<Element>(\n value: Element[],\n): value is NonEmptyArray<Element> {\n return Array.isArray(value) && value.length > 0;\n}\n\n/**\n * Type guard for \"nullishness\".\n *\n * @param value - Any value.\n * @returns `true` if the value is null or undefined, `false` otherwise.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/**\n * A type guard for {@link RuntimeObject}.\n *\n * @param value - The value to check.\n * @returns Whether the specified value has a runtime type of `object` and is\n * neither `null` nor an `Array`.\n */\nexport function isObject(value: unknown): value is RuntimeObject {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n//\n// Other utility functions\n//\n\n/**\n * An alias for {@link Object.hasOwnProperty}.\n *\n * @param object - The object to check.\n * @param name - The property name to check for.\n * @returns Whether the specified object has an own property with the specified\n * name, regardless of whether it is enumerable or not.\n */\nexport const hasProperty = (\n object: RuntimeObject,\n name: string | number | symbol,\n): boolean => Object.hasOwnProperty.call(object, name);\n\nexport type PlainObject = Record<number | string | symbol, unknown>;\n\n/**\n * Predefined sizes (in Bytes) of specific parts of JSON structure.\n */\nexport enum JsonSize {\n Null = 4,\n Comma = 1,\n Wrapper = 1,\n True = 4,\n False = 5,\n Quote = 1,\n Colon = 1,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n Date = 24,\n}\n\n/**\n * Regular expression with pattern matching for (special) escaped characters.\n */\nexport const ESCAPE_CHARACTERS_REGEXP = /\"|\\\\|\\n|\\r|\\t/gu;\n\n/**\n * Check if the value is plain object.\n *\n * @param value - Value to be checked.\n * @returns True if an object is the plain JavaScript object,\n * false if the object is not plain (e.g. function).\n */\nexport function isPlainObject(value: unknown): value is PlainObject {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n try {\n let proto = value;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n\n return Object.getPrototypeOf(value) === proto;\n } catch (_) {\n return false;\n }\n}\n\n/**\n * Check if character is ASCII.\n *\n * @param character - Character.\n * @returns True if a character code is ASCII, false if not.\n */\nexport function isASCII(character: string) {\n return character.charCodeAt(0) <= 127;\n}\n\n/**\n * Calculate string size.\n *\n * @param value - String value to calculate size.\n * @returns Number of bytes used to store whole string value.\n */\nexport function calculateStringSize(value: string): number {\n const size = value.split('').reduce((total, character) => {\n if (isASCII(character)) {\n return total + 1;\n }\n return total + 2;\n }, 0);\n\n // Also detect characters that need backslash escape\n return size + (value.match(ESCAPE_CHARACTERS_REGEXP) ?? []).length;\n}\n\n/**\n * Calculate size of a number ofter JSON serialization.\n *\n * @param value - Number value to calculate size.\n * @returns Number of bytes used to store whole number in JSON.\n */\nexport function calculateNumberSize(value: number): number {\n return value.toString().length;\n}\n"]}