@metamask-previews/json-rpc-engine 10.5.0-preview-4f4c98e → 10.5.0-preview-eb263b0ee
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 +0 -1
- package/dist/JsonRpcEngine.cjs +352 -0
- package/dist/JsonRpcEngine.cjs.map +1 -0
- package/dist/{JsonRpcEngine.d.ts → JsonRpcEngine.d.cts} +3 -3
- package/dist/JsonRpcEngine.d.cts.map +1 -0
- package/dist/JsonRpcEngine.d.mts +132 -0
- package/dist/JsonRpcEngine.d.mts.map +1 -0
- package/dist/{JsonRpcEngine.js → JsonRpcEngine.mjs} +5 -5
- package/dist/JsonRpcEngine.mjs.map +1 -0
- package/dist/asV2Middleware.cjs +57 -0
- package/dist/asV2Middleware.cjs.map +1 -0
- package/dist/{asV2Middleware.d.ts → asV2Middleware.d.cts} +6 -6
- package/dist/asV2Middleware.d.cts.map +1 -0
- package/dist/asV2Middleware.d.mts +20 -0
- package/dist/asV2Middleware.d.mts.map +1 -0
- package/dist/{asV2Middleware.js → asV2Middleware.mjs} +5 -5
- package/dist/asV2Middleware.mjs.map +1 -0
- package/dist/createAsyncMiddleware.cjs +71 -0
- package/dist/createAsyncMiddleware.cjs.map +1 -0
- package/dist/{createAsyncMiddleware.d.ts → createAsyncMiddleware.d.cts} +3 -3
- package/dist/createAsyncMiddleware.d.cts.map +1 -0
- package/dist/createAsyncMiddleware.d.mts +28 -0
- package/dist/createAsyncMiddleware.d.mts.map +1 -0
- package/dist/{createAsyncMiddleware.js → createAsyncMiddleware.mjs} +1 -1
- package/dist/createAsyncMiddleware.mjs.map +1 -0
- package/dist/createMethodMiddleware.cjs +56 -0
- package/dist/createMethodMiddleware.cjs.map +1 -0
- package/dist/{createMethodMiddleware.d.ts → createMethodMiddleware.d.cts} +6 -6
- package/dist/createMethodMiddleware.d.cts.map +1 -0
- package/dist/createMethodMiddleware.d.mts +86 -0
- package/dist/createMethodMiddleware.d.mts.map +1 -0
- package/dist/{createMethodMiddleware.js → createMethodMiddleware.mjs} +3 -3
- package/dist/createMethodMiddleware.mjs.map +1 -0
- package/dist/createOriginMiddleware.cjs +18 -0
- package/dist/createOriginMiddleware.cjs.map +1 -0
- package/dist/{createOriginMiddleware.d.ts → createOriginMiddleware.d.cts} +3 -3
- package/dist/createOriginMiddleware.d.cts.map +1 -0
- package/dist/createOriginMiddleware.d.mts +11 -0
- package/dist/createOriginMiddleware.d.mts.map +1 -0
- package/dist/{createOriginMiddleware.js → createOriginMiddleware.mjs} +1 -1
- package/dist/createOriginMiddleware.mjs.map +1 -0
- package/dist/createScaffoldMiddleware.cjs +31 -0
- package/dist/createScaffoldMiddleware.cjs.map +1 -0
- package/dist/{createScaffoldMiddleware.d.ts → createScaffoldMiddleware.d.cts} +3 -3
- package/dist/createScaffoldMiddleware.d.cts.map +1 -0
- package/dist/createScaffoldMiddleware.d.mts +18 -0
- package/dist/createScaffoldMiddleware.d.mts.map +1 -0
- package/dist/{createScaffoldMiddleware.js → createScaffoldMiddleware.mjs} +1 -1
- package/dist/createScaffoldMiddleware.mjs.map +1 -0
- package/dist/getUniqueId.cjs +20 -0
- package/dist/getUniqueId.cjs.map +1 -0
- package/dist/{getUniqueId.d.ts → getUniqueId.d.cts} +1 -1
- package/dist/getUniqueId.d.cts.map +1 -0
- package/dist/getUniqueId.d.mts +9 -0
- package/dist/getUniqueId.d.mts.map +1 -0
- package/dist/{getUniqueId.js → getUniqueId.mjs} +1 -1
- package/dist/getUniqueId.mjs.map +1 -0
- package/dist/idRemapMiddleware.cjs +29 -0
- package/dist/idRemapMiddleware.cjs.map +1 -0
- package/dist/{idRemapMiddleware.d.ts → idRemapMiddleware.d.cts} +3 -3
- package/dist/idRemapMiddleware.d.cts.map +1 -0
- package/dist/idRemapMiddleware.d.mts +14 -0
- package/dist/idRemapMiddleware.d.mts.map +1 -0
- package/dist/{idRemapMiddleware.js → idRemapMiddleware.mjs} +2 -2
- package/dist/idRemapMiddleware.mjs.map +1 -0
- package/dist/index.cjs +22 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +13 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +13 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +10 -0
- package/dist/index.mjs.map +1 -0
- package/dist/mergeMiddleware.cjs +18 -0
- package/dist/mergeMiddleware.cjs.map +1 -0
- package/dist/{mergeMiddleware.d.ts → mergeMiddleware.d.cts} +3 -3
- package/dist/mergeMiddleware.d.cts.map +1 -0
- package/dist/mergeMiddleware.d.mts +11 -0
- package/dist/mergeMiddleware.d.mts.map +1 -0
- package/dist/{mergeMiddleware.js → mergeMiddleware.mjs} +2 -2
- package/dist/mergeMiddleware.mjs.map +1 -0
- package/dist/v2/JsonRpcEngineV2.cjs +220 -0
- package/dist/v2/JsonRpcEngineV2.cjs.map +1 -0
- package/dist/v2/{JsonRpcEngineV2.d.ts → JsonRpcEngineV2.d.cts} +5 -5
- package/dist/v2/JsonRpcEngineV2.d.cts.map +1 -0
- package/dist/v2/JsonRpcEngineV2.d.mts +136 -0
- package/dist/v2/JsonRpcEngineV2.d.mts.map +1 -0
- package/dist/v2/{JsonRpcEngineV2.js → JsonRpcEngineV2.mjs} +13 -9
- package/dist/v2/JsonRpcEngineV2.mjs.map +1 -0
- package/dist/v2/JsonRpcServer.cjs +178 -0
- package/dist/v2/JsonRpcServer.cjs.map +1 -0
- package/dist/v2/{JsonRpcServer.d.ts → JsonRpcServer.d.cts} +4 -4
- package/dist/v2/JsonRpcServer.d.cts.map +1 -0
- package/dist/v2/JsonRpcServer.d.mts +104 -0
- package/dist/v2/JsonRpcServer.d.mts.map +1 -0
- package/dist/v2/{JsonRpcServer.js → JsonRpcServer.mjs} +5 -5
- package/dist/v2/JsonRpcServer.mjs.map +1 -0
- package/dist/v2/MiddlewareContext.cjs +108 -0
- package/dist/v2/MiddlewareContext.cjs.map +1 -0
- package/dist/v2/{MiddlewareContext.d.ts → MiddlewareContext.d.cts} +2 -2
- package/dist/v2/MiddlewareContext.d.cts.map +1 -0
- package/dist/v2/MiddlewareContext.d.mts +108 -0
- package/dist/v2/MiddlewareContext.d.mts.map +1 -0
- package/dist/v2/{MiddlewareContext.js → MiddlewareContext.mjs} +2 -2
- package/dist/v2/MiddlewareContext.mjs.map +1 -0
- package/dist/v2/asLegacyMiddleware.cjs +45 -0
- package/dist/v2/asLegacyMiddleware.cjs.map +1 -0
- package/dist/v2/{asLegacyMiddleware.d.ts → asLegacyMiddleware.d.cts} +5 -5
- package/dist/v2/asLegacyMiddleware.d.cts.map +1 -0
- package/dist/v2/asLegacyMiddleware.d.mts +19 -0
- package/dist/v2/asLegacyMiddleware.d.mts.map +1 -0
- package/dist/v2/{asLegacyMiddleware.js → asLegacyMiddleware.mjs} +4 -4
- package/dist/v2/asLegacyMiddleware.mjs.map +1 -0
- package/dist/v2/compatibility-utils.cjs +167 -0
- package/dist/v2/compatibility-utils.cjs.map +1 -0
- package/dist/v2/{compatibility-utils.d.ts → compatibility-utils.d.cts} +5 -5
- package/dist/v2/compatibility-utils.d.cts.map +1 -0
- package/dist/v2/compatibility-utils.d.mts +75 -0
- package/dist/v2/compatibility-utils.d.mts.map +1 -0
- package/dist/v2/{compatibility-utils.js → compatibility-utils.mjs} +6 -6
- package/dist/v2/compatibility-utils.mjs.map +1 -0
- package/dist/v2/createMethodMiddleware.cjs +44 -0
- package/dist/v2/createMethodMiddleware.cjs.map +1 -0
- package/dist/v2/{createMethodMiddleware.d.ts → createMethodMiddleware.d.cts} +5 -5
- package/dist/v2/createMethodMiddleware.d.cts.map +1 -0
- package/dist/v2/createMethodMiddleware.d.mts +71 -0
- package/dist/v2/createMethodMiddleware.d.mts.map +1 -0
- package/dist/v2/{createMethodMiddleware.js → createMethodMiddleware.mjs} +3 -2
- package/dist/v2/createMethodMiddleware.mjs.map +1 -0
- package/dist/v2/createOriginMiddleware.cjs +18 -0
- package/dist/v2/createOriginMiddleware.cjs.map +1 -0
- package/dist/v2/{createOriginMiddleware.d.ts → createOriginMiddleware.d.cts} +4 -4
- package/dist/v2/createOriginMiddleware.d.cts.map +1 -0
- package/dist/v2/createOriginMiddleware.d.mts +13 -0
- package/dist/v2/createOriginMiddleware.d.mts.map +1 -0
- package/dist/v2/{createOriginMiddleware.js → createOriginMiddleware.mjs} +2 -1
- package/dist/v2/createOriginMiddleware.mjs.map +1 -0
- package/dist/v2/createScaffoldMiddleware.cjs +25 -0
- package/dist/v2/createScaffoldMiddleware.cjs.map +1 -0
- package/dist/v2/{createScaffoldMiddleware.d.ts → createScaffoldMiddleware.d.cts} +4 -4
- package/dist/v2/createScaffoldMiddleware.d.cts.map +1 -0
- package/dist/v2/createScaffoldMiddleware.d.mts +30 -0
- package/dist/v2/createScaffoldMiddleware.d.mts.map +1 -0
- package/dist/v2/{createScaffoldMiddleware.js → createScaffoldMiddleware.mjs} +1 -1
- package/dist/v2/createScaffoldMiddleware.mjs.map +1 -0
- package/dist/v2/index.cjs +26 -0
- package/dist/v2/index.cjs.map +1 -0
- package/dist/v2/index.d.cts +14 -0
- package/dist/v2/index.d.cts.map +1 -0
- package/dist/v2/index.d.mts +14 -0
- package/dist/v2/index.d.mts.map +1 -0
- package/dist/v2/index.mjs +10 -0
- package/dist/v2/index.mjs.map +1 -0
- package/dist/v2/utils.cjs +122 -0
- package/dist/v2/utils.cjs.map +1 -0
- package/dist/v2/{utils.d.ts → utils.d.cts} +5 -5
- package/dist/v2/utils.d.cts.map +1 -0
- package/dist/v2/utils.d.mts +85 -0
- package/dist/v2/utils.d.mts.map +1 -0
- package/dist/v2/{utils.js → utils.mjs} +3 -3
- package/dist/v2/utils.mjs.map +1 -0
- package/package.json +25 -15
- package/dist/JsonRpcEngine.d.ts.map +0 -1
- package/dist/JsonRpcEngine.js.map +0 -1
- package/dist/asV2Middleware.d.ts.map +0 -1
- package/dist/asV2Middleware.js.map +0 -1
- package/dist/createAsyncMiddleware.d.ts.map +0 -1
- package/dist/createAsyncMiddleware.js.map +0 -1
- package/dist/createMethodMiddleware.d.ts.map +0 -1
- package/dist/createMethodMiddleware.js.map +0 -1
- package/dist/createOriginMiddleware.d.ts.map +0 -1
- package/dist/createOriginMiddleware.js.map +0 -1
- package/dist/createScaffoldMiddleware.d.ts.map +0 -1
- package/dist/createScaffoldMiddleware.js.map +0 -1
- package/dist/getUniqueId.d.ts.map +0 -1
- package/dist/getUniqueId.js.map +0 -1
- package/dist/idRemapMiddleware.d.ts.map +0 -1
- package/dist/idRemapMiddleware.js.map +0 -1
- package/dist/index.d.ts +0 -13
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -10
- package/dist/index.js.map +0 -1
- package/dist/mergeMiddleware.d.ts.map +0 -1
- package/dist/mergeMiddleware.js.map +0 -1
- package/dist/v2/JsonRpcEngineV2.d.ts.map +0 -1
- package/dist/v2/JsonRpcEngineV2.js.map +0 -1
- package/dist/v2/JsonRpcServer.d.ts.map +0 -1
- package/dist/v2/JsonRpcServer.js.map +0 -1
- package/dist/v2/MiddlewareContext.d.ts.map +0 -1
- package/dist/v2/MiddlewareContext.js.map +0 -1
- package/dist/v2/asLegacyMiddleware.d.ts.map +0 -1
- package/dist/v2/asLegacyMiddleware.js.map +0 -1
- package/dist/v2/compatibility-utils.d.ts.map +0 -1
- package/dist/v2/compatibility-utils.js.map +0 -1
- package/dist/v2/createMethodMiddleware.d.ts.map +0 -1
- package/dist/v2/createMethodMiddleware.js.map +0 -1
- package/dist/v2/createOriginMiddleware.d.ts.map +0 -1
- package/dist/v2/createOriginMiddleware.js.map +0 -1
- package/dist/v2/createScaffoldMiddleware.d.ts.map +0 -1
- package/dist/v2/createScaffoldMiddleware.js.map +0 -1
- package/dist/v2/index.d.ts +0 -14
- package/dist/v2/index.d.ts.map +0 -1
- package/dist/v2/index.js +0 -10
- package/dist/v2/index.js.map +0 -1
- package/dist/v2/utils.d.ts.map +0 -1
- package/dist/v2/utils.js.map +0 -1
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { ActionConstraint } from "@metamask/messenger";
|
|
2
|
+
import { Messenger } from "@metamask/messenger";
|
|
3
|
+
import type { JsonRpcNotification, JsonRpcParams, JsonRpcRequest } from "@metamask/utils";
|
|
4
|
+
export type { Json, JsonRpcParams, JsonRpcRequest, JsonRpcNotification, } from "@metamask/utils";
|
|
5
|
+
export type JsonRpcCall<Params extends JsonRpcParams = JsonRpcParams> = JsonRpcNotification<Params> | JsonRpcRequest<Params>;
|
|
6
|
+
export declare const isRequest: <Params extends JsonRpcParams>(message: JsonRpcCall<Params> | Readonly<JsonRpcCall<Params>>) => message is JsonRpcRequest<Params>;
|
|
7
|
+
export declare const isNotification: <Params extends JsonRpcParams>(message: JsonRpcCall<Params>) => message is JsonRpcNotification<Params>;
|
|
8
|
+
/**
|
|
9
|
+
* An unholy incantation that converts a union of object types into an
|
|
10
|
+
* intersection of object types.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* type A = { a: string } | { b: number };
|
|
14
|
+
* type B = UnionToIntersection<A>; // { a: string } & { b: number }
|
|
15
|
+
*/
|
|
16
|
+
export type UnionToIntersection<Union> = (Union extends never ? never : (k: Union) => void) extends (k: infer Args) => void ? Args : never;
|
|
17
|
+
/**
|
|
18
|
+
* JSON-stringifies a value.
|
|
19
|
+
*
|
|
20
|
+
* @param value - The value to stringify.
|
|
21
|
+
* @returns The stringified value.
|
|
22
|
+
*/
|
|
23
|
+
export declare function stringify(value: unknown): string;
|
|
24
|
+
/**
|
|
25
|
+
* The implementation of static `isInstance` methods for classes that have them.
|
|
26
|
+
*
|
|
27
|
+
* @param value - The value to check.
|
|
28
|
+
* @param symbol - The symbol property to check for.
|
|
29
|
+
* @returns Whether the value has `{ [symbol]: true }` in its prototype chain.
|
|
30
|
+
*/
|
|
31
|
+
export declare const isInstance: (value: unknown, symbol: symbol) => value is {
|
|
32
|
+
[key: symbol]: true;
|
|
33
|
+
};
|
|
34
|
+
declare const JsonRpcEngineErrorSymbol: unique symbol;
|
|
35
|
+
export declare class JsonRpcEngineError extends Error {
|
|
36
|
+
private readonly [JsonRpcEngineErrorSymbol];
|
|
37
|
+
constructor(message: string);
|
|
38
|
+
/**
|
|
39
|
+
* Check if a value is a {@link JsonRpcEngineError} instance.
|
|
40
|
+
* Works across different package versions in the same realm.
|
|
41
|
+
*
|
|
42
|
+
* @param value - The value to check.
|
|
43
|
+
* @returns Whether the value is a {@link JsonRpcEngineError} instance.
|
|
44
|
+
*/
|
|
45
|
+
static isInstance(value: unknown): value is JsonRpcEngineError;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Returns the subset of the specified `hooks` that are included in the
|
|
49
|
+
* `hookNames` object. This is a Principle of Least Authority (POLA) measure
|
|
50
|
+
* to ensure that each RPC method implementation only has access to the
|
|
51
|
+
* API "hooks" it needs to do its job.
|
|
52
|
+
*
|
|
53
|
+
* @param hooks - The hooks to select from.
|
|
54
|
+
* @param hookNames - The names of the hooks to select.
|
|
55
|
+
* @returns The selected hooks, or `undefined` if `hookNames` is not provided.
|
|
56
|
+
* @template Hooks - The hooks to select from.
|
|
57
|
+
* @template HookName - The names of the hooks to select.
|
|
58
|
+
*/
|
|
59
|
+
export declare function selectHooks<Hooks, HookName extends keyof Hooks>(hooks: Hooks, hookNames?: Record<HookName, true>): Pick<Hooks, HookName> | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* Asserts that `hooks` contains exactly the hook names in `expectedHookNames`.
|
|
62
|
+
* Throws on any missing hooks, then on any extraneous hooks.
|
|
63
|
+
*
|
|
64
|
+
* @param hooks - The hooks object to validate.
|
|
65
|
+
* @param expectedHookNames - The expected hook names.
|
|
66
|
+
*/
|
|
67
|
+
export declare function assertExpectedHooks(hooks: Record<string, unknown>, expectedHookNames: Set<string>): void;
|
|
68
|
+
/**
|
|
69
|
+
* Creates a per-handler messenger namespaced to `namespace`, and delegates the
|
|
70
|
+
* specified `actionNames` from `rootMessenger` to it. This lets each handler
|
|
71
|
+
* call only the actions it declared, per POLA.
|
|
72
|
+
*
|
|
73
|
+
* @param options - The options.
|
|
74
|
+
* @param options.namespace - The namespace for the handler messenger.
|
|
75
|
+
* @param options.actionNames - Actions to delegate from the root messenger.
|
|
76
|
+
* @param options.rootMessenger - The root messenger to delegate from. Required
|
|
77
|
+
* when `actionNames` are provided.
|
|
78
|
+
* @returns The per-handler messenger.
|
|
79
|
+
*/
|
|
80
|
+
export declare function createHandlerMessenger<Actions extends ActionConstraint>({ namespace, actionNames, rootMessenger, }: {
|
|
81
|
+
namespace: string;
|
|
82
|
+
actionNames: readonly Actions['type'][] | undefined;
|
|
83
|
+
rootMessenger?: Messenger<string, Actions> | undefined;
|
|
84
|
+
}): Messenger<string, Actions> | undefined;
|
|
85
|
+
//# sourceMappingURL=utils.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../../src/v2/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,4BAA4B;AAC5D,OAAO,EAAE,SAAS,EAAE,4BAA4B;AAEhD,OAAO,KAAK,EACV,mBAAmB,EACnB,aAAa,EACb,cAAc,EACf,wBAAwB;AAEzB,YAAY,EACV,IAAI,EACJ,aAAa,EACb,cAAc,EACd,mBAAmB,GACpB,wBAAwB;AAEzB,MAAM,MAAM,WAAW,CAAC,MAAM,SAAS,aAAa,GAAG,aAAa,IAChE,mBAAmB,CAAC,MAAM,CAAC,GAC3B,cAAc,CAAC,MAAM,CAAC,CAAC;AAE3B,eAAO,MAAM,SAAS,mIAE4C,CAAC;AAEnE,eAAO,MAAM,cAAc,wGAEqC,CAAC;AAEjE;;;;;;;GAOG;AACH,MAAM,MAAM,mBAAmB,CAAC,KAAK,IAAI,CACvC,KAAK,SAAS,KAAK,GAAG,KAAK,GAAG,CAAC,CAAC,EAAE,KAAK,KAAK,IAAI,CACjD,SAAS,CAAC,CAAC,EAAE,MAAM,IAAI,KAAK,IAAI,GAC7B,IAAI,GACJ,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
var _a;
|
|
2
|
-
import { Messenger } from
|
|
3
|
-
import { hasProperty, isObject } from
|
|
2
|
+
import { Messenger } from "@metamask/messenger";
|
|
3
|
+
import { hasProperty, isObject } from "@metamask/utils";
|
|
4
4
|
export const isRequest = (message) => hasProperty(message, 'id');
|
|
5
5
|
export const isNotification = (message) => !isRequest(message);
|
|
6
6
|
/**
|
|
@@ -108,4 +108,4 @@ export function createHandlerMessenger({ namespace, actionNames, rootMessenger,
|
|
|
108
108
|
});
|
|
109
109
|
return handlerMessenger;
|
|
110
110
|
}
|
|
111
|
-
//# sourceMappingURL=utils.
|
|
111
|
+
//# sourceMappingURL=utils.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/v2/utils.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,SAAS,EAAE,4BAA4B;AAChD,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,wBAAwB;AAkBxD,MAAM,CAAC,MAAM,SAAS,GAAG,CACvB,OAA4D,EACzB,EAAE,CAAC,WAAW,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AAEnE,MAAM,CAAC,MAAM,cAAc,GAAG,CAC5B,OAA4B,EACY,EAAE,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;AAgBjE;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,KAAc;IACtC,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACxC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CACxB,KAAc,EACd,MAAc,EACoB,EAAE,CACpC,QAAQ,CAAC,KAAK,CAAC,IAAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,IAAI,CAAC;AAE/D,MAAM,wBAAwB,GAAG,MAAM,CAAC,GAAG,CACzC,oCAAoC,CACrC,CAAC;AAEF,MAA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AAM,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC,MAAM,CAClE,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,iBAAiB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAC/C,CAAC;IACF,IAAI,mBAAmB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CACb,iCAAiC,mBAAmB,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CACpE,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,sBAAsB,CAAmC,EACvE,SAAS,EACT,WAAW,EACX,aAAa,GAKd;IACC,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CACb,8DAA8D,CAC/D,CAAC;IACJ,CAAC;IAED,MAAM,gBAAgB,GAAG,IAAI,SAAS,CAKpC,EAAE,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC,CAAC;IAExC,aAAa,CAAC,QAAQ,CAAC;QACrB,OAAO,EAAE,WAAgC;QACzC,SAAS,EAAE,gBAAgB;KAC5B,CAAC,CAAC;IAEH,OAAO,gBAAgB,CAAC;AAC1B,CAAC","sourcesContent":["import type { ActionConstraint } from '@metamask/messenger';\nimport { Messenger } from '@metamask/messenger';\nimport { hasProperty, isObject } from '@metamask/utils';\nimport type {\n JsonRpcNotification,\n JsonRpcParams,\n JsonRpcRequest,\n} from '@metamask/utils';\n\nexport type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcNotification,\n} from '@metamask/utils';\n\nexport type JsonRpcCall<Params extends JsonRpcParams = JsonRpcParams> =\n | JsonRpcNotification<Params>\n | JsonRpcRequest<Params>;\n\nexport const isRequest = <Params extends JsonRpcParams>(\n message: JsonRpcCall<Params> | Readonly<JsonRpcCall<Params>>,\n): message is JsonRpcRequest<Params> => hasProperty(message, 'id');\n\nexport const isNotification = <Params extends JsonRpcParams>(\n message: JsonRpcCall<Params>,\n): message is JsonRpcNotification<Params> => !isRequest(message);\n\n/**\n * An unholy incantation that converts a union of object types into an\n * intersection of object types.\n *\n * @example\n * type A = { a: string } | { b: number };\n * type B = UnionToIntersection<A>; // { a: string } & { b: number }\n */\nexport type UnionToIntersection<Union> = (\n Union extends never ? never : (k: Union) => void\n) extends (k: infer Args) => void\n ? Args\n : never;\n\n/**\n * JSON-stringifies a value.\n *\n * @param value - The value to stringify.\n * @returns The stringified value.\n */\nexport function stringify(value: unknown): string {\n return JSON.stringify(value, null, 2);\n}\n\n/**\n * The implementation of static `isInstance` methods for classes that have them.\n *\n * @param value - The value to check.\n * @param symbol - The symbol property to check for.\n * @returns Whether the value has `{ [symbol]: true }` in its prototype chain.\n */\nexport const isInstance = (\n value: unknown,\n symbol: symbol,\n): value is { [key: symbol]: true } =>\n isObject(value) && symbol in value && value[symbol] === true;\n\nconst JsonRpcEngineErrorSymbol = Symbol.for(\n 'json-rpc-engine#JsonRpcEngineError',\n);\n\nexport class JsonRpcEngineError extends Error {\n // This is a computed property name, and it doesn't seem possible to make it\n // hash private using `#`.\n // eslint-disable-next-line no-restricted-syntax\n private readonly [JsonRpcEngineErrorSymbol] = true;\n\n constructor(message: string) {\n super(message);\n this.name = 'JsonRpcEngineError';\n }\n\n /**\n * Check if a value is a {@link JsonRpcEngineError} instance.\n * Works across different package versions in the same realm.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link JsonRpcEngineError} instance.\n */\n static isInstance(value: unknown): value is JsonRpcEngineError {\n return isInstance(value, JsonRpcEngineErrorSymbol);\n }\n}\n\n// Method middleware utils\n\n/**\n * Returns the subset of the specified `hooks` that are included in the\n * `hookNames` object. This is a Principle of Least Authority (POLA) measure\n * to ensure that each RPC method implementation only has access to the\n * API \"hooks\" it needs to do its job.\n *\n * @param hooks - The hooks to select from.\n * @param hookNames - The names of the hooks to select.\n * @returns The selected hooks, or `undefined` if `hookNames` is not provided.\n * @template Hooks - The hooks to select from.\n * @template HookName - The names of the hooks to select.\n */\nexport function selectHooks<Hooks, HookName extends keyof Hooks>(\n hooks: Hooks,\n hookNames?: Record<HookName, true>,\n): Pick<Hooks, HookName> | undefined {\n if (hookNames) {\n return Object.keys(hookNames).reduce<Partial<Pick<Hooks, HookName>>>(\n (subset, name) => {\n const hookName = name as HookName;\n subset[hookName] = hooks[hookName];\n return subset;\n },\n {},\n ) as Pick<Hooks, HookName>;\n }\n return undefined;\n}\n\n/**\n * Asserts that `hooks` contains exactly the hook names in `expectedHookNames`.\n * Throws on any missing hooks, then on any extraneous hooks.\n *\n * @param hooks - The hooks object to validate.\n * @param expectedHookNames - The expected hook names.\n */\nexport function assertExpectedHooks(\n hooks: Record<string, unknown>,\n expectedHookNames: Set<string>,\n): void {\n const missingHookNames = Array.from(expectedHookNames).filter(\n (hookName) => !hasProperty(hooks, hookName),\n );\n if (missingHookNames.length > 0) {\n throw new Error(\n `Missing expected hooks:\\n\\n${missingHookNames.join('\\n')}\\n`,\n );\n }\n\n const extraneousHookNames = Object.getOwnPropertyNames(hooks).filter(\n (hookName) => !expectedHookNames.has(hookName),\n );\n if (extraneousHookNames.length > 0) {\n throw new Error(\n `Received unexpected hooks:\\n\\n${extraneousHookNames.join('\\n')}\\n`,\n );\n }\n}\n\n/**\n * Creates a per-handler messenger namespaced to `namespace`, and delegates the\n * specified `actionNames` from `rootMessenger` to it. This lets each handler\n * call only the actions it declared, per POLA.\n *\n * @param options - The options.\n * @param options.namespace - The namespace for the handler messenger.\n * @param options.actionNames - Actions to delegate from the root messenger.\n * @param options.rootMessenger - The root messenger to delegate from. Required\n * when `actionNames` are provided.\n * @returns The per-handler messenger.\n */\nexport function createHandlerMessenger<Actions extends ActionConstraint>({\n namespace,\n actionNames,\n rootMessenger,\n}: {\n namespace: string;\n actionNames: readonly Actions['type'][] | undefined;\n rootMessenger?: Messenger<string, Actions> | undefined;\n}): Messenger<string, Actions> | undefined {\n if (!actionNames) {\n return undefined;\n }\n\n if (!rootMessenger) {\n throw new Error(\n 'A messenger is required when a handler declares actionNames.',\n );\n }\n\n const handlerMessenger = new Messenger<\n string,\n Actions,\n never,\n typeof rootMessenger\n >({ namespace, parent: rootMessenger });\n\n rootMessenger.delegate({\n actions: actionNames as Actions['type'][],\n messenger: handlerMessenger,\n });\n\n return handlerMessenger;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/json-rpc-engine",
|
|
3
|
-
"version": "10.5.0-preview-
|
|
3
|
+
"version": "10.5.0-preview-eb263b0ee",
|
|
4
4
|
"description": "A tool for processing JSON-RPC messages",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -22,16 +22,29 @@
|
|
|
22
22
|
"dist/",
|
|
23
23
|
"v2.js"
|
|
24
24
|
],
|
|
25
|
-
"type": "module",
|
|
26
25
|
"sideEffects": false,
|
|
26
|
+
"main": "./dist/index.cjs",
|
|
27
|
+
"types": "./dist/index.d.cts",
|
|
27
28
|
"exports": {
|
|
28
29
|
".": {
|
|
29
|
-
"
|
|
30
|
-
|
|
30
|
+
"import": {
|
|
31
|
+
"types": "./dist/index.d.mts",
|
|
32
|
+
"default": "./dist/index.mjs"
|
|
33
|
+
},
|
|
34
|
+
"require": {
|
|
35
|
+
"types": "./dist/index.d.cts",
|
|
36
|
+
"default": "./dist/index.cjs"
|
|
37
|
+
}
|
|
31
38
|
},
|
|
32
39
|
"./v2": {
|
|
33
|
-
"
|
|
34
|
-
|
|
40
|
+
"import": {
|
|
41
|
+
"types": "./dist/v2/index.d.mts",
|
|
42
|
+
"default": "./dist/v2/index.mjs"
|
|
43
|
+
},
|
|
44
|
+
"require": {
|
|
45
|
+
"types": "./dist/v2/index.d.cts",
|
|
46
|
+
"default": "./dist/v2/index.cjs"
|
|
47
|
+
}
|
|
35
48
|
},
|
|
36
49
|
"./package.json": "./package.json"
|
|
37
50
|
},
|
|
@@ -40,11 +53,9 @@
|
|
|
40
53
|
"registry": "https://registry.npmjs.org/"
|
|
41
54
|
},
|
|
42
55
|
"scripts": {
|
|
43
|
-
"build": "
|
|
44
|
-
"build:all": "
|
|
45
|
-
"build:clean": "yarn build:only-clean && yarn build",
|
|
56
|
+
"build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
|
|
57
|
+
"build:all": "ts-bridge --project tsconfig.build.json --verbose --clean",
|
|
46
58
|
"build:docs": "typedoc",
|
|
47
|
-
"build:only-clean": "rimraf './dist' './tsconfig.build.tsbuildinfo'",
|
|
48
59
|
"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",
|
|
49
60
|
"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",
|
|
50
61
|
"lint:tsconfigs": "tsx ../../scripts/lint-tsconfigs/lint-tsconfigs.mts",
|
|
@@ -58,7 +69,7 @@
|
|
|
58
69
|
"dependencies": {
|
|
59
70
|
"@metamask/messenger": "^2.0.0",
|
|
60
71
|
"@metamask/rpc-errors": "^7.0.2",
|
|
61
|
-
"@metamask/safe-event-emitter": "^3.
|
|
72
|
+
"@metamask/safe-event-emitter": "^3.0.0",
|
|
62
73
|
"@metamask/utils": "^11.11.0",
|
|
63
74
|
"@types/deep-freeze-strict": "^1.1.0",
|
|
64
75
|
"deep-freeze-strict": "^1.1.1",
|
|
@@ -68,18 +79,17 @@
|
|
|
68
79
|
"@lavamoat/allow-scripts": "^3.0.4",
|
|
69
80
|
"@lavamoat/preinstall-always-fail": "^2.1.0",
|
|
70
81
|
"@metamask/auto-changelog": "^6.1.0",
|
|
82
|
+
"@ts-bridge/cli": "^0.6.4",
|
|
71
83
|
"@types/jest": "^30.0.0",
|
|
72
|
-
"@typescript/native": "npm:typescript@^7.0.2",
|
|
73
84
|
"deepmerge": "^4.2.2",
|
|
74
85
|
"jest": "^30.4.2",
|
|
75
|
-
"rimraf": "^5.0.5",
|
|
76
86
|
"ts-jest": "^29.4.11",
|
|
77
87
|
"tsx": "^4.20.5",
|
|
78
88
|
"typedoc": "^0.25.13",
|
|
79
|
-
"typescript": "
|
|
89
|
+
"typescript": "~5.3.3"
|
|
80
90
|
},
|
|
81
91
|
"engines": {
|
|
82
|
-
"node": "^
|
|
92
|
+
"node": "^18.18 || >=20"
|
|
83
93
|
},
|
|
84
94
|
"lavamoat": {
|
|
85
95
|
"allowScripts": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcEngine.d.ts","sourceRoot":"","sources":["../src/JsonRpcEngine.ts"],"names":[],"mappings":"AACA,OAAO,gBAAgB,MAAM,8BAA8B,CAAC;AAC5D,OAAO,KAAK,EACV,YAAY,IAAI,sBAAsB,EACtC,cAAc,EACd,eAAe,EACf,mBAAmB,EACnB,IAAI,EACJ,aAAa,EACb,sBAAsB,EACvB,MAAM,iBAAiB,CAAC;AASzB,MAAM,MAAM,0BAA0B,GAAG,KAAK,GAAG,sBAAsB,GAAG,IAAI,CAAC;AAE/E;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG,CACvC,IAAI,EAAE,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,IAAI,KAC5B,IAAI,CAAC;AAEV;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG,CACtC,qBAAqB,CAAC,EAAE,0BAA0B,KAC/C,IAAI,CAAC;AAEV;;GAEG;AACH,MAAM,MAAM,wBAAwB,GAAG,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;AAEjE;;GAEG;AACH,MAAM,MAAM,iBAAiB,CAC3B,MAAM,SAAS,aAAa,EAC5B,MAAM,SAAS,IAAI,IACjB;IACF,CACE,GAAG,EAAE,cAAc,CAAC,MAAM,CAAC,EAC3B,GAAG,EAAE,sBAAsB,CAAC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AC,CAAC,CAAC;YACzB,CAAC;QACH,CAAC,CAAC;QAEF,IAAI,CAAC;YACH,UAAU,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;QAC3C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,KAAK,CAAC,CAAC;QACb,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC,qCAQM,KAAK,2CACV,QAAsC;IAEtC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAC1C,4CAA4C;YAC5C,2EAA2E;YAC3E,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;QAC1D,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,iFAYC,OAAuB,EACvB,QAAgC,EAChC,UAAmB;IAEnB,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,CAAC;QACxE,MAAM,IAAI,YAAY,CACpB,UAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,gEAAgE,SAAS,CACvE,OAAO,CACR,EAAE,EACH,EAAE,OAAO,EAAE,CACZ,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,MAAM,IAAI,YAAY,CACpB,UAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,0CAA0C,SAAS,CAAC,OAAO,CAAC,EAAE,EAC9D,EAAE,OAAO,EAAE,CACZ,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { errorCodes, JsonRpcError, serializeError } from '@metamask/rpc-errors';\nimport SafeEventEmitter from '@metamask/safe-event-emitter';\nimport type {\n JsonRpcError as SerializedJsonRpcError,\n JsonRpcRequest,\n JsonRpcResponse,\n JsonRpcNotification,\n Json,\n JsonRpcParams,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\nimport {\n hasProperty,\n isJsonRpcNotification,\n isJsonRpcRequest,\n} from '@metamask/utils';\n\nimport { stringify } from './v2/utils.js';\n\nexport type JsonRpcEngineCallbackError = Error | SerializedJsonRpcError | null;\n\n/**\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n */\nexport type JsonRpcEngineReturnHandler = (\n done: (error?: unknown) => void,\n) => void;\n\n/**\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n */\nexport type JsonRpcEngineNextCallback = (\n returnHandlerCallback?: JsonRpcEngineReturnHandler,\n) => void;\n\n/**\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n */\nexport type JsonRpcEngineEndCallback = (error?: unknown) => void;\n\n/**\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n */\nexport type JsonRpcMiddleware<\n Params extends JsonRpcParams,\n Result extends Json,\n> = {\n (\n req: JsonRpcRequest<Params>,\n res: PendingJsonRpcResponse<Result>,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n ): void;\n destroy?: () => void | Promise<void>;\n};\n\nconst DESTROYED_ERROR_MESSAGE =\n 'This engine is destroyed and can no longer be used.';\n\n/**\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n */\nexport type JsonRpcNotificationHandler<Params extends JsonRpcParams> = (\n notification: JsonRpcNotification<Params>,\n) => void | Promise<void>;\n\ntype JsonRpcEngineArgs = {\n /**\n * A function for handling JSON-RPC notifications. A JSON-RPC notification is\n * defined as a JSON-RPC request without an `id` property. If this option is\n * _not_ provided, notifications will be treated the same as requests. If this\n * option _is_ provided, notifications will be passed to the handler\n * function without touching the engine's middleware stack.\n *\n * This function should not throw or reject.\n */\n notificationHandler?: JsonRpcNotificationHandler<JsonRpcParams>;\n};\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 * @deprecated Use `JsonRpcEngineV2` instead.\n */\nexport class JsonRpcEngine extends SafeEventEmitter {\n /**\n * Indicating whether this engine is destroyed or not.\n */\n #isDestroyed = false;\n\n #middleware: JsonRpcMiddleware<JsonRpcParams, Json>[];\n\n readonly #notificationHandler?:\n | JsonRpcNotificationHandler<JsonRpcParams>\n | undefined;\n\n /**\n * Constructs a {@link JsonRpcEngine} instance.\n *\n * @param options - Options bag.\n * @param options.notificationHandler - A function for handling JSON-RPC\n * notifications. A JSON-RPC notification is defined as a JSON-RPC request\n * without an `id` property. If this option is _not_ provided, notifications\n * will be treated the same as requests. If this option _is_ provided,\n * notifications will be passed to the handler function without touching\n * the engine's middleware stack. This function should not throw or reject.\n */\n constructor({ notificationHandler }: JsonRpcEngineArgs = {}) {\n super();\n this.#middleware = [];\n this.#notificationHandler = notificationHandler;\n }\n\n /**\n * Throws an error if this engine is destroyed.\n */\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new Error(DESTROYED_ERROR_MESSAGE);\n }\n }\n\n /**\n * Calls the `destroy()` function of any middleware with that property, clears\n * the middleware array, and marks this engine as destroyed. A destroyed\n * engine cannot be used.\n */\n destroy(): void {\n this.#middleware.forEach(\n (middleware: JsonRpcMiddleware<JsonRpcParams, Json>) => {\n if (\n // `in` walks the prototype chain, which is probably the desired\n // behavior here.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n middleware.destroy();\n }\n },\n );\n this.#middleware = [];\n this.#isDestroyed = true;\n }\n\n /**\n * Add a middleware function to the engine's middleware stack.\n *\n * @param middleware - The middleware function to add.\n */\n push<Params extends JsonRpcParams, Result extends Json>(\n middleware: JsonRpcMiddleware<Params, Result>,\n ): void {\n this.#assertIsNotDestroyed();\n this.#middleware.push(middleware as JsonRpcMiddleware<JsonRpcParams, Json>);\n }\n\n /**\n * Handle a JSON-RPC request, and return a response.\n *\n * @param request - The request to handle.\n * @param callback - An error-first callback that will receive the response.\n */\n handle<Params extends JsonRpcParams, Result extends Json>(\n request: JsonRpcRequest<Params>,\n callback: (error: unknown, response: JsonRpcResponse<Result>) => void,\n ): void;\n\n /**\n * Handle a JSON-RPC notification.\n *\n * @param notification - The notification to handle.\n * @param callback - An error-first callback that will receive a `void` response.\n */\n handle<Params extends JsonRpcParams>(\n notification: JsonRpcNotification<Params>,\n callback: (error: unknown, response: void) => void,\n ): void;\n\n /**\n * Handle an array of JSON-RPC requests and/or notifications, and return an\n * array of responses to any included requests.\n *\n * @param request - The requests to handle.\n * @param callback - An error-first callback that will receive the array of\n * responses.\n */\n handle<Params extends JsonRpcParams, Result extends Json>(\n requests: (JsonRpcRequest<Params> | JsonRpcNotification<Params>)[],\n callback: (error: unknown, responses: JsonRpcResponse<Result>[]) => void,\n ): void;\n\n /**\n * Handle a JSON-RPC request, and return a response.\n *\n * @param request - The JSON-RPC request to handle.\n * @returns The JSON-RPC response.\n */\n handle<Params extends JsonRpcParams, Result extends Json>(\n request: JsonRpcRequest<Params>,\n ): Promise<JsonRpcResponse<Result>>;\n\n /**\n * Handle a JSON-RPC notification.\n *\n * @param notification - The notification to handle.\n */\n handle<Params extends JsonRpcParams>(\n notification: JsonRpcNotification<Params>,\n ): Promise<void>;\n\n /**\n * Handle an array of JSON-RPC requests and/or notifications, and return an\n * array of responses to any included requests.\n *\n * @param request - The JSON-RPC requests to handle.\n * @returns An array of JSON-RPC responses.\n */\n handle<Params extends JsonRpcParams, Result extends Json>(\n requests: (JsonRpcRequest<Params> | JsonRpcNotification<Params>)[],\n ): Promise<JsonRpcResponse<Result>[]>;\n\n handle(\n req:\n | (JsonRpcRequest | JsonRpcNotification)[]\n | JsonRpcRequest\n | JsonRpcNotification,\n callback?: (error: unknown, response: never) => void,\n ): Promise<JsonRpcResponse[]> | Promise<JsonRpcResponse | void> {\n this.#assertIsNotDestroyed();\n\n if (callback && typeof callback !== 'function') {\n throw new Error('\"callback\" must be a function if provided.');\n }\n\n if (Array.isArray(req)) {\n if (callback) {\n return this.#handleBatch(\n req,\n // This assertion is safe because of the runtime checks validating that `req` is an array and `callback` is defined.\n // There is only one overload signature that satisfies both conditions, and its `callback` type is the one that's being asserted.\n callback as (error: unknown, responses?: JsonRpcResponse[]) => void,\n );\n }\n return this.#handleBatch(req);\n }\n\n if (callback) {\n return this.#handle(\n req,\n callback as (error: unknown, response?: JsonRpcResponse) => void,\n );\n }\n return this._promiseHandle(req);\n }\n\n /**\n * Returns this engine as a middleware function that can be pushed to other\n * engines.\n *\n * @returns This engine as a middleware function.\n */\n asMiddleware(): JsonRpcMiddleware<JsonRpcParams, Json> {\n this.#assertIsNotDestroyed();\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n return async (req, res, next, end) => {\n try {\n const [middlewareError, isComplete, returnHandlers] =\n await JsonRpcEngine.#runAllMiddleware(req, res, this.#middleware);\n\n if (isComplete) {\n await JsonRpcEngine.#runReturnHandlers(returnHandlers);\n return end(middlewareError);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n return next(async (handlerCallback) => {\n try {\n await JsonRpcEngine.#runReturnHandlers(returnHandlers);\n } catch (error) {\n return handlerCallback(error);\n }\n return handlerCallback();\n });\n } catch (error) {\n return end(error);\n }\n };\n }\n\n /**\n * Like _handle, but for batch requests.\n */\n #handleBatch(\n reqs: (JsonRpcRequest | JsonRpcNotification)[],\n ): Promise<JsonRpcResponse[]>;\n\n /**\n * Like _handle, but for batch requests.\n */\n #handleBatch(\n reqs: (JsonRpcRequest | JsonRpcNotification)[],\n callback: (error: unknown, responses?: JsonRpcResponse[]) => void,\n ): Promise<void>;\n\n /**\n * Handles a batch of JSON-RPC requests, either in `async` or callback\n * fashion.\n *\n * @param requests - The request objects to process.\n * @param callback - The completion callback.\n * @returns The array of responses, or nothing if a callback was specified.\n */\n async #handleBatch(\n requests: (JsonRpcRequest | JsonRpcNotification)[],\n callback?: (error: unknown, responses?: JsonRpcResponse[]) => void,\n ): Promise<JsonRpcResponse[] | void> {\n // The order here is important\n try {\n // If the batch is an empty array, the response array must contain a single object\n if (requests.length === 0) {\n const response: JsonRpcResponse[] = [\n {\n id: null,\n jsonrpc: '2.0',\n error: new JsonRpcError(\n errorCodes.rpc.invalidRequest,\n 'Request batch must contain plain objects. Received an empty array',\n ),\n },\n ];\n if (callback) {\n return callback(null, response);\n }\n return response;\n }\n\n // 2. Wait for all requests to finish, or throw on some kind of fatal\n // error\n const responses = (\n await Promise.all(\n // 1. Begin executing each request in the order received\n requests.map(this._promiseHandle.bind(this)),\n )\n ).filter(\n // Filter out any notification responses.\n (response): response is JsonRpcResponse => response !== undefined,\n );\n\n // 3. Return batch response\n if (callback) {\n return callback(null, responses);\n }\n return responses;\n } catch (error) {\n if (callback) {\n return callback(error);\n }\n\n throw error;\n }\n }\n\n /**\n * A promise-wrapped _handle.\n *\n * @param request - The JSON-RPC request.\n * @returns The JSON-RPC response.\n */\n // This function is used in tests, so we cannot easily change it to use the\n // hash syntax.\n // eslint-disable-next-line no-restricted-syntax\n private async _promiseHandle(\n request: JsonRpcRequest | JsonRpcNotification,\n ): Promise<JsonRpcResponse | void> {\n return new Promise((resolve, reject) => {\n this.#handle(request, (error, res) => {\n // For notifications, the response will be `undefined`, and any caught\n // errors are unexpected and should be surfaced to the caller.\n if (error && res === undefined) {\n // We are not going to change this behavior.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n } else {\n // Excepting notifications, there will always be a response, and it will\n // always have any error that is caught and propagated.\n resolve(res);\n }\n }).catch(reject);\n });\n }\n\n /**\n * Ensures that the request / notification object is valid, processes it, and\n * passes any error and response object to the given callback.\n *\n * Does not reject.\n *\n * @param callerReq - The request object from the caller.\n * @param callback - The callback function.\n * @returns Nothing.\n */\n async #handle(\n callerReq: JsonRpcRequest | JsonRpcNotification,\n callback: (error: unknown, response?: JsonRpcResponse) => void,\n ): Promise<void> {\n if (\n !callerReq ||\n Array.isArray(callerReq) ||\n typeof callerReq !== 'object'\n ) {\n const error = new JsonRpcError(\n errorCodes.rpc.invalidRequest,\n `Requests must be plain objects. Received: ${typeof callerReq}`,\n { request: callerReq },\n );\n return callback(error, { id: null, jsonrpc: '2.0', error });\n }\n\n if (typeof callerReq.method !== 'string') {\n const error = new JsonRpcError(\n errorCodes.rpc.invalidRequest,\n `Must specify a string method. Received: ${typeof callerReq.method}`,\n { request: callerReq },\n );\n\n if (this.#notificationHandler && !isJsonRpcRequest(callerReq)) {\n // Do not reply to notifications, even if they are malformed.\n return callback(null);\n }\n\n return callback(error, {\n // Typecast: This could be a notification, but we want to access the\n // `id` even if it doesn't exist.\n id: (callerReq as JsonRpcRequest).id ?? null,\n jsonrpc: '2.0',\n error,\n });\n } else if (\n this.#notificationHandler &&\n isJsonRpcNotification(callerReq) &&\n !isJsonRpcRequest(callerReq)\n ) {\n try {\n await this.#notificationHandler(callerReq);\n } catch (error) {\n return callback(error);\n }\n return callback(null);\n }\n let error = null;\n\n // Handle requests.\n // Typecast: Permit missing id's for backwards compatibility.\n const req = { ...(callerReq as JsonRpcRequest) };\n const res: PendingJsonRpcResponse = {\n id: req.id,\n jsonrpc: req.jsonrpc,\n };\n\n try {\n await JsonRpcEngine.#processRequest(req, res, this.#middleware);\n } catch (_error) {\n // A request handler error, a re-thrown middleware error, or something\n // unexpected.\n error = _error;\n }\n\n if (error) {\n // Ensure no result is present on an errored response\n delete res.result;\n res.error ??= serializeError(error);\n }\n\n return callback(error, res as JsonRpcResponse);\n }\n\n /**\n * For the given request and response, runs all middleware and their return\n * handlers, if any, and ensures that internal request processing semantics\n * are satisfied.\n *\n * @param req - The request object.\n * @param res - The response object.\n * @param middlewares - The stack of middleware functions.\n */\n static async #processRequest(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n middlewares: JsonRpcMiddleware<JsonRpcParams, Json>[],\n ): Promise<void> {\n const [error, isComplete, returnHandlers] =\n await JsonRpcEngine.#runAllMiddleware(req, res, middlewares);\n\n // Throw if \"end\" was not called, or if the response has neither a result\n // nor an error.\n JsonRpcEngine.#checkForCompletion(req, res, isComplete);\n\n // The return handlers should run even if an error was encountered during\n // middleware processing.\n await JsonRpcEngine.#runReturnHandlers(returnHandlers);\n\n // Now we re-throw the middleware processing error, if any, to catch it\n // further up the call chain.\n if (error) {\n // eslint-disable-next-line @typescript-eslint/only-throw-error\n throw error;\n }\n }\n\n /**\n * Serially executes the given stack of middleware.\n *\n * @param req - The request object.\n * @param res - The response object.\n * @param middlewares - The stack of middleware functions to execute.\n * @returns An array of any error encountered during middleware execution,\n * a boolean indicating whether the request was completed, and an array of\n * middleware-defined return handlers.\n */\n static async #runAllMiddleware(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n middlewares: JsonRpcMiddleware<JsonRpcParams, Json>[],\n ): Promise<\n [\n unknown, // error\n boolean, // isComplete\n JsonRpcEngineReturnHandler[],\n ]\n > {\n const returnHandlers: JsonRpcEngineReturnHandler[] = [];\n let error = null;\n let isComplete = false;\n\n // Go down stack of middleware, call and collect optional returnHandlers\n for (const middleware of middlewares) {\n [error, isComplete] = await JsonRpcEngine.#runMiddleware(\n req,\n res,\n middleware,\n returnHandlers,\n );\n\n if (isComplete) {\n break;\n }\n }\n return [error, isComplete, returnHandlers.reverse()];\n }\n\n /**\n * Runs an individual middleware function.\n *\n * @param request - The request object.\n * @param response - The response object.\n * @param middleware - The middleware function to execute.\n * @param returnHandlers - The return handlers array for the current request.\n * @returns An array of any error encountered during middleware execution,\n * and a boolean indicating whether the request should end.\n */\n static async #runMiddleware(\n request: JsonRpcRequest,\n response: PendingJsonRpcResponse,\n middleware: JsonRpcMiddleware<JsonRpcParams, Json>,\n returnHandlers: JsonRpcEngineReturnHandler[],\n ): Promise<[unknown, boolean]> {\n return new Promise((resolve) => {\n const end: JsonRpcEngineEndCallback = (error) => {\n const parsedError = error ?? response.error;\n if (parsedError) {\n response.error = serializeError(parsedError);\n }\n // True indicates that the request should end\n resolve([parsedError, true]);\n };\n\n const next: JsonRpcEngineNextCallback = (\n returnHandler?: JsonRpcEngineReturnHandler,\n ) => {\n if (response.error) {\n end(response.error);\n } else {\n if (returnHandler) {\n if (typeof returnHandler !== 'function') {\n end(\n new JsonRpcError(\n errorCodes.rpc.internal,\n `JsonRpcEngine: \"next\" return handlers must be functions. ` +\n `Received \"${typeof returnHandler}\" for request:\\n${stringify(\n request,\n )}`,\n { request },\n ),\n );\n }\n returnHandlers.push(returnHandler);\n }\n\n // False indicates that the request should not end\n resolve([null, false]);\n }\n };\n\n try {\n middleware(request, response, next, end);\n } catch (error) {\n end(error);\n }\n });\n }\n\n /**\n * Serially executes array of return handlers. The request and response are\n * assumed to be in their scope.\n *\n * @param handlers - The return handlers to execute.\n */\n static async #runReturnHandlers(\n handlers: JsonRpcEngineReturnHandler[],\n ): Promise<void> {\n for (const handler of handlers) {\n await new Promise<void>((resolve, reject) => {\n // We are not going to change this behavior.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n handler((error) => (error ? reject(error) : resolve()));\n });\n }\n }\n\n /**\n * Throws an error if the response has neither a result nor an error, or if\n * the \"isComplete\" flag is falsy.\n *\n * @param request - The request object.\n * @param response - The response object.\n * @param isComplete - Boolean from {@link JsonRpcEngine.#runAllMiddleware}\n * indicating whether a middleware ended the request.\n */\n static #checkForCompletion(\n request: JsonRpcRequest,\n response: PendingJsonRpcResponse,\n isComplete: boolean,\n ): void {\n if (!hasProperty(response, 'result') && !hasProperty(response, 'error')) {\n throw new JsonRpcError(\n errorCodes.rpc.internal,\n `JsonRpcEngine: Response has no error or result for request:\\n${stringify(\n request,\n )}`,\n { request },\n );\n }\n\n if (!isComplete) {\n throw new JsonRpcError(\n errorCodes.rpc.internal,\n `JsonRpcEngine: Nothing ended request:\\n${stringify(request)}`,\n { request },\n );\n }\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"asV2Middleware.d.ts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAGV,aAAa,EACb,cAAc,EAEf,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EACV,aAAa,EAGd,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,iBAAiB,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAShF,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAC1E,OAAO,KAAK,EAIV,iBAAiB,EACjB,gBAAgB,EACjB,MAAM,yBAAyB,CAAC;AAEjC;;;;;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,GAAG,aAAa,EAC5C,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,EAC/D,MAAM,SAAS,gBAAgB,CAAC,OAAO,CAAC,GAAG,gBAAgB,CAAC,OAAO,CAAC,EACpE,OAAO,SAAS,iBAAiB,GAAG,iBAAiB,EAErD,GAAG,UAAU,EAAE,gBAAgB,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,GAChD,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"asV2Middleware.js","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAe9C,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OA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;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,CAAC;YACrD,MAAM,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACzC,CAAC;aAAM,IAAI,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE,CAAC;YAC3C,OAAO,QAAQ,CAAC,MAAmC,CAAC;QACtD,CAAC;QACD,OAAO,IAAI,CAAC,iBAAiB,CAAC,GAAc,CAAC,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { serializeError } from '@metamask/rpc-errors';\nimport { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcFailure,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngine,\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from './JsonRpcEngine.js';\nimport type { JsonRpcMiddleware as LegacyMiddleware } from './JsonRpcEngine.js';\nimport { mergeMiddleware } from './mergeMiddleware.js';\nimport {\n deepClone,\n fromLegacyRequest,\n propagateToContext,\n propagateToRequest,\n deserializeError,\n} from './v2/compatibility-utils.js';\nimport type { ContextConstraint, MiddlewareContext } from './v2/index.js';\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.js';\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 = JsonRpcParams,\n Request extends JsonRpcRequest<Params> = JsonRpcRequest<Params>,\n Result extends ResultConstraint<Request> = ResultConstraint<Request>,\n Context extends ContextConstraint = MiddlewareContext,\n>(\n ...middleware: LegacyMiddleware<Params, Result>[]\n): JsonRpcMiddleware<Request, Result, Context>;\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 = ((callback: JsonRpcEngineEndCallback) =>\n callback(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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncMiddleware.d.ts","sourceRoot":"","sources":["../src/createAsyncMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,IAAI,EACJ,aAAa,EACb,cAAc,EACd,sBAAsB,EACvB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EAEV,iBAAiB,EAClB,MAAM,oBAAoB,CAAC;AAE5B,MAAM,MAAM,8BAA8B,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;AAEjE,MAAM,MAAM,sBAAsB,CAChC,MAAM,SAAS,aAAa,EAC5B,MAAM,SAAS,IAAI,IACjB,CACF,OAAO,EAAE,cAAc,CAAC,MAAM,CAAC,EAC/B,QAAQ,EAAE,sBAAsB,CAAC,MAAM,CAAC,EACxC,IAAI,EAAE,8BAA8B,KACjC,OAAO,CAAC,IAAI,CAAC,CAAC;AAInB;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,SAAS,aAAa,EAC5B,MAAM,SAAS,IAAI,EAEnB,eAAe,EAAE,sBAAsB,CAAC,MAAM,EAAE,MAAM,CAAC,GACtD,iBAAiB,CAAC,MAAM,EAAE,MAAM,CAAC,CA6CnC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncMiddleware.js","sourceRoot":"","sources":["../src/createAsyncMiddleware.ts"],"names":[],"mappings":"AAyBA;;;;;;;;;;;;;;;;;;;;;GAqBG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JsonRpcParams,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngineReturnHandler,\n JsonRpcMiddleware,\n} from './JsonRpcEngine.js';\n\nexport type AsyncJsonRpcEngineNextCallback = () => Promise<void>;\n\nexport type AsyncJsonrpcMiddleware<\n Params extends JsonRpcParams,\n Result extends Json,\n> = (\n request: JsonRpcRequest<Params>,\n response: PendingJsonRpcResponse<Result>,\n next: AsyncJsonRpcEngineNextCallback,\n) => Promise<void>;\n\ntype ReturnHandlerCallback = Parameters<JsonRpcEngineReturnHandler>[0];\n\n/**\n * JsonRpcEngine only accepts callback-based middleware directly.\n * createAsyncMiddleware exists to enable consumers to pass in async middleware\n * functions.\n *\n * Async middleware have no \"end\" function. Instead, they \"end\" if they return\n * without calling \"next\". Rather than passing in explicit return handlers,\n * async middleware can simply await \"next\", and perform operations on the\n * response object when execution resumes.\n *\n * To accomplish this, createAsyncMiddleware passes the async middleware a\n * wrapped \"next\" function. That function calls the internal JsonRpcEngine\n * \"next\" function with a return handler that resolves a promise when called.\n *\n * The return handler will always be called. Its resolution of the promise\n * enables the control flow described above.\n *\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n * @param asyncMiddleware - The asynchronous middleware function to wrap.\n * @returns The wrapped asynchronous middleware function, ready to be consumed\n * by JsonRpcEngine.\n */\nexport function createAsyncMiddleware<\n Params extends JsonRpcParams,\n Result extends Json,\n>(\n asyncMiddleware: AsyncJsonrpcMiddleware<Params, Result>,\n): JsonRpcMiddleware<Params, Result> {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n return async (request, response, next, end) => {\n // nextPromise is the key to the implementation\n // it is resolved by the return handler passed to the\n // \"next\" function\n let resolveNextPromise: () => void;\n const nextPromise = new Promise<void>((resolve) => {\n resolveNextPromise = resolve;\n });\n\n let returnHandlerCallback: unknown = null;\n let nextWasCalled = false;\n\n // This will be called by the consumer's async middleware.\n const asyncNext = async (): Promise<void> => {\n nextWasCalled = true;\n\n // We pass a return handler to next(). When it is called by the engine,\n // the consumer's async middleware will resume executing.\n next((runReturnHandlersCallback) => {\n // This callback comes from JsonRpcEngine._runReturnHandlers\n returnHandlerCallback = runReturnHandlersCallback;\n resolveNextPromise();\n });\n return nextPromise;\n };\n\n try {\n await asyncMiddleware(request, response, asyncNext);\n\n if (nextWasCalled) {\n await nextPromise; // we must wait until the return handler is called\n (returnHandlerCallback as ReturnHandlerCallback)(null);\n } else {\n end(null);\n }\n } catch (error) {\n if (returnHandlerCallback) {\n (returnHandlerCallback as ReturnHandlerCallback)(error);\n } else {\n end(error);\n }\n }\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"createMethodMiddleware.d.ts","sourceRoot":"","sources":["../src/createMethodMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAErD,OAAO,KAAK,EACV,IAAI,EACJ,aAAa,EACb,cAAc,EACd,sBAAsB,EACvB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EACzB,iBAAiB,EAClB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAIL,mBAAmB,EACpB,MAAM,eAAe,CAAC;AAEvB,KAAK,cAAc,CAAC,OAAO,IAAI,OAAO,SAAS;IAC7C,cAAc,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,IAAI,KAAK,OAAO,CAAC;CAClD,GACG,IAAI,SAAS;IACX,OAAO;IACP,OAAO;IACP,OAAO;IACP,OAAO;IACP,OAAO;IACP,MAAM,gBAAgB;CACvB,GACC,gBAAgB,SAAS,SAAS,CAAC,MAAM,EAAE,MAAM,OAAO,CAAC,GACvD,OAAO,GACP,KAAK,GACP,KAAK,GACP,KAAK,CAAC;AAEV,KAAK,YAAY,CAAC,OAAO,IAAI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AE,IAAI,EAAE,GAAG,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;QAC5E,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,EAAE,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;YACtB,OAAO,GAAG,CACR,KAAK,YAAY,KAAK;gBACpB,CAAC,CAAC,KAAK;gBACP,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,KAAa,EAAE,CAAC,CAChD,CAAC;QACJ,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ActionConstraint } from '@metamask/messenger';\nimport type { Messenger } from '@metamask/messenger';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n JsonRpcMiddleware,\n} from './JsonRpcEngine.js';\nimport {\n assertExpectedHooks,\n createHandlerMessenger,\n selectHooks,\n UnionToIntersection,\n} from './v2/utils.js';\n\ntype HandlerActions<Handler> = Handler extends {\n implementation: (...args: infer Args) => unknown;\n}\n ? Args extends [\n unknown,\n unknown,\n unknown,\n unknown,\n unknown,\n infer HandlerMessenger,\n ]\n ? HandlerMessenger extends Messenger<string, infer Actions>\n ? Actions\n : never\n : never\n : never;\n\ntype HandlerHooks<Handler> = Handler extends {\n implementation: (...args: infer Args) => unknown;\n}\n ? Args extends [\n unknown,\n unknown,\n unknown,\n unknown,\n infer ArgHooks,\n ...unknown[],\n ]\n ? ArgHooks extends Record<string, unknown>\n ? ArgHooks\n : never\n : never\n : never;\n\n/**\n * A {@link MethodHandler} implementation.\n *\n * @deprecated Use the v2 `createMethodMiddleware` instead.\n */\nexport type MethodHandlerImplementation<\n Hooks extends Record<string, unknown> = never,\n MessengerActions extends ActionConstraint = never,\n Params extends JsonRpcParams = JsonRpcParams,\n Result extends Json = Json,\n RequestExtras extends Record<string, unknown> = Record<string, unknown>,\n> = (\n req: JsonRpcRequest<Params> & RequestExtras,\n res: PendingJsonRpcResponse<Result>,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n hooks: Hooks,\n messenger: Messenger<string, MessengerActions>,\n) => Promise<void> | void;\n\n/**\n * A handler for {@link createMethodMiddleware}.\n *\n * @deprecated Use the v2 `createMethodMiddleware` instead.\n */\nexport type MethodHandler<\n Hooks extends Record<string, unknown> = never,\n MessengerActions extends ActionConstraint = never,\n Params extends JsonRpcParams = JsonRpcParams,\n Result extends Json = Json,\n RequestExtras extends Record<string, unknown> = Record<string, unknown>,\n> = {\n implementation: MethodHandlerImplementation<\n Hooks,\n MessengerActions,\n Params,\n Result,\n RequestExtras\n >;\n} & ([Hooks] extends [never]\n ? { hookNames?: undefined }\n : { hookNames: { [Key in keyof Hooks]: true } }) &\n ([MessengerActions] extends [never]\n ? { actionNames?: undefined }\n : { actionNames: readonly MessengerActions['type'][] });\n\ntype AnyMethodHandler = {\n implementation(\n this: void,\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n hooks: unknown,\n messenger: unknown,\n ): Promise<void> | void;\n hookNames?: Record<string, true>;\n actionNames?: readonly string[];\n};\n\ntype CreateMethodMiddlewareBaseOptions<\n Handlers extends Record<string, AnyMethodHandler>,\n> = {\n handlers: Handlers;\n // Due to a quirk of TypeScript's inference over generics, the hooks property must\n // be present even if no hooks are needed. Otherwise, TypeScript will fail to infer\n // the correct type for the messenger property. `Record<string, never>` is the\n // (hopefully) least confusing way to satisfy this requirement.\n hooks: [HandlerHooks<Handlers[keyof Handlers]>] extends [never]\n ? Record<string, never>\n : UnionToIntersection<HandlerHooks<Handlers[keyof Handlers]>>;\n /**\n * Called when a handler throws, before the error is forwarded to `end`.\n * Intended for logging; must not throw.\n */\n onError?: (error: unknown, request: JsonRpcRequest) => void;\n};\n\n/**\n * Options for {@link createMethodMiddleware}.\n *\n * @deprecated Use the v2 `createMethodMiddleware` instead.\n */\nexport type CreateMethodMiddlewareOptions<\n Handlers extends Record<string, AnyMethodHandler>,\n> = CreateMethodMiddlewareBaseOptions<Handlers> &\n ([HandlerActions<Handlers[keyof Handlers]>] extends [never]\n ? {\n messenger?: undefined;\n }\n : {\n messenger: Messenger<string, HandlerActions<Handlers[keyof Handlers]>>;\n });\n\ntype ResolvedHandler = {\n implementation: AnyMethodHandler['implementation'];\n hooks: Record<string, unknown>;\n messenger?: Messenger<string, ActionConstraint> | undefined;\n};\n\n/**\n * Create a JSON-RPC middleware that handles the passed JSON-RPC method handlers using the messenger and hooks.\n *\n * @deprecated Use the v2 `createMethodMiddleware` instead.\n * @param options The options.\n * @param options.handlers - The JSON-RPC method handler implementations.\n * @param options.messenger - The messenger to be used by the handlers.\n * @param options.hooks - The hooks to be used by the handlers.\n * @returns A JsonRpcEngineV2 middleware.\n */\nexport function createMethodMiddleware<\n Handlers extends Record<string, AnyMethodHandler>,\n>(\n options: CreateMethodMiddlewareOptions<Handlers>,\n): JsonRpcMiddleware<JsonRpcParams, Json> {\n const { messenger: rootMessenger, onError } = options;\n const allHooks = options.hooks as Record<string, unknown>;\n\n const expectedHookNames = new Set(\n Object.values(options.handlers).flatMap((handler) =>\n handler.hookNames ? Object.getOwnPropertyNames(handler.hookNames) : [],\n ),\n );\n assertExpectedHooks(allHooks, expectedHookNames);\n\n const handlers = Object.entries(options.handlers).reduce<\n Record<string, ResolvedHandler>\n >((accumulator, [handlerName, handler]) => {\n const handlerHooks = selectHooks(allHooks, handler.hookNames) ?? {};\n const handlerMessenger = createHandlerMessenger<\n HandlerActions<Handlers[keyof Handlers]>\n >({\n namespace: handlerName,\n actionNames: handler.actionNames as\n | readonly HandlerActions<Handlers[keyof Handlers]>['type'][]\n | undefined,\n rootMessenger,\n });\n\n accumulator[handlerName] = {\n implementation: handler.implementation,\n hooks: handlerHooks,\n messenger: handlerMessenger,\n };\n return accumulator;\n }, {});\n\n // This should technically use createAsyncMiddleware, but we get around this by catching\n // all handler errors.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n return async (req, res, next, end) => {\n const handler = handlers[req.method];\n if (!handler) {\n return next();\n }\n\n const { implementation, hooks: handlerHooks, messenger } = handler;\n try {\n return await implementation(req, res, next, end, handlerHooks, messenger);\n } catch (error) {\n onError?.(error, req);\n return end(\n error instanceof Error\n ? error\n : rpcErrors.internal({ data: error as Json }),\n );\n }\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"createOriginMiddleware.d.ts","sourceRoot":"","sources":["../src/createOriginMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAEvD;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,MAAM,GACb,iBAAiB,CAAC,cAAc,EAAE,IAAI,CAAC,CAKzC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"createOriginMiddleware.js","sourceRoot":"","sources":["../src/createOriginMiddleware.ts"],"names":[],"mappings":"AAIA;;;;;;GAMG;AACH,MAAM,UAAU,sBAAsB,CACpC,MAAc;IAEd,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE;QAC/B,OAA0D,CAAC,MAAM,GAAG,MAAM,CAAC;QAC5E,IAAI,EAAE,CAAC;IACT,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { Json, JsonRpcRequest } from '@metamask/utils';\n\nimport { JsonRpcMiddleware } from './JsonRpcEngine.js';\n\n/**\n * Create a middleware function that adds `origin` to the request object.\n *\n * @deprecated Use the v2 `createOriginMiddleware` instead.\n * @param origin - The origin.\n * @returns The middleware.\n */\nexport function createOriginMiddleware(\n origin: string,\n): JsonRpcMiddleware<JsonRpcRequest, Json> {\n return (request, _result, next) => {\n (request as unknown as JsonRpcRequest & { origin: string }).origin = origin;\n next();\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"createScaffoldMiddleware.d.ts","sourceRoot":"","sources":["../src/createScaffoldMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAkB,MAAM,iBAAiB,CAAC;AAE3E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAE5D,KAAK,yBAAyB,CAC5B,MAAM,SAAS,aAAa,EAC5B,MAAM,SAAS,IAAI,IACjB,iBAAiB,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAC;AAE7C;;;;;;;;;GASG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE;IACjD,CAAC,UAAU,EAAE,MAAM,GAAG,yBAAyB,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;CACtE,GAAG,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,CAgBzC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"createScaffoldMiddleware.js","sourceRoot":"","sources":["../src/createScaffoldMiddleware.ts"],"names":[],"mappings":"AASA;;;;;;;;;GASG;AACH,MAAM,UAAU,wBAAwB,CAAC,QAExC;IACC,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE;QAC7B,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACrC,wBAAwB;QACxB,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YAC1B,OAAO,IAAI,EAAE,CAAC;QAChB,CAAC;QAED,uCAAuC;QACvC,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE,CAAC;YAClC,OAAO,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;QACtC,CAAC;QACD,gDAAgD;QAC/C,GAAsB,CAAC,MAAM,GAAG,OAAO,CAAC;QACzC,OAAO,GAAG,EAAE,CAAC;IACf,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { Json, JsonRpcParams, JsonRpcSuccess } from '@metamask/utils';\n\nimport type { JsonRpcMiddleware } from './JsonRpcEngine.js';\n\ntype ScaffoldMiddlewareHandler<\n Params extends JsonRpcParams,\n Result extends Json,\n> = JsonRpcMiddleware<Params, Result> | Json;\n\n/**\n * Creates a middleware function from an object of RPC method handler functions,\n * keyed to particular method names. If a method corresponding to a key of this\n * object is requested, this middleware will pass it to the corresponding\n * handler and return the result.\n *\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n * @param handlers - The RPC method handler functions.\n * @returns The scaffold middleware function.\n */\nexport function createScaffoldMiddleware(handlers: {\n [methodName: string]: ScaffoldMiddlewareHandler<JsonRpcParams, Json>;\n}): JsonRpcMiddleware<JsonRpcParams, Json> {\n return (req, res, next, end) => {\n const handler = handlers[req.method];\n // if no handler, return\n if (handler === undefined) {\n return next();\n }\n\n // if handler is fn, call as middleware\n if (typeof handler === 'function') {\n return handler(req, res, next, end);\n }\n // if handler is some other value, use as result\n (res as JsonRpcSuccess).result = handler;\n return end();\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"getUniqueId.d.ts","sourceRoot":"","sources":["../src/getUniqueId.ts"],"names":[],"mappings":"AAKA;;;;;;GAMG;AACH,wBAAgB,WAAW,IAAI,MAAM,CAGpC"}
|
package/dist/getUniqueId.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"getUniqueId.js","sourceRoot":"","sources":["../src/getUniqueId.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,iDAAiD;AACjD,MAAM,GAAG,GAAG,UAAa,CAAC;AAC1B,IAAI,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,GAAG,CAAC,CAAC;AAEhD;;;;;;GAMG;AACH,MAAM,UAAU,WAAW;IACzB,SAAS,GAAG,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC;IAClC,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// uint32 (two's complement) max\n// more conservative than Number.MAX_SAFE_INTEGER\nconst MAX = 4_294_967_295;\nlet idCounter = Math.floor(Math.random() * MAX);\n\n/**\n * Gets an ID that is guaranteed to be unique so long as no more than\n * 4_294_967_295 (uint32 max) IDs are created, or the IDs are rapidly turned\n * over.\n *\n * @returns The unique ID.\n */\nexport function getUniqueId(): number {\n idCounter = (idCounter + 1) % MAX;\n return idCounter;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"idRemapMiddleware.d.ts","sourceRoot":"","sources":["../src/idRemapMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAG3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAE5D;;;;;;;;;GASG;AACH,wBAAgB,uBAAuB,IAAI,iBAAiB,CAC1D,aAAa,EACb,IAAI,CACL,CAYA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"idRemapMiddleware.js","sourceRoot":"","sources":["../src/idRemapMiddleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAG/C;;;;;;;;;GASG;AACH,MAAM,UAAU,uBAAuB;IAIrC,OAAO,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;QACvC,MAAM,UAAU,GAAG,OAAO,CAAC,EAAE,CAAC;QAC9B,MAAM,KAAK,GAAG,WAAW,EAAE,CAAC;QAC5B,OAAO,CAAC,EAAE,GAAG,KAAK,CAAC;QACnB,QAAQ,CAAC,EAAE,GAAG,KAAK,CAAC;QACpB,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE;YACZ,OAAO,CAAC,EAAE,GAAG,UAAU,CAAC;YACxB,QAAQ,CAAC,EAAE,GAAG,UAAU,CAAC;YACzB,IAAI,EAAE,CAAC;QACT,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { Json, JsonRpcParams } from '@metamask/utils';\n\nimport { getUniqueId } from './getUniqueId.js';\nimport type { JsonRpcMiddleware } from './JsonRpcEngine.js';\n\n/**\n * Returns a middleware function that overwrites the `id` property of each\n * request with an ID that is guaranteed to be unique, and restores the original\n * ID in a return handler.\n *\n * If used, should be the first middleware in the stack.\n *\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n * @returns The ID remap middleware function.\n */\nexport function createIdRemapMiddleware(): JsonRpcMiddleware<\n JsonRpcParams,\n Json\n> {\n return (request, response, next, _end) => {\n const originalId = request.id;\n const newId = getUniqueId();\n request.id = newId;\n response.id = newId;\n next((done) => {\n request.id = originalId;\n response.id = originalId;\n done();\n });\n };\n}\n"]}
|
package/dist/index.d.ts
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
export { asV2Middleware } from './asV2Middleware.js';
|
|
2
|
-
export type { AsyncJsonRpcEngineNextCallback, AsyncJsonrpcMiddleware, } from './createAsyncMiddleware.js';
|
|
3
|
-
export { createAsyncMiddleware } from './createAsyncMiddleware.js';
|
|
4
|
-
export type { CreateMethodMiddlewareOptions, MethodHandler, MethodHandlerImplementation, } from './createMethodMiddleware.js';
|
|
5
|
-
export { createMethodMiddleware } from './createMethodMiddleware.js';
|
|
6
|
-
export { createOriginMiddleware } from './createOriginMiddleware.js';
|
|
7
|
-
export { createScaffoldMiddleware } from './createScaffoldMiddleware.js';
|
|
8
|
-
export { getUniqueId } from './getUniqueId.js';
|
|
9
|
-
export { createIdRemapMiddleware } from './idRemapMiddleware.js';
|
|
10
|
-
export type { JsonRpcEngineCallbackError, JsonRpcEngineReturnHandler, JsonRpcEngineNextCallback, JsonRpcEngineEndCallback, JsonRpcMiddleware, JsonRpcNotificationHandler, } from './JsonRpcEngine.js';
|
|
11
|
-
export { JsonRpcEngine } from './JsonRpcEngine.js';
|
|
12
|
-
export { mergeMiddleware } from './mergeMiddleware.js';
|
|
13
|
-
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,YAAY,EACV,8BAA8B,EAC9B,sBAAsB,GACvB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,YAAY,EACV,6BAA6B,EAC7B,aAAa,EACb,2BAA2B,GAC5B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AACzE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,YAAY,EACV,0BAA0B,EAC1B,0BAA0B,EAC1B,yBAAyB,EACzB,wBAAwB,EACxB,iBAAiB,EACjB,0BAA0B,GAC3B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC"}
|
package/dist/index.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
export { asV2Middleware } from './asV2Middleware.js';
|
|
2
|
-
export { createAsyncMiddleware } from './createAsyncMiddleware.js';
|
|
3
|
-
export { createMethodMiddleware } from './createMethodMiddleware.js';
|
|
4
|
-
export { createOriginMiddleware } from './createOriginMiddleware.js';
|
|
5
|
-
export { createScaffoldMiddleware } from './createScaffoldMiddleware.js';
|
|
6
|
-
export { getUniqueId } from './getUniqueId.js';
|
|
7
|
-
export { createIdRemapMiddleware } from './idRemapMiddleware.js';
|
|
8
|
-
export { JsonRpcEngine } from './JsonRpcEngine.js';
|
|
9
|
-
export { mergeMiddleware } from './mergeMiddleware.js';
|
|
10
|
-
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAKrD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAMnE,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AACzE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AASjE,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC","sourcesContent":["export { asV2Middleware } from './asV2Middleware.js';\nexport type {\n AsyncJsonRpcEngineNextCallback,\n AsyncJsonrpcMiddleware,\n} from './createAsyncMiddleware.js';\nexport { createAsyncMiddleware } from './createAsyncMiddleware.js';\nexport type {\n CreateMethodMiddlewareOptions,\n MethodHandler,\n MethodHandlerImplementation,\n} from './createMethodMiddleware.js';\nexport { createMethodMiddleware } from './createMethodMiddleware.js';\nexport { createOriginMiddleware } from './createOriginMiddleware.js';\nexport { createScaffoldMiddleware } from './createScaffoldMiddleware.js';\nexport { getUniqueId } from './getUniqueId.js';\nexport { createIdRemapMiddleware } from './idRemapMiddleware.js';\nexport type {\n JsonRpcEngineCallbackError,\n JsonRpcEngineReturnHandler,\n JsonRpcEngineNextCallback,\n JsonRpcEngineEndCallback,\n JsonRpcMiddleware,\n JsonRpcNotificationHandler,\n} from './JsonRpcEngine.js';\nexport { JsonRpcEngine } from './JsonRpcEngine.js';\nexport { mergeMiddleware } from './mergeMiddleware.js';\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mergeMiddleware.d.ts","sourceRoot":"","sources":["../src/mergeMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAE3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAG5D;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,eAAe,EAAE,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,EAAE,GACxD,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,CAIxC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mergeMiddleware.js","sourceRoot":"","sources":["../src/mergeMiddleware.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,eAAyD;IAEzD,MAAM,MAAM,GAAG,IAAI,aAAa,EAAE,CAAC;IACnC,eAAe,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IACjE,OAAO,MAAM,CAAC,YAAY,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["import type { Json, JsonRpcParams } from '@metamask/utils';\n\nimport type { JsonRpcMiddleware } from './JsonRpcEngine.js';\nimport { JsonRpcEngine } from './JsonRpcEngine.js';\n\n/**\n * Takes a stack of middleware and joins them into a single middleware function.\n *\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n * @param middlewareStack - The middleware stack to merge.\n * @returns The merged middleware function.\n */\nexport function mergeMiddleware(\n middlewareStack: JsonRpcMiddleware<JsonRpcParams, Json>[],\n): JsonRpcMiddleware<JsonRpcParams, Json> {\n const engine = new JsonRpcEngine();\n middlewareStack.forEach((middleware) => engine.push(middleware));\n return engine.asMiddleware();\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcEngineV2.d.ts","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,IAAI,EACJ,cAAc,EACd,mBAAmB,EAEpB,MAAM,iBAAiB,CAAC;AAIzB,OAAO,KAAK,EACV,iBAAiB,EACjB,cAAc,EACd,aAAa,EACd,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAO3D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAG9C,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,CAAC,CAAC;AAE3D,MAAM,MAAM,gBAAgB,CAAC,OAAO,SAAS,WAAW,IACtD,OAAO,SAAS,cAAc,GAAG,IAAI,GAAG,IAAI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,EAAE,CACvG,CAAC;IACJ,CAAC;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,CAAC;QACD,MAAM,IAAI,kBAAkB,CAC1B,sEAAsE,SAAS,CAAC,cAAc,CAAC,EAAE,CAClG,CAAC;IACJ,CAAC;AACH,CAAC;IAqDC,IAAI,uBAAA,IAAI,oCAAa,EAAE,CAAC;QACtB,MAAM,IAAI,kBAAkB,CAAC,qBAAqB,CAAC,CAAC;IACtD,CAAC;AACH,CAAC","sourcesContent":["import { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcRequest,\n JsonRpcNotification,\n NonEmptyArray,\n} from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\n\nimport { deepClone } from './compatibility-utils.js';\nimport type {\n ContextConstraint,\n InferKeyValues,\n MergeContexts,\n} from './MiddlewareContext.js';\nimport { MiddlewareContext } from './MiddlewareContext.js';\nimport {\n isNotification,\n isRequest,\n JsonRpcEngineError,\n stringify,\n} from './utils.js';\nimport type { JsonRpcCall } from './utils.js';\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 ContextConstraint = 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\n/**\n * The options for the JSON-RPC request/notification handling operation.\n */\nexport type HandleOptions<Context extends ContextConstraint> = {\n context?: Context | InferKeyValues<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 // eslint-disable-next-line no-restricted-syntax\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 >({\n middleware,\n }: {\n middleware: Middleware[];\n }): MergedContextOf<Middleware> extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<RequestOf<Middleware>, MergedContextOf<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\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<ResultConstraint<Request> | void> {\n // This error appeared when upgrading to TypeScript 7.\n // @ts-expect-error: TS2345: Argument of type 'JsonRpcCall' is not assignable\n // to parameter of type 'JsonRpcCall<Record<string, Json>> | Readonly<JsonRpcCall<Record<string, Json>>>'.\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 deepClone(result) as ResultConstraint<Request>;\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 rawContext - The context to pass to the middleware.\n * @returns The result from the middleware.\n */\n async #handle(\n originalRequest: Request,\n rawContext:\n | Context\n | InferKeyValues<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 const context = MiddlewareContext.isInstance(rawContext)\n ? rawContext\n : (new MiddlewareContext(rawContext) as Context);\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\n // We can't use nullish coalescing here because `result` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcServer.d.ts","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,mBAAmB,EAEnB,cAAc,EACd,eAAe,EACf,aAAa,EACd,MAAM,iBAAiB,CAAC;AAIzB,OAAO,KAAK,EACV,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,oBAAoB,EAErB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAGvD,KAAK,OAAO,GAAG,CA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AAQ,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,CAAC;QACtC,OAAO,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IACzE,CAAC;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,CAAC;QAC1D,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC;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 { getUniqueId } from '../getUniqueId.js';\nimport type {\n HandleOptions,\n JsonRpcMiddleware,\n MergedContextOf,\n MiddlewareConstraint,\n RequestOf,\n} from './JsonRpcEngineV2.js';\nimport { JsonRpcEngineV2 } from './JsonRpcEngineV2.js';\nimport type { JsonRpcCall } from './utils.js';\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. If the `onError`\n * callback itself throws or rejects, the error is silently ignored.\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 * @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: JsonRpcRequest,\n options?: HandleOptions<MergedContextOf<Middleware>>,\n ): 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 * @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: JsonRpcNotification,\n options?: HandleOptions<MergedContextOf<Middleware>>,\n ): 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 * @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 request is a\n * notification.\n */\n async handle(\n rawRequest: unknown,\n options?: HandleOptions<MergedContextOf<Middleware>>,\n ): Promise<JsonRpcResponse | void>;\n\n async handle(\n rawRequest: unknown,\n options?: HandleOptions<MergedContextOf<Middleware>>,\n ): 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 = JsonRpcServer.#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, options);\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 try {\n const maybePromise: unknown = this.#onError?.(error);\n if (maybePromise instanceof Promise) {\n maybePromise.catch(() => {\n // Prevent unhandled promise rejection.\n });\n }\n } catch {\n // onError must not prevent handle() from honoring its \"never throws\" contract.\n }\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 static #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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MiddlewareContext.d.ts","sourceRoot":"","sources":["../../src/v2/MiddlewareContext.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtD,QAAA,MAAM,uBAAuB,eAAkD,CAAC;AAEhF;;;;;;;;;;;;;;;;;;;;;;;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;IAIxD,OAAO,CAAC,QAAQ,CAAC,CAAC,uBAAuB,CAAC,CAAQ;IAElD;;;;;;OAMG;IACH,MAAM,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,iBAAiB,CAE5D;IAED,YACE,OAAO,CAAC,EACJ,QAAQ,CAAC,SAAS,CAAC,MAAM,SAAS,EAAE,SAAS,CAAC,MAAM,SAAS,CAAC,CAAC,CAAC,GAChE,SAAS,EAQd;IAED,GAAG,CAAC,GAAG,SAAS,MAAM,SAAS,EAAE,GAAG,EAAE,GAAG,GAAG,SAAS,CAAC,GAAG,CAAC,GAAG,SAAS,CAErE;IAED;;;;;OAKG;IACH,SAAS,CAAC,GAAG,SAAS,MAAM,SAAS,EAAE,GAAG,EAAE,GAAG,GAAG,SAAS,CAAC,GAAG,CAAC,CAK/D;IAED;;;;;;;;OAQG;IACH,GAAG,CAAC,GAAG,SAAS,MAAM,SAAS,EAAE,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,CAAC,GAAG,IAAI,CAMtE;CACF;A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