@web3auth/ws-embed
Version: 
Embed script
60 lines (55 loc) • 1.91 kB
JavaScript
import _objectSpread from '@babel/runtime/helpers/objectSpread2';
import { rpcErrors } from '@web3auth/auth';
import log from './loglevel.js';
// utility functions
/**
 * json-rpc-engine middleware that logs RPC errors and and validates req.method.
 *
 * @param log - The logging API to use.
 * @returns  json-rpc-engine middleware function
 */
function createErrorMiddleware() {
  return (req, res, next) => {
    // json-rpc-engine will terminate the request when it notices this error
    if (typeof req.method !== "string" || !req.method) {
      res.error = rpcErrors.invalidRequest({
        message: `The request 'method' must be a non-empty string.`,
        data: _objectSpread(_objectSpread({}, req || {}), {}, {
          cause: `The request 'method' must be a non-empty string.`
        })
      });
    }
    next(done => {
      const {
        error
      } = res;
      if (!error) {
        return done();
      }
      log.error(`Ws-Embed - RPC Error: ${error.message}`, error);
      return done();
    });
  };
}
/**
 * Logs a stream disconnection error. Emits an 'error' if given an
 * EventEmitter that has listeners for the 'error' event.
 *
 * @param log - The logging API to use.
 * @param remoteLabel - The label of the disconnected stream.
 * @param error - The associated error to log.
 * @param emitter - The logging API to use.
 */
function logStreamDisconnectWarning(remoteLabel, error, emitter) {
  let warningMsg = `Web3Auth: Lost connection to "${remoteLabel}".`;
  if (error !== null && error !== void 0 && error.stack) {
    warningMsg += `\n${error.stack}`;
  }
  log.warn(warningMsg);
  if (emitter && emitter.listenerCount("error") > 0) {
    emitter.emit("error", warningMsg);
  }
}
const EMITTED_NOTIFICATIONS = ["eth_subscription" // per eth-json-rpc-filters/subscriptionManager
];
export { EMITTED_NOTIFICATIONS, createErrorMiddleware, logStreamDisconnectWarning };