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

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

const core = require('@sentry/core');
const utils = require('@sentry/utils');
const debugBuild = require('./debug-build.js');

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
const MaybeGlobalAsyncLocalStorage = (utils.GLOBAL_OBJ ).AsyncLocalStorage;

let asyncStorage;

/**
 * Sets the async context strategy to use AsyncLocalStorage which should be available in the edge runtime.
 */
function setAsyncLocalStorageAsyncContextStrategy() {
  if (!MaybeGlobalAsyncLocalStorage) {
    debugBuild.DEBUG_BUILD &&
      utils.logger.warn(
        "Tried to register AsyncLocalStorage async context strategy in a runtime that doesn't support AsyncLocalStorage.",
      );
    return;
  }

  if (!asyncStorage) {
    asyncStorage = new MaybeGlobalAsyncLocalStorage();
  }

  function getCurrentHub() {
    return asyncStorage.getStore();
  }

  function createNewHub(parent) {
    const carrier = {};
    core.ensureHubOnCarrier(carrier, parent);
    return core.getHubFromCarrier(carrier);
  }

  function runWithAsyncContext(callback, options) {
    const existingHub = getCurrentHub();

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

    const newHub = createNewHub(existingHub);

    return asyncStorage.run(newHub, () => {
      return callback();
    });
  }

  core.setAsyncContextStrategy({ getCurrentHub, runWithAsyncContext });
}

exports.setAsyncLocalStorageAsyncContextStrategy = setAsyncLocalStorageAsyncContextStrategy;
//# sourceMappingURL=async.js.map