@metamask-previews/json-rpc-engine 11.0.0-preview-ff2ab0583 → 11.0.0-preview-a2f6118d2

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.
@@ -217,7 +217,7 @@ export class JsonRpcEngineV2 {
217
217
  typeof middleware.destroy === 'function') {
218
218
  return middleware.destroy();
219
219
  }
220
- return;
220
+ return undefined;
221
221
  }));
222
222
  this.#middleware = [];
223
223
  await destructionPromise;
@@ -1 +1 @@
1
- {"version":3,"file":"JsonRpcEngineV2.js","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAO9C,OAAO,UAAU,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAMrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,cAAc,EACd,SAAS,EACT,kBAAkB,EAClB,SAAS,GACV,MAAM,YAAY,CAAC;AAqGpB,MAAM,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAShD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,OAAO,eAAe;IAI1B,WAAW,CAIT;IAEF,YAAY,GAAG,KAAK,CAAC;IAErB,yCAAyC;IACzC,gDAAgD;IAChD,YAAoB,EAAE,UAAU,EAAwC;QACtE,IAAI,CAAC,WAAW,GAAG,CAAC,GAAG,UAAU,CAAC,CAAC;IACrC,CAAC;IAED,+FAA+F;IAC/F,6FAA6F;IAC7F,iBAAiB;IACjB;;;;;;;OAOG;IACH,MAAM,CAAC,MAAM,CASX,EACA,UAAU,GAGX;QAGC,6EAA6E;QAC7E,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC5B,MAAM,IAAI,kBAAkB,CAAC,kCAAkC,CAAC,CAA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AY;QAKV,IAAI,CAAC,qBAAqB,EAAE,CAAC;QAE7B,OAAO,KAAK,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE;YAC1C,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,GAAG,MAAM,IAAI,CAAC,OAAO,CAC1D,OAAO,EACP,OAAO,CACR,CAAC;YAEF,uEAAuE;YACvE,wEAAwE;YACxE,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAClE,CAAC,CAAC;IACJ,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,OAAO;QACX,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,OAAO;QACT,CAAC;QACD,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QAEzB,MAAM,kBAAkB,GAAG,OAAO,CAAC,GAAG,CACpC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,EAAE,EAAE;YACxC;YACE,wDAAwD;YACxD,SAAS,IAAI,UAAU;gBACvB,OAAO,UAAU,CAAC,OAAO,KAAK,UAAU,EACxC,CAAC;gBACD,OAAO,UAAU,CAAC,OAAO,EAAE,CAAC;YAC9B,CAAC;YACD,OAAO;QACT,CAAC,CAAC,CACH,CAAC;QACF,IAAI,CAAC,WAAW,GAAG,EAAW,CAAC;QAC/B,MAAM,kBAAkB,CAAC;IAC3B,CAAC;IAED,qBAAqB;QACnB,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,MAAM,IAAI,kBAAkB,CAAC,qBAAqB,CAAC,CAAC;QACtD,CAAC;IACH,CAAC;CACF","sourcesContent":["import { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcRequest,\n JsonRpcNotification,\n NonEmptyArray,\n} from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\n\nimport { deepClone } from './compatibility-utils.js';\nimport type {\n ContextConstraint,\n InferKeyValues,\n MergeContexts,\n} from './MiddlewareContext.js';\nimport { MiddlewareContext } from './MiddlewareContext.js';\nimport {\n isNotification,\n isRequest,\n JsonRpcEngineError,\n stringify,\n} from './utils.js';\nimport type { JsonRpcCall } from './utils.js';\n\n// Helper to forbid `id` on notifications\ntype WithoutId<Request extends JsonRpcCall> = Request & { id?: never };\n\n// Helper to enable JsonRpcCall overload of handle()\ntype MixedParam<Request extends JsonRpcCall> = [\n Extract<Request, JsonRpcRequest>,\n] extends [never]\n ? never\n : [Extract<Request, JsonRpcNotification>] extends [never]\n ? never\n :\n | Extract<Request, JsonRpcRequest>\n | WithoutId<Extract<Request, JsonRpcNotification>>;\n\nexport type ResultConstraint<Request extends JsonRpcCall> =\n Request extends JsonRpcRequest ? Json : void;\n\nexport type Next<Request extends JsonRpcCall> = (\n request?: Readonly<Request>,\n) => Promise<Readonly<ResultConstraint<Request>> | undefined>;\n\nexport type MiddlewareParams<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends ContextConstraint = MiddlewareContext,\n> = {\n request: Readonly<Request>;\n context: Context;\n next: Next<Request>;\n};\n\nexport type JsonRpcMiddleware<\n Request extends JsonRpcCall = JsonRpcCall,\n Result extends ResultConstraint<Request> = ResultConstraint<Request>,\n Context extends ContextConstraint = MiddlewareContext,\n> = (\n params: MiddlewareParams<Request, Context>,\n) => Readonly<Result> | undefined | Promise<Readonly<Result> | undefined>;\n\ntype RequestState<Request extends JsonRpcCall> = {\n request: Request;\n result: Readonly<ResultConstraint<Request>> | undefined;\n};\n\n/**\n * The options for the JSON-RPC request/notification handling operation.\n */\nexport type HandleOptions<Context extends ContextConstraint> = {\n context?: Context | InferKeyValues<Context>;\n};\n\ntype ConstructorOptions<\n Request extends JsonRpcCall,\n Context extends MiddlewareContext,\n> = {\n middleware: NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >;\n};\n\n/**\n * The request type of a middleware.\n */\nexport type RequestOf<Middleware> =\n Middleware extends JsonRpcMiddleware<\n infer Request,\n ResultConstraint<infer Request>,\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n >\n ? Request\n : never;\n\ntype ContextOf<Middleware> =\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Middleware extends JsonRpcMiddleware<any, ResultConstraint<any>, infer C>\n ? C\n : never;\n\n/**\n * A constraint for {@link JsonRpcMiddleware} generic parameters.\n */\n// Non-polluting `any` constraint.\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type MiddlewareConstraint = JsonRpcMiddleware<\n any,\n ResultConstraint<any>,\n MiddlewareContext<any>\n>;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/**\n * The context supertype of a middleware type.\n */\nexport type MergedContextOf<Middleware extends MiddlewareConstraint> =\n MergeContexts<ContextOf<Middleware>>;\n\nconst INVALID_ENGINE = Symbol('Invalid engine');\n\n/**\n * An internal type for invalid engines that explains why the engine is invalid.\n *\n * @template Message - The message explaining why the engine is invalid.\n */\ntype InvalidEngine<Message extends string> = { [INVALID_ENGINE]: Message };\n\n/**\n * A JSON-RPC request and response processor.\n *\n * Give it a stack of middleware, pass it requests, and get back responses.\n *\n * #### Requests vs. notifications\n *\n * JSON-RPC requests come in two flavors:\n *\n * - [Requests](https://www.jsonrpc.org/specification#request_object), i.e. request objects _with_ an `id`\n * - [Notifications](https://www.jsonrpc.org/specification#notification), i.e. request objects _without_ an `id`\n *\n * For requests, one of the engine's middleware must \"end\" the request by returning a non-`undefined` result,\n * or {@link handle} will throw an error:\n *\n * For notifications, on the other hand, one of the engine's middleware must return `undefined` to end the request,\n * and any non-`undefined` return values will cause an error:\n *\n * @template Request - The type of request to handle.\n * @template Result - The type of result to return.\n *\n * @example\n * ```ts\n * const engine = JsonRpcEngineV2.create({\n * middleware,\n * });\n *\n * try {\n * const result = await engine.handle(request);\n * // Handle result\n * } catch (error) {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcEngineV2<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends ContextConstraint = MiddlewareContext,\n> {\n #middleware: Readonly<\n NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >\n >;\n\n #isDestroyed = false;\n\n // See .create() for why this is private.\n // eslint-disable-next-line no-restricted-syntax\n private constructor({ middleware }: ConstructorOptions<Request, Context>) {\n this.#middleware = [...middleware];\n }\n\n // We use a static factory method in order to construct a supertype of all middleware contexts,\n // which enables us to instantiate an engine despite different middleware expecting different\n // context types.\n /**\n * Create a new JSON-RPC engine.\n *\n * @throws If the middleware array is empty.\n * @param options - The options for the engine.\n * @param options.middleware - The middleware to use.\n * @returns The JSON-RPC engine.\n */\n static create<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n >({\n middleware,\n }: {\n middleware: Middleware[];\n }): MergedContextOf<Middleware> extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<RequestOf<Middleware>, MergedContextOf<Middleware>> {\n // We can't use NonEmptyArray for the params because it ruins type inference.\n if (middleware.length === 0) {\n throw new JsonRpcEngineError('Middleware array cannot be empty');\n }\n\n type MergedContext = MergedContextOf<Middleware>;\n type InputRequest = RequestOf<Middleware>;\n const mw = middleware as unknown as NonEmptyArray<\n JsonRpcMiddleware<\n InputRequest,\n ResultConstraint<InputRequest>,\n MergedContext\n >\n >;\n\n return new JsonRpcEngineV2<InputRequest, MergedContext>({\n middleware: mw,\n }) as MergedContext extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<InputRequest, MergedContext>;\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * @param request - The JSON-RPC request to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response.\n */\n async handle(\n request: Extract<Request, JsonRpcRequest> extends never\n ? never\n : Extract<Request, JsonRpcRequest>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcRequest> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC notification. Notifications do not return a result.\n *\n * @param notification - The JSON-RPC notification to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n */\n async handle(\n notification: Extract<Request, JsonRpcNotification> extends never\n ? never\n : WithoutId<Extract<Request, JsonRpcNotification>>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcNotification> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC call, i.e. request or notification. Requests return a\n * result, notifications do not.\n *\n * @param call - The JSON-RPC call to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response, or `undefined` if the call is a notification.\n */\n async handle(\n call: MixedParam<Request>,\n options?: HandleOptions<Context>,\n ): Promise<ResultConstraint<Request> | void>;\n\n async handle(\n request: Request,\n { context }: HandleOptions<Context> = {},\n ): Promise<ResultConstraint<Request> | void> {\n // This error appeared when upgrading to TypeScript 7.\n // @ts-expect-error: TS2345: Argument of type 'JsonRpcCall' is not assignable\n // to parameter of type 'JsonRpcCall<Record<string, Json>> | Readonly<JsonRpcCall<Record<string, Json>>>'.\n const isReq = isRequest(request);\n const { result } = await this.#handle(request, context);\n\n if (isReq && result === undefined) {\n throw new JsonRpcEngineError(\n `Nothing ended request: ${stringify(request)}`,\n );\n }\n return deepClone(result) as ResultConstraint<Request>;\n }\n\n /**\n * Handle a JSON-RPC request. Throws if a middleware performs an invalid\n * operation. Permits returning an `undefined` result.\n *\n * @param originalRequest - The JSON-RPC request to handle.\n * @param rawContext - The context to pass to the middleware.\n * @returns The result from the middleware.\n */\n async #handle(\n originalRequest: Request,\n rawContext:\n | Context\n | InferKeyValues<Context> = new MiddlewareContext() as Context,\n ): Promise<RequestState<Request>> {\n this.#assertIsNotDestroyed();\n\n deepFreeze(originalRequest);\n\n const state: RequestState<Request> = {\n request: originalRequest,\n result: undefined,\n };\n const middlewareIterator = this.#makeMiddlewareIterator();\n const firstMiddleware = middlewareIterator.next().value;\n const context = MiddlewareContext.isInstance(rawContext)\n ? rawContext\n : (new MiddlewareContext(rawContext) as Context);\n\n const makeNext = this.#makeNextFactory(middlewareIterator, state, context);\n\n const result = await firstMiddleware({\n request: originalRequest,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state;\n }\n\n /**\n * Create a factory of `next()` functions for use with a particular request.\n * The factory is recursive, and a new `next()` is created for each middleware\n * invocation.\n *\n * @param middlewareIterator - The iterator of middleware for the current\n * request.\n * @param state - The current values of the request and result.\n * @param context - The context to pass to the middleware.\n * @returns The `next()` function factory.\n */\n #makeNextFactory(\n middlewareIterator: Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >,\n state: RequestState<Request>,\n context: Context,\n ): () => Next<Request> {\n const makeNext = (): Next<Request> => {\n let wasCalled = false;\n\n const next = async (\n request: Request = state.request,\n ): Promise<Readonly<ResultConstraint<Request>> | undefined> => {\n if (wasCalled) {\n throw new JsonRpcEngineError(\n `Middleware attempted to call next() multiple times for request: ${stringify(request)}`,\n );\n }\n wasCalled = true;\n\n if (request !== state.request) {\n this.#assertValidNextRequest(state.request, request);\n state.request = deepFreeze(request);\n }\n\n const { value: nextMiddleware, done } = middlewareIterator.next();\n if (done) {\n // This will cause the last middleware to return `undefined`. See the class\n // JSDoc or package README for more details.\n return undefined;\n }\n\n const result = await nextMiddleware({\n request,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state.result;\n };\n return next;\n };\n\n return makeNext;\n }\n\n #makeMiddlewareIterator(): Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n > {\n return this.#middleware[Symbol.iterator]();\n }\n\n /**\n * Validate the result from a middleware and, if it's a new value, update the\n * current result.\n *\n * @param result - The result from the middleware.\n * @param state - The current values of the request and result.\n */\n #updateResult(\n result:\n | Readonly<ResultConstraint<Request>>\n | ResultConstraint<Request>\n | void,\n state: RequestState<Request>,\n ): void {\n if (isNotification(state.request) && result !== undefined) {\n throw new JsonRpcEngineError(\n `Result returned for notification: ${stringify(state.request)}`,\n );\n }\n\n if (result !== undefined && result !== state.result) {\n if (typeof result === 'object' && result !== null) {\n deepFreeze(result);\n }\n state.result = result;\n }\n }\n\n /**\n * Assert that a request modified by a middleware is valid.\n *\n * @param currentRequest - The current request.\n * @param nextRequest - The next request.\n */\n #assertValidNextRequest(currentRequest: Request, nextRequest: Request): void {\n if (nextRequest.jsonrpc !== currentRequest.jsonrpc) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"jsonrpc\" for request: ${stringify(currentRequest)}`,\n );\n }\n if (\n hasProperty(nextRequest, 'id') !== hasProperty(currentRequest, 'id') ||\n // @ts-expect-error - \"id\" does not exist on notifications, but we can still\n // check the value of the property at runtime.\n nextRequest.id !== currentRequest.id\n ) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"id\" for request: ${stringify(currentRequest)}`,\n );\n }\n }\n\n /**\n * Convert the engine into a JSON-RPC middleware.\n *\n * @returns The JSON-RPC middleware.\n */\n asMiddleware(): JsonRpcMiddleware<\n Request,\n ResultConstraint<Request>,\n Context\n > {\n this.#assertIsNotDestroyed();\n\n return async ({ request, context, next }) => {\n const { result, request: finalRequest } = await this.#handle(\n request,\n context,\n );\n\n // We can't use nullish coalescing here because `result` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n return result === undefined ? await next(finalRequest) : result;\n };\n }\n\n /**\n * Destroy the engine. Calls the `destroy()` method of any middleware that has\n * one. Attempting to use the engine after destroying it will throw an error.\n */\n async destroy(): Promise<void> {\n if (this.#isDestroyed) {\n return;\n }\n this.#isDestroyed = true;\n\n const destructionPromise = Promise.all(\n this.#middleware.map(async (middleware) => {\n if (\n // Intentionally using `in` to walk the prototype chain.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n return middleware.destroy();\n }\n return;\n }),\n );\n this.#middleware = [] as never;\n await destructionPromise;\n }\n\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new JsonRpcEngineError('Engine is destroyed');\n }\n }\n}\n"]}
1
+ {"version":3,"file":"JsonRpcEngineV2.js","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAO9C,OAAO,UAAU,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAMrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,cAAc,EACd,SAAS,EACT,kBAAkB,EAClB,SAAS,GACV,MAAM,YAAY,CAAC;AAqGpB,MAAM,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAShD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,OAAO,eAAe;IAI1B,WAAW,CAIT;IAEF,YAAY,GAAG,KAAK,CAAC;IAErB,yCAAyC;IACzC,gDAAgD;IAChD,YAAoB,EAAE,UAAU,EAAwC;QACtE,IAAI,CAAC,WAAW,GAAG,CAAC,GAAG,UAAU,CAAC,CAAC;IACrC,CAAC;IAED,+FAA+F;IAC/F,6FAA6F;IAC7F,iBAAiB;IACjB;;;;;;;OAOG;IACH,MAAM,CAAC,MAAM,CASX,EACA,UAAU,GAGX;QAGC,6EAA6E;QAC7E,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC5B,MAAM,IAAI,kBAAkB,CAAC,kCAAkC,CAAC,CAAC;QACnE,CAAC;QAID,MAAM,EAAE,GAAG,UAMV,CAAC;QAEF,OAAO,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EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE;YAC1C,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,GAAG,MAAM,IAAI,CAAC,OAAO,CAC1D,OAAO,EACP,OAAO,CACR,CAAC;YAEF,uEAAuE;YACvE,wEAAwE;YACxE,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAClE,CAAC,CAAC;IACJ,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,OAAO;QACX,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,OAAO;QACT,CAAC;QACD,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QAEzB,MAAM,kBAAkB,GAAG,OAAO,CAAC,GAAG,CACpC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,EAAE,EAAE;YACxC;YACE,wDAAwD;YACxD,SAAS,IAAI,UAAU;gBACvB,OAAO,UAAU,CAAC,OAAO,KAAK,UAAU,EACxC,CAAC;gBACD,OAAO,UAAU,CAAC,OAAO,EAAE,CAAC;YAC9B,CAAC;YACD,OAAO,SAAS,CAAC;QACnB,CAAC,CAAC,CACH,CAAC;QACF,IAAI,CAAC,WAAW,GAAG,EAAW,CAAC;QAC/B,MAAM,kBAAkB,CAAC;IAC3B,CAAC;IAED,qBAAqB;QACnB,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,MAAM,IAAI,kBAAkB,CAAC,qBAAqB,CAAC,CAAC;QACtD,CAAC;IACH,CAAC;CACF","sourcesContent":["import { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcRequest,\n JsonRpcNotification,\n NonEmptyArray,\n} from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\n\nimport { deepClone } from './compatibility-utils.js';\nimport type {\n ContextConstraint,\n InferKeyValues,\n MergeContexts,\n} from './MiddlewareContext.js';\nimport { MiddlewareContext } from './MiddlewareContext.js';\nimport {\n isNotification,\n isRequest,\n JsonRpcEngineError,\n stringify,\n} from './utils.js';\nimport type { JsonRpcCall } from './utils.js';\n\n// Helper to forbid `id` on notifications\ntype WithoutId<Request extends JsonRpcCall> = Request & { id?: never };\n\n// Helper to enable JsonRpcCall overload of handle()\ntype MixedParam<Request extends JsonRpcCall> = [\n Extract<Request, JsonRpcRequest>,\n] extends [never]\n ? never\n : [Extract<Request, JsonRpcNotification>] extends [never]\n ? never\n :\n | Extract<Request, JsonRpcRequest>\n | WithoutId<Extract<Request, JsonRpcNotification>>;\n\nexport type ResultConstraint<Request extends JsonRpcCall> =\n Request extends JsonRpcRequest ? Json : void;\n\nexport type Next<Request extends JsonRpcCall> = (\n request?: Readonly<Request>,\n) => Promise<Readonly<ResultConstraint<Request>> | undefined>;\n\nexport type MiddlewareParams<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends ContextConstraint = MiddlewareContext,\n> = {\n request: Readonly<Request>;\n context: Context;\n next: Next<Request>;\n};\n\nexport type JsonRpcMiddleware<\n Request extends JsonRpcCall = JsonRpcCall,\n Result extends ResultConstraint<Request> = ResultConstraint<Request>,\n Context extends ContextConstraint = MiddlewareContext,\n> = (\n params: MiddlewareParams<Request, Context>,\n) => Readonly<Result> | undefined | Promise<Readonly<Result> | undefined>;\n\ntype RequestState<Request extends JsonRpcCall> = {\n request: Request;\n result: Readonly<ResultConstraint<Request>> | undefined;\n};\n\n/**\n * The options for the JSON-RPC request/notification handling operation.\n */\nexport type HandleOptions<Context extends ContextConstraint> = {\n context?: Context | InferKeyValues<Context>;\n};\n\ntype ConstructorOptions<\n Request extends JsonRpcCall,\n Context extends MiddlewareContext,\n> = {\n middleware: NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >;\n};\n\n/**\n * The request type of a middleware.\n */\nexport type RequestOf<Middleware> =\n Middleware extends JsonRpcMiddleware<\n infer Request,\n ResultConstraint<infer Request>,\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n >\n ? Request\n : never;\n\ntype ContextOf<Middleware> =\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Middleware extends JsonRpcMiddleware<any, ResultConstraint<any>, infer C>\n ? C\n : never;\n\n/**\n * A constraint for {@link JsonRpcMiddleware} generic parameters.\n */\n// Non-polluting `any` constraint.\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type MiddlewareConstraint = JsonRpcMiddleware<\n any,\n ResultConstraint<any>,\n MiddlewareContext<any>\n>;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/**\n * The context supertype of a middleware type.\n */\nexport type MergedContextOf<Middleware extends MiddlewareConstraint> =\n MergeContexts<ContextOf<Middleware>>;\n\nconst INVALID_ENGINE = Symbol('Invalid engine');\n\n/**\n * An internal type for invalid engines that explains why the engine is invalid.\n *\n * @template Message - The message explaining why the engine is invalid.\n */\ntype InvalidEngine<Message extends string> = { [INVALID_ENGINE]: Message };\n\n/**\n * A JSON-RPC request and response processor.\n *\n * Give it a stack of middleware, pass it requests, and get back responses.\n *\n * #### Requests vs. notifications\n *\n * JSON-RPC requests come in two flavors:\n *\n * - [Requests](https://www.jsonrpc.org/specification#request_object), i.e. request objects _with_ an `id`\n * - [Notifications](https://www.jsonrpc.org/specification#notification), i.e. request objects _without_ an `id`\n *\n * For requests, one of the engine's middleware must \"end\" the request by returning a non-`undefined` result,\n * or {@link handle} will throw an error:\n *\n * For notifications, on the other hand, one of the engine's middleware must return `undefined` to end the request,\n * and any non-`undefined` return values will cause an error:\n *\n * @template Request - The type of request to handle.\n * @template Result - The type of result to return.\n *\n * @example\n * ```ts\n * const engine = JsonRpcEngineV2.create({\n * middleware,\n * });\n *\n * try {\n * const result = await engine.handle(request);\n * // Handle result\n * } catch (error) {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcEngineV2<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends ContextConstraint = MiddlewareContext,\n> {\n #middleware: Readonly<\n NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >\n >;\n\n #isDestroyed = false;\n\n // See .create() for why this is private.\n // eslint-disable-next-line no-restricted-syntax\n private constructor({ middleware }: ConstructorOptions<Request, Context>) {\n this.#middleware = [...middleware];\n }\n\n // We use a static factory method in order to construct a supertype of all middleware contexts,\n // which enables us to instantiate an engine despite different middleware expecting different\n // context types.\n /**\n * Create a new JSON-RPC engine.\n *\n * @throws If the middleware array is empty.\n * @param options - The options for the engine.\n * @param options.middleware - The middleware to use.\n * @returns The JSON-RPC engine.\n */\n static create<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n >({\n middleware,\n }: {\n middleware: Middleware[];\n }): MergedContextOf<Middleware> extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<RequestOf<Middleware>, MergedContextOf<Middleware>> {\n // We can't use NonEmptyArray for the params because it ruins type inference.\n if (middleware.length === 0) {\n throw new JsonRpcEngineError('Middleware array cannot be empty');\n }\n\n type MergedContext = MergedContextOf<Middleware>;\n type InputRequest = RequestOf<Middleware>;\n const mw = middleware as unknown as NonEmptyArray<\n JsonRpcMiddleware<\n InputRequest,\n ResultConstraint<InputRequest>,\n MergedContext\n >\n >;\n\n return new JsonRpcEngineV2<InputRequest, MergedContext>({\n middleware: mw,\n }) as MergedContext extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<InputRequest, MergedContext>;\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * @param request - The JSON-RPC request to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response.\n */\n async handle(\n request: Extract<Request, JsonRpcRequest> extends never\n ? never\n : Extract<Request, JsonRpcRequest>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcRequest> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC notification. Notifications do not return a result.\n *\n * @param notification - The JSON-RPC notification to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n */\n async handle(\n notification: Extract<Request, JsonRpcNotification> extends never\n ? never\n : WithoutId<Extract<Request, JsonRpcNotification>>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcNotification> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC call, i.e. request or notification. Requests return a\n * result, notifications do not.\n *\n * @param call - The JSON-RPC call to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response, or `undefined` if the call is a notification.\n */\n async handle(\n call: MixedParam<Request>,\n options?: HandleOptions<Context>,\n ): Promise<ResultConstraint<Request> | void>;\n\n async handle(\n request: Request,\n { context }: HandleOptions<Context> = {},\n ): Promise<ResultConstraint<Request> | void> {\n // This error appeared when upgrading to TypeScript 7.\n // @ts-expect-error: TS2345: Argument of type 'JsonRpcCall' is not assignable\n // to parameter of type 'JsonRpcCall<Record<string, Json>> | Readonly<JsonRpcCall<Record<string, Json>>>'.\n const isReq = isRequest(request);\n const { result } = await this.#handle(request, context);\n\n if (isReq && result === undefined) {\n throw new JsonRpcEngineError(\n `Nothing ended request: ${stringify(request)}`,\n );\n }\n return deepClone(result) as ResultConstraint<Request>;\n }\n\n /**\n * Handle a JSON-RPC request. Throws if a middleware performs an invalid\n * operation. Permits returning an `undefined` result.\n *\n * @param originalRequest - The JSON-RPC request to handle.\n * @param rawContext - The context to pass to the middleware.\n * @returns The result from the middleware.\n */\n async #handle(\n originalRequest: Request,\n rawContext:\n | Context\n | InferKeyValues<Context> = new MiddlewareContext() as Context,\n ): Promise<RequestState<Request>> {\n this.#assertIsNotDestroyed();\n\n deepFreeze(originalRequest);\n\n const state: RequestState<Request> = {\n request: originalRequest,\n result: undefined,\n };\n const middlewareIterator = this.#makeMiddlewareIterator();\n const firstMiddleware = middlewareIterator.next().value;\n const context = MiddlewareContext.isInstance(rawContext)\n ? rawContext\n : (new MiddlewareContext(rawContext) as Context);\n\n const makeNext = this.#makeNextFactory(middlewareIterator, state, context);\n\n const result = await firstMiddleware({\n request: originalRequest,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state;\n }\n\n /**\n * Create a factory of `next()` functions for use with a particular request.\n * The factory is recursive, and a new `next()` is created for each middleware\n * invocation.\n *\n * @param middlewareIterator - The iterator of middleware for the current\n * request.\n * @param state - The current values of the request and result.\n * @param context - The context to pass to the middleware.\n * @returns The `next()` function factory.\n */\n #makeNextFactory(\n middlewareIterator: Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >,\n state: RequestState<Request>,\n context: Context,\n ): () => Next<Request> {\n const makeNext = (): Next<Request> => {\n let wasCalled = false;\n\n const next = async (\n request: Request = state.request,\n ): Promise<Readonly<ResultConstraint<Request>> | undefined> => {\n if (wasCalled) {\n throw new JsonRpcEngineError(\n `Middleware attempted to call next() multiple times for request: ${stringify(request)}`,\n );\n }\n wasCalled = true;\n\n if (request !== state.request) {\n this.#assertValidNextRequest(state.request, request);\n state.request = deepFreeze(request);\n }\n\n const { value: nextMiddleware, done } = middlewareIterator.next();\n if (done) {\n // This will cause the last middleware to return `undefined`. See the class\n // JSDoc or package README for more details.\n return undefined;\n }\n\n const result = await nextMiddleware({\n request,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state.result;\n };\n return next;\n };\n\n return makeNext;\n }\n\n #makeMiddlewareIterator(): Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n > {\n return this.#middleware[Symbol.iterator]();\n }\n\n /**\n * Validate the result from a middleware and, if it's a new value, update the\n * current result.\n *\n * @param result - The result from the middleware.\n * @param state - The current values of the request and result.\n */\n #updateResult(\n result:\n | Readonly<ResultConstraint<Request>>\n | ResultConstraint<Request>\n | void,\n state: RequestState<Request>,\n ): void {\n if (isNotification(state.request) && result !== undefined) {\n throw new JsonRpcEngineError(\n `Result returned for notification: ${stringify(state.request)}`,\n );\n }\n\n if (result !== undefined && result !== state.result) {\n if (typeof result === 'object' && result !== null) {\n deepFreeze(result);\n }\n state.result = result;\n }\n }\n\n /**\n * Assert that a request modified by a middleware is valid.\n *\n * @param currentRequest - The current request.\n * @param nextRequest - The next request.\n */\n #assertValidNextRequest(currentRequest: Request, nextRequest: Request): void {\n if (nextRequest.jsonrpc !== currentRequest.jsonrpc) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"jsonrpc\" for request: ${stringify(currentRequest)}`,\n );\n }\n if (\n hasProperty(nextRequest, 'id') !== hasProperty(currentRequest, 'id') ||\n // @ts-expect-error - \"id\" does not exist on notifications, but we can still\n // check the value of the property at runtime.\n nextRequest.id !== currentRequest.id\n ) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"id\" for request: ${stringify(currentRequest)}`,\n );\n }\n }\n\n /**\n * Convert the engine into a JSON-RPC middleware.\n *\n * @returns The JSON-RPC middleware.\n */\n asMiddleware(): JsonRpcMiddleware<\n Request,\n ResultConstraint<Request>,\n Context\n > {\n this.#assertIsNotDestroyed();\n\n return async ({ request, context, next }) => {\n const { result, request: finalRequest } = await this.#handle(\n request,\n context,\n );\n\n // We can't use nullish coalescing here because `result` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n return result === undefined ? await next(finalRequest) : result;\n };\n }\n\n /**\n * Destroy the engine. Calls the `destroy()` method of any middleware that has\n * one. Attempting to use the engine after destroying it will throw an error.\n */\n async destroy(): Promise<void> {\n if (this.#isDestroyed) {\n return;\n }\n this.#isDestroyed = true;\n\n const destructionPromise = Promise.all(\n this.#middleware.map(async (middleware) => {\n if (\n // Intentionally using `in` to walk the prototype chain.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n return middleware.destroy();\n }\n return undefined;\n }),\n );\n this.#middleware = [] as never;\n await destructionPromise;\n }\n\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new JsonRpcEngineError('Engine is destroyed');\n }\n }\n}\n"]}
@@ -33,7 +33,7 @@ export function asLegacyMiddleware(engineOrMiddleware, ...rest) {
33
33
  if (result !== undefined) {
34
34
  // Unclear why the `as unknown` is needed here, but the cast is safe.
35
35
  res.result = deepClone(result);
36
- return;
36
+ return undefined;
37
37
  }
38
38
  return next();
39
39
  });
