@sentry/opentelemetry 8.0.0-alpha.1 → 8.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/README.md +2 -1
  2. package/cjs/index.js +2120 -55
  3. package/cjs/index.js.map +1 -1
  4. package/esm/index.js +2091 -22
  5. package/esm/index.js.map +1 -1
  6. package/esm/package.json +1 -0
  7. package/package.json +18 -5
  8. package/types/asyncContextStrategy.d.ts.map +1 -1
  9. package/types/constants.d.ts +3 -5
  10. package/types/constants.d.ts.map +1 -1
  11. package/types/contextManager.d.ts.map +1 -1
  12. package/types/custom/getCurrentHub.d.ts.map +1 -1
  13. package/types/index.d.ts +6 -7
  14. package/types/index.d.ts.map +1 -1
  15. package/types/propagator.d.ts +26 -2
  16. package/types/propagator.d.ts.map +1 -1
  17. package/types/sampler.d.ts.map +1 -1
  18. package/types/semanticAttributes.d.ts +2 -7
  19. package/types/semanticAttributes.d.ts.map +1 -1
  20. package/types/setupEventContextTrace.d.ts.map +1 -1
  21. package/types/spanExporter.d.ts.map +1 -1
  22. package/types/spanProcessor.d.ts.map +1 -1
  23. package/types/trace.d.ts +14 -1
  24. package/types/trace.d.ts.map +1 -1
  25. package/types/types.d.ts +3 -4
  26. package/types/types.d.ts.map +1 -1
  27. package/types/utils/captureExceptionForTimedEvent.d.ts +1 -2
  28. package/types/utils/captureExceptionForTimedEvent.d.ts.map +1 -1
  29. package/types/utils/contextData.d.ts +1 -21
  30. package/types/utils/contextData.d.ts.map +1 -1
  31. package/types/utils/dynamicSamplingContext.d.ts.map +1 -1
  32. package/types/utils/getActiveSpan.d.ts +0 -5
  33. package/types/utils/getActiveSpan.d.ts.map +1 -1
  34. package/types/utils/groupSpansWithParents.d.ts.map +1 -1
  35. package/types/utils/mapStatus.d.ts +2 -2
  36. package/types/utils/mapStatus.d.ts.map +1 -1
  37. package/types/utils/setupCheck.d.ts +9 -0
  38. package/types/utils/setupCheck.d.ts.map +1 -0
  39. package/types/utils/spanData.d.ts +1 -14
  40. package/types/utils/spanData.d.ts.map +1 -1
  41. package/types-ts3.8/constants.d.ts +3 -5
  42. package/types-ts3.8/index.d.ts +6 -7
  43. package/types-ts3.8/propagator.d.ts +26 -2
  44. package/types-ts3.8/semanticAttributes.d.ts +2 -7
  45. package/types-ts3.8/trace.d.ts +14 -1
  46. package/types-ts3.8/types.d.ts +3 -4
  47. package/types-ts3.8/utils/captureExceptionForTimedEvent.d.ts +1 -2
  48. package/types-ts3.8/utils/contextData.d.ts +1 -21
  49. package/types-ts3.8/utils/getActiveSpan.d.ts +0 -5
  50. package/types-ts3.8/utils/mapStatus.d.ts +2 -2
  51. package/types-ts3.8/utils/setupCheck.d.ts +9 -0
  52. package/types-ts3.8/utils/spanData.d.ts +1 -14
  53. package/cjs/asyncContextStrategy.js +0 -114
  54. package/cjs/asyncContextStrategy.js.map +0 -1
  55. package/cjs/constants.js +0 -32
  56. package/cjs/constants.js.map +0 -1
  57. package/cjs/contextManager.js +0 -82
  58. package/cjs/contextManager.js.map +0 -1
  59. package/cjs/custom/client.js +0 -64
  60. package/cjs/custom/client.js.map +0 -1
  61. package/cjs/custom/getCurrentHub.js +0 -106
  62. package/cjs/custom/getCurrentHub.js.map +0 -1
  63. package/cjs/custom/hub.js +0 -13
  64. package/cjs/custom/hub.js.map +0 -1
  65. package/cjs/custom/hubextensions.js +0 -37
  66. package/cjs/custom/hubextensions.js.map +0 -1
  67. package/cjs/custom/transaction.js +0 -26
  68. package/cjs/custom/transaction.js.map +0 -1
  69. package/cjs/debug-build.js +0 -11
  70. package/cjs/debug-build.js.map +0 -1
  71. package/cjs/propagator.js +0 -159
  72. package/cjs/propagator.js.map +0 -1
  73. package/cjs/sampler.js +0 -186
  74. package/cjs/sampler.js.map +0 -1
  75. package/cjs/semanticAttributes.js +0 -12
  76. package/cjs/semanticAttributes.js.map +0 -1
  77. package/cjs/setupEventContextTrace.js +0 -40
  78. package/cjs/setupEventContextTrace.js.map +0 -1
  79. package/cjs/spanExporter.js +0 -314
  80. package/cjs/spanExporter.js.map +0 -1
  81. package/cjs/spanProcessor.js +0 -95
  82. package/cjs/spanProcessor.js.map +0 -1
  83. package/cjs/trace.js +0 -222
  84. package/cjs/trace.js.map +0 -1
  85. package/cjs/utils/addOriginToSpan.js +0 -11
  86. package/cjs/utils/addOriginToSpan.js.map +0 -1
  87. package/cjs/utils/captureExceptionForTimedEvent.js +0 -59
  88. package/cjs/utils/captureExceptionForTimedEvent.js.map +0 -1
  89. package/cjs/utils/contextData.js +0 -79
  90. package/cjs/utils/contextData.js.map +0 -1
  91. package/cjs/utils/convertOtelTimeToSeconds.js +0 -9
  92. package/cjs/utils/convertOtelTimeToSeconds.js.map +0 -1
  93. package/cjs/utils/dynamicSamplingContext.js +0 -64
  94. package/cjs/utils/dynamicSamplingContext.js.map +0 -1
  95. package/cjs/utils/getActiveSpan.js +0 -29
  96. package/cjs/utils/getActiveSpan.js.map +0 -1
  97. package/cjs/utils/getRequestSpanData.js +0 -48
  98. package/cjs/utils/getRequestSpanData.js.map +0 -1
  99. package/cjs/utils/getSpanKind.js +0 -21
  100. package/cjs/utils/getSpanKind.js.map +0 -1
  101. package/cjs/utils/groupSpansWithParents.js +0 -74
  102. package/cjs/utils/groupSpansWithParents.js.map +0 -1
  103. package/cjs/utils/isSentryRequest.js +0 -29
  104. package/cjs/utils/isSentryRequest.js.map +0 -1
  105. package/cjs/utils/mapStatus.js +0 -76
  106. package/cjs/utils/mapStatus.js.map +0 -1
  107. package/cjs/utils/parseSpanDescription.js +0 -158
  108. package/cjs/utils/parseSpanDescription.js.map +0 -1
  109. package/cjs/utils/spanData.js +0 -72
  110. package/cjs/utils/spanData.js.map +0 -1
  111. package/cjs/utils/spanTypes.js +0 -77
  112. package/cjs/utils/spanTypes.js.map +0 -1
  113. package/esm/asyncContextStrategy.js +0 -112
  114. package/esm/asyncContextStrategy.js.map +0 -1
  115. package/esm/constants.js +0 -22
  116. package/esm/constants.js.map +0 -1
  117. package/esm/contextManager.js +0 -77
  118. package/esm/contextManager.js.map +0 -1
  119. package/esm/custom/client.js +0 -59
  120. package/esm/custom/client.js.map +0 -1
  121. package/esm/custom/getCurrentHub.js +0 -101
  122. package/esm/custom/getCurrentHub.js.map +0 -1
  123. package/esm/custom/hub.js +0 -11
  124. package/esm/custom/hub.js.map +0 -1
  125. package/esm/custom/hubextensions.js +0 -35
  126. package/esm/custom/hubextensions.js.map +0 -1
  127. package/esm/custom/transaction.js +0 -24
  128. package/esm/custom/transaction.js.map +0 -1
  129. package/esm/debug-build.js +0 -9
  130. package/esm/debug-build.js.map +0 -1
  131. package/esm/propagator.js +0 -154
  132. package/esm/propagator.js.map +0 -1
  133. package/esm/sampler.js +0 -184
  134. package/esm/sampler.js.map +0 -1
  135. package/esm/semanticAttributes.js +0 -10
  136. package/esm/semanticAttributes.js.map +0 -1
  137. package/esm/setupEventContextTrace.js +0 -38
  138. package/esm/setupEventContextTrace.js.map +0 -1
  139. package/esm/spanExporter.js +0 -312
  140. package/esm/spanExporter.js.map +0 -1
  141. package/esm/spanProcessor.js +0 -93
  142. package/esm/spanProcessor.js.map +0 -1
  143. package/esm/trace.js +0 -217
  144. package/esm/trace.js.map +0 -1
  145. package/esm/utils/addOriginToSpan.js +0 -9
  146. package/esm/utils/addOriginToSpan.js.map +0 -1
  147. package/esm/utils/captureExceptionForTimedEvent.js +0 -57
  148. package/esm/utils/captureExceptionForTimedEvent.js.map +0 -1
  149. package/esm/utils/contextData.js +0 -70
  150. package/esm/utils/contextData.js.map +0 -1
  151. package/esm/utils/convertOtelTimeToSeconds.js +0 -7
  152. package/esm/utils/convertOtelTimeToSeconds.js.map +0 -1
  153. package/esm/utils/dynamicSamplingContext.js +0 -59
  154. package/esm/utils/dynamicSamplingContext.js.map +0 -1
  155. package/esm/utils/getActiveSpan.js +0 -26
  156. package/esm/utils/getActiveSpan.js.map +0 -1
  157. package/esm/utils/getRequestSpanData.js +0 -46
  158. package/esm/utils/getRequestSpanData.js.map +0 -1
  159. package/esm/utils/getSpanKind.js +0 -19
  160. package/esm/utils/getSpanKind.js.map +0 -1
  161. package/esm/utils/groupSpansWithParents.js +0 -72
  162. package/esm/utils/groupSpansWithParents.js.map +0 -1
  163. package/esm/utils/isSentryRequest.js +0 -27
  164. package/esm/utils/isSentryRequest.js.map +0 -1
  165. package/esm/utils/mapStatus.js +0 -74
  166. package/esm/utils/mapStatus.js.map +0 -1
  167. package/esm/utils/parseSpanDescription.js +0 -154
  168. package/esm/utils/parseSpanDescription.js.map +0 -1
  169. package/esm/utils/spanData.js +0 -63
  170. package/esm/utils/spanData.js.map +0 -1
  171. package/esm/utils/spanTypes.js +0 -70
  172. package/esm/utils/spanTypes.js.map +0 -1
  173. package/types/custom/hubextensions.d.ts +0 -5
  174. package/types/custom/hubextensions.d.ts.map +0 -1
  175. package/types/custom/transaction.d.ts +0 -8
  176. package/types/custom/transaction.d.ts.map +0 -1
  177. package/types-ts3.8/custom/hubextensions.d.ts +0 -5
  178. package/types-ts3.8/custom/transaction.d.ts +0 -8
package/cjs/index.js CHANGED
@@ -1,69 +1,2134 @@
1
+ var {
2
+ _optionalChain
3
+ } = require('@sentry/utils');
4
+
1
5
  Object.defineProperty(exports, '__esModule', { value: true });
2
6
 
3
- const addOriginToSpan = require('./utils/addOriginToSpan.js');
4
- const captureExceptionForTimedEvent = require('./utils/captureExceptionForTimedEvent.js');
5
- const getRequestSpanData = require('./utils/getRequestSpanData.js');
6
- const client = require('./custom/client.js');
7
- const getSpanKind = require('./utils/getSpanKind.js');
8
- const spanData = require('./utils/spanData.js');
9
- const contextData = require('./utils/contextData.js');
10
- const spanTypes = require('./utils/spanTypes.js');
11
- const isSentryRequest = require('./utils/isSentryRequest.js');
12
- const getActiveSpan = require('./utils/getActiveSpan.js');
13
- const trace = require('./trace.js');
14
- const hub = require('./custom/hub.js');
15
- const getCurrentHub = require('./custom/getCurrentHub.js');
16
- const hubextensions = require('./custom/hubextensions.js');
17
- const setupEventContextTrace = require('./setupEventContextTrace.js');
18
- const asyncContextStrategy = require('./asyncContextStrategy.js');
19
- const contextManager = require('./contextManager.js');
20
- const propagator = require('./propagator.js');
21
- const spanProcessor = require('./spanProcessor.js');
22
- const sampler = require('./sampler.js');
7
+ const semanticConventions = require('@opentelemetry/semantic-conventions');
23
8
  const core = require('@sentry/core');
