@sentry/opentelemetry 10.53.1 → 10.54.0

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.
@@ -0,0 +1,1607 @@
1
+ import * as api from '@opentelemetry/api';
2
+ import { trace, SpanKind, createContextKey, TraceFlags, propagation, INVALID_TRACEID, context, SpanStatusCode, ROOT_CONTEXT, isSpanContextValid } from '@opentelemetry/api';
3
+ import { parseUrl, getSanitizedUrlString, SDK_VERSION, derefWeakRef, addNonEnumerableProperty, makeWeakRef, isSentryRequestUrl, getClient, baggageHeaderToDynamicSamplingContext, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, stripUrlQueryAndFragment, spanToJSON, hasSpansEnabled, dynamicSamplingContextToSentryBaggageHeader, LRUMap, debug, shouldPropagateTraceForUrl, parseBaggageHeader, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, generateTraceparentHeader, getDynamicSamplingContextFromSpan, getCurrentScope, getDynamicSamplingContextFromScope, getIsolationScope, propagationContextFromHeaders, shouldContinueTrace, spanToTraceContext, getTraceContextFromScope, generateTraceId, generateSpanId, _INTERNAL_safeMathRandom, getRootSpan, handleCallbackErrors, getCapturedScopesOnSpan, setAsyncContextStrategy, getDefaultIsolationScope, getDefaultCurrentScope, SPAN_STATUS_OK, SPAN_STATUS_ERROR, getSpanStatusFromHttpCode, _INTERNAL_safeDateNow, debounce, timedEventsToMeasurements, captureEvent, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, convertSpanLinksForEnvelope, getStatusMessage, spanTimeInputToSeconds, addChildSpanToSpan, setCapturedScopesOnSpan, logSpanStart, logSpanEnd, hasSpanStreamingEnabled, shouldIgnoreSpan, parseSampleRate, sampleSpan } from '@sentry/core';
4
+ import { ATTR_URL_FULL, SEMATTRS_HTTP_URL, ATTR_HTTP_REQUEST_METHOD, SEMATTRS_HTTP_METHOD, ATTR_DB_SYSTEM_NAME, SEMATTRS_DB_SYSTEM, SEMATTRS_RPC_SERVICE, SEMATTRS_MESSAGING_SYSTEM, SEMATTRS_FAAS_TRIGGER, SEMATTRS_DB_STATEMENT, SEMATTRS_HTTP_TARGET, ATTR_HTTP_ROUTE, ATTR_HTTP_RESPONSE_STATUS_CODE, SEMATTRS_HTTP_STATUS_CODE, SEMATTRS_RPC_GRPC_STATUS_CODE, ATTR_TELEMETRY_SDK_VERSION, ATTR_TELEMETRY_SDK_NAME, ATTR_TELEMETRY_SDK_LANGUAGE, ATTR_SERVICE_VERSION, ATTR_SERVICE_NAME, SEMRESATTRS_SERVICE_NAMESPACE } from '@opentelemetry/semantic-conventions';
5
+ import { TraceState, W3CBaggagePropagator, isTracingSuppressed, suppressTracing as suppressTracing$1, SDK_INFO } from '@opentelemetry/core';
6
+ import { D as DEBUG_BUILD } from './debug-build-B98wrZ1j.js';
7
+ import { SamplingDecision } from '@opentelemetry/sdk-trace-base';
8
+
9
+ const SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE = "sentry.parentIsRemote";
10
+ const SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION = "sentry.graphql.operation";
11
+
12
+ function getParentSpanId(span) {
13
+ if ("parentSpanId" in span) {
14
+ return span.parentSpanId;
15
+ } else if ("parentSpanContext" in span) {
16
+ return span.parentSpanContext?.spanId;
17
+ }
18
+ return void 0;
19
+ }
20
+
21
+ function spanHasAttributes(span) {
22
+ const castSpan = span;
23
+ return !!castSpan.attributes && typeof castSpan.attributes === "object";
24
+ }
25
+ function spanHasKind(span) {
26
+ const castSpan = span;
27
+ return typeof castSpan.kind === "number";
28
+ }
29
+ function spanHasStatus(span) {
30
+ const castSpan = span;
31
+ return !!castSpan.status;
32
+ }
33
+ function spanHasName(span) {
34
+ const castSpan = span;
35
+ return !!castSpan.name;
36
+ }
37
+ function spanHasParentId(span) {
38
+ const castSpan = span;
39
+ return !!getParentSpanId(castSpan);
40
+ }
41
+ function spanHasEvents(span) {
42
+ const castSpan = span;
43
+ return Array.isArray(castSpan.events);
44
+ }
45
+
46
+ function getRequestSpanData(span) {
47
+ if (!spanHasAttributes(span)) {
48
+ return {};
49
+ }
50
+ const maybeUrlAttribute = span.attributes[ATTR_URL_FULL] || span.attributes[SEMATTRS_HTTP_URL];
51
+ const data = {
52
+ url: maybeUrlAttribute,
53
+ // eslint-disable-next-line deprecation/deprecation
54
+ "http.method": span.attributes[ATTR_HTTP_REQUEST_METHOD] || span.attributes[SEMATTRS_HTTP_METHOD]
55
+ };
56
+ if (!data["http.method"] && data.url) {
57
+ data["http.method"] = "GET";
58
+ }
59
+ try {
60
+ if (typeof maybeUrlAttribute === "string") {
61
+ const url = parseUrl(maybeUrlAttribute);
62
+ data.url = getSanitizedUrlString(url);
63
+ if (url.search) {
64
+ data["http.query"] = url.search;
65
+ }
66
+ if (url.hash) {
67
+ data["http.fragment"] = url.hash;
68
+ }
69
+ }
70
+ } catch {
71
+ }
72
+ return data;
73
+ }
74
+
75
+ function wrapClientClass(ClientClass) {
76
+ class OpenTelemetryClient extends ClientClass {
77
+ constructor(...args) {
78
+ super(...args);
79
+ }
80
+ /** Get the OTEL tracer. */
81
+ get tracer() {
82
+ if (this._tracer) {
83
+ return this._tracer;
84
+ }
85
+ const name = "@sentry/opentelemetry";
86
+ const version = SDK_VERSION;
87
+ const tracer = trace.getTracer(name, version);
88
+ this._tracer = tracer;
89
+ return tracer;
90
+ }
91
+ /**
92
+ * @inheritDoc
93
+ */
94
+ async flush(timeout) {
95
+ const provider = this.traceProvider;
96
+ await provider?.forceFlush();
97
+ return super.flush(timeout);
98
+ }
99
+ }
100
+ return OpenTelemetryClient;
101
+ }
102
+
103
+ function getSpanKind(span) {
104
+ if (spanHasKind(span)) {
105
+ return span.kind;
106
+ }
107
+ return SpanKind.INTERNAL;
108
+ }
109
+
110
+ const SENTRY_TRACE_HEADER = "sentry-trace";
111
+ const SENTRY_BAGGAGE_HEADER = "baggage";
112
+ const SENTRY_TRACE_STATE_DSC = "sentry.dsc";
113
+ const SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING = "sentry.sampled_not_recording";
114
+ const SENTRY_TRACE_STATE_URL = "sentry.url";
115
+ const SENTRY_TRACE_STATE_SAMPLE_RAND = "sentry.sample_rand";
116
+ const SENTRY_TRACE_STATE_SAMPLE_RATE = "sentry.sample_rate";
117
+ const SENTRY_TRACE_STATE_CHILD_IGNORED = "sentry.ignored";
118
+ const SENTRY_TRACE_STATE_SEGMENT_IGNORED = "sentry.segment_ignored";
119
+ const SENTRY_SCOPES_CONTEXT_KEY = createContextKey("sentry_scopes");
120
+ const SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey("sentry_fork_isolation_scope");
121
+ const SENTRY_FORK_SET_SCOPE_CONTEXT_KEY = createContextKey("sentry_fork_set_scope");
122
+ const SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey("sentry_fork_set_isolation_scope");
123
+
124
+ const SCOPE_CONTEXT_FIELD = "_scopeContext";
125
+ function getScopesFromContext(context) {
126
+ return context.getValue(SENTRY_SCOPES_CONTEXT_KEY);
127
+ }
128
+ function setScopesOnContext(context, scopes) {
129
+ return context.setValue(SENTRY_SCOPES_CONTEXT_KEY, scopes);
130
+ }
131
+ function setContextOnScope(scope, context) {
132
+ addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, makeWeakRef(context));
133
+ }
134
+ function getContextFromScope(scope) {
135
+ return derefWeakRef(scope[SCOPE_CONTEXT_FIELD]);
136
+ }
137
+
138
+ function isSentryRequestSpan(span) {
139
+ if (!spanHasAttributes(span)) {
140
+ return false;
141
+ }
142
+ const { attributes } = span;
143
+ const httpUrl = attributes[SEMATTRS_HTTP_URL] || attributes[ATTR_URL_FULL];
144
+ if (!httpUrl) {
145
+ return false;
146
+ }
147
+ return isSentryRequestUrl(httpUrl.toString(), getClient());
148
+ }
149
+
150
+ function getSamplingDecision(spanContext) {
151
+ const { traceFlags, traceState } = spanContext;
152
+ const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === "1" : false;
153
+ if (traceFlags === TraceFlags.SAMPLED) {
154
+ return true;
155
+ }
156
+ if (sampledNotRecording) {
157
+ return false;
158
+ }
159
+ const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : void 0;
160
+ const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : void 0;
161
+ if (dsc?.sampled === "true") {
162
+ return true;
163
+ }
164
+ if (dsc?.sampled === "false") {
165
+ return false;
166
+ }
167
+ return void 0;
168
+ }
169
+
170
+ function inferSpanData(spanName, attributes, kind) {
171
+ const httpMethod = attributes[ATTR_HTTP_REQUEST_METHOD] || attributes[SEMATTRS_HTTP_METHOD];
172
+ if (httpMethod) {
173
+ return descriptionForHttpMethod({ attributes, name: spanName, kind }, httpMethod);
174
+ }
175
+ const dbSystem = attributes[ATTR_DB_SYSTEM_NAME] || attributes[SEMATTRS_DB_SYSTEM];
176
+ const opIsCache = typeof attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] === "string" && attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP].startsWith("cache.");
177
+ if (dbSystem && !opIsCache) {
178
+ return descriptionForDbSystem({ attributes, name: spanName });
179
+ }
180
+ const customSourceOrRoute = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === "custom" ? "custom" : "route";
181
+ const rpcService = attributes[SEMATTRS_RPC_SERVICE];
182
+ if (rpcService) {
183
+ return {
184
+ ...getUserUpdatedNameAndSource(spanName, attributes, "route"),
185
+ op: "rpc"
186
+ };
187
+ }
188
+ const messagingSystem = attributes[SEMATTRS_MESSAGING_SYSTEM];
189
+ if (messagingSystem) {
190
+ return {
191
+ ...getUserUpdatedNameAndSource(spanName, attributes, customSourceOrRoute),
192
+ op: "message"
193
+ };
194
+ }
195
+ const faasTrigger = attributes[SEMATTRS_FAAS_TRIGGER];
196
+ if (faasTrigger) {
197
+ return {
198
+ ...getUserUpdatedNameAndSource(spanName, attributes, customSourceOrRoute),
199
+ op: faasTrigger.toString()
200
+ };
201
+ }
202
+ return { op: void 0, description: spanName, source: "custom" };
203
+ }
204
+ function parseSpanDescription(span) {
205
+ const attributes = spanHasAttributes(span) ? span.attributes : {};
206
+ const name = spanHasName(span) ? span.name : "<unknown>";
207
+ const kind = getSpanKind(span);
208
+ return inferSpanData(name, attributes, kind);
209
+ }
210
+ function descriptionForDbSystem({ attributes, name }) {
211
+ const userDefinedName = attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
212
+ if (typeof userDefinedName === "string") {
213
+ return {
214
+ op: "db",
215
+ description: userDefinedName,
216
+ source: attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] || "custom"
217
+ };
218
+ }
219
+ if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === "custom") {
220
+ return { op: "db", description: name, source: "custom" };
221
+ }
222
+ const statement = attributes[SEMATTRS_DB_STATEMENT];
223
+ const description = statement ? statement.toString() : name;
224
+ return { op: "db", description, source: "task" };
225
+ }
226
+ function descriptionForHttpMethod({ name, kind, attributes }, httpMethod) {
227
+ const opParts = ["http"];
228
+ switch (kind) {
229
+ case SpanKind.CLIENT:
230
+ opParts.push("client");
231
+ break;
232
+ case SpanKind.SERVER:
233
+ opParts.push("server");
234
+ break;
235
+ }
236
+ if (attributes["sentry.http.prefetch"]) {
237
+ opParts.push("prefetch");
238
+ }
239
+ const { urlPath, url, query, fragment, hasRoute } = getSanitizedUrl(attributes, kind);
240
+ if (!urlPath) {
241
+ return { ...getUserUpdatedNameAndSource(name, attributes), op: opParts.join(".") };
242
+ }
243
+ const graphqlOperationsAttribute = attributes[SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION];
244
+ const baseDescription = `${httpMethod} ${urlPath}`;
245
+ const inferredDescription = graphqlOperationsAttribute ? `${baseDescription} (${getGraphqlOperationNamesFromAttribute(graphqlOperationsAttribute)})` : baseDescription;
246
+ const inferredSource = hasRoute || urlPath === "/" ? "route" : "url";
247
+ const data = {};
248
+ if (url) {
249
+ data.url = url;
250
+ }
251
+ if (query) {
252
+ data["http.query"] = query;
253
+ }
254
+ if (fragment) {
255
+ data["http.fragment"] = fragment;
256
+ }
257
+ const isClientOrServerKind = kind === SpanKind.CLIENT || kind === SpanKind.SERVER;
258
+ const origin = attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] || "manual";
259
+ const isManualSpan = !`${origin}`.startsWith("auto");
260
+ const alreadyHasCustomSource = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === "custom";
261
+ const customSpanName = attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
262
+ const useInferredDescription = !alreadyHasCustomSource && customSpanName == null && (isClientOrServerKind || !isManualSpan);
263
+ const { description, source } = useInferredDescription ? { description: inferredDescription, source: inferredSource } : getUserUpdatedNameAndSource(name, attributes);
264
+ return {
265
+ op: opParts.join("."),
266
+ description,
267
+ source,
268
+ data
269
+ };
270
+ }
271
+ function getGraphqlOperationNamesFromAttribute(attr) {
272
+ if (Array.isArray(attr)) {
273
+ const sorted = attr.slice().sort();
274
+ if (sorted.length <= 5) {
275
+ return sorted.join(", ");
276
+ } else {
277
+ return `${sorted.slice(0, 5).join(", ")}, +${sorted.length - 5}`;
278
+ }
279
+ }
280
+ return `${attr}`;
281
+ }
282
+ function getSanitizedUrl(attributes, kind) {
283
+ const httpTarget = attributes[SEMATTRS_HTTP_TARGET];
284
+ const httpUrl = attributes[SEMATTRS_HTTP_URL] || attributes[ATTR_URL_FULL];
285
+ const httpRoute = attributes[ATTR_HTTP_ROUTE];
286
+ const parsedUrl = typeof httpUrl === "string" ? parseUrl(httpUrl) : void 0;
287
+ const url = parsedUrl ? getSanitizedUrlString(parsedUrl) : void 0;
288
+ const query = parsedUrl?.search || void 0;
289
+ const fragment = parsedUrl?.hash || void 0;
290
+ if (typeof httpRoute === "string") {
291
+ return { urlPath: httpRoute, url, query, fragment, hasRoute: true };
292
+ }
293
+ if (kind === SpanKind.SERVER && typeof httpTarget === "string") {
294
+ return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
295
+ }
296
+ if (parsedUrl) {
297
+ return { urlPath: url, url, query, fragment, hasRoute: false };
298
+ }
299
+ if (typeof httpTarget === "string") {
300
+ return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
301
+ }
302
+ return { urlPath: void 0, url, query, fragment, hasRoute: false };
303
+ }
304
+ function getUserUpdatedNameAndSource(originalName, attributes, fallbackSource = "custom") {
305
+ const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] || fallbackSource;
306
+ const description = attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
307
+ if (description && typeof description === "string") {
308
+ return {
309
+ description,
310
+ source
311
+ };
312
+ }
313
+ return { description: originalName, source };
314
+ }
315
+
316
+ function enhanceDscWithOpenTelemetryRootSpanName(client) {
317
+ client.on("createDsc", (dsc, rootSpan) => {
318
+ if (!rootSpan) {
319
+ return;
320
+ }
321
+ const jsonSpan = spanToJSON(rootSpan);
322
+ const attributes = jsonSpan.data;
323
+ const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
324
+ const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: void 0 };
325
+ if (source !== "url" && description) {
326
+ dsc.transaction = description;
327
+ }
328
+ if (hasSpansEnabled()) {
329
+ const sampled = getSamplingDecision(rootSpan.spanContext());
330
+ dsc.sampled = sampled == void 0 ? void 0 : String(sampled);
331
+ }
332
+ });
333
+ }
334
+
335
+ function getActiveSpan() {
336
+ return trace.getActiveSpan();
337
+ }
338
+
339
+ function makeTraceState({
340
+ dsc,
341
+ sampled
342
+ }) {
343
+ const dscString = dsc ? dynamicSamplingContextToSentryBaggageHeader(dsc) : void 0;
344
+ const traceStateBase = new TraceState();
345
+ const traceStateWithDsc = dscString ? traceStateBase.set(SENTRY_TRACE_STATE_DSC, dscString) : traceStateBase;
346
+ return sampled === false ? traceStateWithDsc.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, "1") : traceStateWithDsc;
347
+ }
348
+
349
+ const setupElements = /* @__PURE__ */ new Set();
350
+ function openTelemetrySetupCheck() {
351
+ return Array.from(setupElements);
352
+ }
353
+ function setIsSetup(element) {
354
+ setupElements.add(element);
355
+ }
356
+
357
+ class SentryPropagator extends W3CBaggagePropagator {
358
+ constructor() {
359
+ super();
360
+ setIsSetup("SentryPropagator");
361
+ this._urlMatchesTargetsMap = new LRUMap(100);
362
+ }
363
+ /**
364
+ * @inheritDoc
365
+ */
366
+ inject(context2, carrier, setter) {
367
+ if (isTracingSuppressed(context2)) {
368
+ DEBUG_BUILD && debug.log("[Tracing] Not injecting trace data for url because tracing is suppressed.");
369
+ return;
370
+ }
371
+ const activeSpan = trace.getSpan(context2);
372
+ const url = activeSpan && getCurrentURL(activeSpan);
373
+ const { tracePropagationTargets, propagateTraceparent } = getClient()?.getOptions() || {};
374
+ if (!shouldPropagateTraceForUrl(url, tracePropagationTargets, this._urlMatchesTargetsMap)) {
375
+ DEBUG_BUILD && debug.log("[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:", url);
376
+ return;
377
+ }
378
+ const existingBaggageHeader = getExistingBaggage(carrier);
379
+ const existingSentryTraceHeader = getExistingSentryTrace(carrier);
380
+ let baggage = propagation.getBaggage(context2) || propagation.createBaggage({});
381
+ const { dynamicSamplingContext, traceId, spanId, sampled } = getInjectionData(context2);
382
+ if (existingBaggageHeader) {
383
+ const baggageEntries = parseBaggageHeader(existingBaggageHeader);
384
+ if (baggageEntries) {
385
+ Object.entries(baggageEntries).forEach(([key, value]) => {
386
+ if (!existingSentryTraceHeader && key.startsWith(SENTRY_BAGGAGE_KEY_PREFIX)) {
387
+ return;
388
+ }
389
+ baggage = baggage.setEntry(key, { value });
390
+ });
391
+ }
392
+ }
393
+ if (!existingSentryTraceHeader && dynamicSamplingContext) {
394
+ baggage = Object.entries(dynamicSamplingContext).reduce((b, [dscKey, dscValue]) => {
395
+ if (dscValue) {
396
+ return b.setEntry(`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`, { value: dscValue });
397
+ }
398
+ return b;
399
+ }, baggage);
400
+ }
401
+ if (!existingSentryTraceHeader && traceId && traceId !== INVALID_TRACEID) {
402
+ setter.set(carrier, SENTRY_TRACE_HEADER, generateSentryTraceHeader(traceId, spanId, sampled));
403
+ if (propagateTraceparent) {
404
+ setter.set(carrier, "traceparent", generateTraceparentHeader(traceId, spanId, sampled));
405
+ }
406
+ }
407
+ super.inject(propagation.setBaggage(context2, baggage), carrier, setter);
408
+ }
409
+ /**
410
+ * @inheritDoc
411
+ */
412
+ extract(context2, carrier, getter) {
413
+ const maybeSentryTraceHeader = getter.get(carrier, SENTRY_TRACE_HEADER);
414
+ const baggage = getter.get(carrier, SENTRY_BAGGAGE_HEADER);
415
+ const sentryTrace = maybeSentryTraceHeader ? Array.isArray(maybeSentryTraceHeader) ? maybeSentryTraceHeader[0] : maybeSentryTraceHeader : void 0;
416
+ return ensureScopesOnContext(getContextWithRemoteActiveSpan(context2, { sentryTrace, baggage }));
417
+ }
418
+ /**
419
+ * @inheritDoc
420
+ */
421
+ fields() {
422
+ return [SENTRY_TRACE_HEADER, SENTRY_BAGGAGE_HEADER, "traceparent"];
423
+ }
424
+ }
425
+ function getInjectionData(context2, options = {}) {
426
+ const span = trace.getSpan(context2);
427
+ if (span?.spanContext().isRemote) {
428
+ const spanContext = span.spanContext();
429
+ const dynamicSamplingContext2 = getDynamicSamplingContextFromSpan(span);
430
+ return {
431
+ dynamicSamplingContext: dynamicSamplingContext2,
432
+ traceId: spanContext.traceId,
433
+ spanId: void 0,
434
+ sampled: getSamplingDecision(spanContext)
435
+ // TODO: Do we need to change something here?
436
+ };
437
+ }
438
+ if (span) {
439
+ const spanContext = span.spanContext();
440
+ const dynamicSamplingContext2 = getDynamicSamplingContextFromSpan(span);
441
+ return {
442
+ dynamicSamplingContext: dynamicSamplingContext2,
443
+ traceId: spanContext.traceId,
444
+ spanId: spanContext.spanId,
445
+ sampled: getSamplingDecision(spanContext)
446
+ // TODO: Do we need to change something here?
447
+ };
448
+ }
449
+ const scope = options.scope || getScopesFromContext(context2)?.scope || getCurrentScope();
450
+ const client = options.client || getClient();
451
+ const propagationContext = scope.getPropagationContext();
452
+ const dynamicSamplingContext = client ? getDynamicSamplingContextFromScope(client, scope) : void 0;
453
+ return {
454
+ dynamicSamplingContext,
455
+ traceId: propagationContext.traceId,
456
+ spanId: propagationContext.propagationSpanId,
457
+ sampled: propagationContext.sampled
458
+ };
459
+ }
460
+ function getContextWithRemoteActiveSpan(ctx, { sentryTrace, baggage }) {
461
+ const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
462
+ const { traceId, parentSpanId, sampled, dsc } = propagationContext;
463
+ const client = getClient();
464
+ const incomingDsc = baggageHeaderToDynamicSamplingContext(baggage);
465
+ if (!parentSpanId || client && !shouldContinueTrace(client, incomingDsc?.org_id)) {
466
+ return ctx;
467
+ }
468
+ const spanContext = generateRemoteSpanContext({
469
+ traceId,
470
+ spanId: parentSpanId,
471
+ sampled,
472
+ dsc
473
+ });
474
+ return trace.setSpanContext(ctx, spanContext);
475
+ }
476
+ function continueTraceAsRemoteSpan(ctx, options, callback) {
477
+ const ctxWithSpanContext = ensureScopesOnContext(getContextWithRemoteActiveSpan(ctx, options));
478
+ return context.with(ctxWithSpanContext, callback);
479
+ }
480
+ function ensureScopesOnContext(ctx) {
481
+ const scopes = getScopesFromContext(ctx);
482
+ const newScopes = {
483
+ // If we have no scope here, this is most likely either the root context or a context manually derived from it
484
+ // In this case, we want to fork the current scope, to ensure we do not pollute the root scope
485
+ scope: scopes ? scopes.scope : getCurrentScope().clone(),
486
+ isolationScope: scopes ? scopes.isolationScope : getIsolationScope()
487
+ };
488
+ return setScopesOnContext(ctx, newScopes);
489
+ }
490
+ function getExistingBaggage(carrier) {
491
+ try {
492
+ const baggage = carrier[SENTRY_BAGGAGE_HEADER];
493
+ return Array.isArray(baggage) ? baggage.join(",") : baggage;
494
+ } catch {
495
+ return void 0;
496
+ }
497
+ }
498
+ function getExistingSentryTrace(carrier) {
499
+ try {
500
+ return carrier[SENTRY_TRACE_HEADER];
501
+ } catch {
502
+ return void 0;
503
+ }
504
+ }
505
+ function getCurrentURL(span) {
506
+ const spanData = spanToJSON(span).data;
507
+ const urlAttribute = spanData[SEMATTRS_HTTP_URL] || spanData[ATTR_URL_FULL];
508
+ if (typeof urlAttribute === "string") {
509
+ return urlAttribute;
510
+ }
511
+ const urlTraceState = span.spanContext().traceState?.get(SENTRY_TRACE_STATE_URL);
512
+ if (urlTraceState) {
513
+ return urlTraceState;
514
+ }
515
+ return void 0;
516
+ }
517
+ function generateRemoteSpanContext({
518
+ spanId,
519
+ traceId,
520
+ sampled,
521
+ dsc
522
+ }) {
523
+ const traceState = makeTraceState({
524
+ dsc,
525
+ sampled
526
+ });
527
+ const spanContext = {
528
+ traceId,
529
+ spanId,
530
+ isRemote: true,
531
+ traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
532
+ traceState
533
+ };
534
+ return spanContext;
535
+ }
536
+
537
+ function _startSpan(options, callback, autoEnd) {
538
+ const tracer = getTracer();
539
+ const { name, parentSpan: customParentSpan } = options;
540
+ const wrapper = getActiveSpanWrapper(customParentSpan);
541
+ return wrapper(() => {
542
+ const activeCtx = getContext(options.scope, options.forceTransaction);
543
+ const missingRequiredParent = options.onlyIfParent && !trace.getSpan(activeCtx);
544
+ const ctx = missingRequiredParent ? suppressTracing$1(activeCtx) : activeCtx;
545
+ if (missingRequiredParent) {
546
+ getClient()?.recordDroppedEvent("no_parent_span", "span");
547
+ }
548
+ const spanOptions = getSpanOptions(options);
549
+ if (!hasSpansEnabled()) {
550
+ const suppressedCtx = isTracingSuppressed(ctx) ? ctx : suppressTracing$1(ctx);
551
+ return context.with(suppressedCtx, () => {
552
+ return tracer.startActiveSpan(name, spanOptions, suppressedCtx, (span) => {
553
+ patchSpanEnd(span);
554
+ return context.with(activeCtx, () => {
555
+ return handleCallbackErrors(
556
+ () => callback(span),
557
+ () => {
558
+ if (spanToJSON(span).status === void 0) {
559
+ span.setStatus({ code: SpanStatusCode.ERROR });
560
+ }
561
+ },
562
+ autoEnd ? () => span.end() : void 0
563
+ );
564
+ });
565
+ });
566
+ });
567
+ }
568
+ return tracer.startActiveSpan(name, spanOptions, ctx, (span) => {
569
+ patchSpanEnd(span);
570
+ return handleCallbackErrors(
571
+ () => callback(span),
572
+ () => {
573
+ if (spanToJSON(span).status === void 0) {
574
+ span.setStatus({ code: SpanStatusCode.ERROR });
575
+ }
576
+ },
577
+ autoEnd ? () => span.end() : void 0
578
+ );
579
+ });
580
+ });
581
+ }
582
+ function startSpan(options, callback) {
583
+ return _startSpan(options, callback, true);
584
+ }
585
+ function startSpanManual(options, callback) {
586
+ return _startSpan(options, (span) => callback(span, () => span.end()), false);
587
+ }
588
+ function startInactiveSpan(options) {
589
+ const tracer = getTracer();
590
+ const { name, parentSpan: customParentSpan } = options;
591
+ const wrapper = getActiveSpanWrapper(customParentSpan);
592
+ return wrapper(() => {
593
+ const activeCtx = getContext(options.scope, options.forceTransaction);
594
+ const missingRequiredParent = options.onlyIfParent && !trace.getSpan(activeCtx);
595
+ let ctx = missingRequiredParent ? suppressTracing$1(activeCtx) : activeCtx;
596
+ if (missingRequiredParent) {
597
+ getClient()?.recordDroppedEvent("no_parent_span", "span");
598
+ }
599
+ const spanOptions = getSpanOptions(options);
600
+ if (!hasSpansEnabled()) {
601
+ ctx = isTracingSuppressed(ctx) ? ctx : suppressTracing$1(ctx);
602
+ }
603
+ const span = tracer.startSpan(name, spanOptions, ctx);
604
+ patchSpanEnd(span);
605
+ return span;
606
+ });
607
+ }
608
+ function withActiveSpan(span, callback) {
609
+ const newContextWithActiveSpan = span ? trace.setSpan(context.active(), span) : trace.deleteSpan(context.active());
610
+ return context.with(newContextWithActiveSpan, () => callback(getCurrentScope()));
611
+ }
612
+ function getTracer() {
613
+ const client = getClient();
614
+ return client?.tracer || trace.getTracer("@sentry/opentelemetry", SDK_VERSION);
615
+ }
616
+ function getSpanOptions(options) {
617
+ const { startTime, attributes, kind, op, links } = options;
618
+ const fixedStartTime = typeof startTime === "number" ? ensureTimestampInMilliseconds(startTime) : startTime;
619
+ return {
620
+ attributes: op ? {
621
+ [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
622
+ ...attributes
623
+ } : attributes,
624
+ kind,
625
+ links,
626
+ startTime: fixedStartTime
627
+ };
628
+ }
629
+ function ensureTimestampInMilliseconds(timestamp) {
630
+ const isMs = timestamp < 9999999999;
631
+ return isMs ? timestamp * 1e3 : timestamp;
632
+ }
633
+ function patchSpanEnd(span) {
634
+ const originalEnd = span.end.bind(span);
635
+ span.end = (endTime) => {
636
+ return originalEnd(typeof endTime === "number" ? ensureTimestampInMilliseconds(endTime) : endTime);
637
+ };
638
+ }
639
+ function getContext(scope, forceTransaction) {
640
+ const ctx = getContextForScope(scope);
641
+ const parentSpan = trace.getSpan(ctx);
642
+ if (!parentSpan) {
643
+ return ctx;
644
+ }
645
+ if (!forceTransaction) {
646
+ return ctx;
647
+ }
648
+ const ctxWithoutSpan = trace.deleteSpan(ctx);
649
+ const { spanId, traceId } = parentSpan.spanContext();
650
+ const sampled = getSamplingDecision(parentSpan.spanContext());
651
+ const rootSpan = getRootSpan(parentSpan);
652
+ const dsc = getDynamicSamplingContextFromSpan(rootSpan);
653
+ const traceState = makeTraceState({
654
+ dsc,
655
+ sampled
656
+ });
657
+ const spanOptions = {
658
+ traceId,
659
+ spanId,
660
+ isRemote: true,
661
+ traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
662
+ traceState
663
+ };
664
+ const ctxWithSpanContext = trace.setSpanContext(ctxWithoutSpan, spanOptions);
665
+ return ctxWithSpanContext;
666
+ }
667
+ function getContextForScope(scope) {
668
+ if (scope) {
669
+ const ctx = getContextFromScope(scope);
670
+ if (ctx) {
671
+ return ctx;
672
+ }
673
+ }
674
+ return context.active();
675
+ }
676
+ function continueTrace(options, callback) {
677
+ return continueTraceAsRemoteSpan(context.active(), options, callback);
678
+ }
679
+ function startNewTrace(callback) {
680
+ const traceId = generateTraceId();
681
+ const spanId = generateSpanId();
682
+ const spanContext = {
683
+ traceId,
684
+ spanId,
685
+ isRemote: true,
686
+ traceFlags: TraceFlags.NONE
687
+ };
688
+ const ctxWithTrace = trace.setSpanContext(context.active(), spanContext);
689
+ return context.with(ctxWithTrace, () => {
690
+ getCurrentScope().setPropagationContext({
691
+ traceId,
692
+ sampleRand: _INTERNAL_safeMathRandom()
693
+ });
694
+ return callback();
695
+ });
696
+ }
697
+ function getTraceContextForScope(client, scope) {
698
+ const ctx = getContextFromScope(scope);
699
+ const span = ctx && trace.getSpan(ctx);
700
+ const traceContext = span ? spanToTraceContext(span) : getTraceContextFromScope(scope);
701
+ const dynamicSamplingContext = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope);
702
+ return [dynamicSamplingContext, traceContext];
703
+ }
704
+ function getActiveSpanWrapper(parentSpan) {
705
+ return parentSpan !== void 0 ? (callback) => {
706
+ return withActiveSpan(parentSpan, callback);
707
+ } : (callback) => callback();
708
+ }
709
+
710
+ function suppressTracing(callback) {
711
+ const ctx = suppressTracing$1(context.active());
712
+ return context.with(ctx, callback);
713
+ }
714
+
715
+ function setupEventContextTrace(client) {
716
+ client.on("preprocessEvent", (event) => {
717
+ const span = getActiveSpan();
718
+ if (!span || event.type === "transaction") {
719
+ return;
720
+ }
721
+ event.contexts = {
722
+ trace: spanToTraceContext(span),
723
+ ...event.contexts
724
+ };
725
+ const rootSpan = getRootSpan(span);
726
+ event.sdkProcessingMetadata = {
727
+ dynamicSamplingContext: getDynamicSamplingContextFromSpan(rootSpan),
728
+ ...event.sdkProcessingMetadata
729
+ };
730
+ return event;
731
+ });
732
+ }
733
+
734
+ function getTraceData({
735
+ span,
736
+ scope,
737
+ client,
738
+ propagateTraceparent
739
+ } = {}) {
740
+ let ctx = (scope && getContextFromScope(scope)) ?? api.context.active();
741
+ if (span) {
742
+ const { scope: scope2 } = getCapturedScopesOnSpan(span);
743
+ ctx = scope2 && getContextFromScope(scope2) || api.trace.setSpan(api.context.active(), span);
744
+ }
745
+ const { traceId, spanId, sampled, dynamicSamplingContext } = getInjectionData(ctx, { scope, client });
746
+ const traceData = {
747
+ "sentry-trace": generateSentryTraceHeader(traceId, spanId, sampled),
748
+ baggage: dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext)
749
+ };
750
+ if (propagateTraceparent) {
751
+ traceData.traceparent = generateTraceparentHeader(traceId, spanId, sampled);
752
+ }
753
+ return traceData;
754
+ }
755
+
756
+ function setOpenTelemetryContextAsyncContextStrategy() {
757
+ function getScopes() {
758
+ const ctx = api.context.active();
759
+ const scopes = getScopesFromContext(ctx);
760
+ if (scopes) {
761
+ return scopes;
762
+ }
763
+ return {
764
+ scope: getDefaultCurrentScope(),
765
+ isolationScope: getDefaultIsolationScope()
766
+ };
767
+ }
768
+ function withScope(callback) {
769
+ const ctx = api.context.active();
770
+ return api.context.with(ctx, () => {
771
+ return callback(getCurrentScope());
772
+ });
773
+ }
774
+ function withSetScope(scope, callback) {
775
+ const ctx = getContextFromScope(scope) || api.context.active();
776
+ return api.context.with(ctx.setValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY, scope), () => {
777
+ return callback(scope);
778
+ });
779
+ }
780
+ function withIsolationScope(callback) {
781
+ const ctx = api.context.active();
782
+ return api.context.with(ctx.setValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY, true), () => {
783
+ return callback(getIsolationScope());
784
+ });
785
+ }
786
+ function withSetIsolationScope(isolationScope, callback) {
787
+ const ctx = api.context.active();
788
+ return api.context.with(ctx.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, isolationScope), () => {
789
+ return callback(getIsolationScope());
790
+ });
791
+ }
792
+ function getCurrentScope() {
793
+ return getScopes().scope;
794
+ }
795
+ function getIsolationScope() {
796
+ return getScopes().isolationScope;
797
+ }
798
+ setAsyncContextStrategy({
799
+ withScope,
800
+ withSetScope,
801
+ withSetIsolationScope,
802
+ withIsolationScope,
803
+ getCurrentScope,
804
+ getIsolationScope,
805
+ startSpan,
806
+ startSpanManual,
807
+ startInactiveSpan,
808
+ getActiveSpan,
809
+ suppressTracing,
810
+ getTraceData,
811
+ continueTrace,
812
+ startNewTrace,
813
+ // The types here don't fully align, because our own `Span` type is narrower
814
+ // than the OTEL one - but this is OK for here, as we now we'll only have OTEL spans passed around
815
+ withActiveSpan
816
+ });
817
+ }
818
+
819
+ function buildContextWithSentryScopes(context, activeContext) {
820
+ const span = trace.getSpan(context);
821
+ let effectiveContext;
822
+ if (span?.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === "1") {
823
+ const contextWithoutSpan = trace.deleteSpan(context);
824
+ const parentSpan = trace.getSpan(activeContext);
825
+ effectiveContext = parentSpan ? trace.setSpan(contextWithoutSpan, parentSpan) : contextWithoutSpan;
826
+ } else {
827
+ effectiveContext = context;
828
+ }
829
+ const currentScopes = getScopesFromContext(effectiveContext);
830
+ const currentScope = currentScopes?.scope || getCurrentScope();
831
+ const currentIsolationScope = currentScopes?.isolationScope || getIsolationScope();
832
+ const shouldForkIsolationScope = effectiveContext.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
833
+ const scope = effectiveContext.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY);
834
+ const isolationScope = effectiveContext.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
835
+ const newCurrentScope = scope || currentScope.clone();
836
+ const newIsolationScope = isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);
837
+ const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };
838
+ const ctx1 = setScopesOnContext(effectiveContext, scopes);
839
+ const ctx2 = ctx1.deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY).deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY).deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
840
+ setContextOnScope(newCurrentScope, ctx2);
841
+ return ctx2;
842
+ }
843
+
844
+ function wrapContextManagerClass(ContextManagerClass) {
845
+ class SentryContextManager extends ContextManagerClass {
846
+ constructor(...args) {
847
+ super(...args);
848
+ setIsSetup("SentryContextManager");
849
+ }
850
+ /**
851
+ * Overwrite with() of the original AsyncLocalStorageContextManager
852
+ * to ensure we also create new scopes per context.
853
+ */
854
+ with(context, fn, thisArg, ...args) {
855
+ const ctx2 = buildContextWithSentryScopes(context, this.active());
856
+ return super.with(ctx2, fn, thisArg, ...args);
857
+ }
858
+ /**
859
+ * Gets underlying AsyncLocalStorage and symbol to allow lookup of scope.
860
+ */
861
+ getAsyncLocalStorageLookup() {
862
+ return {
863
+ // @ts-expect-error This is on the base class, but not part of the interface
864
+ asyncLocalStorage: this._asyncLocalStorage,
865
+ contextSymbol: SENTRY_SCOPES_CONTEXT_KEY
866
+ };
867
+ }
868
+ }
869
+ return SentryContextManager;
870
+ }
871
+
872
+ function groupSpansWithParents(spans) {
873
+ const nodeMap = /* @__PURE__ */ new Map();
874
+ for (const span of spans) {
875
+ createOrUpdateSpanNodeAndRefs(nodeMap, span);
876
+ }
877
+ return Array.from(nodeMap, function([_id, spanNode]) {
878
+ return spanNode;
879
+ });
880
+ }
881
+ function getLocalParentId(span) {
882
+ const parentIsRemote = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE] === true;
883
+ return !parentIsRemote ? getParentSpanId(span) : void 0;
884
+ }
885
+ function createOrUpdateSpanNodeAndRefs(nodeMap, span) {
886
+ const id = span.spanContext().spanId;
887
+ const parentId = getLocalParentId(span);
888
+ if (!parentId) {
889
+ createOrUpdateNode(nodeMap, { id, span, children: [] });
890
+ return;
891
+ }
892
+ const parentNode = createOrGetParentNode(nodeMap, parentId);
893
+ const node = createOrUpdateNode(nodeMap, { id, span, parentNode, children: [] });
894
+ parentNode.children.push(node);
895
+ }
896
+ function createOrGetParentNode(nodeMap, id) {
897
+ const existing = nodeMap.get(id);
898
+ if (existing) {
899
+ return existing;
900
+ }
901
+ return createOrUpdateNode(nodeMap, { id, children: [] });
902
+ }
903
+ function createOrUpdateNode(nodeMap, spanNode) {
904
+ const existing = nodeMap.get(spanNode.id);
905
+ if (existing?.span) {
906
+ return existing;
907
+ }
908
+ if (existing && !existing.span) {
909
+ existing.span = spanNode.span;
910
+ existing.parentNode = spanNode.parentNode;
911
+ return existing;
912
+ }
913
+ nodeMap.set(spanNode.id, spanNode);
914
+ return spanNode;
915
+ }
916
+
917
+ const canonicalGrpcErrorCodesMap = {
918
+ "1": "cancelled",
919
+ "2": "unknown_error",
920
+ "3": "invalid_argument",
921
+ "4": "deadline_exceeded",
922
+ "5": "not_found",
923
+ "6": "already_exists",
924
+ "7": "permission_denied",
925
+ "8": "resource_exhausted",
926
+ "9": "failed_precondition",
927
+ "10": "aborted",
928
+ "11": "out_of_range",
929
+ "12": "unimplemented",
930
+ "13": "internal_error",
931
+ "14": "unavailable",
932
+ "15": "data_loss",
933
+ "16": "unauthenticated"
934
+ };
935
+ const isStatusErrorMessageValid = (message) => {
936
+ return Object.values(canonicalGrpcErrorCodesMap).includes(message);
937
+ };
938
+ function mapStatus(span) {
939
+ const attributes = spanHasAttributes(span) ? span.attributes : {};
940
+ const status = spanHasStatus(span) ? span.status : void 0;
941
+ if (status) {
942
+ if (status.code === SpanStatusCode.OK) {
943
+ return { code: SPAN_STATUS_OK };
944
+ } else if (status.code === SpanStatusCode.ERROR) {
945
+ if (typeof status.message === "undefined") {
946
+ const inferredStatus2 = inferStatusFromAttributes(attributes);
947
+ if (inferredStatus2) {
948
+ return inferredStatus2;
949
+ }
950
+ }
951
+ if (status.message && isStatusErrorMessageValid(status.message)) {
952
+ return { code: SPAN_STATUS_ERROR, message: status.message };
953
+ } else {
954
+ return { code: SPAN_STATUS_ERROR, message: "internal_error" };
955
+ }
956
+ }
957
+ }
958
+ const inferredStatus = inferStatusFromAttributes(attributes);
959
+ if (inferredStatus) {
960
+ return inferredStatus;
961
+ }
962
+ if (status?.code === SpanStatusCode.UNSET) {
963
+ return { code: SPAN_STATUS_OK };
964
+ } else {
965
+ return { code: SPAN_STATUS_ERROR, message: "unknown_error" };
966
+ }
967
+ }
968
+ function inferStatusFromAttributes(attributes) {
969
+ const httpCodeAttribute = attributes[ATTR_HTTP_RESPONSE_STATUS_CODE] || attributes[SEMATTRS_HTTP_STATUS_CODE];
970
+ const grpcCodeAttribute = attributes[SEMATTRS_RPC_GRPC_STATUS_CODE];
971
+ const numberHttpCode = typeof httpCodeAttribute === "number" ? httpCodeAttribute : typeof httpCodeAttribute === "string" ? parseInt(httpCodeAttribute) : void 0;
972
+ if (typeof numberHttpCode === "number") {
973
+ return getSpanStatusFromHttpCode(numberHttpCode);
974
+ }
975
+ if (typeof grpcCodeAttribute === "string") {
976
+ return { code: SPAN_STATUS_ERROR, message: canonicalGrpcErrorCodesMap[grpcCodeAttribute] || "unknown_error" };
977
+ }
978
+ return void 0;
979
+ }
980
+
981
+ const MAX_SPAN_COUNT = 1e3;
982
+ const DEFAULT_TIMEOUT = 300;
983
+ class SentrySpanExporter {
984
+ constructor(options) {
985
+ this._finishedSpanBucketSize = options?.timeout || DEFAULT_TIMEOUT;
986
+ this._finishedSpanBuckets = new Array(this._finishedSpanBucketSize).fill(void 0);
987
+ this._lastCleanupTimestampInS = Math.floor(_INTERNAL_safeDateNow() / 1e3);
988
+ this._spansToBucketEntry = /* @__PURE__ */ new WeakMap();
989
+ this._sentSpans = /* @__PURE__ */ new Map();
990
+ this._debouncedFlush = debounce(this.flush.bind(this), 1, { maxWait: 100 });
991
+ }
992
+ /**
993
+ * Export a single span.
994
+ * This is called by the span processor whenever a span is ended.
995
+ */
996
+ export(span) {
997
+ const currentTimestampInS = Math.floor(_INTERNAL_safeDateNow() / 1e3);
998
+ if (this._lastCleanupTimestampInS !== currentTimestampInS) {
999
+ let droppedSpanCount = 0;
1000
+ this._finishedSpanBuckets.forEach((bucket, i) => {
1001
+ if (bucket && bucket.timestampInS <= currentTimestampInS - this._finishedSpanBucketSize) {
1002
+ droppedSpanCount += bucket.spans.size;
1003
+ this._finishedSpanBuckets[i] = void 0;
1004
+ }
1005
+ });
1006
+ if (droppedSpanCount > 0) {
1007
+ DEBUG_BUILD && debug.log(
1008
+ `SpanExporter dropped ${droppedSpanCount} spans because they were pending for more than ${this._finishedSpanBucketSize} seconds.`
1009
+ );
1010
+ }
1011
+ this._lastCleanupTimestampInS = currentTimestampInS;
1012
+ }
1013
+ const currentBucketIndex = currentTimestampInS % this._finishedSpanBucketSize;
1014
+ const currentBucket = this._finishedSpanBuckets[currentBucketIndex] || {
1015
+ timestampInS: currentTimestampInS,
1016
+ spans: /* @__PURE__ */ new Set()
1017
+ };
1018
+ this._finishedSpanBuckets[currentBucketIndex] = currentBucket;
1019
+ currentBucket.spans.add(span);
1020
+ this._spansToBucketEntry.set(span, currentBucket);
1021
+ const localParentId = getLocalParentId(span);
1022
+ if (!localParentId || this._sentSpans.has(localParentId)) {
1023
+ this._debouncedFlush();
1024
+ }
1025
+ }
1026
+ /**
1027
+ * Try to flush any pending spans immediately.
1028
+ * This is called internally by the exporter (via _debouncedFlush),
1029
+ * but can also be triggered externally if we force-flush.
1030
+ */
1031
+ flush() {
1032
+ const finishedSpans = this._finishedSpanBuckets.flatMap((bucket) => bucket ? Array.from(bucket.spans) : []);
1033
+ this._flushSentSpanCache();
1034
+ const sentSpans = this._maybeSend(finishedSpans);
1035
+ const sentSpanCount = sentSpans.size;
1036
+ const remainingOpenSpanCount = finishedSpans.length - sentSpanCount;
1037
+ DEBUG_BUILD && debug.log(
1038
+ `SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} spans are waiting for their parent spans to finish`
1039
+ );
1040
+ const expirationDate = _INTERNAL_safeDateNow() + DEFAULT_TIMEOUT * 1e3;
1041
+ for (const span of sentSpans) {
1042
+ this._sentSpans.set(span.spanContext().spanId, expirationDate);
1043
+ const bucketEntry = this._spansToBucketEntry.get(span);
1044
+ if (bucketEntry) {
1045
+ bucketEntry.spans.delete(span);
1046
+ }
1047
+ }
1048
+ this._debouncedFlush.cancel();
1049
+ }
1050
+ /**
1051
+ * Clear the exporter.
1052
+ * This is called when the span processor is shut down.
1053
+ */
1054
+ clear() {
1055
+ this._finishedSpanBuckets = this._finishedSpanBuckets.fill(void 0);
1056
+ this._sentSpans.clear();
1057
+ this._debouncedFlush.cancel();
1058
+ }
1059
+ /**
1060
+ * Send the given spans, but only if they are part of a finished transaction.
1061
+ *
1062
+ * Returns the sent spans.
1063
+ * Spans remain unsent when their parent span is not yet finished.
1064
+ * This will happen regularly, as child spans are generally finished before their parents.
1065
+ * But it _could_ also happen because, for whatever reason, a parent span was lost.
1066
+ * In this case, we'll eventually need to clean this up.
1067
+ */
1068
+ _maybeSend(spans) {
1069
+ const grouped = groupSpansWithParents(spans);
1070
+ const sentSpans = /* @__PURE__ */ new Set();
1071
+ const rootNodes = this._getCompletedRootNodes(grouped);
1072
+ for (const root of rootNodes) {
1073
+ const span = root.span;
1074
+ sentSpans.add(span);
1075
+ const transactionEvent = createTransactionForOtelSpan(span);
1076
+ if (root.parentNode && this._sentSpans.has(root.parentNode.id)) {
1077
+ const traceData = transactionEvent.contexts?.trace?.data;
1078
+ if (traceData) {
1079
+ traceData["sentry.parent_span_already_sent"] = true;
1080
+ }
1081
+ }
1082
+ const spans2 = transactionEvent.spans || [];
1083
+ let hasGenAiSpans = false;
1084
+ for (const child of root.children) {
1085
+ if (createAndFinishSpanForOtelSpan(child, spans2, sentSpans)) {
1086
+ hasGenAiSpans = true;
1087
+ }
1088
+ }
1089
+ transactionEvent.spans = spans2.length > MAX_SPAN_COUNT ? spans2.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT) : spans2;
1090
+ if (hasGenAiSpans) {
1091
+ transactionEvent.sdkProcessingMetadata = {
1092
+ ...transactionEvent.sdkProcessingMetadata,
1093
+ hasGenAiSpans: true
1094
+ };
1095
+ }
1096
+ const measurements = timedEventsToMeasurements(span.events);
1097
+ if (measurements) {
1098
+ transactionEvent.measurements = measurements;
1099
+ }
1100
+ captureEvent(transactionEvent);
1101
+ }
1102
+ return sentSpans;
1103
+ }
1104
+ /** Remove "expired" span id entries from the _sentSpans cache. */
1105
+ _flushSentSpanCache() {
1106
+ const currentTimestamp = _INTERNAL_safeDateNow();
1107
+ for (const [spanId, expirationTime] of this._sentSpans.entries()) {
1108
+ if (expirationTime <= currentTimestamp) {
1109
+ this._sentSpans.delete(spanId);
1110
+ }
1111
+ }
1112
+ }
1113
+ /** Check if a node is a completed root node or a node whose parent has already been sent */
1114
+ _nodeIsCompletedRootNodeOrHasSentParent(node) {
1115
+ return !!node.span && (!node.parentNode || this._sentSpans.has(node.parentNode.id));
1116
+ }
1117
+ /** Get all completed root nodes from a list of nodes */
1118
+ _getCompletedRootNodes(nodes) {
1119
+ return nodes.filter((node) => this._nodeIsCompletedRootNodeOrHasSentParent(node));
1120
+ }
1121
+ }
1122
+ function parseSpan(span) {
1123
+ const attributes = span.attributes;
1124
+ const origin = attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN];
1125
+ const op = attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP];
1126
+ const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
1127
+ return { origin, op, source };
1128
+ }
1129
+ function createTransactionForOtelSpan(span) {
1130
+ const { op, description, data, origin = "manual", source } = getSpanData(span);
1131
+ const capturedSpanScopes = getCapturedScopesOnSpan(span);
1132
+ const sampleRate = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
1133
+ const attributes = {
1134
+ [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source,
1135
+ [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate,
1136
+ [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
1137
+ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,
1138
+ ...data,
1139
+ ...removeSentryAttributes(span.attributes)
1140
+ };
1141
+ const { links } = span;
1142
+ const { traceId: trace_id, spanId: span_id } = span.spanContext();
1143
+ const parent_span_id = getParentSpanId(span);
1144
+ const status = mapStatus(span);
1145
+ const traceContext = {
1146
+ parent_span_id,
1147
+ span_id,
1148
+ trace_id,
1149
+ data: attributes,
1150
+ origin,
1151
+ op,
1152
+ status: getStatusMessage(status),
1153
+ // As per protocol, span status is allowed to be undefined
1154
+ links: convertSpanLinksForEnvelope(links)
1155
+ };
1156
+ const statusCode = attributes[ATTR_HTTP_RESPONSE_STATUS_CODE];
1157
+ const responseContext = typeof statusCode === "number" ? { response: { status_code: statusCode } } : void 0;
1158
+ const transactionEvent = {
1159
+ contexts: {
1160
+ trace: traceContext,
1161
+ otel: {
1162
+ resource: span.resource.attributes
1163
+ },
1164
+ ...responseContext
1165
+ },
1166
+ spans: [],
1167
+ start_timestamp: spanTimeInputToSeconds(span.startTime),
1168
+ timestamp: spanTimeInputToSeconds(span.endTime),
1169
+ transaction: description,
1170
+ type: "transaction",
1171
+ sdkProcessingMetadata: {
1172
+ capturedSpanScope: capturedSpanScopes.scope,
1173
+ capturedSpanIsolationScope: capturedSpanScopes.isolationScope,
1174
+ sampleRate,
1175
+ dynamicSamplingContext: getDynamicSamplingContextFromSpan(span)
1176
+ },
1177
+ ...source && {
1178
+ transaction_info: {
1179
+ source
1180
+ }
1181
+ }
1182
+ };
1183
+ return transactionEvent;
1184
+ }
1185
+ function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
1186
+ const span = node.span;
1187
+ if (span) {
1188
+ sentSpans.add(span);
1189
+ }
1190
+ const shouldDrop = !span;
1191
+ if (shouldDrop) {
1192
+ let hasGenAiSpans2 = false;
1193
+ node.children.forEach((child) => {
1194
+ if (createAndFinishSpanForOtelSpan(child, spans, sentSpans)) {
1195
+ hasGenAiSpans2 = true;
1196
+ }
1197
+ });
1198
+ return hasGenAiSpans2;
1199
+ }
1200
+ const span_id = span.spanContext().spanId;
1201
+ const trace_id = span.spanContext().traceId;
1202
+ const parentSpanId = getParentSpanId(span);
1203
+ const { attributes, startTime, endTime, links } = span;
1204
+ const { op, description, data, origin = "manual" } = getSpanData(span);
1205
+ const allData = {
1206
+ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,
1207
+ [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
1208
+ ...removeSentryAttributes(attributes),
1209
+ ...data
1210
+ };
1211
+ const status = mapStatus(span);
1212
+ const spanJSON = {
1213
+ span_id,
1214
+ trace_id,
1215
+ data: allData,
1216
+ description,
1217
+ parent_span_id: parentSpanId,
1218
+ start_timestamp: spanTimeInputToSeconds(startTime),
1219
+ // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time
1220
+ timestamp: spanTimeInputToSeconds(endTime) || void 0,
1221
+ status: getStatusMessage(status),
1222
+ // As per protocol, span status is allowed to be undefined
1223
+ op,
1224
+ origin,
1225
+ measurements: timedEventsToMeasurements(span.events),
1226
+ links: convertSpanLinksForEnvelope(links)
1227
+ };
1228
+ spans.push(spanJSON);
1229
+ let hasGenAiSpans = !!op?.startsWith("gen_ai.");
1230
+ node.children.forEach((child) => {
1231
+ if (createAndFinishSpanForOtelSpan(child, spans, sentSpans)) {
1232
+ hasGenAiSpans = true;
1233
+ }
1234
+ });
1235
+ return hasGenAiSpans;
1236
+ }
1237
+ function getSpanData(span) {
1238
+ const { op: definedOp, source: definedSource, origin } = parseSpan(span);
1239
+ const { op: inferredOp, description, source: inferredSource, data: inferredData } = parseSpanDescription(span);
1240
+ const op = definedOp || inferredOp;
1241
+ const source = definedSource || inferredSource;
1242
+ const data = { ...inferredData, ...getData(span) };
1243
+ return {
1244
+ op,
1245
+ description,
1246
+ source,
1247
+ origin,
1248
+ data
1249
+ };
1250
+ }
1251
+ function removeSentryAttributes(data) {
1252
+ const cleanedData = { ...data };
1253
+ delete cleanedData[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
1254
+ delete cleanedData[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE];
1255
+ delete cleanedData[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
1256
+ return cleanedData;
1257
+ }
1258
+ function getData(span) {
1259
+ const attributes = span.attributes;
1260
+ const data = {};
1261
+ if (span.kind !== SpanKind.INTERNAL) {
1262
+ data["otel.kind"] = SpanKind[span.kind];
1263
+ }
1264
+ const maybeHttpStatusCodeAttribute = attributes[SEMATTRS_HTTP_STATUS_CODE];
1265
+ if (maybeHttpStatusCodeAttribute) {
1266
+ data[ATTR_HTTP_RESPONSE_STATUS_CODE] = maybeHttpStatusCodeAttribute;
1267
+ }
1268
+ const requestData = getRequestSpanData(span);
1269
+ if (requestData.url) {
1270
+ data.url = requestData.url;
1271
+ }
1272
+ if (requestData["http.query"]) {
1273
+ data["http.query"] = requestData["http.query"].slice(1);
1274
+ }
1275
+ if (requestData["http.fragment"]) {
1276
+ data["http.fragment"] = requestData["http.fragment"].slice(1);
1277
+ }
1278
+ return data;
1279
+ }
1280
+
1281
+ class SentrySpanProcessor {
1282
+ constructor(options) {
1283
+ setIsSetup("SentrySpanProcessor");
1284
+ this._exporter = new SentrySpanExporter(options);
1285
+ }
1286
+ /**
1287
+ * @inheritDoc
1288
+ */
1289
+ async forceFlush() {
1290
+ this._exporter.flush();
1291
+ }
1292
+ /**
1293
+ * @inheritDoc
1294
+ */
1295
+ async shutdown() {
1296
+ this._exporter.clear();
1297
+ }
1298
+ /**
1299
+ * @inheritDoc
1300
+ */
1301
+ onStart(span, parentContext) {
1302
+ const parentSpan = trace.getSpan(parentContext);
1303
+ let scopes = getScopesFromContext(parentContext);
1304
+ if (parentSpan && !parentSpan.spanContext().isRemote) {
1305
+ addChildSpanToSpan(parentSpan, span);
1306
+ }
1307
+ if (parentSpan?.spanContext().isRemote) {
1308
+ span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE, true);
1309
+ }
1310
+ if (parentContext === ROOT_CONTEXT) {
1311
+ scopes = {
1312
+ scope: getDefaultCurrentScope(),
1313
+ isolationScope: getDefaultIsolationScope()
1314
+ };
1315
+ }
1316
+ if (scopes) {
1317
+ setCapturedScopesOnSpan(span, scopes.scope, scopes.isolationScope);
1318
+ }
1319
+ logSpanStart(span);
1320
+ const client = getClient();
1321
+ client?.emit("spanStart", span);
1322
+ }
1323
+ /** @inheritDoc */
1324
+ onEnd(span) {
1325
+ logSpanEnd(span);
1326
+ const client = getClient();
1327
+ client?.emit("spanEnd", span);
1328
+ if (client && hasSpanStreamingEnabled(client)) {
1329
+ client.emit("afterSpanEnd", span);
1330
+ } else {
1331
+ this._exporter.export(span);
1332
+ }
1333
+ }
1334
+ }
1335
+
1336
+ class SentrySampler {
1337
+ constructor(client) {
1338
+ this._client = client;
1339
+ this._isSpanStreaming = hasSpanStreamingEnabled(client);
1340
+ setIsSetup("SentrySampler");
1341
+ }
1342
+ /** @inheritDoc */
1343
+ shouldSample(context, traceId, spanName, spanKind, spanAttributes, _links) {
1344
+ const options = this._client.getOptions();
1345
+ const { ignoreSpans } = options;
1346
+ const parentSpan = getValidSpan(context);
1347
+ const parentContext = parentSpan?.spanContext();
1348
+ if (!hasSpansEnabled(options)) {
1349
+ return wrapSamplingDecision({ decision: void 0, context, spanAttributes });
1350
+ }
1351
+ const maybeSpanHttpMethod = spanAttributes[SEMATTRS_HTTP_METHOD] || spanAttributes[ATTR_HTTP_REQUEST_METHOD];
1352
+ if (spanKind === SpanKind.CLIENT && maybeSpanHttpMethod && (!parentSpan || parentContext?.isRemote)) {
1353
+ if (!this._isSpanStreaming) {
1354
+ this._client.recordDroppedEvent("no_parent_span", "span");
1355
+ return wrapSamplingDecision({ decision: void 0, context, spanAttributes });
1356
+ }
1357
+ }
1358
+ const parentSampled = parentSpan ? getParentSampled(parentSpan, traceId, spanName) : void 0;
1359
+ const isRootSpan = !parentSpan || parentContext?.isRemote;
1360
+ if (!isRootSpan) {
1361
+ if (this._isSpanStreaming) {
1362
+ if (parentSampled) {
1363
+ if (ignoreSpans?.length) {
1364
+ const { description: inferredChildName, op: childOp } = inferSpanData(spanName, spanAttributes, spanKind);
1365
+ if (shouldIgnoreSpan(
1366
+ {
1367
+ description: inferredChildName,
1368
+ op: spanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] ?? childOp,
1369
+ attributes: spanAttributes
1370
+ },
1371
+ ignoreSpans
1372
+ )) {
1373
+ this._client.recordDroppedEvent("ignored", "span");
1374
+ return wrapSamplingDecision({
1375
+ decision: SamplingDecision.NOT_RECORD,
1376
+ context,
1377
+ spanAttributes,
1378
+ ignoredChildSpan: true
1379
+ });
1380
+ }
1381
+ }
1382
+ }
1383
+ if (!parentSampled) {
1384
+ const parentSegmentIgnored = parentContext?.traceState?.get(SENTRY_TRACE_STATE_SEGMENT_IGNORED) === "1";
1385
+ this._client.recordDroppedEvent(parentSegmentIgnored ? "ignored" : "sample_rate", "span");
1386
+ }
1387
+ }
1388
+ return wrapSamplingDecision({
1389
+ decision: parentSampled ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.NOT_RECORD,
1390
+ context,
1391
+ spanAttributes
1392
+ });
1393
+ }
1394
+ const {
1395
+ description: inferredSpanName,
1396
+ data: inferredAttributes,
1397
+ op
1398
+ } = inferSpanData(spanName, spanAttributes, spanKind);
1399
+ const mergedAttributes = {
1400
+ ...inferredAttributes,
1401
+ ...spanAttributes
1402
+ };
1403
+ if (op) {
1404
+ mergedAttributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = op;
1405
+ }
1406
+ if (this._isSpanStreaming && ignoreSpans?.length && shouldIgnoreSpan(
1407
+ {
1408
+ description: inferredSpanName,
1409
+ op: mergedAttributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] ?? op,
1410
+ attributes: mergedAttributes
1411
+ },
1412
+ ignoreSpans
1413
+ )) {
1414
+ this._client.recordDroppedEvent("ignored", "span");
1415
+ return wrapSamplingDecision({
1416
+ decision: SamplingDecision.NOT_RECORD,
1417
+ context,
1418
+ spanAttributes,
1419
+ ignoredSegmentSpan: true
1420
+ });
1421
+ }
1422
+ const mutableSamplingDecision = { decision: true };
1423
+ this._client.emit(
1424
+ "beforeSampling",
1425
+ {
1426
+ spanAttributes: mergedAttributes,
1427
+ spanName: inferredSpanName,
1428
+ parentSampled,
1429
+ parentContext
1430
+ },
1431
+ mutableSamplingDecision
1432
+ );
1433
+ if (!mutableSamplingDecision.decision) {
1434
+ return wrapSamplingDecision({ decision: void 0, context, spanAttributes });
1435
+ }
1436
+ const { isolationScope } = getScopesFromContext(context) ?? {};
1437
+ const dscString = parentContext?.traceState ? parentContext.traceState.get(SENTRY_TRACE_STATE_DSC) : void 0;
1438
+ const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : void 0;
1439
+ const sampleRand = parseSampleRate(dsc?.sample_rand) ?? _INTERNAL_safeMathRandom();
1440
+ const [sampled, sampleRate, localSampleRateWasApplied] = sampleSpan(
1441
+ options,
1442
+ {
1443
+ name: inferredSpanName,
1444
+ attributes: mergedAttributes,
1445
+ normalizedRequest: isolationScope?.getScopeData().sdkProcessingMetadata.normalizedRequest,
1446
+ parentSampled,
1447
+ parentSampleRate: parseSampleRate(dsc?.sample_rate)
1448
+ },
1449
+ sampleRand
1450
+ );
1451
+ const method = `${maybeSpanHttpMethod}`.toUpperCase();
1452
+ if (method === "OPTIONS" || method === "HEAD") {
1453
+ DEBUG_BUILD && debug.log(`[Tracing] Not sampling span because HTTP method is '${method}' for ${spanName}`);
1454
+ return wrapSamplingDecision({
1455
+ decision: SamplingDecision.NOT_RECORD,
1456
+ context,
1457
+ spanAttributes,
1458
+ sampleRand,
1459
+ downstreamTraceSampleRate: 0
1460
+ // we don't want to sample anything in the downstream trace either
1461
+ });
1462
+ }
1463
+ if (!sampled && // We check for `parentSampled === undefined` because we only want to record client reports for spans that are trace roots (ie. when there was incoming trace)
1464
+ parentSampled === void 0) {
1465
+ DEBUG_BUILD && debug.log("[Tracing] Discarding root span because its trace was not chosen to be sampled.");
1466
+ this._client.recordDroppedEvent("sample_rate", this._isSpanStreaming ? "span" : "transaction");
1467
+ }
1468
+ return {
1469
+ ...wrapSamplingDecision({
1470
+ decision: sampled ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.NOT_RECORD,
1471
+ context,
1472
+ spanAttributes,
1473
+ sampleRand,
1474
+ downstreamTraceSampleRate: localSampleRateWasApplied ? sampleRate : void 0
1475
+ }),
1476
+ attributes: {
1477
+ // We set the sample rate on the span when a local sample rate was applied to better understand how traces were sampled in Sentry
1478
+ [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: localSampleRateWasApplied ? sampleRate : void 0
1479
+ }
1480
+ };
1481
+ }
1482
+ /** Returns the sampler name or short description with the configuration. */
1483
+ toString() {
1484
+ return "SentrySampler";
1485
+ }
1486
+ }
1487
+ function getParentSampled(parentSpan, traceId, spanName) {
1488
+ const parentContext = parentSpan.spanContext();
1489
+ if (isSpanContextValid(parentContext) && parentContext.traceId === traceId) {
1490
+ if (parentContext.isRemote) {
1491
+ const parentSampled2 = getSamplingDecision(parentSpan.spanContext());
1492
+ DEBUG_BUILD && debug.log(`[Tracing] Inheriting remote parent's sampled decision for ${spanName}: ${parentSampled2}`);
1493
+ return parentSampled2;
1494
+ }
1495
+ const parentSampled = getSamplingDecision(parentContext);
1496
+ DEBUG_BUILD && debug.log(`[Tracing] Inheriting parent's sampled decision for ${spanName}: ${parentSampled}`);
1497
+ return parentSampled;
1498
+ }
1499
+ return void 0;
1500
+ }
1501
+ function wrapSamplingDecision({
1502
+ decision,
1503
+ context,
1504
+ spanAttributes,
1505
+ sampleRand,
1506
+ downstreamTraceSampleRate,
1507
+ ignoredChildSpan,
1508
+ ignoredSegmentSpan
1509
+ }) {
1510
+ let traceState = getBaseTraceState(context, spanAttributes);
1511
+ if (downstreamTraceSampleRate !== void 0) {
1512
+ traceState = traceState.set(SENTRY_TRACE_STATE_SAMPLE_RATE, `${downstreamTraceSampleRate}`);
1513
+ }
1514
+ if (sampleRand !== void 0) {
1515
+ traceState = traceState.set(SENTRY_TRACE_STATE_SAMPLE_RAND, `${sampleRand}`);
1516
+ }
1517
+ if (ignoredChildSpan) {
1518
+ traceState = traceState.set(SENTRY_TRACE_STATE_CHILD_IGNORED, "1");
1519
+ }
1520
+ if (ignoredSegmentSpan) {
1521
+ traceState = traceState.set(SENTRY_TRACE_STATE_SEGMENT_IGNORED, "1");
1522
+ }
1523
+ if (decision == void 0) {
1524
+ return { decision: SamplingDecision.NOT_RECORD, traceState };
1525
+ }
1526
+ if (decision === SamplingDecision.NOT_RECORD) {
1527
+ return { decision, traceState: traceState.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, "1") };
1528
+ }
1529
+ return { decision, traceState };
1530
+ }
1531
+ function getBaseTraceState(context, spanAttributes) {
1532
+ const parentSpan = trace.getSpan(context);
1533
+ const parentContext = parentSpan?.spanContext();
1534
+ let traceState = parentContext?.traceState || new TraceState();
1535
+ const url = spanAttributes[SEMATTRS_HTTP_URL] || spanAttributes[ATTR_URL_FULL];
1536
+ if (url && typeof url === "string") {
1537
+ traceState = traceState.set(SENTRY_TRACE_STATE_URL, url);
1538
+ }
1539
+ return traceState;
1540
+ }
1541
+ function getValidSpan(context) {
1542
+ const span = trace.getSpan(context);
1543
+ return span && isSpanContextValid(span.spanContext()) ? span : void 0;
1544
+ }
1545
+
1546
+ class SentryResource {
1547
+ constructor(attributes) {
1548
+ this._attributes = attributes;
1549
+ }
1550
+ get attributes() {
1551
+ return this._attributes;
1552
+ }
1553
+ merge(other) {
1554
+ if (!other) {
1555
+ return this;
1556
+ }
1557
+ return new SentryResource({ ...this._attributes, ...other.attributes });
1558
+ }
1559
+ getRawAttributes() {
1560
+ return Object.entries(this._attributes);
1561
+ }
1562
+ }
1563
+ function parseOtelResourceAttributes(raw) {
1564
+ if (!raw) {
1565
+ return {};
1566
+ }
1567
+ const result = {};
1568
+ for (const pair of raw.split(",")) {
1569
+ const eq = pair.indexOf("=");
1570
+ if (eq === -1) {
1571
+ continue;
1572
+ }
1573
+ const key = pair.substring(0, eq).trim();
1574
+ const value = pair.substring(eq + 1).trim();
1575
+ if (key) {
1576
+ try {
1577
+ result[key] = decodeURIComponent(value);
1578
+ } catch {
1579
+ result[key] = value;
1580
+ }
1581
+ }
1582
+ }
1583
+ return result;
1584
+ }
1585
+ function getSentryResource(serviceNameFallback) {
1586
+ const env = typeof process !== "undefined" ? process.env : {};
1587
+ const otelServiceName = env.OTEL_SERVICE_NAME;
1588
+ const otelResourceAttrs = parseOtelResourceAttributes(env.OTEL_RESOURCE_ATTRIBUTES);
1589
+ return new SentryResource({
1590
+ // Lowest priority: Sentry defaults
1591
+ // eslint-disable-next-line deprecation/deprecation
1592
+ [SEMRESATTRS_SERVICE_NAMESPACE]: "sentry",
1593
+ [ATTR_SERVICE_NAME]: serviceNameFallback,
1594
+ // OTEL_RESOURCE_ATTRIBUTES overrides defaults (including service.name and service.namespace)
1595
+ ...otelResourceAttrs,
1596
+ // OTEL_SERVICE_NAME explicitly overrides service.name
1597
+ ...otelServiceName ? { [ATTR_SERVICE_NAME]: otelServiceName } : {},
1598
+ // Highest priority: Sentry SDK telemetry attrs (cannot be overridden by env vars)
1599
+ [ATTR_SERVICE_VERSION]: SDK_VERSION,
1600
+ [ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],
1601
+ [ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],
1602
+ [ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION]
1603
+ });
1604
+ }
1605
+
1606
+ export { startSpanManual as A, suppressTracing as B, withActiveSpan as C, wrapClientClass as D, wrapContextManagerClass as E, wrapSamplingDecision as F, SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION as S, SENTRY_SCOPES_CONTEXT_KEY as a, SentryPropagator as b, SentrySampler as c, SentrySpanProcessor as d, buildContextWithSentryScopes as e, continueTrace as f, enhanceDscWithOpenTelemetryRootSpanName as g, getActiveSpan as h, getRequestSpanData as i, getScopesFromContext as j, getSentryResource as k, getSpanKind as l, getTraceContextForScope as m, isSentryRequestSpan as n, openTelemetrySetupCheck as o, setOpenTelemetryContextAsyncContextStrategy as p, setupEventContextTrace as q, spanHasAttributes as r, setIsSetup as s, spanHasEvents as t, spanHasKind as u, spanHasName as v, spanHasParentId as w, spanHasStatus as x, startInactiveSpan as y, startSpan as z };
1607
+ //# sourceMappingURL=resource--8DgFma7.js.map