@metamask-previews/json-rpc-engine 10.2.0-preview-7cfbb337 → 10.2.0-preview-bea9ae5
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/asV2Middleware.cjs.map +1 -1
- package/dist/asV2Middleware.d.cts +2 -2
- package/dist/asV2Middleware.d.cts.map +1 -1
- package/dist/asV2Middleware.d.mts +2 -2
- package/dist/asV2Middleware.d.mts.map +1 -1
- package/dist/asV2Middleware.mjs.map +1 -1
- package/dist/v2/JsonRpcEngineV2.cjs.map +1 -1
- package/dist/v2/JsonRpcEngineV2.d.cts +1 -1
- package/dist/v2/JsonRpcEngineV2.d.cts.map +1 -1
- package/dist/v2/JsonRpcEngineV2.d.mts +1 -1
- package/dist/v2/JsonRpcEngineV2.d.mts.map +1 -1
- package/dist/v2/JsonRpcEngineV2.mjs.map +1 -1
- package/dist/v2/MiddlewareContext.cjs.map +1 -1
- package/dist/v2/MiddlewareContext.d.cts +1 -1
- package/dist/v2/MiddlewareContext.d.cts.map +1 -1
- package/dist/v2/MiddlewareContext.d.mts +1 -1
- package/dist/v2/MiddlewareContext.d.mts.map +1 -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 +1 -1
- package/dist/v2/compatibility-utils.d.cts.map +1 -1
- package/dist/v2/compatibility-utils.d.mts +1 -1
- package/dist/v2/compatibility-utils.d.mts.map +1 -1
- package/dist/v2/compatibility-utils.mjs.map +1 -1
- package/dist/v2/utils.cjs.map +1 -1
- package/dist/v2/utils.d.cts +1 -1
- package/dist/v2/utils.d.cts.map +1 -1
- package/dist/v2/utils.d.mts +1 -1
- package/dist/v2/utils.d.mts.map +1 -1
- package/dist/v2/utils.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asV2Middleware.cjs","sourceRoot":"","sources":["../src/asV2Middle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8B,CAAC;YAExC,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 = ((cb: JsonRpcEngineEndCallback) =>\n cb(end)) as JsonRpcEngineNextCallback;\n\n legacyMiddleware(req, res, legacyNext, end);\n });\n propagateToContext(req, context);\n\n // Mimic the behavior of JsonRpcEngine.#handle(), which only treats truthy errors as errors.\n // Legacy middleware may violate the invariant that response objects have either a result or an\n // error property. In practice, we may see response objects with results and `{ error: undefined }`.\n if (hasProperty(response, 'error') && response.error) {\n throw deserializeError(response.error);\n } else if (hasProperty(response, 'result')) {\n return response.result as ResultConstraint<Request>;\n }\n return next(fromLegacyRequest(req as Request));\n };\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { JsonRpcParams, JsonRpcRequest } from "@metamask/utils";
|
|
2
2
|
import type { JsonRpcEngine } from "./JsonRpcEngine.cjs";
|
|
3
|
-
import {
|
|
3
|
+
import type { JsonRpcMiddleware as LegacyMiddleware } from "./JsonRpcEngine.cjs";
|
|
4
4
|
import type { ContextConstraint, MiddlewareContext } from "./v2/index.cjs";
|
|
5
5
|
import type { JsonRpcMiddleware, ResultConstraint } from "./v2/JsonRpcEngineV2.cjs";
|
|
6
6
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asV2Middleware.d.cts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,
|
|
1
|
+
{"version":3,"file":"asV2Middleware.d.cts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAGV,aAAa,EACb,cAAc,EAEf,wBAAwB;AAEzB,OAAO,KAAK,EACV,aAAa,EAGd,4BAAwB;AACzB,OAAO,KAAK,EAAE,iBAAiB,IAAI,gBAAgB,EAAE,4BAAwB;AAE7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,uBAAa;AAQjE,OAAO,KAAK,EAIV,iBAAiB,EACjB,gBAAgB,EACjB,iCAA6B;AAE9B;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EACtC,MAAM,EAAE,aAAa,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;AAErD;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,GAAG,aAAa,EAC5C,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,EAC/D,MAAM,SAAS,gBAAgB,CAAC,OAAO,CAAC,GAAG,gBAAgB,CAAC,OAAO,CAAC,EACpE,OAAO,SAAS,iBAAiB,GAAG,iBAAiB,EAErD,GAAG,UAAU,EAAE,gBAAgB,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,GAChD,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { JsonRpcParams, JsonRpcRequest } from "@metamask/utils";
|
|
2
2
|
import type { JsonRpcEngine } from "./JsonRpcEngine.mjs";
|
|
3
|
-
import {
|
|
3
|
+
import type { JsonRpcMiddleware as LegacyMiddleware } from "./JsonRpcEngine.mjs";
|
|
4
4
|
import type { ContextConstraint, MiddlewareContext } from "./v2/index.mjs";
|
|
5
5
|
import type { JsonRpcMiddleware, ResultConstraint } from "./v2/JsonRpcEngineV2.mjs";
|
|
6
6
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asV2Middleware.d.mts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,
|
|
1
|
+
{"version":3,"file":"asV2Middleware.d.mts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAGV,aAAa,EACb,cAAc,EAEf,wBAAwB;AAEzB,OAAO,KAAK,EACV,aAAa,EAGd,4BAAwB;AACzB,OAAO,KAAK,EAAE,iBAAiB,IAAI,gBAAgB,EAAE,4BAAwB;AAE7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,uBAAa;AAQjE,OAAO,KAAK,EAIV,iBAAiB,EACjB,gBAAgB,EACjB,iCAA6B;AAE9B;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EACtC,MAAM,EAAE,aAAa,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;AAErD;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,GAAG,aAAa,EAC5C,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,EAC/D,MAAM,SAAS,gBAAgB,CAAC,OAAO,CAAC,GAAG,gBAAgB,CAAC,OAAO,CAAC,EACpE,OAAO,SAAS,iBAAiB,GAAG,iBAAiB,EAErD,GAAG,UAAU,EAAE,gBAAgB,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,GAChD,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asV2Middleware.mjs","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,6BAA6B;
|
|
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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AAoG;QACpG,IAAI,WAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,IAAI,QAAQ,CAAC,KAAK,EAAE,CAAC;YACrD,MAAM,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACzC,CAAC;aAAM,IAAI,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE,CAAC;YAC3C,OAAO,QAAQ,CAAC,MAAmC,CAAC;QACtD,CAAC;QACD,OAAO,IAAI,CAAC,iBAAiB,CAAC,GAAc,CAAC,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { serializeError } from '@metamask/rpc-errors';\nimport { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcFailure,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngine,\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from './JsonRpcEngine';\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 = ((cb: JsonRpcEngineEndCallback) =>\n cb(end)) as JsonRpcEngineNextCallback;\n\n legacyMiddleware(req, res, legacyNext, end);\n });\n propagateToContext(req, context);\n\n // Mimic the behavior of JsonRpcEngine.#handle(), which only treats truthy errors as errors.\n // Legacy middleware may violate the invariant that response objects have either a result or an\n // error property. In practice, we may see response objects with results and `{ error: undefined }`.\n if (hasProperty(response, 'error') && response.error) {\n throw deserializeError(response.error);\n } else if (hasProperty(response, 'result')) {\n return response.result as ResultConstraint<Request>;\n }\n return next(fromLegacyRequest(req as Request));\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcEngineV2.cjs","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,2CAMyB;AACzB,4EAA4C;AAO5C,+DAAwD;AACxD,uCAKiB;AAqGjB,MAAM,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAShD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAa,eAAe;IAY1B,yCAAyC;IACzC,YAAoB,EAAE,UAAU,EAAwC;;QATxE,8CAIE;QAEF,uCAAe,KAAK,EAAC;QAInB,uBAAA,IAAI,+BAAe,CAAC,GAAG,UAAU,CAAC,MAAA,CAAC;IACrC,CAAC;IAED,+FAA+F;IAC/F,6FAA6F;IAC7F,iBAAiB;IACjB;;;;;;;OAOG;IACH,MAAM,CAAC,MAAM,CASX,EAAE,UAAU,EAAgC;QAC5C,6EAA6E;QAC7E,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC5B,MAAM,IAAI,0BAAkB,CAAC,kCAAkC,CAAC,CAAC;QACnE,CAAC;QAID,MAAM,EAAE,GAAG,UAMV,CAAC;QACF,OAAO,IAAI,eAAe,CAA8B;YACtD,UAAU,EAAE,EAAE;SACf,CAE+C,CAAC;IACnD,CAAC;IAqDD,KAAK,CAAC,MAAM,CACV,OAAgB,EAChB,EAAE,OAAO,KAA6B,EAAE;QAExC,MAAM,KAAK,GAAG,IAAA,iBAAS,EAAC,OAAO,CAAC,CAAC;QACjC,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,uBAAA,IAAI,2DAAQ,M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I,MAAM,KAAK,IAAI,EAAE,CAAC;YAClD,IAAA,4BAAU,EAAC,MAAM,CAAC,CAAC;QACrB,CAAC;QACD,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC;IACxB,CAAC;AACH,CAAC,6FAQuB,cAAuB,EAAE,WAAoB;IACnE,IAAI,WAAW,CAAC,OAAO,KAAK,cAAc,CAAC,OAAO,EAAE,CAAC;QACnD,MAAM,IAAI,0BAAkB,CAC1B,2EAA2E,IAAA,iBAAS,EAAC,cAAc,CAAC,EAAE,CACvG,CAAC;IACJ,CAAC;IACD,IACE,IAAA,mBAAW,EAAC,WAAW,EAAE,IAAI,CAAC,KAAK,IAAA,mBAAW,EAAC,cAAc,EAAE,IAAI,CAAC;QACpE,4EAA4E;QAC5E,8CAA8C;QAC9C,WAAW,CAAC,EAAE,KAAK,cAAc,CAAC,EAAE,EACpC,CAAC;QACD,MAAM,IAAI,0BAAkB,CAC1B,sEAAsE,IAAA,iBAAS,EAAC,cAAc,CAAC,EAAE,CAClG,CAAC;IACJ,CAAC;AACH,CAAC;IAkDC,IAAI,uBAAA,IAAI,oCAAa,EAAE,CAAC;QACtB,MAAM,IAAI,0BAAkB,CAAC,qBAAqB,CAAC,CAAC;IACtD,CAAC;AACH,CAAC","sourcesContent":["import {\n type Json,\n type JsonRpcRequest,\n type JsonRpcNotification,\n type NonEmptyArray,\n hasProperty,\n} from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\n\nimport type {\n ContextConstraint,\n InferKeyValues,\n MergeContexts,\n} from './MiddlewareContext';\nimport { MiddlewareContext } from './MiddlewareContext';\nimport {\n isNotification,\n isRequest,\n JsonRpcEngineError,\n stringify,\n} from './utils';\nimport type { JsonRpcCall } from './utils';\n\n// Helper to forbid `id` on notifications\ntype WithoutId<Request extends JsonRpcCall> = Request & { id?: never };\n\n// Helper to enable JsonRpcCall overload of handle()\ntype MixedParam<Request extends JsonRpcCall> = [\n Extract<Request, JsonRpcRequest>,\n] extends [never]\n ? never\n : [Extract<Request, JsonRpcNotification>] extends [never]\n ? never\n :\n | Extract<Request, JsonRpcRequest>\n | WithoutId<Extract<Request, JsonRpcNotification>>;\n\nexport type ResultConstraint<Request extends JsonRpcCall> =\n Request extends JsonRpcRequest ? Json : void;\n\nexport type Next<Request extends JsonRpcCall> = (\n request?: Readonly<Request>,\n) => Promise<Readonly<ResultConstraint<Request>> | undefined>;\n\nexport type MiddlewareParams<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends 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 private constructor({ middleware }: ConstructorOptions<Request, Context>) {\n this.#middleware = [...middleware];\n }\n\n // We use a static factory method in order to construct a supertype of all middleware contexts,\n // which enables us to instantiate an engine despite different middleware expecting different\n // context types.\n /**\n * Create a new JSON-RPC engine.\n *\n * @throws If the middleware array is empty.\n * @param options - The options for the engine.\n * @param options.middleware - The middleware to use.\n * @returns The JSON-RPC engine.\n */\n static create<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n >({ middleware }: { middleware: Middleware[] }) {\n // We can't use NonEmptyArray for the params because it ruins type inference.\n if (middleware.length === 0) {\n throw new JsonRpcEngineError('Middleware array cannot be empty');\n }\n\n type MergedContext = MergedContextOf<Middleware>;\n type InputRequest = RequestOf<Middleware>;\n const mw = middleware as unknown as NonEmptyArray<\n JsonRpcMiddleware<\n InputRequest,\n ResultConstraint<InputRequest>,\n MergedContext\n >\n >;\n return new JsonRpcEngineV2<InputRequest, MergedContext>({\n middleware: mw,\n }) as MergedContext extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<InputRequest, MergedContext>;\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * @param request - The JSON-RPC request to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response.\n */\n async handle(\n request: Extract<Request, JsonRpcRequest> extends never\n ? never\n : Extract<Request, JsonRpcRequest>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcRequest> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC notification. Notifications do not return a result.\n *\n * @param notification - The JSON-RPC notification to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n */\n async handle(\n notification: Extract<Request, JsonRpcNotification> extends never\n ? never\n : WithoutId<Extract<Request, JsonRpcNotification>>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcNotification> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC call, i.e. request or notification. Requests return a\n * result, notifications do not.\n *\n * @param call - The JSON-RPC call to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response, or `undefined` if the call is a notification.\n */\n async handle(\n call: MixedParam<Request>,\n options?: HandleOptions<Context>,\n ): Promise<ResultConstraint<Request> | void>;\n\n async handle(\n request: Request,\n { context }: HandleOptions<Context> = {},\n ): Promise<Readonly<ResultConstraint<Request>> | void> {\n const isReq = isRequest(request);\n const { result } = await this.#handle(request, context);\n\n if (isReq && result === undefined) {\n throw new JsonRpcEngineError(\n `Nothing ended request: ${stringify(request)}`,\n );\n }\n return result;\n }\n\n /**\n * Handle a JSON-RPC request. Throws if a middleware performs an invalid\n * operation. Permits returning an `undefined` result.\n *\n * @param originalRequest - The JSON-RPC request to handle.\n * @param 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 return result === undefined ? await next(finalRequest) : result;\n };\n }\n\n /**\n * Destroy the engine. Calls the `destroy()` method of any middleware that has\n * one. Attempting to use the engine after destroying it will throw an error.\n */\n async destroy(): Promise<void> {\n if (this.#isDestroyed) {\n return;\n }\n this.#isDestroyed = true;\n\n const destructionPromise = Promise.all(\n this.#middleware.map(async (middleware) => {\n if (\n // Intentionally using `in` to walk the prototype chain.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n return middleware.destroy();\n }\n return undefined;\n }),\n );\n this.#middleware = [] as never;\n await destructionPromise;\n }\n\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new JsonRpcEngineError('Engine is destroyed');\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"JsonRpcEngineV2.cjs","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,2CAA8C;AAO9C,4EAA4C;AAO5C,+DAAwD;AACxD,uCAKiB;AAqGjB,MAAM,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAShD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAa,eAAe;IAY1B,yCAAyC;IACzC,YAAoB,EAAE,UAAU,EAAwC;;QATxE,8CAIE;QAEF,uCAAe,KAAK,EAAC;QAInB,uBAAA,IAAI,+BAAe,CAAC,GAAG,UAAU,CAAC,MAAA,CAA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;IAkDC,IAAI,uBAAA,IAAI,oCAAa,EAAE,CAAC;QACtB,MAAM,IAAI,0BAAkB,CAAC,qBAAqB,CAAC,CAAC;IACtD,CAAC;AACH,CAAC","sourcesContent":["import { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcRequest,\n JsonRpcNotification,\n NonEmptyArray,\n} from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\n\nimport type {\n ContextConstraint,\n InferKeyValues,\n MergeContexts,\n} from './MiddlewareContext';\nimport { MiddlewareContext } from './MiddlewareContext';\nimport {\n isNotification,\n isRequest,\n JsonRpcEngineError,\n stringify,\n} from './utils';\nimport type { JsonRpcCall } from './utils';\n\n// Helper to forbid `id` on notifications\ntype WithoutId<Request extends JsonRpcCall> = Request & { id?: never };\n\n// Helper to enable JsonRpcCall overload of handle()\ntype MixedParam<Request extends JsonRpcCall> = [\n Extract<Request, JsonRpcRequest>,\n] extends [never]\n ? never\n : [Extract<Request, JsonRpcNotification>] extends [never]\n ? never\n :\n | Extract<Request, JsonRpcRequest>\n | WithoutId<Extract<Request, JsonRpcNotification>>;\n\nexport type ResultConstraint<Request extends JsonRpcCall> =\n Request extends JsonRpcRequest ? Json : void;\n\nexport type Next<Request extends JsonRpcCall> = (\n request?: Readonly<Request>,\n) => Promise<Readonly<ResultConstraint<Request>> | undefined>;\n\nexport type MiddlewareParams<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends 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 private constructor({ middleware }: ConstructorOptions<Request, Context>) {\n this.#middleware = [...middleware];\n }\n\n // We use a static factory method in order to construct a supertype of all middleware contexts,\n // which enables us to instantiate an engine despite different middleware expecting different\n // context types.\n /**\n * Create a new JSON-RPC engine.\n *\n * @throws If the middleware array is empty.\n * @param options - The options for the engine.\n * @param options.middleware - The middleware to use.\n * @returns The JSON-RPC engine.\n */\n static create<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n >({ middleware }: { middleware: Middleware[] }) {\n // We can't use NonEmptyArray for the params because it ruins type inference.\n if (middleware.length === 0) {\n throw new JsonRpcEngineError('Middleware array cannot be empty');\n }\n\n type MergedContext = MergedContextOf<Middleware>;\n type InputRequest = RequestOf<Middleware>;\n const mw = middleware as unknown as NonEmptyArray<\n JsonRpcMiddleware<\n InputRequest,\n ResultConstraint<InputRequest>,\n MergedContext\n >\n >;\n return new JsonRpcEngineV2<InputRequest, MergedContext>({\n middleware: mw,\n }) as MergedContext extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<InputRequest, MergedContext>;\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * @param request - The JSON-RPC request to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response.\n */\n async handle(\n request: Extract<Request, JsonRpcRequest> extends never\n ? never\n : Extract<Request, JsonRpcRequest>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcRequest> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC notification. Notifications do not return a result.\n *\n * @param notification - The JSON-RPC notification to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n */\n async handle(\n notification: Extract<Request, JsonRpcNotification> extends never\n ? never\n : WithoutId<Extract<Request, JsonRpcNotification>>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcNotification> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC call, i.e. request or notification. Requests return a\n * result, notifications do not.\n *\n * @param call - The JSON-RPC call to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response, or `undefined` if the call is a notification.\n */\n async handle(\n call: MixedParam<Request>,\n options?: HandleOptions<Context>,\n ): Promise<ResultConstraint<Request> | void>;\n\n async handle(\n request: Request,\n { context }: HandleOptions<Context> = {},\n ): Promise<Readonly<ResultConstraint<Request>> | void> {\n const isReq = isRequest(request);\n const { result } = await this.#handle(request, context);\n\n if (isReq && result === undefined) {\n throw new JsonRpcEngineError(\n `Nothing ended request: ${stringify(request)}`,\n );\n }\n return result;\n }\n\n /**\n * Handle a JSON-RPC request. Throws if a middleware performs an invalid\n * operation. Permits returning an `undefined` result.\n *\n * @param originalRequest - The JSON-RPC request to handle.\n * @param 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 return result === undefined ? await next(finalRequest) : result;\n };\n }\n\n /**\n * Destroy the engine. Calls the `destroy()` method of any middleware that has\n * one. Attempting to use the engine after destroying it will throw an error.\n */\n async destroy(): Promise<void> {\n if (this.#isDestroyed) {\n return;\n }\n this.#isDestroyed = true;\n\n const destructionPromise = Promise.all(\n this.#middleware.map(async (middleware) => {\n if (\n // Intentionally using `in` to walk the prototype chain.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n return middleware.destroy();\n }\n return undefined;\n }),\n );\n this.#middleware = [] as never;\n await destructionPromise;\n }\n\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new JsonRpcEngineError('Engine is destroyed');\n }\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Json, JsonRpcRequest, JsonRpcNotification } from "@metamask/utils";
|
|
2
2
|
import type { ContextConstraint, InferKeyValues, MergeContexts } from "./MiddlewareContext.cjs";
|
|
3
3
|
import { MiddlewareContext } from "./MiddlewareContext.cjs";
|
|
4
4
|
import type { JsonRpcCall } from "./utils.cjs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcEngineV2.d.cts","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"JsonRpcEngineV2.d.cts","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,IAAI,EACJ,cAAc,EACd,mBAAmB,EAEpB,wBAAwB;AAGzB,OAAO,KAAK,EACV,iBAAiB,EACjB,cAAc,EACd,aAAa,EACd,gCAA4B;AAC7B,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AAOxD,OAAO,KAAK,EAAE,WAAW,EAAE,oBAAgB;AAG3C,KAAK,SAAS,CAAC,OAAO,SAAS,WAAW,IAAI,OAAO,GAAG;IAAE,EAAE,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AAGvE,KAAK,UAAU,CAAC,OAAO,SAAS,WAAW,IAAI;IAC7C,OAAO,CAAC,OAAO,EAAE,cAAc,CAAC;CACjC,SAAS,CAAC,KAAK,CAAC,GACb,KAAK,GACL,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,GACrD,KAAK,GAED,OAAO,CAAC,OAAO,EAAE,cAAc,CAAC,GAChC,SAAS,CAAC,OAAO,CAA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EAAE,cAAc,CAAC,SAAS,KAAK,GAC1C,KAAK,GACL,gBAAgB,CAAC,OAAO,CAAC,CAC9B;IAED;;;;;;OAMG;IACG,MAAM,CACV,YAAY,EAAE,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,SAAS,KAAK,GAC7D,KAAK,GACL,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC,EACpD,OAAO,CAAC,EAAE,aAAa,CAAC,OAAO,CAAC,GAC/B,OAAO,CACR,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,SAAS,KAAK,GAC/C,KAAK,GACL,gBAAgB,CAAC,OAAO,CAAC,CAC9B;IAED;;;;;;;;OAQG;IACG,MAAM,CACV,IAAI,EAAE,UAAU,CAAC,OAAO,CAAC,EACzB,OAAO,CAAC,EAAE,aAAa,CAAC,OAAO,CAAC,GAC/B,OAAO,CAAC,gBAAgB,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;IA6K5C;;;;OAIG;IACH,YAAY,IAAI,iBAAiB,CAC/B,OAAO,EACP,gBAAgB,CAAC,OAAO,CAAC,EACzB,OAAO,CACR;IAYD;;;OAGG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CA2B/B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Json, JsonRpcRequest, JsonRpcNotification } from "@metamask/utils";
|
|
2
2
|
import type { ContextConstraint, InferKeyValues, MergeContexts } from "./MiddlewareContext.mjs";
|
|
3
3
|
import { MiddlewareContext } from "./MiddlewareContext.mjs";
|
|
4
4
|
import type { JsonRpcCall } from "./utils.mjs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonRpcEngineV2.d.mts","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"JsonRpcEngineV2.d.mts","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"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K,CAAC,MAAM,EAAE,CAAC;QACpD,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;YAClD,UAAU,CAAC,MAAM,CAAC,CAAC;QACrB,CAAC;QACD,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC;IACxB,CAAC;AACH,CAAC,6FAQuB,cAAuB,EAAE,WAAoB;IACnE,IAAI,WAAW,CAAC,OAAO,KAAK,cAAc,CAAC,OAAO,EAAE,CAAC;QACnD,MAAM,IAAI,kBAAkB,CAC1B,2EAA2E,SAAS,CAAC,cAAc,CAAC,EAAE,CACvG,CAAC;IACJ,CAAC;IACD,IACE,WAAW,CAAC,WAAW,EAAE,IAAI,CAAC,KAAK,WAAW,CAAC,cAAc,EAAE,IAAI,CAAC;QACpE,4EAA4E;QAC5E,8CAA8C;QAC9C,WAAW,CAAC,EAAE,KAAK,cAAc,CAAC,EAAE,EACpC,CAAC;QACD,MAAM,IAAI,kBAAkB,CAC1B,sEAAsE,SAAS,CAAC,cAAc,CAAC,EAAE,CAClG,CAAC;IACJ,CAAC;AACH,CAAC;IAkDC,IAAI,uBAAA,IAAI,oCAAa,EAAE,CAAC;QACtB,MAAM,IAAI,kBAAkB,CAAC,qBAAqB,CAAC,CAAC;IACtD,CAAC;AACH,CAAC","sourcesContent":["import {\n type Json,\n type JsonRpcRequest,\n type JsonRpcNotification,\n type NonEmptyArray,\n hasProperty,\n} from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\n\nimport type {\n ContextConstraint,\n InferKeyValues,\n MergeContexts,\n} from './MiddlewareContext';\nimport { MiddlewareContext } from './MiddlewareContext';\nimport {\n isNotification,\n isRequest,\n JsonRpcEngineError,\n stringify,\n} from './utils';\nimport type { JsonRpcCall } from './utils';\n\n// Helper to forbid `id` on notifications\ntype WithoutId<Request extends JsonRpcCall> = Request & { id?: never };\n\n// Helper to enable JsonRpcCall overload of handle()\ntype MixedParam<Request extends JsonRpcCall> = [\n Extract<Request, JsonRpcRequest>,\n] extends [never]\n ? never\n : [Extract<Request, JsonRpcNotification>] extends [never]\n ? never\n :\n | Extract<Request, JsonRpcRequest>\n | WithoutId<Extract<Request, JsonRpcNotification>>;\n\nexport type ResultConstraint<Request extends JsonRpcCall> =\n Request extends JsonRpcRequest ? Json : void;\n\nexport type Next<Request extends JsonRpcCall> = (\n request?: Readonly<Request>,\n) => Promise<Readonly<ResultConstraint<Request>> | undefined>;\n\nexport type MiddlewareParams<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends 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 private constructor({ middleware }: ConstructorOptions<Request, Context>) {\n this.#middleware = [...middleware];\n }\n\n // We use a static factory method in order to construct a supertype of all middleware contexts,\n // which enables us to instantiate an engine despite different middleware expecting different\n // context types.\n /**\n * Create a new JSON-RPC engine.\n *\n * @throws If the middleware array is empty.\n * @param options - The options for the engine.\n * @param options.middleware - The middleware to use.\n * @returns The JSON-RPC engine.\n */\n static create<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n >({ middleware }: { middleware: Middleware[] }) {\n // We can't use NonEmptyArray for the params because it ruins type inference.\n if (middleware.length === 0) {\n throw new JsonRpcEngineError('Middleware array cannot be empty');\n }\n\n type MergedContext = MergedContextOf<Middleware>;\n type InputRequest = RequestOf<Middleware>;\n const mw = middleware as unknown as NonEmptyArray<\n JsonRpcMiddleware<\n InputRequest,\n ResultConstraint<InputRequest>,\n MergedContext\n >\n >;\n return new JsonRpcEngineV2<InputRequest, MergedContext>({\n middleware: mw,\n }) as MergedContext extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<InputRequest, MergedContext>;\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * @param request - The JSON-RPC request to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response.\n */\n async handle(\n request: Extract<Request, JsonRpcRequest> extends never\n ? never\n : Extract<Request, JsonRpcRequest>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcRequest> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC notification. Notifications do not return a result.\n *\n * @param notification - The JSON-RPC notification to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n */\n async handle(\n notification: Extract<Request, JsonRpcNotification> extends never\n ? never\n : WithoutId<Extract<Request, JsonRpcNotification>>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcNotification> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC call, i.e. request or notification. Requests return a\n * result, notifications do not.\n *\n * @param call - The JSON-RPC call to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response, or `undefined` if the call is a notification.\n */\n async handle(\n call: MixedParam<Request>,\n options?: HandleOptions<Context>,\n ): Promise<ResultConstraint<Request> | void>;\n\n async handle(\n request: Request,\n { context }: HandleOptions<Context> = {},\n ): Promise<Readonly<ResultConstraint<Request>> | void> {\n const isReq = isRequest(request);\n const { result } = await this.#handle(request, context);\n\n if (isReq && result === undefined) {\n throw new JsonRpcEngineError(\n `Nothing ended request: ${stringify(request)}`,\n );\n }\n return result;\n }\n\n /**\n * Handle a JSON-RPC request. Throws if a middleware performs an invalid\n * operation. Permits returning an `undefined` result.\n *\n * @param originalRequest - The JSON-RPC request to handle.\n * @param 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 return result === undefined ? await next(finalRequest) : result;\n };\n }\n\n /**\n * Destroy the engine. Calls the `destroy()` method of any middleware that has\n * one. Attempting to use the engine after destroying it will throw an error.\n */\n async destroy(): Promise<void> {\n if (this.#isDestroyed) {\n return;\n }\n this.#isDestroyed = true;\n\n const destructionPromise = Promise.all(\n this.#middleware.map(async (middleware) => {\n if (\n // Intentionally using `in` to walk the prototype chain.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n return middleware.destroy();\n }\n return undefined;\n }),\n );\n this.#middleware = [] as never;\n await destructionPromise;\n }\n\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new JsonRpcEngineError('Engine is destroyed');\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"JsonRpcEngineV2.mjs","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAO9C,OAAO,WAAU,2BAA2B;;AAO5C,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AACxD,OAAO,EACL,cAAc,EACd,SAAS,EACT,kBAAkB,EAClB,SAAS,EACV,oBAAgB;AAqGjB,MAAM,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAShD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,O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AAC,cAAc,CAAC,EAAE,CAClG,CAAC;IACJ,CAAC;AACH,CAAC;IAkDC,IAAI,uBAAA,IAAI,oCAAa,EAAE,CAAC;QACtB,MAAM,IAAI,kBAAkB,CAAC,qBAAqB,CAAC,CAAC;IACtD,CAAC;AACH,CAAC","sourcesContent":["import { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcRequest,\n JsonRpcNotification,\n NonEmptyArray,\n} from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\n\nimport type {\n ContextConstraint,\n InferKeyValues,\n MergeContexts,\n} from './MiddlewareContext';\nimport { MiddlewareContext } from './MiddlewareContext';\nimport {\n isNotification,\n isRequest,\n JsonRpcEngineError,\n stringify,\n} from './utils';\nimport type { JsonRpcCall } from './utils';\n\n// Helper to forbid `id` on notifications\ntype WithoutId<Request extends JsonRpcCall> = Request & { id?: never };\n\n// Helper to enable JsonRpcCall overload of handle()\ntype MixedParam<Request extends JsonRpcCall> = [\n Extract<Request, JsonRpcRequest>,\n] extends [never]\n ? never\n : [Extract<Request, JsonRpcNotification>] extends [never]\n ? never\n :\n | Extract<Request, JsonRpcRequest>\n | WithoutId<Extract<Request, JsonRpcNotification>>;\n\nexport type ResultConstraint<Request extends JsonRpcCall> =\n Request extends JsonRpcRequest ? Json : void;\n\nexport type Next<Request extends JsonRpcCall> = (\n request?: Readonly<Request>,\n) => Promise<Readonly<ResultConstraint<Request>> | undefined>;\n\nexport type MiddlewareParams<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends 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 private constructor({ middleware }: ConstructorOptions<Request, Context>) {\n this.#middleware = [...middleware];\n }\n\n // We use a static factory method in order to construct a supertype of all middleware contexts,\n // which enables us to instantiate an engine despite different middleware expecting different\n // context types.\n /**\n * Create a new JSON-RPC engine.\n *\n * @throws If the middleware array is empty.\n * @param options - The options for the engine.\n * @param options.middleware - The middleware to use.\n * @returns The JSON-RPC engine.\n */\n static create<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n >({ middleware }: { middleware: Middleware[] }) {\n // We can't use NonEmptyArray for the params because it ruins type inference.\n if (middleware.length === 0) {\n throw new JsonRpcEngineError('Middleware array cannot be empty');\n }\n\n type MergedContext = MergedContextOf<Middleware>;\n type InputRequest = RequestOf<Middleware>;\n const mw = middleware as unknown as NonEmptyArray<\n JsonRpcMiddleware<\n InputRequest,\n ResultConstraint<InputRequest>,\n MergedContext\n >\n >;\n return new JsonRpcEngineV2<InputRequest, MergedContext>({\n middleware: mw,\n }) as MergedContext extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<InputRequest, MergedContext>;\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * @param request - The JSON-RPC request to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response.\n */\n async handle(\n request: Extract<Request, JsonRpcRequest> extends never\n ? never\n : Extract<Request, JsonRpcRequest>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcRequest> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC notification. Notifications do not return a result.\n *\n * @param notification - The JSON-RPC notification to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n */\n async handle(\n notification: Extract<Request, JsonRpcNotification> extends never\n ? never\n : WithoutId<Extract<Request, JsonRpcNotification>>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcNotification> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC call, i.e. request or notification. Requests return a\n * result, notifications do not.\n *\n * @param call - The JSON-RPC call to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response, or `undefined` if the call is a notification.\n */\n async handle(\n call: MixedParam<Request>,\n options?: HandleOptions<Context>,\n ): Promise<ResultConstraint<Request> | void>;\n\n async handle(\n request: Request,\n { context }: HandleOptions<Context> = {},\n ): Promise<Readonly<ResultConstraint<Request>> | void> {\n const isReq = isRequest(request);\n const { result } = await this.#handle(request, context);\n\n if (isReq && result === undefined) {\n throw new JsonRpcEngineError(\n `Nothing ended request: ${stringify(request)}`,\n );\n }\n return result;\n }\n\n /**\n * Handle a JSON-RPC request. Throws if a middleware performs an invalid\n * operation. Permits returning an `undefined` result.\n *\n * @param originalRequest - The JSON-RPC request to handle.\n * @param 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 return result === undefined ? await next(finalRequest) : result;\n };\n }\n\n /**\n * Destroy the engine. Calls the `destroy()` method of any middleware that has\n * one. Attempting to use the engine after destroying it will throw an error.\n */\n async destroy(): Promise<void> {\n if (this.#isDestroyed) {\n return;\n }\n this.#isDestroyed = true;\n\n const destructionPromise = Promise.all(\n this.#middleware.map(async (middleware) => {\n if (\n // Intentionally using `in` to walk the prototype chain.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n return middleware.destroy();\n }\n return undefined;\n }),\n );\n this.#middleware = [] as never;\n await destructionPromise;\n }\n\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new JsonRpcEngineError('Engine is destroyed');\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MiddlewareContext.cjs","sourceRoot":"","sources":["../../src/v2/MiddlewareContext.ts"],"names":[],"mappings":";;;;AAAA,
|
|
1
|
+
{"version":3,"file":"MiddlewareContext.cjs","sourceRoot":"","sources":["../../src/v2/MiddlewareContext.ts"],"names":[],"mappings":";;;;AAAA,uCAAqC;AAGrC,MAAM,uBAAuB,GAAG,MAAM,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;AAEhF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAa,iBAEX,SAAQ,GAAgD;IAGxD;;;;;;OAMG;IACH,MAAM,CAAC,UAAU,CAAC,KAAc;QAC9B,OAAO,IAAA,kBAAU,EAAC,KAAK,EAAE,uBAAuB,CAAC,CAAC;IACpD,CAAC;IAED,YACE,OAEa;QAEb,KAAK,CACH,OAAO,IAAI,UAAU,CAAC,OAAO,CAAC;YAC5B,CAAC,CAAC,OAAO;YACT,CAAC,CAAC,oBAAoB,CAAC,OAAO,IAAI,EAAE,CAAC,CACxC,CAAC;QAtBa,QAAyB,GAAG,IAAI,CAAC;QAuBhD,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACtB,CAAC;IAED,GAAG,CAA4B,GAAM;QACnC,OAAO,KAAK,CAAC,GAAG,CAAC,GAAG,CAA6B,CAAC;IACpD,CAAC;IAED;;;;;OAKG;IACH,SAAS,CAA4B,GAAM;QACzC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,gBAAgB,MAAM,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QAC5D,CAAC;QACD,OAAO,KAAK,CAAC,GAAG,CAAC,GAAG,CAAiB,CAAC;IACxC,CAAC;IAED;;;;;;;;OAQG;IACH,GAAG,CAA4B,GAAM,EAAE,KAAmB;QACxD,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,0BAA0B,MAAM,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;QAC3E,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA9DD,8CA8DC;KA3DmB,uBAAuB;AA6D3C;;;;;GAKG;AACH,SAAS,UAAU,CACjB,KAAuD;IAEvD,OAAO,MAAM,CAAC,QAAQ,IAAI,KAAK,CAAC;AAClC,CAAC;AAED;;;;;;GAMG;AACH,SAAS,oBAAoB,CAC3B,SAAoB;IAEpB,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,GAAoB,EAAE,EAAE,CAAC;QAC9D,GAAG;QACH,SAAS,CAAC,GAAG,CAAC;KACf,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { isInstance } from './utils';\nimport type { UnionToIntersection } from './utils';\n\nconst MiddlewareContextSymbol = Symbol.for('json-rpc-engine#MiddlewareContext');\n\n/**\n * An context object for middleware that attempts to protect against accidental\n * modifications. Its interface is frozen.\n *\n * Map keys may not be directly overridden with {@link set}. Instead, use\n * {@link delete} to remove a key and then {@link set} to add a new value.\n *\n * The override protections are circumvented when using e.g. `Reflect.set`, so\n * don't do that.\n *\n * @template KeyValues - The type of the keys and values in the context.\n * @example\n * // By default, the context permits any PropertyKey as a key.\n * const context = new MiddlewareContext();\n * context.set('foo', 'bar');\n * context.get('foo'); // 'bar'\n * context.get('fizz'); // undefined\n * @example\n * // By specifying an object type, the context permits only the keys of the object.\n * type Context = MiddlewareContext<{ foo: string }>;\n * const context = new Context([['foo', 'bar']]);\n * context.get('foo'); // 'bar'\n * context.get('fizz'); // Type error\n */\nexport class MiddlewareContext<\n KeyValues extends Record<PropertyKey, unknown> = Record<PropertyKey, unknown>,\n> extends Map<keyof KeyValues, KeyValues[keyof KeyValues]> {\n private readonly [MiddlewareContextSymbol] = true;\n\n /**\n * Check if a value is a {@link MiddlewareContext} instance.\n * Works across different package versions in the same realm.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link MiddlewareContext} instance.\n */\n static isInstance(value: unknown): value is MiddlewareContext {\n return isInstance(value, MiddlewareContextSymbol);\n }\n\n constructor(\n entries?:\n | Iterable<readonly [keyof KeyValues, KeyValues[keyof KeyValues]]>\n | KeyValues,\n ) {\n super(\n entries && isIterable(entries)\n ? entries\n : entriesFromKeyValues(entries ?? {}),\n );\n Object.freeze(this);\n }\n\n get<K extends keyof KeyValues>(key: K): KeyValues[K] | undefined {\n return super.get(key) as KeyValues[K] | undefined;\n }\n\n /**\n * Get a value from the context. Throws if the key is not found.\n *\n * @param key - The key to get the value for.\n * @returns The value.\n */\n assertGet<K extends keyof KeyValues>(key: K): KeyValues[K] {\n if (!super.has(key)) {\n throw new Error(`Context key \"${String(key)}\" not found`);\n }\n return super.get(key) as KeyValues[K];\n }\n\n /**\n * Set a value in the context. Throws if the key already exists.\n * {@link delete} an existing key before setting it to a new value.\n *\n * @throws If the key already exists.\n * @param key - The key to set the value for.\n * @param value - The value to set.\n * @returns The context.\n */\n set<K extends keyof KeyValues>(key: K, value: KeyValues[K]): this {\n if (super.has(key)) {\n throw new Error(`MiddlewareContext key \"${String(key)}\" already exists`);\n }\n super.set(key, value);\n return this;\n }\n}\n\n/**\n * {@link Iterable} type guard.\n *\n * @param value - The value to check.\n * @returns Whether the value is an {@link Iterable}.\n */\nfunction isIterable(\n value: Iterable<unknown> | Record<PropertyKey, unknown>,\n): value is Iterable<unknown> {\n return Symbol.iterator in value;\n}\n\n/**\n * Like Object.entries(), but includes symbol-keyed properties.\n *\n * @template KeyValues - The type of the keys and values in the object.\n * @param keyValues - The object to convert.\n * @returns The array of entries, including symbol-keyed properties.\n */\nfunction entriesFromKeyValues<KeyValues extends Record<PropertyKey, unknown>>(\n keyValues: KeyValues,\n): [keyof KeyValues, KeyValues[keyof KeyValues]][] {\n return Reflect.ownKeys(keyValues).map((key: keyof KeyValues) => [\n key,\n keyValues[key],\n ]);\n}\n\n/**\n * Infer the KeyValues type from a {@link MiddlewareContext}.\n */\nexport type InferKeyValues<T> =\n T extends MiddlewareContext<infer U> ? U : never;\n\n/**\n * Simplifies an object type by \"merging\" its properties.\n *\n * - Expands intersections into a single object type.\n * - Forces mapped/conditional results to resolve into a readable shape.\n * - No runtime effect; purely a type-level normalization.\n *\n * @example\n * type A = { a: string } & { b: number };\n * type B = Simplify<A>; // { a: string; b: number }\n */\ntype Simplify<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;\n\n/**\n * Rejects record types that contain any `never`-valued property.\n *\n * If any property of `T` resolves to `never`, the result is `never`; otherwise it returns `T` unchanged.\n * Useful as a guard to ensure computed/merged record types didn't collapse any fields to `never`.\n *\n * @example\n * type A = ExcludeNever<{ a: string; b: never }>; // never\n * type B = ExcludeNever<{ a: string; b: number }>; // { a: string; b: number }\n */\ntype ExcludeNever<T extends Record<PropertyKey, unknown>> = {\n [K in keyof T]-?: [T[K]] extends [never] ? K : never;\n}[keyof T] extends never\n ? T\n : never;\n\n/**\n * Merge a union of {@link MiddlewareContext}s into a single {@link MiddlewareContext}\n * supertype.\n *\n * @param Contexts - The union of {@link MiddlewareContext}s to merge.\n * @returns The merged {@link MiddlewareContext} supertype.\n * @example\n * type A = MiddlewareContext<{ a: string }> | MiddlewareContext<{ b: number }>;\n * type B = MergeContexts<A>; // MiddlewareContext<{ a: string, b: number }>\n */\nexport type MergeContexts<Contexts extends ContextConstraint> =\n ExcludeNever<\n Simplify<UnionToIntersection<InferKeyValues<Contexts>>>\n > extends never\n ? never\n : MiddlewareContext<\n ExcludeNever<Simplify<UnionToIntersection<InferKeyValues<Contexts>>>>\n >;\n\n/**\n * A constraint for {@link MiddlewareContext} generic parameters.\n */\n// Non-polluting `any` constraint.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ContextConstraint = MiddlewareContext<any>;\n\n/**\n * The empty context type, i.e. `MiddlewareContext<{}>`.\n */\n// The empty object type is literally an empty object in this context.\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport type EmptyContext = MiddlewareContext<{}>;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MiddlewareContext.d.cts","sourceRoot":"","sources":["../../src/v2/MiddlewareContext.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"MiddlewareContext.d.cts","sourceRoot":"","sources":["../../src/v2/MiddlewareContext.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,oBAAgB;AAEnD,QAAA,MAAM,uBAAuB,eAAkD,CAAC;AAEhF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,iBAAiB,CAC5B,SAAS,SAAS,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,CAC7E,SAAQ,GAAG,CAAC,MAAM,SAAS,EAAE,SAAS,CAAC,MAAM,SAAS,CAAC,CAAC;IACxD,OAAO,CAAC,QAAQ,CAAC,CAAC,uBAAuB,CAAC,CAAQ;IAElD;;;;;;OAMG;IACH,MAAM,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,iBAAiB;gBAK3D,OAAO,CAAC,EACJ,QAAQ,CAAC,SAAS,CAAC,MAAM,SAAS,EAAE,SAAS,CAAC,MAAM,SAAS,CAAC,CAAC,CAAC,GAChE,SAAS;IAUf,GAAG,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,GAAG,SAAS;IAIh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AC;AAEvD;;GAEG;AAGH,MAAM,MAAM,YAAY,GAAG,iBAAiB,CAAC,EAAE,CAAC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MiddlewareContext.d.mts","sourceRoot":"","sources":["../../src/v2/MiddlewareContext.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"MiddlewareContext.d.mts","sourceRoot":"","sources":["../../src/v2/MiddlewareContext.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,oBAAgB;AAEnD,QAAA,MAAM,uBAAuB,eAAkD,CAAC;AAEhF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,iBAAiB,CAC5B,SAAS,SAAS,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,CAC7E,SAAQ,GAAG,CAAC,MAAM,SAAS,EAAE,SAAS,CAAC,MAAM,SAAS,CAAC,CAAC;IACxD,OAAO,CAAC,QAAQ,CAAC,CAAC,uBAAuB,CAAC,CAAQ;IAElD;;;;;;OAMG;IACH,MAAM,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,iBAAiB;gBAK3D,OAAO,CAAC,EACJ,QAAQ,CAAC,SAAS,CAAC,MAAM,SAAS,EAAE,SAAS,CAAC,MAAM,SAAS,CAAC,CAAC,CAAC,GAChE,SAAS;IAUf,GAAG,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,GAAG,SAAS;IAIhE;;;;;OAKG;IACH,SAAS,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC;IAO1D;;;;;;;;OAQG;IACH,GAAG,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,CAAC,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ACD,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;CACF;KA3DmB,uBAAuB;AA6D3C;;;;;GAKG;AACH,SAAS,UAAU,CACjB,KAAuD;IAEvD,OAAO,MAAM,CAAC,QAAQ,IAAI,KAAK,CAAC;AAClC,CAAC;AAED;;;;;;GAMG;AACH,SAAS,oBAAoB,CAC3B,SAAoB;IAEpB,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,GAAoB,EAAE,EAAE,CAAC;QAC9D,GAAG;QACH,SAAS,CAAC,GAAG,CAAC;KACf,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { isInstance } from './utils';\nimport type { UnionToIntersection } from './utils';\n\nconst MiddlewareContextSymbol = Symbol.for('json-rpc-engine#MiddlewareContext');\n\n/**\n * An context object for middleware that attempts to protect against accidental\n * modifications. Its interface is frozen.\n *\n * Map keys may not be directly overridden with {@link set}. Instead, use\n * {@link delete} to remove a key and then {@link set} to add a new value.\n *\n * The override protections are circumvented when using e.g. `Reflect.set`, so\n * don't do that.\n *\n * @template KeyValues - The type of the keys and values in the context.\n * @example\n * // By default, the context permits any PropertyKey as a key.\n * const context = new MiddlewareContext();\n * context.set('foo', 'bar');\n * context.get('foo'); // 'bar'\n * context.get('fizz'); // undefined\n * @example\n * // By specifying an object type, the context permits only the keys of the object.\n * type Context = MiddlewareContext<{ foo: string }>;\n * const context = new Context([['foo', 'bar']]);\n * context.get('foo'); // 'bar'\n * context.get('fizz'); // Type error\n */\nexport class MiddlewareContext<\n KeyValues extends Record<PropertyKey, unknown> = Record<PropertyKey, unknown>,\n> extends Map<keyof KeyValues, KeyValues[keyof KeyValues]> {\n private readonly [MiddlewareContextSymbol] = true;\n\n /**\n * Check if a value is a {@link MiddlewareContext} instance.\n * Works across different package versions in the same realm.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link MiddlewareContext} instance.\n */\n static isInstance(value: unknown): value is MiddlewareContext {\n return isInstance(value, MiddlewareContextSymbol);\n }\n\n constructor(\n entries?:\n | Iterable<readonly [keyof KeyValues, KeyValues[keyof KeyValues]]>\n | KeyValues,\n ) {\n super(\n entries && isIterable(entries)\n ? entries\n : entriesFromKeyValues(entries ?? {}),\n );\n Object.freeze(this);\n }\n\n get<K extends keyof KeyValues>(key: K): KeyValues[K] | undefined {\n return super.get(key) as KeyValues[K] | undefined;\n }\n\n /**\n * Get a value from the context. Throws if the key is not found.\n *\n * @param key - The key to get the value for.\n * @returns The value.\n */\n assertGet<K extends keyof KeyValues>(key: K): KeyValues[K] {\n if (!super.has(key)) {\n throw new Error(`Context key \"${String(key)}\" not found`);\n }\n return super.get(key) as KeyValues[K];\n }\n\n /**\n * Set a value in the context. Throws if the key already exists.\n * {@link delete} an existing key before setting it to a new value.\n *\n * @throws If the key already exists.\n * @param key - The key to set the value for.\n * @param value - The value to set.\n * @returns The context.\n */\n set<K extends keyof KeyValues>(key: K, value: KeyValues[K]): this {\n if (super.has(key)) {\n throw new Error(`MiddlewareContext key \"${String(key)}\" already exists`);\n }\n super.set(key, value);\n return this;\n }\n}\n\n/**\n * {@link Iterable} type guard.\n *\n * @param value - The value to check.\n * @returns Whether the value is an {@link Iterable}.\n */\nfunction isIterable(\n value: Iterable<unknown> | Record<PropertyKey, unknown>,\n): value is Iterable<unknown> {\n return Symbol.iterator in value;\n}\n\n/**\n * Like Object.entries(), but includes symbol-keyed properties.\n *\n * @template KeyValues - The type of the keys and values in the object.\n * @param keyValues - The object to convert.\n * @returns The array of entries, including symbol-keyed properties.\n */\nfunction entriesFromKeyValues<KeyValues extends Record<PropertyKey, unknown>>(\n keyValues: KeyValues,\n): [keyof KeyValues, KeyValues[keyof KeyValues]][] {\n return Reflect.ownKeys(keyValues).map((key: keyof KeyValues) => [\n key,\n keyValues[key],\n ]);\n}\n\n/**\n * Infer the KeyValues type from a {@link MiddlewareContext}.\n */\nexport type InferKeyValues<T> =\n T extends MiddlewareContext<infer U> ? U : never;\n\n/**\n * Simplifies an object type by \"merging\" its properties.\n *\n * - Expands intersections into a single object type.\n * - Forces mapped/conditional results to resolve into a readable shape.\n * - No runtime effect; purely a type-level normalization.\n *\n * @example\n * type A = { a: string } & { b: number };\n * type B = Simplify<A>; // { a: string; b: number }\n */\ntype Simplify<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;\n\n/**\n * Rejects record types that contain any `never`-valued property.\n *\n * If any property of `T` resolves to `never`, the result is `never`; otherwise it returns `T` unchanged.\n * Useful as a guard to ensure computed/merged record types didn't collapse any fields to `never`.\n *\n * @example\n * type A = ExcludeNever<{ a: string; b: never }>; // never\n * type B = ExcludeNever<{ a: string; b: number }>; // { a: string; b: number }\n */\ntype ExcludeNever<T extends Record<PropertyKey, unknown>> = {\n [K in keyof T]-?: [T[K]] extends [never] ? K : never;\n}[keyof T] extends never\n ? T\n : never;\n\n/**\n * Merge a union of {@link MiddlewareContext}s into a single {@link MiddlewareContext}\n * supertype.\n *\n * @param Contexts - The union of {@link MiddlewareContext}s to merge.\n * @returns The merged {@link MiddlewareContext} supertype.\n * @example\n * type A = MiddlewareContext<{ a: string }> | MiddlewareContext<{ b: number }>;\n * type B = MergeContexts<A>; // MiddlewareContext<{ a: string, b: number }>\n */\nexport type MergeContexts<Contexts extends ContextConstraint> =\n ExcludeNever<\n Simplify<UnionToIntersection<InferKeyValues<Contexts>>>\n > extends never\n ? never\n : MiddlewareContext<\n ExcludeNever<Simplify<UnionToIntersection<InferKeyValues<Contexts>>>>\n >;\n\n/**\n * A constraint for {@link MiddlewareContext} generic parameters.\n */\n// Non-polluting `any` constraint.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ContextConstraint = MiddlewareContext<any>;\n\n/**\n * The empty context type, i.e. `MiddlewareContext<{}>`.\n */\n// The empty object type is literally an empty object in this context.\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport type EmptyContext = MiddlewareContext<{}>;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compatibility-utils.cjs","sourceRoot":"","sources":["../../src/v2/compatibility-utils.ts"],"names":[],"mappings":";;;AAAA,qDAAwE;AAExE,2CAAwD;AACxD,sFAAsF;AACtF,iCAA8B;AAE9B,+DAAwD;AACxD,
|
|
1
|
+
{"version":3,"file":"compatibility-utils.cjs","sourceRoot":"","sources":["../../src/v2/compatibility-utils.ts"],"names":[],"mappings":";;;AAAA,qDAAwE;AAExE,2CAAwD;AACxD,sFAAsF;AACtF,iCAA8B;AAE9B,+DAAwD;AACxD,uCAAoC;AAGpC,oCAAoC;AAEpC;;;;;;;;;;GAUG;AACI,MAAM,SAAS,GAAG,CAAI,KAAQ,EAAiB,EAAE,CACtD,IAAA,aAAK,EAAC,KAAK,CAAkB,CAAC;AADnB,QAAA,SAAS,aACU;AAWhC;;GAEG;AACU,QAAA,YAAY,GAAG,CAAC,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC;AAElE;;;;;;GAMG;AACH,SAAgB,iBAAiB,CAC/B,GAAY;IAEZ,MAAM,OAAO,GAAG;QACd,OAAO,EAAE,KAAc;QACvB,MAAM,EAAE,GAAG,CAAC,MAAM;KACC,CAAC;IACtB,OAAO,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,CAAC;IACpB,IAAI,IAAA,mBAAW,EAAC,GAAG,EAAE,QAAQ,CAAC,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;QAC3D,OAAO,CAAC,MAAM,GAAG,IAAA,iBAAS,EAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,OAAkB,CAAC;AAC5B,CAAC;AAZD,8CAYC;AAED;;;;;;GAMG;AACH,SAAgB,WAAW,CACzB,GAAY;IAEZ,MAAM,OAAO,GAAG,IAAI,qCAAiB,EAAE,CAAC;IACxC,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACjC,O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C;QAC9B,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;IACtB,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AA/CD,4CA+CC","sourcesContent":["import { getMessageFromCode, JsonRpcError } from '@metamask/rpc-errors';\nimport type { Json } from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n// ATTN: We must NOT use 'klona/full' here because it freezes properties on the clone.\nimport { klona } from 'klona';\n\nimport { MiddlewareContext } from './MiddlewareContext';\nimport { stringify } from './utils';\nimport type { JsonRpcRequest } from './utils';\n\n// Legacy engine compatibility utils\n\n/**\n * Create a deep clone of a value as follows:\n * - Assumes acyclical objects\n * - Does not copy property descriptors (i.e. uses mutable defaults)\n * - Ignores non-enumerable properties\n * - Ignores getters and setters\n *\n * @throws If the value is an object with a circular reference.\n * @param value - The value to clone.\n * @returns The cloned value.\n */\nexport const deepClone = <T>(value: T): DeepCloned<T> =>\n klona(value) as DeepCloned<T>;\n\n// Matching the default implementation of klona, this type:\n// - Removes readonly modifiers\n// - Excludes non-enumerable / symbol properties\ntype DeepCloned<T> = T extends readonly (infer U)[]\n ? DeepCloned<U>[]\n : T extends object\n ? { -readonly [K in keyof T & (string | number)]: DeepCloned<T[K]> }\n : T;\n\n/**\n * Standard JSON-RPC request properties.\n */\nexport const requestProps = ['jsonrpc', 'method', 'params', 'id'];\n\n/**\n * Make a JSON-RPC request from a legacy request. Clones the params to avoid\n * freezing them, which could cause errors in an involved legacy engine.\n *\n * @param req - The legacy request to make a request from.\n * @returns The JSON-RPC request.\n */\nexport function fromLegacyRequest<Request extends JsonRpcRequest>(\n req: Request,\n): Request {\n const request = {\n jsonrpc: '2.0' as const,\n method: req.method,\n } as Partial<Request>;\n request.id = req.id;\n if (hasProperty(req, 'params') && req.params !== undefined) {\n request.params = deepClone(req.params);\n }\n return request as Request;\n}\n\n/**\n * Make a middleware context from a legacy request by copying over all non-JSON-RPC\n * properties from the request to the context object.\n *\n * @param req - The legacy request to make a context from.\n * @returns The middleware context.\n */\nexport function makeContext<Request extends Record<string | symbol, unknown>>(\n req: Request,\n): MiddlewareContext {\n const context = new MiddlewareContext();\n propagateToContext(req, context);\n return context;\n}\n\n/**\n * Copies non-JSON-RPC string properties from the request to the context.\n *\n * For compatibility with our problematic practice of appending non-standard\n * fields to requests for inter-middleware communication in the legacy engine.\n *\n * **ATTN:** Only string properties that do not already exist in the context\n * are copied.\n *\n * @param req - The request to propagate the context from.\n * @param context - The context to propagate to.\n */\nexport function propagateToContext(\n req: Record<string, unknown>,\n context: MiddlewareContext<Record<string, unknown>>,\n) {\n Object.keys(req)\n .filter(\n (key) =>\n typeof key === 'string' &&\n !requestProps.includes(key) &&\n !context.has(key),\n )\n .forEach((key) => {\n context.set(key, req[key]);\n });\n}\n\n/**\n * Copies non-JSON-RPC string properties from the context to the request.\n *\n * For compatibility with our problematic practice of appending non-standard\n * fields to requests for inter-middleware communication in the legacy engine.\n *\n * **ATTN:** Only string properties are copied.\n *\n * @param req - The request to propagate the context to.\n * @param context - The context to propagate from.\n */\nexport function propagateToRequest(\n req: Record<string, unknown>,\n context: MiddlewareContext,\n) {\n Array.from(context.keys())\n .filter(\n ((key) => typeof key === 'string' && !requestProps.includes(key)) as (\n value: unknown,\n ) => value is string,\n )\n .forEach((key) => {\n req[key] = context.get(key);\n });\n}\n\n/**\n * Unserialize an error from a thrown value. Creates a {@link JsonRpcError} if\n * the thrown value is an object with a `code` property. Otherwise, creates a\n * plain {@link Error}.\n *\n * @param thrown - The thrown value to unserialize.\n * @returns The unserialized error.\n */\nexport function deserializeError(thrown: unknown): Error | JsonRpcError<Json> {\n // @ts-expect-error - New, but preferred if available.\n // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/isError\n if (typeof Error.isError === 'function' && Error.isError(thrown)) {\n return thrown as Error;\n }\n // Unlike Error.isError, instanceof does not work for Errors from other realms.\n if (thrown instanceof Error) {\n return thrown;\n }\n if (typeof thrown === 'string') {\n return new Error(thrown);\n }\n if (!isObject(thrown)) {\n return new Error(`Unknown error: ${stringify(thrown)}`);\n }\n\n const code =\n typeof thrown.code === 'number' && Number.isInteger(thrown.code)\n ? thrown.code\n : undefined;\n\n let message = 'Unknown error';\n if (typeof thrown.message === 'string') {\n message = thrown.message;\n } else if (typeof code === 'number') {\n message = getMessageFromCode(code, message);\n }\n\n const { stack, cause, data } = thrown;\n\n const error =\n code === undefined\n ? // Jest complains if we use the `@ts-expect-error` directive here.\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Our error type is outdated.\n new Error(message, { cause })\n : new JsonRpcError(code, message, {\n ...(isObject(data) ? data : undefined),\n cause,\n });\n\n if (typeof stack === 'string') {\n error.stack = stack;\n }\n\n return error;\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { JsonRpcError } from "@metamask/rpc-errors";
|
|
2
2
|
import type { Json } from "@metamask/utils";
|
|
3
3
|
import { MiddlewareContext } from "./MiddlewareContext.cjs";
|
|
4
|
-
import {
|
|
4
|
+
import type { JsonRpcRequest } from "./utils.cjs";
|
|
5
5
|
/**
|
|
6
6
|
* Create a deep clone of a value as follows:
|
|
7
7
|
* - Assumes acyclical objects
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compatibility-utils.d.cts","sourceRoot":"","sources":["../../src/v2/compatibility-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,YAAY,EAAE,6BAA6B;AACxE,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAK5C,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;
|
|
1
|
+
{"version":3,"file":"compatibility-utils.d.cts","sourceRoot":"","sources":["../../src/v2/compatibility-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,YAAY,EAAE,6BAA6B;AACxE,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAK5C,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AAExD,OAAO,KAAK,EAAE,cA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Context } from "./MiddlewareContext.mjs";
|
|
4
|
-
import {
|
|
4
|
+
import type { JsonRpcRequest } from "./utils.mjs";
|
|
5
5
|
/**
|
|
6
6
|
* Create a deep clone of a value as follows:
|
|
7
7
|
* - Assumes acyclical objects
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compatibility-utils.d.mts","sourceRoot":"","sources":["../../src/v2/compatibility-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,YAAY,EAAE,6BAA6B;AACxE,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAK5C,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;
|
|
1
|
+
{"version":3,"file":"compatibility-utils.d.mts","sourceRoot":"","sources":["../../src/v2/compatibility-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,YAAY,EAAE,6BAA6B;AACxE,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAK5C,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AAExD,OAAO,KAAK,EAAE,cAAc,EAAE,oBAAgB;AAI9C;;;;;;;;;;GAUG;AACH,eAAO,MAAM,SAAS,gCACS,CAAC;AAKhC,KAAK,UAAU,CAAC,CAAC,IAAI,CAAC,SAAS,SAAS,CAAC,MAAM,CAAC,CAAC,EAAE,GAC/C,UAAU,CAAC,CAAC,CAAC,EAAE,GACf,CAAC,SAAS,MAAM,GACd;IAAE,CAAC,UAAU,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,GAClE,CAAC,CAAC;AAER;;GAEG;AACH,eAAO,MAAM,YAAY,UAAwC,CAAC;AAElE;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,SAAS,cAAc,EAC9D,GAAG,EAAE,OAAO,GACX,OAAO,CAUT;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,OAAO,SAAS,MAAM,CAAC,MAAM,GAAG,MAAM,EAAE,OAAO,CAAC,EAC1E,GAAG,EAAE,OAAO,GACX,iBAAiB,CAInB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,OAAO,EAAE,iBAAiB,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,QAYpD;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,OAAO,EAAE,iBAAiB,QAW3B;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,OAAO,GAAG,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC,CA+C5E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compatibility-utils.mjs","sourceRoot":"","sources":["../../src/v2/compatibility-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,6BAA6B;AAExE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,wBAAwB;AACxD,sFAAsF;AACtF,OAAO,EAAE,KAAK,EAAE,cAAc;AAE9B,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AACxD,OAAO,EAAE,SAAS,
|
|
1
|
+
{"version":3,"file":"compatibility-utils.mjs","sourceRoot":"","sources":["../../src/v2/compatibility-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,6BAA6B;AAExE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,wBAAwB;AACxD,sFAAsF;AACtF,OAAO,EAAE,KAAK,EAAE,cAAc;AAE9B,OAAO,EAAE,iBAAiB,EAAE,gCAA4B;AACxD,OAAO,EAAE,SAAS,EAAE,oBAAgB;AAGpC,oCAAoC;AAEpC;;;;;;;;;;GAUG;AACH,MAAM,CAA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,GAAG,eAAe,CAAC;IAC9B,IAAI,OAAO,MAAM,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;QACvC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;IAC3B,CAAC;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QACpC,OAAO,GAAG,kBAAkB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAC9C,CAAC;IAED,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;IAEtC,MAAM,KAAK,GACT,IAAI,KAAK,SAAS;QAChB,CAAC,CAAC,kEAAkE;YAClE,6DAA6D;YAC7D,2CAA2C;YAC3C,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC;QAC/B,CAAC,CAAC,IAAI,YAAY,CAAC,IAAI,EAAE,OAAO,EAAE;YAC9B,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;YACtC,KAAK;SACN,CAAC,CAAC;IAET,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;IACtB,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { getMessageFromCode, JsonRpcError } from '@metamask/rpc-errors';\nimport type { Json } from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n// ATTN: We must NOT use 'klona/full' here because it freezes properties on the clone.\nimport { klona } from 'klona';\n\nimport { MiddlewareContext } from './MiddlewareContext';\nimport { stringify } from './utils';\nimport type { JsonRpcRequest } from './utils';\n\n// Legacy engine compatibility utils\n\n/**\n * Create a deep clone of a value as follows:\n * - Assumes acyclical objects\n * - Does not copy property descriptors (i.e. uses mutable defaults)\n * - Ignores non-enumerable properties\n * - Ignores getters and setters\n *\n * @throws If the value is an object with a circular reference.\n * @param value - The value to clone.\n * @returns The cloned value.\n */\nexport const deepClone = <T>(value: T): DeepCloned<T> =>\n klona(value) as DeepCloned<T>;\n\n// Matching the default implementation of klona, this type:\n// - Removes readonly modifiers\n// - Excludes non-enumerable / symbol properties\ntype DeepCloned<T> = T extends readonly (infer U)[]\n ? DeepCloned<U>[]\n : T extends object\n ? { -readonly [K in keyof T & (string | number)]: DeepCloned<T[K]> }\n : T;\n\n/**\n * Standard JSON-RPC request properties.\n */\nexport const requestProps = ['jsonrpc', 'method', 'params', 'id'];\n\n/**\n * Make a JSON-RPC request from a legacy request. Clones the params to avoid\n * freezing them, which could cause errors in an involved legacy engine.\n *\n * @param req - The legacy request to make a request from.\n * @returns The JSON-RPC request.\n */\nexport function fromLegacyRequest<Request extends JsonRpcRequest>(\n req: Request,\n): Request {\n const request = {\n jsonrpc: '2.0' as const,\n method: req.method,\n } as Partial<Request>;\n request.id = req.id;\n if (hasProperty(req, 'params') && req.params !== undefined) {\n request.params = deepClone(req.params);\n }\n return request as Request;\n}\n\n/**\n * Make a middleware context from a legacy request by copying over all non-JSON-RPC\n * properties from the request to the context object.\n *\n * @param req - The legacy request to make a context from.\n * @returns The middleware context.\n */\nexport function makeContext<Request extends Record<string | symbol, unknown>>(\n req: Request,\n): MiddlewareContext {\n const context = new MiddlewareContext();\n propagateToContext(req, context);\n return context;\n}\n\n/**\n * Copies non-JSON-RPC string properties from the request to the context.\n *\n * For compatibility with our problematic practice of appending non-standard\n * fields to requests for inter-middleware communication in the legacy engine.\n *\n * **ATTN:** Only string properties that do not already exist in the context\n * are copied.\n *\n * @param req - The request to propagate the context from.\n * @param context - The context to propagate to.\n */\nexport function propagateToContext(\n req: Record<string, unknown>,\n context: MiddlewareContext<Record<string, unknown>>,\n) {\n Object.keys(req)\n .filter(\n (key) =>\n typeof key === 'string' &&\n !requestProps.includes(key) &&\n !context.has(key),\n )\n .forEach((key) => {\n context.set(key, req[key]);\n });\n}\n\n/**\n * Copies non-JSON-RPC string properties from the context to the request.\n *\n * For compatibility with our problematic practice of appending non-standard\n * fields to requests for inter-middleware communication in the legacy engine.\n *\n * **ATTN:** Only string properties are copied.\n *\n * @param req - The request to propagate the context to.\n * @param context - The context to propagate from.\n */\nexport function propagateToRequest(\n req: Record<string, unknown>,\n context: MiddlewareContext,\n) {\n Array.from(context.keys())\n .filter(\n ((key) => typeof key === 'string' && !requestProps.includes(key)) as (\n value: unknown,\n ) => value is string,\n )\n .forEach((key) => {\n req[key] = context.get(key);\n });\n}\n\n/**\n * Unserialize an error from a thrown value. Creates a {@link JsonRpcError} if\n * the thrown value is an object with a `code` property. Otherwise, creates a\n * plain {@link Error}.\n *\n * @param thrown - The thrown value to unserialize.\n * @returns The unserialized error.\n */\nexport function deserializeError(thrown: unknown): Error | JsonRpcError<Json> {\n // @ts-expect-error - New, but preferred if available.\n // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/isError\n if (typeof Error.isError === 'function' && Error.isError(thrown)) {\n return thrown as Error;\n }\n // Unlike Error.isError, instanceof does not work for Errors from other realms.\n if (thrown instanceof Error) {\n return thrown;\n }\n if (typeof thrown === 'string') {\n return new Error(thrown);\n }\n if (!isObject(thrown)) {\n return new Error(`Unknown error: ${stringify(thrown)}`);\n }\n\n const code =\n typeof thrown.code === 'number' && Number.isInteger(thrown.code)\n ? thrown.code\n : undefined;\n\n let message = 'Unknown error';\n if (typeof thrown.message === 'string') {\n message = thrown.message;\n } else if (typeof code === 'number') {\n message = getMessageFromCode(code, message);\n }\n\n const { stack, cause, data } = thrown;\n\n const error =\n code === undefined\n ? // Jest complains if we use the `@ts-expect-error` directive here.\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Our error type is outdated.\n new Error(message, { cause })\n : new JsonRpcError(code, message, {\n ...(isObject(data) ? data : undefined),\n cause,\n });\n\n if (typeof stack === 'string') {\n error.stack = stack;\n }\n\n return error;\n}\n"]}
|
package/dist/v2/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../src/v2/utils.ts"],"names":[],"mappings":";;;;AAAA,
|
|
1
|
+
{"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../src/v2/utils.ts"],"names":[],"mappings":";;;;AAAA,2CAAwD;AAkBjD,MAAM,SAAS,GAAG,CACvB,GAAwD,EACzB,EAAE,CAAC,IAAA,mBAAW,EAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AAF9C,QAAA,SAAS,aAEqC;AAEpD,MAAM,cAAc,GAAG,CAC5B,GAAwB,EACY,EAAE,CAAC,CAAC,IAAA,iBAAS,EAAC,GAAG,CAAC,CAAC;AAF5C,QAAA,cAAc,kBAE8B;AAgBzD;;;;;GAKG;AACH,SAAgB,SAAS,CAAC,KAAc;IACtC,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACxC,CAAC;AAFD,8BAEC;AAED;;;;;;GAMG;AACI,MAAM,UAAU,GAAG,CACxB,KAAc,EACd,MAAc,EACoB,EAAE,CACpC,IAAA,gBAAQ,EAAC,KAAK,CAAC,IAAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,IAAI,CAAC;AAJlD,QAAA,UAAU,cAIwC;AAE/D,MAAM,wBAAwB,GAAG,MAAM,CAAC,GAAG,CACzC,oCAAoC,CACrC,CAAC;AAEF,MAAa,kBAAmB,SAAQ,KAAK;IAG3C,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QAHA,QAA0B,GAAG,IAAI,CAAC;QAIjD,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,UAAU,CAAC,KAAc;QAC9B,OAAO,IAAA,kBAAU,EAAC,KAAK,EAAE,wBAAwB,CAAC,CAAC;IACrD,CAAC;CACF;AAlBD,gDAkBC;KAjBmB,wBAAwB","sourcesContent":["import { hasProperty, isObject } from '@metamask/utils';\nimport type {\n JsonRpcNotification,\n JsonRpcParams,\n JsonRpcRequest,\n} from '@metamask/utils';\n\nexport type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcNotification,\n} from '@metamask/utils';\n\nexport type JsonRpcCall<Params extends JsonRpcParams = JsonRpcParams> =\n | JsonRpcNotification<Params>\n | JsonRpcRequest<Params>;\n\nexport const isRequest = <Params extends JsonRpcParams>(\n msg: JsonRpcCall<Params> | Readonly<JsonRpcCall<Params>>,\n): msg is JsonRpcRequest<Params> => hasProperty(msg, 'id');\n\nexport const isNotification = <Params extends JsonRpcParams>(\n msg: JsonRpcCall<Params>,\n): msg is JsonRpcNotification<Params> => !isRequest(msg);\n\n/**\n * An unholy incantation that converts a union of object types into an\n * intersection of object types.\n *\n * @example\n * type A = { a: string } | { b: number };\n * type B = UnionToIntersection<A>; // { a: string } & { b: number }\n */\nexport type UnionToIntersection<U> = (\n U extends never ? never : (k: U) => void\n) extends (k: infer I) => void\n ? I\n : never;\n\n/**\n * JSON-stringifies a value.\n *\n * @param value - The value to stringify.\n * @returns The stringified value.\n */\nexport function stringify(value: unknown): string {\n return JSON.stringify(value, null, 2);\n}\n\n/**\n * The implementation of static `isInstance` methods for classes that have them.\n *\n * @param value - The value to check.\n * @param symbol - The symbol property to check for.\n * @returns Whether the value has `{ [symbol]: true }` in its prototype chain.\n */\nexport const isInstance = (\n value: unknown,\n symbol: symbol,\n): value is { [key: symbol]: true } =>\n isObject(value) && symbol in value && value[symbol] === true;\n\nconst JsonRpcEngineErrorSymbol = Symbol.for(\n 'json-rpc-engine#JsonRpcEngineError',\n);\n\nexport class JsonRpcEngineError extends Error {\n private readonly [JsonRpcEngineErrorSymbol] = true;\n\n constructor(message: string) {\n super(message);\n this.name = 'JsonRpcEngineError';\n }\n\n /**\n * Check if a value is a {@link JsonRpcEngineError} instance.\n * Works across different package versions in the same realm.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link JsonRpcEngineError} instance.\n */\n static isInstance(value: unknown): value is JsonRpcEngineError {\n return isInstance(value, JsonRpcEngineErrorSymbol);\n }\n}\n"]}
|
package/dist/v2/utils.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { JsonRpcNotification, JsonRpcParams, JsonRpcRequest } from "@metamask/utils";
|
|
2
2
|
export type { Json, JsonRpcParams, JsonRpcRequest, JsonRpcNotification, } from "@metamask/utils";
|
|
3
3
|
export type JsonRpcCall<Params extends JsonRpcParams = JsonRpcParams> = JsonRpcNotification<Params> | JsonRpcRequest<Params>;
|
|
4
4
|
export declare const isRequest: <Params extends JsonRpcParams>(msg: JsonRpcCall<Params> | Readonly<JsonRpcCall<Params>>) => msg is JsonRpcRequest<Params>;
|
package/dist/v2/utils.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../../src/v2/utils.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../../src/v2/utils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,mBAAmB,EACnB,aAAa,EACb,cAAc,EACf,wBAAwB;AAEzB,YAAY,EACV,IAAI,EACJ,aAAa,EACb,cAAc,EACd,mBAAmB,GACpB,wBAAwB;AAEzB,MAAM,MAAM,WAAW,CAAC,MAAM,SAAS,aAAa,GAAG,aAAa,IAChE,mBAAmB,CAAC,MAAM,CAAC,GAC3B,cAAc,CAAC,MAAM,CAAC,CAAC;AAE3B,eAAO,MAAM,SAAS,2HAEoC,CAAC;AAE3D,eAAO,MAAM,cAAc,gGAE6B,CAAC;AAEzD;;;;;;;GAOG;AACH,MAAM,MAAM,mBAAmB,CAAC,CAAC,IAAI,CACnC,CAAC,SAAS,KAAK,GAAG,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,IAAI,CACzC,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,KAAK,IAAI,GAC1B,CAAC,GACD,KAAK,CAAC;AAEV;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAEhD;AAED;;;;;;GAMG;AACH,eAAO,MAAM,UAAU,UACd,OAAO,UACN,MAAM;;CAE8C,CAAC;AAE/D,QAAA,MAAM,wBAAwB,eAE7B,CAAC;AAEF,qBAAa,kBAAmB,SAAQ,KAAK;IAC3C,OAAO,CAAC,QAAQ,CAAC,CAAC,wBAAwB,CAAC,CAAQ;gBAEvC,OAAO,EAAE,MAAM;IAK3B;;;;;;OAMG;IACH,MAAM,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,kBAAkB;CAG/D"}
|
package/dist/v2/utils.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { JsonRpcNotification, JsonRpcParams, JsonRpcRequest } from "@metamask/utils";
|
|
2
2
|
export type { Json, JsonRpcParams, JsonRpcRequest, JsonRpcNotification, } from "@metamask/utils";
|
|
3
3
|
export type JsonRpcCall<Params extends JsonRpcParams = JsonRpcParams> = JsonRpcNotification<Params> | JsonRpcRequest<Params>;
|
|
4
4
|
export declare const isRequest: <Params extends JsonRpcParams>(msg: JsonRpcCall<Params> | Readonly<JsonRpcCall<Params>>) => msg is JsonRpcRequest<Params>;
|
package/dist/v2/utils.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../../src/v2/utils.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../../src/v2/utils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,mBAAmB,EACnB,aAAa,EACb,cAAc,EACf,wBAAwB;AAEzB,YAAY,EACV,IAAI,EACJ,aAAa,EACb,cAAc,EACd,mBAAmB,GACpB,wBAAwB;AAEzB,MAAM,MAAM,WAAW,CAAC,MAAM,SAAS,aAAa,GAAG,aAAa,IAChE,mBAAmB,CAAC,MAAM,CAAC,GAC3B,cAAc,CAAC,MAAM,CAAC,CAAC;AAE3B,eAAO,MAAM,SAAS,2HAEoC,CAAC;AAE3D,eAAO,MAAM,cAAc,gGAE6B,CAAC;AAEzD;;;;;;;GAOG;AACH,MAAM,MAAM,mBAAmB,CAAC,CAAC,IAAI,CACnC,CAAC,SAAS,KAAK,GAAG,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,IAAI,CACzC,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,KAAK,IAAI,GAC1B,CAAC,GACD,KAAK,CAAC;AAEV;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAEhD;AAED;;;;;;GAMG;AACH,eAAO,MAAM,UAAU,UACd,OAAO,UACN,MAAM;;CAE8C,CAAC;AAE/D,QAAA,MAAM,wBAAwB,eAE7B,CAAC;AAEF,qBAAa,kBAAmB,SAAQ,KAAK;IAC3C,OAAO,CAAC,QAAQ,CAAC,CAAC,wBAAwB,CAAC,CAAQ;gBAEvC,OAAO,EAAE,MAAM;IAK3B;;;;;;OAMG;IACH,MAAM,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,kBAAkB;CAG/D"}
|
package/dist/v2/utils.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/v2/utils.ts"],"names":[],"mappings":";AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/v2/utils.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,wBAAwB;AAkBxD,MAAM,CAAC,MAAM,SAAS,GAAG,CACvB,GAAwD,EACzB,EAAE,CAAC,WAAW,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AAE3D,MAAM,CAAC,MAAM,cAAc,GAAG,CAC5B,GAAwB,EACY,EAAE,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;AAgBzD;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,KAAc;IACtC,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACxC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CACxB,KAAc,EACd,MAAc,EACoB,EAAE,CACpC,QAAQ,CAAC,KAAK,CAAC,IAAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,IAAI,CAAC;AAE/D,MAAM,wBAAwB,GAAG,MAAM,CAAC,GAAG,CACzC,oCAAoC,CACrC,CAAC;AAEF,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAG3C,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QAHA,QAA0B,GAAG,IAAI,CAAC;QAIjD,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,UAAU,CAAC,KAAc;QAC9B,OAAO,UAAU,CAAC,KAAK,EAAE,wBAAwB,CAAC,CAAC;IACrD,CAAC;CACF;KAjBmB,wBAAwB","sourcesContent":["import { hasProperty, isObject } from '@metamask/utils';\nimport type {\n JsonRpcNotification,\n JsonRpcParams,\n JsonRpcRequest,\n} from '@metamask/utils';\n\nexport type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcNotification,\n} from '@metamask/utils';\n\nexport type JsonRpcCall<Params extends JsonRpcParams = JsonRpcParams> =\n | JsonRpcNotification<Params>\n | JsonRpcRequest<Params>;\n\nexport const isRequest = <Params extends JsonRpcParams>(\n msg: JsonRpcCall<Params> | Readonly<JsonRpcCall<Params>>,\n): msg is JsonRpcRequest<Params> => hasProperty(msg, 'id');\n\nexport const isNotification = <Params extends JsonRpcParams>(\n msg: JsonRpcCall<Params>,\n): msg is JsonRpcNotification<Params> => !isRequest(msg);\n\n/**\n * An unholy incantation that converts a union of object types into an\n * intersection of object types.\n *\n * @example\n * type A = { a: string } | { b: number };\n * type B = UnionToIntersection<A>; // { a: string } & { b: number }\n */\nexport type UnionToIntersection<U> = (\n U extends never ? never : (k: U) => void\n) extends (k: infer I) => void\n ? I\n : never;\n\n/**\n * JSON-stringifies a value.\n *\n * @param value - The value to stringify.\n * @returns The stringified value.\n */\nexport function stringify(value: unknown): string {\n return JSON.stringify(value, null, 2);\n}\n\n/**\n * The implementation of static `isInstance` methods for classes that have them.\n *\n * @param value - The value to check.\n * @param symbol - The symbol property to check for.\n * @returns Whether the value has `{ [symbol]: true }` in its prototype chain.\n */\nexport const isInstance = (\n value: unknown,\n symbol: symbol,\n): value is { [key: symbol]: true } =>\n isObject(value) && symbol in value && value[symbol] === true;\n\nconst JsonRpcEngineErrorSymbol = Symbol.for(\n 'json-rpc-engine#JsonRpcEngineError',\n);\n\nexport class JsonRpcEngineError extends Error {\n private readonly [JsonRpcEngineErrorSymbol] = true;\n\n constructor(message: string) {\n super(message);\n this.name = 'JsonRpcEngineError';\n }\n\n /**\n * Check if a value is a {@link JsonRpcEngineError} instance.\n * Works across different package versions in the same realm.\n *\n * @param value - The value to check.\n * @returns Whether the value is a {@link JsonRpcEngineError} instance.\n */\n static isInstance(value: unknown): value is JsonRpcEngineError {\n return isInstance(value, JsonRpcEngineErrorSymbol);\n }\n}\n"]}
|