9
+ const utils = require('@sentry/utils');
10
+ const api = require('@opentelemetry/api');
11
+ const core$1 = require('@opentelemetry/core');
12
+ const sdkTraceBase = require('@opentelemetry/sdk-trace-base');
13
+
14
+ /**
15
+ * Maybe capture a Sentry exception for an OTEL timed event.
16
+ * This will check if the event is exception-like and in that case capture it as an exception.
17
+ */
18
+ function maybeCaptureExceptionForTimedEvent(event, otelSpan) {
19
+ if (event.name !== 'exception') {
20
+ return;
21
+ }
22
+
23
+ const attributes = event.attributes;
24
+ if (!attributes) {
25
+ return;
26
+ }
27
+
28
+ const message = attributes[semanticConventions.SemanticAttributes.EXCEPTION_MESSAGE];
29
+
30
+ if (typeof message !== 'string') {
31
+ return;
32
+ }
33
+
34
+ const syntheticError = new Error(message);
35
+
36
+ const stack = attributes[semanticConventions.SemanticAttributes.EXCEPTION_STACKTRACE];
37
+ if (utils.isString(stack)) {
38
+ syntheticError.stack = stack;
39
+ }
40
+
41
+ const type = attributes[semanticConventions.SemanticAttributes.EXCEPTION_TYPE];
42
+ if (utils.isString(type)) {
43
+ syntheticError.name = type;
44
+ }
45
+
46
+ core.captureException(syntheticError, {
47
+ captureContext: otelSpan
48
+ ? {
49
+ contexts: {
50
+ otel: {
51
+ attributes: otelSpan.attributes,
52
+ resource: otelSpan.resource.attributes,
53
+ },
54
+ trace: {
55
+ trace_id: otelSpan.spanContext().traceId,
56
+ span_id: otelSpan.spanContext().spanId,
57
+ parent_span_id: otelSpan.parentSpanId,
58
+ },
59
+ },
60
+ }
61
+ : undefined,
62
+ });
63
+ }
64
+
65
+ /**
66
+ * Check if a given span has attributes.
67
+ * This is necessary because the base `Span` type does not have attributes,
68
+ * so in places where we are passed a generic span, we need to check if we want to access them.
69
+ */
70
+ function spanHasAttributes(
71
+ span,
72
+ ) {
73
+ const castSpan = span ;
74
+ return !!castSpan.attributes && typeof castSpan.attributes === 'object';
75
+ }
76
+
77
+ /**
78
+ * Check if a given span has a kind.
79
+ * This is necessary because the base `Span` type does not have a kind,
80
+ * so in places where we are passed a generic span, we need to check if we want to access it.
81
+ */
82
+ function spanHasKind(span) {
83
+ const castSpan = span ;
84
+ return !!castSpan.kind;
85
+ }
86
+
87
+ /**
88
+ * Check if a given span has a status.
89
+ * This is necessary because the base `Span` type does not have a status,
90
+ * so in places where we are passed a generic span, we need to check if we want to access it.
91
+ */
92
+ function spanHasStatus(
93
+ span,
94
+ ) {
95
+ const castSpan = span ;
96
+ return !!castSpan.status;
97
+ }
98
+
99
+ /**
100
+ * Check if a given span has a name.
101
+ * This is necessary because the base `Span` type does not have a name,
102
+ * so in places where we are passed a generic span, we need to check if we want to access it.
103
+ */
104
+ function spanHasName(span) {
105
+ const castSpan = span ;
106
+ return !!castSpan.name;
107
+ }
108
+
109
+ /**
110
+ * Check if a given span has a kind.
111
+ * This is necessary because the base `Span` type does not have a kind,
112
+ * so in places where we are passed a generic span, we need to check if we want to access it.
113
+ */
114
+ function spanHasParentId(
115
+ span,
116
+ ) {
117
+ const castSpan = span ;
118
+ return !!castSpan.parentSpanId;
119
+ }
120
+
121
+ /**
122
+ * Check if a given span has events.
123
+ * This is necessary because the base `Span` type does not have events,
124
+ * so in places where we are passed a generic span, we need to check if we want to access it.
125
+ */
126
+ function spanHasEvents(
127
+ span,
128
+ ) {
129
+ const castSpan = span ;
130
+ return Array.isArray(castSpan.events);
131
+ }
132
+
133
+ /**
134
+ * Get sanitizied request data from an OTEL span.
135
+ */
136
+ function getRequestSpanData(span) {
137
+ // The base `Span` type has no `attributes`, so we need to guard here against that
138
+ if (!spanHasAttributes(span)) {
139
+ return {};
140
+ }
141
+
142
+ const data = {
143
+ url: span.attributes[semanticConventions.SemanticAttributes.HTTP_URL] ,
144
+ 'http.method': span.attributes[semanticConventions.SemanticAttributes.HTTP_METHOD] ,
145
+ };
146
+
147
+ // Default to GET if URL is set but method is not
148
+ if (!data['http.method'] && data.url) {
149
+ data['http.method'] = 'GET';
150
+ }
151
+
152
+ try {
153
+ const urlStr = span.attributes[semanticConventions.SemanticAttributes.HTTP_URL];
154
+ if (typeof urlStr === 'string') {
155
+ const url = utils.parseUrl(urlStr);
156
+
157
+ data.url = utils.getSanitizedUrlString(url);
158
+
159
+ if (url.search) {
160
+ data['http.query'] = url.search;
161
+ }
162
+ if (url.hash) {
163
+ data['http.fragment'] = url.hash;
164
+ }
165
+ }
166
+ } catch (e) {
167
+ // ignore
168
+ }
169
+
170
+ return data;
171
+ }
172
+
173
+ function _optionalChain$8(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
174
+
175
+ // Typescript complains if we do not use `...args: any[]` for the mixin, with:
176
+ // A mixin class must have a constructor with a single rest parameter of type 'any[]'.ts(2545)
177
+ /* eslint-disable @typescript-eslint/no-explicit-any */
178
+
179
+ /**
180
+ * Wrap an Client with things we need for OpenTelemetry support.
181
+ *
182
+ * Usage:
183
+ * const OpenTelemetryClient = getWrappedClientClass(NodeClient);
184
+ * const client = new OpenTelemetryClient(options);
185
+ */
186
+ function wrapClientClass
187
+
188
+ (ClientClass) {
189
+ class OpenTelemetryClient extends ClientClass {
190
+
191
+ constructor(...args) {
192
+ super(...args);
193
+ }
194
+
195
+ /** Get the OTEL tracer. */
196
+ get tracer() {
197
+ if (this._tracer) {
198
+ return this._tracer;
199
+ }
200
+
201
+ const name = '@sentry/opentelemetry';
202
+ const version = core.SDK_VERSION;
203
+ const tracer = api.trace.getTracer(name, version);
204
+ this._tracer = tracer;
205
+
206
+ return tracer;
207
+ }
208
+
209
+ /**
210
+ * @inheritDoc
211
+ */
212
+ async flush(timeout) {
213
+ const provider = this.traceProvider;
214
+ const spanProcessor = _optionalChain$8([provider, 'optionalAccess', _ => _.activeSpanProcessor]);
215
+
216
+ if (spanProcessor) {
217
+ await spanProcessor.forceFlush();
218
+ }
219
+
220
+ return super.flush(timeout);
221
+ }
222
+ }
223
+
224
+ return OpenTelemetryClient ;
225
+ }
226
+ /* eslint-enable @typescript-eslint/no-explicit-any */
227
+
228
+ /**
229
+ * Get the span kind from a span.
230
+ * For whatever reason, this is not public API on the generic "Span" type,
231
+ * so we need to check if we actually have a `SDKTraceBaseSpan` where we can fetch this from.
232
+ * Otherwise, we fall back to `SpanKind.INTERNAL`.
233
+ */
234
+ function getSpanKind(span) {
235
+ if (spanHasKind(span)) {
236
+ return span.kind;
237
+ }
238
+
239
+ return api.SpanKind.INTERNAL;
240
+ }
241
+
242
+ // We store the parent span, scopes & metadata in separate weakmaps, so we can access them for a given span
243
+ // This way we can enhance the data that an OTEL Span natively gives us
244
+ // and since we are using weakmaps, we do not need to clean up after ourselves
245
+ const SpanScopes = new WeakMap
246
+
247
+ ();
248
+
249
+ /**
250
+ * Set the Sentry scope to be used for finishing a given OTEL span.
251
+ * This is different from `setCapturedScopesOnSpan`, as that works on _sentry_ spans,
252
+ * while here we are basically "caching" this on the otel spans.
253
+ */
254
+ function setSpanScopes(
255
+ span,
256
+ scopes
257
+
258
+ ,
259
+ ) {
260
+ SpanScopes.set(span, scopes);
261
+ }
262
+
263
+ /** Get the Sentry scopes to use for finishing an OTEL span. */
264
+ function getSpanScopes(span)
265
+
266
+ {
267
+ return SpanScopes.get(span);
268
+ }
269
+
270
+ const SENTRY_TRACE_HEADER = 'sentry-trace';
271
+ const SENTRY_BAGGAGE_HEADER = 'baggage';
272
+
273
+ const SENTRY_TRACE_STATE_DSC = 'sentry.dsc';
274
+ const SENTRY_TRACE_STATE_PARENT_SPAN_ID = 'sentry.parent_span_id';
275
+ const SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING = 'sentry.sampled_not_recording';
276
+
277
+ const SENTRY_SCOPES_CONTEXT_KEY = api.createContextKey('sentry_scopes');
278
+
279
+ const SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY = api.createContextKey('sentry_fork_isolation_scope');
280
+
281
+ const SENTRY_FORK_SET_SCOPE_CONTEXT_KEY = api.createContextKey('sentry_fork_set_scope');
282
+
283
+ const SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY = api.createContextKey('sentry_fork_set_isolation_scope');
284
+
285
+ const SCOPE_CONTEXT_MAP = new WeakMap();
286
+
287
+ /**
288
+ * Try to get the current scopes from the given OTEL context.
289
+ * This requires a Context Manager that was wrapped with getWrappedContextManager.
290
+ */
291
+ function getScopesFromContext(context) {
292
+ return context.getValue(SENTRY_SCOPES_CONTEXT_KEY) ;
293
+ }
294
+
295
+ /**
296
+ * Set the current scopes on an OTEL context.
297
+ * This will return a forked context with the Propagation Context set.
298
+ */
299
+ function setScopesOnContext(context, scopes) {
300
+ return context.setValue(SENTRY_SCOPES_CONTEXT_KEY, scopes);
301
+ }
302
+
303
+ /**
304
+ * Set the context on the scope so we can later look it up.
305
+ * We need this to get the context from the scope in the `trace` functions.
306
+ */
307
+ function setContextOnScope(scope, context) {
308
+ SCOPE_CONTEXT_MAP.set(scope, context);
309
+ }
310
+
311
+ /**
312
+ * Get the context related to a scope.
313
+ * TODO v8: Use this for the `trace` functions.
314
+ * */
315
+ function getContextFromScope(scope) {
316
+ return SCOPE_CONTEXT_MAP.get(scope);
317
+ }
318
+
319
+ const setupElements = new Set();
320
+
321
+ /** Get all the OpenTelemetry elements that have been set up. */
322
+ function openTelemetrySetupCheck() {
323
+ return Array.from(setupElements);
324
+ }
325
+
326
+ /** Mark an OpenTelemetry element as setup. */
327
+ function setIsSetup(element) {
328
+ setupElements.add(element);
329
+ }
330
+
331
+ function _optionalChain$7(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
332
+
333
+ /** Get the Sentry propagation context from a span context. */
334
+ function getPropagationContextFromSpanContext(spanContext) {
335
+ const { traceId, spanId, traceState } = spanContext;
336
+
337
+ const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
338
+ const dsc = dscString ? utils.baggageHeaderToDynamicSamplingContext(dscString) : undefined;
339
+ const parentSpanId = traceState ? traceState.get(SENTRY_TRACE_STATE_PARENT_SPAN_ID) : undefined;
340
+
341
+ const sampled = getSamplingDecision(spanContext);
342
+
343
+ return {
344
+ traceId,
345
+ spanId,
346
+ sampled,
347
+ parentSpanId,
348
+ dsc,
349
+ };
350
+ }
351
+
352
+ /**
353
+ * Injects and extracts `sentry-trace` and `baggage` headers from carriers.
354
+ */
355
+ class SentryPropagator extends core$1.W3CBaggagePropagator {
356
+ constructor() {
357
+ super();
358
+ setIsSetup('SentryPropagator');
359
+ }
360
+
361
+ /**
362
+ * @inheritDoc
363
+ */
364
+ inject(context, carrier, setter) {
365
+ if (core$1.isTracingSuppressed(context)) {
366
+ return;
367
+ }
368
+
369
+ let baggage = api.propagation.getBaggage(context) || api.propagation.createBaggage({});
370
+
371
+ const { dynamicSamplingContext, traceId, spanId, sampled } = getInjectionData(context);
372
+
373
+ if (dynamicSamplingContext) {
374
+ baggage = Object.entries(dynamicSamplingContext).reduce((b, [dscKey, dscValue]) => {
375
+ if (dscValue) {
376
+ return b.setEntry(`${utils.SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`, { value: dscValue });
377
+ }
378
+ return b;
379
+ }, baggage);
380
+ }
381
+
382
+ setter.set(carrier, SENTRY_TRACE_HEADER, utils.generateSentryTraceHeader(traceId, spanId, sampled));
383
+
384
+ super.inject(api.propagation.setBaggage(context, baggage), carrier, setter);
385
+ }
386
+
387
+ /**
388
+ * @inheritDoc
389
+ */
390
+ extract(context, carrier, getter) {
391
+ const maybeSentryTraceHeader = getter.get(carrier, SENTRY_TRACE_HEADER);
392
+ const baggage = getter.get(carrier, SENTRY_BAGGAGE_HEADER);
393
+
394
+ const sentryTrace = maybeSentryTraceHeader
395
+ ? Array.isArray(maybeSentryTraceHeader)
396
+ ? maybeSentryTraceHeader[0]
397
+ : maybeSentryTraceHeader
398
+ : undefined;
399
+
400
+ const propagationContext = utils.propagationContextFromHeaders(sentryTrace, baggage);
401
+
402
+ // Add remote parent span context,
403
+ const ctxWithSpanContext = getContextWithRemoteActiveSpan(context, { sentryTrace, baggage });
404
+
405
+ // Also update the scope on the context (to be sure this is picked up everywhere)
406
+ const scopes = getScopesFromContext(ctxWithSpanContext);
407
+ const newScopes = {
408
+ scope: scopes ? scopes.scope.clone() : core.getCurrentScope().clone(),
409
+ isolationScope: scopes ? scopes.isolationScope : core.getIsolationScope(),
410
+ };
411
+ newScopes.scope.setPropagationContext(propagationContext);
412
+
413
+ return setScopesOnContext(ctxWithSpanContext, newScopes);
414
+ }
415
+
416
+ /**
417
+ * @inheritDoc
418
+ */
419
+ fields() {
420
+ return [SENTRY_TRACE_HEADER, SENTRY_BAGGAGE_HEADER];
421
+ }
422
+ }
423
+
424
+ /** Exported for tests. */
425
+ function makeTraceState({
426
+ parentSpanId,
427
+ dsc,
428
+ sampled,
429
+ }
430
+
431
+ ) {
432
+ if (!parentSpanId && !dsc && sampled !== false) {
433
+ return undefined;
434
+ }
435
+
436
+ // We store the DSC as OTEL trace state on the span context
437
+ const dscString = dsc ? utils.dynamicSamplingContextToSentryBaggageHeader(dsc) : undefined;
438
+
439
+ const traceStateBase = parentSpanId
440
+ ? new core$1.TraceState().set(SENTRY_TRACE_STATE_PARENT_SPAN_ID, parentSpanId)
441
+ : new core$1.TraceState();
442
+
443
+ const traceStateWithDsc = dscString ? traceStateBase.set(SENTRY_TRACE_STATE_DSC, dscString) : traceStateBase;
444
+
445
+ // We also specifically want to store if this is sampled to be not recording,
446
+ // or unsampled (=could be either sampled or not)
447
+ return sampled === false ? traceStateWithDsc.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1') : traceStateWithDsc;
448
+ }
449
+
450
+ function getInjectionData(context)
451
+
452
+ {
453
+ const span = api.trace.getSpan(context);
454
+ const spanIsRemote = _optionalChain$7([span, 'optionalAccess', _ => _.spanContext, 'call', _2 => _2(), 'access', _3 => _3.isRemote]);
455
+
456
+ // If we have a local span, we can just pick everything from it
457
+ if (span && !spanIsRemote) {
458
+ const spanContext = span.spanContext();
459
+ const propagationContext = getPropagationContextFromSpanContext(spanContext);
460
+ const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
461
+ return {
462
+ dynamicSamplingContext,
463
+ traceId: spanContext.traceId,
464
+ spanId: spanContext.spanId,
465
+ sampled: getSamplingDecision(spanContext),
466
+ };
467
+ }
468
+
469
+ // Else we try to use the propagation context from the scope
470
+ const scope = _optionalChain$7([getScopesFromContext, 'call', _4 => _4(context), 'optionalAccess', _5 => _5.scope]);
471
+ if (scope) {
472
+ const propagationContext = scope.getPropagationContext();
473
+ const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, propagationContext.traceId);
474
+ return {
475
+ dynamicSamplingContext,
476
+ traceId: propagationContext.traceId,
477
+ spanId: propagationContext.spanId,
478
+ sampled: propagationContext.sampled,
479
+ };
480
+ }
481
+
482
+ // Else, we look at the remote span context
483
+ const spanContext = api.trace.getSpanContext(context);
484
+ if (spanContext) {
485
+ const propagationContext = getPropagationContextFromSpanContext(spanContext);
486
+ const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
487
+
488
+ return {
489
+ dynamicSamplingContext,
490
+ traceId: spanContext.traceId,
491
+ spanId: spanContext.spanId,
492
+ sampled: getSamplingDecision(spanContext),
493
+ };
494
+ }
495
+
496
+ // If we have neither, there is nothing much we can do, but that should not happen usually
497
+ // Unless there is a detached OTEL context being passed around
498
+ return {
499
+ dynamicSamplingContext: undefined,
500
+ traceId: undefined,
501
+ spanId: undefined,
502
+ sampled: undefined,
503
+ };
504
+ }
505
+
506
+ /** Get the DSC from a context, or fall back to use the one from the client. */
507
+ function getDynamicSamplingContext(
508
+ propagationContext,
509
+ traceId,
510
+ ) {
511
+ // If we have a DSC on the propagation context, we just use it
512
+ if (_optionalChain$7([propagationContext, 'optionalAccess', _6 => _6.dsc])) {
513
+ return propagationContext.dsc;
514
+ }
515
+
516
+ // Else, we try to generate a new one
517
+ const client = core.getClient();
518
+
519
+ if (client) {
520
+ return core.getDynamicSamplingContextFromClient(traceId || propagationContext.traceId, client);
521
+ }
522
+
523
+ return undefined;
524
+ }
525
+
526
+ function getContextWithRemoteActiveSpan(
527
+ ctx,
528
+ { sentryTrace, baggage },
529
+ ) {
530
+ const propagationContext = utils.propagationContextFromHeaders(sentryTrace, baggage);
531
+
532
+ // We store the DSC as OTEL trace state on the span context
533
+ const traceState = makeTraceState({
534
+ parentSpanId: propagationContext.parentSpanId,
535
+ dsc: propagationContext.dsc,
536
+ sampled: propagationContext.sampled,
537
+ });
538
+
539
+ const spanContext = {
540
+ traceId: propagationContext.traceId,
541
+ spanId: propagationContext.parentSpanId || '',
542
+ isRemote: true,
543
+ traceFlags: propagationContext.sampled ? api.TraceFlags.SAMPLED : api.TraceFlags.NONE,
544
+ traceState,
545
+ };
546
+
547
+ return api.trace.setSpanContext(ctx, spanContext);
548
+ }
549
+
550
+ /**
551
+ * Takes trace strings and propagates them as a remote active span.
552
+ * This should be used in addition to `continueTrace` in OTEL-powered environments.
553
+ */
554
+ function continueTraceAsRemoteSpan(
555
+ ctx,
556
+ options,
557
+ callback,
558
+ ) {
559
+ const ctxWithSpanContext = getContextWithRemoteActiveSpan(ctx, options);
560
+
561
+ return api.context.with(ctxWithSpanContext, callback);
562
+ }
563
+
564
+ /**
565
+ * OpenTelemetry only knows about SAMPLED or NONE decision,
566
+ * but for us it is important to differentiate between unset and unsampled.
567
+ *
568
+ * Both of these are identified as `traceFlags === TracegFlags.NONE`,
569
+ * but we additionally look at a special trace state to differentiate between them.
570
+ */
571
+ function getSamplingDecision(spanContext) {
572
+ const { traceFlags, traceState } = spanContext;
573
+
574
+ const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === '1' : false;
575
+
576
+ // If trace flag is `SAMPLED`, we interpret this as sampled
577
+ // If it is `NONE`, it could mean either it was sampled to be not recorder, or that it was not sampled at all
578
+ // For us this is an important difference, sow e look at the SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING
579
+ // to identify which it is
580
+ if (traceFlags === api.TraceFlags.SAMPLED) {
581
+ return true;
582
+ }
583
+
584
+ if (sampledNotRecording) {
585
+ return false;
586
+ }
587
+
588
+ // Fall back to DSC as a last resort, that may also contain `sampled`...
589
+ const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
590
+ const dsc = dscString ? utils.baggageHeaderToDynamicSamplingContext(dscString) : undefined;
591
+
592
+ if (_optionalChain$7([dsc, 'optionalAccess', _7 => _7.sampled]) === 'true') {
593
+ return true;
594
+ }
595
+ if (_optionalChain$7([dsc, 'optionalAccess', _8 => _8.sampled]) === 'false') {
596
+ return false;
597
+ }
598
+
599
+ return undefined;
600
+ }
601
+
602
+ function _optionalChain$6(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
603
+ /**
604
+ * Creates a dynamic sampling context from a span (and client and scope)
605
+ *
606
+ * @param span the span from which a few values like the root span name and sample rate are extracted.
607
+ *
608
+ * @returns a dynamic sampling context
609
+ */
610
+ function getDynamicSamplingContextFromSpan(span) {
611
+ const client = core.getClient();
612
+ if (!client) {
613
+ return {};
614
+ }
615
+
616
+ const traceState = span.spanContext().traceState;
617
+ const traceStateDsc = _optionalChain$6([traceState, 'optionalAccess', _ => _.get, 'call', _2 => _2(SENTRY_TRACE_STATE_DSC)]);
618
+
619
+ // If the span has a DSC, we want it to take precedence
620
+ const dscOnSpan = traceStateDsc ? utils.baggageHeaderToDynamicSamplingContext(traceStateDsc) : undefined;
621
+
622
+ if (dscOnSpan) {
623
+ return dscOnSpan;
624
+ }
625
+
626
+ const dsc = core.getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
627
+
628
+ const attributes = spanHasAttributes(span) ? span.attributes : {};
629
+
630
+ const sampleRate = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
631
+ if (sampleRate != null) {
632
+ dsc.sample_rate = `${sampleRate}`;
633
+ }
634
+
635
+ // We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII
636
+ const source = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
637
+ const name = spanHasName(span) ? span.name : '';
638
+
639
+ if (source !== 'url' && name) {
640
+ dsc.transaction = name;
641
+ }
642
+
643
+ const sampled = getSamplingDecision(span.spanContext());
644
+ if (sampled != null) {
645
+ dsc.sampled = String(sampled);
646
+ }
647
+
648
+ client.emit('createDsc', dsc);
649
+
650
+ return dsc;
651
+ }
652
+
653
+ /**
654
+ *
655
+ * @param otelSpan Checks wheter a given OTEL Span is an http request to sentry.
656
+ * @returns boolean
657
+ */
658
+ function isSentryRequestSpan(span) {
659
+ if (!spanHasAttributes(span)) {
660
+ return false;
661
+ }
662
+
663
+ const { attributes } = span;
664
+
665
+ const httpUrl = attributes[semanticConventions.SemanticAttributes.HTTP_URL];
666
+
667
+ if (!httpUrl) {
668
+ return false;
669
+ }
670
+
671
+ return core.isSentryRequestUrl(httpUrl.toString(), core.getClient());
672
+ }
673
+
674
+ /**
675
+ * Returns the currently active span.
676
+ */
677
+ function getActiveSpan() {
678
+ return api.trace.getActiveSpan();
679
+ }
680
+
681
+ function _optionalChain$5(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
682
+
683
+ /**
684
+ * Wraps a function with a transaction/span and finishes the span after the function is done.
685
+ * The created span is the active span and will be used as parent by other spans created inside the function
686
+ * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active.
687
+ *
688
+ * If you want to create a span that is not set as active, use {@link startInactiveSpan}.
689
+ *
690
+ * Note that you'll always get a span passed to the callback, it may just be a NonRecordingSpan if the span is not sampled.
691
+ */
692
+ function startSpan(options, callback) {
693
+ const tracer = getTracer();
694
+
695
+ const { name } = options;
696
+
697
+ const activeCtx = getContext(options.scope, options.forceTransaction);
698
+ const shouldSkipSpan = options.onlyIfParent && !api.trace.getSpan(activeCtx);
699
+ const ctx = shouldSkipSpan ? core$1.suppressTracing(activeCtx) : activeCtx;
700
+
701
+ const spanContext = getSpanContext(options);
702
+
703
+ return tracer.startActiveSpan(name, spanContext, ctx, span => {
704
+ _applySentryAttributesToSpan(span, options);
705
+
706
+ return core.handleCallbackErrors(
707
+ () => callback(span),
708
+ () => {
709
+ span.setStatus({ code: api.SpanStatusCode.ERROR });
710
+ },
711
+ () => span.end(),
712
+ );
713
+ });
714
+ }
715
+
716
+ /**
717
+ * Similar to `Sentry.startSpan`. Wraps a function with a span, but does not finish the span
718
+ * after the function is done automatically. You'll have to call `span.end()` manually.
719
+ *
720
+ * The created span is the active span and will be used as parent by other spans created inside the function
721
+ * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
722
+ *
723
+ * Note that you'll always get a span passed to the callback, it may just be a NonRecordingSpan if the span is not sampled.
724
+ */
725
+ function startSpanManual(
726
+ options,
727
+ callback,
728
+ ) {
729
+ const tracer = getTracer();
730
+
731
+ const { name } = options;
732
+
733
+ const activeCtx = getContext(options.scope, options.forceTransaction);
734
+ const shouldSkipSpan = options.onlyIfParent && !api.trace.getSpan(activeCtx);
735
+ const ctx = shouldSkipSpan ? core$1.suppressTracing(activeCtx) : activeCtx;
736
+
737
+ const spanContext = getSpanContext(options);
738
+
739
+ return tracer.startActiveSpan(name, spanContext, ctx, span => {
740
+ _applySentryAttributesToSpan(span, options);
741
+
742
+ return core.handleCallbackErrors(
743
+ () => callback(span, () => span.end()),
744
+ () => {
745
+ span.setStatus({ code: api.SpanStatusCode.ERROR });
746
+ },
747
+ );
748
+ });
749
+ }
750
+
751
+ /**
752
+ * Creates a span. This span is not set as active, so will not get automatic instrumentation spans
753
+ * as children or be able to be accessed via `Sentry.getSpan()`.
754
+ *
755
+ * If you want to create a span that is set as active, use {@link startSpan}.
756
+ *
757
+ * Note that if you have not enabled tracing extensions via `addTracingExtensions`
758
+ * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans
759
+ * and the `span` returned from the callback will be undefined.
760
+ */
761
+ function startInactiveSpan(options) {
762
+ const tracer = getTracer();
763
+
764
+ const { name } = options;
765
+
766
+ const activeCtx = getContext(options.scope, options.forceTransaction);
767
+ const shouldSkipSpan = options.onlyIfParent && !api.trace.getSpan(activeCtx);
768
+ const ctx = shouldSkipSpan ? core$1.suppressTracing(activeCtx) : activeCtx;
769
+
770
+ const spanContext = getSpanContext(options);
771
+
772
+ const span = tracer.startSpan(name, spanContext, ctx);
773
+
774
+ _applySentryAttributesToSpan(span, options);
775
+
776
+ return span;
777
+ }
778
+
779
+ /**
780
+ * Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be
781
+ * passed `null` to start an entirely new span tree.
782
+ *
783
+ * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,
784
+ * spans started within the callback will not be attached to a parent span.
785
+ * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.
786
+ * @returns the value returned from the provided callback function.
787
+ */
788
+ function withActiveSpan(span, callback) {
789
+ const newContextWithActiveSpan = span ? api.trace.setSpan(api.context.active(), span) : api.trace.deleteSpan(api.context.active());
790
+ return api.context.with(newContextWithActiveSpan, () => callback(core.getCurrentScope()));
791
+ }
792
+
793
+ function getTracer() {
794
+ const client = core.getClient();
795
+ return (client && client.tracer) || api.trace.getTracer('@sentry/opentelemetry', core.SDK_VERSION);
796
+ }
797
+
798
+ function _applySentryAttributesToSpan(span, options) {
799
+ const { op } = options;
800
+
801
+ if (op) {
802
+ span.setAttribute(core.SEMANTIC_ATTRIBUTE_SENTRY_OP, op);
803
+ }
804
+ }
805
+
806
+ function getSpanContext(options) {
807
+ const { startTime, attributes, kind } = options;
808
+
809
+ // OTEL expects timestamps in ms, not seconds
810
+ const fixedStartTime = typeof startTime === 'number' ? ensureTimestampInMilliseconds(startTime) : startTime;
811
+
812
+ return {
813
+ attributes,
814
+ kind,
815
+ startTime: fixedStartTime,
816
+ };
817
+ }
818
+
819
+ function ensureTimestampInMilliseconds(timestamp) {
820
+ const isMs = timestamp < 9999999999;
821
+ return isMs ? timestamp * 1000 : timestamp;
822
+ }
823
+
824
+ function getContext(scope, forceTransaction) {
825
+ const ctx = getContextForScope(scope);
826
+ const actualScope = _optionalChain$5([getScopesFromContext, 'call', _ => _(ctx), 'optionalAccess', _2 => _2.scope]);
827
+
828
+ const parentSpan = api.trace.getSpan(ctx);
829
+
830
+ // In the case that we have no parent span, we need to "simulate" one to ensure the propagation context is correct
831
+ if (!parentSpan) {
832
+ const client = core.getClient();
833
+
834
+ if (actualScope && client) {
835
+ const propagationContext = actualScope.getPropagationContext();
836
+ const dynamicSamplingContext =
837
+ propagationContext.dsc || core.getDynamicSamplingContextFromClient(propagationContext.traceId, client);
838
+
839
+ // We store the DSC as OTEL trace state on the span context
840
+ const traceState = makeTraceState({
841
+ parentSpanId: propagationContext.parentSpanId,
842
+ dsc: dynamicSamplingContext,
843
+ sampled: propagationContext.sampled,
844
+ });
845
+
846
+ const spanContext = {
847
+ traceId: propagationContext.traceId,
848
+ spanId: propagationContext.parentSpanId || propagationContext.spanId,
849
+ isRemote: true,
850
+ traceFlags: propagationContext.sampled ? api.TraceFlags.SAMPLED : api.TraceFlags.NONE,
851
+ traceState,
852
+ };
853
+
854
+ // Add remote parent span context,
855
+ return api.trace.setSpanContext(ctx, spanContext);
856
+ }
857
+
858
+ // if we have no scope or client, we just return the context as-is
859
+ return ctx;
860
+ }
861
+
862
+ // If we don't want to force a transaction, and we have a parent span, all good, we just return as-is!
863
+ if (!forceTransaction) {
864
+ return ctx;
865
+ }
866
+
867
+ // Else, if we do have a parent span but want to force a transaction, we have to simulate a "root" context
868
+
869
+ // Else, we need to do two things:
870
+ // 1. Unset the parent span from the context, so we'll create a new root span
871
+ // 2. Ensure the propagation context is correct, so we'll continue from the parent span
872
+ const ctxWithoutSpan = api.trace.deleteSpan(ctx);
873
+
874
+ const { spanId, traceId } = parentSpan.spanContext();
875
+ const sampled = getSamplingDecision(parentSpan.spanContext());
876
+
877
+ const rootSpan = core.getRootSpan(parentSpan);
878
+ const dsc = getDynamicSamplingContextFromSpan(rootSpan);
879
+
880
+ const traceState = makeTraceState({
881
+ dsc,
882
+ parentSpanId: spanId,
883
+ sampled,
884
+ });
885
+
886
+ const spanContext = {
887
+ traceId,
888
+ spanId,
889
+ isRemote: true,
890
+ traceFlags: sampled ? api.TraceFlags.SAMPLED : api.TraceFlags.NONE,
891
+ traceState,
892
+ };
893
+
894
+ const ctxWithSpanContext = api.trace.setSpanContext(ctxWithoutSpan, spanContext);
895
+
896
+ return ctxWithSpanContext;
897
+ }
898
+
899
+ function getContextForScope(scope) {
900
+ if (scope) {
901
+ const ctx = getContextFromScope(scope);
902
+ if (ctx) {
903
+ return ctx;
904
+ }
905
+ }
906
+
907
+ return api.context.active();
908
+ }
909
+
910
+ /**
911
+ * Continue a trace from `sentry-trace` and `baggage` values.
912
+ * These values can be obtained from incoming request headers, or in the browser from `<meta name="sentry-trace">`
913
+ * and `<meta name="baggage">` HTML tags.
914
+ *
915
+ * Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically
916
+ * be attached to the incoming trace.
917
+ *
918
+ * This is a custom version of `continueTrace` that is used in OTEL-powered environments.
919
+ * It propagates the trace as a remote span, in addition to setting it on the propagation context.
920
+ */
921
+ function continueTrace(options, callback) {
922
+ return core.continueTrace(options, () => {
923
+ return continueTraceAsRemoteSpan(api.context.active(), options, callback);
924
+ });
925
+ }
926
+
927
+ /**
928
+ * Ensure the global hub is setup.
929
+ *
930
+ * @deprecated This will be removed in the next major version.
931
+ */
932
+ function setupGlobalHub() {
933
+ // noop
934
+ }
935
+
936
+ function _optionalChain$4(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
937
+
938
+ /**
939
+ * This is for legacy reasons, and returns a proxy object instead of a hub to be used.
940
+ * @deprecated Use the methods directly.
941
+ */
942
+ function getCurrentHub() {
943
+ return {
944
+ isOlderThan(_version) {
945
+ return false;
946
+ },
947
+
948
+ bindClient(client) {
949
+ const scope = core.getCurrentScope();
950
+ scope.setClient(client);
951
+ },
952
+
953
+ pushScope() {
954
+ // TODO: This does not work and is actually deprecated
955
+ return core.getCurrentScope();
956
+ },
957
+
958
+ popScope() {
959
+ // TODO: This does not work and is actually deprecated
960
+ return false;
961
+ },
962
+
963
+ withScope: core.withScope,
964
+ getClient: () => core.getClient() ,
965
+ getScope: core.getCurrentScope,
966
+ getIsolationScope: core.getIsolationScope,
967
+ captureException: (exception, hint) => {
968
+ return core.getCurrentScope().captureException(exception, hint);
969
+ },
970
+ captureMessage: (message, level, hint) => {
971
+ return core.getCurrentScope().captureMessage(message, level, hint);
972
+ },
973
+ captureEvent: core.captureEvent,
974
+ addBreadcrumb: core.addBreadcrumb,
975
+ setUser: core.setUser,
976
+ setTags: core.setTags,
977
+ setTag: core.setTag,
978
+ setExtra: core.setExtra,
979
+ setExtras: core.setExtras,
980
+ setContext: core.setContext,
981
+
982
+ getIntegration(integration) {
983
+ // eslint-disable-next-line deprecation/deprecation
984
+ return _optionalChain$4([core.getClient, 'call', _ => _(), 'optionalAccess', _2 => _2.getIntegration, 'call', _3 => _3(integration)]) || null;
985
+ },
986
+
987
+ startSession: core.startSession,
988
+
989
+ endSession: core.endSession,
990
+
991
+ captureSession(endSession) {
992
+ // both send the update and pull the session from the scope
993
+ if (endSession) {
994
+ // eslint-disable-next-line deprecation/deprecation
995
+ return this.endSession();
996
+ }
997
+
998
+ // only send the update
999
+ _sendSessionUpdate();
1000
+ },
1001
+
1002
+ shouldSendDefaultPii() {
1003
+ const client = core.getClient();
1004
+ return Boolean(client ? client.getOptions().sendDefaultPii : false);
1005
+ },
1006
+ };
1007
+ }
1008
+
1009
+ /**
1010
+ * Sends the current Session on the scope
1011
+ */
1012
+ function _sendSessionUpdate() {
1013
+ const scope = core.getCurrentScope();
1014
+ const client = core.getClient();
1015
+
1016
+ const session = scope.getSession();
1017
+ if (client && session) {
1018
+ client.captureSession(session);
1019
+ }
1020
+ }
1021
+
1022
+ /** Ensure the `trace` context is set on all events. */
1023
+ function setupEventContextTrace(client) {
1024
+ client.addEventProcessor(event => {
1025
+ const span = getActiveSpan();
1026
+ // For transaction events, this is handled separately
1027
+ // Because the active span may not be the span that is actually the transaction event
1028
+ if (!span || event.type === 'transaction') {
1029
+ return event;
1030
+ }
1031
+
1032
+ const spanContext = span.spanContext();
1033
+
1034
+ // If event has already set `trace` context, use that one.
1035
+ event.contexts = {
1036
+ trace: utils.dropUndefinedKeys({
1037
+ trace_id: spanContext.traceId,
1038
+ span_id: spanContext.spanId,
1039
+ parent_span_id: spanHasParentId(span) ? span.parentSpanId : undefined,
1040
+ }),
1041
+ ...event.contexts,
1042
+ };
1043
+
1044
+ const rootSpan = core.getRootSpan(span);
1045
+ const transactionName = spanHasName(rootSpan) ? rootSpan.name : undefined;
1046
+ if (transactionName && !event.transaction) {
1047
+ event.transaction = transactionName;
1048
+ }
1049
+
1050
+ return event;
1051
+ });
1052
+ }
1053
+
1054
+ /**
1055
+ * Sets the async context strategy to use follow the OTEL context under the hood.
1056
+ * We handle forking a hub inside of our custom OTEL Context Manager (./otelContextManager.ts)
1057
+ */
1058
+ function setOpenTelemetryContextAsyncContextStrategy() {
1059
+ function getScopes() {
1060
+ const ctx = api.context.active();
1061
+ const scopes = getScopesFromContext(ctx);
1062
+
1063
+ if (scopes) {
1064
+ return scopes;
1065
+ }
1066
+
1067
+ // fallback behavior:
1068
+ // if, for whatever reason, we can't find scopes on the context here, we have to fix this somehow
1069
+ return {
1070
+ scope: core.getDefaultCurrentScope(),
1071
+ isolationScope: core.getDefaultIsolationScope(),
1072
+ };
1073
+ }
1074
+
1075
+ function getCurrentHub$1() {
1076
+ // eslint-disable-next-line deprecation/deprecation
1077
+ const hub = getCurrentHub();
1078
+ return {
1079
+ ...hub,
1080
+ getScope: () => {
1081
+ const scopes = getScopes();
1082
+ return scopes.scope;
1083
+ },
1084
+ getIsolationScope: () => {
1085
+ const scopes = getScopes();
1086
+ return scopes.isolationScope;
1087
+ },
1088
+ };
1089
+ }
1090
+
1091
+ function withScope(callback) {
1092
+ const ctx = api.context.active();
1093
+
1094
+ // We depend on the otelContextManager to handle the context/hub
1095
+ // We set the `SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY` context value, which is picked up by
1096
+ // the OTEL context manager, which uses the presence of this key to determine if it should
1097
+ // fork the isolation scope, or not
1098
+ // as by default, we don't want to fork this, unless triggered explicitly by `withScope`
1099
+ return api.context.with(ctx, () => {
1100
+ return callback(getCurrentScope());
1101
+ });
1102
+ }
1103
+
1104
+ function withSetScope(scope, callback) {
1105
+ const ctx = api.context.active();
1106
+
1107
+ // We depend on the otelContextManager to handle the context/hub
1108
+ // We set the `SENTRY_FORK_SET_SCOPE_CONTEXT_KEY` context value, which is picked up by
1109
+ // the OTEL context manager, which picks up this scope as the current scope
1110
+ return api.context.with(ctx.setValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY, scope), () => {
1111
+ return callback(scope);
1112
+ });
1113
+ }
1114
+
1115
+ function withIsolationScope(callback) {
1116
+ const ctx = api.context.active();
1117
+
1118
+ // We depend on the otelContextManager to handle the context/hub
1119
+ // We set the `SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY` context value, which is picked up by
1120
+ // the OTEL context manager, which uses the presence of this key to determine if it should
1121
+ // fork the isolation scope, or not
1122
+ return api.context.with(ctx.setValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY, true), () => {
1123
+ return callback(getIsolationScope());
1124
+ });
1125
+ }
1126
+
1127
+ function withSetIsolationScope(isolationScope, callback) {
1128
+ const ctx = api.context.active();
1129
+
1130
+ // We depend on the otelContextManager to handle the context/hub
1131
+ // We set the `SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY` context value, which is picked up by
1132
+ // the OTEL context manager, which uses the presence of this key to determine if it should
1133
+ // fork the isolation scope, or not
1134
+ return api.context.with(ctx.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, isolationScope), () => {
1135
+ return callback(getIsolationScope());
1136
+ });
1137
+ }
1138
+
1139
+ function getCurrentScope() {
1140
+ return getScopes().scope;
1141
+ }
1142
+
1143
+ function getIsolationScope() {
1144
+ return getScopes().isolationScope;
1145
+ }
1146
+
1147
+ core.setAsyncContextStrategy({
1148
+ getCurrentHub: getCurrentHub$1,
1149
+ withScope,
1150
+ withSetScope,
1151
+ withSetIsolationScope,
1152
+ withIsolationScope,
1153
+ getCurrentScope,
1154
+ getIsolationScope,
1155
+ startSpan,
1156
+ startSpanManual,
1157
+ startInactiveSpan,
1158
+ getActiveSpan,
1159
+ // The types here don't fully align, because our own `Span` type is narrower
1160
+ // than the OTEL one - but this is OK for here, as we now we'll only have OTEL spans passed around
1161
+ withActiveSpan: withActiveSpan ,
1162
+ });
1163
+ }
1164
+
1165
+ function _optionalChain$3(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1166
+
1167
+ /**
1168
+ * Wrap an OpenTelemetry ContextManager in a way that ensures the context is kept in sync with the Sentry Hub.
1169
+ *
1170
+ * Usage:
1171
+ * import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
1172
+ * const SentryContextManager = wrapContextManagerClass(AsyncLocalStorageContextManager);
1173
+ * const contextManager = new SentryContextManager();
1174
+ */
1175
+ function wrapContextManagerClass(
1176
+ ContextManagerClass,
1177
+ ) {
1178
+ /**
1179
+ * This is a custom ContextManager for OpenTelemetry, which extends the default AsyncLocalStorageContextManager.
1180
+ * It ensures that we create a new hub per context, so that the OTEL Context & the Sentry Hub are always in sync.
1181
+ *
1182
+ * Note that we currently only support AsyncHooks with this,
1183
+ * but since this should work for Node 14+ anyhow that should be good enough.
1184
+ */
1185
+
1186
+ // @ts-expect-error TS does not like this, but we know this is fine
1187
+ class SentryContextManager extends ContextManagerClass {
1188
+ constructor() {
1189
+ super();
1190
+ setIsSetup('SentryContextManager');
1191
+ }
1192
+ /**
1193
+ * Overwrite with() of the original AsyncLocalStorageContextManager
1194
+ * to ensure we also create a new hub per context.
1195
+ */
1196
+ with(
1197
+ context,
1198
+ fn,
1199
+ thisArg,
1200
+ ...args
1201
+ ) {
1202
+ const currentScopes = getScopesFromContext(context);
1203
+ const currentScope = _optionalChain$3([currentScopes, 'optionalAccess', _ => _.scope]) || core.getCurrentScope();
1204
+ const currentIsolationScope = _optionalChain$3([currentScopes, 'optionalAccess', _2 => _2.isolationScope]) || core.getIsolationScope();
1205
+
1206
+ const shouldForkIsolationScope = context.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
1207
+ const scope = context.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY) ;
1208
+ const isolationScope = context.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY) ;
1209
+
1210
+ const newCurrentScope = scope || currentScope.clone();
1211
+ const newIsolationScope =
1212
+ isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);
1213
+ const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };
1214
+
1215
+ const ctx1 = setScopesOnContext(context, scopes);
1216
+
1217
+ // Remove the unneeded values again
1218
+ const ctx2 = ctx1
1219
+ .deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY)
1220
+ .deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY)
1221
+ .deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
1222
+
1223
+ setContextOnScope(newCurrentScope, ctx2);
1224
+
1225
+ return super.with(ctx2, fn, thisArg, ...args);
1226
+ }
1227
+ }
1228
+
1229
+ return SentryContextManager ;
1230
+ }
1231
+
1232
+ /**
1233
+ * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
1234
+ *
1235
+ * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
1236
+ */
1237
+ const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
1238
+
1239
+ /** If this attribute is true, it means that the parent is a remote span. */
1240
+ const SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE = 'sentry.parentIsRemote';
1241
+
1242
+ /** Convert an OTEL time to seconds */
1243
+ function convertOtelTimeToSeconds([seconds, nano]) {
1244
+ return seconds + nano / 1000000000;
1245
+ }
1246
+
1247
+ /**
1248
+ * This function runs through a list of OTEL Spans, and wraps them in an `SpanNode`
1249
+ * where each node holds a reference to their parent node.
1250
+ */
1251
+ function groupSpansWithParents(spans) {
1252
+ const nodeMap = new Map();
1253
+
1254
+ for (const span of spans) {
1255
+ createOrUpdateSpanNodeAndRefs(nodeMap, span);
1256
+ }
1257
+
1258
+ return Array.from(nodeMap, function ([_id, spanNode]) {
1259
+ return spanNode;
1260
+ });
1261
+ }
1262
+
1263
+ function createOrUpdateSpanNodeAndRefs(nodeMap, span) {
1264
+ const parentIsRemote = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE] === true;
1265
+
1266
+ const id = span.spanContext().spanId;
1267
+
1268
+ // If the parentId is the trace parent ID, we pretend it's undefined
1269
+ // As this means the parent exists somewhere else
1270
+ const parentId = !parentIsRemote ? span.parentSpanId : undefined;
1271
+
1272
+ if (!parentId) {
1273
+ createOrUpdateNode(nodeMap, { id, span, children: [] });
1274
+ return;
1275
+ }
1276
+
1277
+ // Else make sure to create parent node as well
1278
+ // Note that the parent may not know it's parent _yet_, this may be updated in a later pass
1279
+ const parentNode = createOrGetParentNode(nodeMap, parentId);
1280
+ const node = createOrUpdateNode(nodeMap, { id, span, parentNode, children: [] });
1281
+ parentNode.children.push(node);
1282
+ }
1283
+
1284
+ function createOrGetParentNode(nodeMap, id) {
1285
+ const existing = nodeMap.get(id);
1286
+
1287
+ if (existing) {
1288
+ return existing;
1289
+ }
1290
+
1291
+ return createOrUpdateNode(nodeMap, { id, children: [] });
1292
+ }
1293
+
1294
+ function createOrUpdateNode(nodeMap, spanNode) {
1295
+ const existing = nodeMap.get(spanNode.id);
1296
+
1297
+ // If span is already set, nothing to do here
1298
+ if (existing && existing.span) {
1299
+ return existing;
1300
+ }
1301
+
1302
+ // If it exists but span is not set yet, we update it
1303
+ if (existing && !existing.span) {
1304
+ existing.span = spanNode.span;
1305
+ existing.parentNode = spanNode.parentNode;
1306
+ return existing;
1307
+ }
1308
+
1309
+ // Else, we create a new one...
1310
+ nodeMap.set(spanNode.id, spanNode);
1311
+ return spanNode;
1312
+ }
1313
+
1314
+ // canonicalCodesHTTPMap maps some HTTP codes to Sentry's span statuses. See possible mapping in https://develop.sentry.dev/sdk/event-payloads/span/
1315
+ const canonicalCodesHTTPMap = {
1316
+ '400': 'failed_precondition',
1317
+ '401': 'unauthenticated',
1318
+ '403': 'permission_denied',
1319
+ '404': 'not_found',
1320
+ '409': 'aborted',
1321
+ '429': 'resource_exhausted',
1322
+ '499': 'cancelled',
1323
+ '500': 'internal_error',
1324
+ '501': 'unimplemented',
1325
+ '503': 'unavailable',
1326
+ '504': 'deadline_exceeded',
1327
+ } ;
1328
+
1329
+ // canonicalCodesGrpcMap maps some GRPC codes to Sentry's span statuses. See description in grpc documentation.
1330
+ const canonicalCodesGrpcMap = {
1331
+ '1': 'cancelled',
1332
+ '2': 'unknown_error',
1333
+ '3': 'invalid_argument',
1334
+ '4': 'deadline_exceeded',
1335
+ '5': 'not_found',
1336
+ '6': 'already_exists',
1337
+ '7': 'permission_denied',
1338
+ '8': 'resource_exhausted',
1339
+ '9': 'failed_precondition',
1340
+ '10': 'aborted',
1341
+ '11': 'out_of_range',
1342
+ '12': 'unimplemented',
1343
+ '13': 'internal_error',
1344
+ '14': 'unavailable',
1345
+ '15': 'data_loss',
1346
+ '16': 'unauthenticated',
1347
+ } ;
1348
+
1349
+ /**
1350
+ * Get a Sentry span status from an otel span.
1351
+ */
1352
+ function mapStatus(span) {
1353
+ const attributes = spanHasAttributes(span) ? span.attributes : {};
1354
+ const status = spanHasStatus(span) ? span.status : undefined;
1355
+
1356
+ const httpCode = attributes[semanticConventions.SemanticAttributes.HTTP_STATUS_CODE];
1357
+ const grpcCode = attributes[semanticConventions.SemanticAttributes.RPC_GRPC_STATUS_CODE];
1358
+
1359
+ const code = typeof httpCode === 'string' ? httpCode : typeof httpCode === 'number' ? httpCode.toString() : undefined;
1360
+ if (code) {
1361
+ const sentryStatus = canonicalCodesHTTPMap[code];
1362
+ if (sentryStatus) {
1363
+ return { code: core.SPAN_STATUS_ERROR, message: sentryStatus };
1364
+ }
1365
+ }
1366
+
1367
+ if (typeof grpcCode === 'string') {
1368
+ const sentryStatus = canonicalCodesGrpcMap[grpcCode];
1369
+ if (sentryStatus) {
1370
+ return { code: core.SPAN_STATUS_ERROR, message: sentryStatus };
1371
+ }
1372
+ }
1373
+
1374
+ const statusCode = status && status.code;
1375
+ if (statusCode === api.SpanStatusCode.OK || statusCode === api.SpanStatusCode.UNSET) {
1376
+ return { code: core.SPAN_STATUS_OK };
1377
+ }
1378
+
1379
+ return { code: core.SPAN_STATUS_ERROR, message: 'unknown_error' };
1380
+ }
1381
+
1382
+ /**
1383
+ * Extract better op/description from an otel span.
1384
+ *
1385
+ * Based on https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/7422ce2a06337f68a59b552b8c5a2ac125d6bae5/exporter/sentryexporter/sentry_exporter.go#L306
1386
+ */
1387
+ function parseSpanDescription(span) {
1388
+ const attributes = spanHasAttributes(span) ? span.attributes : {};
1389
+ const name = spanHasName(span) ? span.name : '<unknown>';
1390
+
1391
+ // if http.method exists, this is an http request span
1392
+ const httpMethod = attributes[semanticConventions.SemanticAttributes.HTTP_METHOD];
1393
+ if (httpMethod) {
1394
+ return descriptionForHttpMethod({ attributes, name, kind: getSpanKind(span) }, httpMethod);
1395
+ }
1396
+
1397
+ // If db.type exists then this is a database call span.
1398
+ const dbSystem = attributes[semanticConventions.SemanticAttributes.DB_SYSTEM];
1399
+ if (dbSystem) {
1400
+ return descriptionForDbSystem({ attributes, name });
1401
+ }
1402
+
1403
+ // If rpc.service exists then this is a rpc call span.
1404
+ const rpcService = attributes[semanticConventions.SemanticAttributes.RPC_SERVICE];
1405
+ if (rpcService) {
1406
+ return {
1407
+ op: 'rpc',
1408
+ description: name,
1409
+ source: 'route',
1410
+ };
1411
+ }
1412
+
1413
+ // If messaging.system exists then this is a messaging system span.
1414
+ const messagingSystem = attributes[semanticConventions.SemanticAttributes.MESSAGING_SYSTEM];
1415
+ if (messagingSystem) {
1416
+ return {
1417
+ op: 'message',
1418
+ description: name,
1419
+ source: 'route',
1420
+ };
1421
+ }
1422
+
1423
+ // If faas.trigger exists then this is a function as a service span.
1424
+ const faasTrigger = attributes[semanticConventions.SemanticAttributes.FAAS_TRIGGER];
1425
+ if (faasTrigger) {
1426
+ return { op: faasTrigger.toString(), description: name, source: 'route' };
1427
+ }
1428
+
1429
+ return { op: undefined, description: name, source: 'custom' };
1430
+ }
1431
+
1432
+ function descriptionForDbSystem({ attributes, name }) {
1433
+ // Use DB statement (Ex "SELECT * FROM table") if possible as description.
1434
+ const statement = attributes[semanticConventions.SemanticAttributes.DB_STATEMENT];
1435
+
1436
+ const description = statement ? statement.toString() : name;
1437
+
1438
+ return { op: 'db', description, source: 'task' };
1439
+ }
1440
+
1441
+ /** Only exported for tests. */
1442
+ function descriptionForHttpMethod(
1443
+ { name, kind, attributes },
1444
+ httpMethod,
1445
+ ) {
1446
+ const opParts = ['http'];
1447
+
1448
+ switch (kind) {
1449
+ case api.SpanKind.CLIENT:
1450
+ opParts.push('client');
1451
+ break;
1452
+ case api.SpanKind.SERVER:
1453
+ opParts.push('server');
1454
+ break;
1455
+ }
1456
+
1457
+ const { urlPath, url, query, fragment, hasRoute } = getSanitizedUrl(attributes, kind);
1458
+
1459
+ if (!urlPath) {
1460
+ return { op: opParts.join('.'), description: name, source: 'custom' };
1461
+ }
1462
+
1463
+ // Ex. description="GET /api/users".
1464
+ const description = `${httpMethod} ${urlPath}`;
1465
+
1466
+ // If `httpPath` is a root path, then we can categorize the transaction source as route.
1467
+ const source = hasRoute || urlPath === '/' ? 'route' : 'url';
1468
+
1469
+ const data = {};
1470
+
1471
+ if (url) {
1472
+ data.url = url;
1473
+ }
1474
+ if (query) {
1475
+ data['http.query'] = query;
1476
+ }
1477
+ if (fragment) {
1478
+ data['http.fragment'] = fragment;
1479
+ }
1480
+
1481
+ return {
1482
+ op: opParts.join('.'),
1483
+ description,
1484
+ source,
1485
+ data,
1486
+ };
1487
+ }
1488
+
1489
+ /** Exported for tests only */
1490
+ function getSanitizedUrl(
1491
+ attributes,
1492
+ kind,
1493
+ )
1494
+
1495
+ {
1496
+ // This is the relative path of the URL, e.g. /sub
1497
+ const httpTarget = attributes[semanticConventions.SemanticAttributes.HTTP_TARGET];
1498
+ // This is the full URL, including host & query params etc., e.g. https://example.com/sub?foo=bar
1499
+ const httpUrl = attributes[semanticConventions.SemanticAttributes.HTTP_URL];
1500
+ // This is the normalized route name - may not always be available!
1501
+ const httpRoute = attributes[semanticConventions.SemanticAttributes.HTTP_ROUTE];
1502
+
1503
+ const parsedUrl = typeof httpUrl === 'string' ? utils.parseUrl(httpUrl) : undefined;
1504
+ const url = parsedUrl ? utils.getSanitizedUrlString(parsedUrl) : undefined;
1505
+ const query = parsedUrl && parsedUrl.search ? parsedUrl.search : undefined;
1506
+ const fragment = parsedUrl && parsedUrl.hash ? parsedUrl.hash : undefined;
1507
+
1508
+ if (typeof httpRoute === 'string') {
1509
+ return { urlPath: httpRoute, url, query, fragment, hasRoute: true };
1510
+ }
1511
+
1512
+ if (kind === api.SpanKind.SERVER && typeof httpTarget === 'string') {
1513
+ return { urlPath: utils.stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
1514
+ }
1515
+
1516
+ if (parsedUrl) {
1517
+ return { urlPath: url, url, query, fragment, hasRoute: false };
1518
+ }
1519
+
1520
+ // fall back to target even for client spans, if no URL is present
1521
+ if (typeof httpTarget === 'string') {
1522
+ return { urlPath: utils.stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
1523
+ }
1524
+
1525
+ return { urlPath: undefined, url, query, fragment, hasRoute: false };
1526
+ }
1527
+
1528
+ function _optionalChain$2(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1529
+
1530
+ /**
1531
+ * A Sentry-specific exporter that converts OpenTelemetry Spans to Sentry Spans & Transactions.
1532
+ */
1533
+ class SentrySpanExporter {
1534
+
1535
+ constructor() {
1536
+ this._stopped = false;
1537
+ this._finishedSpans = [];
1538
+ }
1539
+
1540
+ /** @inheritDoc */
1541
+ export(spans, resultCallback) {
1542
+ if (this._stopped) {
1543
+ return resultCallback({
1544
+ code: core$1.ExportResultCode.FAILED,
1545
+ error: new Error('Exporter has been stopped'),
1546
+ });
1547
+ }
1548
+
1549
+ const openSpanCount = this._finishedSpans.length;
1550
+ const newSpanCount = spans.length;
1551
+
1552
+ this._finishedSpans.push(...spans);
1553
+
1554
+ const remainingSpans = maybeSend(this._finishedSpans);
1555
+
1556
+ const remainingOpenSpanCount = remainingSpans.length;
1557
+ const sentSpanCount = openSpanCount + newSpanCount - remainingOpenSpanCount;
1558
+
1559
+ DEBUG_BUILD &&
1560
+ utils.logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1561
+
1562
+ this._finishedSpans = remainingSpans.filter(span => {
1563
+ const shouldDrop = shouldCleanupSpan(span, 5 * 60);
1564
+ DEBUG_BUILD &&
1565
+ shouldDrop &&
1566
+ utils.logger.log(
1567
+ `SpanExporter dropping span ${span.name} (${
1568
+ span.spanContext().spanId
1569
+ }) because it is pending for more than 5 minutes.`,
1570
+ );
1571
+ return !shouldDrop;
1572
+ });
1573
+
1574
+ resultCallback({ code: core$1.ExportResultCode.SUCCESS });
1575
+ }
1576
+
1577
+ /** @inheritDoc */
1578
+ shutdown() {
1579
+ const forceFlush = this.forceFlush();
1580
+ this._stopped = true;
1581
+ this._finishedSpans = [];
1582
+ return forceFlush;
1583
+ }
1584
+
1585
+ /** @inheritDoc */
1586
+ forceFlush() {
1587
+ return new Promise(resolve => {
1588
+ this.export(this._finishedSpans, () => resolve());
1589
+ });
1590
+ }
1591
+ }
1592
+
1593
+ /**
1594
+ * Send the given spans, but only if they are part of a finished transaction.
1595
+ *
1596
+ * Returns the unsent spans.
1597
+ * Spans remain unsent when their parent span is not yet finished.
1598
+ * This will happen regularly, as child spans are generally finished before their parents.
1599
+ * But it _could_ also happen because, for whatever reason, a parent span was lost.
1600
+ * In this case, we'll eventually need to clean this up.
1601
+ */
1602
+ function maybeSend(spans) {
1603
+ const grouped = groupSpansWithParents(spans);
1604
+ const remaining = new Set(grouped);
1605
+
1606
+ const rootNodes = getCompletedRootNodes(grouped);
1607
+
1608
+ rootNodes.forEach(root => {
1609
+ remaining.delete(root);
1610
+ const span = root.span;
1611
+ const transactionEvent = createTransactionForOtelSpan(span);
1612
+
1613
+ // We'll recursively add all the child spans to this array
1614
+ const spans = transactionEvent.spans || [];
1615
+
1616
+ root.children.forEach(child => {
1617
+ createAndFinishSpanForOtelSpan(child, spans, remaining);
1618
+ });
1619
+
1620
+ transactionEvent.spans = spans;
1621
+
1622
+ // TODO Measurements are not yet implemented in OTEL
1623
+
1624
+ core.captureEvent(transactionEvent);
1625
+ });
1626
+
1627
+ return Array.from(remaining)
1628
+ .map(node => node.span)
1629
+ .filter((span) => !!span);
1630
+ }
1631
+
1632
+ function getCompletedRootNodes(nodes) {
1633
+ return nodes.filter((node) => !!node.span && !node.parentNode);
1634
+ }
1635
+
1636
+ function shouldCleanupSpan(span, maxStartTimeOffsetSeconds) {
1637
+ const cutoff = Date.now() / 1000 - maxStartTimeOffsetSeconds;
1638
+ return convertOtelTimeToSeconds(span.startTime) < cutoff;
1639
+ }
1640
+
1641
+ function parseSpan(span) {
1642
+ const attributes = span.attributes;
1643
+
1644
+ const origin = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] ;
1645
+ const op = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_OP] ;
1646
+ const source = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] ;
1647
+
1648
+ return { origin, op, source };
1649
+ }
1650
+
1651
+ function createTransactionForOtelSpan(span) {
1652
+ const { op, description, data, origin = 'manual', source } = getSpanData(span);
1653
+ const capturedSpanScopes = getSpanScopes(span);
1654
+
1655
+ const sampleRate = span.attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ;
1656
+
1657
+ const attributes = utils.dropUndefinedKeys({
1658
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source,
1659
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate,
1660
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
1661
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,
1662
+ ...data,
1663
+ ...removeSentryAttributes(span.attributes),
1664
+ });
1665
+
1666
+ const { traceId: trace_id, spanId: span_id } = span.spanContext();
1667
+ const parent_span_id = span.parentSpanId;
1668
+
1669
+ const status = mapStatus(span);
1670
+
1671
+ const traceContext = utils.dropUndefinedKeys({
1672
+ parent_span_id,
1673
+ span_id,
1674
+ trace_id,
1675
+ data: attributes,
1676
+ origin,
1677
+ op,
1678
+ status: core.getStatusMessage(status),
1679
+ });
1680
+
1681
+ const transactionEvent = {
1682
+ contexts: {
1683
+ trace: traceContext,
1684
+ otel: {
1685
+ // TODO: remove the attributes here?
1686
+ attributes: removeSentryAttributes(span.attributes),
1687
+ resource: span.resource.attributes,
1688
+ },
1689
+ },
1690
+ spans: [],
1691
+ start_timestamp: convertOtelTimeToSeconds(span.startTime),
1692
+ timestamp: convertOtelTimeToSeconds(span.endTime),
1693
+ transaction: description,
1694
+ type: 'transaction',
1695
+ sdkProcessingMetadata: {
1696
+ ...utils.dropUndefinedKeys({
1697
+ capturedSpanScope: _optionalChain$2([capturedSpanScopes, 'optionalAccess', _ => _.scope]),
1698
+ capturedSpanIsolationScope: _optionalChain$2([capturedSpanScopes, 'optionalAccess', _2 => _2.isolationScope]),
1699
+ sampleRate,
1700
+ dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
1701
+ }),
1702
+ },
1703
+ ...(source && {
1704
+ transaction_info: {
1705
+ source,
1706
+ },
1707
+ }),
1708
+ _metrics_summary: core.getMetricSummaryJsonForSpan(span ),
1709
+ };
1710
+
1711
+ return transactionEvent;
1712
+ }
1713
+
1714
+ function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1715
+ remaining.delete(node);
1716
+ const span = node.span;
1717
+
1718
+ const shouldDrop = !span;
1719
+
1720
+ // If this span should be dropped, we still want to create spans for the children of this
1721
+ if (shouldDrop) {
1722
+ node.children.forEach(child => {
1723
+ createAndFinishSpanForOtelSpan(child, spans, remaining);
1724
+ });
1725
+ return;
1726
+ }
1727
+
1728
+ const span_id = span.spanContext().spanId;
1729
+ const trace_id = span.spanContext().traceId;
1730
+
1731
+ const { attributes, startTime, endTime, parentSpanId } = span;
1732
+
1733
+ const { op, description, data, origin = 'manual' } = getSpanData(span);
1734
+ const allData = utils.dropUndefinedKeys({
1735
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,
1736
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
1737
+ ...removeSentryAttributes(attributes),
1738
+ ...data,
1739
+ });
1740
+
1741
+ const status = mapStatus(span);
1742
+
1743
+ const spanJSON = utils.dropUndefinedKeys({
1744
+ span_id,
1745
+ trace_id,
1746
+ data: allData,
1747
+ description,
1748
+ parent_span_id: parentSpanId,
1749
+ start_timestamp: convertOtelTimeToSeconds(startTime),
1750
+ // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time
1751
+ timestamp: convertOtelTimeToSeconds(endTime) || undefined,
1752
+ status: core.getStatusMessage(status),
1753
+ op,
1754
+ origin,
1755
+ _metrics_summary: core.getMetricSummaryJsonForSpan(span ),
1756
+ });
1757
+
1758
+ spans.push(spanJSON);
1759
+
1760
+ node.children.forEach(child => {
1761
+ createAndFinishSpanForOtelSpan(child, spans, remaining);
1762
+ });
1763
+ }
1764
+
1765
+ function getSpanData(span)
1766
+
1767
+ {
1768
+ const { op: definedOp, source: definedSource, origin } = parseSpan(span);
1769
+ const { op: inferredOp, description, source: inferredSource, data: inferredData } = parseSpanDescription(span);
1770
+
1771
+ const op = definedOp || inferredOp;
1772
+ const source = definedSource || inferredSource;
1773
+
1774
+ const data = { ...inferredData, ...getData(span) };
1775
+
1776
+ return {
1777
+ op,
1778
+ description,
1779
+ source,
1780
+ origin,
1781
+ data,
1782
+ };
1783
+ }
1784
+
1785
+ /**
1786
+ * Remove custom `sentry.` attribtues we do not need to send.
1787
+ * These are more carrier attributes we use inside of the SDK, we do not need to send them to the API.
1788
+ */
1789
+ function removeSentryAttributes(data) {
1790
+ const cleanedData = { ...data };
1791
+
1792
+ /* eslint-disable @typescript-eslint/no-dynamic-delete */
1793
+ delete cleanedData[core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
1794
+ delete cleanedData[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE];
1795
+ /* eslint-enable @typescript-eslint/no-dynamic-delete */
1796
+
1797
+ return cleanedData;
1798
+ }
1799
+
1800
+ function getData(span) {
1801
+ const attributes = span.attributes;
1802
+ const data = {
1803
+ 'otel.kind': api.SpanKind[span.kind],
1804
+ };
1805
+
1806
+ if (attributes[semanticConventions.SemanticAttributes.HTTP_STATUS_CODE]) {
1807
+ const statusCode = attributes[semanticConventions.SemanticAttributes.HTTP_STATUS_CODE] ;
1808
+ data['http.response.status_code'] = statusCode;
1809
+ }
1810
+
1811
+ const requestData = getRequestSpanData(span);
1812
+
1813
+ if (requestData.url) {
1814
+ data.url = requestData.url;
1815
+ }
1816
+
1817
+ if (requestData['http.query']) {
1818
+ data['http.query'] = requestData['http.query'].slice(1);
1819
+ }
1820
+ if (requestData['http.fragment']) {
1821
+ data['http.fragment'] = requestData['http.fragment'].slice(1);
1822
+ }
1823
+
1824
+ return data;
1825
+ }
1826
+
1827
+ function _optionalChain$1(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1828
+
1829
+ function onSpanStart(span, parentContext) {
1830
+ // This is a reliable way to get the parent span - because this is exactly how the parent is identified in the OTEL SDK
1831
+ const parentSpan = api.trace.getSpan(parentContext);
1832
+
1833
+ let scopes = getScopesFromContext(parentContext);
1834
+
1835
+ // We need access to the parent span in order to be able to move up the span tree for breadcrumbs
1836
+ if (parentSpan && !parentSpan.spanContext().isRemote) {
1837
+ core.addChildSpanToSpan(parentSpan, span);
1838
+ }
1839
+
1840
+ // We need this in the span exporter
1841
+ if (parentSpan && parentSpan.spanContext().isRemote) {
1842
+ span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE, true);
1843
+ }
1844
+
1845
+ // The root context does not have scopes stored, so we check for this specifically
1846
+ // As fallback we attach the global scopes
1847
+ if (parentContext === api.ROOT_CONTEXT) {
1848
+ scopes = {
1849
+ scope: core.getDefaultCurrentScope(),
1850
+ isolationScope: core.getDefaultIsolationScope(),
1851
+ };
1852
+ }
1853
+
1854
+ // We need the scope at time of span creation in order to apply it to the event when the span is finished
1855
+ if (scopes) {
1856
+ setSpanScopes(span, scopes);
1857
+ }
1858
+
1859
+ const client = core.getClient();
1860
+ _optionalChain$1([client, 'optionalAccess', _ => _.emit, 'call', _2 => _2('spanStart', span)]);
1861
+ }
1862
+
1863
+ function onSpanEnd(span) {
1864
+ // Capture exceptions as events
1865
+ span.events.forEach(event => {
1866
+ maybeCaptureExceptionForTimedEvent(event, span);
1867
+ });
1868
+
1869
+ const client = core.getClient();
1870
+ _optionalChain$1([client, 'optionalAccess', _3 => _3.emit, 'call', _4 => _4('spanEnd', span)]);
1871
+ }
1872
+
1873
+ /**
1874
+ * Converts OpenTelemetry Spans to Sentry Spans and sends them to Sentry via
1875
+ * the Sentry SDK.
1876
+ */
1877
+ class SentrySpanProcessor extends sdkTraceBase.BatchSpanProcessor {
1878
+ constructor() {
1879
+ super(new SentrySpanExporter());
1880
+
1881
+ setIsSetup('SentrySpanProcessor');
1882
+ }
1883
+
1884
+ /**
1885
+ * @inheritDoc
1886
+ */
1887
+ onStart(span, parentContext) {
1888
+ onSpanStart(span, parentContext);
1889
+
1890
+ // TODO (v8): Trigger client `spanStart` & `spanEnd` in here,
1891
+ // once we decoupled opentelemetry from SentrySpan
1892
+
1893
+ DEBUG_BUILD && utils.logger.log(`[Tracing] Starting span "${span.name}" (${span.spanContext().spanId})`);
1894
+
1895
+ return super.onStart(span, parentContext);
1896
+ }
1897
+
1898
+ /** @inheritDoc */
1899
+ onEnd(span) {
1900
+ DEBUG_BUILD && utils.logger.log(`[Tracing] Finishing span "${span.name}" (${span.spanContext().spanId})`);
1901
+
1902
+ if (!this._shouldSendSpanToSentry(span)) {
1903
+ // Prevent this being called to super.onEnd(), which would pass this to the span exporter
1904
+ return;
1905
+ }
1906
+
1907
+ onSpanEnd(span);
1908
+
1909
+ return super.onEnd(span);
1910
+ }
1911
+
1912
+ /**
1913
+ * You can overwrite this in a sub class to implement custom behavior for dropping spans.
1914
+ * If you return `false` here, the span will not be passed to the exporter and thus not be sent.
1915
+ */
1916
+ _shouldSendSpanToSentry(_span) {
1917
+ return true;
1918
+ }
1919
+ }
1920
+
1921
+ /**
1922
+ * A custom OTEL sampler that uses Sentry sampling rates to make it's decision
1923
+ */
1924
+ class SentrySampler {
1925
+
1926
+ constructor(client) {
1927
+ this._client = client;
1928
+ setIsSetup('SentrySampler');
1929
+ }
1930
+
1931
+ /** @inheritDoc */
1932
+ shouldSample(
1933
+ context,
1934
+ traceId,
1935
+ spanName,
1936
+ _spanKind,
1937
+ spanAttributes,
1938
+ _links,
1939
+ ) {
1940
+ const options = this._client.getOptions();
1941
+
1942
+ if (!core.hasTracingEnabled(options)) {
1943
+ return { decision: sdkTraceBase.SamplingDecision.NOT_RECORD };
1944
+ }
1945
+
1946
+ const parentContext = api.trace.getSpanContext(context);
1947
+ const traceState = _optionalChain([parentContext, 'optionalAccess', _ => _.traceState]) || new core$1.TraceState();
1948
+
1949
+ let parentSampled = undefined;
1950
+
1951
+ // Only inherit sample rate if `traceId` is the same
1952
+ // Note for testing: `isSpanContextValid()` checks the format of the traceId/spanId, so we need to pass valid ones
1953
+ if (parentContext && api.isSpanContextValid(parentContext) && parentContext.traceId === traceId) {
1954
+ if (parentContext.isRemote) {
1955
+ parentSampled = getParentRemoteSampled(parentContext);
1956
+ DEBUG_BUILD &&
1957
+ utils.logger.log(`[Tracing] Inheriting remote parent's sampled decision for ${spanName}: ${parentSampled}`);
1958
+ } else {
1959
+ parentSampled = getSamplingDecision(parentContext);
1960
+ DEBUG_BUILD && utils.logger.log(`[Tracing] Inheriting parent's sampled decision for ${spanName}: ${parentSampled}`);
1961
+ }
1962
+ }
1963
+
1964
+ const sampleRate = getSampleRate(options, {
1965
+ name: spanName,
1966
+ attributes: spanAttributes,
1967
+ transactionContext: {
1968
+ name: spanName,
1969
+ parentSampled,
1970
+ },
1971
+ parentSampled,
1972
+ });
1973
+
1974
+ const attributes = {
1975
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: Number(sampleRate),
1976
+ };
1977
+
1978
+ // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The
1979
+ // only valid values are booleans or numbers between 0 and 1.)
1980
+ if (!isValidSampleRate(sampleRate)) {
1981
+ DEBUG_BUILD && utils.logger.warn('[Tracing] Discarding span because of invalid sample rate.');
1982
+
1983
+ return {
1984
+ decision: sdkTraceBase.SamplingDecision.NOT_RECORD,
1985
+ attributes,
1986
+ traceState: traceState.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1'),
1987
+ };
1988
+ }
1989
+
1990
+ // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped
1991
+ if (!sampleRate) {
1992
+ DEBUG_BUILD &&
1993
+ utils.logger.log(
1994
+ `[Tracing] Discarding span because ${
1995
+ typeof options.tracesSampler === 'function'
1996
+ ? 'tracesSampler returned 0 or false'
1997
+ : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'
1998
+ }`,
1999
+ );
2000
+
2001
+ return {
2002
+ decision: sdkTraceBase.SamplingDecision.NOT_RECORD,
2003
+ attributes,
2004
+ traceState: traceState.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1'),
2005
+ };
2006
+ }
2007
+
2008
+ // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is
2009
+ // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.
2010
+ const isSampled = Math.random() < (sampleRate );
2011
+
2012
+ // if we're not going to keep it, we're done
2013
+ if (!isSampled) {
2014
+ DEBUG_BUILD &&
2015
+ utils.logger.log(
2016
+ `[Tracing] Discarding span because it's not included in the random sample (sampling rate = ${Number(
2017
+ sampleRate,
2018
+ )})`,
2019
+ );
2020
+
2021
+ return {
2022
+ decision: sdkTraceBase.SamplingDecision.NOT_RECORD,
2023
+ attributes,
2024
+ traceState: traceState.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1'),
2025
+ };
2026
+ }
2027
+
2028
+ return {
2029
+ decision: sdkTraceBase.SamplingDecision.RECORD_AND_SAMPLED,
2030
+ attributes,
2031
+ };
2032
+ }
2033
+
2034
+ /** Returns the sampler name or short description with the configuration. */
2035
+ toString() {
2036
+ return 'SentrySampler';
2037
+ }
2038
+ }
2039
+
2040
+ function getSampleRate(
2041
+ options,
2042
+ samplingContext,
2043
+ ) {
2044
+ if (typeof options.tracesSampler === 'function') {
2045
+ return options.tracesSampler(samplingContext);
2046
+ }
2047
+
2048
+ if (samplingContext.parentSampled !== undefined) {
2049
+ return samplingContext.parentSampled;
2050
+ }
2051
+
2052
+ if (typeof options.tracesSampleRate !== 'undefined') {
2053
+ return options.tracesSampleRate;
2054
+ }
2055
+
2056
+ // When `enableTracing === true`, we use a sample rate of 100%
2057
+ if (options.enableTracing) {
2058
+ return 1;
2059
+ }
2060
+
2061
+ return 0;
2062
+ }
2063
+
2064
+ /**
2065
+ * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).
2066
+ */
2067
+ function isValidSampleRate(rate) {
2068
+ // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck
2069
+ if (utils.isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {
2070
+ DEBUG_BUILD &&
2071
+ utils.logger.warn(
2072
+ `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
2073
+ rate,
2074
+ )} of type ${JSON.stringify(typeof rate)}.`,
2075
+ );
2076
+ return false;
2077
+ }
2078
+
2079
+ // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false
2080
+ if (rate < 0 || rate > 1) {
2081
+ DEBUG_BUILD &&
2082
+ utils.logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);
2083
+ return false;
2084
+ }
2085
+ return true;
2086
+ }
2087
+
2088
+ function getParentRemoteSampled(spanContext) {
2089
+ const traceId = spanContext.traceId;
2090
+ const traceparentData = getPropagationContextFromSpanContext(spanContext);
2091
+
2092
+ // Only inherit sampled if `traceId` is the same
2093
+ return traceparentData && traceId === traceparentData.traceId ? traceparentData.sampled : undefined;
2094
+ }
24
2095
 
25
2096
  /**
26
2097
  * The following internal utils are not considered public API and are subject to change.
27
2098
  * @hidden
28
2099
  */
29
2100
  const _INTERNAL = {
30
- addOriginToSpan: addOriginToSpan.addOriginToSpan,
31
- maybeCaptureExceptionForTimedEvent: captureExceptionForTimedEvent.maybeCaptureExceptionForTimedEvent,
32
- getRequestSpanData: getRequestSpanData.getRequestSpanData,
2101
+ maybeCaptureExceptionForTimedEvent,
2102
+ getRequestSpanData,
33
2103
  } ;
34
2104
 
35
- exports.wrapClientClass = client.wrapClientClass;
36
- exports.getSpanKind = getSpanKind.getSpanKind;
37
- exports.getSpanHub = spanData.getSpanHub;
38
- exports.getSpanMetadata = spanData.getSpanMetadata;
39
- exports.getSpanParent = spanData.getSpanParent;
40
- exports.getSpanScopes = spanData.getSpanScopes;
41
- exports.setSpanMetadata = spanData.setSpanMetadata;
42
- exports.getPropagationContextFromContext = contextData.getPropagationContextFromContext;
43
- exports.getScopesFromContext = contextData.getScopesFromContext;
44
- exports.setPropagationContextOnContext = contextData.setPropagationContextOnContext;
45
- exports.spanHasAttributes = spanTypes.spanHasAttributes;
46
- exports.spanHasEvents = spanTypes.spanHasEvents;
47
- exports.spanHasKind = spanTypes.spanHasKind;
48
- exports.spanHasName = spanTypes.spanHasName;
49
- exports.spanHasParentId = spanTypes.spanHasParentId;
50
- exports.spanHasStatus = spanTypes.spanHasStatus;
51
- exports.isSentryRequestSpan = isSentryRequest.isSentryRequestSpan;
52
- exports.getActiveSpan = getActiveSpan.getActiveSpan;
53
- exports.getRootSpan = getActiveSpan.getRootSpan;
54
- exports.startInactiveSpan = trace.startInactiveSpan;
55
- exports.startSpan = trace.startSpan;
56
- exports.startSpanManual = trace.startSpanManual;
57
- exports.withActiveSpan = trace.withActiveSpan;
58
- exports.setupGlobalHub = hub.setupGlobalHub;
59
- exports.getCurrentHub = getCurrentHub.getCurrentHub;
60
- exports.addTracingExtensions = hubextensions.addTracingExtensions;
61
- exports.setupEventContextTrace = setupEventContextTrace.setupEventContextTrace;
62
- exports.setOpenTelemetryContextAsyncContextStrategy = asyncContextStrategy.setOpenTelemetryContextAsyncContextStrategy;
63
- exports.wrapContextManagerClass = contextManager.wrapContextManagerClass;
64
- exports.SentryPropagator = propagator.SentryPropagator;
65
- exports.SentrySpanProcessor = spanProcessor.SentrySpanProcessor;
66
- exports.SentrySampler = sampler.SentrySampler;
67
2105
  exports.getClient = core.getClient;
2106
+ exports.SentryPropagator = SentryPropagator;
2107
+ exports.SentrySampler = SentrySampler;
2108
+ exports.SentrySpanProcessor = SentrySpanProcessor;
68
2109
  exports._INTERNAL = _INTERNAL;
2110
+ exports.continueTrace = continueTrace;
2111
+ exports.getActiveSpan = getActiveSpan;
2112
+ exports.getCurrentHub = getCurrentHub;
2113
+ exports.getDynamicSamplingContextFromSpan = getDynamicSamplingContextFromSpan;
2114
+ exports.getScopesFromContext = getScopesFromContext;
2115
+ exports.getSpanKind = getSpanKind;
2116
+ exports.getSpanScopes = getSpanScopes;
2117
+ exports.isSentryRequestSpan = isSentryRequestSpan;
2118
+ exports.openTelemetrySetupCheck = openTelemetrySetupCheck;
2119
+ exports.setOpenTelemetryContextAsyncContextStrategy = setOpenTelemetryContextAsyncContextStrategy;
2120
+ exports.setupEventContextTrace = setupEventContextTrace;
2121
+ exports.setupGlobalHub = setupGlobalHub;
2122
+ exports.spanHasAttributes = spanHasAttributes;
2123
+ exports.spanHasEvents = spanHasEvents;
2124
+ exports.spanHasKind = spanHasKind;
2125
+ exports.spanHasName = spanHasName;
2126
+ exports.spanHasParentId = spanHasParentId;
2127
+ exports.spanHasStatus = spanHasStatus;
2128
+ exports.startInactiveSpan = startInactiveSpan;
2129
+ exports.startSpan = startSpan;
2130
+ exports.startSpanManual = startSpanManual;
2131
+ exports.withActiveSpan = withActiveSpan;
2132
+ exports.wrapClientClass = wrapClientClass;
2133
+ exports.wrapContextManagerClass = wrapContextManagerClass;
69
2134
  //# sourceMappingURL=index.js.map