@@ -1 +1 @@
1
- {"version":3,"file":"asLegacyMiddleware.js","sourceRoot":"","sources":["../../src/v2/asLegacyMiddleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEpD,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,WAAW,EACX,kBAAkB,GACnB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AA4BvD;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAIhC,kBAEyD,EACzD,GAAG,IAA6D;IAEhE,MAAM,YAAY,GAChB,OAAO,kBAAkB,KAAK,UAAU;QACtC,CAAC,CAAC,eAAe,CAAC,MAAM,CAAC;YACrB,UAAU,EAAE,CAAC,kBAAkB,EAAE,GAAG,IAAI,CAAC;SAC1C,CAAC,CAAC,YAAY,EAAE;QACnB,CAAC,CAAC,kBAAkB,CAAC,YAAY,EAAE,CAAC;IAExC,OAAO,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACpD,MAAM,OAAO,GAAG,iBAAiB,CAAC,GAAc,CAAC,CAAC;QAClD,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;QACjC,IAAI,eAAoC,CAAC;QAEzC,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC;YAChC,OAAO;YACP,OAAO;YACP,IAAI,EAAE,CAAC,YAAY,EAAE,EAAE;gBACrB,eAAe,GAAG,YAAY,CAAC;gBAC/B,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;YACpC,CAAC;SACF,CAAC,CAAC;QAEH,IAAI,eAAe,KAAK,SAAS,IAAI,eAAe,KAAK,OAAO,EAAE,CAAC;YACjE,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,SAAS,CAAC,eAAe,CAAC,CAAC,CAAC;QACjD,CAAC;QACD,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACzB,qEAAqE;YACrE,GAAG,CAAC,MAAM,GAAG,SAAS,CAAC,MAAM,CAAyC,CAAC;YACvE,OAAO;QACT,CAAC;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nimport { createAsyncMiddleware } from '../index.js';\nimport type { JsonRpcMiddleware as LegacyMiddleware } from '../index.js';\nimport {\n deepClone,\n fromLegacyRequest,\n makeContext,\n propagateToRequest,\n} from './compatibility-utils.js';\nimport type { JsonRpcMiddleware, ResultConstraint } from './JsonRpcEngineV2.js';\nimport { JsonRpcEngineV2 } from './JsonRpcEngineV2.js';\n\n/**\n * Convert a {@link JsonRpcEngineV2} into a legacy middleware.\n *\n * @param engine - The engine to convert.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engine: JsonRpcEngineV2<Request>,\n): LegacyMiddleware<Params, ResultConstraint<Request>>;\n\n/**\n * Convert one or more V2 middlewares into a legacy middleware.\n *\n * @param middleware - The V2 middleware(s) to convert.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n ...middleware: JsonRpcMiddleware<Request, ResultConstraint<Request>>[]\n): LegacyMiddleware<Params, ResultConstraint<Request>>;\n\n/**\n * The asLegacyMiddleware implementation.\n *\n * @param engineOrMiddleware - A V2 engine or V2 middleware.\n * @param rest - Any additional V2 middleware when the first argument is a middleware.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engineOrMiddleware:\n | JsonRpcEngineV2<Request>\n | JsonRpcMiddleware<Request, ResultConstraint<Request>>,\n ...rest: JsonRpcMiddleware<Request, ResultConstraint<Request>>[]\n): LegacyMiddleware<Params, ResultConstraint<Request>> {\n const v2Middleware =\n typeof engineOrMiddleware === 'function'\n ? JsonRpcEngineV2.create({\n middleware: [engineOrMiddleware, ...rest],\n }).asMiddleware()\n : engineOrMiddleware.asMiddleware();\n\n return createAsyncMiddleware(async (req, res, next) => {\n const request = fromLegacyRequest(req as Request);\n const context = makeContext(req);\n let modifiedRequest: Request | undefined;\n\n const result = await v2Middleware({\n request,\n context,\n next: (finalRequest) => {\n modifiedRequest = finalRequest;\n return Promise.resolve(undefined);\n },\n });\n\n if (modifiedRequest !== undefined && modifiedRequest !== request) {\n Object.assign(req, deepClone(modifiedRequest));\n }\n propagateToRequest(req, context);\n\n if (result !== undefined) {\n // Unclear why the `as unknown` is needed here, but the cast is safe.\n res.result = deepClone(result) as unknown as ResultConstraint<Request>;\n return;\n }\n return next();\n });\n}\n"]}
1
+ {"version":3,"file":"asLegacyMiddleware.js","sourceRoot":"","sources":["../../src/v2/asLegacyMiddleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEpD,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,WAAW,EACX,kBAAkB,GACnB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AA4B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syncMiddleware } from '../index.js';\nimport type { JsonRpcMiddleware as LegacyMiddleware } from '../index.js';\nimport {\n deepClone,\n fromLegacyRequest,\n makeContext,\n propagateToRequest,\n} from './compatibility-utils.js';\nimport type { JsonRpcMiddleware, ResultConstraint } from './JsonRpcEngineV2.js';\nimport { JsonRpcEngineV2 } from './JsonRpcEngineV2.js';\n\n/**\n * Convert a {@link JsonRpcEngineV2} into a legacy middleware.\n *\n * @param engine - The engine to convert.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engine: JsonRpcEngineV2<Request>,\n): LegacyMiddleware<Params, ResultConstraint<Request>>;\n\n/**\n * Convert one or more V2 middlewares into a legacy middleware.\n *\n * @param middleware - The V2 middleware(s) to convert.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n ...middleware: JsonRpcMiddleware<Request, ResultConstraint<Request>>[]\n): LegacyMiddleware<Params, ResultConstraint<Request>>;\n\n/**\n * The asLegacyMiddleware implementation.\n *\n * @param engineOrMiddleware - A V2 engine or V2 middleware.\n * @param rest - Any additional V2 middleware when the first argument is a middleware.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engineOrMiddleware:\n | JsonRpcEngineV2<Request>\n | JsonRpcMiddleware<Request, ResultConstraint<Request>>,\n ...rest: JsonRpcMiddleware<Request, ResultConstraint<Request>>[]\n): LegacyMiddleware<Params, ResultConstraint<Request>> {\n const v2Middleware =\n typeof engineOrMiddleware === 'function'\n ? JsonRpcEngineV2.create({\n middleware: [engineOrMiddleware, ...rest],\n }).asMiddleware()\n : engineOrMiddleware.asMiddleware();\n\n return createAsyncMiddleware(async (req, res, next) => {\n const request = fromLegacyRequest(req as Request);\n const context = makeContext(req);\n let modifiedRequest: Request | undefined;\n\n const result = await v2Middleware({\n request,\n context,\n next: (finalRequest) => {\n modifiedRequest = finalRequest;\n return Promise.resolve(undefined);\n },\n });\n\n if (modifiedRequest !== undefined && modifiedRequest !== request) {\n Object.assign(req, deepClone(modifiedRequest));\n }\n propagateToRequest(req, context);\n\n if (result !== undefined) {\n // Unclear why the `as unknown` is needed here, but the cast is safe.\n res.result = deepClone(result) as unknown as ResultConstraint<Request>;\n return undefined;\n }\n return next();\n });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/json-rpc-engine",
3
- "version": "11.0.0-preview-ff2ab0583",
3
+ "version": "11.0.0-preview-a2f6118d2",
4
4
  "description": "A tool for processing JSON-RPC messages",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -65,16 +65,16 @@
65
65
  "klona": "^2.0.6"
66
66
  },
67
67
  "devDependencies": {
68
- "@lavamoat/allow-scripts": "^3.4.3",
68
+ "@lavamoat/allow-scripts": "^3.0.4",
69
69
  "@lavamoat/preinstall-always-fail": "^2.1.0",
70
- "@metamask/auto-changelog": "^6.2.1",
70
+ "@metamask/auto-changelog": "^6.1.0",
71
71
  "@types/jest": "^30.0.0",
72
72
  "@typescript/native": "npm:typescript@^7.0.2",
73
- "deepmerge": "^4.3.1",
73
+ "deepmerge": "^4.2.2",
74
74
  "jest": "^30.4.2",
75
- "rimraf": "^6.1.3",
76
- "ts-jest": "^29.4.12",
77
- "tsx": "^4.23.15",
75
+ "rimraf": "^5.0.5",
76
+ "ts-jest": "^29.4.11",
77
+ "tsx": "^4.20.5",
78
78
  "typedoc": "^0.25.13",
79
79
  "typescript": "npm:@typescript/typescript6@^6.0.2"
80
80
  },