@getmicdrop/svelte-components 5.3.13 → 5.3.14

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.
package/dist/telemetry.js CHANGED
@@ -1,358 +1,403 @@
1
- import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
2
- import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
3
- import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
4
- import { Resource } from '@opentelemetry/resources';
5
- import { SEMRESATTRS_SERVICE_NAME, SEMRESATTRS_SERVICE_VERSION, SEMRESATTRS_DEPLOYMENT_ENVIRONMENT } from '@opentelemetry/semantic-conventions';
6
- import { DocumentLoadInstrumentation } from '@opentelemetry/instrumentation-document-load';
7
- import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
8
- import { XMLHttpRequestInstrumentation } from '@opentelemetry/instrumentation-xml-http-request';
9
- import { UserInteractionInstrumentation } from '@opentelemetry/instrumentation-user-interaction';
10
- import { ZoneContextManager } from '@opentelemetry/context-zone';
11
- import { B3Propagator } from '@opentelemetry/propagator-b3';
12
-
13
- // Telemetry configuration from environment or defaults
14
- const TELEMETRY_CONFIG = {
15
- serviceName: import.meta.env.VITE_OTEL_SERVICE_NAME || 'jetbook-performersportal',
16
- serviceVersion: import.meta.env.VITE_OTEL_SERVICE_VERSION || '1.0.0',
17
- environment: import.meta.env.VITE_ENVIRONMENT || 'development',
18
- otlpEndpoint: import.meta.env.VITE_OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318/v1/traces',
19
- tracesEnabled: import.meta.env.VITE_OTEL_TRACES_ENABLED !== 'false',
20
- sampleRate: parseFloat(import.meta.env.VITE_OTEL_TRACES_SAMPLER_ARG || '0.1'), // 10% sampling by default
21
- consoleDebug: import.meta.env.VITE_OTEL_DEBUG === 'true'
22
- };
23
-
24
- let tracer = null;
25
- let tracerProvider = null;
26
-
27
- // Helper to log telemetry events when debugging
28
- function debugLog(message, data) {
29
- if (TELEMETRY_CONFIG.consoleDebug) {
30
- console.log(`[Telemetry] ${message}`, data || '');
31
- }
32
- }
33
-
34
- // Initialize OpenTelemetry
35
- export function initTelemetry() {
36
- if (!TELEMETRY_CONFIG.tracesEnabled) {
37
- console.log('[Telemetry] Tracing is disabled');
38
- return;
39
- }
40
-
41
- try {
42
- // Create resource with service information
43
- const resource = new Resource({
44
- [SEMRESATTRS_SERVICE_NAME]: TELEMETRY_CONFIG.serviceName,
45
- [SEMRESATTRS_SERVICE_VERSION]: TELEMETRY_CONFIG.serviceVersion,
46
- [SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]: TELEMETRY_CONFIG.environment,
47
- 'browser.user_agent': navigator.userAgent,
48
- 'browser.language': navigator.language,
49
- 'browser.platform': navigator.platform
50
- });
51
-
52
- // Create tracer provider
53
- tracerProvider = new WebTracerProvider({
54
- resource,
55
- sampler: {
56
- shouldSample: () => {
57
- return {
58
- decision: Math.random() < TELEMETRY_CONFIG.sampleRate ? 1 : 0,
59
- attributes: []
60
- };
61
- }
62
- }
63
- });
64
-
65
- // Configure OTLP exporter
66
- const exporter = new OTLPTraceExporter({
67
- url: TELEMETRY_CONFIG.otlpEndpoint,
68
- headers: {
69
- 'Content-Type': 'application/json'
70
- }
71
- });
72
-
73
- // Add batch span processor
74
- tracerProvider.addSpanProcessor(new BatchSpanProcessor(exporter, {
75
- maxQueueSize: 100,
76
- maxExportBatchSize: 50,
77
- scheduledDelayMillis: 500,
78
- exportTimeoutMillis: 30000
79
- }));
80
-
81
- // Set global provider
82
- tracerProvider.register({
83
- contextManager: new ZoneContextManager(),
84
- propagator: new B3Propagator()
85
- });
86
-
87
- // Enable browser instrumentations
88
- // These auto-register with the global tracer provider when instantiated and enabled
89
- new DocumentLoadInstrumentation({
90
- applyCustomAttributesOnSpan: {
91
- documentLoad: (span) => {
92
- span.setAttribute('page.path', window.location.pathname);
93
- span.setAttribute('page.search', window.location.search);
94
- span.setAttribute('page.hash', window.location.hash);
95
- span.setAttribute('portal.type', 'performers');
96
- },
97
- documentFetch: (span) => {
98
- span.setAttribute('document.referrer', document.referrer);
99
- }
100
- }
101
- }).enable();
102
-
103
- new FetchInstrumentation({
104
- propagateTraceHeaderCorsUrls: [
105
- /^http:\/\/localhost:8080\/.*/,
106
- /^https:\/\/api\.jetbook\.com\/.*/,
107
- /^https:\/\/.*\.get-micdrop\.com\/.*/
108
- ],
109
- clearTimingResources: true,
110
- applyCustomAttributesOnSpan: (span, request, response) => {
111
- const url = new URL(request.url || '');
112
- span.setAttribute('http.url.pathname', url.pathname);
113
- span.setAttribute('http.url.search', url.search);
114
- span.setAttribute('portal.type', 'performers');
115
-
116
- if (response) {
117
- span.setAttribute('http.response.status', response.status);
118
- span.setAttribute('http.response.content_length', response.headers?.get('content-length') || 0);
119
- }
120
- }
121
- }).enable();
122
-
123
- new XMLHttpRequestInstrumentation({
124
- propagateTraceHeaderCorsUrls: [
125
- /^http:\/\/localhost:8080\/.*/,
126
- /^https:\/\/api\.jetbook\.com\/.*/,
127
- /^https:\/\/.*\.get-micdrop\.com\/.*/
128
- ],
129
- clearTimingResources: true
130
- }).enable();
131
-
132
- new UserInteractionInstrumentation({
133
- eventNames: ['click', 'submit', 'change'],
134
- shouldPreventSpanCreation: (eventType, element, span) => {
135
- // Skip telemetry for certain elements
136
- if (element.classList?.contains('no-telemetry')) {
137
- return true;
138
- }
139
- // Skip very frequent events
140
- if (eventType === 'change' && element.tagName === 'INPUT' && element.type === 'text') {
141
- return true;
142
- }
143
- return false;
144
- }
145
- }).enable();
146
-
147
- // Get tracer instance
148
- tracer = tracerProvider.getTracer(
149
- TELEMETRY_CONFIG.serviceName,
150
- TELEMETRY_CONFIG.serviceVersion
151
- );
152
-
153
- debugLog('Telemetry initialized', TELEMETRY_CONFIG);
154
- console.log(`[Telemetry] Initialized with ${TELEMETRY_CONFIG.sampleRate * 100}% sampling rate`);
155
-
156
- } catch (error) {
157
- console.error('[Telemetry] Failed to initialize:', error);
158
- }
159
- }
160
-
161
- // Create custom span for tracking specific operations
162
- export function startSpan(name, options = {}) {
163
- if (!tracer) return null;
164
-
165
- const span = tracer.startSpan(name, {
166
- ...options,
167
- attributes: {
168
- 'span.kind': 'internal',
169
- 'portal.type': 'performers',
170
- ...options.attributes
171
- }
172
- });
173
-
174
- debugLog(`Started span: ${name}`, options.attributes);
175
- return span;
176
- }
177
-
178
- // End a span and set its status
179
- export function endSpan(span, status = { code: 0 }) {
180
- if (!span) return;
181
-
182
- span.setStatus(status);
183
- span.end();
184
- debugLog(`Ended span: ${span.name}`, status);
185
- }
186
-
187
- // Track page views (for SPAs)
188
- export function trackPageView(pagePath, pageTitle) {
189
- if (!tracer) return;
190
-
191
- const span = tracer.startSpan('page_view', {
192
- attributes: {
193
- 'page.path': pagePath,
194
- 'page.title': pageTitle || document.title,
195
- 'page.url': window.location.href,
196
- 'page.referrer': document.referrer,
197
- 'portal.type': 'performers'
198
- }
199
- });
200
-
201
- span.end();
202
- debugLog(`Tracked page view: ${pagePath}`);
203
- }
204
-
205
- // Track custom events
206
- export function trackEvent(eventName, attributes = {}) {
207
- if (!tracer) return;
208
-
209
- const span = tracer.startSpan(`event.${eventName}`, {
210
- attributes: {
211
- 'event.name': eventName,
212
- 'event.timestamp': new Date().toISOString(),
213
- 'portal.type': 'performers',
214
- ...attributes
215
- }
216
- });
217
-
218
- span.end();
219
- debugLog(`Tracked event: ${eventName}`, attributes);
220
- }
221
-
222
- // Track performer-specific actions
223
- export function trackPerformerAction(action, metadata = {}) {
224
- if (!tracer) return;
225
-
226
- const span = tracer.startSpan(`performer.${action}`, {
227
- attributes: {
228
- 'performer.action': action,
229
- 'performer.metadata': JSON.stringify(metadata),
230
- 'portal.type': 'performers',
231
- 'page.url': window.location.href,
232
- 'timestamp': new Date().toISOString()
233
- }
234
- });
235
-
236
- span.end();
237
- debugLog(`Tracked performer action: ${action}`, metadata);
238
- }
239
-
240
- // Track errors
241
- export function trackError(error, context = {}) {
242
- if (!tracer) return;
243
-
244
- const span = tracer.startSpan('error', {
245
- attributes: {
246
- 'error.message': error.message || String(error),
247
- 'error.stack': error.stack,
248
- 'error.type': error.name || 'Error',
249
- 'error.context': JSON.stringify(context),
250
- 'page.url': window.location.href,
251
- 'portal.type': 'performers'
252
- }
253
- });
254
-
255
- span.setStatus({ code: 2, message: error.message });
256
- span.recordException(error);
257
- span.end();
258
-
259
- debugLog(`Tracked error: ${error.message}`, context);
260
- }
261
-
262
- // Track API calls with custom attributes
263
- export function trackAPICall(method, endpoint, status, duration, attributes = {}) {
264
- if (!tracer) return;
265
-
266
- const span = tracer.startSpan('api_call', {
267
- attributes: {
268
- 'http.method': method,
269
- 'http.url': endpoint,
270
- 'http.status_code': status,
271
- 'http.duration_ms': duration,
272
- 'portal.type': 'performers',
273
- ...attributes
274
- }
275
- });
276
-
277
- span.setStatus({ code: status >= 400 ? 2 : 0 });
278
- span.end();
279
-
280
- debugLog(`Tracked API call: ${method} ${endpoint}`, { status, duration });
281
- }
282
-
283
- // Track user actions
284
- export function trackUserAction(action, metadata = {}) {
285
- if (!tracer) return;
286
-
287
- const span = tracer.startSpan(`user.${action}`, {
288
- attributes: {
289
- 'user.action': action,
290
- 'user.metadata': JSON.stringify(metadata),
291
- 'portal.type': 'performers',
292
- 'page.url': window.location.href,
293
- 'timestamp': new Date().toISOString()
294
- }
295
- });
296
-
297
- span.end();
298
- debugLog(`Tracked user action: ${action}`, metadata);
299
- }
300
-
301
- // Shutdown telemetry gracefully
302
- export async function shutdownTelemetry() {
303
- if (tracerProvider) {
304
- try {
305
- await tracerProvider.shutdown();
306
- console.log('[Telemetry] Shutdown complete');
307
- } catch (error) {
308
- console.error('[Telemetry] Shutdown error:', error);
309
- }
310
- }
311
- }
312
-
313
- // Connect client spans with SSR spans using trace context
314
- function connectWithSSRTrace() {
315
- // Check if we have trace context from SSR
316
- const ssrTraceContext = window.__TRACE_CONTEXT__;
317
- if (ssrTraceContext && tracer) {
318
- // Create a span linked to the SSR span
319
- const span = tracer.startSpan('client.performer.init', {
320
- attributes: {
321
- 'span.kind': 'client',
322
- 'client.type': 'browser',
323
- 'portal.type': 'performers',
324
- 'ssr.trace_id': ssrTraceContext.traceId,
325
- 'ssr.span_id': ssrTraceContext.spanId
326
- },
327
- links: [{
328
- context: {
329
- traceId: ssrTraceContext.traceId,
330
- spanId: ssrTraceContext.spanId,
331
- traceFlags: ssrTraceContext.traceFlags || 0
332
- }
333
- }]
334
- });
335
-
336
- span.end();
337
- debugLog('Connected to SSR trace', ssrTraceContext);
338
- }
339
- }
340
-
341
- // Auto-initialize on module load if in browser environment
342
- if (typeof window !== 'undefined') {
343
- // Initialize telemetry when DOM is ready
344
- if (document.readyState === 'loading') {
345
- document.addEventListener('DOMContentLoaded', () => {
346
- initTelemetry();
347
- connectWithSSRTrace();
348
- });
349
- } else {
350
- initTelemetry();
351
- connectWithSSRTrace();
352
- }
353
-
354
- // Cleanup on page unload
355
- window.addEventListener('beforeunload', () => {
356
- shutdownTelemetry();
357
- });
358
- }
1
+ import { ZoneContextManager } from '@opentelemetry/context-zone';
2
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
3
+ import { registerInstrumentations } from '@opentelemetry/instrumentation';
4
+ import { DocumentLoadInstrumentation } from '@opentelemetry/instrumentation-document-load';
5
+ import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
6
+ import { UserInteractionInstrumentation } from '@opentelemetry/instrumentation-user-interaction';
7
+ import { XMLHttpRequestInstrumentation } from '@opentelemetry/instrumentation-xml-http-request';
8
+ import { B3Propagator } from '@opentelemetry/propagator-b3';
9
+ import { Resource } from '@opentelemetry/resources';
10
+ import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
11
+ import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
12
+ import {
13
+ SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,
14
+ SEMRESATTRS_SERVICE_NAME,
15
+ SEMRESATTRS_SERVICE_VERSION,
16
+ } from '@opentelemetry/semantic-conventions';
17
+
18
+ /**
19
+ * Telemetry configuration from environment variables.
20
+ * Each app can override these via VITE_* environment variables.
21
+ */
22
+ const TELEMETRY_CONFIG = {
23
+ serviceName: import.meta.env.VITE_OTEL_SERVICE_NAME || 'micdrop-app',
24
+ serviceVersion: import.meta.env.VITE_OTEL_SERVICE_VERSION || '1.0.0',
25
+ environment: import.meta.env.VITE_ENVIRONMENT || 'development',
26
+ otlpEndpoint: import.meta.env.VITE_OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318/v1/traces',
27
+ tracesEnabled: import.meta.env.VITE_OTEL_TRACES_ENABLED !== 'false',
28
+ sampleRate: parseFloat(import.meta.env.VITE_OTEL_TRACES_SAMPLER_ARG || '0.1'), // 10% sampling by default
29
+ consoleDebug: import.meta.env.VITE_OTEL_DEBUG === 'true',
30
+ // Portal type for distinguishing apps in traces (e.g., 'frontend', 'performers')
31
+ portalType: import.meta.env.VITE_PORTAL_TYPE || 'unknown',
32
+ };
33
+
34
+ // Default CORS URLs for trace propagation - apps can extend this
35
+ const DEFAULT_CORS_URLS = [
36
+ /^http:\/\/localhost:8080\/.*/,
37
+ /^https:\/\/api\.jetbook\.com\/.*/,
38
+ /^https:\/\/api\.micdrop\.com\/.*/,
39
+ /^https:\/\/.*\.get-micdrop\.com\/.*/,
40
+ ];
41
+
42
+ let tracer = null;
43
+ let tracerProvider = null;
44
+
45
+ // Helper to log telemetry events when debugging
46
+ function debugLog(message, data) {
47
+ if (TELEMETRY_CONFIG.consoleDebug) {
48
+ console.log(`[Telemetry] ${message}`, data || '');
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Initialize OpenTelemetry with optional custom configuration
54
+ * @param {Object} customConfig - Override default config
55
+ */
56
+ export function initTelemetry(customConfig = {}) {
57
+ const config = { ...TELEMETRY_CONFIG, ...customConfig };
58
+
59
+ if (!config.tracesEnabled) {
60
+ console.log('[Telemetry] Tracing is disabled');
61
+ return;
62
+ }
63
+
64
+ try {
65
+ // Create resource with service information
66
+ const resource = new Resource({
67
+ [SEMRESATTRS_SERVICE_NAME]: config.serviceName,
68
+ [SEMRESATTRS_SERVICE_VERSION]: config.serviceVersion,
69
+ [SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]: config.environment,
70
+ 'browser.user_agent': navigator.userAgent,
71
+ 'browser.language': navigator.language,
72
+ 'browser.platform': navigator.platform,
73
+ 'portal.type': config.portalType,
74
+ });
75
+
76
+ // Create tracer provider
77
+ tracerProvider = new WebTracerProvider({
78
+ resource,
79
+ sampler: {
80
+ shouldSample: () => {
81
+ return {
82
+ decision: Math.random() < config.sampleRate ? 1 : 0,
83
+ attributes: [],
84
+ };
85
+ },
86
+ },
87
+ });
88
+
89
+ // Configure OTLP exporter
90
+ const exporter = new OTLPTraceExporter({
91
+ url: config.otlpEndpoint,
92
+ headers: {
93
+ 'Content-Type': 'application/json',
94
+ },
95
+ });
96
+
97
+ // Add batch span processor
98
+ tracerProvider.addSpanProcessor(
99
+ new BatchSpanProcessor(exporter, {
100
+ maxQueueSize: 100,
101
+ maxExportBatchSize: 50,
102
+ scheduledDelayMillis: 500,
103
+ exportTimeoutMillis: 30000,
104
+ })
105
+ );
106
+
107
+ // Set global provider
108
+ tracerProvider.register({
109
+ contextManager: new ZoneContextManager(),
110
+ propagator: new B3Propagator(),
111
+ });
112
+
113
+ // Get CORS URLs (allow custom via config)
114
+ const corsUrls = config.corsUrls || DEFAULT_CORS_URLS;
115
+
116
+ // Register instrumentations
117
+ registerInstrumentations({
118
+ instrumentations: [
119
+ // Document load instrumentation
120
+ new DocumentLoadInstrumentation({
121
+ applyCustomAttributesOnSpan: {
122
+ documentLoad: span => {
123
+ span.setAttribute('page.path', window.location.pathname);
124
+ span.setAttribute('page.search', window.location.search);
125
+ span.setAttribute('page.hash', window.location.hash);
126
+ span.setAttribute('portal.type', config.portalType);
127
+ },
128
+ documentFetch: span => {
129
+ span.setAttribute('document.referrer', document.referrer);
130
+ },
131
+ },
132
+ }),
133
+
134
+ // Fetch instrumentation for API calls
135
+ new FetchInstrumentation({
136
+ propagateTraceHeaderCorsUrls: corsUrls,
137
+ clearTimingResources: true,
138
+ applyCustomAttributesOnSpan: (span, request, response) => {
139
+ const url = new URL(request.url || '');
140
+ span.setAttribute('http.url.pathname', url.pathname);
141
+ span.setAttribute('http.url.search', url.search);
142
+ span.setAttribute('portal.type', config.portalType);
143
+
144
+ if (response) {
145
+ span.setAttribute('http.response.status', response.status);
146
+ span.setAttribute(
147
+ 'http.response.content_length',
148
+ response.headers?.get('content-length') || 0
149
+ );
150
+ }
151
+ },
152
+ }),
153
+
154
+ // XHR instrumentation for legacy AJAX calls
155
+ new XMLHttpRequestInstrumentation({
156
+ propagateTraceHeaderCorsUrls: corsUrls,
157
+ clearTimingResources: true,
158
+ }),
159
+
160
+ // User interaction instrumentation
161
+ new UserInteractionInstrumentation({
162
+ eventNames: ['click', 'submit', 'change'],
163
+ shouldPreventSpanCreation: (eventType, element, span) => {
164
+ // Skip telemetry for certain elements
165
+ if (element.classList?.contains('no-telemetry')) {
166
+ return true;
167
+ }
168
+ // Skip very frequent events
169
+ if (
170
+ eventType === 'change' &&
171
+ element.tagName === 'INPUT' &&
172
+ element.type === 'text'
173
+ ) {
174
+ return true;
175
+ }
176
+ return false;
177
+ },
178
+ }),
179
+ ],
180
+ });
181
+
182
+ // Get tracer instance
183
+ tracer = tracerProvider.getTracer(config.serviceName, config.serviceVersion);
184
+
185
+ debugLog('Telemetry initialized', config);
186
+ console.log(
187
+ `[Telemetry] Initialized ${config.serviceName} with ${config.sampleRate * 100}% sampling rate`
188
+ );
189
+ } catch (error) {
190
+ console.error('[Telemetry] Failed to initialize:', error);
191
+ }
192
+ }
193
+
194
+ // Create custom span for tracking specific operations
195
+ export function startSpan(name, options = {}) {
196
+ if (!tracer) return null;
197
+
198
+ const span = tracer.startSpan(name, {
199
+ ...options,
200
+ attributes: {
201
+ 'span.kind': 'internal',
202
+ 'portal.type': TELEMETRY_CONFIG.portalType,
203
+ ...options.attributes,
204
+ },
205
+ });
206
+
207
+ debugLog(`Started span: ${name}`, options.attributes);
208
+ return span;
209
+ }
210
+
211
+ // End a span and set its status
212
+ export function endSpan(span, status = { code: 0 }) {
213
+ if (!span) return;
214
+
215
+ span.setStatus(status);
216
+ span.end();
217
+ debugLog(`Ended span: ${span.name}`, status);
218
+ }
219
+
220
+ // Track page views (for SPAs)
221
+ export function trackPageView(pagePath, pageTitle) {
222
+ if (!tracer) return;
223
+
224
+ const span = tracer.startSpan('page_view', {
225
+ attributes: {
226
+ 'page.path': pagePath,
227
+ 'page.title': pageTitle || document.title,
228
+ 'page.url': window.location.href,
229
+ 'page.referrer': document.referrer,
230
+ 'portal.type': TELEMETRY_CONFIG.portalType,
231
+ },
232
+ });
233
+
234
+ span.end();
235
+ debugLog(`Tracked page view: ${pagePath}`);
236
+ }
237
+
238
+ // Track custom events
239
+ export function trackEvent(eventName, attributes = {}) {
240
+ if (!tracer) return;
241
+
242
+ const span = tracer.startSpan(`event.${eventName}`, {
243
+ attributes: {
244
+ 'event.name': eventName,
245
+ 'event.timestamp': new Date().toISOString(),
246
+ 'portal.type': TELEMETRY_CONFIG.portalType,
247
+ ...attributes,
248
+ },
249
+ });
250
+
251
+ span.end();
252
+ debugLog(`Tracked event: ${eventName}`, attributes);
253
+ }
254
+
255
+ // Track errors
256
+ export function trackError(error, context = {}) {
257
+ if (!tracer) return;
258
+
259
+ const span = tracer.startSpan('error', {
260
+ attributes: {
261
+ 'error.message': error.message || String(error),
262
+ 'error.stack': error.stack,
263
+ 'error.type': error.name || 'Error',
264
+ 'error.context': JSON.stringify(context),
265
+ 'page.url': window.location.href,
266
+ 'portal.type': TELEMETRY_CONFIG.portalType,
267
+ },
268
+ });
269
+
270
+ span.setStatus({ code: 2, message: error.message });
271
+ span.recordException(error);
272
+ span.end();
273
+
274
+ debugLog(`Tracked error: ${error.message}`, context);
275
+ }
276
+
277
+ // Track API calls with custom attributes
278
+ export function trackAPICall(method, endpoint, status, duration, attributes = {}) {
279
+ if (!tracer) return;
280
+
281
+ const span = tracer.startSpan('api_call', {
282
+ attributes: {
283
+ 'http.method': method,
284
+ 'http.url': endpoint,
285
+ 'http.status_code': status,
286
+ 'http.duration_ms': duration,
287
+ 'portal.type': TELEMETRY_CONFIG.portalType,
288
+ ...attributes,
289
+ },
290
+ });
291
+
292
+ span.setStatus({ code: status >= 400 ? 2 : 0 });
293
+ span.end();
294
+
295
+ debugLog(`Tracked API call: ${method} ${endpoint}`, { status, duration });
296
+ }
297
+
298
+ // Track user actions
299
+ export function trackUserAction(action, metadata = {}) {
300
+ if (!tracer) return;
301
+
302
+ const span = tracer.startSpan(`user.${action}`, {
303
+ attributes: {
304
+ 'user.action': action,
305
+ 'user.metadata': JSON.stringify(metadata),
306
+ 'page.url': window.location.href,
307
+ 'portal.type': TELEMETRY_CONFIG.portalType,
308
+ timestamp: new Date().toISOString(),
309
+ },
310
+ });
311
+
312
+ span.end();
313
+ debugLog(`Tracked user action: ${action}`, metadata);
314
+ }
315
+
316
+ // Track performer-specific actions (for performers portal)
317
+ export function trackPerformerAction(action, metadata = {}) {
318
+ if (!tracer) return;
319
+
320
+ const span = tracer.startSpan(`performer.${action}`, {
321
+ attributes: {
322
+ 'performer.action': action,
323
+ 'performer.metadata': JSON.stringify(metadata),
324
+ 'page.url': window.location.href,
325
+ 'portal.type': TELEMETRY_CONFIG.portalType,
326
+ timestamp: new Date().toISOString(),
327
+ },
328
+ });
329
+
330
+ span.end();
331
+ debugLog(`Tracked performer action: ${action}`, metadata);
332
+ }
333
+
334
+ // Shutdown telemetry gracefully
335
+ export async function shutdownTelemetry() {
336
+ if (tracerProvider) {
337
+ try {
338
+ await tracerProvider.shutdown();
339
+ console.log('[Telemetry] Shutdown complete');
340
+ } catch (error) {
341
+ console.error('[Telemetry] Shutdown error:', error);
342
+ }
343
+ }
344
+ }
345
+
346
+ // Connect client spans with SSR spans using trace context
347
+ function connectWithSSRTrace() {
348
+ // Check if we have trace context from SSR
349
+ const ssrTraceContext = window.__TRACE_CONTEXT__;
350
+ if (ssrTraceContext && tracer) {
351
+ // Create a span linked to the SSR span
352
+ const span = tracer.startSpan('client.init', {
353
+ attributes: {
354
+ 'span.kind': 'client',
355
+ 'client.type': 'browser',
356
+ 'portal.type': TELEMETRY_CONFIG.portalType,
357
+ 'ssr.trace_id': ssrTraceContext.traceId,
358
+ 'ssr.span_id': ssrTraceContext.spanId,
359
+ },
360
+ links: [
361
+ {
362
+ context: {
363
+ traceId: ssrTraceContext.traceId,
364
+ spanId: ssrTraceContext.spanId,
365
+ traceFlags: ssrTraceContext.traceFlags || 0,
366
+ },
367
+ },
368
+ ],
369
+ });
370
+
371
+ span.end();
372
+ debugLog('Connected to SSR trace', ssrTraceContext);
373
+ }
374
+ }
375
+
376
+ /**
377
+ * Auto-initialize telemetry (call this in your app's entry point)
378
+ * This sets up auto-initialization and cleanup handlers
379
+ */
380
+ export function setupAutoTelemetry() {
381
+ if (typeof window === 'undefined') return;
382
+
383
+ // Initialize telemetry when DOM is ready
384
+ if (document.readyState === 'loading') {
385
+ document.addEventListener('DOMContentLoaded', () => {
386
+ initTelemetry();
387
+ connectWithSSRTrace();
388
+ });
389
+ } else {
390
+ initTelemetry();
391
+ connectWithSSRTrace();
392
+ }
393
+
394
+ // Cleanup on page unload
395
+ window.addEventListener('beforeunload', () => {
396
+ shutdownTelemetry();
397
+ });
398
+ }
399
+
400
+ // Export config for testing/debugging
401
+ export function getTelemetryConfig() {
402
+ return { ...TELEMETRY_CONFIG };
403
+ }