exports.js 15 KB

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