async.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. var {
  2. _optionalChain
  3. } = require('@sentry/utils');
  4. Object.defineProperty(exports, '__esModule', { value: true });
  5. const core = require('@sentry/core');
  6. const utils = require('@sentry/utils');
  7. const debugBuild = require('./debug-build.js');
  8. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
  9. const MaybeGlobalAsyncLocalStorage = (utils.GLOBAL_OBJ ).AsyncLocalStorage;
  10. let asyncStorage;
  11. /**
  12. * Sets the async context strategy to use AsyncLocalStorage which should be available in the edge runtime.
  13. */
  14. function setAsyncLocalStorageAsyncContextStrategy() {
  15. if (!MaybeGlobalAsyncLocalStorage) {
  16. debugBuild.DEBUG_BUILD &&
  17. utils.logger.warn(
  18. "Tried to register AsyncLocalStorage async context strategy in a runtime that doesn't support AsyncLocalStorage.",
  19. );
  20. return;
  21. }
  22. if (!asyncStorage) {
  23. asyncStorage = new MaybeGlobalAsyncLocalStorage();
  24. }
  25. function getCurrentHub() {
  26. return asyncStorage.getStore();
  27. }
  28. function createNewHub(parent) {
  29. const carrier = {};
  30. core.ensureHubOnCarrier(carrier, parent);
  31. return core.getHubFromCarrier(carrier);
  32. }
  33. function runWithAsyncContext(callback, options) {
  34. const existingHub = getCurrentHub();
  35. if (existingHub && _optionalChain([options, 'optionalAccess', _ => _.reuseExisting])) {
  36. // We're already in an async context, so we don't need to create a new one
  37. // just call the callback with the current hub
  38. return callback();
  39. }
  40. const newHub = createNewHub(existingHub);
  41. return asyncStorage.run(newHub, () => {
  42. return callback();
  43. });
  44. }
  45. core.setAsyncContextStrategy({ getCurrentHub, runWithAsyncContext });
  46. }
  47. exports.setAsyncLocalStorageAsyncContextStrategy = setAsyncLocalStorageAsyncContextStrategy;
  48. //# sourceMappingURL=async.js.map