@metamask/json-rpc-engine
Advanced tools
Comparing version 7.3.3 to 8.0.0
@@ -10,2 +10,9 @@ # Changelog | ||
## [8.0.0] | ||
### Added | ||
- **BREAKING**: Add ESM build ([#3998](https://github.com/MetaMask/core/pull/3998)) | ||
- It's no longer possible to import files from `./dist` directly. | ||
## [7.3.3] | ||
@@ -141,3 +148,4 @@ | ||
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@7.3.3...HEAD | ||
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@8.0.0...HEAD | ||
[8.0.0]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@7.3.3...@metamask/json-rpc-engine@8.0.0 | ||
[7.3.3]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@7.3.2...@metamask/json-rpc-engine@7.3.3 | ||
@@ -144,0 +152,0 @@ [7.3.2]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@7.3.1...@metamask/json-rpc-engine@7.3.2 |
@@ -1,81 +0,8 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.createAsyncMiddleware = void 0; | ||
/** | ||
* JsonRpcEngine only accepts callback-based middleware directly. | ||
* createAsyncMiddleware exists to enable consumers to pass in async middleware | ||
* functions. | ||
* | ||
* Async middleware have no "end" function. Instead, they "end" if they return | ||
* without calling "next". Rather than passing in explicit return handlers, | ||
* async middleware can simply await "next", and perform operations on the | ||
* response object when execution resumes. | ||
* | ||
* To accomplish this, createAsyncMiddleware passes the async middleware a | ||
* wrapped "next" function. That function calls the internal JsonRpcEngine | ||
* "next" function with a return handler that resolves a promise when called. | ||
* | ||
* The return handler will always be called. Its resolution of the promise | ||
* enables the control flow described above. | ||
* | ||
* @param asyncMiddleware - The asynchronous middleware function to wrap. | ||
* @returns The wrapped asynchronous middleware function, ready to be consumed | ||
* by JsonRpcEngine. | ||
*/ | ||
function createAsyncMiddleware(asyncMiddleware) { | ||
// eslint-disable-next-line @typescript-eslint/no-misused-promises | ||
return (request, response, next, end) => __awaiter(this, void 0, void 0, function* () { | ||
// nextPromise is the key to the implementation | ||
// it is resolved by the return handler passed to the | ||
// "next" function | ||
let resolveNextPromise; | ||
const nextPromise = new Promise((resolve) => { | ||
resolveNextPromise = resolve; | ||
}); | ||
let returnHandlerCallback = null; | ||
let nextWasCalled = false; | ||
// This will be called by the consumer's async middleware. | ||
const asyncNext = () => __awaiter(this, void 0, void 0, function* () { | ||
nextWasCalled = true; | ||
// We pass a return handler to next(). When it is called by the engine, | ||
// the consumer's async middleware will resume executing. | ||
next((runReturnHandlersCallback) => { | ||
// This callback comes from JsonRpcEngine._runReturnHandlers | ||
returnHandlerCallback = runReturnHandlersCallback; | ||
resolveNextPromise(); | ||
}); | ||
return nextPromise; | ||
}); | ||
try { | ||
yield asyncMiddleware(request, response, asyncNext); | ||
if (nextWasCalled) { | ||
yield nextPromise; // we must wait until the return handler is called | ||
returnHandlerCallback(null); | ||
} | ||
else { | ||
end(null); | ||
} | ||
// TODO: Replace `any` with type | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
} | ||
catch (error) { | ||
if (returnHandlerCallback) { | ||
returnHandlerCallback(error); | ||
} | ||
else { | ||
end(error); | ||
} | ||
} | ||
}); | ||
} | ||
exports.createAsyncMiddleware = createAsyncMiddleware; | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); | ||
var _chunkENMR2SJCjs = require('./chunk-ENMR2SJC.js'); | ||
require('./chunk-Z4BLTVTB.js'); | ||
exports.createAsyncMiddleware = _chunkENMR2SJCjs.createAsyncMiddleware; | ||
//# sourceMappingURL=createAsyncMiddleware.js.map |
@@ -1,30 +0,8 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.createScaffoldMiddleware = void 0; | ||
/** | ||
* Creates a middleware function from an object of RPC method handler functions, | ||
* keyed to particular method names. If a method corresponding to a key of this | ||
* object is requested, this middleware will pass it to the corresponding | ||
* handler and return the result. | ||
* | ||
* @param handlers - The RPC method handler functions. | ||
* @returns The scaffold middleware function. | ||
*/ | ||
function createScaffoldMiddleware(handlers) { | ||
return (req, res, next, end) => { | ||
const handler = handlers[req.method]; | ||
// if no handler, return | ||
if (handler === undefined) { | ||
return next(); | ||
} | ||
// if handler is fn, call as middleware | ||
if (typeof handler === 'function') { | ||
return handler(req, res, next, end); | ||
} | ||
// if handler is some other value, use as result | ||
res.result = handler; | ||
return end(); | ||
}; | ||
} | ||
exports.createScaffoldMiddleware = createScaffoldMiddleware; | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); | ||
var _chunk3AC2MINDjs = require('./chunk-3AC2MIND.js'); | ||
require('./chunk-Z4BLTVTB.js'); | ||
exports.createScaffoldMiddleware = _chunk3AC2MINDjs.createScaffoldMiddleware; | ||
//# sourceMappingURL=createScaffoldMiddleware.js.map |
@@ -1,20 +0,8 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getUniqueId = void 0; | ||
// uint32 (two's complement) max | ||
// more conservative than Number.MAX_SAFE_INTEGER | ||
const MAX = 4294967295; | ||
let idCounter = Math.floor(Math.random() * MAX); | ||
/** | ||
* Gets an ID that is guaranteed to be unique so long as no more than | ||
* 4_294_967_295 (uint32 max) IDs are created, or the IDs are rapidly turned | ||
* over. | ||
* | ||
* @returns The unique ID. | ||
*/ | ||
function getUniqueId() { | ||
idCounter = (idCounter + 1) % MAX; | ||
return idCounter; | ||
} | ||
exports.getUniqueId = getUniqueId; | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); | ||
var _chunkXDGWQHNYjs = require('./chunk-XDGWQHNY.js'); | ||
require('./chunk-Z4BLTVTB.js'); | ||
exports.getUniqueId = _chunkXDGWQHNYjs.getUniqueId; | ||
//# sourceMappingURL=getUniqueId.js.map |
@@ -1,28 +0,9 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.createIdRemapMiddleware = void 0; | ||
const getUniqueId_1 = require("./getUniqueId"); | ||
/** | ||
* Returns a middleware function that overwrites the `id` property of each | ||
* request with an ID that is guaranteed to be unique, and restores the original | ||
* ID in a return handler. | ||
* | ||
* If used, should be the first middleware in the stack. | ||
* | ||
* @returns The ID remap middleware function. | ||
*/ | ||
function createIdRemapMiddleware() { | ||
return (request, response, next, _end) => { | ||
const originalId = request.id; | ||
const newId = (0, getUniqueId_1.getUniqueId)(); | ||
request.id = newId; | ||
response.id = newId; | ||
next((done) => { | ||
request.id = originalId; | ||
response.id = originalId; | ||
done(); | ||
}); | ||
}; | ||
} | ||
exports.createIdRemapMiddleware = createIdRemapMiddleware; | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); | ||
var _chunkPBQXMZM5js = require('./chunk-PBQXMZM5.js'); | ||
require('./chunk-XDGWQHNY.js'); | ||
require('./chunk-Z4BLTVTB.js'); | ||
exports.createIdRemapMiddleware = _chunkPBQXMZM5js.createIdRemapMiddleware; | ||
//# sourceMappingURL=idRemapMiddleware.js.map |
@@ -1,23 +0,28 @@ | ||
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
o[k2] = m[k]; | ||
})); | ||
var __exportStar = (this && this.__exportStar) || function(m, exports) { | ||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
__exportStar(require("./createAsyncMiddleware"), exports); | ||
__exportStar(require("./createScaffoldMiddleware"), exports); | ||
__exportStar(require("./getUniqueId"), exports); | ||
__exportStar(require("./idRemapMiddleware"), exports); | ||
__exportStar(require("./JsonRpcEngine"), exports); | ||
__exportStar(require("./mergeMiddleware"), exports); | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); | ||
var _chunkENMR2SJCjs = require('./chunk-ENMR2SJC.js'); | ||
var _chunk3AC2MINDjs = require('./chunk-3AC2MIND.js'); | ||
var _chunkPBQXMZM5js = require('./chunk-PBQXMZM5.js'); | ||
var _chunkXDGWQHNYjs = require('./chunk-XDGWQHNY.js'); | ||
var _chunkI2BVUFWRjs = require('./chunk-I2BVUFWR.js'); | ||
var _chunkIPW2SZMYjs = require('./chunk-IPW2SZMY.js'); | ||
require('./chunk-Z4BLTVTB.js'); | ||
exports.JsonRpcEngine = _chunkIPW2SZMYjs.JsonRpcEngine; exports.createAsyncMiddleware = _chunkENMR2SJCjs.createAsyncMiddleware; exports.createIdRemapMiddleware = _chunkPBQXMZM5js.createIdRemapMiddleware; exports.createScaffoldMiddleware = _chunk3AC2MINDjs.createScaffoldMiddleware; exports.getUniqueId = _chunkXDGWQHNYjs.getUniqueId; exports.mergeMiddleware = _chunkI2BVUFWRjs.mergeMiddleware; | ||
//# sourceMappingURL=index.js.map |
@@ -1,367 +0,8 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { | ||
if (kind === "m") throw new TypeError("Private method is not writable"); | ||
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); | ||
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); | ||
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; | ||
}; | ||
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { | ||
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); | ||
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); | ||
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
var _JsonRpcEngine_instances, _a, _JsonRpcEngine_isDestroyed, _JsonRpcEngine_middleware, _JsonRpcEngine_notificationHandler, _JsonRpcEngine_assertIsNotDestroyed, _JsonRpcEngine_handleBatch, _JsonRpcEngine_handle, _JsonRpcEngine_processRequest, _JsonRpcEngine_runAllMiddleware, _JsonRpcEngine_runMiddleware, _JsonRpcEngine_runReturnHandlers, _JsonRpcEngine_checkForCompletion; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.JsonRpcEngine = void 0; | ||
const rpc_errors_1 = require("@metamask/rpc-errors"); | ||
const safe_event_emitter_1 = __importDefault(require("@metamask/safe-event-emitter")); | ||
const utils_1 = require("@metamask/utils"); | ||
const DESTROYED_ERROR_MESSAGE = 'This engine is destroyed and can no longer be used.'; | ||
/** | ||
* A JSON-RPC request and response processor. | ||
* Give it a stack of middleware, pass it requests, and get back responses. | ||
*/ | ||
class JsonRpcEngine extends safe_event_emitter_1.default { | ||
/** | ||
* Constructs a {@link JsonRpcEngine} instance. | ||
* | ||
* @param options - Options bag. | ||
* @param options.notificationHandler - A function for handling JSON-RPC | ||
* notifications. A JSON-RPC notification is defined as a JSON-RPC request | ||
* without an `id` property. If this option is _not_ provided, notifications | ||
* will be treated the same as requests. If this option _is_ provided, | ||
* notifications will be passed to the handler function without touching | ||
* the engine's middleware stack. This function should not throw or reject. | ||
*/ | ||
constructor({ notificationHandler } = {}) { | ||
super(); | ||
_JsonRpcEngine_instances.add(this); | ||
/** | ||
* Indicating whether this engine is destroyed or not. | ||
*/ | ||
_JsonRpcEngine_isDestroyed.set(this, false); | ||
_JsonRpcEngine_middleware.set(this, void 0); | ||
_JsonRpcEngine_notificationHandler.set(this, void 0); | ||
__classPrivateFieldSet(this, _JsonRpcEngine_middleware, [], "f"); | ||
__classPrivateFieldSet(this, _JsonRpcEngine_notificationHandler, notificationHandler, "f"); | ||
} | ||
/** | ||
* Calls the `destroy()` function of any middleware with that property, clears | ||
* the middleware array, and marks this engine as destroyed. A destroyed | ||
* engine cannot be used. | ||
*/ | ||
destroy() { | ||
__classPrivateFieldGet(this, _JsonRpcEngine_middleware, "f").forEach((middleware) => { | ||
if ( | ||
// `in` walks the prototype chain, which is probably the desired | ||
// behavior here. | ||
'destroy' in middleware && | ||
typeof middleware.destroy === 'function') { | ||
// eslint-disable-next-line @typescript-eslint/no-floating-promises | ||
middleware.destroy(); | ||
} | ||
}); | ||
__classPrivateFieldSet(this, _JsonRpcEngine_middleware, [], "f"); | ||
__classPrivateFieldSet(this, _JsonRpcEngine_isDestroyed, true, "f"); | ||
} | ||
/** | ||
* Add a middleware function to the engine's middleware stack. | ||
* | ||
* @param middleware - The middleware function to add. | ||
*/ | ||
push(middleware) { | ||
__classPrivateFieldGet(this, _JsonRpcEngine_instances, "m", _JsonRpcEngine_assertIsNotDestroyed).call(this); | ||
__classPrivateFieldGet(this, _JsonRpcEngine_middleware, "f").push(middleware); | ||
} | ||
// TODO: Replace `any` with type | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
handle(req, callback) { | ||
__classPrivateFieldGet(this, _JsonRpcEngine_instances, "m", _JsonRpcEngine_assertIsNotDestroyed).call(this); | ||
if (callback && typeof callback !== 'function') { | ||
throw new Error('"callback" must be a function if provided.'); | ||
} | ||
if (Array.isArray(req)) { | ||
if (callback) { | ||
return __classPrivateFieldGet(this, _JsonRpcEngine_instances, "m", _JsonRpcEngine_handleBatch).call(this, req, callback); | ||
} | ||
return __classPrivateFieldGet(this, _JsonRpcEngine_instances, "m", _JsonRpcEngine_handleBatch).call(this, req); | ||
} | ||
if (callback) { | ||
return __classPrivateFieldGet(this, _JsonRpcEngine_instances, "m", _JsonRpcEngine_handle).call(this, req, callback); | ||
} | ||
return this._promiseHandle(req); | ||
} | ||
/** | ||
* Returns this engine as a middleware function that can be pushed to other | ||
* engines. | ||
* | ||
* @returns This engine as a middleware function. | ||
*/ | ||
asMiddleware() { | ||
__classPrivateFieldGet(this, _JsonRpcEngine_instances, "m", _JsonRpcEngine_assertIsNotDestroyed).call(this); | ||
// eslint-disable-next-line @typescript-eslint/no-misused-promises | ||
return (req, res, next, end) => __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
const [middlewareError, isComplete, returnHandlers] = yield __classPrivateFieldGet(JsonRpcEngine, _a, "m", _JsonRpcEngine_runAllMiddleware).call(JsonRpcEngine, req, res, __classPrivateFieldGet(this, _JsonRpcEngine_middleware, "f")); | ||
if (isComplete) { | ||
yield __classPrivateFieldGet(JsonRpcEngine, _a, "m", _JsonRpcEngine_runReturnHandlers).call(JsonRpcEngine, returnHandlers); | ||
return end(middlewareError); | ||
} | ||
// eslint-disable-next-line @typescript-eslint/no-misused-promises | ||
return next((handlerCallback) => __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
yield __classPrivateFieldGet(JsonRpcEngine, _a, "m", _JsonRpcEngine_runReturnHandlers).call(JsonRpcEngine, returnHandlers); | ||
// TODO: Replace `any` with type | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
} | ||
catch (error) { | ||
return handlerCallback(error); | ||
} | ||
return handlerCallback(); | ||
})); | ||
// TODO: Replace `any` with type | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
} | ||
catch (error) { | ||
return end(error); | ||
} | ||
}); | ||
} | ||
/** | ||
* A promise-wrapped _handle. | ||
* | ||
* @param request - The JSON-RPC request. | ||
* @returns The JSON-RPC response. | ||
*/ | ||
// This function is used in tests, so we cannot easily change it to use the | ||
// hash syntax. | ||
// eslint-disable-next-line no-restricted-syntax | ||
_promiseHandle(request) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return new Promise((resolve, reject) => { | ||
__classPrivateFieldGet(this, _JsonRpcEngine_instances, "m", _JsonRpcEngine_handle).call(this, request, (error, res) => { | ||
// For notifications, the response will be `undefined`, and any caught | ||
// errors are unexpected and should be surfaced to the caller. | ||
if (error && res === undefined) { | ||
reject(error); | ||
} | ||
else { | ||
// Excepting notifications, there will always be a response, and it will | ||
// always have any error that is caught and propagated. | ||
resolve(res); | ||
} | ||
}).catch(reject); | ||
}); | ||
}); | ||
} | ||
} | ||
exports.JsonRpcEngine = JsonRpcEngine; | ||
_a = JsonRpcEngine, _JsonRpcEngine_isDestroyed = new WeakMap(), _JsonRpcEngine_middleware = new WeakMap(), _JsonRpcEngine_notificationHandler = new WeakMap(), _JsonRpcEngine_instances = new WeakSet(), _JsonRpcEngine_assertIsNotDestroyed = function _JsonRpcEngine_assertIsNotDestroyed() { | ||
if (__classPrivateFieldGet(this, _JsonRpcEngine_isDestroyed, "f")) { | ||
throw new Error(DESTROYED_ERROR_MESSAGE); | ||
} | ||
}, _JsonRpcEngine_handleBatch = function _JsonRpcEngine_handleBatch(requests, callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
// The order here is important | ||
try { | ||
// If the batch is an empty array, the response array must contain a single object | ||
if (requests.length === 0) { | ||
const response = [ | ||
{ | ||
id: null, | ||
jsonrpc: '2.0', | ||
error: new rpc_errors_1.JsonRpcError(rpc_errors_1.errorCodes.rpc.invalidRequest, 'Request batch must contain plain objects. Received an empty array'), | ||
}, | ||
]; | ||
if (callback) { | ||
return callback(null, response); | ||
} | ||
return response; | ||
} | ||
// 2. Wait for all requests to finish, or throw on some kind of fatal | ||
// error | ||
const responses = (yield Promise.all( | ||
// 1. Begin executing each request in the order received | ||
requests.map(this._promiseHandle.bind(this)))).filter( | ||
// Filter out any notification responses. | ||
(response) => response !== undefined); | ||
// 3. Return batch response | ||
if (callback) { | ||
return callback(null, responses); | ||
} | ||
return responses; | ||
} | ||
catch (error) { | ||
if (callback) { | ||
return callback(error); | ||
} | ||
throw error; | ||
} | ||
}); | ||
}, _JsonRpcEngine_handle = function _JsonRpcEngine_handle(callerReq, callback) { | ||
var _b; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!callerReq || | ||
Array.isArray(callerReq) || | ||
typeof callerReq !== 'object') { | ||
const error = new rpc_errors_1.JsonRpcError(rpc_errors_1.errorCodes.rpc.invalidRequest, `Requests must be plain objects. Received: ${typeof callerReq}`, { request: callerReq }); | ||
return callback(error, { id: null, jsonrpc: '2.0', error }); | ||
} | ||
if (typeof callerReq.method !== 'string') { | ||
const error = new rpc_errors_1.JsonRpcError(rpc_errors_1.errorCodes.rpc.invalidRequest, `Must specify a string method. Received: ${typeof callerReq.method}`, { request: callerReq }); | ||
if (__classPrivateFieldGet(this, _JsonRpcEngine_notificationHandler, "f") && !(0, utils_1.isJsonRpcRequest)(callerReq)) { | ||
// Do not reply to notifications, even if they are malformed. | ||
return callback(null); | ||
} | ||
return callback(error, { | ||
// Typecast: This could be a notification, but we want to access the | ||
// `id` even if it doesn't exist. | ||
id: (_b = callerReq.id) !== null && _b !== void 0 ? _b : null, | ||
jsonrpc: '2.0', | ||
error, | ||
}); | ||
} | ||
// Handle notifications. | ||
// We can't use isJsonRpcNotification here because that narrows callerReq to | ||
// "never" after the if clause for unknown reasons. | ||
if (__classPrivateFieldGet(this, _JsonRpcEngine_notificationHandler, "f") && !(0, utils_1.isJsonRpcRequest)(callerReq)) { | ||
try { | ||
yield __classPrivateFieldGet(this, _JsonRpcEngine_notificationHandler, "f").call(this, callerReq); | ||
} | ||
catch (error) { | ||
return callback(error); | ||
} | ||
return callback(null); | ||
} | ||
let error = null; | ||
// Handle requests. | ||
// Typecast: Permit missing id's for backwards compatibility. | ||
const req = Object.assign({}, callerReq); | ||
const res = { | ||
id: req.id, | ||
jsonrpc: req.jsonrpc, | ||
}; | ||
try { | ||
yield __classPrivateFieldGet(JsonRpcEngine, _a, "m", _JsonRpcEngine_processRequest).call(JsonRpcEngine, req, res, __classPrivateFieldGet(this, _JsonRpcEngine_middleware, "f")); | ||
// TODO: Replace `any` with type | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
} | ||
catch (_error) { | ||
// A request handler error, a re-thrown middleware error, or something | ||
// unexpected. | ||
error = _error; | ||
} | ||
if (error) { | ||
// Ensure no result is present on an errored response | ||
delete res.result; | ||
if (!res.error) { | ||
res.error = (0, rpc_errors_1.serializeError)(error); | ||
} | ||
} | ||
return callback(error, res); | ||
}); | ||
}, _JsonRpcEngine_processRequest = function _JsonRpcEngine_processRequest(req, res, middlewares) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const [error, isComplete, returnHandlers] = yield __classPrivateFieldGet(JsonRpcEngine, _a, "m", _JsonRpcEngine_runAllMiddleware).call(JsonRpcEngine, req, res, middlewares); | ||
// Throw if "end" was not called, or if the response has neither a result | ||
// nor an error. | ||
__classPrivateFieldGet(JsonRpcEngine, _a, "m", _JsonRpcEngine_checkForCompletion).call(JsonRpcEngine, req, res, isComplete); | ||
// The return handlers should run even if an error was encountered during | ||
// middleware processing. | ||
yield __classPrivateFieldGet(JsonRpcEngine, _a, "m", _JsonRpcEngine_runReturnHandlers).call(JsonRpcEngine, returnHandlers); | ||
// Now we re-throw the middleware processing error, if any, to catch it | ||
// further up the call chain. | ||
if (error) { | ||
// eslint-disable-next-line @typescript-eslint/no-throw-literal | ||
throw error; | ||
} | ||
}); | ||
}, _JsonRpcEngine_runAllMiddleware = function _JsonRpcEngine_runAllMiddleware(req, res, middlewares) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const returnHandlers = []; | ||
let error = null; | ||
let isComplete = false; | ||
// Go down stack of middleware, call and collect optional returnHandlers | ||
for (const middleware of middlewares) { | ||
[error, isComplete] = yield __classPrivateFieldGet(JsonRpcEngine, _a, "m", _JsonRpcEngine_runMiddleware).call(JsonRpcEngine, req, res, middleware, returnHandlers); | ||
if (isComplete) { | ||
break; | ||
} | ||
} | ||
return [error, isComplete, returnHandlers.reverse()]; | ||
}); | ||
}, _JsonRpcEngine_runMiddleware = function _JsonRpcEngine_runMiddleware(request, response, middleware, returnHandlers) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return new Promise((resolve) => { | ||
const end = (error) => { | ||
const parsedError = error || response.error; | ||
if (parsedError) { | ||
response.error = (0, rpc_errors_1.serializeError)(parsedError); | ||
} | ||
// True indicates that the request should end | ||
resolve([parsedError, true]); | ||
}; | ||
const next = (returnHandler) => { | ||
if (response.error) { | ||
end(response.error); | ||
} | ||
else { | ||
if (returnHandler) { | ||
if (typeof returnHandler !== 'function') { | ||
end(new rpc_errors_1.JsonRpcError(rpc_errors_1.errorCodes.rpc.internal, `JsonRpcEngine: "next" return handlers must be functions. ` + | ||
`Received "${typeof returnHandler}" for request:\n${jsonify(request)}`, { request: request })); | ||
} | ||
returnHandlers.push(returnHandler); | ||
} | ||
// False indicates that the request should not end | ||
resolve([null, false]); | ||
} | ||
}; | ||
try { | ||
middleware(request, response, next, end); | ||
// TODO: Replace `any` with type | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
} | ||
catch (error) { | ||
end(error); | ||
} | ||
}); | ||
}); | ||
}, _JsonRpcEngine_runReturnHandlers = function _JsonRpcEngine_runReturnHandlers(handlers) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
for (const handler of handlers) { | ||
yield new Promise((resolve, reject) => { | ||
handler((error) => (error ? reject(error) : resolve())); | ||
}); | ||
} | ||
}); | ||
}, _JsonRpcEngine_checkForCompletion = function _JsonRpcEngine_checkForCompletion(request, response, isComplete) { | ||
if (!(0, utils_1.hasProperty)(response, 'result') && !(0, utils_1.hasProperty)(response, 'error')) { | ||
throw new rpc_errors_1.JsonRpcError(rpc_errors_1.errorCodes.rpc.internal, `JsonRpcEngine: Response has no error or result for request:\n${jsonify(request)}`, { request: request }); | ||
} | ||
if (!isComplete) { | ||
throw new rpc_errors_1.JsonRpcError(rpc_errors_1.errorCodes.rpc.internal, `JsonRpcEngine: Nothing ended request:\n${jsonify(request)}`, { request: request }); | ||
} | ||
}; | ||
/** | ||
* JSON-stringifies a request object. | ||
* | ||
* @param request - The request object to JSON-stringify. | ||
* @returns The JSON-stringified request object. | ||
*/ | ||
function jsonify(request) { | ||
return JSON.stringify(request, null, 2); | ||
} | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); | ||
var _chunkIPW2SZMYjs = require('./chunk-IPW2SZMY.js'); | ||
require('./chunk-Z4BLTVTB.js'); | ||
exports.JsonRpcEngine = _chunkIPW2SZMYjs.JsonRpcEngine; | ||
//# sourceMappingURL=JsonRpcEngine.js.map |
@@ -1,17 +0,9 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.mergeMiddleware = void 0; | ||
const JsonRpcEngine_1 = require("./JsonRpcEngine"); | ||
/** | ||
* Takes a stack of middleware and joins them into a single middleware function. | ||
* | ||
* @param middlewareStack - The middleware stack to merge. | ||
* @returns The merged middleware function. | ||
*/ | ||
function mergeMiddleware(middlewareStack) { | ||
const engine = new JsonRpcEngine_1.JsonRpcEngine(); | ||
middlewareStack.forEach((middleware) => engine.push(middleware)); | ||
return engine.asMiddleware(); | ||
} | ||
exports.mergeMiddleware = mergeMiddleware; | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); | ||
var _chunkI2BVUFWRjs = require('./chunk-I2BVUFWR.js'); | ||
require('./chunk-IPW2SZMY.js'); | ||
require('./chunk-Z4BLTVTB.js'); | ||
exports.mergeMiddleware = _chunkI2BVUFWRjs.mergeMiddleware; | ||
//# sourceMappingURL=mergeMiddleware.js.map |
{ | ||
"name": "@metamask/json-rpc-engine", | ||
"version": "7.3.3", | ||
"version": "8.0.0", | ||
"description": "A tool for processing JSON-RPC messages", | ||
@@ -18,2 +18,11 @@ "keywords": [ | ||
"license": "ISC", | ||
"sideEffects": false, | ||
"exports": { | ||
".": { | ||
"import": "./dist/index.mjs", | ||
"require": "./dist/index.js", | ||
"types": "./dist/types/index.d.ts" | ||
}, | ||
"./package.json": "./package.json" | ||
}, | ||
"main": "./dist/index.js", | ||
@@ -28,4 +37,3 @@ "types": "./dist/index.d.ts", | ||
"scripts": { | ||
"build": "tsc --project tsconfig.build.json", | ||
"build:clean": "rimraf dist && yarn build", | ||
"build": "tsup --config ../../tsup.config.ts --tsconfig ./tsconfig.build.json --clean", | ||
"build:docs": "typedoc", | ||
@@ -32,0 +40,0 @@ "changelog:update": "../../scripts/update-changelog.sh @metamask/json-rpc-engine --tag-prefix-before-package-rename json-rpc-engine@ --version-before-package-rename 6.1.0", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
188941
75
1336
1