@metamask-previews/json-rpc-engine 10.2.0-preview-de995bed → 10.2.0-preview-cb4a07d5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/JsonRpcEngine.cjs +3 -4
- package/dist/JsonRpcEngine.cjs.map +1 -1
- package/dist/JsonRpcEngine.d.cts.map +1 -1
- package/dist/JsonRpcEngine.d.mts.map +1 -1
- package/dist/JsonRpcEngine.mjs +3 -4
- package/dist/JsonRpcEngine.mjs.map +1 -1
- package/dist/asV2Middleware.cjs +1 -1
- package/dist/asV2Middleware.cjs.map +1 -1
- package/dist/asV2Middleware.mjs +1 -1
- package/dist/asV2Middleware.mjs.map +1 -1
- package/dist/createAsyncMiddleware.cjs.map +1 -1
- package/dist/createAsyncMiddleware.mjs.map +1 -1
- package/dist/mergeMiddleware.cjs.map +1 -1
- package/dist/mergeMiddleware.d.cts.map +1 -1
- package/dist/mergeMiddleware.d.mts.map +1 -1
- package/dist/mergeMiddleware.mjs.map +1 -1
- package/dist/v2/JsonRpcEngineV2.cjs +4 -1
- package/dist/v2/JsonRpcEngineV2.cjs.map +1 -1
- package/dist/v2/JsonRpcEngineV2.d.cts +2 -2
- package/dist/v2/JsonRpcEngineV2.d.cts.map +1 -1
- package/dist/v2/JsonRpcEngineV2.d.mts +2 -2
- package/dist/v2/JsonRpcEngineV2.d.mts.map +1 -1
- package/dist/v2/JsonRpcEngineV2.mjs +4 -1
- package/dist/v2/JsonRpcEngineV2.mjs.map +1 -1
- package/dist/v2/MiddlewareContext.cjs +4 -1
- package/dist/v2/MiddlewareContext.cjs.map +1 -1
- package/dist/v2/MiddlewareContext.d.cts +10 -10
- package/dist/v2/MiddlewareContext.d.cts.map +1 -1
- package/dist/v2/MiddlewareContext.d.mts +10 -10
- package/dist/v2/MiddlewareContext.d.mts.map +1 -1
- package/dist/v2/MiddlewareContext.mjs +4 -1
- package/dist/v2/MiddlewareContext.mjs.map +1 -1
- package/dist/v2/compatibility-utils.cjs.map +1 -1
- package/dist/v2/compatibility-utils.d.cts +4 -4
- package/dist/v2/compatibility-utils.d.cts.map +1 -1
- package/dist/v2/compatibility-utils.d.mts +4 -4
- package/dist/v2/compatibility-utils.d.mts.map +1 -1
- package/dist/v2/compatibility-utils.mjs.map +1 -1
- package/dist/v2/utils.cjs +5 -2
- package/dist/v2/utils.cjs.map +1 -1
- package/dist/v2/utils.d.cts +3 -3
- package/dist/v2/utils.d.cts.map +1 -1
- package/dist/v2/utils.d.mts +3 -3
- package/dist/v2/utils.d.mts.map +1 -1
- package/dist/v2/utils.mjs +5 -2
- package/dist/v2/utils.mjs.map +1 -1
- package/package.json +1 -1
package/dist/JsonRpcEngine.cjs
CHANGED
|
@@ -139,6 +139,7 @@ class JsonRpcEngine extends safe_event_emitter_1.default {
|
|
|
139
139
|
*/
|
|
140
140
|
// This function is used in tests, so we cannot easily change it to use the
|
|
141
141
|
// hash syntax.
|
|
142
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
142
143
|
async _promiseHandle(request) {
|
|
143
144
|
return new Promise((resolve, reject) => {
|
|
144
145
|
__classPrivateFieldGet(this, _JsonRpcEngine_instances, "m", _JsonRpcEngine_handle).call(this, request, (error, res) => {
|
|
@@ -270,9 +271,7 @@ async function _JsonRpcEngine_handle(callerReq, callback) {
|
|
|
270
271
|
if (error) {
|
|
271
272
|
// Ensure no result is present on an errored response
|
|
272
273
|
delete res.result;
|
|
273
|
-
|
|
274
|
-
res.error = (0, rpc_errors_1.serializeError)(error);
|
|
275
|
-
}
|
|
274
|
+
res.error ?? (res.error = (0, rpc_errors_1.serializeError)(error));
|
|
276
275
|
}
|
|
277
276
|
return callback(error, res);
|
|
278
277
|
}, _JsonRpcEngine_processRequest = async function _JsonRpcEngine_processRequest(req, res, middlewares) {
|
|
@@ -304,7 +303,7 @@ async function _JsonRpcEngine_handle(callerReq, callback) {
|
|
|
304
303
|
}, _JsonRpcEngine_runMiddleware = async function _JsonRpcEngine_runMiddleware(request, response, middleware, returnHandlers) {
|
|
305
304
|
return new Promise((resolve) => {
|
|
306
305
|
const end = (error) => {
|
|
307
|
-
const parsedError = error
|
|
306
|
+
const parsedError = error ?? response.error;
|
|
308
307
|
if (parsedError) {
|
|
309
308
|
response.error = (0, rpc_errors_1.serializeError)(parsedError);
|
|
310
309
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcEngine.cjs","sourceRoot":"","sources":["../src/JsonRpcEngine.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,qDAAgF;AAChF,sFAA4D;AAU5D,2CAIyB;AAEzB,0CAAuC;AAuCvC,MAAM,uBAAuB,GAC3B,qDAAqD,CAAC;AAsBxD;;;;;;GAMG;AACH,MAAa,aAAc,SAAQ,4BAAgB;IAYjD;;;;;;;;;;OAUG;IACH,YAAY,EAAE,mBAAmB,KAAwB,EAAE;QACzD,KAAK,EAAE,CAAC;;QAvBV;;WAEG;QACH,qCAAe,KAAK,EAAC;QAErB,4CAAsD;QAE7C,qDAEK;QAeZ,uBAAA,IAAI,6BAAe,EAAE,MAAA,CAAC;QACtB,uBAAA,IAAI,sCAAwB,mBAAmB,MAAA,CAAC;IAClD,CAAC;IAWD;;;;OAIG;IACH,OAAO;QACL,uBAAA,IAAI,iCAAY,CAAC,OAAO,CACtB,CAAC,UAAkD,EAAE,EAAE;YACrD;YACE,gEAAgE;YAChE,iBAAiB;YACjB,SAAS,IAAI,UAAU;gBACvB,OAAO,UAAU,CAAC,OAAO,KAAK,UAAU,EACxC,CAAC;gBACD,mEAAmE;gBACnE,UAAU,CAAC,OAAO,EAAE,CAAC;YACvB,CAAC;QACH,CAAC,CACF,CAAC;QACF,uBAAA,IAAI,6BAAe,EAAE,MAAA,CAAC;QACtB,uBAAA,IAAI,8BAAgB,IAAI,MAAA,CAAC;IAC3B,CAAC;IAED;;;;OAIG;IACH,IAAI,CACF,UAA6C;QAE7C,uBAAA,IAAI,qEAAsB,MAA1B,IAA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M,IAAI,yBAAY,CACpB,uBAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,gEAAgE,IAAA,iBAAS,EACvE,OAAO,CACR,EAAE,EACH,EAAE,OAAO,EAAE,CACZ,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,MAAM,IAAI,yBAAY,CACpB,uBAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,0CAA0C,IAAA,iBAAS,EAAC,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';\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() {\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 ) {\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\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 if (!res.error) {\n res.error = serializeError(error);\n }\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
|
+
{"version":3,"file":"JsonRpcEngine.cjs","sourceRoot":"","sources":["../src/JsonRpcEngine.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,qDAAgF;AAChF,sFAA4D;AAU5D,2CAIyB;AAEzB,0CAAuC;AAuCvC,MAAM,uBAAuB,GAC3B,qDAAqD,CAAC;AAsBxD;;;;;;GAMG;AACH,MAAa,aAAc,SAAQ,4BAAgB;IAYjD;;;;;;;;;;OAUG;IACH,YAAY,EAAE,mBAAmB,KAAwB,EAAE;QACzD,KAAK,EAAE,CAAC;;QAvBV;;WAEG;QACH,qCAAe,KAAK,EAAC;QAErB,4CAAsD;QAE7C,qDAEK;QAeZ,uBAAA,IAAI,6BAAe,EAAE,MAAA,CAAC;QACtB,uBAAA,IAAI,sCAAwB,mBAAmB,MAAA,CAAC;IAClD,CAAC;IAWD;;;;OAIG;IACH,OAAO;QACL,uBAAA,IAAI,iCAAY,CAAC,OAAO,CACtB,CAAC,UAAkD,EAAE,EAAE;YACrD;YACE,gEAAgE;YAChE,iBAAiB;YACjB,SAAS,IAAI,UAAU;gBACvB,OAAO,UAAU,CAAC,OAAO,KAAK,UAAU,EACxC,CAAC;gBACD,mEAAmE;gBACnE,UAAU,CAAC,OAAO,EAAE,CAAC;YACvB,CAAC;QACH,CAAC,CACF,CAAC;QACF,uBAAA,IAAI,6BAAe,EAAE,MAAA,CAAC;QACtB,uBAAA,IAAI,8BAAgB,IAAI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CAAC,IAAI,CAAC,IAAA,mBAAW,EAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,CAAC;QACxE,MAAM,IAAI,yBAAY,CACpB,uBAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,gEAAgE,IAAA,iBAAS,EACvE,OAAO,CACR,EAAE,EACH,EAAE,OAAO,EAAE,CACZ,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,MAAM,IAAI,yBAAY,CACpB,uBAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,0CAA0C,IAAA,iBAAS,EAAC,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';\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcEngine.d.cts","sourceRoot":"","sources":["../src/JsonRpcEngine.ts"],"names":[],"mappings":"AACA,OAAO,gBAAgB,qCAAqC;AAC5D,OAAO,KAAK,EACV,YAAY,IAAI,sBAAsB,EACtC,cAAc,EACd,eAAe,EACf,mBAAmB,EACnB,IAAI,EACJ,aAAa,EACb,sBAAsB,EACvB,wBAAwB;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;IAC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AAmB,CAAC,MAAM,CAAC,EACzC,QAAQ,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,KAAK,IAAI,GACjD,IAAI;IAEP;;;;;;;OAOG;IACH,MAAM,CAAC,MAAM,SAAS,aAAa,EAAE,MAAM,SAAS,IAAI,EACtD,QAAQ,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC,EAAE,EAClE,QAAQ,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC,EAAE,KAAK,IAAI,GACvE,IAAI;IAEP;;;;;OAKG;IACH,MAAM,CAAC,MAAM,SAAS,aAAa,EAAE,MAAM,SAAS,IAAI,EACtD,OAAO,EAAE,cAAc,CAAC,MAAM,CAAC,GAC9B,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;IAEnC;;;;OAIG;IACH,MAAM,CAAC,MAAM,SAAS,aAAa,EACjC,YAAY,EAAE,mBAAmB,CAAC,MAAM,CAAC,GACxC,OAAO,CAAC,IAAI,CAAC;IAEhB;;;;;;OAMG;IACH,MAAM,CAAC,MAAM,SAAS,aAAa,EAAE,MAAM,SAAS,IAAI,EACtD,QAAQ,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC,EAAE,GACjE,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC;IAoCrC;;;;;OAKG;IACH,YAAY,IAAI,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC;IAsGtD;;;;;OAKG;YAIW,cAAc;CAkS7B"}
|
package/dist/JsonRpcEngine.mjs
CHANGED
|
@@ -133,6 +133,7 @@ export class JsonRpcEngine extends SafeEventEmitter {
|
|
|
133
133
|
*/
|
|
134
134
|
// This function is used in tests, so we cannot easily change it to use the
|
|
135
135
|
// hash syntax.
|
|
136
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
136
137
|
async _promiseHandle(request) {
|
|
137
138
|
return new Promise((resolve, reject) => {
|
|
138
139
|
__classPrivateFieldGet(this, _JsonRpcEngine_instances, "m", _JsonRpcEngine_handle).call(this, request, (error, res) => {
|
|
@@ -263,9 +264,7 @@ async function _JsonRpcEngine_handle(callerReq, callback) {
|
|
|
263
264
|
if (error) {
|
|
264
265
|
// Ensure no result is present on an errored response
|
|
265
266
|
delete res.result;
|
|
266
|
-
|
|
267
|
-
res.error = serializeError(error);
|
|
268
|
-
}
|
|
267
|
+
res.error ?? (res.error = serializeError(error));
|
|
269
268
|
}
|
|
270
269
|
return callback(error, res);
|
|
271
270
|
}, _JsonRpcEngine_processRequest = async function _JsonRpcEngine_processRequest(req, res, middlewares) {
|
|
@@ -297,7 +296,7 @@ async function _JsonRpcEngine_handle(callerReq, callback) {
|
|
|
297
296
|
}, _JsonRpcEngine_runMiddleware = async function _JsonRpcEngine_runMiddleware(request, response, middleware, returnHandlers) {
|
|
298
297
|
return new Promise((resolve) => {
|
|
299
298
|
const end = (error) => {
|
|
300
|
-
const parsedError = error
|
|
299
|
+
const parsedError = error ?? response.error;
|
|
301
300
|
if (parsedError) {
|
|
302
301
|
response.error = serializeError(parsedError);
|
|
303
302
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcEngine.mjs","sourceRoot":"","sources":["../src/JsonRpcEngine.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,cAAc,EAAE,6BAA6B;AAChF,OAAO,gBAAgB,qCAAqC;AAU5D,OAAO,EACL,WAAW,EACX,qBAAqB,EACrB,gBAAgB,EACjB,wBAAwB;AAEzB,OAAO,EAAE,SAAS,EAAE,uBAAmB;AAuCvC,MAAM,uBAAuB,GAC3B,qDAAqD,CAAC;AAsBxD;;;;;;GAMG;AACH,MAAM,OAAO,aAAc,SAAQ,gBAAgB;IAYjD;;;;;;;;;;OAUG;IACH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C;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';\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() {\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 ) {\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\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 if (!res.error) {\n res.error = serializeError(error);\n }\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
|
+
{"version":3,"file":"JsonRpcEngine.mjs","sourceRoot":"","sources":["../src/JsonRpcEngine.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,cAAc,EAAE,6BAA6B;AAChF,OAAO,gBAAgB,qCAAqC;AAU5D,OAAO,EACL,WAAW,EACX,qBAAqB,EACrB,gBAAgB,EACjB,wBAAwB;AAEzB,OAAO,EAAE,SAAS,EAAE,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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';\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"]}
|
package/dist/asV2Middleware.cjs
CHANGED
|
@@ -37,7 +37,7 @@ function asV2Middleware(engineOrMiddleware, ...rest) {
|
|
|
37
37
|
// We know from the implementation of JsonRpcEngine.asMiddleware() that
|
|
38
38
|
// legacyNext will always be passed a callback, so cb can never be
|
|
39
39
|
// undefined.
|
|
40
|
-
const legacyNext = ((
|
|
40
|
+
const legacyNext = ((callback) => callback(end));
|
|
41
41
|
legacyMiddleware(req, res, legacyNext, end);
|
|
42
42
|
});
|
|
43
43
|
(0, compatibility_utils_1.propagateToContext)(req, context);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asV2Middleware.cjs","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":";;;AAAA,qDAAsD;AACtD,2CAA8C;AAe9C,2DAAoD;AAEpD,sEAMkC;AAmClC;;;;;;GAMG;AACH,SAAgB,cAAc,CAI5B,kBAAyE,EACzE,GAAG,IAA6C;IAEhD,MAAM,gBAAgB,GACpB,OAAO,kBAAkB,KAAK,UAAU;QACtC,CAAC,CAAC,wFAAwF;YACxF,6BAA6B;YAC7B,IAAA,iCAAe,EAAC,CAAC,kBAAkB,EAAE,GAAG,IAAI,CAAC,CAAC;QAChD,CAAC,CAAC,kBAAkB,CAAC,YAAY,EAAE,CAAC;IAExC,OAAO,KAAK,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE;QAC1C,MAAM,GAAG,GAAG,IAAA,+BAAS,EAAC,OAAO,CAA2B,CAAC;QACzD,IAAA,wCAAkB,EAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,MAAM,QAAQ,GAAG,MAAM,IAAI,OAAO,CAAkB,CAAC,OAAO,EAAE,EAAE;YAC9D,gEAAgE;YAChE,cAAc;YACd,MAAM,GAAG,GAAG;gBACV,OAAO,EAAE,KAAc;gBACvB,EAAE,EAAE,GAAG,CAAC,EAAE;aACQ,CAAC;YAErB,MAAM,GAAG,GAA6B,CAAC,KAAK,EAAE,EAAE;gBAC9C,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;oBACvB,GAAsB,CAAC,KAAK,GAAG,IAAA,2BAAc,EAAC,KAA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AuE;YACvE,kEAAkE;YAClE,aAAa;YACb,MAAM,UAAU,GAAG,CAAC,CAAC,QAAkC,EAAE,EAAE,CACzD,QAAQ,CAAC,GAAG,CAAC,CAA8B,CAAC;YAE9C,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QAC9C,CAAC,CAAC,CAAC;QACH,IAAA,wCAAkB,EAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,4FAA4F;QAC5F,+FAA+F;QAC/F,oGAAoG;QACpG,IAAI,IAAA,mBAAW,EAAC,QAAQ,EAAE,OAAO,CAAC,IAAI,QAAQ,CAAC,KAAK,EAAE,CAAC;YACrD,MAAM,IAAA,sCAAgB,EAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACzC,CAAC;aAAM,IAAI,IAAA,mBAAW,EAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE,CAAC;YAC3C,OAAO,QAAQ,CAAC,MAAmC,CAAC;QACtD,CAAC;QACD,OAAO,IAAI,CAAC,IAAA,uCAAiB,EAAC,GAAc,CAAC,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,CAAC;AArDD,wCAqDC","sourcesContent":["import { serializeError } from '@metamask/rpc-errors';\nimport { 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';\nimport type { JsonRpcMiddleware as LegacyMiddleware } from './JsonRpcEngine';\nimport { mergeMiddleware } from './mergeMiddleware';\nimport type { ContextConstraint, MiddlewareContext } from './v2';\nimport {\n deepClone,\n fromLegacyRequest,\n propagateToContext,\n propagateToRequest,\n deserializeError,\n} from './v2/compatibility-utils';\nimport type {\n // Used in docs.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n JsonRpcEngineV2,\n JsonRpcMiddleware,\n ResultConstraint,\n} from './v2/JsonRpcEngineV2';\n\n/**\n * Convert a legacy {@link JsonRpcEngine} into a {@link JsonRpcEngineV2} middleware.\n *\n * @param engine - The legacy engine to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(engine: JsonRpcEngine): JsonRpcMiddleware<Request>;\n\n/**\n * Convert one or more legacy middleware into a {@link JsonRpcEngineV2} middleware.\n *\n * @param middleware - The legacy middleware to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams = 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"]}
|
package/dist/asV2Middleware.mjs
CHANGED
|
@@ -34,7 +34,7 @@ export function asV2Middleware(engineOrMiddleware, ...rest) {
|
|
|
34
34
|
// We know from the implementation of JsonRpcEngine.asMiddleware() that
|
|
35
35
|
// legacyNext will always be passed a callback, so cb can never be
|
|
36
36
|
// undefined.
|
|
37
|
-
const legacyNext = ((
|
|
37
|
+
const legacyNext = ((callback) => callback(end));
|
|
38
38
|
legacyMiddleware(req, res, legacyNext, end);
|
|
39
39
|
});
|
|
40
40
|
propagateToContext(req, context);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asV2Middleware.mjs","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,6BAA6B;AACtD,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAe9C,OAAO,EAAE,eAAe,EAAE,8BAA0B;AAEpD,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,gBAAgB,EACjB,qCAAiC;AAmClC;;;;;;GAMG;AACH,MAAM,UAAU,cA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G,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';\nimport type { JsonRpcMiddleware as LegacyMiddleware } from './JsonRpcEngine';\nimport { mergeMiddleware } from './mergeMiddleware';\nimport type { ContextConstraint, MiddlewareContext } from './v2';\nimport {\n deepClone,\n fromLegacyRequest,\n propagateToContext,\n propagateToRequest,\n deserializeError,\n} from './v2/compatibility-utils';\nimport type {\n // Used in docs.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n JsonRpcEngineV2,\n JsonRpcMiddleware,\n ResultConstraint,\n} from './v2/JsonRpcEngineV2';\n\n/**\n * Convert a legacy {@link JsonRpcEngine} into a {@link JsonRpcEngineV2} middleware.\n *\n * @param engine - The legacy engine to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(engine: JsonRpcEngine): JsonRpcMiddleware<Request>;\n\n/**\n * Convert one or more legacy middleware into a {@link JsonRpcEngineV2} middleware.\n *\n * @param middleware - The legacy middleware to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams = 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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncMiddleware.cjs","sourceRoot":"","sources":["../src/createAsyncMiddleware.ts"],"names":[],"mappings":";;;AAyBA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,SAAgB,qBAAqB,CAInC,eAAuD;IAEvD,kEAAkE;IAClE,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE;QAC5C,+CAA+C;QAC/C,qDAAqD;QACrD,kBAAkB;QAClB,IAAI,kBAA8B,CAAC;QACnC,MAAM,WAAW,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;YAChD,kBAAkB,GAAG,OAAO,CAAC;QAC/B,CAAC,CAAC,CAAC;QAEH,IAAI,qBAAqB,GAAY,IAAI,CAAC;QAC1C,IAAI,aAAa,GAAG,KAAK,CAAC;QAE1B,0DAA0D;QAC1D,MAAM,SAAS,GAAG,KAAK,
|
|
1
|
+
{"version":3,"file":"createAsyncMiddleware.cjs","sourceRoot":"","sources":["../src/createAsyncMiddleware.ts"],"names":[],"mappings":";;;AAyBA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,SAAgB,qBAAqB,CAInC,eAAuD;IAEvD,kEAAkE;IAClE,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE;QAC5C,+CAA+C;QAC/C,qDAAqD;QACrD,kBAAkB;QAClB,IAAI,kBAA8B,CAAC;QACnC,MAAM,WAAW,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;YAChD,kBAAkB,GAAG,OAAO,CAAC;QAC/B,CAAC,CAAC,CAAC;QAEH,IAAI,qBAAqB,GAAY,IAAI,CAAC;QAC1C,IAAI,aAAa,GAAG,KAAK,CAAC;QAE1B,0DAA0D;QAC1D,MAAM,SAAS,GAAG,KAAK,IAAmB,EAAE;YAC1C,aAAa,GAAG,IAAI,CAAC;YAErB,uEAAuE;YACvE,yDAAyD;YACzD,IAAI,CAAC,CAAC,yBAAyB,EAAE,EAAE;gBACjC,4DAA4D;gBAC5D,qBAAqB,GAAG,yBAAyB,CAAC;gBAClD,kBAAkB,EAAE,CAAC;YACvB,CAAC,CAAC,CAAC;YACH,OAAO,WAAW,CAAC;QACrB,CAAC,CAAC;QAEF,IAAI,CAAC;YACH,MAAM,eAAe,CAAC,OAAO,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;YAEpD,IAAI,aAAa,EAAE,CAAC;gBAClB,MAAM,WAAW,CAAC,CAAC,kDAAkD;gBACpE,qBAA+C,CAAC,IAAI,CAAC,CAAC;YACzD,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,IAAI,CAAC,CAAC;YACZ,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,qBAAqB,EAAE,CAAC;gBACzB,qBAA+C,CAAC,KAAK,CAAC,CAAC;YAC1D,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,KAAK,CAAC,CAAC;YACb,CAAC;QACH,CAAC;IACH,CAAC,CAAC;AACJ,CAAC;AAlDD,sDAkDC","sourcesContent":["import type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngineReturnHandler,\n JsonRpcMiddleware,\n} from './JsonRpcEngine';\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncMiddleware.mjs","sourceRoot":"","sources":["../src/createAsyncMiddleware.ts"],"names":[],"mappings":"AAyBA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,UAAU,qBAAqB,CAInC,eAAuD;IAEvD,kEAAkE;IAClE,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE;QAC5C,+CAA+C;QAC/C,qDAAqD;QACrD,kBAAkB;QAClB,IAAI,kBAA8B,CAAC;QACnC,MAAM,WAAW,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;YAChD,kBAAkB,GAAG,OAAO,CAAC;QAC/B,CAAC,CAAC,CAAC;QAEH,IAAI,qBAAqB,GAAY,IAAI,CAAC;QAC1C,IAAI,aAAa,GAAG,KAAK,CAAC;QAE1B,0DAA0D;QAC1D,MAAM,SAAS,GAAG,KAAK,
|
|
1
|
+
{"version":3,"file":"createAsyncMiddleware.mjs","sourceRoot":"","sources":["../src/createAsyncMiddleware.ts"],"names":[],"mappings":"AAyBA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,UAAU,qBAAqB,CAInC,eAAuD;IAEvD,kEAAkE;IAClE,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE;QAC5C,+CAA+C;QAC/C,qDAAqD;QACrD,kBAAkB;QAClB,IAAI,kBAA8B,CAAC;QACnC,MAAM,WAAW,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;YAChD,kBAAkB,GAAG,OAAO,CAAC;QAC/B,CAAC,CAAC,CAAC;QAEH,IAAI,qBAAqB,GAAY,IAAI,CAAC;QAC1C,IAAI,aAAa,GAAG,KAAK,CAAC;QAE1B,0DAA0D;QAC1D,MAAM,SAAS,GAAG,KAAK,IAAmB,EAAE;YAC1C,aAAa,GAAG,IAAI,CAAC;YAErB,uEAAuE;YACvE,yDAAyD;YACzD,IAAI,CAAC,CAAC,yBAAyB,EAAE,EAAE;gBACjC,4DAA4D;gBAC5D,qBAAqB,GAAG,yBAAyB,CAAC;gBAClD,kBAAkB,EAAE,CAAC;YACvB,CAAC,CAAC,CAAC;YACH,OAAO,WAAW,CAAC;QACrB,CAAC,CAAC;QAEF,IAAI,CAAC;YACH,MAAM,eAAe,CAAC,OAAO,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;YAEpD,IAAI,aAAa,EAAE,CAAC;gBAClB,MAAM,WAAW,CAAC,CAAC,kDAAkD;gBACpE,qBAA+C,CAAC,IAAI,CAAC,CAAC;YACzD,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,IAAI,CAAC,CAAC;YACZ,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,qBAAqB,EAAE,CAAC;gBACzB,qBAA+C,CAAC,KAAK,CAAC,CAAC;YAC1D,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,KAAK,CAAC,CAAC;YACb,CAAC;QACH,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngineReturnHandler,\n JsonRpcMiddleware,\n} from './JsonRpcEngine';\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mergeMiddleware.cjs","sourceRoot":"","sources":["../src/mergeMiddleware.ts"],"names":[],"mappings":";;;AAGA,uDAAgD;AAEhD;;;;;;GAMG;AACH,SAAgB,eAAe,CAC7B,eAAyD;IAEzD,MAAM,MAAM,GAAG,IAAI,6BAAa,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;AAND,0CAMC","sourcesContent":["import type { Json, JsonRpcParams } from '@metamask/utils';\n\nimport type { JsonRpcMiddleware } from './JsonRpcEngine';\nimport { JsonRpcEngine } from './JsonRpcEngine';\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) {\n const engine = new JsonRpcEngine();\n middlewareStack.forEach((middleware) => engine.push(middleware));\n return engine.asMiddleware();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mergeMiddleware.cjs","sourceRoot":"","sources":["../src/mergeMiddleware.ts"],"names":[],"mappings":";;;AAGA,uDAAgD;AAEhD;;;;;;GAMG;AACH,SAAgB,eAAe,CAC7B,eAAyD;IAEzD,MAAM,MAAM,GAAG,IAAI,6BAAa,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;AAND,0CAMC","sourcesContent":["import type { Json, JsonRpcParams } from '@metamask/utils';\n\nimport type { JsonRpcMiddleware } from './JsonRpcEngine';\nimport { JsonRpcEngine } from './JsonRpcEngine';\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mergeMiddleware.d.cts","sourceRoot":"","sources":["../src/mergeMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,wBAAwB;AAE3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,4BAAwB;AAGzD;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,eAAe,EAAE,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,EAAE,
|
|
1
|
+
{"version":3,"file":"mergeMiddleware.d.cts","sourceRoot":"","sources":["../src/mergeMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,wBAAwB;AAE3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,4BAAwB;AAGzD;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,eAAe,EAAE,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,EAAE,GACxD,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,CAIxC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mergeMiddleware.d.mts","sourceRoot":"","sources":["../src/mergeMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,wBAAwB;AAE3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,4BAAwB;AAGzD;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,eAAe,EAAE,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,EAAE,
|
|
1
|
+
{"version":3,"file":"mergeMiddleware.d.mts","sourceRoot":"","sources":["../src/mergeMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,wBAAwB;AAE3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,4BAAwB;AAGzD;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,eAAe,EAAE,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,EAAE,GACxD,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,CAIxC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mergeMiddleware.mjs","sourceRoot":"","sources":["../src/mergeMiddleware.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAE,4BAAwB;AAEhD;;;;;;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';\nimport { JsonRpcEngine } from './JsonRpcEngine';\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) {\n const engine = new JsonRpcEngine();\n middlewareStack.forEach((middleware) => engine.push(middleware));\n return engine.asMiddleware();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mergeMiddleware.mjs","sourceRoot":"","sources":["../src/mergeMiddleware.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAE,4BAAwB;AAEhD;;;;;;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';\nimport { JsonRpcEngine } from './JsonRpcEngine';\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"]}
|
|
@@ -58,6 +58,7 @@ const INVALID_ENGINE = Symbol('Invalid engine');
|
|
|
58
58
|
*/
|
|
59
59
|
class JsonRpcEngineV2 {
|
|
60
60
|
// See .create() for why this is private.
|
|
61
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
61
62
|
constructor({ middleware }) {
|
|
62
63
|
_JsonRpcEngineV2_instances.add(this);
|
|
63
64
|
_JsonRpcEngineV2_middleware.set(this, void 0);
|
|
@@ -75,7 +76,7 @@ class JsonRpcEngineV2 {
|
|
|
75
76
|
* @param options.middleware - The middleware to use.
|
|
76
77
|
* @returns The JSON-RPC engine.
|
|
77
78
|
*/
|
|
78
|
-
static create({ middleware }) {
|
|
79
|
+
static create({ middleware, }) {
|
|
79
80
|
// We can't use NonEmptyArray for the params because it ruins type inference.
|
|
80
81
|
if (middleware.length === 0) {
|
|
81
82
|
throw new utils_2.JsonRpcEngineError('Middleware array cannot be empty');
|
|
@@ -102,6 +103,8 @@ class JsonRpcEngineV2 {
|
|
|
102
103
|
__classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_assertIsNotDestroyed).call(this);
|
|
103
104
|
return async ({ request, context, next }) => {
|
|
104
105
|
const { result, request: finalRequest } = await __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_handle).call(this, request, context);
|
|
106
|
+
// We can't use nullish coalescing here because `result` may be `null`.
|
|
107
|
+
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
|
105
108
|
return result === undefined ? await next(finalRequest) : result;
|
|
106
109
|
};
|
|
107
110
|
}
|