@metamask-previews/json-rpc-engine 10.1.1-preview-2e88eaea → 10.1.1-preview-b289ac1c
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2 -3
- package/dist/asV2Middleware.cjs +8 -3
- package/dist/asV2Middleware.cjs.map +1 -1
- package/dist/asV2Middleware.d.cts +1 -1
- package/dist/asV2Middleware.d.cts.map +1 -1
- package/dist/asV2Middleware.d.mts +1 -1
- package/dist/asV2Middleware.d.mts.map +1 -1
- package/dist/asV2Middleware.mjs +9 -4
- package/dist/asV2Middleware.mjs.map +1 -1
- package/dist/v2/JsonRpcEngineV2.cjs.map +1 -1
- package/dist/v2/JsonRpcEngineV2.d.cts +11 -1
- package/dist/v2/JsonRpcEngineV2.d.cts.map +1 -1
- package/dist/v2/JsonRpcEngineV2.d.mts +11 -1
- package/dist/v2/JsonRpcEngineV2.d.mts.map +1 -1
- package/dist/v2/JsonRpcEngineV2.mjs.map +1 -1
- package/dist/v2/JsonRpcServer.cjs.map +1 -1
- package/dist/v2/JsonRpcServer.d.cts +3 -3
- package/dist/v2/JsonRpcServer.d.cts.map +1 -1
- package/dist/v2/JsonRpcServer.d.mts +3 -3
- package/dist/v2/JsonRpcServer.d.mts.map +1 -1
- package/dist/v2/JsonRpcServer.mjs.map +1 -1
- package/dist/v2/MiddlewareContext.cjs.map +1 -1
- package/dist/v2/MiddlewareContext.d.cts +3 -0
- package/dist/v2/MiddlewareContext.d.cts.map +1 -1
- package/dist/v2/MiddlewareContext.d.mts +3 -0
- package/dist/v2/MiddlewareContext.d.mts.map +1 -1
- package/dist/v2/MiddlewareContext.mjs.map +1 -1
- package/dist/v2/compatibility-utils.cjs +3 -3
- package/dist/v2/compatibility-utils.cjs.map +1 -1
- package/dist/v2/compatibility-utils.d.cts +1 -1
- package/dist/v2/compatibility-utils.d.mts +1 -1
- package/dist/v2/compatibility-utils.mjs +1 -1
- package/dist/v2/compatibility-utils.mjs.map +1 -1
- package/dist/v2/index.cjs.map +1 -1
- package/dist/v2/index.d.cts +2 -2
- package/dist/v2/index.d.cts.map +1 -1
- package/dist/v2/index.d.mts +2 -2
- package/dist/v2/index.d.mts.map +1 -1
- package/dist/v2/index.mjs.map +1 -1
- package/package.json +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,9 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
9
9
|
|
|
10
10
|
### Added
|
|
11
11
|
|
|
12
|
-
- `JsonRpcEngineV2` ([#6176](https://github.com/MetaMask/core/pull/6176), [#6971](https://github.com/MetaMask/core/pull/6971), [#6975](https://github.com/MetaMask/core/pull/6975), [#6990](https://github.com/MetaMask/core/pull/6990), [#6991](https://github.com/MetaMask/core/pull/6991), [#7032](https://github.com/MetaMask/core/pull/7032))
|
|
13
|
-
- This is a complete rewrite of `JsonRpcEngine`, intended to replace the original implementation.
|
|
14
|
-
See the readme for details.
|
|
12
|
+
- Add `JsonRpcEngineV2` ([#6176](https://github.com/MetaMask/core/pull/6176), [#6971](https://github.com/MetaMask/core/pull/6971), [#6975](https://github.com/MetaMask/core/pull/6975), [#6990](https://github.com/MetaMask/core/pull/6990), [#6991](https://github.com/MetaMask/core/pull/6991), [#7001](https://github.com/MetaMask/core/pull/7001), [#7032](https://github.com/MetaMask/core/pull/7032))
|
|
13
|
+
- This is a complete rewrite of `JsonRpcEngine`, intended to replace the original implementation. See the readme for details.
|
|
15
14
|
|
|
16
15
|
## [10.1.1]
|
|
17
16
|
|
package/dist/asV2Middleware.cjs
CHANGED
|
@@ -14,7 +14,9 @@ const compatibility_utils_1 = require("./v2/compatibility-utils.cjs");
|
|
|
14
14
|
*/
|
|
15
15
|
function asV2Middleware(engineOrMiddleware, ...rest) {
|
|
16
16
|
const legacyMiddleware = typeof engineOrMiddleware === 'function'
|
|
17
|
-
?
|
|
17
|
+
? // mergeMiddleware uses .asMiddleware() internally, which is necessary for our purposes.
|
|
18
|
+
// See comment on this below.
|
|
19
|
+
(0, mergeMiddleware_1.mergeMiddleware)([engineOrMiddleware, ...rest])
|
|
18
20
|
: engineOrMiddleware.asMiddleware();
|
|
19
21
|
return async ({ request, context, next }) => {
|
|
20
22
|
const req = (0, compatibility_utils_1.deepClone)(request);
|
|
@@ -39,8 +41,11 @@ function asV2Middleware(engineOrMiddleware, ...rest) {
|
|
|
39
41
|
legacyMiddleware(req, res, legacyNext, end);
|
|
40
42
|
});
|
|
41
43
|
(0, compatibility_utils_1.propagateToContext)(req, context);
|
|
42
|
-
|
|
43
|
-
|
|
44
|
+
// Mimic the behavior of JsonRpcEngine.#handle(), which only treats truthy errors as errors.
|
|
45
|
+
// Legacy middleware may violate the invariant that response objects have either a result or an
|
|
46
|
+
// error property. In practice, we may see response objects with results and `{ error: undefined }`.
|
|
47
|
+
if ((0, utils_1.hasProperty)(response, 'error') && response.error) {
|
|
48
|
+
throw (0, compatibility_utils_1.deserializeError)(response.error);
|
|
44
49
|
}
|
|
45
50
|
else if ((0, utils_1.hasProperty)(response, 'result')) {
|
|
46
51
|
return response.result;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asV2Middleware.cjs","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":";;;AAAA,qDAAsD;AAEtD,2CAKyB;AAQzB,2DAAoD;AACpD,sEAMkC;
|
|
1
|
+
{"version":3,"file":"asV2Middleware.cjs","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":";;;AAAA,qDAAsD;AAEtD,2CAKyB;AAQzB,2DAAoD;AACpD,sEAMkC;AAkClC;;;;;;GAMG;AACH,SAAgB,cAAc,CAI5B,kBAAyE,EACzE,GAAG,IAA6C;IAEhD,MAAM,gBAAgB,GACpB,OAAO,kBAAkB,KAAK,UAAU;QACtC,CAAC,CAAC,wFAAwF;YACxF,6BAA6B;YAC7B,IAAA,iCAAe,EAAC,CAAC,kBAAkB,EAAE,GAAG,IAAI,CAAC,CAAC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C1C,OAAO,QAAQ,CAAC,MAAmC,CAAC;SACrD;QACD,OAAO,IAAI,CAAC,IAAA,uCAAiB,EAAC,GAAc,CAAC,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,CAAC;AArDD,wCAqDC","sourcesContent":["import { serializeError } from '@metamask/rpc-errors';\nimport type { JsonRpcFailure, JsonRpcResponse } from '@metamask/utils';\nimport {\n hasProperty,\n type Json,\n type JsonRpcParams,\n type JsonRpcRequest,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngine,\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from './JsonRpcEngine';\nimport { type JsonRpcMiddleware as LegacyMiddleware } from './JsonRpcEngine';\nimport { mergeMiddleware } from './mergeMiddleware';\nimport {\n deepClone,\n fromLegacyRequest,\n propagateToContext,\n propagateToRequest,\n deserializeError,\n} from './v2/compatibility-utils';\nimport type {\n // Used in docs.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n JsonRpcEngineV2,\n JsonRpcMiddleware,\n ResultConstraint,\n} from './v2/JsonRpcEngineV2';\n\n/**\n * Convert a legacy {@link JsonRpcEngine} into a {@link JsonRpcEngineV2} middleware.\n *\n * @param engine - The legacy engine to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(engine: JsonRpcEngine): JsonRpcMiddleware<Request>;\n\n/**\n * Convert one or more legacy middleware into a {@link JsonRpcEngineV2} middleware.\n *\n * @param middleware - The legacy middleware to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n Result extends Json,\n>(\n ...middleware: LegacyMiddleware<Params, Result>[]\n): JsonRpcMiddleware<Request>;\n\n/**\n * The asV2Middleware implementation.\n *\n * @param engineOrMiddleware - A legacy engine or legacy middleware.\n * @param rest - Any additional legacy middleware when the first argument is a middleware.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engineOrMiddleware: JsonRpcEngine | LegacyMiddleware<JsonRpcParams, Json>,\n ...rest: LegacyMiddleware<JsonRpcParams, Json>[]\n): JsonRpcMiddleware<Request> {\n const legacyMiddleware =\n typeof engineOrMiddleware === 'function'\n ? // mergeMiddleware uses .asMiddleware() internally, which is necessary for our purposes.\n // See comment on this below.\n mergeMiddleware([engineOrMiddleware, ...rest])\n : engineOrMiddleware.asMiddleware();\n\n return async ({ request, context, next }) => {\n const req = deepClone(request) as JsonRpcRequest<Params>;\n propagateToRequest(req, context);\n\n const response = await new Promise<JsonRpcResponse>((resolve) => {\n // The result or error property will be set by the legacy engine\n // middleware.\n const res = {\n jsonrpc: '2.0' as const,\n id: req.id,\n } as JsonRpcResponse;\n\n const end: JsonRpcEngineEndCallback = (error) => {\n if (error !== undefined) {\n (res as JsonRpcFailure).error = serializeError(error);\n }\n resolve(res);\n };\n\n // We know from the implementation of JsonRpcEngine.asMiddleware() that\n // legacyNext will always be passed a callback, so cb can never be\n // undefined.\n const legacyNext = ((cb: JsonRpcEngineEndCallback) =>\n cb(end)) as JsonRpcEngineNextCallback;\n\n legacyMiddleware(req, res, legacyNext, end);\n });\n propagateToContext(req, context);\n\n // Mimic the behavior of JsonRpcEngine.#handle(), which only treats truthy errors as errors.\n // Legacy middleware may violate the invariant that response objects have either a result or an\n // error property. In practice, we may see response objects with results and `{ error: undefined }`.\n if (hasProperty(response, 'error') && response.error) {\n throw deserializeError(response.error);\n } else if (hasProperty(response, 'result')) {\n return response.result as ResultConstraint<Request>;\n }\n return next(fromLegacyRequest(req as Request));\n };\n}\n"]}
|
|
@@ -15,5 +15,5 @@ export declare function asV2Middleware<Params extends JsonRpcParams, Request ext
|
|
|
15
15
|
* @param middleware - The legacy middleware to convert.
|
|
16
16
|
* @returns The {@link JsonRpcEngineV2} middleware.
|
|
17
17
|
*/
|
|
18
|
-
export declare function asV2Middleware<Params extends JsonRpcParams, Request extends JsonRpcRequest<Params
|
|
18
|
+
export declare function asV2Middleware<Params extends JsonRpcParams, Request extends JsonRpcRequest<Params>, Result extends Json>(...middleware: LegacyMiddleware<Params, Result>[]): JsonRpcMiddleware<Request>;
|
|
19
19
|
//# sourceMappingURL=asV2Middleware.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asV2Middleware.d.cts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,IAAI,EACT,KAAK,aAAa,EAClB,KAAK,cAAc,EACpB,wBAAwB;AAEzB,OAAO,KAAK,EACV,aAAa,EAGd,4BAAwB;AACzB,OAAO,EAAE,KAAK,iBAAiB,IAAI,gBAAgB,EAAE,4BAAwB;AAS7E,OAAO,KAAK,EAIV,iBAAiB,EAElB,iCAA6B;AAE9B;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EACtC,MAAM,EAAE,aAAa,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;AAErD;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,
|
|
1
|
+
{"version":3,"file":"asV2Middleware.d.cts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,IAAI,EACT,KAAK,aAAa,EAClB,KAAK,cAAc,EACpB,wBAAwB;AAEzB,OAAO,KAAK,EACV,aAAa,EAGd,4BAAwB;AACzB,OAAO,EAAE,KAAK,iBAAiB,IAAI,gBAAgB,EAAE,4BAAwB;AAS7E,OAAO,KAAK,EAIV,iBAAiB,EAElB,iCAA6B;AAE9B;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EACtC,MAAM,EAAE,aAAa,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;AAErD;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EACtC,MAAM,SAAS,IAAI,EAEnB,GAAG,UAAU,EAAE,gBAAgB,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,GAChD,iBAAiB,CAAC,OAAO,CAAC,CAAC"}
|
|
@@ -15,5 +15,5 @@ export declare function asV2Middleware<Params extends JsonRpcParams, Request ext
|
|
|
15
15
|
* @param middleware - The legacy middleware to convert.
|
|
16
16
|
* @returns The {@link JsonRpcEngineV2} middleware.
|
|
17
17
|
*/
|
|
18
|
-
export declare function asV2Middleware<Params extends JsonRpcParams, Request extends JsonRpcRequest<Params
|
|
18
|
+
export declare function asV2Middleware<Params extends JsonRpcParams, Request extends JsonRpcRequest<Params>, Result extends Json>(...middleware: LegacyMiddleware<Params, Result>[]): JsonRpcMiddleware<Request>;
|
|
19
19
|
//# sourceMappingURL=asV2Middleware.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asV2Middleware.d.mts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,IAAI,EACT,KAAK,aAAa,EAClB,KAAK,cAAc,EACpB,wBAAwB;AAEzB,OAAO,KAAK,EACV,aAAa,EAGd,4BAAwB;AACzB,OAAO,EAAE,KAAK,iBAAiB,IAAI,gBAAgB,EAAE,4BAAwB;AAS7E,OAAO,KAAK,EAIV,iBAAiB,EAElB,iCAA6B;AAE9B;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EACtC,MAAM,EAAE,aAAa,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;AAErD;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,
|
|
1
|
+
{"version":3,"file":"asV2Middleware.d.mts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,IAAI,EACT,KAAK,aAAa,EAClB,KAAK,cAAc,EACpB,wBAAwB;AAEzB,OAAO,KAAK,EACV,aAAa,EAGd,4BAAwB;AACzB,OAAO,EAAE,KAAK,iBAAiB,IAAI,gBAAgB,EAAE,4BAAwB;AAS7E,OAAO,KAAK,EAIV,iBAAiB,EAElB,iCAA6B;AAE9B;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EACtC,MAAM,EAAE,aAAa,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;AAErD;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EACtC,MAAM,SAAS,IAAI,EAEnB,GAAG,UAAU,EAAE,gBAAgB,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,GAChD,iBAAiB,CAAC,OAAO,CAAC,CAAC"}
|
package/dist/asV2Middleware.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { serializeError } from "@metamask/rpc-errors";
|
|
2
2
|
import { hasProperty } from "@metamask/utils";
|
|
3
3
|
import { mergeMiddleware } from "./mergeMiddleware.mjs";
|
|
4
|
-
import { deepClone, fromLegacyRequest, propagateToContext, propagateToRequest,
|
|
4
|
+
import { deepClone, fromLegacyRequest, propagateToContext, propagateToRequest, deserializeError } from "./v2/compatibility-utils.mjs";
|
|
5
5
|
/**
|
|
6
6
|
* The asV2Middleware implementation.
|
|
7
7
|
*
|
|
@@ -11,7 +11,9 @@ import { deepClone, fromLegacyRequest, propagateToContext, propagateToRequest, u
|
|
|
11
11
|
*/
|
|
12
12
|
export function asV2Middleware(engineOrMiddleware, ...rest) {
|
|
13
13
|
const legacyMiddleware = typeof engineOrMiddleware === 'function'
|
|
14
|
-
? mergeMiddleware(
|
|
14
|
+
? // mergeMiddleware uses .asMiddleware() internally, which is necessary for our purposes.
|
|
15
|
+
// See comment on this below.
|
|
16
|
+
mergeMiddleware([engineOrMiddleware, ...rest])
|
|
15
17
|
: engineOrMiddleware.asMiddleware();
|
|
16
18
|
return async ({ request, context, next }) => {
|
|
17
19
|
const req = deepClone(request);
|
|
@@ -36,8 +38,11 @@ export function asV2Middleware(engineOrMiddleware, ...rest) {
|
|
|
36
38
|
legacyMiddleware(req, res, legacyNext, end);
|
|
37
39
|
});
|
|
38
40
|
propagateToContext(req, context);
|
|
39
|
-
|
|
40
|
-
|
|
41
|
+
// Mimic the behavior of JsonRpcEngine.#handle(), which only treats truthy errors as errors.
|
|
42
|
+
// Legacy middleware may violate the invariant that response objects have either a result or an
|
|
43
|
+
// error property. In practice, we may see response objects with results and `{ error: undefined }`.
|
|
44
|
+
if (hasProperty(response, 'error') && response.error) {
|
|
45
|
+
throw deserializeError(response.error);
|
|
41
46
|
}
|
|
42
47
|
else if (hasProperty(response, 'result')) {
|
|
43
48
|
return response.result;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asV2Middleware.mjs","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,6BAA6B;AAEtD,OAAO,EACL,WAAW,EAIZ,wBAAwB;AAQzB,OAAO,EAAE,eAAe,EAAE,8BAA0B;AACpD,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,gBAAgB,EACjB,qCAAiC;
|
|
1
|
+
{"version":3,"file":"asV2Middleware.mjs","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAAA,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gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QAC9C,CAAC,CAAC,CAAC;QACH,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,4FAA4F;QAC5F,+FAA+F;QAC/F,oGAAoG;QACpG,IAAI,WAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,IAAI,QAAQ,CAAC,KAAK,EAAE;YACpD,MAAM,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;SACxC;aAAM,IAAI,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE;YAC1C,OAAO,QAAQ,CAAC,MAAmC,CAAC;SACrD;QACD,OAAO,IAAI,CAAC,iBAAiB,CAAC,GAAc,CAAC,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { serializeError } from '@metamask/rpc-errors';\nimport type { JsonRpcFailure, JsonRpcResponse } from '@metamask/utils';\nimport {\n hasProperty,\n type Json,\n type JsonRpcParams,\n type JsonRpcRequest,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngine,\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from './JsonRpcEngine';\nimport { type JsonRpcMiddleware as LegacyMiddleware } from './JsonRpcEngine';\nimport { mergeMiddleware } from './mergeMiddleware';\nimport {\n deepClone,\n fromLegacyRequest,\n propagateToContext,\n propagateToRequest,\n deserializeError,\n} from './v2/compatibility-utils';\nimport type {\n // Used in docs.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n JsonRpcEngineV2,\n JsonRpcMiddleware,\n ResultConstraint,\n} from './v2/JsonRpcEngineV2';\n\n/**\n * Convert a legacy {@link JsonRpcEngine} into a {@link JsonRpcEngineV2} middleware.\n *\n * @param engine - The legacy engine to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(engine: JsonRpcEngine): JsonRpcMiddleware<Request>;\n\n/**\n * Convert one or more legacy middleware into a {@link JsonRpcEngineV2} middleware.\n *\n * @param middleware - The legacy middleware to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n Result extends Json,\n>(\n ...middleware: LegacyMiddleware<Params, Result>[]\n): JsonRpcMiddleware<Request>;\n\n/**\n * The asV2Middleware implementation.\n *\n * @param engineOrMiddleware - A legacy engine or legacy middleware.\n * @param rest - Any additional legacy middleware when the first argument is a middleware.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engineOrMiddleware: JsonRpcEngine | LegacyMiddleware<JsonRpcParams, Json>,\n ...rest: LegacyMiddleware<JsonRpcParams, Json>[]\n): JsonRpcMiddleware<Request> {\n const legacyMiddleware =\n typeof engineOrMiddleware === 'function'\n ? // mergeMiddleware uses .asMiddleware() internally, which is necessary for our purposes.\n // See comment on this below.\n mergeMiddleware([engineOrMiddleware, ...rest])\n : engineOrMiddleware.asMiddleware();\n\n return async ({ request, context, next }) => {\n const req = deepClone(request) as JsonRpcRequest<Params>;\n propagateToRequest(req, context);\n\n const response = await new Promise<JsonRpcResponse>((resolve) => {\n // The result or error property will be set by the legacy engine\n // middleware.\n const res = {\n jsonrpc: '2.0' as const,\n id: req.id,\n } as JsonRpcResponse;\n\n const end: JsonRpcEngineEndCallback = (error) => {\n if (error !== undefined) {\n (res as JsonRpcFailure).error = serializeError(error);\n }\n resolve(res);\n };\n\n // We know from the implementation of JsonRpcEngine.asMiddleware() that\n // legacyNext will always be passed a callback, so cb can never be\n // undefined.\n const legacyNext = ((cb: JsonRpcEngineEndCallback) =>\n cb(end)) as JsonRpcEngineNextCallback;\n\n legacyMiddleware(req, res, legacyNext, end);\n });\n propagateToContext(req, context);\n\n // Mimic the behavior of JsonRpcEngine.#handle(), which only treats truthy errors as errors.\n // Legacy middleware may violate the invariant that response objects have either a result or an\n // error property. In practice, we may see response objects with results and `{ error: undefined }`.\n if (hasProperty(response, 'error') && response.error) {\n throw deserializeError(response.error);\n } else if (hasProperty(response, 'result')) {\n return response.result as ResultConstraint<Request>;\n }\n return next(fromLegacyRequest(req as Request));\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcEngineV2.cjs","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,2CAMyB;AACzB,4EAA4C;AAG5C,+DAAwD;AACxD,uCAKiB;AAmFjB,MAAM,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAShD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAa,eAAe;IAY1B,yCAAyC;IACzC,YAAoB,EAAE,UAAU,EAAwC;;QATxE,8CAIE;QAEF,uCAAe,KAAK,EAAC;QAInB,uBAAA,IAAI,+BAAe,CAAC,GAAG,UAAU,CAAC,MAAA,CAAC;IACrC,CAAC;IAED,+FAA+F;IAC/F,6FAA6F;IAC7F,iBAAiB;IACjB;;;;;;;OAOG;IACH,MAAM,CAAC,MAAM,CASX,EAAE,UAAU,EAAgC;QAC5C,6EAA6E;QAC7E,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE;YAC3B,MAAM,IAAI,0BAAkB,CAAC,kCAAkC,CAAC,CAAC;SAClE;QAID,MAAM,EAAE,GAAG,UAMV,CAAC;QACF,OAAO,IAAI,eAAe,CAA8B;YACtD,UAAU,EAAE,EAAE;SACf,CAE+C,CAAC;IACnD,CAAC;IAqDD,KAAK,CAAC,MAAM,CACV,OAAgB,EAChB,EAAE,OAAO,KAA6B,EAAE;QAExC,MAAM,KAAK,GAAG,IAAA,iBAAS,EAAC,OAAO,CAAC,CAAC;QACjC,MAAM,EAAE,MAAM,EAAE,GAAG,M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AO,EAAE;QAClD,MAAM,IAAI,0BAAkB,CAC1B,2EAA2E,IAAA,iBAAS,EAAC,cAAc,CAAC,EAAE,CACvG,CAAC;KACH;IACD,IACE,IAAA,mBAAW,EAAC,WAAW,EAAE,IAAI,CAAC,KAAK,IAAA,mBAAW,EAAC,cAAc,EAAE,IAAI,CAAC;QACpE,4EAA4E;QAC5E,8CAA8C;QAC9C,WAAW,CAAC,EAAE,KAAK,cAAc,CAAC,EAAE,EACpC;QACA,MAAM,IAAI,0BAAkB,CAC1B,sEAAsE,IAAA,iBAAS,EAAC,cAAc,CAAC,EAAE,CAClG,CAAC;KACH;AACH,CAAC;IAkDC,IAAI,uBAAA,IAAI,oCAAa,EAAE;QACrB,MAAM,IAAI,0BAAkB,CAAC,qBAAqB,CAAC,CAAC;KACrD;AACH,CAAC","sourcesContent":["import {\n type Json,\n type JsonRpcRequest,\n type JsonRpcNotification,\n type NonEmptyArray,\n hasProperty,\n} from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\n\nimport type { ContextConstraint, MergeContexts } from './MiddlewareContext';\nimport { MiddlewareContext } from './MiddlewareContext';\nimport {\n isNotification,\n isRequest,\n JsonRpcEngineError,\n stringify,\n} from './utils';\nimport type { JsonRpcCall } from './utils';\n\n// Helper to forbid `id` on notifications\ntype WithoutId<Request extends JsonRpcCall> = Request & { id?: never };\n\n// Helper to enable JsonRpcCall overload of handle()\ntype MixedParam<Request extends JsonRpcCall> = [\n Extract<Request, JsonRpcRequest>,\n] extends [never]\n ? never\n : [Extract<Request, JsonRpcNotification>] extends [never]\n ? never\n :\n | Extract<Request, JsonRpcRequest>\n | WithoutId<Extract<Request, JsonRpcNotification>>;\n\nexport type ResultConstraint<Request extends JsonRpcCall> =\n Request extends JsonRpcRequest ? Json : void;\n\nexport type Next<Request extends JsonRpcCall> = (\n request?: Readonly<Request>,\n) => Promise<Readonly<ResultConstraint<Request>> | undefined>;\n\nexport type MiddlewareParams<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends MiddlewareContext = MiddlewareContext,\n> = {\n request: Readonly<Request>;\n context: Context;\n next: Next<Request>;\n};\n\nexport type JsonRpcMiddleware<\n Request extends JsonRpcCall = JsonRpcCall,\n Result extends ResultConstraint<Request> = ResultConstraint<Request>,\n Context extends ContextConstraint = MiddlewareContext,\n> = (\n params: MiddlewareParams<Request, Context>,\n) => Readonly<Result> | undefined | Promise<Readonly<Result> | undefined>;\n\ntype RequestState<Request extends JsonRpcCall> = {\n request: Request;\n result: Readonly<ResultConstraint<Request>> | undefined;\n};\n\ntype HandleOptions<Context extends MiddlewareContext> = {\n context?: Context;\n};\n\ntype ConstructorOptions<\n Request extends JsonRpcCall,\n Context extends MiddlewareContext,\n> = {\n middleware: NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >;\n};\n\nexport type RequestOf<Middleware> =\n Middleware extends JsonRpcMiddleware<\n infer Request,\n ResultConstraint<infer Request>,\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n >\n ? Request\n : never;\n\ntype ContextOf<Middleware> =\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Middleware extends JsonRpcMiddleware<any, ResultConstraint<any>, infer C>\n ? C\n : never;\n\nexport type MergedContextOf<\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Middleware extends JsonRpcMiddleware<any, any, any>,\n> = MergeContexts<ContextOf<Middleware>>;\n\nconst INVALID_ENGINE = Symbol('Invalid engine');\n\n/**\n * An internal type for invalid engines that explains why the engine is invalid.\n *\n * @template Message - The message explaining why the engine is invalid.\n */\ntype InvalidEngine<Message extends string> = { [INVALID_ENGINE]: Message };\n\n/**\n * A JSON-RPC request and response processor.\n *\n * Give it a stack of middleware, pass it requests, and get back responses.\n *\n * #### Requests vs. notifications\n *\n * JSON-RPC requests come in two flavors:\n *\n * - [Requests](https://www.jsonrpc.org/specification#request_object), i.e. request objects _with_ an `id`\n * - [Notifications](https://www.jsonrpc.org/specification#notification), i.e. request objects _without_ an `id`\n *\n * For requests, one of the engine's middleware must \"end\" the request by returning a non-`undefined` result,\n * or {@link handle} will throw an error:\n *\n * For notifications, on the other hand, one of the engine's middleware must return `undefined` to end the request,\n * and any non-`undefined` return values will cause an error:\n *\n * @template Request - The type of request to handle.\n * @template Result - The type of result to return.\n *\n * @example\n * ```ts\n * const engine = JsonRpcEngineV2.create({\n * middleware,\n * });\n *\n * try {\n * const result = await engine.handle(request);\n * // Handle result\n * } catch (error) {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcEngineV2<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends ContextConstraint = MiddlewareContext,\n> {\n #middleware: Readonly<\n NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >\n >;\n\n #isDestroyed = false;\n\n // See .create() for why this is private.\n private constructor({ middleware }: ConstructorOptions<Request, Context>) {\n this.#middleware = [...middleware];\n }\n\n // We use a static factory method in order to construct a supertype of all middleware contexts,\n // which enables us to instantiate an engine despite different middleware expecting different\n // context types.\n /**\n * Create a new JSON-RPC engine.\n *\n * @throws If the middleware array is empty.\n * @param options - The options for the engine.\n * @param options.middleware - The middleware to use.\n * @returns The JSON-RPC engine.\n */\n static create<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n >({ middleware }: { middleware: Middleware[] }) {\n // We can't use NonEmptyArray for the params because it ruins type inference.\n if (middleware.length === 0) {\n throw new JsonRpcEngineError('Middleware array cannot be empty');\n }\n\n type MergedContext = MergedContextOf<Middleware>;\n type InputRequest = RequestOf<Middleware>;\n const mw = middleware as unknown as NonEmptyArray<\n JsonRpcMiddleware<\n InputRequest,\n ResultConstraint<InputRequest>,\n MergedContext\n >\n >;\n return new JsonRpcEngineV2<InputRequest, MergedContext>({\n middleware: mw,\n }) as MergedContext extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<InputRequest, MergedContext>;\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * @param request - The JSON-RPC request to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response.\n */\n async handle(\n request: Extract<Request, JsonRpcRequest> extends never\n ? never\n : Extract<Request, JsonRpcRequest>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcRequest> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC notification. Notifications do not return a result.\n *\n * @param notification - The JSON-RPC notification to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n */\n async handle(\n notification: Extract<Request, JsonRpcNotification> extends never\n ? never\n : WithoutId<Extract<Request, JsonRpcNotification>>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcNotification> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC call, i.e. request or notification. Requests return a\n * result, notifications do not.\n *\n * @param call - The JSON-RPC call to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response, or `undefined` if the call is a notification.\n */\n async handle(\n call: MixedParam<Request>,\n options?: HandleOptions<Context>,\n ): Promise<ResultConstraint<Request> | void>;\n\n async handle(\n request: Request,\n { context }: HandleOptions<Context> = {},\n ): Promise<Readonly<ResultConstraint<Request>> | void> {\n const isReq = isRequest(request);\n const { result } = await this.#handle(request, context);\n\n if (isReq && result === undefined) {\n throw new JsonRpcEngineError(\n `Nothing ended request: ${stringify(request)}`,\n );\n }\n return result;\n }\n\n /**\n * Handle a JSON-RPC request. Throws if a middleware performs an invalid\n * operation. Permits returning an `undefined` result.\n *\n * @param originalRequest - The JSON-RPC request to handle.\n * @param context - The context to pass to the middleware.\n * @returns The result from the middleware.\n */\n async #handle(\n originalRequest: Request,\n context: Context = new MiddlewareContext() as Context,\n ): Promise<RequestState<Request>> {\n this.#assertIsNotDestroyed();\n\n deepFreeze(originalRequest);\n\n const state: RequestState<Request> = {\n request: originalRequest,\n result: undefined,\n };\n const middlewareIterator = this.#makeMiddlewareIterator();\n const firstMiddleware = middlewareIterator.next().value;\n\n const makeNext = this.#makeNextFactory(middlewareIterator, state, context);\n\n const result = await firstMiddleware({\n request: originalRequest,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state;\n }\n\n /**\n * Create a factory of `next()` functions for use with a particular request.\n * The factory is recursive, and a new `next()` is created for each middleware\n * invocation.\n *\n * @param middlewareIterator - The iterator of middleware for the current\n * request.\n * @param state - The current values of the request and result.\n * @param context - The context to pass to the middleware.\n * @returns The `next()` function factory.\n */\n #makeNextFactory(\n middlewareIterator: Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >,\n state: RequestState<Request>,\n context: Context,\n ): () => Next<Request> {\n const makeNext = (): Next<Request> => {\n let wasCalled = false;\n\n const next = async (\n request: Request = state.request,\n ): Promise<Readonly<ResultConstraint<Request>> | undefined> => {\n if (wasCalled) {\n throw new JsonRpcEngineError(\n `Middleware attempted to call next() multiple times for request: ${stringify(request)}`,\n );\n }\n wasCalled = true;\n\n if (request !== state.request) {\n this.#assertValidNextRequest(state.request, request);\n state.request = deepFreeze(request);\n }\n\n const { value: nextMiddleware, done } = middlewareIterator.next();\n if (done) {\n // This will cause the last middleware to return `undefined`. See the class\n // JSDoc or package README for more details.\n return undefined;\n }\n\n const result = await nextMiddleware({\n request,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state.result;\n };\n return next;\n };\n\n return makeNext;\n }\n\n #makeMiddlewareIterator(): Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n > {\n return this.#middleware[Symbol.iterator]();\n }\n\n /**\n * Validate the result from a middleware and, if it's a new value, update the\n * current result.\n *\n * @param result - The result from the middleware.\n * @param state - The current values of the request and result.\n */\n #updateResult(\n result:\n | Readonly<ResultConstraint<Request>>\n | ResultConstraint<Request>\n | void,\n state: RequestState<Request>,\n ): void {\n if (isNotification(state.request) && result !== undefined) {\n throw new JsonRpcEngineError(\n `Result returned for notification: ${stringify(state.request)}`,\n );\n }\n\n if (result !== undefined && result !== state.result) {\n if (typeof result === 'object' && result !== null) {\n deepFreeze(result);\n }\n state.result = result;\n }\n }\n\n /**\n * Assert that a request modified by a middleware is valid.\n *\n * @param currentRequest - The current request.\n * @param nextRequest - The next request.\n */\n #assertValidNextRequest(currentRequest: Request, nextRequest: Request): void {\n if (nextRequest.jsonrpc !== currentRequest.jsonrpc) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"jsonrpc\" for request: ${stringify(currentRequest)}`,\n );\n }\n if (\n hasProperty(nextRequest, 'id') !== hasProperty(currentRequest, 'id') ||\n // @ts-expect-error - \"id\" does not exist on notifications, but we can still\n // check the value of the property at runtime.\n nextRequest.id !== currentRequest.id\n ) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"id\" for request: ${stringify(currentRequest)}`,\n );\n }\n }\n\n /**\n * Convert the engine into a JSON-RPC middleware.\n *\n * @returns The JSON-RPC middleware.\n */\n asMiddleware(): JsonRpcMiddleware<\n Request,\n ResultConstraint<Request>,\n Context\n > {\n this.#assertIsNotDestroyed();\n\n return async ({ request, context, next }) => {\n const { result, request: finalRequest } = await this.#handle(\n request,\n context,\n );\n return result === undefined ? await next(finalRequest) : result;\n };\n }\n\n /**\n * Destroy the engine. Calls the `destroy()` method of any middleware that has\n * one. Attempting to use the engine after destroying it will throw an error.\n */\n async destroy(): Promise<void> {\n if (this.#isDestroyed) {\n return;\n }\n this.#isDestroyed = true;\n\n const destructionPromise = Promise.all(\n this.#middleware.map(async (middleware) => {\n if (\n // Intentionally using `in` to walk the prototype chain.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n return middleware.destroy();\n }\n return undefined;\n }),\n );\n this.#middleware = [] as never;\n await destructionPromise;\n }\n\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new JsonRpcEngineError('Engine is destroyed');\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"JsonRpcEngineV2.cjs","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,2CAMyB;AACzB,4EAA4C;AAG5C,+DAAwD;AACxD,uCAKiB;AAkGjB,MAAM,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAShD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAa,eAAe;IAY1B,yCAAyC;IACzC,YAAoB,EAAE,UAAU,EAAwC;;QATxE,8CAIE;QAEF,uCAAe,KAAK,EAAC;QAInB,uBAAA,IAAI,+BAAe,CAAC,GAAG,UAAU,CAAC,MAAA,CAAC;IACrC,CAAC;IAED,+FAA+F;IAC/F,6FAA6F;IAC7F,iBAAiB;IACjB;;;;;;;OAOG;IACH,MAAM,CAAC,MAAM,CASX,EAAE,UAAU,EAAgC;QAC5C,6EAA6E;QAC7E,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE;YAC3B,MAAM,IAAI,0BAAkB,CAAC,kCAAkC,CAAC,CAAC;SAClE;QAID,MAAM,EAAE,GAAG,UAMV,CAAC;QACF,OAAO,IAAI,eAAe,CAA8B;YACtD,UAAU,EAAE,EAAE;SACf,CAE+C,CAAC;IACnD,CAAC;IAqDD,KAAK,CAAC,MAAM,CACV,OAAgB,EAChB,EAAE,OAAO,KAA6B,EAAE;QAExC,MAAM,KAAK,GAAG,IAAA,iBAAS,EAAC,OAAO,CAAC,CAAC;QACjC,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,uBAAA,IAAI,2DAAQ,MAAZ,IAAI,EAAS,OAAO,EAAE,OAAO,CAAC,CAAC;QAExD,IA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AAE,CACvG,CAAC;KACH;IACD,IACE,IAAA,mBAAW,EAAC,WAAW,EAAE,IAAI,CAAC,KAAK,IAAA,mBAAW,EAAC,cAAc,EAAE,IAAI,CAAC;QACpE,4EAA4E;QAC5E,8CAA8C;QAC9C,WAAW,CAAC,EAAE,KAAK,cAAc,CAAC,EAAE,EACpC;QACA,MAAM,IAAI,0BAAkB,CAC1B,sEAAsE,IAAA,iBAAS,EAAC,cAAc,CAAC,EAAE,CAClG,CAAC;KACH;AACH,CAAC;IAkDC,IAAI,uBAAA,IAAI,oCAAa,EAAE;QACrB,MAAM,IAAI,0BAAkB,CAAC,qBAAqB,CAAC,CAAC;KACrD;AACH,CAAC","sourcesContent":["import {\n type Json,\n type JsonRpcRequest,\n type JsonRpcNotification,\n type NonEmptyArray,\n hasProperty,\n} from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\n\nimport type { ContextConstraint, MergeContexts } from './MiddlewareContext';\nimport { MiddlewareContext } from './MiddlewareContext';\nimport {\n isNotification,\n isRequest,\n JsonRpcEngineError,\n stringify,\n} from './utils';\nimport type { JsonRpcCall } from './utils';\n\n// Helper to forbid `id` on notifications\ntype WithoutId<Request extends JsonRpcCall> = Request & { id?: never };\n\n// Helper to enable JsonRpcCall overload of handle()\ntype MixedParam<Request extends JsonRpcCall> = [\n Extract<Request, JsonRpcRequest>,\n] extends [never]\n ? never\n : [Extract<Request, JsonRpcNotification>] extends [never]\n ? never\n :\n | Extract<Request, JsonRpcRequest>\n | WithoutId<Extract<Request, JsonRpcNotification>>;\n\nexport type ResultConstraint<Request extends JsonRpcCall> =\n Request extends JsonRpcRequest ? Json : void;\n\nexport type Next<Request extends JsonRpcCall> = (\n request?: Readonly<Request>,\n) => Promise<Readonly<ResultConstraint<Request>> | undefined>;\n\nexport type MiddlewareParams<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends MiddlewareContext = MiddlewareContext,\n> = {\n request: Readonly<Request>;\n context: Context;\n next: Next<Request>;\n};\n\nexport type JsonRpcMiddleware<\n Request extends JsonRpcCall = JsonRpcCall,\n Result extends ResultConstraint<Request> = ResultConstraint<Request>,\n Context extends ContextConstraint = MiddlewareContext,\n> = (\n params: MiddlewareParams<Request, Context>,\n) => Readonly<Result> | undefined | Promise<Readonly<Result> | undefined>;\n\ntype RequestState<Request extends JsonRpcCall> = {\n request: Request;\n result: Readonly<ResultConstraint<Request>> | undefined;\n};\n\ntype HandleOptions<Context extends MiddlewareContext> = {\n context?: Context;\n};\n\ntype ConstructorOptions<\n Request extends JsonRpcCall,\n Context extends MiddlewareContext,\n> = {\n middleware: NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >;\n};\n\n/**\n * The request type of a middleware.\n */\nexport type RequestOf<Middleware> =\n Middleware extends JsonRpcMiddleware<\n infer Request,\n ResultConstraint<infer Request>,\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n >\n ? Request\n : never;\n\ntype ContextOf<Middleware> =\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Middleware extends JsonRpcMiddleware<any, ResultConstraint<any>, infer C>\n ? C\n : never;\n\n/**\n * A constraint for {@link JsonRpcMiddleware} generic parameters.\n */\n// Non-polluting `any` constraint.\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type MiddlewareConstraint = JsonRpcMiddleware<\n any,\n ResultConstraint<any>,\n MiddlewareContext<any>\n>;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/**\n * The context supertype of a middleware type.\n */\nexport type MergedContextOf<Middleware extends MiddlewareConstraint> =\n MergeContexts<ContextOf<Middleware>>;\n\nconst INVALID_ENGINE = Symbol('Invalid engine');\n\n/**\n * An internal type for invalid engines that explains why the engine is invalid.\n *\n * @template Message - The message explaining why the engine is invalid.\n */\ntype InvalidEngine<Message extends string> = { [INVALID_ENGINE]: Message };\n\n/**\n * A JSON-RPC request and response processor.\n *\n * Give it a stack of middleware, pass it requests, and get back responses.\n *\n * #### Requests vs. notifications\n *\n * JSON-RPC requests come in two flavors:\n *\n * - [Requests](https://www.jsonrpc.org/specification#request_object), i.e. request objects _with_ an `id`\n * - [Notifications](https://www.jsonrpc.org/specification#notification), i.e. request objects _without_ an `id`\n *\n * For requests, one of the engine's middleware must \"end\" the request by returning a non-`undefined` result,\n * or {@link handle} will throw an error:\n *\n * For notifications, on the other hand, one of the engine's middleware must return `undefined` to end the request,\n * and any non-`undefined` return values will cause an error:\n *\n * @template Request - The type of request to handle.\n * @template Result - The type of result to return.\n *\n * @example\n * ```ts\n * const engine = JsonRpcEngineV2.create({\n * middleware,\n * });\n *\n * try {\n * const result = await engine.handle(request);\n * // Handle result\n * } catch (error) {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcEngineV2<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends ContextConstraint = MiddlewareContext,\n> {\n #middleware: Readonly<\n NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >\n >;\n\n #isDestroyed = false;\n\n // See .create() for why this is private.\n private constructor({ middleware }: ConstructorOptions<Request, Context>) {\n this.#middleware = [...middleware];\n }\n\n // We use a static factory method in order to construct a supertype of all middleware contexts,\n // which enables us to instantiate an engine despite different middleware expecting different\n // context types.\n /**\n * Create a new JSON-RPC engine.\n *\n * @throws If the middleware array is empty.\n * @param options - The options for the engine.\n * @param options.middleware - The middleware to use.\n * @returns The JSON-RPC engine.\n */\n static create<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n >({ middleware }: { middleware: Middleware[] }) {\n // We can't use NonEmptyArray for the params because it ruins type inference.\n if (middleware.length === 0) {\n throw new JsonRpcEngineError('Middleware array cannot be empty');\n }\n\n type MergedContext = MergedContextOf<Middleware>;\n type InputRequest = RequestOf<Middleware>;\n const mw = middleware as unknown as NonEmptyArray<\n JsonRpcMiddleware<\n InputRequest,\n ResultConstraint<InputRequest>,\n MergedContext\n >\n >;\n return new JsonRpcEngineV2<InputRequest, MergedContext>({\n middleware: mw,\n }) as MergedContext extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<InputRequest, MergedContext>;\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * @param request - The JSON-RPC request to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response.\n */\n async handle(\n request: Extract<Request, JsonRpcRequest> extends never\n ? never\n : Extract<Request, JsonRpcRequest>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcRequest> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC notification. Notifications do not return a result.\n *\n * @param notification - The JSON-RPC notification to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n */\n async handle(\n notification: Extract<Request, JsonRpcNotification> extends never\n ? never\n : WithoutId<Extract<Request, JsonRpcNotification>>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcNotification> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC call, i.e. request or notification. Requests return a\n * result, notifications do not.\n *\n * @param call - The JSON-RPC call to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response, or `undefined` if the call is a notification.\n */\n async handle(\n call: MixedParam<Request>,\n options?: HandleOptions<Context>,\n ): Promise<ResultConstraint<Request> | void>;\n\n async handle(\n request: Request,\n { context }: HandleOptions<Context> = {},\n ): Promise<Readonly<ResultConstraint<Request>> | void> {\n const isReq = isRequest(request);\n const { result } = await this.#handle(request, context);\n\n if (isReq && result === undefined) {\n throw new JsonRpcEngineError(\n `Nothing ended request: ${stringify(request)}`,\n );\n }\n return result;\n }\n\n /**\n * Handle a JSON-RPC request. Throws if a middleware performs an invalid\n * operation. Permits returning an `undefined` result.\n *\n * @param originalRequest - The JSON-RPC request to handle.\n * @param context - The context to pass to the middleware.\n * @returns The result from the middleware.\n */\n async #handle(\n originalRequest: Request,\n context: Context = new MiddlewareContext() as Context,\n ): Promise<RequestState<Request>> {\n this.#assertIsNotDestroyed();\n\n deepFreeze(originalRequest);\n\n const state: RequestState<Request> = {\n request: originalRequest,\n result: undefined,\n };\n const middlewareIterator = this.#makeMiddlewareIterator();\n const firstMiddleware = middlewareIterator.next().value;\n\n const makeNext = this.#makeNextFactory(middlewareIterator, state, context);\n\n const result = await firstMiddleware({\n request: originalRequest,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state;\n }\n\n /**\n * Create a factory of `next()` functions for use with a particular request.\n * The factory is recursive, and a new `next()` is created for each middleware\n * invocation.\n *\n * @param middlewareIterator - The iterator of middleware for the current\n * request.\n * @param state - The current values of the request and result.\n * @param context - The context to pass to the middleware.\n * @returns The `next()` function factory.\n */\n #makeNextFactory(\n middlewareIterator: Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >,\n state: RequestState<Request>,\n context: Context,\n ): () => Next<Request> {\n const makeNext = (): Next<Request> => {\n let wasCalled = false;\n\n const next = async (\n request: Request = state.request,\n ): Promise<Readonly<ResultConstraint<Request>> | undefined> => {\n if (wasCalled) {\n throw new JsonRpcEngineError(\n `Middleware attempted to call next() multiple times for request: ${stringify(request)}`,\n );\n }\n wasCalled = true;\n\n if (request !== state.request) {\n this.#assertValidNextRequest(state.request, request);\n state.request = deepFreeze(request);\n }\n\n const { value: nextMiddleware, done } = middlewareIterator.next();\n if (done) {\n // This will cause the last middleware to return `undefined`. See the class\n // JSDoc or package README for more details.\n return undefined;\n }\n\n const result = await nextMiddleware({\n request,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state.result;\n };\n return next;\n };\n\n return makeNext;\n }\n\n #makeMiddlewareIterator(): Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n > {\n return this.#middleware[Symbol.iterator]();\n }\n\n /**\n * Validate the result from a middleware and, if it's a new value, update the\n * current result.\n *\n * @param result - The result from the middleware.\n * @param state - The current values of the request and result.\n */\n #updateResult(\n result:\n | Readonly<ResultConstraint<Request>>\n | ResultConstraint<Request>\n | void,\n state: RequestState<Request>,\n ): void {\n if (isNotification(state.request) && result !== undefined) {\n throw new JsonRpcEngineError(\n `Result returned for notification: ${stringify(state.request)}`,\n );\n }\n\n if (result !== undefined && result !== state.result) {\n if (typeof result === 'object' && result !== null) {\n deepFreeze(result);\n }\n state.result = result;\n }\n }\n\n /**\n * Assert that a request modified by a middleware is valid.\n *\n * @param currentRequest - The current request.\n * @param nextRequest - The next request.\n */\n #assertValidNextRequest(currentRequest: Request, nextRequest: Request): void {\n if (nextRequest.jsonrpc !== currentRequest.jsonrpc) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"jsonrpc\" for request: ${stringify(currentRequest)}`,\n );\n }\n if (\n hasProperty(nextRequest, 'id') !== hasProperty(currentRequest, 'id') ||\n // @ts-expect-error - \"id\" does not exist on notifications, but we can still\n // check the value of the property at runtime.\n nextRequest.id !== currentRequest.id\n ) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"id\" for request: ${stringify(currentRequest)}`,\n );\n }\n }\n\n /**\n * Convert the engine into a JSON-RPC middleware.\n *\n * @returns The JSON-RPC middleware.\n */\n asMiddleware(): JsonRpcMiddleware<\n Request,\n ResultConstraint<Request>,\n Context\n > {\n this.#assertIsNotDestroyed();\n\n return async ({ request, context, next }) => {\n const { result, request: finalRequest } = await this.#handle(\n request,\n context,\n );\n return result === undefined ? await next(finalRequest) : result;\n };\n }\n\n /**\n * Destroy the engine. Calls the `destroy()` method of any middleware that has\n * one. Attempting to use the engine after destroying it will throw an error.\n */\n async destroy(): Promise<void> {\n if (this.#isDestroyed) {\n return;\n }\n this.#isDestroyed = true;\n\n const destructionPromise = Promise.all(\n this.#middleware.map(async (middleware) => {\n if (\n // Intentionally using `in` to walk the prototype chain.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n return middleware.destroy();\n }\n return undefined;\n }),\n );\n this.#middleware = [] as never;\n await destructionPromise;\n }\n\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new JsonRpcEngineError('Engine is destroyed');\n }\n }\n}\n"]}
|
|
@@ -19,9 +19,19 @@ export type JsonRpcMiddleware<Request extends JsonRpcCall = JsonRpcCall, Result
|
|
|
19
19
|
type HandleOptions<Context extends MiddlewareContext> = {
|
|
20
20
|
context?: Context;
|
|
21
21
|
};
|
|
22
|
+
/**
|
|
23
|
+
* The request type of a middleware.
|
|
24
|
+
*/
|
|
22
25
|
export type RequestOf<Middleware> = Middleware extends JsonRpcMiddleware<infer Request, ResultConstraint<infer Request>, any> ? Request : never;
|
|
23
26
|
type ContextOf<Middleware> = Middleware extends JsonRpcMiddleware<any, ResultConstraint<any>, infer C> ? C : never;
|
|
24
|
-
|
|
27
|
+
/**
|
|
28
|
+
* A constraint for {@link JsonRpcMiddleware} generic parameters.
|
|
29
|
+
*/
|
|
30
|
+
export type MiddlewareConstraint = JsonRpcMiddleware<any, ResultConstraint<any>, MiddlewareContext<any>>;
|
|
31
|
+
/**
|
|
32
|
+
* The context supertype of a middleware type.
|
|
33
|
+
*/
|
|
34
|
+
export type MergedContextOf<Middleware extends MiddlewareConstraint> = MergeContexts<ContextOf<Middleware>>;
|
|
25
35
|
declare const INVALID_ENGINE: unique symbol;
|
|
26
36
|
/**
|
|
27
37
|
* An internal type for invalid engines that explains why the engine is invalid.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcEngineV2.d.cts","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,IAAI,EACT,KAAK,cAAc,EACnB,KAAK,mBAAmB,EAGzB,wBAAwB;AAGzB,OAAO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AS,KAAK,GACnD,KAAK,GACL,OAAO,CAAC,OAAO,EAAE,cAAc,CAAC,EACpC,OAAO,CAAC,EAAE,aAAa,CAAC,OAAO,CAAC,GAC/B,OAAO,CACR,OAAO,CAAC,OAAO,EAAE,cAAc,CAAC,SAAS,KAAK,GAC1C,KAAK,GACL,gBAAgB,CAAC,OAAO,CAAC,CAC9B;IAED;;;;;;OAMG;IACG,MAAM,CACV,YAAY,EAAE,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,SAAS,KAAK,GAC7D,KAAK,GACL,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC,EACpD,OAAO,CAAC,EAAE,aAAa,CAAC,OAAO,CAAC,GAC/B,OAAO,CACR,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,SAAS,KAAK,GAC/C,KAAK,GACL,gBAAgB,CAAC,OAAO,CAAC,CAC9B;IAED;;;;;;;;OAQG;IACG,MAAM,CACV,IAAI,EAAE,UAAU,CAAC,OAAO,CAAC,EACzB,OAAO,CAAC,EAAE,aAAa,CAAC,OAAO,CAAC,GAC/B,OAAO,CAAC,gBAAgB,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;IAwK5C;;;;OAIG;IACH,YAAY,IAAI,iBAAiB,CAC/B,OAAO,EACP,gBAAgB,CAAC,OAAO,CAAC,EACzB,OAAO,CACR;IAYD;;;OAGG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CA2B/B"}
|
|
@@ -19,9 +19,19 @@ export type JsonRpcMiddleware<Request extends JsonRpcCall = JsonRpcCall, Result
|
|
|
19
19
|
type HandleOptions<Context extends MiddlewareContext> = {
|
|
20
20
|
context?: Context;
|
|
21
21
|
};
|
|
22
|
+
/**
|
|
23
|
+
* The request type of a middleware.
|
|
24
|
+
*/
|
|
22
25
|
export type RequestOf<Middleware> = Middleware extends JsonRpcMiddleware<infer Request, ResultConstraint<infer Request>, any> ? Request : never;
|
|
23
26
|
type ContextOf<Middleware> = Middleware extends JsonRpcMiddleware<any, ResultConstraint<any>, infer C> ? C : never;
|
|
24
|
-
|
|
27
|
+
/**
|
|
28
|
+
* A constraint for {@link JsonRpcMiddleware} generic parameters.
|
|
29
|
+
*/
|
|
30
|
+
export type MiddlewareConstraint = JsonRpcMiddleware<any, ResultConstraint<any>, MiddlewareContext<any>>;
|
|
31
|
+
/**
|
|
32
|
+
* The context supertype of a middleware type.
|
|
33
|
+
*/
|
|
34
|
+
export type MergedContextOf<Middleware extends MiddlewareConstraint> = MergeContexts<ContextOf<Middleware>>;
|
|
25
35
|
declare const INVALID_ENGINE: unique symbol;
|
|
26
36
|
/**
|
|
27
37
|
* An internal type for invalid engines that explains why the engine is invalid.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcEngineV2.d.mts","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,IAAI,EACT,KAAK,cAAc,EACnB,KAAK,mBAAmB,EAGzB,wBAAwB;AAGzB,OAAO,KAAK,EAAE,iBAAiB,EAAE,aAAa,EAAE,gCAA4B;AAC5E,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AAOxD,OAAO,KAAK,EAAE,WAAW,EAAE,oBAAgB;AAG3C,KAAK,SAAS,CAAC,OAAO,SAAS,WAAW,IAAI,OAAO,GAAG;IAAE,EAAE,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AAGvE,KAAK,UAAU,CAAC,OAAO,SAAS,WAAW,IAAI;IAC7C,OAAO,CAAC,OAAO,EAAE,cAAc,CAAC;CACjC,SAAS,CAAC,KAAK,CAAC,GACb,KAAK,GACL,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,GACrD,KAAK,GAED,OAAO,CAAC,OAAO,EAAE,cAAc,CAAC,GAChC,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,C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I,EAAE;YACjD,UAAU,CAAC,MAAM,CAAC,CAAC;SACpB;QACD,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC;KACvB;AACH,CAAC,6FAQuB,cAAuB,EAAE,WAAoB;IACnE,IAAI,WAAW,CAAC,OAAO,KAAK,cAAc,CAAC,OAAO,EAAE;QAClD,MAAM,IAAI,kBAAkB,CAC1B,2EAA2E,SAAS,CAAC,cAAc,CAAC,EAAE,CACvG,CAAC;KACH;IACD,IACE,WAAW,CAAC,WAAW,EAAE,IAAI,CAAC,KAAK,WAAW,CAAC,cAAc,EAAE,IAAI,CAAC;QACpE,4EAA4E;QAC5E,8CAA8C;QAC9C,WAAW,CAAC,EAAE,KAAK,cAAc,CAAC,EAAE,EACpC;QACA,MAAM,IAAI,kBAAkB,CAC1B,sEAAsE,SAAS,CAAC,cAAc,CAAC,EAAE,CAClG,CAAC;KACH;AACH,CAAC;IAkDC,IAAI,uBAAA,IAAI,oCAAa,EAAE;QACrB,MAAM,IAAI,kBAAkB,CAAC,qBAAqB,CAAC,CAAC;KACrD;AACH,CAAC","sourcesContent":["import {\n type Json,\n type JsonRpcRequest,\n type JsonRpcNotification,\n type NonEmptyArray,\n hasProperty,\n} from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\n\nimport type { ContextConstraint, MergeContexts } from './MiddlewareContext';\nimport { MiddlewareContext } from './MiddlewareContext';\nimport {\n isNotification,\n isRequest,\n JsonRpcEngineError,\n stringify,\n} from './utils';\nimport type { JsonRpcCall } from './utils';\n\n// Helper to forbid `id` on notifications\ntype WithoutId<Request extends JsonRpcCall> = Request & { id?: never };\n\n// Helper to enable JsonRpcCall overload of handle()\ntype MixedParam<Request extends JsonRpcCall> = [\n Extract<Request, JsonRpcRequest>,\n] extends [never]\n ? never\n : [Extract<Request, JsonRpcNotification>] extends [never]\n ? never\n :\n | Extract<Request, JsonRpcRequest>\n | WithoutId<Extract<Request, JsonRpcNotification>>;\n\nexport type ResultConstraint<Request extends JsonRpcCall> =\n Request extends JsonRpcRequest ? Json : void;\n\nexport type Next<Request extends JsonRpcCall> = (\n request?: Readonly<Request>,\n) => Promise<Readonly<ResultConstraint<Request>> | undefined>;\n\nexport type MiddlewareParams<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends MiddlewareContext = MiddlewareContext,\n> = {\n request: Readonly<Request>;\n context: Context;\n next: Next<Request>;\n};\n\nexport type JsonRpcMiddleware<\n Request extends JsonRpcCall = JsonRpcCall,\n Result extends ResultConstraint<Request> = ResultConstraint<Request>,\n Context extends ContextConstraint = MiddlewareContext,\n> = (\n params: MiddlewareParams<Request, Context>,\n) => Readonly<Result> | undefined | Promise<Readonly<Result> | undefined>;\n\ntype RequestState<Request extends JsonRpcCall> = {\n request: Request;\n result: Readonly<ResultConstraint<Request>> | undefined;\n};\n\ntype HandleOptions<Context extends MiddlewareContext> = {\n context?: Context;\n};\n\ntype ConstructorOptions<\n Request extends JsonRpcCall,\n Context extends MiddlewareContext,\n> = {\n middleware: NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >;\n};\n\nexport type RequestOf<Middleware> =\n Middleware extends JsonRpcMiddleware<\n infer Request,\n ResultConstraint<infer Request>,\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n >\n ? Request\n : never;\n\ntype ContextOf<Middleware> =\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Middleware extends JsonRpcMiddleware<any, ResultConstraint<any>, infer C>\n ? C\n : never;\n\nexport type MergedContextOf<\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Middleware extends JsonRpcMiddleware<any, any, any>,\n> = MergeContexts<ContextOf<Middleware>>;\n\nconst INVALID_ENGINE = Symbol('Invalid engine');\n\n/**\n * An internal type for invalid engines that explains why the engine is invalid.\n *\n * @template Message - The message explaining why the engine is invalid.\n */\ntype InvalidEngine<Message extends string> = { [INVALID_ENGINE]: Message };\n\n/**\n * A JSON-RPC request and response processor.\n *\n * Give it a stack of middleware, pass it requests, and get back responses.\n *\n * #### Requests vs. notifications\n *\n * JSON-RPC requests come in two flavors:\n *\n * - [Requests](https://www.jsonrpc.org/specification#request_object), i.e. request objects _with_ an `id`\n * - [Notifications](https://www.jsonrpc.org/specification#notification), i.e. request objects _without_ an `id`\n *\n * For requests, one of the engine's middleware must \"end\" the request by returning a non-`undefined` result,\n * or {@link handle} will throw an error:\n *\n * For notifications, on the other hand, one of the engine's middleware must return `undefined` to end the request,\n * and any non-`undefined` return values will cause an error:\n *\n * @template Request - The type of request to handle.\n * @template Result - The type of result to return.\n *\n * @example\n * ```ts\n * const engine = JsonRpcEngineV2.create({\n * middleware,\n * });\n *\n * try {\n * const result = await engine.handle(request);\n * // Handle result\n * } catch (error) {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcEngineV2<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends ContextConstraint = MiddlewareContext,\n> {\n #middleware: Readonly<\n NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >\n >;\n\n #isDestroyed = false;\n\n // See .create() for why this is private.\n private constructor({ middleware }: ConstructorOptions<Request, Context>) {\n this.#middleware = [...middleware];\n }\n\n // We use a static factory method in order to construct a supertype of all middleware contexts,\n // which enables us to instantiate an engine despite different middleware expecting different\n // context types.\n /**\n * Create a new JSON-RPC engine.\n *\n * @throws If the middleware array is empty.\n * @param options - The options for the engine.\n * @param options.middleware - The middleware to use.\n * @returns The JSON-RPC engine.\n */\n static create<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n >({ middleware }: { middleware: Middleware[] }) {\n // We can't use NonEmptyArray for the params because it ruins type inference.\n if (middleware.length === 0) {\n throw new JsonRpcEngineError('Middleware array cannot be empty');\n }\n\n type MergedContext = MergedContextOf<Middleware>;\n type InputRequest = RequestOf<Middleware>;\n const mw = middleware as unknown as NonEmptyArray<\n JsonRpcMiddleware<\n InputRequest,\n ResultConstraint<InputRequest>,\n MergedContext\n >\n >;\n return new JsonRpcEngineV2<InputRequest, MergedContext>({\n middleware: mw,\n }) as MergedContext extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<InputRequest, MergedContext>;\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * @param request - The JSON-RPC request to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response.\n */\n async handle(\n request: Extract<Request, JsonRpcRequest> extends never\n ? never\n : Extract<Request, JsonRpcRequest>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcRequest> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC notification. Notifications do not return a result.\n *\n * @param notification - The JSON-RPC notification to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n */\n async handle(\n notification: Extract<Request, JsonRpcNotification> extends never\n ? never\n : WithoutId<Extract<Request, JsonRpcNotification>>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcNotification> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC call, i.e. request or notification. Requests return a\n * result, notifications do not.\n *\n * @param call - The JSON-RPC call to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response, or `undefined` if the call is a notification.\n */\n async handle(\n call: MixedParam<Request>,\n options?: HandleOptions<Context>,\n ): Promise<ResultConstraint<Request> | void>;\n\n async handle(\n request: Request,\n { context }: HandleOptions<Context> = {},\n ): Promise<Readonly<ResultConstraint<Request>> | void> {\n const isReq = isRequest(request);\n const { result } = await this.#handle(request, context);\n\n if (isReq && result === undefined) {\n throw new JsonRpcEngineError(\n `Nothing ended request: ${stringify(request)}`,\n );\n }\n return result;\n }\n\n /**\n * Handle a JSON-RPC request. Throws if a middleware performs an invalid\n * operation. Permits returning an `undefined` result.\n *\n * @param originalRequest - The JSON-RPC request to handle.\n * @param context - The context to pass to the middleware.\n * @returns The result from the middleware.\n */\n async #handle(\n originalRequest: Request,\n context: Context = new MiddlewareContext() as Context,\n ): Promise<RequestState<Request>> {\n this.#assertIsNotDestroyed();\n\n deepFreeze(originalRequest);\n\n const state: RequestState<Request> = {\n request: originalRequest,\n result: undefined,\n };\n const middlewareIterator = this.#makeMiddlewareIterator();\n const firstMiddleware = middlewareIterator.next().value;\n\n const makeNext = this.#makeNextFactory(middlewareIterator, state, context);\n\n const result = await firstMiddleware({\n request: originalRequest,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state;\n }\n\n /**\n * Create a factory of `next()` functions for use with a particular request.\n * The factory is recursive, and a new `next()` is created for each middleware\n * invocation.\n *\n * @param middlewareIterator - The iterator of middleware for the current\n * request.\n * @param state - The current values of the request and result.\n * @param context - The context to pass to the middleware.\n * @returns The `next()` function factory.\n */\n #makeNextFactory(\n middlewareIterator: Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >,\n state: RequestState<Request>,\n context: Context,\n ): () => Next<Request> {\n const makeNext = (): Next<Request> => {\n let wasCalled = false;\n\n const next = async (\n request: Request = state.request,\n ): Promise<Readonly<ResultConstraint<Request>> | undefined> => {\n if (wasCalled) {\n throw new JsonRpcEngineError(\n `Middleware attempted to call next() multiple times for request: ${stringify(request)}`,\n );\n }\n wasCalled = true;\n\n if (request !== state.request) {\n this.#assertValidNextRequest(state.request, request);\n state.request = deepFreeze(request);\n }\n\n const { value: nextMiddleware, done } = middlewareIterator.next();\n if (done) {\n // This will cause the last middleware to return `undefined`. See the class\n // JSDoc or package README for more details.\n return undefined;\n }\n\n const result = await nextMiddleware({\n request,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state.result;\n };\n return next;\n };\n\n return makeNext;\n }\n\n #makeMiddlewareIterator(): Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n > {\n return this.#middleware[Symbol.iterator]();\n }\n\n /**\n * Validate the result from a middleware and, if it's a new value, update the\n * current result.\n *\n * @param result - The result from the middleware.\n * @param state - The current values of the request and result.\n */\n #updateResult(\n result:\n | Readonly<ResultConstraint<Request>>\n | ResultConstraint<Request>\n | void,\n state: RequestState<Request>,\n ): void {\n if (isNotification(state.request) && result !== undefined) {\n throw new JsonRpcEngineError(\n `Result returned for notification: ${stringify(state.request)}`,\n );\n }\n\n if (result !== undefined && result !== state.result) {\n if (typeof result === 'object' && result !== null) {\n deepFreeze(result);\n }\n state.result = result;\n }\n }\n\n /**\n * Assert that a request modified by a middleware is valid.\n *\n * @param currentRequest - The current request.\n * @param nextRequest - The next request.\n */\n #assertValidNextRequest(currentRequest: Request, nextRequest: Request): void {\n if (nextRequest.jsonrpc !== currentRequest.jsonrpc) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"jsonrpc\" for request: ${stringify(currentRequest)}`,\n );\n }\n if (\n hasProperty(nextRequest, 'id') !== hasProperty(currentRequest, 'id') ||\n // @ts-expect-error - \"id\" does not exist on notifications, but we can still\n // check the value of the property at runtime.\n nextRequest.id !== currentRequest.id\n ) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"id\" for request: ${stringify(currentRequest)}`,\n );\n }\n }\n\n /**\n * Convert the engine into a JSON-RPC middleware.\n *\n * @returns The JSON-RPC middleware.\n */\n asMiddleware(): JsonRpcMiddleware<\n Request,\n ResultConstraint<Request>,\n Context\n > {\n this.#assertIsNotDestroyed();\n\n return async ({ request, context, next }) => {\n const { result, request: finalRequest } = await this.#handle(\n request,\n context,\n );\n return result === undefined ? await next(finalRequest) : result;\n };\n }\n\n /**\n * Destroy the engine. Calls the `destroy()` method of any middleware that has\n * one. Attempting to use the engine after destroying it will throw an error.\n */\n async destroy(): Promise<void> {\n if (this.#isDestroyed) {\n return;\n }\n this.#isDestroyed = true;\n\n const destructionPromise = Promise.all(\n this.#middleware.map(async (middleware) => {\n if (\n // Intentionally using `in` to walk the prototype chain.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n return middleware.destroy();\n }\n return undefined;\n }),\n );\n this.#middleware = [] as never;\n await destructionPromise;\n }\n\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new JsonRpcEngineError('Engine is destroyed');\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"JsonRpcEngineV2.mjs","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,OAAO,EAKL,WAAW,EACZ,wBAAwB;AACzB,OAAO,WAAU,2BAA2B;;AAG5C,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AACxD,OAAO,EACL,cAAc,EACd,SAAS,EACT,kBAAkB,EAClB,SAAS,EACV,oBAAgB;AAkGjB,MAAM,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAShD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,OAAO,eAAe;IAY1B,yCAAyC;IACzC,YAAoB,EAAE,UAAU,EAAwC;;QATxE,8CAIE;QAEF,uCAAe,KAAK,EAAC;QAInB,uBAAA,IAAI,+BAAe,CAAC,GAAG,UAAU,CAAC,MAAA,CAAC;IACrC,CAAC;IAED,+FAA+F;IAC/F,6FAA6F;IAC7F,iBAAiB;IACjB;;;;;;;OAOG;IACH,MAAM,CAAC,MAAM,CASX,EAAE,UAAU,EAAgC;QAC5C,6EAA6E;QAC7E,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE;YAC3B,MAAM,IAAI,kBAAkB,CAAC,kCAAkC,CAAC,CAAC;SAClE;QAID,MAAM,EAAE,GAAG,UAMV,CAAC;QACF,OAAO,IAAI,eAAe,CAA8B;YACtD,UAAU,EAAE,E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K,CAAC,MAAM,GAAG,MAAM,CAAC;KACvB;AACH,CAAC,6FAQuB,cAAuB,EAAE,WAAoB;IACnE,IAAI,WAAW,CAAC,OAAO,KAAK,cAAc,CAAC,OAAO,EAAE;QAClD,MAAM,IAAI,kBAAkB,CAC1B,2EAA2E,SAAS,CAAC,cAAc,CAAC,EAAE,CACvG,CAAC;KACH;IACD,IACE,WAAW,CAAC,WAAW,EAAE,IAAI,CAAC,KAAK,WAAW,CAAC,cAAc,EAAE,IAAI,CAAC;QACpE,4EAA4E;QAC5E,8CAA8C;QAC9C,WAAW,CAAC,EAAE,KAAK,cAAc,CAAC,EAAE,EACpC;QACA,MAAM,IAAI,kBAAkB,CAC1B,sEAAsE,SAAS,CAAC,cAAc,CAAC,EAAE,CAClG,CAAC;KACH;AACH,CAAC;IAkDC,IAAI,uBAAA,IAAI,oCAAa,EAAE;QACrB,MAAM,IAAI,kBAAkB,CAAC,qBAAqB,CAAC,CAAC;KACrD;AACH,CAAC","sourcesContent":["import {\n type Json,\n type JsonRpcRequest,\n type JsonRpcNotification,\n type NonEmptyArray,\n hasProperty,\n} from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\n\nimport type { ContextConstraint, MergeContexts } from './MiddlewareContext';\nimport { MiddlewareContext } from './MiddlewareContext';\nimport {\n isNotification,\n isRequest,\n JsonRpcEngineError,\n stringify,\n} from './utils';\nimport type { JsonRpcCall } from './utils';\n\n// Helper to forbid `id` on notifications\ntype WithoutId<Request extends JsonRpcCall> = Request & { id?: never };\n\n// Helper to enable JsonRpcCall overload of handle()\ntype MixedParam<Request extends JsonRpcCall> = [\n Extract<Request, JsonRpcRequest>,\n] extends [never]\n ? never\n : [Extract<Request, JsonRpcNotification>] extends [never]\n ? never\n :\n | Extract<Request, JsonRpcRequest>\n | WithoutId<Extract<Request, JsonRpcNotification>>;\n\nexport type ResultConstraint<Request extends JsonRpcCall> =\n Request extends JsonRpcRequest ? Json : void;\n\nexport type Next<Request extends JsonRpcCall> = (\n request?: Readonly<Request>,\n) => Promise<Readonly<ResultConstraint<Request>> | undefined>;\n\nexport type MiddlewareParams<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends MiddlewareContext = MiddlewareContext,\n> = {\n request: Readonly<Request>;\n context: Context;\n next: Next<Request>;\n};\n\nexport type JsonRpcMiddleware<\n Request extends JsonRpcCall = JsonRpcCall,\n Result extends ResultConstraint<Request> = ResultConstraint<Request>,\n Context extends ContextConstraint = MiddlewareContext,\n> = (\n params: MiddlewareParams<Request, Context>,\n) => Readonly<Result> | undefined | Promise<Readonly<Result> | undefined>;\n\ntype RequestState<Request extends JsonRpcCall> = {\n request: Request;\n result: Readonly<ResultConstraint<Request>> | undefined;\n};\n\ntype HandleOptions<Context extends MiddlewareContext> = {\n context?: Context;\n};\n\ntype ConstructorOptions<\n Request extends JsonRpcCall,\n Context extends MiddlewareContext,\n> = {\n middleware: NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >;\n};\n\n/**\n * The request type of a middleware.\n */\nexport type RequestOf<Middleware> =\n Middleware extends JsonRpcMiddleware<\n infer Request,\n ResultConstraint<infer Request>,\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n >\n ? Request\n : never;\n\ntype ContextOf<Middleware> =\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Middleware extends JsonRpcMiddleware<any, ResultConstraint<any>, infer C>\n ? C\n : never;\n\n/**\n * A constraint for {@link JsonRpcMiddleware} generic parameters.\n */\n// Non-polluting `any` constraint.\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type MiddlewareConstraint = JsonRpcMiddleware<\n any,\n ResultConstraint<any>,\n MiddlewareContext<any>\n>;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/**\n * The context supertype of a middleware type.\n */\nexport type MergedContextOf<Middleware extends MiddlewareConstraint> =\n MergeContexts<ContextOf<Middleware>>;\n\nconst INVALID_ENGINE = Symbol('Invalid engine');\n\n/**\n * An internal type for invalid engines that explains why the engine is invalid.\n *\n * @template Message - The message explaining why the engine is invalid.\n */\ntype InvalidEngine<Message extends string> = { [INVALID_ENGINE]: Message };\n\n/**\n * A JSON-RPC request and response processor.\n *\n * Give it a stack of middleware, pass it requests, and get back responses.\n *\n * #### Requests vs. notifications\n *\n * JSON-RPC requests come in two flavors:\n *\n * - [Requests](https://www.jsonrpc.org/specification#request_object), i.e. request objects _with_ an `id`\n * - [Notifications](https://www.jsonrpc.org/specification#notification), i.e. request objects _without_ an `id`\n *\n * For requests, one of the engine's middleware must \"end\" the request by returning a non-`undefined` result,\n * or {@link handle} will throw an error:\n *\n * For notifications, on the other hand, one of the engine's middleware must return `undefined` to end the request,\n * and any non-`undefined` return values will cause an error:\n *\n * @template Request - The type of request to handle.\n * @template Result - The type of result to return.\n *\n * @example\n * ```ts\n * const engine = JsonRpcEngineV2.create({\n * middleware,\n * });\n *\n * try {\n * const result = await engine.handle(request);\n * // Handle result\n * } catch (error) {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcEngineV2<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends ContextConstraint = MiddlewareContext,\n> {\n #middleware: Readonly<\n NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >\n >;\n\n #isDestroyed = false;\n\n // See .create() for why this is private.\n private constructor({ middleware }: ConstructorOptions<Request, Context>) {\n this.#middleware = [...middleware];\n }\n\n // We use a static factory method in order to construct a supertype of all middleware contexts,\n // which enables us to instantiate an engine despite different middleware expecting different\n // context types.\n /**\n * Create a new JSON-RPC engine.\n *\n * @throws If the middleware array is empty.\n * @param options - The options for the engine.\n * @param options.middleware - The middleware to use.\n * @returns The JSON-RPC engine.\n */\n static create<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n >({ middleware }: { middleware: Middleware[] }) {\n // We can't use NonEmptyArray for the params because it ruins type inference.\n if (middleware.length === 0) {\n throw new JsonRpcEngineError('Middleware array cannot be empty');\n }\n\n type MergedContext = MergedContextOf<Middleware>;\n type InputRequest = RequestOf<Middleware>;\n const mw = middleware as unknown as NonEmptyArray<\n JsonRpcMiddleware<\n InputRequest,\n ResultConstraint<InputRequest>,\n MergedContext\n >\n >;\n return new JsonRpcEngineV2<InputRequest, MergedContext>({\n middleware: mw,\n }) as MergedContext extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<InputRequest, MergedContext>;\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * @param request - The JSON-RPC request to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response.\n */\n async handle(\n request: Extract<Request, JsonRpcRequest> extends never\n ? never\n : Extract<Request, JsonRpcRequest>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcRequest> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC notification. Notifications do not return a result.\n *\n * @param notification - The JSON-RPC notification to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n */\n async handle(\n notification: Extract<Request, JsonRpcNotification> extends never\n ? never\n : WithoutId<Extract<Request, JsonRpcNotification>>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcNotification> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC call, i.e. request or notification. Requests return a\n * result, notifications do not.\n *\n * @param call - The JSON-RPC call to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response, or `undefined` if the call is a notification.\n */\n async handle(\n call: MixedParam<Request>,\n options?: HandleOptions<Context>,\n ): Promise<ResultConstraint<Request> | void>;\n\n async handle(\n request: Request,\n { context }: HandleOptions<Context> = {},\n ): Promise<Readonly<ResultConstraint<Request>> | void> {\n const isReq = isRequest(request);\n const { result } = await this.#handle(request, context);\n\n if (isReq && result === undefined) {\n throw new JsonRpcEngineError(\n `Nothing ended request: ${stringify(request)}`,\n );\n }\n return result;\n }\n\n /**\n * Handle a JSON-RPC request. Throws if a middleware performs an invalid\n * operation. Permits returning an `undefined` result.\n *\n * @param originalRequest - The JSON-RPC request to handle.\n * @param context - The context to pass to the middleware.\n * @returns The result from the middleware.\n */\n async #handle(\n originalRequest: Request,\n context: Context = new MiddlewareContext() as Context,\n ): Promise<RequestState<Request>> {\n this.#assertIsNotDestroyed();\n\n deepFreeze(originalRequest);\n\n const state: RequestState<Request> = {\n request: originalRequest,\n result: undefined,\n };\n const middlewareIterator = this.#makeMiddlewareIterator();\n const firstMiddleware = middlewareIterator.next().value;\n\n const makeNext = this.#makeNextFactory(middlewareIterator, state, context);\n\n const result = await firstMiddleware({\n request: originalRequest,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state;\n }\n\n /**\n * Create a factory of `next()` functions for use with a particular request.\n * The factory is recursive, and a new `next()` is created for each middleware\n * invocation.\n *\n * @param middlewareIterator - The iterator of middleware for the current\n * request.\n * @param state - The current values of the request and result.\n * @param context - The context to pass to the middleware.\n * @returns The `next()` function factory.\n */\n #makeNextFactory(\n middlewareIterator: Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >,\n state: RequestState<Request>,\n context: Context,\n ): () => Next<Request> {\n const makeNext = (): Next<Request> => {\n let wasCalled = false;\n\n const next = async (\n request: Request = state.request,\n ): Promise<Readonly<ResultConstraint<Request>> | undefined> => {\n if (wasCalled) {\n throw new JsonRpcEngineError(\n `Middleware attempted to call next() multiple times for request: ${stringify(request)}`,\n );\n }\n wasCalled = true;\n\n if (request !== state.request) {\n this.#assertValidNextRequest(state.request, request);\n state.request = deepFreeze(request);\n }\n\n const { value: nextMiddleware, done } = middlewareIterator.next();\n if (done) {\n // This will cause the last middleware to return `undefined`. See the class\n // JSDoc or package README for more details.\n return undefined;\n }\n\n const result = await nextMiddleware({\n request,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state.result;\n };\n return next;\n };\n\n return makeNext;\n }\n\n #makeMiddlewareIterator(): Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n > {\n return this.#middleware[Symbol.iterator]();\n }\n\n /**\n * Validate the result from a middleware and, if it's a new value, update the\n * current result.\n *\n * @param result - The result from the middleware.\n * @param state - The current values of the request and result.\n */\n #updateResult(\n result:\n | Readonly<ResultConstraint<Request>>\n | ResultConstraint<Request>\n | void,\n state: RequestState<Request>,\n ): void {\n if (isNotification(state.request) && result !== undefined) {\n throw new JsonRpcEngineError(\n `Result returned for notification: ${stringify(state.request)}`,\n );\n }\n\n if (result !== undefined && result !== state.result) {\n if (typeof result === 'object' && result !== null) {\n deepFreeze(result);\n }\n state.result = result;\n }\n }\n\n /**\n * Assert that a request modified by a middleware is valid.\n *\n * @param currentRequest - The current request.\n * @param nextRequest - The next request.\n */\n #assertValidNextRequest(currentRequest: Request, nextRequest: Request): void {\n if (nextRequest.jsonrpc !== currentRequest.jsonrpc) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"jsonrpc\" for request: ${stringify(currentRequest)}`,\n );\n }\n if (\n hasProperty(nextRequest, 'id') !== hasProperty(currentRequest, 'id') ||\n // @ts-expect-error - \"id\" does not exist on notifications, but we can still\n // check the value of the property at runtime.\n nextRequest.id !== currentRequest.id\n ) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"id\" for request: ${stringify(currentRequest)}`,\n );\n }\n }\n\n /**\n * Convert the engine into a JSON-RPC middleware.\n *\n * @returns The JSON-RPC middleware.\n */\n asMiddleware(): JsonRpcMiddleware<\n Request,\n ResultConstraint<Request>,\n Context\n > {\n this.#assertIsNotDestroyed();\n\n return async ({ request, context, next }) => {\n const { result, request: finalRequest } = await this.#handle(\n request,\n context,\n );\n return result === undefined ? await next(finalRequest) : result;\n };\n }\n\n /**\n * Destroy the engine. Calls the `destroy()` method of any middleware that has\n * one. Attempting to use the engine after destroying it will throw an error.\n */\n async destroy(): Promise<void> {\n if (this.#isDestroyed) {\n return;\n }\n this.#isDestroyed = true;\n\n const destructionPromise = Promise.all(\n this.#middleware.map(async (middleware) => {\n if (\n // Intentionally using `in` to walk the prototype chain.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n return middleware.destroy();\n }\n return undefined;\n }),\n );\n this.#middleware = [] as never;\n await destructionPromise;\n }\n\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new JsonRpcEngineError('Engine is destroyed');\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcServer.cjs","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qDAAiE;AAQjE,2CAAwD;AAQxD,2DAAoD;AAEpD,oDAA6C;AAe7C,MAAM,OAAO,GAAG,KAAc,CAAC;AAE/B;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAa,aAAa;IAiBxB;;;;;;;;;;;;OAYG;IACH,YAAY,OAA4B;;QApB/B,wCAGP;QAEO,yCAA+B;QAgBtC,uBAAA,IAAI,0BAAY,OAAO,CAAC,OAAO,MAAA,CAAC;QAEhC,IAAI,IAAA,mBAAW,EAAC,OAAO,EAAE,QAAQ,CAAC,EAAE;YAClC,2DAA2D;YAC3D,uBAAA,IAAI,yBAAW,OAAO,CAAC,MAAM,MAAA,CAAC;SAC/B;aAAM;YACL,kGAAkG;YAClG,uBAAA,IAAI,yBAAW,iCAAe,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,EAAE,CAAC,MAAA,CAAC;SAC3E;IACH,CAAC;IAgDD,KAAK,CAAC,MAAM,CAAC,UAAmB;QAC9B,uEAAuE;QACvE,qEAAqE;QACrE,s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IAAI,SAAS,EAAE;QACZ,OAA0B,CAAC,EAAE,GAAG,IAAA,yBAAW,GAAE,CAAC;KAChD;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAWH;;;;;GAKG;AACH,SAAS,gBAAgB,CAAC,UAAmB;IAC3C,OAAO,CACL,IAAA,gBAAQ,EAAC,UAAU,CAAC;QACpB,IAAA,mBAAW,EAAC,UAAU,EAAE,QAAQ,CAAC;QACjC,OAAO,UAAU,CAAC,MAAM,KAAK,QAAQ;QACrC,cAAc,CAAC,UAAU,CAAC,CAC3B,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,SAAS,cAAc,CACrB,UAAmC;IAEnC,IAAI,IAAA,mBAAW,EAAC,UAAU,EAAE,QAAQ,CAAC,EAAE;QACrC,OAAO,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,IAAA,gBAAQ,EAAC,UAAU,CAAC,MAAM,CAAC,CAAC;KACxE;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;GAMG;AACH,SAAS,aAAa,CAAC,UAAmB;IACxC,IAAI,IAAA,gBAAQ,EAAC,UAAU,CAAC,IAAI,IAAA,mBAAW,EAAC,UAAU,EAAE,IAAI,CAAC,EAAE;QACzD,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;KAC9B;IACD,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import { rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type {\n JsonRpcNotification,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n NonEmptyArray,\n} from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport type {\n JsonRpcMiddleware,\n MergedContextOf,\n RequestOf,\n ResultConstraint,\n} from './JsonRpcEngineV2';\nimport { JsonRpcEngineV2 } from './JsonRpcEngineV2';\nimport type { JsonRpcCall } from './utils';\nimport { getUniqueId } from '../getUniqueId';\n\ntype OnError = (error: unknown) => void;\n\ntype Options<Middleware extends JsonRpcMiddleware> = {\n onError?: OnError;\n} & (\n | {\n engine: ReturnType<typeof JsonRpcEngineV2.create<Middleware>>;\n }\n | {\n middleware: NonEmptyArray<Middleware>;\n }\n);\n\nconst jsonrpc = '2.0' as const;\n\n/**\n * A JSON-RPC server that handles requests and notifications.\n *\n * Essentially wraps a {@link JsonRpcEngineV2} in order to create a conformant\n * yet permissive JSON-RPC 2.0 server.\n *\n * Note that the server will accept both requests and notifications via {@link handle},\n * even if the underlying engine is only able to handle one or the other.\n *\n * @example\n * ```ts\n * const server = new JsonRpcServer({\n * engine,\n * onError,\n * });\n *\n * const response = await server.handle(request);\n * if ('result' in response) {\n * // Handle result\n * } else {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcServer<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n> {\n readonly #engine: JsonRpcEngineV2<\n RequestOf<Middleware>,\n MergedContextOf<Middleware>\n >;\n\n readonly #onError?: OnError | undefined;\n\n /**\n * Construct a new JSON-RPC server.\n *\n * @param options - The options for the server.\n * @param options.onError - The callback to handle errors thrown by the\n * engine. Errors always result in a failed response object, containing a\n * JSON-RPC 2.0 serialized version of the original error. If you need to\n * access the original error, use the `onError` callback.\n * @param options.engine - The engine to use. Mutually exclusive with\n * `middleware`.\n * @param options.middleware - The middleware to use. Mutually exclusive with\n * `engine`.\n */\n constructor(options: Options<Middleware>) {\n this.#onError = options.onError;\n\n if (hasProperty(options, 'engine')) {\n // @ts-expect-error - hasProperty fails to narrow the type.\n this.#engine = options.engine;\n } else {\n // @ts-expect-error - TypeScript complains that engine is of the wrong type, but clearly it's not.\n this.#engine = JsonRpcEngineV2.create({ middleware: options.middleware });\n }\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * This method never throws. For requests, a response is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine can only handle notifications.\n *\n * @param request - The request to handle.\n * @returns The JSON-RPC response.\n */\n async handle(request: JsonRpcRequest): Promise<JsonRpcResponse>;\n\n /**\n * Handle a JSON-RPC notification.\n *\n * This method never throws. For notifications, `undefined` is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine cannot handle notifications.\n *\n * @param notification - The notification to handle.\n */\n async handle(notification: JsonRpcNotification): Promise<void>;\n\n /**\n * Handle an alleged JSON-RPC request or notification. Permits any plain\n * object with `{ method: string }`, so long as any present JSON-RPC 2.0\n * properties are valid. If the object has an `id` property, it will be\n * treated as a request, otherwise it will be treated as a notification.\n *\n * This method never throws. All errors are passed to the engine's\n * `onError` callback. A JSON-RPC response is always returned for requests,\n * and `undefined` is returned for notifications.\n *\n * **WARNING**: The request will fail if its coerced type (i.e. request or\n * response) is not of the type expected by the underlying engine.\n *\n * @param rawRequest - The raw request to handle.\n * @returns The JSON-RPC response, or `undefined` if the request is a\n * notification.\n */\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void>;\n\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void> {\n // If rawRequest is not a notification, the originalId will be attached\n // to the response. We attach our own, trusted id in #coerceRequest()\n // while the request is being handled.\n const [originalId, isRequest] = getOriginalId(rawRequest);\n\n try {\n const request = this.#coerceRequest(rawRequest, isRequest);\n // @ts-expect-error - The request may not be of the type expected by the engine,\n // and we intentionally allow this to happen.\n const result = await this.#engine.handle(request);\n\n if (result !== undefined) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n result,\n };\n }\n } catch (error) {\n this.#onError?.(error);\n\n if (isRequest) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n error: serializeError(error, {\n shouldIncludeStack: false,\n shouldPreserveMessage: true,\n }),\n };\n }\n }\n return undefined;\n }\n\n #coerceRequest(rawRequest: unknown, isRequest: boolean): JsonRpcCall {\n if (!isMinimalRequest(rawRequest)) {\n throw rpcErrors.invalidRequest({\n data: {\n request: rawRequest,\n },\n });\n }\n\n const request: JsonRpcCall = {\n jsonrpc,\n method: rawRequest.method,\n };\n\n if (hasProperty(rawRequest, 'params')) {\n request.params = rawRequest.params as JsonRpcParams;\n }\n\n if (isRequest) {\n (request as JsonRpcRequest).id = getUniqueId();\n }\n\n return request;\n }\n}\n\n/**\n * The most minimally conformant request object that we will accept.\n */\ntype MinimalRequest = {\n method: string;\n params?: JsonRpcParams;\n} & Record<string, unknown>;\n\n/**\n * Check if an unvalidated request is a minimal request.\n *\n * @param rawRequest - The raw request to check.\n * @returns `true` if the request is a {@link MinimalRequest}, `false` otherwise.\n */\nfunction isMinimalRequest(rawRequest: unknown): rawRequest is MinimalRequest {\n return (\n isObject(rawRequest) &&\n hasProperty(rawRequest, 'method') &&\n typeof rawRequest.method === 'string' &&\n hasValidParams(rawRequest)\n );\n}\n\n/**\n * Check if a request has valid params, i.e. an array or object.\n * The contents of the params are not inspected.\n *\n * @param rawRequest - The request to check.\n * @returns `true` if the request has valid params, `false` otherwise.\n */\nfunction hasValidParams(\n rawRequest: Record<string, unknown>,\n): rawRequest is { params?: JsonRpcParams } {\n if (hasProperty(rawRequest, 'params')) {\n return Array.isArray(rawRequest.params) || isObject(rawRequest.params);\n }\n return true;\n}\n\n/**\n * Get the original id from a request.\n *\n * @param rawRequest - The request to get the original id from.\n * @returns The original id and a boolean indicating if the request is a request\n * (as opposed to a notification).\n */\nfunction getOriginalId(rawRequest: unknown): [unknown, boolean] {\n if (isObject(rawRequest) && hasProperty(rawRequest, 'id')) {\n return [rawRequest.id, true];\n }\n return [undefined, false];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"JsonRpcServer.cjs","sourceRoot":"","sources":["../../src/v2/J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CAAC,IAAI,IAAA,gBAAQ,EAAC,UAAU,CAAC,MAAM,CAAC,CAAC;KACxE;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;GAMG;AACH,SAAS,aAAa,CAAC,UAAmB;IACxC,IAAI,IAAA,gBAAQ,EAAC,UAAU,CAAC,IAAI,IAAA,mBAAW,EAAC,UAAU,EAAE,IAAI,CAAC,EAAE;QACzD,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;KAC9B;IACD,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import { rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type {\n JsonRpcNotification,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n NonEmptyArray,\n} from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport type {\n JsonRpcMiddleware,\n MergedContextOf,\n MiddlewareConstraint,\n RequestOf,\n} from './JsonRpcEngineV2';\nimport { JsonRpcEngineV2 } from './JsonRpcEngineV2';\nimport type { JsonRpcCall } from './utils';\nimport { getUniqueId } from '../getUniqueId';\n\ntype OnError = (error: unknown) => void;\n\ntype Options<Middleware extends MiddlewareConstraint> = {\n onError?: OnError;\n} & (\n | {\n engine: ReturnType<typeof JsonRpcEngineV2.create<Middleware>>;\n }\n | {\n middleware: NonEmptyArray<Middleware>;\n }\n);\n\nconst jsonrpc = '2.0' as const;\n\n/**\n * A JSON-RPC server that handles requests and notifications.\n *\n * Essentially wraps a {@link JsonRpcEngineV2} in order to create a conformant\n * yet permissive JSON-RPC 2.0 server.\n *\n * Note that the server will accept both requests and notifications via {@link handle},\n * even if the underlying engine is only able to handle one or the other.\n *\n * @example\n * ```ts\n * const server = new JsonRpcServer({\n * engine,\n * onError,\n * });\n *\n * const response = await server.handle(request);\n * if ('result' in response) {\n * // Handle result\n * } else {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcServer<\n Middleware extends MiddlewareConstraint = JsonRpcMiddleware,\n> {\n readonly #engine: JsonRpcEngineV2<\n RequestOf<Middleware>,\n MergedContextOf<Middleware>\n >;\n\n readonly #onError?: OnError | undefined;\n\n /**\n * Construct a new JSON-RPC server.\n *\n * @param options - The options for the server.\n * @param options.onError - The callback to handle errors thrown by the\n * engine. Errors always result in a failed response object, containing a\n * JSON-RPC 2.0 serialized version of the original error. If you need to\n * access the original error, use the `onError` callback.\n * @param options.engine - The engine to use. Mutually exclusive with\n * `middleware`.\n * @param options.middleware - The middleware to use. Mutually exclusive with\n * `engine`.\n */\n constructor(options: Options<Middleware>) {\n this.#onError = options.onError;\n\n if (hasProperty(options, 'engine')) {\n // @ts-expect-error - hasProperty fails to narrow the type.\n this.#engine = options.engine;\n } else {\n // @ts-expect-error - TypeScript complains that engine is of the wrong type, but clearly it's not.\n this.#engine = JsonRpcEngineV2.create({ middleware: options.middleware });\n }\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * This method never throws. For requests, a response is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine can only handle notifications.\n *\n * @param request - The request to handle.\n * @returns The JSON-RPC response.\n */\n async handle(request: JsonRpcRequest): Promise<JsonRpcResponse>;\n\n /**\n * Handle a JSON-RPC notification.\n *\n * This method never throws. For notifications, `undefined` is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine cannot handle notifications.\n *\n * @param notification - The notification to handle.\n */\n async handle(notification: JsonRpcNotification): Promise<void>;\n\n /**\n * Handle an alleged JSON-RPC request or notification. Permits any plain\n * object with `{ method: string }`, so long as any present JSON-RPC 2.0\n * properties are valid. If the object has an `id` property, it will be\n * treated as a request, otherwise it will be treated as a notification.\n *\n * This method never throws. All errors are passed to the engine's\n * `onError` callback. A JSON-RPC response is always returned for requests,\n * and `undefined` is returned for notifications.\n *\n * **WARNING**: The request will fail if its coerced type (i.e. request or\n * response) is not of the type expected by the underlying engine.\n *\n * @param rawRequest - The raw request to handle.\n * @returns The JSON-RPC response, or `undefined` if the request is a\n * notification.\n */\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void>;\n\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void> {\n // If rawRequest is not a notification, the originalId will be attached\n // to the response. We attach our own, trusted id in #coerceRequest()\n // while the request is being handled.\n const [originalId, isRequest] = getOriginalId(rawRequest);\n\n try {\n const request = this.#coerceRequest(rawRequest, isRequest);\n // @ts-expect-error - The request may not be of the type expected by the engine,\n // and we intentionally allow this to happen.\n const result = await this.#engine.handle(request);\n\n if (result !== undefined) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n result,\n };\n }\n } catch (error) {\n this.#onError?.(error);\n\n if (isRequest) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n error: serializeError(error, {\n shouldIncludeStack: false,\n shouldPreserveMessage: true,\n }),\n };\n }\n }\n return undefined;\n }\n\n #coerceRequest(rawRequest: unknown, isRequest: boolean): JsonRpcCall {\n if (!isMinimalRequest(rawRequest)) {\n throw rpcErrors.invalidRequest({\n data: {\n request: rawRequest,\n },\n });\n }\n\n const request: JsonRpcCall = {\n jsonrpc,\n method: rawRequest.method,\n };\n\n if (hasProperty(rawRequest, 'params')) {\n request.params = rawRequest.params as JsonRpcParams;\n }\n\n if (isRequest) {\n (request as JsonRpcRequest).id = getUniqueId();\n }\n\n return request;\n }\n}\n\n/**\n * The most minimally conformant request object that we will accept.\n */\ntype MinimalRequest = {\n method: string;\n params?: JsonRpcParams;\n} & Record<string, unknown>;\n\n/**\n * Check if an unvalidated request is a minimal request.\n *\n * @param rawRequest - The raw request to check.\n * @returns `true` if the request is a {@link MinimalRequest}, `false` otherwise.\n */\nfunction isMinimalRequest(rawRequest: unknown): rawRequest is MinimalRequest {\n return (\n isObject(rawRequest) &&\n hasProperty(rawRequest, 'method') &&\n typeof rawRequest.method === 'string' &&\n hasValidParams(rawRequest)\n );\n}\n\n/**\n * Check if a request has valid params, i.e. an array or object.\n * The contents of the params are not inspected.\n *\n * @param rawRequest - The request to check.\n * @returns `true` if the request has valid params, `false` otherwise.\n */\nfunction hasValidParams(\n rawRequest: Record<string, unknown>,\n): rawRequest is { params?: JsonRpcParams } {\n if (hasProperty(rawRequest, 'params')) {\n return Array.isArray(rawRequest.params) || isObject(rawRequest.params);\n }\n return true;\n}\n\n/**\n * Get the original id from a request.\n *\n * @param rawRequest - The request to get the original id from.\n * @returns The original id and a boolean indicating if the request is a request\n * (as opposed to a notification).\n */\nfunction getOriginalId(rawRequest: unknown): [unknown, boolean] {\n if (isObject(rawRequest) && hasProperty(rawRequest, 'id')) {\n return [rawRequest.id, true];\n }\n return [undefined, false];\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, NonEmptyArray } from "@metamask/utils";
|
|
2
|
-
import type { JsonRpcMiddleware,
|
|
2
|
+
import type { JsonRpcMiddleware, MiddlewareConstraint } from "./JsonRpcEngineV2.cjs";
|
|
3
3
|
import { JsonRpcEngineV2 } from "./JsonRpcEngineV2.cjs";
|
|
4
4
|
type OnError = (error: unknown) => void;
|
|
5
|
-
type Options<Middleware extends
|
|
5
|
+
type Options<Middleware extends MiddlewareConstraint> = {
|
|
6
6
|
onError?: OnError;
|
|
7
7
|
} & ({
|
|
8
8
|
engine: ReturnType<typeof JsonRpcEngineV2.create<Middleware>>;
|
|
@@ -33,7 +33,7 @@ type Options<Middleware extends JsonRpcMiddleware> = {
|
|
|
33
33
|
* }
|
|
34
34
|
* ```
|
|
35
35
|
*/
|
|
36
|
-
export declare class JsonRpcServer<Middleware extends
|
|
36
|
+
export declare class JsonRpcServer<Middleware extends MiddlewareConstraint = JsonRpcMiddleware> {
|
|
37
37
|
#private;
|
|
38
38
|
/**
|
|
39
39
|
* Construct a new JSON-RPC server.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcServer.d.cts","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,mBAAmB,EAEnB,cAAc,EACd,eAAe,EACf,aAAa,EACd,wBAAwB;AAGzB,OAAO,KAAK,EACV,iBAAiB,
|
|
1
|
+
{"version":3,"file":"JsonRpcServer.d.cts","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,mBAAmB,EAEnB,cAAc,EACd,eAAe,EACf,aAAa,EACd,wBAAwB;AAGzB,OAAO,KAAK,EACV,iBAAiB,EAEjB,oBAAoB,EAErB,8BAA0B;AAC3B,OAAO,EAAE,eAAe,EAAE,8BAA0B;AAIpD,KAAK,OAAO,GAAG,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;AAExC,KAAK,OAAO,CAAC,UAAU,SAAS,oBAAoB,IAAI;IACtD,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,GAAG,CACA;IACE,MAAM,EAAE,UAAU,CAAC,OAAO,eAAe,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;CAC/D,GACD;IACE,UAAU,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;CACvC,CACJ,CAAC;AAIF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,aAAa,CACxB,UAAU,SAAS,oBAAoB,GAAG,iBAAiB;;IAS3D;;;;;;;;;;;;OAYG;gBACS,OAAO,EAAE,OAAO,CAAC,UAAU,CAAC;IAYxC;;;;;;;;;;;OAWG;IACG,MAAM,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,eAAe,CAAC;IAE/D;;;;;;;;;;OAUG;IACG,MAAM,CAAC,YAAY,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IAE9D;;;;;;;;;;;;;;;;OAgBG;IACG,MAAM,CAAC,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;CAgEnE"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, NonEmptyArray } from "@metamask/utils";
|
|
2
|
-
import type { JsonRpcMiddleware,
|
|
2
|
+
import type { JsonRpcMiddleware, MiddlewareConstraint } from "./JsonRpcEngineV2.mjs";
|
|
3
3
|
import { JsonRpcEngineV2 } from "./JsonRpcEngineV2.mjs";
|
|
4
4
|
type OnError = (error: unknown) => void;
|
|
5
|
-
type Options<Middleware extends
|
|
5
|
+
type Options<Middleware extends MiddlewareConstraint> = {
|
|
6
6
|
onError?: OnError;
|
|
7
7
|
} & ({
|
|
8
8
|
engine: ReturnType<typeof JsonRpcEngineV2.create<Middleware>>;
|
|
@@ -33,7 +33,7 @@ type Options<Middleware extends JsonRpcMiddleware> = {
|
|
|
33
33
|
* }
|
|
34
34
|
* ```
|
|
35
35
|
*/
|
|
36
|
-
export declare class JsonRpcServer<Middleware extends
|
|
36
|
+
export declare class JsonRpcServer<Middleware extends MiddlewareConstraint = JsonRpcMiddleware> {
|
|
37
37
|
#private;
|
|
38
38
|
/**
|
|
39
39
|
* Construct a new JSON-RPC server.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcServer.d.mts","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,mBAAmB,EAEnB,cAAc,EACd,eAAe,EACf,aAAa,EACd,wBAAwB;AAGzB,OAAO,KAAK,EACV,iBAAiB,
|
|
1
|
+
{"version":3,"file":"JsonRpcServer.d.mts","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,mBAAmB,EAEnB,cAAc,EACd,eAAe,EACf,aAAa,EACd,wBAAwB;AAGzB,OAAO,KAAK,EACV,iBAAiB,EAE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EAAE;QACzD,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;KAC9B;IACD,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import { rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type {\n JsonRpcNotification,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n NonEmptyArray,\n} from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport type {\n JsonRpcMiddleware,\n MergedContextOf,\n RequestOf,\n ResultConstraint,\n} from './JsonRpcEngineV2';\nimport { JsonRpcEngineV2 } from './JsonRpcEngineV2';\nimport type { JsonRpcCall } from './utils';\nimport { getUniqueId } from '../getUniqueId';\n\ntype OnError = (error: unknown) => void;\n\ntype Options<Middleware extends JsonRpcMiddleware> = {\n onError?: OnError;\n} & (\n | {\n engine: ReturnType<typeof JsonRpcEngineV2.create<Middleware>>;\n }\n | {\n middleware: NonEmptyArray<Middleware>;\n }\n);\n\nconst jsonrpc = '2.0' as const;\n\n/**\n * A JSON-RPC server that handles requests and notifications.\n *\n * Essentially wraps a {@link JsonRpcEngineV2} in order to create a conformant\n * yet permissive JSON-RPC 2.0 server.\n *\n * Note that the server will accept both requests and notifications via {@link handle},\n * even if the underlying engine is only able to handle one or the other.\n *\n * @example\n * ```ts\n * const server = new JsonRpcServer({\n * engine,\n * onError,\n * });\n *\n * const response = await server.handle(request);\n * if ('result' in response) {\n * // Handle result\n * } else {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcServer<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n> {\n readonly #engine: JsonRpcEngineV2<\n RequestOf<Middleware>,\n MergedContextOf<Middleware>\n >;\n\n readonly #onError?: OnError | undefined;\n\n /**\n * Construct a new JSON-RPC server.\n *\n * @param options - The options for the server.\n * @param options.onError - The callback to handle errors thrown by the\n * engine. Errors always result in a failed response object, containing a\n * JSON-RPC 2.0 serialized version of the original error. If you need to\n * access the original error, use the `onError` callback.\n * @param options.engine - The engine to use. Mutually exclusive with\n * `middleware`.\n * @param options.middleware - The middleware to use. Mutually exclusive with\n * `engine`.\n */\n constructor(options: Options<Middleware>) {\n this.#onError = options.onError;\n\n if (hasProperty(options, 'engine')) {\n // @ts-expect-error - hasProperty fails to narrow the type.\n this.#engine = options.engine;\n } else {\n // @ts-expect-error - TypeScript complains that engine is of the wrong type, but clearly it's not.\n this.#engine = JsonRpcEngineV2.create({ middleware: options.middleware });\n }\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * This method never throws. For requests, a response is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine can only handle notifications.\n *\n * @param request - The request to handle.\n * @returns The JSON-RPC response.\n */\n async handle(request: JsonRpcRequest): Promise<JsonRpcResponse>;\n\n /**\n * Handle a JSON-RPC notification.\n *\n * This method never throws. For notifications, `undefined` is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine cannot handle notifications.\n *\n * @param notification - The notification to handle.\n */\n async handle(notification: JsonRpcNotification): Promise<void>;\n\n /**\n * Handle an alleged JSON-RPC request or notification. Permits any plain\n * object with `{ method: string }`, so long as any present JSON-RPC 2.0\n * properties are valid. If the object has an `id` property, it will be\n * treated as a request, otherwise it will be treated as a notification.\n *\n * This method never throws. All errors are passed to the engine's\n * `onError` callback. A JSON-RPC response is always returned for requests,\n * and `undefined` is returned for notifications.\n *\n * **WARNING**: The request will fail if its coerced type (i.e. request or\n * response) is not of the type expected by the underlying engine.\n *\n * @param rawRequest - The raw request to handle.\n * @returns The JSON-RPC response, or `undefined` if the request is a\n * notification.\n */\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void>;\n\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void> {\n // If rawRequest is not a notification, the originalId will be attached\n // to the response. We attach our own, trusted id in #coerceRequest()\n // while the request is being handled.\n const [originalId, isRequest] = getOriginalId(rawRequest);\n\n try {\n const request = this.#coerceRequest(rawRequest, isRequest);\n // @ts-expect-error - The request may not be of the type expected by the engine,\n // and we intentionally allow this to happen.\n const result = await this.#engine.handle(request);\n\n if (result !== undefined) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n result,\n };\n }\n } catch (error) {\n this.#onError?.(error);\n\n if (isRequest) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n error: serializeError(error, {\n shouldIncludeStack: false,\n shouldPreserveMessage: true,\n }),\n };\n }\n }\n return undefined;\n }\n\n #coerceRequest(rawRequest: unknown, isRequest: boolean): JsonRpcCall {\n if (!isMinimalRequest(rawRequest)) {\n throw rpcErrors.invalidRequest({\n data: {\n request: rawRequest,\n },\n });\n }\n\n const request: JsonRpcCall = {\n jsonrpc,\n method: rawRequest.method,\n };\n\n if (hasProperty(rawRequest, 'params')) {\n request.params = rawRequest.params as JsonRpcParams;\n }\n\n if (isRequest) {\n (request as JsonRpcRequest).id = getUniqueId();\n }\n\n return request;\n }\n}\n\n/**\n * The most minimally conformant request object that we will accept.\n */\ntype MinimalRequest = {\n method: string;\n params?: JsonRpcParams;\n} & Record<string, unknown>;\n\n/**\n * Check if an unvalidated request is a minimal request.\n *\n * @param rawRequest - The raw request to check.\n * @returns `true` if the request is a {@link MinimalRequest}, `false` otherwise.\n */\nfunction isMinimalRequest(rawRequest: unknown): rawRequest is MinimalRequest {\n return (\n isObject(rawRequest) &&\n hasProperty(rawRequest, 'method') &&\n typeof rawRequest.method === 'string' &&\n hasValidParams(rawRequest)\n );\n}\n\n/**\n * Check if a request has valid params, i.e. an array or object.\n * The contents of the params are not inspected.\n *\n * @param rawRequest - The request to check.\n * @returns `true` if the request has valid params, `false` otherwise.\n */\nfunction hasValidParams(\n rawRequest: Record<string, unknown>,\n): rawRequest is { params?: JsonRpcParams } {\n if (hasProperty(rawRequest, 'params')) {\n return Array.isArray(rawRequest.params) || isObject(rawRequest.params);\n }\n return true;\n}\n\n/**\n * Get the original id from a request.\n *\n * @param rawRequest - The request to get the original id from.\n * @returns The original id and a boolean indicating if the request is a request\n * (as opposed to a notification).\n */\nfunction getOriginalId(rawRequest: unknown): [unknown, boolean] {\n if (isObject(rawRequest) && hasProperty(rawRequest, 'id')) {\n return [rawRequest.id, true];\n }\n return [undefined, false];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"JsonRpcServer.mjs","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,6BAA6B;AAQjE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,wBAAwB;AAQxD,OAAO,EAAE,eAAe,EAAE,8BAA0B;AAEpD,OAAO,EAAE,WAAW,EAAE,2BAAuB;AAe7C,MAAM,OAAO,GAAG,KAAc,CAAC;AAE/B;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,OAAO,aAAa;IAUxB;;;;;;;;;;;;OAYG;IACH,YAAY,OAA4B;;QApB/B,wCAGP;QAEO,yCAA+B;QAgBtC,uBAAA,IAAI,0BAAY,OAAO,CAAC,OAAO,MAAA,CAAC;QAEhC,IAAI,WAAW,CAAC,OAAO,EAAE,QAAQ,CAAC,EAAE;YAClC,2DAA2D;YAC3D,uBAAA,IAAI,yBAAW,OAAO,CAAC,MAAM,MAAA,CAAC;SAC/B;aAAM;YACL,kGAAkG;YAClG,uBAAA,IAAI,yBAAW,eAAe,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,EAAE,CAAC,MAAA,CAAC;SAC3E;IACH,CAAC;IAgDD,KAAK,CAAC,MAAM,CAAC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AC;KACrD;IAED,IAAI,SAAS,EAAE;QACZ,OAA0B,CAAC,EAAE,GAAG,WAAW,EAAE,CAAC;KAChD;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAWH;;;;;GAKG;AACH,SAAS,gBAAgB,CAAC,UAAmB;IAC3C,OAAO,CACL,QAAQ,CAAC,UAAU,CAAC;QACpB,WAAW,CAAC,UAAU,EAAE,QAAQ,CAAC;QACjC,OAAO,UAAU,CAAC,MAAM,KAAK,QAAQ;QACrC,cAAc,CAAC,UAAU,CAAC,CAC3B,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,SAAS,cAAc,CACrB,UAAmC;IAEnC,IAAI,WAAW,CAAC,UAAU,EAAE,QAAQ,CAAC,EAAE;QACrC,OAAO,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;KACxE;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;GAMG;AACH,SAAS,aAAa,CAAC,UAAmB;IACxC,IAAI,QAAQ,CAAC,UAAU,CAAC,IAAI,WAAW,CAAC,UAAU,EAAE,IAAI,CAAC,EAAE;QACzD,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;KAC9B;IACD,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import { rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type {\n JsonRpcNotification,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n NonEmptyArray,\n} from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport type {\n JsonRpcMiddleware,\n MergedContextOf,\n MiddlewareConstraint,\n RequestOf,\n} from './JsonRpcEngineV2';\nimport { JsonRpcEngineV2 } from './JsonRpcEngineV2';\nimport type { JsonRpcCall } from './utils';\nimport { getUniqueId } from '../getUniqueId';\n\ntype OnError = (error: unknown) => void;\n\ntype Options<Middleware extends MiddlewareConstraint> = {\n onError?: OnError;\n} & (\n | {\n engine: ReturnType<typeof JsonRpcEngineV2.create<Middleware>>;\n }\n | {\n middleware: NonEmptyArray<Middleware>;\n }\n);\n\nconst jsonrpc = '2.0' as const;\n\n/**\n * A JSON-RPC server that handles requests and notifications.\n *\n * Essentially wraps a {@link JsonRpcEngineV2} in order to create a conformant\n * yet permissive JSON-RPC 2.0 server.\n *\n * Note that the server will accept both requests and notifications via {@link handle},\n * even if the underlying engine is only able to handle one or the other.\n *\n * @example\n * ```ts\n * const server = new JsonRpcServer({\n * engine,\n * onError,\n * });\n *\n * const response = await server.handle(request);\n * if ('result' in response) {\n * // Handle result\n * } else {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcServer<\n Middleware extends MiddlewareConstraint = JsonRpcMiddleware,\n> {\n readonly #engine: JsonRpcEngineV2<\n RequestOf<Middleware>,\n MergedContextOf<Middleware>\n >;\n\n readonly #onError?: OnError | undefined;\n\n /**\n * Construct a new JSON-RPC server.\n *\n * @param options - The options for the server.\n * @param options.onError - The callback to handle errors thrown by the\n * engine. Errors always result in a failed response object, containing a\n * JSON-RPC 2.0 serialized version of the original error. If you need to\n * access the original error, use the `onError` callback.\n * @param options.engine - The engine to use. Mutually exclusive with\n * `middleware`.\n * @param options.middleware - The middleware to use. Mutually exclusive with\n * `engine`.\n */\n constructor(options: Options<Middleware>) {\n this.#onError = options.onError;\n\n if (hasProperty(options, 'engine')) {\n // @ts-expect-error - hasProperty fails to narrow the type.\n this.#engine = options.engine;\n } else {\n // @ts-expect-error - TypeScript complains that engine is of the wrong type, but clearly it's not.\n this.#engine = JsonRpcEngineV2.create({ middleware: options.middleware });\n }\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * This method never throws. For requests, a response is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine can only handle notifications.\n *\n * @param request - The request to handle.\n * @returns The JSON-RPC response.\n */\n async handle(request: JsonRpcRequest): Promise<JsonRpcResponse>;\n\n /**\n * Handle a JSON-RPC notification.\n *\n * This method never throws. For notifications, `undefined` is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine cannot handle notifications.\n *\n * @param notification - The notification to handle.\n */\n async handle(notification: JsonRpcNotification): Promise<void>;\n\n /**\n * Handle an alleged JSON-RPC request or notification. Permits any plain\n * object with `{ method: string }`, so long as any present JSON-RPC 2.0\n * properties are valid. If the object has an `id` property, it will be\n * treated as a request, otherwise it will be treated as a notification.\n *\n * This method never throws. All errors are passed to the engine's\n * `onError` callback. A JSON-RPC response is always returned for requests,\n * and `undefined` is returned for notifications.\n *\n * **WARNING**: The request will fail if its coerced type (i.e. request or\n * response) is not of the type expected by the underlying engine.\n *\n * @param rawRequest - The raw request to handle.\n * @returns The JSON-RPC response, or `undefined` if the request is a\n * notification.\n */\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void>;\n\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void> {\n // If rawRequest is not a notification, the originalId will be attached\n // to the response. We attach our own, trusted id in #coerceRequest()\n // while the request is being handled.\n const [originalId, isRequest] = getOriginalId(rawRequest);\n\n try {\n const request = this.#coerceRequest(rawRequest, isRequest);\n // @ts-expect-error - The request may not be of the type expected by the engine,\n // and we intentionally allow this to happen.\n const result = await this.#engine.handle(request);\n\n if (result !== undefined) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n result,\n };\n }\n } catch (error) {\n this.#onError?.(error);\n\n if (isRequest) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n error: serializeError(error, {\n shouldIncludeStack: false,\n shouldPreserveMessage: true,\n }),\n };\n }\n }\n return undefined;\n }\n\n #coerceRequest(rawRequest: unknown, isRequest: boolean): JsonRpcCall {\n if (!isMinimalRequest(rawRequest)) {\n throw rpcErrors.invalidRequest({\n data: {\n request: rawRequest,\n },\n });\n }\n\n const request: JsonRpcCall = {\n jsonrpc,\n method: rawRequest.method,\n };\n\n if (hasProperty(rawRequest, 'params')) {\n request.params = rawRequest.params as JsonRpcParams;\n }\n\n if (isRequest) {\n (request as JsonRpcRequest).id = getUniqueId();\n }\n\n return request;\n }\n}\n\n/**\n * The most minimally conformant request object that we will accept.\n */\ntype MinimalRequest = {\n method: string;\n params?: JsonRpcParams;\n} & Record<string, unknown>;\n\n/**\n * Check if an unvalidated request is a minimal request.\n *\n * @param rawRequest - The raw request to check.\n * @returns `true` if the request is a {@link MinimalRequest}, `false` otherwise.\n */\nfunction isMinimalRequest(rawRequest: unknown): rawRequest is MinimalRequest {\n return (\n isObject(rawRequest) &&\n hasProperty(rawRequest, 'method') &&\n typeof rawRequest.method === 'string' &&\n hasValidParams(rawRequest)\n );\n}\n\n/**\n * Check if a request has valid params, i.e. an array or object.\n * The contents of the params are not inspected.\n *\n * @param rawRequest - The request to check.\n * @returns `true` if the request has valid params, `false` otherwise.\n */\nfunction hasValidParams(\n rawRequest: Record<string, unknown>,\n): rawRequest is { params?: JsonRpcParams } {\n if (hasProperty(rawRequest, 'params')) {\n return Array.isArray(rawRequest.params) || isObject(rawRequest.params);\n }\n return true;\n}\n\n/**\n * Get the original id from a request.\n *\n * @param rawRequest - The request to get the original id from.\n * @returns The original id and a boolean indicating if the request is a request\n * (as opposed to a notification).\n */\nfunction getOriginalId(rawRequest: unknown): [unknown, boolean] {\n if (isObject(rawRequest) && hasProperty(rawRequest, 'id')) {\n return [rawRequest.id, true];\n }\n return [undefined, false];\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MiddlewareContext.cjs","sourceRoot":"","sources":["../../src/v2/MiddlewareContext.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAa,iBAEX,SAAQ,GAAgD;IACxD,YACE,OAA0E;QAE1E,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACtB,CAAC;IAED,GAAG,CAA4B,GAAM;QACnC,OAAO,KAAK,CAAC,GAAG,CAAC,GAAG,CAA6B,CAAC;IACpD,CAAC;IAED;;;;;OAKG;IACH,SAAS,CAA4B,GAAM;QACzC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YACnB,MAAM,IAAI,KAAK,CAAC,gBAAgB,MAAM,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;SAC3D;QACD,OAAO,KAAK,CAAC,GAAG,CAAC,GAAG,CAAiB,CAAC;IACxC,CAAC;IAED;;;;;;;;OAQG;IACH,GAAG,CAA4B,GAAM,EAAE,KAAmB;QACxD,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YAClB,MAAM,IAAI,KAAK,CAAC,0BAA0B,MAAM,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;SAC1E;QACD,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA3CD,8CA2CC","sourcesContent":["import type { UnionToIntersection } from './utils';\n\n/**\n * An context object for middleware that attempts to protect against accidental\n * modifications. Its interface is frozen.\n *\n * Map keys may not be directly overridden with {@link set}. Instead, use\n * {@link delete} to remove a key and then {@link set} to add a new value.\n *\n * The override protections are circumvented when using e.g. `Reflect.set`, so\n * don't do that.\n *\n * @template KeyValues - The type of the keys and values in the context.\n * @example\n * // By default, the context permits any PropertyKey as a key.\n * const context = new MiddlewareContext();\n * context.set('foo', 'bar');\n * context.get('foo'); // 'bar'\n * context.get('fizz'); // undefined\n * @example\n * // By specifying an object type, the context permits only the keys of the object.\n * type Context = MiddlewareContext<{ foo: string }>;\n * const context = new Context([['foo', 'bar']]);\n * context.get('foo'); // 'bar'\n * context.get('fizz'); // Type error\n */\nexport class MiddlewareContext<\n KeyValues extends Record<PropertyKey, unknown> = Record<PropertyKey, unknown>,\n> extends Map<keyof KeyValues, KeyValues[keyof KeyValues]> {\n constructor(\n entries?: Iterable<readonly [keyof KeyValues, KeyValues[keyof KeyValues]]>,\n ) {\n super(entries);\n Object.freeze(this);\n }\n\n get<K extends keyof KeyValues>(key: K): KeyValues[K] | undefined {\n return super.get(key) as KeyValues[K] | undefined;\n }\n\n /**\n * Get a value from the context. Throws if the key is not found.\n *\n * @param key - The key to get the value for.\n * @returns The value.\n */\n assertGet<K extends keyof KeyValues>(key: K): KeyValues[K] {\n if (!super.has(key)) {\n throw new Error(`Context key \"${String(key)}\" not found`);\n }\n return super.get(key) as KeyValues[K];\n }\n\n /**\n * Set a value in the context. Throws if the key already exists.\n * {@link delete} an existing key before setting it to a new value.\n *\n * @throws If the key already exists.\n * @param key - The key to set the value for.\n * @param value - The value to set.\n * @returns The context.\n */\n set<K extends keyof KeyValues>(key: K, value: KeyValues[K]): this {\n if (super.has(key)) {\n throw new Error(`MiddlewareContext key \"${String(key)}\" already exists`);\n }\n super.set(key, value);\n return this;\n }\n}\n\n/**\n * Infer the KeyValues type from a {@link MiddlewareContext}.\n */\ntype InferKeyValues<T> = T extends MiddlewareContext<infer U> ? U : never;\n\n/**\n * Simplifies an object type by \"merging\" its properties.\n *\n * - Expands intersections into a single object type.\n * - Forces mapped/conditional results to resolve into a readable shape.\n * - No runtime effect; purely a type-level normalization.\n *\n * @example\n * type A = { a: string } & { b: number };\n * type B = Simplify<A>; // { a: string; b: number }\n */\ntype Simplify<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;\n\n/**\n * Rejects record types that contain any `never`-valued property.\n *\n * If any property of `T` resolves to `never`, the result is `never`; otherwise it returns `T` unchanged.\n * Useful as a guard to ensure computed/merged record types didn't collapse any fields to `never`.\n *\n * @example\n * type A = ExcludeNever<{ a: string; b: never }>; // never\n * type B = ExcludeNever<{ a: string; b: number }>; // { a: string; b: number }\n */\ntype ExcludeNever<T extends Record<PropertyKey, unknown>> = {\n [K in keyof T]-?: [T[K]] extends [never] ? K : never;\n}[keyof T] extends never\n ? T\n : never;\n\n/**\n * Merge a union of {@link MiddlewareContext}s into a single {@link MiddlewareContext}\n * supertype.\n *\n * @param Contexts - The union of {@link MiddlewareContext}s to merge.\n * @returns The merged {@link MiddlewareContext} supertype.\n * @example\n * type A = MiddlewareContext<{ a: string }> | MiddlewareContext<{ b: number }>;\n * type B = MergeContexts<A>; // MiddlewareContext<{ a: string, b: number }>\n */\nexport type MergeContexts<Contexts extends ContextConstraint> =\n ExcludeNever<\n Simplify<UnionToIntersection<InferKeyValues<Contexts>>>\n > extends never\n ? never\n : MiddlewareContext<\n ExcludeNever<Simplify<UnionToIntersection<InferKeyValues<Contexts>>>>\n >;\n\n// Non-polluting `any` constraint.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ContextConstraint = MiddlewareContext<any>;\n\n/**\n * The empty context type, i.e. `MiddlewareContext<{}>`.\n */\n// The empty object type is literally an empty object in this context.\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport type EmptyContext = MiddlewareContext<{}>;\n"]}
|
|
1
|
+
{"version":3,"file":"MiddlewareContext.cjs","sourceRoot":"","sources":["../../src/v2/MiddlewareContext.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAa,iBAEX,SAAQ,GAAgD;IACxD,YACE,OAA0E;QAE1E,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACtB,CAAC;IAED,GAAG,CAA4B,GAAM;QACnC,OAAO,KAAK,CAAC,GAAG,CAAC,GAAG,CAA6B,CAAC;IACpD,CAAC;IAED;;;;;OAKG;IACH,SAAS,CAA4B,GAAM;QACzC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YACnB,MAAM,IAAI,KAAK,CAAC,gBAAgB,MAAM,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;SAC3D;QACD,OAAO,KAAK,CAAC,GAAG,CAAC,GAAG,CAAiB,CAAC;IACxC,CAAC;IAED;;;;;;;;OAQG;IACH,GAAG,CAA4B,GAAM,EAAE,KAAmB;QACxD,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YAClB,MAAM,IAAI,KAAK,CAAC,0BAA0B,MAAM,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;SAC1E;QACD,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA3CD,8CA2CC","sourcesContent":["import type { UnionToIntersection } from './utils';\n\n/**\n * An context object for middleware that attempts to protect against accidental\n * modifications. Its interface is frozen.\n *\n * Map keys may not be directly overridden with {@link set}. Instead, use\n * {@link delete} to remove a key and then {@link set} to add a new value.\n *\n * The override protections are circumvented when using e.g. `Reflect.set`, so\n * don't do that.\n *\n * @template KeyValues - The type of the keys and values in the context.\n * @example\n * // By default, the context permits any PropertyKey as a key.\n * const context = new MiddlewareContext();\n * context.set('foo', 'bar');\n * context.get('foo'); // 'bar'\n * context.get('fizz'); // undefined\n * @example\n * // By specifying an object type, the context permits only the keys of the object.\n * type Context = MiddlewareContext<{ foo: string }>;\n * const context = new Context([['foo', 'bar']]);\n * context.get('foo'); // 'bar'\n * context.get('fizz'); // Type error\n */\nexport class MiddlewareContext<\n KeyValues extends Record<PropertyKey, unknown> = Record<PropertyKey, unknown>,\n> extends Map<keyof KeyValues, KeyValues[keyof KeyValues]> {\n constructor(\n entries?: Iterable<readonly [keyof KeyValues, KeyValues[keyof KeyValues]]>,\n ) {\n super(entries);\n Object.freeze(this);\n }\n\n get<K extends keyof KeyValues>(key: K): KeyValues[K] | undefined {\n return super.get(key) as KeyValues[K] | undefined;\n }\n\n /**\n * Get a value from the context. Throws if the key is not found.\n *\n * @param key - The key to get the value for.\n * @returns The value.\n */\n assertGet<K extends keyof KeyValues>(key: K): KeyValues[K] {\n if (!super.has(key)) {\n throw new Error(`Context key \"${String(key)}\" not found`);\n }\n return super.get(key) as KeyValues[K];\n }\n\n /**\n * Set a value in the context. Throws if the key already exists.\n * {@link delete} an existing key before setting it to a new value.\n *\n * @throws If the key already exists.\n * @param key - The key to set the value for.\n * @param value - The value to set.\n * @returns The context.\n */\n set<K extends keyof KeyValues>(key: K, value: KeyValues[K]): this {\n if (super.has(key)) {\n throw new Error(`MiddlewareContext key \"${String(key)}\" already exists`);\n }\n super.set(key, value);\n return this;\n }\n}\n\n/**\n * Infer the KeyValues type from a {@link MiddlewareContext}.\n */\ntype InferKeyValues<T> = T extends MiddlewareContext<infer U> ? U : never;\n\n/**\n * Simplifies an object type by \"merging\" its properties.\n *\n * - Expands intersections into a single object type.\n * - Forces mapped/conditional results to resolve into a readable shape.\n * - No runtime effect; purely a type-level normalization.\n *\n * @example\n * type A = { a: string } & { b: number };\n * type B = Simplify<A>; // { a: string; b: number }\n */\ntype Simplify<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;\n\n/**\n * Rejects record types that contain any `never`-valued property.\n *\n * If any property of `T` resolves to `never`, the result is `never`; otherwise it returns `T` unchanged.\n * Useful as a guard to ensure computed/merged record types didn't collapse any fields to `never`.\n *\n * @example\n * type A = ExcludeNever<{ a: string; b: never }>; // never\n * type B = ExcludeNever<{ a: string; b: number }>; // { a: string; b: number }\n */\ntype ExcludeNever<T extends Record<PropertyKey, unknown>> = {\n [K in keyof T]-?: [T[K]] extends [never] ? K : never;\n}[keyof T] extends never\n ? T\n : never;\n\n/**\n * Merge a union of {@link MiddlewareContext}s into a single {@link MiddlewareContext}\n * supertype.\n *\n * @param Contexts - The union of {@link MiddlewareContext}s to merge.\n * @returns The merged {@link MiddlewareContext} supertype.\n * @example\n * type A = MiddlewareContext<{ a: string }> | MiddlewareContext<{ b: number }>;\n * type B = MergeContexts<A>; // MiddlewareContext<{ a: string, b: number }>\n */\nexport type MergeContexts<Contexts extends ContextConstraint> =\n ExcludeNever<\n Simplify<UnionToIntersection<InferKeyValues<Contexts>>>\n > extends never\n ? never\n : MiddlewareContext<\n ExcludeNever<Simplify<UnionToIntersection<InferKeyValues<Contexts>>>>\n >;\n\n/**\n * A constraint for {@link MiddlewareContext} generic parameters.\n */\n// Non-polluting `any` constraint.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ContextConstraint = MiddlewareContext<any>;\n\n/**\n * The empty context type, i.e. `MiddlewareContext<{}>`.\n */\n// The empty object type is literally an empty object in this context.\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport type EmptyContext = MiddlewareContext<{}>;\n"]}
|
|
@@ -86,6 +86,9 @@ type ExcludeNever<T extends Record<PropertyKey, unknown>> = {
|
|
|
86
86
|
* type B = MergeContexts<A>; // MiddlewareContext<{ a: string, b: number }>
|
|
87
87
|
*/
|
|
88
88
|
export type MergeContexts<Contexts extends ContextConstraint> = ExcludeNever<Simplify<UnionToIntersection<InferKeyValues<Contexts>>>> extends never ? never : MiddlewareContext<ExcludeNever<Simplify<UnionToIntersection<InferKeyValues<Contexts>>>>>;
|
|
89
|
+
/**
|
|
90
|
+
* A constraint for {@link MiddlewareContext} generic parameters.
|
|
91
|
+
*/
|
|
89
92
|
export type ContextConstraint = MiddlewareContext<any>;
|
|
90
93
|
/**
|
|
91
94
|
* The empty context type, i.e. `MiddlewareContext<{}>`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MiddlewareContext.d.cts","sourceRoot":"","sources":["../../src/v2/MiddlewareContext.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,oBAAgB;AAEnD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,iBAAiB,CAC5B,SAAS,SAAS,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,CAC7E,SAAQ,GAAG,CAAC,MAA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,IAAI,CAAC,SAAS,MAAM,CAAC,GAAG;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAAE,GAAG,KAAK,CAAC;AAExE;;;;;;;;;GASG;AACH,KAAK,YAAY,CAAC,CAAC,SAAS,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,IAAI;KACzD,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK;CACrD,CAAC,MAAM,CAAC,CAAC,SAAS,KAAK,GACpB,CAAC,GACD,KAAK,CAAC;AAEV;;;;;;;;;GASG;AACH,MAAM,MAAM,aAAa,CAAC,QAAQ,SAAS,iBAAiB,IAC1D,YAAY,CACV,QAAQ,CAAC,mBAAmB,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC,CAAC,CACxD,SAAS,KAAK,GACX,KAAK,GACL,iBAAiB,CACf,YAAY,CAAC,QAAQ,CAAC,mBAAmB,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CACtE,CAAC;AAER;;GAEG;AAGH,MAAM,MAAM,iBAAiB,GAAG,iBAAiB,CAAC,GAAG,CAAC,CAAC;AAEvD;;GAEG;AAGH,MAAM,MAAM,YAAY,GAAG,iBAAiB,CAAC,EAAE,CAAC,CAAC"}
|
|
@@ -86,6 +86,9 @@ type ExcludeNever<T extends Record<PropertyKey, unknown>> = {
|
|
|
86
86
|
* type B = MergeContexts<A>; // MiddlewareContext<{ a: string, b: number }>
|
|
87
87
|
*/
|
|
88
88
|
export type MergeContexts<Contexts extends ContextConstraint> = ExcludeNever<Simplify<UnionToIntersection<InferKeyValues<Contexts>>>> extends never ? never : MiddlewareContext<ExcludeNever<Simplify<UnionToIntersection<InferKeyValues<Contexts>>>>>;
|
|
89
|
+
/**
|
|
90
|
+
* A constraint for {@link MiddlewareContext} generic parameters.
|
|
91
|
+
*/
|
|
89
92
|
export type ContextConstraint = MiddlewareContext<any>;
|
|
90
93
|
/**
|
|
91
94
|
* The empty context type, i.e. `MiddlewareContext<{}>`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MiddlewareContext.d.mts","sourceRoot":"","sources":["../../src/v2/MiddlewareContext.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,oBAAgB;AAEnD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,iBAAiB,CAC5B,SAAS,SAAS,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,CAC7E,SAAQ,GAAG,CAAC,MAAM,SAAS,EAAE,SAAS,CAAC,MAAM,SAAS,CAAC,CAAC;gBAEtD,OAAO,CAAC,EAAE,QAAQ,CAAC,SAAS,CAAC,MAAM,SAAS,EAAE,SAAS,CAAC,MAAM,SAAS,CAAC,CAAC,CAAC;IAM5E,GAAG,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,GAAG,SAAS;IAIhE;;;;;OAKG;IACH,SAAS,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC;IAO1D;;;;;;;;OAQG;IACH,GAAG,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,IAAI;CAOlE;AAED;;GAEG;AACH,KAAK,cAAc,CAAC,CAAC,IAAI,CAAC,SAAS,iBAAiB,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAE1E;;;;;;;;;;GAUG;AACH,KAAK,QAAQ,CAAC,CAAC,IAAI,CAAC,SAAS,MAAM,CAAC,GAAG;KAAG,CAAC,IAAI,MAAM,CAAC,G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,GAAG,CAAC,CAAC;AAEvD;;GAEG;AAGH,MAAM,MAAM,YAAY,GAAG,iBAAiB,CAAC,EAAE,CAAC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MiddlewareContext.mjs","sourceRoot":"","sources":["../../src/v2/MiddlewareContext.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,OAAO,iBAEX,SAAQ,GAAgD;IACxD,YACE,OAA0E;QAE1E,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACtB,CAAC;IAED,GAAG,CAA4B,GAAM;QACnC,OAAO,KAAK,CAAC,GAAG,CAAC,GAAG,CAA6B,CAAC;IACpD,CAAC;IAED;;;;;OAKG;IACH,SAAS,CAA4B,GAAM;QACzC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YACnB,MAAM,IAAI,KAAK,CAAC,gBAAgB,MAAM,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;SAC3D;QACD,OAAO,KAAK,CAAC,GAAG,CAAC,GAAG,CAAiB,CAAC;IACxC,CAAC;IAED;;;;;;;;OAQG;IACH,GAAG,CAA4B,GAAM,EAAE,KAAmB;QACxD,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YAClB,MAAM,IAAI,KAAK,CAAC,0BAA0B,MAAM,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;SAC1E;QACD,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import type { UnionToIntersection } from './utils';\n\n/**\n * An context object for middleware that attempts to protect against accidental\n * modifications. Its interface is frozen.\n *\n * Map keys may not be directly overridden with {@link set}. Instead, use\n * {@link delete} to remove a key and then {@link set} to add a new value.\n *\n * The override protections are circumvented when using e.g. `Reflect.set`, so\n * don't do that.\n *\n * @template KeyValues - The type of the keys and values in the context.\n * @example\n * // By default, the context permits any PropertyKey as a key.\n * const context = new MiddlewareContext();\n * context.set('foo', 'bar');\n * context.get('foo'); // 'bar'\n * context.get('fizz'); // undefined\n * @example\n * // By specifying an object type, the context permits only the keys of the object.\n * type Context = MiddlewareContext<{ foo: string }>;\n * const context = new Context([['foo', 'bar']]);\n * context.get('foo'); // 'bar'\n * context.get('fizz'); // Type error\n */\nexport class MiddlewareContext<\n KeyValues extends Record<PropertyKey, unknown> = Record<PropertyKey, unknown>,\n> extends Map<keyof KeyValues, KeyValues[keyof KeyValues]> {\n constructor(\n entries?: Iterable<readonly [keyof KeyValues, KeyValues[keyof KeyValues]]>,\n ) {\n super(entries);\n Object.freeze(this);\n }\n\n get<K extends keyof KeyValues>(key: K): KeyValues[K] | undefined {\n return super.get(key) as KeyValues[K] | undefined;\n }\n\n /**\n * Get a value from the context. Throws if the key is not found.\n *\n * @param key - The key to get the value for.\n * @returns The value.\n */\n assertGet<K extends keyof KeyValues>(key: K): KeyValues[K] {\n if (!super.has(key)) {\n throw new Error(`Context key \"${String(key)}\" not found`);\n }\n return super.get(key) as KeyValues[K];\n }\n\n /**\n * Set a value in the context. Throws if the key already exists.\n * {@link delete} an existing key before setting it to a new value.\n *\n * @throws If the key already exists.\n * @param key - The key to set the value for.\n * @param value - The value to set.\n * @returns The context.\n */\n set<K extends keyof KeyValues>(key: K, value: KeyValues[K]): this {\n if (super.has(key)) {\n throw new Error(`MiddlewareContext key \"${String(key)}\" already exists`);\n }\n super.set(key, value);\n return this;\n }\n}\n\n/**\n * Infer the KeyValues type from a {@link MiddlewareContext}.\n */\ntype InferKeyValues<T> = T extends MiddlewareContext<infer U> ? U : never;\n\n/**\n * Simplifies an object type by \"merging\" its properties.\n *\n * - Expands intersections into a single object type.\n * - Forces mapped/conditional results to resolve into a readable shape.\n * - No runtime effect; purely a type-level normalization.\n *\n * @example\n * type A = { a: string } & { b: number };\n * type B = Simplify<A>; // { a: string; b: number }\n */\ntype Simplify<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;\n\n/**\n * Rejects record types that contain any `never`-valued property.\n *\n * If any property of `T` resolves to `never`, the result is `never`; otherwise it returns `T` unchanged.\n * Useful as a guard to ensure computed/merged record types didn't collapse any fields to `never`.\n *\n * @example\n * type A = ExcludeNever<{ a: string; b: never }>; // never\n * type B = ExcludeNever<{ a: string; b: number }>; // { a: string; b: number }\n */\ntype ExcludeNever<T extends Record<PropertyKey, unknown>> = {\n [K in keyof T]-?: [T[K]] extends [never] ? K : never;\n}[keyof T] extends never\n ? T\n : never;\n\n/**\n * Merge a union of {@link MiddlewareContext}s into a single {@link MiddlewareContext}\n * supertype.\n *\n * @param Contexts - The union of {@link MiddlewareContext}s to merge.\n * @returns The merged {@link MiddlewareContext} supertype.\n * @example\n * type A = MiddlewareContext<{ a: string }> | MiddlewareContext<{ b: number }>;\n * type B = MergeContexts<A>; // MiddlewareContext<{ a: string, b: number }>\n */\nexport type MergeContexts<Contexts extends ContextConstraint> =\n ExcludeNever<\n Simplify<UnionToIntersection<InferKeyValues<Contexts>>>\n > extends never\n ? never\n : MiddlewareContext<\n ExcludeNever<Simplify<UnionToIntersection<InferKeyValues<Contexts>>>>\n >;\n\n// Non-polluting `any` constraint.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ContextConstraint = MiddlewareContext<any>;\n\n/**\n * The empty context type, i.e. `MiddlewareContext<{}>`.\n */\n// The empty object type is literally an empty object in this context.\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport type EmptyContext = MiddlewareContext<{}>;\n"]}
|
|
1
|
+
{"version":3,"file":"MiddlewareContext.mjs","sourceRoot":"","sources":["../../src/v2/MiddlewareContext.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,OAAO,iBAEX,SAAQ,GAAgD;IACxD,YACE,OAA0E;QAE1E,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACtB,CAAC;IAED,GAAG,CAA4B,GAAM;QACnC,OAAO,KAAK,CAAC,GAAG,CAAC,GAAG,CAA6B,CAAC;IACpD,CAAC;IAED;;;;;OAKG;IACH,SAAS,CAA4B,GAAM;QACzC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YACnB,MAAM,IAAI,KAAK,CAAC,gBAAgB,MAAM,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;SAC3D;QACD,OAAO,KAAK,CAAC,GAAG,CAAC,GAAG,CAAiB,CAAC;IACxC,CAAC;IAED;;;;;;;;OAQG;IACH,GAAG,CAA4B,GAAM,EAAE,KAAmB;QACxD,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YAClB,MAAM,IAAI,KAAK,CAAC,0BAA0B,MAAM,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;SAC1E;QACD,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import type { UnionToIntersection } from './utils';\n\n/**\n * An context object for middleware that attempts to protect against accidental\n * modifications. Its interface is frozen.\n *\n * Map keys may not be directly overridden with {@link set}. Instead, use\n * {@link delete} to remove a key and then {@link set} to add a new value.\n *\n * The override protections are circumvented when using e.g. `Reflect.set`, so\n * don't do that.\n *\n * @template KeyValues - The type of the keys and values in the context.\n * @example\n * // By default, the context permits any PropertyKey as a key.\n * const context = new MiddlewareContext();\n * context.set('foo', 'bar');\n * context.get('foo'); // 'bar'\n * context.get('fizz'); // undefined\n * @example\n * // By specifying an object type, the context permits only the keys of the object.\n * type Context = MiddlewareContext<{ foo: string }>;\n * const context = new Context([['foo', 'bar']]);\n * context.get('foo'); // 'bar'\n * context.get('fizz'); // Type error\n */\nexport class MiddlewareContext<\n KeyValues extends Record<PropertyKey, unknown> = Record<PropertyKey, unknown>,\n> extends Map<keyof KeyValues, KeyValues[keyof KeyValues]> {\n constructor(\n entries?: Iterable<readonly [keyof KeyValues, KeyValues[keyof KeyValues]]>,\n ) {\n super(entries);\n Object.freeze(this);\n }\n\n get<K extends keyof KeyValues>(key: K): KeyValues[K] | undefined {\n return super.get(key) as KeyValues[K] | undefined;\n }\n\n /**\n * Get a value from the context. Throws if the key is not found.\n *\n * @param key - The key to get the value for.\n * @returns The value.\n */\n assertGet<K extends keyof KeyValues>(key: K): KeyValues[K] {\n if (!super.has(key)) {\n throw new Error(`Context key \"${String(key)}\" not found`);\n }\n return super.get(key) as KeyValues[K];\n }\n\n /**\n * Set a value in the context. Throws if the key already exists.\n * {@link delete} an existing key before setting it to a new value.\n *\n * @throws If the key already exists.\n * @param key - The key to set the value for.\n * @param value - The value to set.\n * @returns The context.\n */\n set<K extends keyof KeyValues>(key: K, value: KeyValues[K]): this {\n if (super.has(key)) {\n throw new Error(`MiddlewareContext key \"${String(key)}\" already exists`);\n }\n super.set(key, value);\n return this;\n }\n}\n\n/**\n * Infer the KeyValues type from a {@link MiddlewareContext}.\n */\ntype InferKeyValues<T> = T extends MiddlewareContext<infer U> ? U : never;\n\n/**\n * Simplifies an object type by \"merging\" its properties.\n *\n * - Expands intersections into a single object type.\n * - Forces mapped/conditional results to resolve into a readable shape.\n * - No runtime effect; purely a type-level normalization.\n *\n * @example\n * type A = { a: string } & { b: number };\n * type B = Simplify<A>; // { a: string; b: number }\n */\ntype Simplify<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;\n\n/**\n * Rejects record types that contain any `never`-valued property.\n *\n * If any property of `T` resolves to `never`, the result is `never`; otherwise it returns `T` unchanged.\n * Useful as a guard to ensure computed/merged record types didn't collapse any fields to `never`.\n *\n * @example\n * type A = ExcludeNever<{ a: string; b: never }>; // never\n * type B = ExcludeNever<{ a: string; b: number }>; // { a: string; b: number }\n */\ntype ExcludeNever<T extends Record<PropertyKey, unknown>> = {\n [K in keyof T]-?: [T[K]] extends [never] ? K : never;\n}[keyof T] extends never\n ? T\n : never;\n\n/**\n * Merge a union of {@link MiddlewareContext}s into a single {@link MiddlewareContext}\n * supertype.\n *\n * @param Contexts - The union of {@link MiddlewareContext}s to merge.\n * @returns The merged {@link MiddlewareContext} supertype.\n * @example\n * type A = MiddlewareContext<{ a: string }> | MiddlewareContext<{ b: number }>;\n * type B = MergeContexts<A>; // MiddlewareContext<{ a: string, b: number }>\n */\nexport type MergeContexts<Contexts extends ContextConstraint> =\n ExcludeNever<\n Simplify<UnionToIntersection<InferKeyValues<Contexts>>>\n > extends never\n ? never\n : MiddlewareContext<\n ExcludeNever<Simplify<UnionToIntersection<InferKeyValues<Contexts>>>>\n >;\n\n/**\n * A constraint for {@link MiddlewareContext} generic parameters.\n */\n// Non-polluting `any` constraint.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ContextConstraint = MiddlewareContext<any>;\n\n/**\n * The empty context type, i.e. `MiddlewareContext<{}>`.\n */\n// The empty object type is literally an empty object in this context.\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport type EmptyContext = MiddlewareContext<{}>;\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.deserializeError = exports.propagateToRequest = exports.propagateToContext = exports.makeContext = exports.fromLegacyRequest = exports.requestProps = exports.deepClone = void 0;
|
|
4
4
|
const rpc_errors_1 = require("@metamask/rpc-errors");
|
|
5
5
|
const utils_1 = require("@metamask/utils");
|
|
6
6
|
// ATTN: We must NOT use 'klona/full' here because it freezes properties on the clone.
|
|
@@ -106,7 +106,7 @@ exports.propagateToRequest = propagateToRequest;
|
|
|
106
106
|
* @param thrown - The thrown value to unserialize.
|
|
107
107
|
* @returns The unserialized error.
|
|
108
108
|
*/
|
|
109
|
-
function
|
|
109
|
+
function deserializeError(thrown) {
|
|
110
110
|
// @ts-expect-error - New, but preferred if available.
|
|
111
111
|
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/isError
|
|
112
112
|
if (typeof Error.isError === 'function' && Error.isError(thrown)) {
|
|
@@ -147,5 +147,5 @@ function unserializeError(thrown) {
|
|
|
147
147
|
}
|
|
148
148
|
return error;
|
|
149
149
|
}
|
|
150
|
-
exports.
|
|
150
|
+
exports.deserializeError = deserializeError;
|
|
151
151
|
//# sourceMappingURL=compatibility-utils.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compatibility-utils.cjs","sourceRoot":"","sources":["../../src/v2/compatibility-utils.ts"],"names":[],"mappings":";;;AAAA,qDAAwE;AAExE,2CAAwD;AACxD,sFAAsF;AACtF,iCAA8B;AAE9B,+DAAwD;AACxD,uCAAyD;AAEzD,oCAAoC;AAEpC;;;;;;;;;;GAUG;AACI,MAAM,SAAS,GAAG,CAAI,KAAQ,EAAiB,EAAE,CACtD,IAAA,aAAK,EAAC,KAAK,CAAkB,CAAC;AADnB,QAAA,SAAS,aACU;AAWhC;;GAEG;AACU,QAAA,YAAY,GAAG,CAAC,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC;AAElE;;;;;;GAMG;AACH,SAAgB,iBAAiB,CAC/B,GAAY;IAEZ,MAAM,OAAO,GAAG;QACd,OAAO,EAAE,KAAc;QACvB,MAAM,EAAE,GAAG,CAAC,MAAM;KACC,CAAC;IACtB,OAAO,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,CAAC;IACpB,IAAI,IAAA,mBAAW,EAAC,GAAG,EAAE,QAAQ,CAAC,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS,EAAE;QAC1D,OAAO,CAAC,MAAM,GAAG,IAAA,iBAAS,EAAC,GAAG,CAAC,MAAM,CAAC,CAAC;KACxC;IACD,OAAO,OAAkB,CAAC;AAC5B,CAAC;AAZD,8CAYC;AAED;;;;;;GAMG;AACH,SAAgB,WAA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AC;IAET,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC7B,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;KACrB;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AA/CD,4CA+CC","sourcesContent":["import { getMessageFromCode, JsonRpcError } from '@metamask/rpc-errors';\nimport type { Json } from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n// ATTN: We must NOT use 'klona/full' here because it freezes properties on the clone.\nimport { klona } from 'klona';\n\nimport { MiddlewareContext } from './MiddlewareContext';\nimport { stringify, type JsonRpcRequest } from './utils';\n\n// Legacy engine compatibility utils\n\n/**\n * Create a deep clone of a value as follows:\n * - Assumes acyclical objects\n * - Does not copy property descriptors (i.e. uses mutable defaults)\n * - Ignores non-enumerable properties\n * - Ignores getters and setters\n *\n * @throws If the value is an object with a circular reference.\n * @param value - The value to clone.\n * @returns The cloned value.\n */\nexport const deepClone = <T>(value: T): DeepCloned<T> =>\n klona(value) as DeepCloned<T>;\n\n// Matching the default implementation of klona, this type:\n// - Removes readonly modifiers\n// - Excludes non-enumerable / symbol properties\ntype DeepCloned<T> = T extends readonly (infer U)[]\n ? DeepCloned<U>[]\n : T extends object\n ? { -readonly [K in keyof T & (string | number)]: DeepCloned<T[K]> }\n : T;\n\n/**\n * Standard JSON-RPC request properties.\n */\nexport const requestProps = ['jsonrpc', 'method', 'params', 'id'];\n\n/**\n * Make a JSON-RPC request from a legacy request. Clones the params to avoid\n * freezing them, which could cause errors in an involved legacy engine.\n *\n * @param req - The legacy request to make a request from.\n * @returns The JSON-RPC request.\n */\nexport function fromLegacyRequest<Request extends JsonRpcRequest>(\n req: Request,\n): Request {\n const request = {\n jsonrpc: '2.0' as const,\n method: req.method,\n } as Partial<Request>;\n request.id = req.id;\n if (hasProperty(req, 'params') && req.params !== undefined) {\n request.params = deepClone(req.params);\n }\n return request as Request;\n}\n\n/**\n * Make a middleware context from a legacy request by copying over all non-JSON-RPC\n * properties from the request to the context object.\n *\n * @param req - The legacy request to make a context from.\n * @returns The middleware context.\n */\nexport function makeContext<Request extends Record<string | symbol, unknown>>(\n req: Request,\n): MiddlewareContext {\n const context = new MiddlewareContext();\n propagateToContext(req, context);\n return context;\n}\n\n/**\n * Copies non-JSON-RPC string properties from the request to the context.\n *\n * For compatibility with our problematic practice of appending non-standard\n * fields to requests for inter-middleware communication in the legacy engine.\n *\n * **ATTN:** Only string properties that do not already exist in the context\n * are copied.\n *\n * @param req - The request to propagate the context from.\n * @param context - The context to propagate to.\n */\nexport function propagateToContext(\n req: Record<string, unknown>,\n context: MiddlewareContext<Record<string, unknown>>,\n) {\n Object.keys(req)\n .filter(\n (key) =>\n typeof key === 'string' &&\n !requestProps.includes(key) &&\n !context.has(key),\n )\n .forEach((key) => {\n context.set(key, req[key]);\n });\n}\n\n/**\n * Copies non-JSON-RPC string properties from the context to the request.\n *\n * For compatibility with our problematic practice of appending non-standard\n * fields to requests for inter-middleware communication in the legacy engine.\n *\n * **ATTN:** Only string properties are copied.\n *\n * @param req - The request to propagate the context to.\n * @param context - The context to propagate from.\n */\nexport function propagateToRequest(\n req: Record<string, unknown>,\n context: MiddlewareContext,\n) {\n Array.from(context.keys())\n .filter(\n ((key) => typeof key === 'string' && !requestProps.includes(key)) as (\n value: unknown,\n ) => value is string,\n )\n .forEach((key) => {\n req[key] = context.get(key);\n });\n}\n\n/**\n * Unserialize an error from a thrown value. Creates a {@link JsonRpcError} if\n * the thrown value is an object with a `code` property. Otherwise, creates a\n * plain {@link Error}.\n *\n * @param thrown - The thrown value to unserialize.\n * @returns The unserialized error.\n */\nexport function
|
|
1
|
+
{"version":3,"file":"compatibility-utils.cjs","sourceRoot":"","sources":["../../src/v2/compatibility-utils.ts"],"names":[],"mappings":";;;AAAA,qDAAwE;AAExE,2CAAwD;AACxD,sFAAsF;AACtF,iCAA8B;AAE9B,+DAAwD;AACxD,uCAAyD;AAEzD,oCAAoC;AAEpC;;;;;;;;;;GAUG;AACI,MAAM,SAAS,GAAG,CA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Ae,CAAC;IAC9B,IAAI,OAAO,MAAM,CAAC,OAAO,KAAK,QAAQ,EAAE;QACtC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;KAC1B;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,OAAO,GAAG,IAAA,+BAAkB,EAAC,IAAI,EAAE,OAAO,CAAC,CAAC;KAC7C;IAED,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;IAEtC,MAAM,KAAK,GACT,IAAI,KAAK,SAAS;QAChB,CAAC,CAAC,kEAAkE;YAClE,6DAA6D;YAC7D,2CAA2C;YAC3C,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC;QAC/B,CAAC,CAAC,IAAI,yBAAY,CAAC,IAAI,EAAE,OAAO,EAAE;YAC9B,GAAG,CAAC,IAAA,gBAAQ,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;YACtC,KAAK;SACN,CAAC,CAAC;IAET,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC7B,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;KACrB;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AA/CD,4CA+CC","sourcesContent":["import { getMessageFromCode, JsonRpcError } from '@metamask/rpc-errors';\nimport type { Json } from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n// ATTN: We must NOT use 'klona/full' here because it freezes properties on the clone.\nimport { klona } from 'klona';\n\nimport { MiddlewareContext } from './MiddlewareContext';\nimport { stringify, type JsonRpcRequest } from './utils';\n\n// Legacy engine compatibility utils\n\n/**\n * Create a deep clone of a value as follows:\n * - Assumes acyclical objects\n * - Does not copy property descriptors (i.e. uses mutable defaults)\n * - Ignores non-enumerable properties\n * - Ignores getters and setters\n *\n * @throws If the value is an object with a circular reference.\n * @param value - The value to clone.\n * @returns The cloned value.\n */\nexport const deepClone = <T>(value: T): DeepCloned<T> =>\n klona(value) as DeepCloned<T>;\n\n// Matching the default implementation of klona, this type:\n// - Removes readonly modifiers\n// - Excludes non-enumerable / symbol properties\ntype DeepCloned<T> = T extends readonly (infer U)[]\n ? DeepCloned<U>[]\n : T extends object\n ? { -readonly [K in keyof T & (string | number)]: DeepCloned<T[K]> }\n : T;\n\n/**\n * Standard JSON-RPC request properties.\n */\nexport const requestProps = ['jsonrpc', 'method', 'params', 'id'];\n\n/**\n * Make a JSON-RPC request from a legacy request. Clones the params to avoid\n * freezing them, which could cause errors in an involved legacy engine.\n *\n * @param req - The legacy request to make a request from.\n * @returns The JSON-RPC request.\n */\nexport function fromLegacyRequest<Request extends JsonRpcRequest>(\n req: Request,\n): Request {\n const request = {\n jsonrpc: '2.0' as const,\n method: req.method,\n } as Partial<Request>;\n request.id = req.id;\n if (hasProperty(req, 'params') && req.params !== undefined) {\n request.params = deepClone(req.params);\n }\n return request as Request;\n}\n\n/**\n * Make a middleware context from a legacy request by copying over all non-JSON-RPC\n * properties from the request to the context object.\n *\n * @param req - The legacy request to make a context from.\n * @returns The middleware context.\n */\nexport function makeContext<Request extends Record<string | symbol, unknown>>(\n req: Request,\n): MiddlewareContext {\n const context = new MiddlewareContext();\n propagateToContext(req, context);\n return context;\n}\n\n/**\n * Copies non-JSON-RPC string properties from the request to the context.\n *\n * For compatibility with our problematic practice of appending non-standard\n * fields to requests for inter-middleware communication in the legacy engine.\n *\n * **ATTN:** Only string properties that do not already exist in the context\n * are copied.\n *\n * @param req - The request to propagate the context from.\n * @param context - The context to propagate to.\n */\nexport function propagateToContext(\n req: Record<string, unknown>,\n context: MiddlewareContext<Record<string, unknown>>,\n) {\n Object.keys(req)\n .filter(\n (key) =>\n typeof key === 'string' &&\n !requestProps.includes(key) &&\n !context.has(key),\n )\n .forEach((key) => {\n context.set(key, req[key]);\n });\n}\n\n/**\n * Copies non-JSON-RPC string properties from the context to the request.\n *\n * For compatibility with our problematic practice of appending non-standard\n * fields to requests for inter-middleware communication in the legacy engine.\n *\n * **ATTN:** Only string properties are copied.\n *\n * @param req - The request to propagate the context to.\n * @param context - The context to propagate from.\n */\nexport function propagateToRequest(\n req: Record<string, unknown>,\n context: MiddlewareContext,\n) {\n Array.from(context.keys())\n .filter(\n ((key) => typeof key === 'string' && !requestProps.includes(key)) as (\n value: unknown,\n ) => value is string,\n )\n .forEach((key) => {\n req[key] = context.get(key);\n });\n}\n\n/**\n * Unserialize an error from a thrown value. Creates a {@link JsonRpcError} if\n * the thrown value is an object with a `code` property. Otherwise, creates a\n * plain {@link Error}.\n *\n * @param thrown - The thrown value to unserialize.\n * @returns The unserialized error.\n */\nexport function deserializeError(thrown: unknown): Error | JsonRpcError<Json> {\n // @ts-expect-error - New, but preferred if available.\n // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/isError\n if (typeof Error.isError === 'function' && Error.isError(thrown)) {\n return thrown as Error;\n }\n // Unlike Error.isError, instanceof does not work for Errors from other realms.\n if (thrown instanceof Error) {\n return thrown;\n }\n if (typeof thrown === 'string') {\n return new Error(thrown);\n }\n if (!isObject(thrown)) {\n return new Error(`Unknown error: ${stringify(thrown)}`);\n }\n\n const code =\n typeof thrown.code === 'number' && Number.isInteger(thrown.code)\n ? thrown.code\n : undefined;\n\n let message = 'Unknown error';\n if (typeof thrown.message === 'string') {\n message = thrown.message;\n } else if (typeof code === 'number') {\n message = getMessageFromCode(code, message);\n }\n\n const { stack, cause, data } = thrown;\n\n const error =\n code === undefined\n ? // Jest complains if we use the `@ts-expect-error` directive here.\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Our error type is outdated.\n new Error(message, { cause })\n : new JsonRpcError(code, message, {\n ...(isObject(data) ? data : undefined),\n cause,\n });\n\n if (typeof stack === 'string') {\n error.stack = stack;\n }\n\n return error;\n}\n"]}
|
|
@@ -70,6 +70,6 @@ export declare function propagateToRequest(req: Record<string, unknown>, context
|
|
|
70
70
|
* @param thrown - The thrown value to unserialize.
|
|
71
71
|
* @returns The unserialized error.
|
|
72
72
|
*/
|
|
73
|
-
export declare function
|
|
73
|
+
export declare function deserializeError(thrown: unknown): Error | JsonRpcError<Json>;
|
|
74
74
|
export {};
|
|
75
75
|
//# sourceMappingURL=compatibility-utils.d.cts.map
|
|
@@ -70,6 +70,6 @@ export declare function propagateToRequest(req: Record<string, unknown>, context
|
|
|
70
70
|
* @param thrown - The thrown value to unserialize.
|
|
71
71
|
* @returns The unserialized error.
|
|
72
72
|
*/
|
|
73
|
-
export declare function
|
|
73
|
+
export declare function deserializeError(thrown: unknown): Error | JsonRpcError<Json>;
|
|
74
74
|
export {};
|
|
75
75
|
//# sourceMappingURL=compatibility-utils.d.mts.map
|
|
@@ -98,7 +98,7 @@ export function propagateToRequest(req, context) {
|
|
|
98
98
|
* @param thrown - The thrown value to unserialize.
|
|
99
99
|
* @returns The unserialized error.
|
|
100
100
|
*/
|
|
101
|
-
export function
|
|
101
|
+
export function deserializeError(thrown) {
|
|
102
102
|
// @ts-expect-error - New, but preferred if available.
|
|
103
103
|
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/isError
|
|
104
104
|
if (typeof Error.isError === 'function' && Error.isError(thrown)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compatibility-utils.mjs","sourceRoot":"","sources":["../../src/v2/compatibility-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,6BAA6B;AAExE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,wBAAwB;AACxD,sFAAsF;AACtF,OAAO,EAAE,KAAK,EAAE,cAAc;AAE9B,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AACxD,OAAO,EAAE,SAAS,EAAuB,oBAAgB;AAEzD,oCAAoC;AAEpC;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAI,KAAQ,EAAiB,EAAE,CACtD,KA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KAC1B;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,OAAO,GAAG,kBAAkB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;KAC7C;IAED,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;IAEtC,MAAM,KAAK,GACT,IAAI,KAAK,SAAS;QAChB,CAAC,CAAC,kEAAkE;YAClE,6DAA6D;YAC7D,2CAA2C;YAC3C,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC;QAC/B,CAAC,CAAC,IAAI,YAAY,CAAC,IAAI,EAAE,OAAO,EAAE;YAC9B,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;YACtC,KAAK;SACN,CAAC,CAAC;IAET,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC7B,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;KACrB;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { getMessageFromCode, JsonRpcError } from '@metamask/rpc-errors';\nimport type { Json } from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n// ATTN: We must NOT use 'klona/full' here because it freezes properties on the clone.\nimport { klona } from 'klona';\n\nimport { MiddlewareContext } from './MiddlewareContext';\nimport { stringify, type JsonRpcRequest } from './utils';\n\n// Legacy engine compatibility utils\n\n/**\n * Create a deep clone of a value as follows:\n * - Assumes acyclical objects\n * - Does not copy property descriptors (i.e. uses mutable defaults)\n * - Ignores non-enumerable properties\n * - Ignores getters and setters\n *\n * @throws If the value is an object with a circular reference.\n * @param value - The value to clone.\n * @returns The cloned value.\n */\nexport const deepClone = <T>(value: T): DeepCloned<T> =>\n klona(value) as DeepCloned<T>;\n\n// Matching the default implementation of klona, this type:\n// - Removes readonly modifiers\n// - Excludes non-enumerable / symbol properties\ntype DeepCloned<T> = T extends readonly (infer U)[]\n ? DeepCloned<U>[]\n : T extends object\n ? { -readonly [K in keyof T & (string | number)]: DeepCloned<T[K]> }\n : T;\n\n/**\n * Standard JSON-RPC request properties.\n */\nexport const requestProps = ['jsonrpc', 'method', 'params', 'id'];\n\n/**\n * Make a JSON-RPC request from a legacy request. Clones the params to avoid\n * freezing them, which could cause errors in an involved legacy engine.\n *\n * @param req - The legacy request to make a request from.\n * @returns The JSON-RPC request.\n */\nexport function fromLegacyRequest<Request extends JsonRpcRequest>(\n req: Request,\n): Request {\n const request = {\n jsonrpc: '2.0' as const,\n method: req.method,\n } as Partial<Request>;\n request.id = req.id;\n if (hasProperty(req, 'params') && req.params !== undefined) {\n request.params = deepClone(req.params);\n }\n return request as Request;\n}\n\n/**\n * Make a middleware context from a legacy request by copying over all non-JSON-RPC\n * properties from the request to the context object.\n *\n * @param req - The legacy request to make a context from.\n * @returns The middleware context.\n */\nexport function makeContext<Request extends Record<string | symbol, unknown>>(\n req: Request,\n): MiddlewareContext {\n const context = new MiddlewareContext();\n propagateToContext(req, context);\n return context;\n}\n\n/**\n * Copies non-JSON-RPC string properties from the request to the context.\n *\n * For compatibility with our problematic practice of appending non-standard\n * fields to requests for inter-middleware communication in the legacy engine.\n *\n * **ATTN:** Only string properties that do not already exist in the context\n * are copied.\n *\n * @param req - The request to propagate the context from.\n * @param context - The context to propagate to.\n */\nexport function propagateToContext(\n req: Record<string, unknown>,\n context: MiddlewareContext<Record<string, unknown>>,\n) {\n Object.keys(req)\n .filter(\n (key) =>\n typeof key === 'string' &&\n !requestProps.includes(key) &&\n !context.has(key),\n )\n .forEach((key) => {\n context.set(key, req[key]);\n });\n}\n\n/**\n * Copies non-JSON-RPC string properties from the context to the request.\n *\n * For compatibility with our problematic practice of appending non-standard\n * fields to requests for inter-middleware communication in the legacy engine.\n *\n * **ATTN:** Only string properties are copied.\n *\n * @param req - The request to propagate the context to.\n * @param context - The context to propagate from.\n */\nexport function propagateToRequest(\n req: Record<string, unknown>,\n context: MiddlewareContext,\n) {\n Array.from(context.keys())\n .filter(\n ((key) => typeof key === 'string' && !requestProps.includes(key)) as (\n value: unknown,\n ) => value is string,\n )\n .forEach((key) => {\n req[key] = context.get(key);\n });\n}\n\n/**\n * Unserialize an error from a thrown value. Creates a {@link JsonRpcError} if\n * the thrown value is an object with a `code` property. Otherwise, creates a\n * plain {@link Error}.\n *\n * @param thrown - The thrown value to unserialize.\n * @returns The unserialized error.\n */\nexport function
|
|
1
|
+
{"version":3,"file":"compatibility-utils.mjs","sourceRoot":"","sources":["../../src/v2/compatibility-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,6BAA6B;AAExE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,wBAAwB;AACxD,sFAAsF;AACtF,OAAO,EAAE,KAAK,EAAE,cAAc;AAE9B,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AACxD,OAAO,EAAE,SAAS,EAAuB,oBAAgB;AAEzD,oCAAoC;AAEpC;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAI,KAAQ,EAAiB,EAAE,CACtD,KAAK,CAAC,KAAK,CAAkB,CAAC;AAWhC;;GAEG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC;AAElE;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAC/B,GAAY;IAEZ,MAAM,OAAO,GAAG;QACd,OAAO,EAAE,KAAc;QACvB,MAAM,EAAE,GAAG,CAAC,MAAM;KACC,CAAC;IACtB,OAAO,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,CAAC;IACpB,IAAI,WAAW,CAAC,GAAG,EAAE,QAAQ,CAAC,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS,EAAE;QAC1D,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;KACxC;IAC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AK;SACN,CAAC,CAAC;IAET,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC7B,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;KACrB;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { getMessageFromCode, JsonRpcError } from '@metamask/rpc-errors';\nimport type { Json } from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n// ATTN: We must NOT use 'klona/full' here because it freezes properties on the clone.\nimport { klona } from 'klona';\n\nimport { MiddlewareContext } from './MiddlewareContext';\nimport { stringify, type JsonRpcRequest } from './utils';\n\n// Legacy engine compatibility utils\n\n/**\n * Create a deep clone of a value as follows:\n * - Assumes acyclical objects\n * - Does not copy property descriptors (i.e. uses mutable defaults)\n * - Ignores non-enumerable properties\n * - Ignores getters and setters\n *\n * @throws If the value is an object with a circular reference.\n * @param value - The value to clone.\n * @returns The cloned value.\n */\nexport const deepClone = <T>(value: T): DeepCloned<T> =>\n klona(value) as DeepCloned<T>;\n\n// Matching the default implementation of klona, this type:\n// - Removes readonly modifiers\n// - Excludes non-enumerable / symbol properties\ntype DeepCloned<T> = T extends readonly (infer U)[]\n ? DeepCloned<U>[]\n : T extends object\n ? { -readonly [K in keyof T & (string | number)]: DeepCloned<T[K]> }\n : T;\n\n/**\n * Standard JSON-RPC request properties.\n */\nexport const requestProps = ['jsonrpc', 'method', 'params', 'id'];\n\n/**\n * Make a JSON-RPC request from a legacy request. Clones the params to avoid\n * freezing them, which could cause errors in an involved legacy engine.\n *\n * @param req - The legacy request to make a request from.\n * @returns The JSON-RPC request.\n */\nexport function fromLegacyRequest<Request extends JsonRpcRequest>(\n req: Request,\n): Request {\n const request = {\n jsonrpc: '2.0' as const,\n method: req.method,\n } as Partial<Request>;\n request.id = req.id;\n if (hasProperty(req, 'params') && req.params !== undefined) {\n request.params = deepClone(req.params);\n }\n return request as Request;\n}\n\n/**\n * Make a middleware context from a legacy request by copying over all non-JSON-RPC\n * properties from the request to the context object.\n *\n * @param req - The legacy request to make a context from.\n * @returns The middleware context.\n */\nexport function makeContext<Request extends Record<string | symbol, unknown>>(\n req: Request,\n): MiddlewareContext {\n const context = new MiddlewareContext();\n propagateToContext(req, context);\n return context;\n}\n\n/**\n * Copies non-JSON-RPC string properties from the request to the context.\n *\n * For compatibility with our problematic practice of appending non-standard\n * fields to requests for inter-middleware communication in the legacy engine.\n *\n * **ATTN:** Only string properties that do not already exist in the context\n * are copied.\n *\n * @param req - The request to propagate the context from.\n * @param context - The context to propagate to.\n */\nexport function propagateToContext(\n req: Record<string, unknown>,\n context: MiddlewareContext<Record<string, unknown>>,\n) {\n Object.keys(req)\n .filter(\n (key) =>\n typeof key === 'string' &&\n !requestProps.includes(key) &&\n !context.has(key),\n )\n .forEach((key) => {\n context.set(key, req[key]);\n });\n}\n\n/**\n * Copies non-JSON-RPC string properties from the context to the request.\n *\n * For compatibility with our problematic practice of appending non-standard\n * fields to requests for inter-middleware communication in the legacy engine.\n *\n * **ATTN:** Only string properties are copied.\n *\n * @param req - The request to propagate the context to.\n * @param context - The context to propagate from.\n */\nexport function propagateToRequest(\n req: Record<string, unknown>,\n context: MiddlewareContext,\n) {\n Array.from(context.keys())\n .filter(\n ((key) => typeof key === 'string' && !requestProps.includes(key)) as (\n value: unknown,\n ) => value is string,\n )\n .forEach((key) => {\n req[key] = context.get(key);\n });\n}\n\n/**\n * Unserialize an error from a thrown value. Creates a {@link JsonRpcError} if\n * the thrown value is an object with a `code` property. Otherwise, creates a\n * plain {@link Error}.\n *\n * @param thrown - The thrown value to unserialize.\n * @returns The unserialized error.\n */\nexport function deserializeError(thrown: unknown): Error | JsonRpcError<Json> {\n // @ts-expect-error - New, but preferred if available.\n // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/isError\n if (typeof Error.isError === 'function' && Error.isError(thrown)) {\n return thrown as Error;\n }\n // Unlike Error.isError, instanceof does not work for Errors from other realms.\n if (thrown instanceof Error) {\n return thrown;\n }\n if (typeof thrown === 'string') {\n return new Error(thrown);\n }\n if (!isObject(thrown)) {\n return new Error(`Unknown error: ${stringify(thrown)}`);\n }\n\n const code =\n typeof thrown.code === 'number' && Number.isInteger(thrown.code)\n ? thrown.code\n : undefined;\n\n let message = 'Unknown error';\n if (typeof thrown.message === 'string') {\n message = thrown.message;\n } else if (typeof code === 'number') {\n message = getMessageFromCode(code, message);\n }\n\n const { stack, cause, data } = thrown;\n\n const error =\n code === undefined\n ? // Jest complains if we use the `@ts-expect-error` directive here.\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Our error type is outdated.\n new Error(message, { cause })\n : new JsonRpcError(code, message, {\n ...(isObject(data) ? data : undefined),\n cause,\n });\n\n if (typeof stack === 'string') {\n error.stack = stack;\n }\n\n return error;\n}\n"]}
|
package/dist/v2/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../../src/v2/index.ts"],"names":[],"mappings":";;;AAAA,+DAA0D;AAAjD,wHAAA,kBAAkB,OAAA;AAC3B,kDAA6C;AAApC,0GAAA,WAAW,OAAA;AACpB,2EAAsE;AAA7D,oIAAA,wBAAwB,OAAA;AACjC,yDAAoD;AAA3C,kHAAA,eAAe,OAAA;
|
|
1
|
+
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../../src/v2/index.ts"],"names":[],"mappings":";;;AAAA,+DAA0D;AAAjD,wHAAA,kBAAkB,OAAA;AAC3B,kDAA6C;AAApC,0GAAA,WAAW,OAAA;AACpB,2EAAsE;AAA7D,oIAAA,wBAAwB,OAAA;AACjC,yDAAoD;AAA3C,kHAAA,eAAe,OAAA;AAUxB,qDAAgD;AAAvC,8GAAA,aAAa,OAAA;AACtB,6DAAwD;AAA/C,sHAAA,iBAAiB,OAAA;AAE1B,qCAAwE;AAA/D,uGAAA,cAAc,OAAA;AAAE,kGAAA,SAAS,OAAA;AAAE,2GAAA,kBAAkB,OAAA","sourcesContent":["export { asLegacyMiddleware } from './asLegacyMiddleware';\nexport { getUniqueId } from '../getUniqueId';\nexport { createScaffoldMiddleware } from './createScaffoldMiddleware';\nexport { JsonRpcEngineV2 } from './JsonRpcEngineV2';\nexport type {\n JsonRpcMiddleware,\n MergedContextOf,\n MiddlewareParams,\n MiddlewareConstraint,\n Next,\n RequestOf,\n ResultConstraint,\n} from './JsonRpcEngineV2';\nexport { JsonRpcServer } from './JsonRpcServer';\nexport { MiddlewareContext } from './MiddlewareContext';\nexport type { EmptyContext, ContextConstraint } from './MiddlewareContext';\nexport { isNotification, isRequest, JsonRpcEngineError } from './utils';\nexport type {\n Json,\n JsonRpcCall,\n JsonRpcNotification,\n JsonRpcParams,\n JsonRpcRequest,\n} from './utils';\n"]}
|
package/dist/v2/index.d.cts
CHANGED
|
@@ -2,10 +2,10 @@ export { asLegacyMiddleware } from "./asLegacyMiddleware.cjs";
|
|
|
2
2
|
export { getUniqueId } from "../getUniqueId.cjs";
|
|
3
3
|
export { createScaffoldMiddleware } from "./createScaffoldMiddleware.cjs";
|
|
4
4
|
export { JsonRpcEngineV2 } from "./JsonRpcEngineV2.cjs";
|
|
5
|
-
export type { JsonRpcMiddleware, MiddlewareParams, Next, ResultConstraint, } from "./JsonRpcEngineV2.cjs";
|
|
5
|
+
export type { JsonRpcMiddleware, MergedContextOf, MiddlewareParams, MiddlewareConstraint, Next, RequestOf, ResultConstraint, } from "./JsonRpcEngineV2.cjs";
|
|
6
6
|
export { JsonRpcServer } from "./JsonRpcServer.cjs";
|
|
7
7
|
export { MiddlewareContext } from "./MiddlewareContext.cjs";
|
|
8
|
-
export type { EmptyContext } from "./MiddlewareContext.cjs";
|
|
8
|
+
export type { EmptyContext, ContextConstraint } from "./MiddlewareContext.cjs";
|
|
9
9
|
export { isNotification, isRequest, JsonRpcEngineError } from "./utils.cjs";
|
|
10
10
|
export type { Json, JsonRpcCall, JsonRpcNotification, JsonRpcParams, JsonRpcRequest, } from "./utils.cjs";
|
|
11
11
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/v2/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../src/v2/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,iCAA6B;AAC1D,OAAO,EAAE,WAAW,EAAE,2BAAuB;AAC7C,OAAO,EAAE,wBAAwB,EAAE,uCAAmC;AACtE,OAAO,EAAE,eAAe,EAAE,8BAA0B;AACpD,YAAY,EACV,iBAAiB,EACjB,gBAAgB,EAChB,IAAI,EACJ,gBAAgB,GACjB,8BAA0B;AAC3B,OAAO,EAAE,aAAa,EAAE,4BAAwB;AAChD,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AACxD,YAAY,EAAE,YAAY,EAAE,gCAA4B;
|
|
1
|
+
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../src/v2/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,iCAA6B;AAC1D,OAAO,EAAE,WAAW,EAAE,2BAAuB;AAC7C,OAAO,EAAE,wBAAwB,EAAE,uCAAmC;AACtE,OAAO,EAAE,eAAe,EAAE,8BAA0B;AACpD,YAAY,EACV,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,oBAAoB,EACpB,IAAI,EACJ,SAAS,EACT,gBAAgB,GACjB,8BAA0B;AAC3B,OAAO,EAAE,aAAa,EAAE,4BAAwB;AAChD,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AACxD,YAAY,EAAE,YAAY,EAAE,iBAAiB,EAAE,gCAA4B;AAC3E,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,kBAAkB,EAAE,oBAAgB;AACxE,YAAY,EACV,IAAI,EACJ,WAAW,EACX,mBAAmB,EACnB,aAAa,EACb,cAAc,GACf,oBAAgB"}
|
package/dist/v2/index.d.mts
CHANGED
|
@@ -2,10 +2,10 @@ export { asLegacyMiddleware } from "./asLegacyMiddleware.mjs";
|
|
|
2
2
|
export { getUniqueId } from "../getUniqueId.mjs";
|
|
3
3
|
export { createScaffoldMiddleware } from "./createScaffoldMiddleware.mjs";
|
|
4
4
|
export { JsonRpcEngineV2 } from "./JsonRpcEngineV2.mjs";
|
|
5
|
-
export type { JsonRpcMiddleware, MiddlewareParams, Next, ResultConstraint, } from "./JsonRpcEngineV2.mjs";
|
|
5
|
+
export type { JsonRpcMiddleware, MergedContextOf, MiddlewareParams, MiddlewareConstraint, Next, RequestOf, ResultConstraint, } from "./JsonRpcEngineV2.mjs";
|
|
6
6
|
export { JsonRpcServer } from "./JsonRpcServer.mjs";
|
|
7
7
|
export { MiddlewareContext } from "./MiddlewareContext.mjs";
|
|
8
|
-
export type { EmptyContext } from "./MiddlewareContext.mjs";
|
|
8
|
+
export type { EmptyContext, ContextConstraint } from "./MiddlewareContext.mjs";
|
|
9
9
|
export { isNotification, isRequest, JsonRpcEngineError } from "./utils.mjs";
|
|
10
10
|
export type { Json, JsonRpcCall, JsonRpcNotification, JsonRpcParams, JsonRpcRequest, } from "./utils.mjs";
|
|
11
11
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/v2/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../src/v2/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,iCAA6B;AAC1D,OAAO,EAAE,WAAW,EAAE,2BAAuB;AAC7C,OAAO,EAAE,wBAAwB,EAAE,uCAAmC;AACtE,OAAO,EAAE,eAAe,EAAE,8BAA0B;AACpD,YAAY,EACV,iBAAiB,EACjB,gBAAgB,EAChB,IAAI,EACJ,gBAAgB,GACjB,8BAA0B;AAC3B,OAAO,EAAE,aAAa,EAAE,4BAAwB;AAChD,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AACxD,YAAY,EAAE,YAAY,EAAE,gCAA4B;
|
|
1
|
+
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../src/v2/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,iCAA6B;AAC1D,OAAO,EAAE,WAAW,EAAE,2BAAuB;AAC7C,OAAO,EAAE,wBAAwB,EAAE,uCAAmC;AACtE,OAAO,EAAE,eAAe,EAAE,8BAA0B;AACpD,YAAY,EACV,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,oBAAoB,EACpB,IAAI,EACJ,SAAS,EACT,gBAAgB,GACjB,8BAA0B;AAC3B,OAAO,EAAE,aAAa,EAAE,4BAAwB;AAChD,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AACxD,YAAY,EAAE,YAAY,EAAE,iBAAiB,EAAE,gCAA4B;AAC3E,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,kBAAkB,EAAE,oBAAgB;AACxE,YAAY,EACV,IAAI,EACJ,WAAW,EACX,mBAAmB,EACnB,aAAa,EACb,cAAc,GACf,oBAAgB"}
|
package/dist/v2/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../src/v2/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,iCAA6B;AAC1D,OAAO,EAAE,WAAW,EAAE,2BAAuB;AAC7C,OAAO,EAAE,wBAAwB,EAAE,uCAAmC;AACtE,OAAO,EAAE,eAAe,EAAE,8BAA0B;
|
|
1
|
+
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../src/v2/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,iCAA6B;AAC1D,OAAO,EAAE,WAAW,EAAE,2BAAuB;AAC7C,OAAO,EAAE,wBAAwB,EAAE,uCAAmC;AACtE,OAAO,EAAE,eAAe,EAAE,8BAA0B;AAUpD,OAAO,EAAE,aAAa,EAAE,4BAAwB;AAChD,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AAExD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,kBAAkB,EAAE,oBAAgB","sourcesContent":["export { asLegacyMiddleware } from './asLegacyMiddleware';\nexport { getUniqueId } from '../getUniqueId';\nexport { createScaffoldMiddleware } from './createScaffoldMiddleware';\nexport { JsonRpcEngineV2 } from './JsonRpcEngineV2';\nexport type {\n JsonRpcMiddleware,\n MergedContextOf,\n MiddlewareParams,\n MiddlewareConstraint,\n Next,\n RequestOf,\n ResultConstraint,\n} from './JsonRpcEngineV2';\nexport { JsonRpcServer } from './JsonRpcServer';\nexport { MiddlewareContext } from './MiddlewareContext';\nexport type { EmptyContext, ContextConstraint } from './MiddlewareContext';\nexport { isNotification, isRequest, JsonRpcEngineError } from './utils';\nexport type {\n Json,\n JsonRpcCall,\n JsonRpcNotification,\n JsonRpcParams,\n JsonRpcRequest,\n} from './utils';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/json-rpc-engine",
|
|
3
|
-
"version": "10.1.1-preview-
|
|
3
|
+
"version": "10.1.1-preview-b289ac1c",
|
|
4
4
|
"description": "A tool for processing JSON-RPC messages",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -50,6 +50,7 @@
|
|
|
50
50
|
],
|
|
51
51
|
"scripts": {
|
|
52
52
|
"build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
|
|
53
|
+
"build:all": "ts-bridge --project tsconfig.build.json --verbose --clean",
|
|
53
54
|
"build:docs": "typedoc",
|
|
54
55
|
"changelog:update": "../../scripts/update-changelog.sh @metamask/json-rpc-engine --tag-prefix-before-package-rename json-rpc-engine@ --version-before-package-rename 6.1.0",
|
|
55
56
|
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/json-rpc-engine --tag-prefix-before-package-rename json-rpc-engine@ --version-before-package-rename 6.1.0",
|
|
@@ -78,6 +79,7 @@
|
|
|
78
79
|
"@lavamoat/allow-scripts": "^3.0.4",
|
|
79
80
|
"@lavamoat/preinstall-always-fail": "^2.1.0",
|
|
80
81
|
"@metamask/auto-changelog": "^3.4.4",
|
|
82
|
+
"@ts-bridge/cli": "^0.6.4",
|
|
81
83
|
"@types/jest": "^27.4.1",
|
|
82
84
|
"deepmerge": "^4.2.2",
|
|
83
85
|
"jest": "^27.5.1",
|