|
1 | | -import type { Span, SpanTimeInput, TraceContext } from '@sentry/types'; |
| 1 | +import type { Span, SpanJSON, SpanTimeInput, TraceContext } from '@sentry/types'; |
2 | 2 | import { dropUndefinedKeys, generateSentryTraceHeader, timestampInSeconds } from '@sentry/utils'; |
| 3 | +import type { Span as SpanClass } from '../tracing/span'; |
3 | 4 |
|
4 | 5 | /** |
5 | 6 | * Convert a span to a trace context, which can be sent as the `trace` context in an event. |
6 | 7 | */ |
7 | 8 | export function spanToTraceContext(span: Span): TraceContext { |
8 | | - const { data, description, op, parent_span_id, span_id, status, tags, trace_id, origin } = span.toJSON(); |
| 9 | + const { spanId: span_id, traceId: trace_id } = span; |
| 10 | + const { data, description, op, parent_span_id, status, tags, origin } = spanToJSON(span); |
9 | 11 |
|
10 | 12 | return dropUndefinedKeys({ |
11 | 13 | data, |
@@ -54,3 +56,35 @@ function ensureTimestampInSeconds(timestamp: number): number { |
54 | 56 | const isMs = timestamp > 9999999999; |
55 | 57 | return isMs ? timestamp / 1000 : timestamp; |
56 | 58 | } |
| 59 | + |
| 60 | +/** |
| 61 | + * Convert a span to a JSON representation. |
| 62 | + * Note that all fields returned here are optional and need to be guarded against. |
| 63 | + * |
| 64 | + * Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json). |
| 65 | + * This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility. |
| 66 | + * And `spanToJSON` needs the Span class from `span.ts` to check here. |
| 67 | + * TODO v8: When we remove the deprecated stuff from `span.ts`, we can remove the circular dependency again. |
| 68 | + */ |
| 69 | +export function spanToJSON(span: Span): Partial<SpanJSON> { |
| 70 | + if (spanIsSpanClass(span)) { |
| 71 | + return span.getSpanJSON(); |
| 72 | + } |
| 73 | + |
| 74 | + // Fallback: We also check for `.toJSON()` here... |
| 75 | + // eslint-disable-next-line deprecation/deprecation |
| 76 | + if (typeof span.toJSON === 'function') { |
| 77 | + // eslint-disable-next-line deprecation/deprecation |
| 78 | + return span.toJSON(); |
| 79 | + } |
| 80 | + |
| 81 | + return {}; |
| 82 | +} |
| 83 | + |
| 84 | +/** |
| 85 | + * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof. |
| 86 | + * :( So instead we approximate this by checking if it has the `getSpanJSON` method. |
| 87 | + */ |
| 88 | +function spanIsSpanClass(span: Span): span is SpanClass { |
| 89 | + return typeof (span as SpanClass).getSpanJSON === 'function'; |
| 90 | +} |
0 commit comments