var {
  _optionalChain
} = require('@sentry/utils');

Object.defineProperty(exports, '__esModule', { value: true });

const domain = require('domain');
const core = require('@sentry/core');

function getActiveDomain() {
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
  return (domain ).active ;
}

// eslint-disable-next-line deprecation/deprecation
function getCurrentHub() {
  const activeDomain = getActiveDomain();

  // If there's no active domain, just return undefined and the global hub will be used
  if (!activeDomain) {
    return undefined;
  }

  core.ensureHubOnCarrier(activeDomain);

  return core.getHubFromCarrier(activeDomain);
}

// eslint-disable-next-line deprecation/deprecation
function createNewHub(parent) {
  const carrier = {};
  core.ensureHubOnCarrier(carrier, parent);
  return core.getHubFromCarrier(carrier);
}

function runWithAsyncContext(callback, options) {
  const activeDomain = getActiveDomain();

  if (activeDomain && _optionalChain([options, 'optionalAccess', _ => _.reuseExisting])) {
    // We're already in a domain, so we don't need to create a new one, just call the callback with the current hub
    return callback();
  }

  const local = domain.create() ;

  const parentHub = activeDomain ? core.getHubFromCarrier(activeDomain) : undefined;
  const newHub = createNewHub(parentHub);
  core.setHubOnCarrier(local, newHub);

  return local.bind(() => {
    return callback();
  })();
}

/**
 * Sets the async context strategy to use Node.js domains.
 */
function setDomainAsyncContextStrategy() {
  core.setAsyncContextStrategy({ getCurrentHub, runWithAsyncContext });
}

exports.setDomainAsyncContextStrategy = setDomainAsyncContextStrategy;
//# sourceMappingURL=domain.js.map
