exports.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. Object.defineProperty(exports, '__esModule', { value: true });
  2. const utils = require('@sentry/utils');
  3. const constants = require('./constants.js');
  4. const debugBuild = require('./debug-build.js');
  5. const hub = require('./hub.js');
  6. const session = require('./session.js');
  7. const prepareEvent = require('./utils/prepareEvent.js');
  8. /**
  9. * Captures an exception event and sends it to Sentry.
  10. *
  11. * @param exception The exception to capture.
  12. * @param hint Optional additional data to attach to the Sentry event.
  13. * @returns the id of the captured Sentry event.
  14. */
  15. function captureException(
  16. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  17. exception,
  18. hint,
  19. ) {
  20. // eslint-disable-next-line deprecation/deprecation
  21. return hub.getCurrentHub().captureException(exception, prepareEvent.parseEventHintOrCaptureContext(hint));
  22. }
  23. /**
  24. * Captures a message event and sends it to Sentry.
  25. *
  26. * @param exception The exception to capture.
  27. * @param captureContext Define the level of the message or pass in additional data to attach to the message.
  28. * @returns the id of the captured message.
  29. */
  30. function captureMessage(
  31. message,
  32. // eslint-disable-next-line deprecation/deprecation
  33. captureContext,
  34. ) {
  35. // This is necessary to provide explicit scopes upgrade, without changing the original
  36. // arity of the `captureMessage(message, level)` method.
  37. const level = typeof captureContext === 'string' ? captureContext : undefined;
  38. const context = typeof captureContext !== 'string' ? { captureContext } : undefined;
  39. // eslint-disable-next-line deprecation/deprecation
  40. return hub.getCurrentHub().captureMessage(message, level, context);
  41. }
  42. /**
  43. * Captures a manually created event and sends it to Sentry.
  44. *
  45. * @param exception The event to send to Sentry.
  46. * @param hint Optional additional data to attach to the Sentry event.
  47. * @returns the id of the captured event.
  48. */
  49. function captureEvent(event, hint) {
  50. // eslint-disable-next-line deprecation/deprecation
  51. return hub.getCurrentHub().captureEvent(event, hint);
  52. }
  53. /**
  54. * Callback to set context information onto the scope.
  55. * @param callback Callback function that receives Scope.
  56. *
  57. * @deprecated Use getCurrentScope() directly.
  58. */
  59. function configureScope(callback) {
  60. // eslint-disable-next-line deprecation/deprecation
  61. hub.getCurrentHub().configureScope(callback);
  62. }
  63. /**
  64. * Records a new breadcrumb which will be attached to future events.
  65. *
  66. * Breadcrumbs will be added to subsequent events to provide more context on
  67. * user's actions prior to an error or crash.
  68. *
  69. * @param breadcrumb The breadcrumb to record.
  70. */
  71. function addBreadcrumb(breadcrumb, hint) {
  72. // eslint-disable-next-line deprecation/deprecation
  73. hub.getCurrentHub().addBreadcrumb(breadcrumb, hint);
  74. }
  75. /**
  76. * Sets context data with the given name.
  77. * @param name of the context
  78. * @param context Any kind of data. This data will be normalized.
  79. */
  80. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  81. function setContext(name, context) {
  82. // eslint-disable-next-line deprecation/deprecation
  83. hub.getCurrentHub().setContext(name, context);
  84. }
  85. /**
  86. * Set an object that will be merged sent as extra data with the event.
  87. * @param extras Extras object to merge into current context.
  88. */
  89. function setExtras(extras) {
  90. // eslint-disable-next-line deprecation/deprecation
  91. hub.getCurrentHub().setExtras(extras);
  92. }
  93. /**
  94. * Set key:value that will be sent as extra data with the event.
  95. * @param key String of extra
  96. * @param extra Any kind of data. This data will be normalized.
  97. */
  98. function setExtra(key, extra) {
  99. // eslint-disable-next-line deprecation/deprecation
  100. hub.getCurrentHub().setExtra(key, extra);
  101. }
  102. /**
  103. * Set an object that will be merged sent as tags data with the event.
  104. * @param tags Tags context object to merge into current context.
  105. */
  106. function setTags(tags) {
  107. // eslint-disable-next-line deprecation/deprecation
  108. hub.getCurrentHub().setTags(tags);
  109. }
  110. /**
  111. * Set key:value that will be sent as tags data with the event.
  112. *
  113. * Can also be used to unset a tag, by passing `undefined`.
  114. *
  115. * @param key String key of tag
  116. * @param value Value of tag
  117. */
  118. function setTag(key, value) {
  119. // eslint-disable-next-line deprecation/deprecation
  120. hub.getCurrentHub().setTag(key, value);
  121. }
  122. /**
  123. * Updates user context information for future events.
  124. *
  125. * @param user User context object to be set in the current context. Pass `null` to unset the user.
  126. */
  127. function setUser(user) {
  128. // eslint-disable-next-line deprecation/deprecation
  129. hub.getCurrentHub().setUser(user);
  130. }
  131. /**
  132. * Creates a new scope with and executes the given operation within.
  133. * The scope is automatically removed once the operation
  134. * finishes or throws.
  135. *
  136. * This is essentially a convenience function for:
  137. *
  138. * pushScope();
  139. * callback();
  140. * popScope();
  141. */
  142. /**
  143. * Either creates a new active scope, or sets the given scope as active scope in the given callback.
  144. */
  145. function withScope(
  146. ...rest
  147. ) {
  148. // eslint-disable-next-line deprecation/deprecation
  149. const hub$1 = hub.getCurrentHub();
  150. // If a scope is defined, we want to make this the active scope instead of the default one
  151. if (rest.length === 2) {
  152. const [scope, callback] = rest;
  153. if (!scope) {
  154. // eslint-disable-next-line deprecation/deprecation
  155. return hub$1.withScope(callback);
  156. }
  157. // eslint-disable-next-line deprecation/deprecation
  158. return hub$1.withScope(() => {
  159. // eslint-disable-next-line deprecation/deprecation
  160. hub$1.getStackTop().scope = scope ;
  161. return callback(scope );
  162. });
  163. }
  164. // eslint-disable-next-line deprecation/deprecation
  165. return hub$1.withScope(rest[0]);
  166. }
  167. /**
  168. * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no
  169. * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the
  170. * case, for example, in the browser).
  171. *
  172. * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.
  173. *
  174. * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in "normal"
  175. * applications directly because it comes with pitfalls. Use at your own risk!
  176. *
  177. * @param callback The callback in which the passed isolation scope is active. (Note: In environments without async
  178. * context strategy, the currently active isolation scope may change within execution of the callback.)
  179. * @returns The same value that `callback` returns.
  180. */
  181. function withIsolationScope(callback) {
  182. return hub.runWithAsyncContext(() => {
  183. return callback(hub.getIsolationScope());
  184. });
  185. }
  186. /**
  187. * Forks the current scope and sets the provided span as active span in the context of the provided callback.
  188. *
  189. * @param span Spans started in the context of the provided callback will be children of this span.
  190. * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.
  191. * @returns the value returned from the provided callback function.
  192. */
  193. function withActiveSpan(span, callback) {
  194. return withScope(scope => {
  195. // eslint-disable-next-line deprecation/deprecation
  196. scope.setSpan(span);
  197. return callback(scope);
  198. });
  199. }
  200. /**
  201. * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.
  202. *
  203. * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a
  204. * new child span within the transaction or any span, call the respective `.startChild()` method.
  205. *
  206. * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.
  207. *
  208. * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its
  209. * finished child spans will be sent to Sentry.
  210. *
  211. * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call
  212. * `startTransaction` directly on the hub.
  213. *
  214. * @param context Properties of the new `Transaction`.
  215. * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent
  216. * default values). See {@link Options.tracesSampler}.
  217. *
  218. * @returns The transaction which was just started
  219. *
  220. * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.
  221. */
  222. function startTransaction(
  223. context,
  224. customSamplingContext,
  225. ) {
  226. // eslint-disable-next-line deprecation/deprecation
  227. return hub.getCurrentHub().startTransaction({ ...context }, customSamplingContext);
  228. }
  229. /**
  230. * Create a cron monitor check in and send it to Sentry.
  231. *
  232. * @param checkIn An object that describes a check in.
  233. * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want
  234. * to create a monitor automatically when sending a check in.
  235. */
  236. function captureCheckIn(checkIn, upsertMonitorConfig) {
  237. const scope = getCurrentScope();
  238. const client = getClient();
  239. if (!client) {
  240. debugBuild.DEBUG_BUILD && utils.logger.warn('Cannot capture check-in. No client defined.');
  241. } else if (!client.captureCheckIn) {
  242. debugBuild.DEBUG_BUILD && utils.logger.warn('Cannot capture check-in. Client does not support sending check-ins.');
  243. } else {
  244. return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);
  245. }
  246. return utils.uuid4();
  247. }
  248. /**
  249. * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.
  250. *
  251. * @param monitorSlug The distinct slug of the monitor.
  252. * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want
  253. * to create a monitor automatically when sending a check in.
  254. */
  255. function withMonitor(
  256. monitorSlug,
  257. callback,
  258. upsertMonitorConfig,
  259. ) {
  260. const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);
  261. const now = utils.timestampInSeconds();
  262. function finishCheckIn(status) {
  263. captureCheckIn({ monitorSlug, status, checkInId, duration: utils.timestampInSeconds() - now });
  264. }
  265. let maybePromiseResult;
  266. try {
  267. maybePromiseResult = callback();
  268. } catch (e) {
  269. finishCheckIn('error');
  270. throw e;
  271. }
  272. if (utils.isThenable(maybePromiseResult)) {
  273. Promise.resolve(maybePromiseResult).then(
  274. () => {
  275. finishCheckIn('ok');
  276. },
  277. () => {
  278. finishCheckIn('error');
  279. },
  280. );
  281. } else {
  282. finishCheckIn('ok');
  283. }
  284. return maybePromiseResult;
  285. }
  286. /**
  287. * Call `flush()` on the current client, if there is one. See {@link Client.flush}.
  288. *
  289. * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause
  290. * the client to wait until all events are sent before resolving the promise.
  291. * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
  292. * doesn't (or if there's no client defined).
  293. */
  294. async function flush(timeout) {
  295. const client = getClient();
  296. if (client) {
  297. return client.flush(timeout);
  298. }
  299. debugBuild.DEBUG_BUILD && utils.logger.warn('Cannot flush events. No client defined.');
  300. return Promise.resolve(false);
  301. }
  302. /**
  303. * Call `close()` on the current client, if there is one. See {@link Client.close}.
  304. *
  305. * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this
  306. * parameter will cause the client to wait until all events are sent before disabling itself.
  307. * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
  308. * doesn't (or if there's no client defined).
  309. */
  310. async function close(timeout) {
  311. const client = getClient();
  312. if (client) {
  313. return client.close(timeout);
  314. }
  315. debugBuild.DEBUG_BUILD && utils.logger.warn('Cannot flush events and disable SDK. No client defined.');
  316. return Promise.resolve(false);
  317. }
  318. /**
  319. * This is the getter for lastEventId.
  320. *
  321. * @returns The last event id of a captured event.
  322. * @deprecated This function will be removed in the next major version of the Sentry SDK.
  323. */
  324. function lastEventId() {
  325. // eslint-disable-next-line deprecation/deprecation
  326. return hub.getCurrentHub().lastEventId();
  327. }
  328. /**
  329. * Get the currently active client.
  330. */
  331. function getClient() {
  332. // eslint-disable-next-line deprecation/deprecation
  333. return hub.getCurrentHub().getClient();
  334. }
  335. /**
  336. * Returns true if Sentry has been properly initialized.
  337. */
  338. function isInitialized() {
  339. return !!getClient();
  340. }
  341. /**
  342. * Get the currently active scope.
  343. */
  344. function getCurrentScope() {
  345. // eslint-disable-next-line deprecation/deprecation
  346. return hub.getCurrentHub().getScope();
  347. }
  348. /**
  349. * Start a session on the current isolation scope.
  350. *
  351. * @param context (optional) additional properties to be applied to the returned session object
  352. *
  353. * @returns the new active session
  354. */
  355. function startSession(context) {
  356. const client = getClient();
  357. const isolationScope = hub.getIsolationScope();
  358. const currentScope = getCurrentScope();
  359. const { release, environment = constants.DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};
  360. // Will fetch userAgent if called from browser sdk
  361. const { userAgent } = utils.GLOBAL_OBJ.navigator || {};
  362. const session$1 = session.makeSession({
  363. release,
  364. environment,
  365. user: currentScope.getUser() || isolationScope.getUser(),
  366. ...(userAgent && { userAgent }),
  367. ...context,
  368. });
  369. // End existing session if there's one
  370. const currentSession = isolationScope.getSession();
  371. if (currentSession && currentSession.status === 'ok') {
  372. session.updateSession(currentSession, { status: 'exited' });
  373. }
  374. endSession();
  375. // Afterwards we set the new session on the scope
  376. isolationScope.setSession(session$1);
  377. // TODO (v8): Remove this and only use the isolation scope(?).
  378. // For v7 though, we can't "soft-break" people using getCurrentHub().getScope().setSession()
  379. currentScope.setSession(session$1);
  380. return session$1;
  381. }
  382. /**
  383. * End the session on the current isolation scope.
  384. */
  385. function endSession() {
  386. const isolationScope = hub.getIsolationScope();
  387. const currentScope = getCurrentScope();
  388. const session$1 = currentScope.getSession() || isolationScope.getSession();
  389. if (session$1) {
  390. session.closeSession(session$1);
  391. }
  392. _sendSessionUpdate();
  393. // the session is over; take it off of the scope
  394. isolationScope.setSession();
  395. // TODO (v8): Remove this and only use the isolation scope(?).
  396. // For v7 though, we can't "soft-break" people using getCurrentHub().getScope().setSession()
  397. currentScope.setSession();
  398. }
  399. /**
  400. * Sends the current Session on the scope
  401. */
  402. function _sendSessionUpdate() {
  403. const isolationScope = hub.getIsolationScope();
  404. const currentScope = getCurrentScope();
  405. const client = getClient();
  406. // TODO (v8): Remove currentScope and only use the isolation scope(?).
  407. // For v7 though, we can't "soft-break" people using getCurrentHub().getScope().setSession()
  408. const session = currentScope.getSession() || isolationScope.getSession();
  409. if (session && client && client.captureSession) {
  410. client.captureSession(session);
  411. }
  412. }
  413. /**
  414. * Sends the current session on the scope to Sentry
  415. *
  416. * @param end If set the session will be marked as exited and removed from the scope.
  417. * Defaults to `false`.
  418. */
  419. function captureSession(end = false) {
  420. // both send the update and pull the session from the scope
  421. if (end) {
  422. endSession();
  423. return;
  424. }
  425. // only send the update
  426. _sendSessionUpdate();
  427. }
  428. exports.addBreadcrumb = addBreadcrumb;
  429. exports.captureCheckIn = captureCheckIn;
  430. exports.captureEvent = captureEvent;
  431. exports.captureException = captureException;
  432. exports.captureMessage = captureMessage;
  433. exports.captureSession = captureSession;
  434. exports.close = close;
  435. exports.configureScope = configureScope;
  436. exports.endSession = endSession;
  437. exports.flush = flush;
  438. exports.getClient = getClient;
  439. exports.getCurrentScope = getCurrentScope;
  440. exports.isInitialized = isInitialized;
  441. exports.lastEventId = lastEventId;
  442. exports.setContext = setContext;
  443. exports.setExtra = setExtra;
  444. exports.setExtras = setExtras;
  445. exports.setTag = setTag;
  446. exports.setTags = setTags;
  447. exports.setUser = setUser;
  448. exports.startSession = startSession;
  449. exports.startTransaction = startTransaction;
  450. exports.withActiveSpan = withActiveSpan;
  451. exports.withIsolationScope = withIsolationScope;
  452. exports.withMonitor = withMonitor;
  453. exports.withScope = withScope;
  454. //# sourceMappingURL=exports.js.map