@jaak.ai/stamps 2.2.0-dev.1 → 2.2.0-dev.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/cjs/jaak-stamps.cjs.entry.js +592 -3098
  2. package/dist/cjs/jaak-stamps.cjs.entry.js.map +1 -1
  3. package/dist/cjs/jaak-stamps.entry.cjs.js.map +1 -1
  4. package/dist/collection/components/my-component/my-component.js +19 -6
  5. package/dist/collection/components/my-component/my-component.js.map +1 -1
  6. package/dist/collection/services/LicenseValidationService.js +2 -2
  7. package/dist/collection/services/LicenseValidationService.js.map +1 -1
  8. package/dist/collection/services/TracingService.js +130 -78
  9. package/dist/collection/services/TracingService.js.map +1 -1
  10. package/dist/collection/services/interfaces/ITracingService.js.map +1 -1
  11. package/dist/components/jaak-stamps.js +592 -3098
  12. package/dist/components/jaak-stamps.js.map +1 -1
  13. package/dist/esm/jaak-stamps.entry.js +592 -3098
  14. package/dist/esm/jaak-stamps.entry.js.map +1 -1
  15. package/dist/jaak-stamps-webcomponent/jaak-stamps-webcomponent.esm.js +1 -1
  16. package/dist/jaak-stamps-webcomponent/jaak-stamps.entry.esm.js.map +1 -1
  17. package/dist/jaak-stamps-webcomponent/p-37281823.entry.js +7 -0
  18. package/dist/jaak-stamps-webcomponent/p-37281823.entry.js.map +1 -0
  19. package/dist/types/components/my-component/my-component.d.ts +1 -1
  20. package/dist/types/components.d.ts +2 -2
  21. package/dist/types/services/LicenseValidationService.d.ts +1 -1
  22. package/dist/types/services/TracingService.d.ts +6 -1
  23. package/dist/types/services/interfaces/ITracingService.d.ts +5 -0
  24. package/package.json +1 -1
  25. package/dist/jaak-stamps-webcomponent/p-8c49893d.entry.js +0 -7
  26. package/dist/jaak-stamps-webcomponent/p-8c49893d.entry.js.map +0 -1
@@ -9,8 +9,8 @@ export class LicenseValidationService {
9
9
  static ENVIRONMENT_URLS = {
10
10
  dev: 'https://api.dev.jaak.ai',
11
11
  qa: 'https://api.qa.jaak.ai',
12
- staging: 'https://api-staging.jaak.ai',
13
- prod: 'https://api.jaak.ai',
12
+ sandbox: 'https://api.sandbox.jaak.ai',
13
+ prod: 'https://services.api.jaak.ai',
14
14
  };
15
15
  constructor(environment = 'prod') {
16
16
  this.baseUrl = LicenseValidationService.ENVIRONMENT_URLS[environment];
@@ -1 +1 @@
1
- {"version":3,"file":"LicenseValidationService.js","sourceRoot":"","sources":["../../src/services/LicenseValidationService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAgCH,MAAM,OAAO,wBAAwB;IAC3B,WAAW,GAAW,0BAA0B,CAAC;IACjD,OAAO,CAAS;IAExB,iCAAiC;IACzB,MAAM,CAAU,gBAAgB,GAAgC;QACtE,GAAG,EAAE,yBAAyB;QAC9B,EAAE,EAAE,wBAAwB;QAC5B,OAAO,EAAE,6BAA6B;QACtC,IAAI,EAAE,qBAAqB;KAC5B,CAAC;IAEF,YAAY,cAA2B,MAAM;QAC3C,IAAI,CAAC,OAAO,GAAG,wBAAwB,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAC;IACxE,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,eAAe,CACnB,OAAe,EACf,OAAgB,EAChB,QAAgB,iBAAiB;QAEjC,mCAAmC;QACnC,MAAM,gBAAgB,GAAG,OAAO,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;QAE3D,qBAAqB;QACrB,MAAM,WAAW,GAA6B;YAC5C,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,gBAAgB,EAAE,CAAC,CAAC,CAAC,OAAO;YACnD,MAAM,EAAE,KAAK;YACb,MAAM,EAAE,KAAK;YACb,OAAO,EAAE,KAAK;YACd,QAAQ,EAAE;gBACR,WAAW,EAAE,OAAO;aACrB;SACF,CAAC;QAEF,MAAM,OAAO,GAAgB;YAC3B,cAAc,EAAE,kBAAkB;SACnC,CAAC;QAEF,oDAAoD;QACpD,OAAO,CAAC,aAAa,CAAC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OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAChF,CAAC;IAED;;OAEG;IACK,cAAc;QACpB,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;QAChC,MAAM,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;QAC9B,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAChF,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,yBAAyB,CAAC,OAAe;QAC9C,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;YAC5C,OAAO,IAAI,CAAC;QACd,CAAC;QAED,+BAA+B;QAC/B,MAAM,OAAO,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;QAErE,sCAAsC;QACtC,IAAI,OAAO,CAAC,MAAM,KAAK,EAAE,IAAI,iBAAiB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;YAC7D,OAAO,OAAO,CAAC,WAAW,EAAE,CAAC;QAC/B,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,iEAAiE,EAAE,OAAO,CAAC,CAAC;QACzF,OAAO,IAAI,CAAC;IACd,CAAC","sourcesContent":["/**\n * License Validation Service\n * Handles license validation for the jaak-stamps webcomponent\n */\n\nexport type Environment = 'dev' | 'qa' | 'staging' | 'prod';\n\nexport interface LicenseValidationRequest {\n license: string;\n origin: string;\n app_id?: string;\n product?: string;\n product_version?: string;\n metadata?: {\n [key: string]: any;\n };\n}\n\nexport interface LicenseValidationResponse {\n access_token: string;\n token_type: string;\n expires_at: string;\n session_id: string;\n jti: string;\n step: number;\n license: string;\n traceId?: string; // Generated or provided traceId\n}\n\nexport interface LicenseValidationError {\n error: string;\n error_description?: string;\n status_code?: number;\n}\n\nexport class LicenseValidationService {\n private apiEndpoint: string = '/api/v1/license/validate';\n private baseUrl: string;\n\n // Environment-specific base URLs\n private static readonly ENVIRONMENT_URLS: Record<Environment, string> = {\n dev: 'https://api.dev.jaak.ai',\n qa: 'https://api.qa.jaak.ai',\n staging: 'https://api-staging.jaak.ai',\n prod: 'https://api.jaak.ai',\n };\n\n constructor(environment: Environment = 'prod') {\n this.baseUrl = LicenseValidationService.ENVIRONMENT_URLS[environment];\n }\n\n /**\n * Validate license with the API\n * @param license License key to validate\n * @param traceId Optional trace ID from W3C Trace Context\n * @param appId Optional application ID\n * @param metadata Optional additional metadata\n * @returns Promise<LicenseValidationResponse>\n */\n async validateLicense(\n license: string,\n traceId?: string,\n appId: string = 'jaak-stamps-web',\n ): Promise<LicenseValidationResponse> {\n // Generate traceId if not provided\n const effectiveTraceId = traceId || this.generateTraceId();\n\n // Build request body\n const requestBody: LicenseValidationRequest = {\n license: traceId ? `L${effectiveTraceId}` : license,\n origin: 'web',\n app_id: appId,\n product: 'kyc',\n metadata: {\n sdk_version: '2.1.0',\n },\n };\n\n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n };\n\n // Add traceparent header with the effective traceId\n headers['traceparent'] = `00-${effectiveTraceId}-${this.generateSpanId()}-01`;\n\n try {\n const response = await fetch(`${this.baseUrl}${this.apiEndpoint}`, {\n method: 'POST',\n headers,\n body: JSON.stringify(requestBody),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw {\n error: errorData.error || 'license_validation_failed',\n error_description: errorData.error_description || `HTTP ${response.status}: ${response.statusText}`,\n status_code: response.status,\n } as LicenseValidationError;\n }\n\n const responseData = await response.json();\n // Add the traceId to the response\n return {\n ...responseData,\n traceId: effectiveTraceId,\n };\n } catch (error) {\n if ((error as any).error) {\n throw error;\n }\n\n throw {\n error: 'network_error',\n error_description: 'Failed to connect to license validation service',\n status_code: 0,\n } as LicenseValidationError;\n }\n }\n\n /**\n * Generate a random trace ID for W3C Trace Context (32 hex characters)\n */\n private generateTraceId(): string {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');\n }\n\n /**\n * Generate a random span ID for W3C Trace Context (16 hex characters)\n */\n private generateSpanId(): string {\n const array = new Uint8Array(8);\n crypto.getRandomValues(array);\n return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');\n }\n\n /**\n * Extract trace ID from license field\n * License format: \"L<32-hex-chars>\"\n * Example: \"Ld79223833a2fd91971e4c14a33298904\" -> \"d79223833a2fd91971e4c14a33298904\"\n */\n static extractTraceIdFromLicense(license: string): string | null {\n if (!license || typeof license !== 'string') {\n return null;\n }\n\n // Remove \"L\" prefix if present\n const traceId = license.startsWith('L') ? license.slice(1) : license;\n\n // Validate format (32 hex characters)\n if (traceId.length === 32 && /^[a-f0-9]{32}$/i.test(traceId)) {\n return traceId.toLowerCase();\n }\n\n console.warn('[LicenseValidationService] Invalid license format for trace ID:', license);\n return null;\n }\n}\n"]}
1
+ {"version":3,"file":"LicenseValidationService.js","sourceRoot":"","sources":["../../src/services/LicenseValidationService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAgCH,MAAM,OAAO,wBAAwB;IAC3B,WAAW,GAAW,0BAA0B,CAAC;IACjD,OAAO,CAAS;IAExB,iCAAiC;IACzB,MAAM,CAAU,gBAAgB,GAAgC;QACtE,GAAG,EAAE,yBAAyB;QAC9B,EAAE,EAAE,wBAAwB;QAC5B,OAAO,EAAE,6BAA6B;QACtC,IAAI,EAAE,8BAA8B;KACrC,CAAC;IAEF,YA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Ae;QAC9C,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;YAC5C,OAAO,IAAI,CAAC;QACd,CAAC;QAED,+BAA+B;QAC/B,MAAM,OAAO,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;QAErE,sCAAsC;QACtC,IAAI,OAAO,CAAC,MAAM,KAAK,EAAE,IAAI,iBAAiB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;YAC7D,OAAO,OAAO,CAAC,WAAW,EAAE,CAAC;QAC/B,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,iEAAiE,EAAE,OAAO,CAAC,CAAC;QACzF,OAAO,IAAI,CAAC;IACd,CAAC","sourcesContent":["/**\n * License Validation Service\n * Handles license validation for the jaak-stamps webcomponent\n */\n\nexport type Environment = 'dev' | 'qa' | 'sandbox' | 'prod';\n\nexport interface LicenseValidationRequest {\n license: string;\n origin: string;\n app_id?: string;\n product?: string;\n product_version?: string;\n metadata?: {\n [key: string]: any;\n };\n}\n\nexport interface LicenseValidationResponse {\n access_token: string;\n token_type: string;\n expires_at: string;\n session_id: string;\n jti: string;\n step: number;\n license: string;\n traceId?: string; // Generated or provided traceId\n}\n\nexport interface LicenseValidationError {\n error: string;\n error_description?: string;\n status_code?: number;\n}\n\nexport class LicenseValidationService {\n private apiEndpoint: string = '/api/v1/license/validate';\n private baseUrl: string;\n\n // Environment-specific base URLs\n private static readonly ENVIRONMENT_URLS: Record<Environment, string> = {\n dev: 'https://api.dev.jaak.ai',\n qa: 'https://api.qa.jaak.ai',\n sandbox: 'https://api.sandbox.jaak.ai',\n prod: 'https://services.api.jaak.ai',\n };\n\n constructor(environment: Environment = 'prod') {\n this.baseUrl = LicenseValidationService.ENVIRONMENT_URLS[environment];\n }\n\n /**\n * Validate license with the API\n * @param license License key to validate\n * @param traceId Optional trace ID from W3C Trace Context\n * @param appId Optional application ID\n * @param metadata Optional additional metadata\n * @returns Promise<LicenseValidationResponse>\n */\n async validateLicense(\n license: string,\n traceId?: string,\n appId: string = 'jaak-stamps-web',\n ): Promise<LicenseValidationResponse> {\n // Generate traceId if not provided\n const effectiveTraceId = traceId || this.generateTraceId();\n\n // Build request body\n const requestBody: LicenseValidationRequest = {\n license: traceId ? `L${effectiveTraceId}` : license,\n origin: 'web',\n app_id: appId,\n product: 'kyc',\n metadata: {\n sdk_version: '2.1.0',\n },\n };\n\n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n };\n\n // Add traceparent header with the effective traceId\n headers['traceparent'] = `00-${effectiveTraceId}-${this.generateSpanId()}-01`;\n\n try {\n const response = await fetch(`${this.baseUrl}${this.apiEndpoint}`, {\n method: 'POST',\n headers,\n body: JSON.stringify(requestBody),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw {\n error: errorData.error || 'license_validation_failed',\n error_description: errorData.error_description || `HTTP ${response.status}: ${response.statusText}`,\n status_code: response.status,\n } as LicenseValidationError;\n }\n\n const responseData = await response.json();\n // Add the traceId to the response\n return {\n ...responseData,\n traceId: effectiveTraceId,\n };\n } catch (error) {\n if ((error as any).error) {\n throw error;\n }\n\n throw {\n error: 'network_error',\n error_description: 'Failed to connect to license validation service',\n status_code: 0,\n } as LicenseValidationError;\n }\n }\n\n /**\n * Generate a random trace ID for W3C Trace Context (32 hex characters)\n */\n private generateTraceId(): string {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');\n }\n\n /**\n * Generate a random span ID for W3C Trace Context (16 hex characters)\n */\n private generateSpanId(): string {\n const array = new Uint8Array(8);\n crypto.getRandomValues(array);\n return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');\n }\n\n /**\n * Extract trace ID from license field\n * License format: \"L<32-hex-chars>\"\n * Example: \"Ld79223833a2fd91971e4c14a33298904\" -> \"d79223833a2fd91971e4c14a33298904\"\n */\n static extractTraceIdFromLicense(license: string): string | null {\n if (!license || typeof license !== 'string') {\n return null;\n }\n\n // Remove \"L\" prefix if present\n const traceId = license.startsWith('L') ? license.slice(1) : license;\n\n // Validate format (32 hex characters)\n if (traceId.length === 32 && /^[a-f0-9]{32}$/i.test(traceId)) {\n return traceId.toLowerCase();\n }\n\n console.warn('[LicenseValidationService] Invalid license format for trace ID:', license);\n return null;\n }\n}\n"]}
@@ -1,18 +1,74 @@
1
- import { trace, SpanStatusCode, context } from "@opentelemetry/api";
1
+ import { trace, SpanStatusCode, context, TraceFlags } from "@opentelemetry/api";
2
2
  import { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
3
3
  import { BatchSpanProcessor, ConsoleSpanExporter } from "@opentelemetry/sdk-trace-base";
4
4
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
5
5
  import { ZoneContextManager } from "@opentelemetry/context-zone";
6
6
  import { W3CTraceContextPropagator } from "@opentelemetry/core";
7
7
  import { registerInstrumentations } from "@opentelemetry/instrumentation";
8
- import { FetchInstrumentation } from "@opentelemetry/instrumentation-fetch";
9
- import { XMLHttpRequestInstrumentation } from "@opentelemetry/instrumentation-xml-http-request";
10
8
  import { UserInteractionInstrumentation } from "@opentelemetry/instrumentation-user-interaction";
11
- import { DocumentLoadInstrumentation } from "@opentelemetry/instrumentation-document-load";
12
9
  import UAParser from "ua-parser-js";
13
10
  // Semantic convention attribute names
14
11
  const ATTR_SERVICE_NAME = 'service.name';
15
12
  const ATTR_SERVICE_VERSION = 'service.version';
13
+ // Token de autenticación para OpenTelemetry Collector
14
+ const AUTH_TOKEN = 'eAzROSTiqNd3i+M9Jw6q5Tld0jarZc617sJB//pvb5c=';
15
+ // Instalar interceptores globalmente UNA SOLA VEZ antes de cualquier inicialización
16
+ let interceptorsInstalled = false;
17
+ function installAuthInterceptors() {
18
+ if (interceptorsInstalled) {
19
+ return;
20
+ }
21
+ interceptorsInstalled = true;
22
+ // Guardar referencia al XHR original ANTES de que OpenTelemetry lo toque
23
+ const RealXHR = window.XMLHttpRequest;
24
+ if (!RealXHR) {
25
+ console.error('[TracingService] XMLHttpRequest not available');
26
+ return;
27
+ }
28
+ // Crear wrapper que agrega el header
29
+ window.XMLHttpRequest = function () {
30
+ const xhr = new RealXHR();
31
+ const originalOpen = xhr.open;
32
+ const originalSend = xhr.send;
33
+ let isCollectorRequest = false;
34
+ xhr.open = function (method, url, ...args) {
35
+ const urlString = typeof url === 'string' ? url : url.toString();
36
+ isCollectorRequest = urlString.includes('collector.jaak.ai');
37
+ return originalOpen.apply(this, [method, url, ...args]);
38
+ };
39
+ xhr.send = function (...args) {
40
+ if (isCollectorRequest) {
41
+ this.setRequestHeader('Authorization', `Bearer ${AUTH_TOKEN}`);
42
+ }
43
+ return originalSend.apply(this, args);
44
+ };
45
+ return xhr;
46
+ };
47
+ // Copiar propiedades del constructor original
48
+ for (const prop in RealXHR) {
49
+ if (RealXHR.hasOwnProperty(prop)) {
50
+ window.XMLHttpRequest[prop] = RealXHR[prop];
51
+ }
52
+ }
53
+ // También interceptar fetch por si el SDK lo usa en lugar de XHR
54
+ const originalFetch = window.fetch;
55
+ window.fetch = function (input, init) {
56
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
57
+ if (url.includes('collector.jaak.ai')) {
58
+ const headers = new Headers(init?.headers || {});
59
+ headers.set('Authorization', `Bearer ${AUTH_TOKEN}`);
60
+ init = {
61
+ ...init,
62
+ headers: headers,
63
+ };
64
+ }
65
+ return originalFetch.call(this, input, init);
66
+ };
67
+ // Deshabilitar sendBeacon globalmente porque no soporta headers personalizados
68
+ navigator.sendBeacon = function () {
69
+ return false; // Retornar false fuerza al SDK a usar XHR/Fetch como fallback
70
+ };
71
+ }
16
72
  export class TracingService {
17
73
  provider = null;
18
74
  tracer = null;
@@ -24,7 +80,6 @@ export class TracingService {
24
80
  customerId;
25
81
  tenantId;
26
82
  environment;
27
- propagateTraceHeaderCorsUrls;
28
83
  enableAutoInstrumentation;
29
84
  spanProcessor = null;
30
85
  parser;
@@ -39,19 +94,43 @@ export class TracingService {
39
94
  this.customerId = config.customerId;
40
95
  this.tenantId = config.tenantId;
41
96
  this.environment = config.environment || 'production';
42
- this.propagateTraceHeaderCorsUrls = config.propagateTraceHeaderCorsUrls || [];
43
97
  this.enableAutoInstrumentation = config.enableAutoInstrumentation ?? false; // Default to false
44
98
  this.parser = new UAParser();
45
99
  }
46
100
  initialize() {
47
101
  try {
102
+ // Instalar interceptores de autenticación ANTES de crear el exporter
103
+ installAuthInterceptors();
48
104
  // Create OTLP exporter
49
- const exporter = new OTLPTraceExporter({
105
+ const baseExporter = new OTLPTraceExporter({
50
106
  url: this.collectorUrl,
51
107
  headers: {
52
108
  'Content-Type': 'application/json',
109
+ 'Authorization': `Bearer ${AUTH_TOKEN}`,
53
110
  },
111
+ // @ts-ignore - useSendBeacon no está en los tipos pero es soportada
112
+ useSendBeacon: false,
54
113
  });
114
+ // Wrap exporter to log export attempts
115
+ const exporter = {
116
+ export: (spans, resultCallback) => {
117
+ if (this.debug) {
118
+ console.log('[TracingService] 📤 Exporting', spans.length, 'spans to collector');
119
+ }
120
+ baseExporter.export(spans, (result) => {
121
+ if (result.code !== 0) {
122
+ console.error('[TracingService] ❌ Export failed:', result);
123
+ }
124
+ resultCallback(result);
125
+ });
126
+ },
127
+ shutdown: async () => {
128
+ return baseExporter.shutdown();
129
+ },
130
+ forceFlush: async () => {
131
+ return baseExporter.forceFlush();
132
+ },
133
+ };
55
134
  // Create console exporter for debug mode
56
135
  const exporters = [exporter];
57
136
  if (this.debug) {
@@ -76,12 +155,10 @@ export class TracingService {
76
155
  if (this.tenantId) {
77
156
  resourceAttributes['tenant.id'] = this.tenantId;
78
157
  }
79
- // Create tracer provider with resource
158
+ // Create tracer provider with span processor in constructor
80
159
  this.provider = new WebTracerProvider({
81
- // Resource will be added via span attributes since Resource class is not available
160
+ spanProcessors: [this.spanProcessor],
82
161
  });
83
- // Add span processor
84
- this.provider.addSpanProcessor?.(this.spanProcessor);
85
162
  // Configure context manager (Zone.js for async context propagation)
86
163
  const contextManager = new ZoneContextManager();
87
164
  // Configure propagators (W3C Trace Context + B3 for compatibility)
@@ -95,19 +172,7 @@ export class TracingService {
95
172
  this.tracer = trace.getTracer(this.serviceName, this.serviceVersion);
96
173
  // Initialize auto-instrumentation if enabled
97
174
  if (this.enableAutoInstrumentation) {
98
- this.initializeAutoInstrumentation(resourceAttributes);
99
- }
100
- if (this.debug) {
101
- console.log('[TracingService] Initialized successfully', {
102
- collectorUrl: this.collectorUrl,
103
- serviceName: this.serviceName,
104
- serviceVersion: this.serviceVersion,
105
- environment: this.environment,
106
- customerId: this.customerId,
107
- tenantId: this.tenantId,
108
- autoInstrumentation: this.enableAutoInstrumentation,
109
- propagateUrls: this.propagateTraceHeaderCorsUrls,
110
- });
175
+ this.initializeAutoInstrumentation();
111
176
  }
112
177
  }
113
178
  catch (error) {
@@ -115,37 +180,15 @@ export class TracingService {
115
180
  // Don't throw - telemetry should fail silently in production
116
181
  }
117
182
  }
118
- initializeAutoInstrumentation(resourceAttributes) {
183
+ initializeAutoInstrumentation() {
119
184
  try {
120
- // Auto-instrumentation is disabled by default to reduce noise
121
- // Enable via config.enableAutoInstrumentation = true if needed
185
+ // NOTE: XHR and Fetch instrumentation are disabled because we manually intercept
186
+ // them to add authentication headers. Enabling them causes conflicts.
187
+ // NOTE: DocumentLoadInstrumentation is disabled because it captures events that
188
+ // occurred before the component initialized, and cannot use custom trace IDs.
189
+ // Only enable user interaction instrumentation
122
190
  registerInstrumentations({
123
191
  instrumentations: [
124
- // Fetch API instrumentation
125
- new FetchInstrumentation({
126
- propagateTraceHeaderCorsUrls: this.propagateTraceHeaderCorsUrls,
127
- clearTimingResources: true,
128
- applyCustomAttributesOnSpan: (span, _request, response) => {
129
- // Add resource attributes to each span
130
- Object.entries(resourceAttributes).forEach(([key, value]) => {
131
- span.setAttribute(key, value);
132
- });
133
- // Add custom attributes
134
- if (response && 'status' in response) {
135
- span.setAttribute('http.response.status_code', response.status);
136
- }
137
- },
138
- }),
139
- // XMLHttpRequest instrumentation
140
- new XMLHttpRequestInstrumentation({
141
- propagateTraceHeaderCorsUrls: this.propagateTraceHeaderCorsUrls,
142
- applyCustomAttributesOnSpan: (span) => {
143
- // Add resource attributes to each span
144
- Object.entries(resourceAttributes).forEach(([key, value]) => {
145
- span.setAttribute(key, value);
146
- });
147
- },
148
- }),
149
192
  // User interaction instrumentation (clicks, etc.)
150
193
  new UserInteractionInstrumentation({
151
194
  eventNames: ['click', 'submit'],
@@ -154,13 +197,8 @@ export class TracingService {
154
197
  return element.tagName === 'BUTTON' || element.tagName === 'A' || element.tagName === 'FORM';
155
198
  },
156
199
  }),
157
- // Document load instrumentation
158
- new DocumentLoadInstrumentation(),
159
200
  ],
160
201
  });
161
- if (this.debug) {
162
- console.log('[TracingService] Auto-instrumentation enabled');
163
- }
164
202
  }
165
203
  catch (error) {
166
204
  console.error('[TracingService] Failed to initialize auto-instrumentation:', error);
@@ -251,19 +289,24 @@ export class TracingService {
251
289
  }
252
290
  startSpan(name, attributes) {
253
291
  if (!this.tracer) {
254
- // Return a no-op span if tracer is not initialized
292
+ console.warn('[TracingService] Tracer not initialized, returning no-op span');
255
293
  return trace.getTracer('noop').startSpan('noop');
256
294
  }
257
295
  try {
258
296
  let currentContext = context.active();
259
- // If we have a session trace ID, create a span context with it
260
- if (this.sessionTraceId) {
261
- const spanContext = {
297
+ // If we have a session trace ID and there's no active span, create a root span context
298
+ if (this.sessionTraceId && !trace.getSpan(currentContext)) {
299
+ // Create a valid span context for the custom trace ID
300
+ const remoteSpanContext = {
262
301
  traceId: this.sessionTraceId,
263
302
  spanId: this.generateSpanId(),
264
- traceFlags: 0x01, // Sampled
303
+ traceFlags: TraceFlags.SAMPLED,
304
+ isRemote: true,
265
305
  };
266
- currentContext = trace.setSpanContext(currentContext, spanContext);
306
+ // Create a non-recording span with the custom trace context
307
+ const remoteSpan = trace.wrapSpanContext(remoteSpanContext);
308
+ // Set this span in the context so child spans inherit the trace ID
309
+ currentContext = trace.setSpan(currentContext, remoteSpan);
267
310
  }
268
311
  // Get device info
269
312
  const deviceInfo = this.getDeviceInfo();
@@ -320,20 +363,15 @@ export class TracingService {
320
363
  }
321
364
  }
322
365
  endSpan(span) {
323
- if (!span)
366
+ if (!span) {
367
+ console.warn('[TracingService] endSpan called with null/undefined span');
324
368
  return;
369
+ }
325
370
  try {
326
371
  span.end();
327
- if (this.debug) {
328
- const spanContext = span.spanContext();
329
- console.log('[TracingService] Ended span', {
330
- traceId: spanContext.traceId,
331
- spanId: spanContext.spanId,
332
- });
333
- }
334
372
  }
335
373
  catch (error) {
336
- console.error('[TracingService] Failed to end span:', error);
374
+ console.error('[TracingService] Failed to end span:', error);
337
375
  }
338
376
  }
339
377
  addSpanEvent(span, name, attributes) {
@@ -358,9 +396,6 @@ export class TracingService {
358
396
  code: SpanStatusCode.ERROR,
359
397
  message: error.message,
360
398
  });
361
- if (this.debug) {
362
- console.log('[TracingService] Recorded exception:', error);
363
- }
364
399
  }
365
400
  catch (err) {
366
401
  console.error('[TracingService] Failed to record exception:', err);
@@ -397,6 +432,26 @@ export class TracingService {
397
432
  this.endSpan(span);
398
433
  }
399
434
  }
435
+ async traceAsync(name, fn, attributes) {
436
+ return this.trace(name, fn, attributes);
437
+ }
438
+ /**
439
+ * Flush all pending spans to the collector
440
+ * Call this when capture/process is complete to send all traces
441
+ */
442
+ async flush() {
443
+ try {
444
+ if (!this.spanProcessor) {
445
+ console.warn('[TracingService] No span processor available to flush');
446
+ return;
447
+ }
448
+ await this.spanProcessor.forceFlush();
449
+ }
450
+ catch (error) {
451
+ console.error('[TracingService] ❌ Failed to flush spans:', error);
452
+ throw error;
453
+ }
454
+ }
400
455
  async cleanup() {
401
456
  try {
402
457
  if (this.spanProcessor) {
@@ -406,9 +461,6 @@ export class TracingService {
406
461
  if (this.provider) {
407
462
  await this.provider.shutdown();
408
463
  }
409
- if (this.debug) {
410
- console.log('[TracingService] Cleaned up successfully');
411
- }
412
464
  }
413
465
  catch (error) {
414
466
  console.error('[TracingService] Failed to cleanup:', error);
@@ -1 +1 @@
1
- {"version":3,"file":"TracingService.js","sourceRoot":"","sources":["../../src/services/TracingService.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAQ,cAAc,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACxF,OAAO,EAAE,iBAAiB,EAAE,MAAM,yCAAyC,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAChE,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAC5E,OAAO,EAAE,6BAA6B,EAAE,MAAM,iDAAiD,CAAC;AAChG,OAAO,EAAE,8BAA8B,EAAE,MAAM,iDAAiD,CAAC;AACjG,OAAO,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAC3F,OAAO,QAAQ,MAAM,cAAc,CAAC;AAEpC,sCAAsC;AACtC,MAAM,iBAAiB,GAAG,cAAc,CAAC;AACzC,MAAM,oBAAoB,GAAG,iBAAiB,CAAC;AAsB/C,MAAM,OAAO,cAAc;IACjB,QAAQ,GAA6B,IAAI,CAAC;IAC1C,MAAM,GAAQ,IAAI,CAAC;IACnB,cAAc,GAAkB,IAAI,CAAC;IAC5B,YAAY,CAAS;IACrB,WAAW,CAAS;IACpB,cAAc,CAAS;IACvB,KAAK,CAAU;IACf,UAAU,CAAU;IACpB,QAAQ,CAAU;IAClB,WAAW,CAAU;IACrB,4BAA4B,CAAsB;IAClD,y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,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;IAED;;OAEG;IACH,iBAAiB;QACf,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;YAC7C,OAAO,IAAI,EAAE,WAAW,EAAE,CAAC,OAAO,CAAC;QACrC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC;IAED;;OAEG;IACH,gBAAgB;QACd,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;YAC7C,OAAO,IAAI,EAAE,WAAW,EAAE,CAAC,MAAM,CAAC;QACpC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC;CACF","sourcesContent":["import { ITracingService } from './interfaces/ITracingService';\nimport { trace, Span, SpanStatusCode, context } from '@opentelemetry/api';\nimport { WebTracerProvider } from '@opentelemetry/sdk-trace-web';\nimport { BatchSpanProcessor, ConsoleSpanExporter } from '@opentelemetry/sdk-trace-base';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { ZoneContextManager } from '@opentelemetry/context-zone';\nimport { W3CTraceContextPropagator } from '@opentelemetry/core';\nimport { registerInstrumentations } from '@opentelemetry/instrumentation';\nimport { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';\nimport { XMLHttpRequestInstrumentation } from '@opentelemetry/instrumentation-xml-http-request';\nimport { UserInteractionInstrumentation } from '@opentelemetry/instrumentation-user-interaction';\nimport { DocumentLoadInstrumentation } from '@opentelemetry/instrumentation-document-load';\nimport UAParser from 'ua-parser-js';\n\n// Semantic convention attribute names\nconst ATTR_SERVICE_NAME = 'service.name';\nconst ATTR_SERVICE_VERSION = 'service.version';\n\ninterface GeoLocation {\n country?: string;\n region?: string;\n city?: string;\n latitude?: number;\n longitude?: number;\n}\n\nexport interface TracingConfig {\n collectorUrl?: string;\n serviceName?: string;\n serviceVersion?: string;\n debug?: boolean;\n customerId?: string;\n tenantId?: string;\n environment?: string;\n propagateTraceHeaderCorsUrls?: (string | RegExp)[];\n enableAutoInstrumentation?: boolean;\n}\n\nexport class TracingService implements ITracingService {\n private provider: WebTracerProvider | null = null;\n private tracer: any = null;\n private sessionTraceId: string | null = null;\n private readonly collectorUrl: string;\n private readonly serviceName: string;\n private readonly serviceVersion: string;\n private readonly debug: boolean;\n private readonly customerId?: string;\n private readonly tenantId?: string;\n private readonly environment?: string;\n private readonly propagateTraceHeaderCorsUrls: (string | RegExp)[];\n private readonly enableAutoInstrumentation: boolean;\n private spanProcessor: BatchSpanProcessor | null = null;\n private parser: UAParser;\n private geoCache: GeoLocation | null = null;\n private geoCacheTimestamp: number = 0;\n private readonly GEO_CACHE_DURATION_MS = 60 * 60 * 1000; // 1 hour\n\n constructor(config: TracingConfig = {}) {\n this.collectorUrl = config.collectorUrl || 'https://collector.jaak.ai/v1/traces';\n this.serviceName = config.serviceName || 'jaak-stamps-webcomponent';\n this.serviceVersion = config.serviceVersion || '2.1.0';\n this.debug = config.debug || false;\n this.customerId = config.customerId;\n this.tenantId = config.tenantId;\n this.environment = config.environment || 'production';\n this.propagateTraceHeaderCorsUrls = config.propagateTraceHeaderCorsUrls || [];\n this.enableAutoInstrumentation = config.enableAutoInstrumentation ?? false; // Default to false\n this.parser = new UAParser();\n }\n\n initialize(): void {\n try {\n // Create OTLP exporter\n const exporter = new OTLPTraceExporter({\n url: this.collectorUrl,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n // Create console exporter for debug mode\n const exporters: any[] = [exporter];\n if (this.debug) {\n exporters.push(new ConsoleSpanExporter());\n }\n\n // Create batch span processor for each exporter\n this.spanProcessor = new BatchSpanProcessor(exporter, {\n maxQueueSize: 100,\n maxExportBatchSize: 10,\n scheduledDelayMillis: 5000,\n exportTimeoutMillis: 30000,\n });\n\n // Create resource attributes\n const resourceAttributes: Record<string, string> = {\n [ATTR_SERVICE_NAME]: this.serviceName,\n [ATTR_SERVICE_VERSION]: this.serviceVersion,\n 'deployment.environment': this.environment,\n };\n\n if (this.customerId) {\n resourceAttributes['customer.id'] = this.customerId;\n }\n\n if (this.tenantId) {\n resourceAttributes['tenant.id'] = this.tenantId;\n }\n\n // Create tracer provider with resource\n this.provider = new WebTracerProvider({\n // Resource will be added via span attributes since Resource class is not available\n });\n\n // Add span processor\n (this.provider as any).addSpanProcessor?.(this.spanProcessor);\n\n // Configure context manager (Zone.js for async context propagation)\n const contextManager = new ZoneContextManager();\n\n // Configure propagators (W3C Trace Context + B3 for compatibility)\n const propagator = new W3CTraceContextPropagator();\n\n // Register the provider globally with context manager and propagator\n this.provider.register({\n contextManager: contextManager,\n propagator: propagator,\n });\n\n // Get tracer with service metadata\n this.tracer = trace.getTracer(this.serviceName, this.serviceVersion);\n\n // Initialize auto-instrumentation if enabled\n if (this.enableAutoInstrumentation) {\n this.initializeAutoInstrumentation(resourceAttributes);\n }\n\n if (this.debug) {\n console.log('[TracingService] Initialized successfully', {\n collectorUrl: this.collectorUrl,\n serviceName: this.serviceName,\n serviceVersion: this.serviceVersion,\n environment: this.environment,\n customerId: this.customerId,\n tenantId: this.tenantId,\n autoInstrumentation: this.enableAutoInstrumentation,\n propagateUrls: this.propagateTraceHeaderCorsUrls,\n });\n }\n } catch (error) {\n console.error('[TracingService] Failed to initialize:', error);\n // Don't throw - telemetry should fail silently in production\n }\n }\n\n private initializeAutoInstrumentation(resourceAttributes: Record<string, string>): void {\n try {\n // Auto-instrumentation is disabled by default to reduce noise\n // Enable via config.enableAutoInstrumentation = true if needed\n registerInstrumentations({\n instrumentations: [\n // Fetch API instrumentation\n new FetchInstrumentation({\n propagateTraceHeaderCorsUrls: this.propagateTraceHeaderCorsUrls,\n clearTimingResources: true,\n applyCustomAttributesOnSpan: (span: Span, _request: Request | RequestInit, response: Response | FetchError) => {\n // Add resource attributes to each span\n Object.entries(resourceAttributes).forEach(([key, value]) => {\n span.setAttribute(key, value);\n });\n\n // Add custom attributes\n if (response && 'status' in response) {\n span.setAttribute('http.response.status_code', response.status);\n }\n },\n }),\n\n // XMLHttpRequest instrumentation\n new XMLHttpRequestInstrumentation({\n propagateTraceHeaderCorsUrls: this.propagateTraceHeaderCorsUrls,\n applyCustomAttributesOnSpan: (span: Span) => {\n // Add resource attributes to each span\n Object.entries(resourceAttributes).forEach(([key, value]) => {\n span.setAttribute(key, value);\n });\n },\n }),\n\n // User interaction instrumentation (clicks, etc.)\n new UserInteractionInstrumentation({\n eventNames: ['click', 'submit'],\n shouldPreventSpanCreation: (_eventType: string, element: HTMLElement) => {\n // Don't create spans for every click, only important ones\n return element.tagName === 'BUTTON' || element.tagName === 'A' || element.tagName === 'FORM';\n },\n }),\n\n // Document load instrumentation\n new DocumentLoadInstrumentation(),\n ],\n });\n\n if (this.debug) {\n console.log('[TracingService] Auto-instrumentation enabled');\n }\n } catch (error) {\n console.error('[TracingService] Failed to initialize auto-instrumentation:', error);\n }\n }\n\n private getDeviceInfo() {\n const result = this.parser.getResult();\n return {\n type: result.device.type || 'desktop',\n vendor: result.device.vendor || 'unknown',\n model: result.device.model || 'unknown',\n };\n }\n\n private getBrowserInfo() {\n const result = this.parser.getResult();\n return {\n name: result.browser.name || 'unknown',\n version: result.browser.version || 'unknown',\n major: result.browser.major || 'unknown',\n };\n }\n\n private getOSInfo() {\n const result = this.parser.getResult();\n return {\n name: result.os.name || 'unknown',\n version: result.os.version || 'unknown',\n };\n }\n\n /**\n * Set the session trace ID from external source (license or component prop)\n * @param traceId - The trace ID to use for all spans (32 hex characters)\n */\n setSessionTraceId(traceId: string | null): void {\n if (traceId && traceId.length === 32 && /^[a-f0-9]{32}$/i.test(traceId)) {\n this.sessionTraceId = traceId.toLowerCase();\n if (this.debug) {\n console.log('[TracingService] Session trace ID set:', this.sessionTraceId);\n }\n } else if (traceId) {\n console.warn('[TracingService] Invalid trace ID format. Must be 32 hex characters:', traceId);\n }\n }\n\n /**\n * Get the current session trace ID\n */\n getSessionTraceId(): string | null {\n return this.sessionTraceId;\n }\n\n /**\n * Generate a random span ID (16 hex characters)\n */\n private generateSpanId(): string {\n const bytes = new Uint8Array(8);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map(byte => byte.toString(16).padStart(2, '0'))\n .join('');\n }\n\n private async getGeoLocation(): Promise<GeoLocation> {\n const now = Date.now();\n\n // Return cached value if still valid\n if (this.geoCache && (now - this.geoCacheTimestamp) < this.GEO_CACHE_DURATION_MS) {\n return this.geoCache;\n }\n\n try {\n const response = await fetch('https://ipapi.co/json/', {\n signal: AbortSignal.timeout(5000), // 5 second timeout\n });\n\n if (!response.ok) {\n return {};\n }\n\n const data = await response.json();\n this.geoCache = {\n country: data.country_name,\n region: data.region,\n city: data.city,\n latitude: data.latitude,\n longitude: data.longitude,\n };\n this.geoCacheTimestamp = now;\n\n return this.geoCache;\n } catch (error) {\n console.warn('[TracingService] Failed to fetch geo location:', error);\n return this.geoCache || {};\n }\n }\n\n startSpan(name: string, attributes?: Record<string, any>): Span {\n if (!this.tracer) {\n // Return a no-op span if tracer is not initialized\n return trace.getTracer('noop').startSpan('noop');\n }\n\n try {\n let currentContext = context.active();\n\n // If we have a session trace ID, create a span context with it\n if (this.sessionTraceId) {\n const spanContext = {\n traceId: this.sessionTraceId,\n spanId: this.generateSpanId(),\n traceFlags: 0x01, // Sampled\n };\n currentContext = trace.setSpanContext(currentContext, spanContext);\n }\n\n // Get device info\n const deviceInfo = this.getDeviceInfo();\n const browserInfo = this.getBrowserInfo();\n const osInfo = this.getOSInfo();\n\n const span = this.tracer.startSpan(name, {\n attributes: {\n ...attributes,\n 'component': this.serviceName.includes('stamps') ? 'jaak-stamps' : 'jaak-visage',\n [ATTR_SERVICE_NAME]: this.serviceName,\n [ATTR_SERVICE_VERSION]: this.serviceVersion,\n 'deployment.environment': this.environment,\n\n // Add trace.id attribute for easy filtering\n 'trace.id': this.sessionTraceId || 'auto-generated',\n\n // Device info\n 'device.type': deviceInfo.type,\n 'device.vendor': deviceInfo.vendor,\n 'device.model': deviceInfo.model,\n\n // Browser info\n 'browser.name': browserInfo.name,\n 'browser.version': browserInfo.version,\n 'browser.major': browserInfo.major,\n\n // OS info\n 'os.name': osInfo.name,\n 'os.version': osInfo.version,\n\n // User agent\n 'user_agent': navigator.userAgent,\n\n ...(this.customerId && { 'customer.id': this.customerId }),\n ...(this.tenantId && { 'tenant.id': this.tenantId }),\n },\n }, currentContext);\n\n // Async add geo location (non-blocking)\n this.getGeoLocation().then(geo => {\n if (geo.country) span.setAttribute('geo.country', geo.country);\n if (geo.region) span.setAttribute('geo.region', geo.region);\n if (geo.city) span.setAttribute('geo.city', geo.city);\n }).catch(err => console.warn('Failed to add geo attributes:', err));\n\n if (this.debug) {\n console.log(`[TracingService] Started span: ${name}`, {\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n sessionTraceId: this.sessionTraceId,\n attributes,\n });\n }\n\n return span;\n } catch (error) {\n console.error('[TracingService] Failed to start span:', error);\n return trace.getTracer('noop').startSpan('noop');\n }\n }\n\n endSpan(span: Span): void {\n if (!span) return;\n\n try {\n span.end();\n\n if (this.debug) {\n const spanContext = span.spanContext();\n console.log('[TracingService] Ended span', {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n });\n }\n } catch (error) {\n console.error('[TracingService] Failed to end span:', error);\n }\n }\n\n addSpanEvent(span: Span, name: string, attributes?: Record<string, any>): void {\n if (!span) return;\n\n try {\n span.addEvent(name, attributes);\n\n if (this.debug) {\n console.log(`[TracingService] Added event to span: ${name}`, attributes);\n }\n } catch (error) {\n console.error('[TracingService] Failed to add span event:', error);\n }\n }\n\n recordException(span: Span, error: Error): void {\n if (!span) return;\n\n try {\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n\n if (this.debug) {\n console.log('[TracingService] Recorded exception:', error);\n }\n } catch (err) {\n console.error('[TracingService] Failed to record exception:', err);\n }\n }\n\n setSpanAttribute(span: Span, key: string, value: any): void {\n if (!span) return;\n\n try {\n span.setAttribute(key, value);\n\n if (this.debug) {\n console.log(`[TracingService] Set attribute: ${key} = ${value}`);\n }\n } catch (error) {\n console.error('[TracingService] Failed to set span attribute:', error);\n }\n }\n\n async trace<T>(name: string, fn: () => T | Promise<T>, attributes?: Record<string, any>): Promise<T> {\n const span = this.startSpan(name, attributes);\n\n try {\n // Run the function within the span context\n const result = await context.with(trace.setSpan(context.active(), span), async () => {\n return await fn();\n });\n\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n this.recordException(span, error as Error);\n throw error;\n } finally {\n this.endSpan(span);\n }\n }\n\n async cleanup(): Promise<void> {\n try {\n if (this.spanProcessor) {\n await this.spanProcessor.forceFlush();\n await this.spanProcessor.shutdown();\n }\n\n if (this.provider) {\n await this.provider.shutdown();\n }\n\n if (this.debug) {\n console.log('[TracingService] Cleaned up successfully');\n }\n } catch (error) {\n console.error('[TracingService] Failed to cleanup:', error);\n }\n }\n\n /**\n * Get the current trace ID (useful for logging correlation)\n */\n getCurrentTraceId(): string | undefined {\n try {\n const span = trace.getSpan(context.active());\n return span?.spanContext().traceId;\n } catch {\n return undefined;\n }\n }\n\n /**\n * Get the current span ID\n */\n getCurrentSpanId(): string | undefined {\n try {\n const span = trace.getSpan(context.active());\n return span?.spanContext().spanId;\n } catch {\n return undefined;\n }\n }\n}\n\n// Type for fetch errors\ninterface FetchError {\n message: string;\n name: string;\n}\n"]}
1
+ {"version":3,"file":"TracingService.js","sourceRoot":"","sources":["../../src/services/TracingService.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAQ,cAAc,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACtF,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,+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,EAAE,CAAC;YACjC,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;IAED;;OAEG;IACH,iBAAiB;QACf,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;YAC7C,OAAO,IAAI,EAAE,WAAW,EAAE,CAAC,OAAO,CAAC;QACrC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC;IAED;;OAEG;IACH,gBAAgB;QACd,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;YAC7C,OAAO,IAAI,EAAE,WAAW,EAAE,CAAC,MAAM,CAAC;QACpC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC;CACF","sourcesContent":["import { ITracingService } from './interfaces/ITracingService';\nimport { trace, Span, SpanStatusCode, context, TraceFlags } from '@opentelemetry/api';\nimport { WebTracerProvider } from '@opentelemetry/sdk-trace-web';\nimport { BatchSpanProcessor, ConsoleSpanExporter } from '@opentelemetry/sdk-trace-base';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { ZoneContextManager } from '@opentelemetry/context-zone';\nimport { W3CTraceContextPropagator } from '@opentelemetry/core';\nimport { registerInstrumentations } from '@opentelemetry/instrumentation';\nimport { UserInteractionInstrumentation } from '@opentelemetry/instrumentation-user-interaction';\nimport UAParser from 'ua-parser-js';\n\n// Semantic convention attribute names\nconst ATTR_SERVICE_NAME = 'service.name';\nconst ATTR_SERVICE_VERSION = 'service.version';\n\n// Token de autenticación para OpenTelemetry Collector\nconst AUTH_TOKEN = 'eAzROSTiqNd3i+M9Jw6q5Tld0jarZc617sJB//pvb5c=';\n\n// Instalar interceptores globalmente UNA SOLA VEZ antes de cualquier inicialización\nlet interceptorsInstalled = false;\n\nfunction installAuthInterceptors(): void {\n if (interceptorsInstalled) {\n return;\n }\n\n interceptorsInstalled = true;\n\n // Guardar referencia al XHR original ANTES de que OpenTelemetry lo toque\n const RealXHR = (window as any).XMLHttpRequest;\n\n if (!RealXHR) {\n console.error('[TracingService] XMLHttpRequest not available');\n return;\n }\n\n // Crear wrapper que agrega el header\n (window as any).XMLHttpRequest = function() {\n const xhr = new RealXHR();\n const originalOpen = xhr.open;\n const originalSend = xhr.send;\n let isCollectorRequest = false;\n\n xhr.open = function(method: string, url: string | URL, ...args: any[]) {\n const urlString = typeof url === 'string' ? url : url.toString();\n isCollectorRequest = urlString.includes('collector.jaak.ai');\n return originalOpen.apply(this, [method, url, ...args]);\n };\n\n xhr.send = function(...args: any[]) {\n if (isCollectorRequest) {\n this.setRequestHeader('Authorization', `Bearer ${AUTH_TOKEN}`);\n }\n return originalSend.apply(this, args);\n };\n\n return xhr;\n };\n\n // Copiar propiedades del constructor original\n for (const prop in RealXHR) {\n if (RealXHR.hasOwnProperty(prop)) {\n (window as any).XMLHttpRequest[prop] = RealXHR[prop];\n }\n }\n\n // También interceptar fetch por si el SDK lo usa en lugar de XHR\n const originalFetch = window.fetch;\n window.fetch = function(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : (input as Request).url;\n\n if (url.includes('collector.jaak.ai')) {\n const headers = new Headers(init?.headers || {});\n headers.set('Authorization', `Bearer ${AUTH_TOKEN}`);\n\n init = {\n ...init,\n headers: headers,\n };\n }\n\n return originalFetch.call(this, input, init);\n };\n\n // Deshabilitar sendBeacon globalmente porque no soporta headers personalizados\n (navigator as any).sendBeacon = function() {\n return false; // Retornar false fuerza al SDK a usar XHR/Fetch como fallback\n };\n}\n\ninterface GeoLocation {\n country?: string;\n region?: string;\n city?: string;\n latitude?: number;\n longitude?: number;\n}\n\nexport interface TracingConfig {\n collectorUrl?: string;\n serviceName?: string;\n serviceVersion?: string;\n debug?: boolean;\n customerId?: string;\n tenantId?: string;\n environment?: string;\n propagateTraceHeaderCorsUrls?: (string | RegExp)[];\n enableAutoInstrumentation?: boolean;\n}\n\nexport class TracingService implements ITracingService {\n private provider: WebTracerProvider | null = null;\n private tracer: any = null;\n private sessionTraceId: string | null = null;\n private readonly collectorUrl: string;\n private readonly serviceName: string;\n private readonly serviceVersion: string;\n private readonly debug: boolean;\n private readonly customerId?: string;\n private readonly tenantId?: string;\n private readonly environment?: string;\n private readonly enableAutoInstrumentation: boolean;\n private spanProcessor: BatchSpanProcessor | null = null;\n private parser: UAParser;\n private geoCache: GeoLocation | null = null;\n private geoCacheTimestamp: number = 0;\n private readonly GEO_CACHE_DURATION_MS = 60 * 60 * 1000; // 1 hour\n\n constructor(config: TracingConfig = {}) {\n this.collectorUrl = config.collectorUrl || 'https://collector.jaak.ai/v1/traces';\n this.serviceName = config.serviceName || 'jaak-stamps-webcomponent';\n this.serviceVersion = config.serviceVersion || '2.1.0';\n this.debug = config.debug || false;\n this.customerId = config.customerId;\n this.tenantId = config.tenantId;\n this.environment = config.environment || 'production';\n this.enableAutoInstrumentation = config.enableAutoInstrumentation ?? false; // Default to false\n this.parser = new UAParser();\n }\n\n initialize(): void {\n try {\n // Instalar interceptores de autenticación ANTES de crear el exporter\n installAuthInterceptors();\n\n // Create OTLP exporter\n const baseExporter = new OTLPTraceExporter({\n url: this.collectorUrl,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${AUTH_TOKEN}`,\n },\n // @ts-ignore - useSendBeacon no está en los tipos pero es soportada\n useSendBeacon: false,\n });\n\n // Wrap exporter to log export attempts\n const exporter = {\n export: (spans: any, resultCallback: any) => {\n if (this.debug) {\n console.log('[TracingService] 📤 Exporting', spans.length, 'spans to collector');\n }\n\n baseExporter.export(spans, (result: any) => {\n if (result.code !== 0) {\n console.error('[TracingService] ❌ Export failed:', result);\n }\n resultCallback(result);\n });\n },\n shutdown: async () => {\n return baseExporter.shutdown();\n },\n forceFlush: async () => {\n return baseExporter.forceFlush();\n },\n } as any;\n\n // Create console exporter for debug mode\n const exporters: any[] = [exporter];\n if (this.debug) {\n exporters.push(new ConsoleSpanExporter());\n }\n\n // Create batch span processor for each exporter\n this.spanProcessor = new BatchSpanProcessor(exporter, {\n maxQueueSize: 100,\n maxExportBatchSize: 10,\n scheduledDelayMillis: 5000,\n exportTimeoutMillis: 30000,\n });\n\n // Create resource attributes\n const resourceAttributes: Record<string, string> = {\n [ATTR_SERVICE_NAME]: this.serviceName,\n [ATTR_SERVICE_VERSION]: this.serviceVersion,\n 'deployment.environment': this.environment,\n };\n\n if (this.customerId) {\n resourceAttributes['customer.id'] = this.customerId;\n }\n\n if (this.tenantId) {\n resourceAttributes['tenant.id'] = this.tenantId;\n }\n\n // Create tracer provider with span processor in constructor\n this.provider = new WebTracerProvider({\n spanProcessors: [this.spanProcessor],\n });\n\n // Configure context manager (Zone.js for async context propagation)\n const contextManager = new ZoneContextManager();\n\n // Configure propagators (W3C Trace Context + B3 for compatibility)\n const propagator = new W3CTraceContextPropagator();\n\n // Register the provider globally with context manager and propagator\n this.provider.register({\n contextManager: contextManager,\n propagator: propagator,\n });\n\n // Get tracer with service metadata\n this.tracer = trace.getTracer(this.serviceName, this.serviceVersion);\n\n // Initialize auto-instrumentation if enabled\n if (this.enableAutoInstrumentation) {\n this.initializeAutoInstrumentation();\n }\n } catch (error) {\n console.error('[TracingService] Failed to initialize:', error);\n // Don't throw - telemetry should fail silently in production\n }\n }\n\n private initializeAutoInstrumentation(): void {\n try {\n // NOTE: XHR and Fetch instrumentation are disabled because we manually intercept\n // them to add authentication headers. Enabling them causes conflicts.\n\n // NOTE: DocumentLoadInstrumentation is disabled because it captures events that\n // occurred before the component initialized, and cannot use custom trace IDs.\n\n // Only enable user interaction instrumentation\n registerInstrumentations({\n instrumentations: [\n // User interaction instrumentation (clicks, etc.)\n new UserInteractionInstrumentation({\n eventNames: ['click', 'submit'],\n shouldPreventSpanCreation: (_eventType: string, element: HTMLElement) => {\n // Don't create spans for every click, only important ones\n return element.tagName === 'BUTTON' || element.tagName === 'A' || element.tagName === 'FORM';\n },\n }),\n ],\n });\n } catch (error) {\n console.error('[TracingService] Failed to initialize auto-instrumentation:', error);\n }\n }\n\n private getDeviceInfo() {\n const result = this.parser.getResult();\n return {\n type: result.device.type || 'desktop',\n vendor: result.device.vendor || 'unknown',\n model: result.device.model || 'unknown',\n };\n }\n\n private getBrowserInfo() {\n const result = this.parser.getResult();\n return {\n name: result.browser.name || 'unknown',\n version: result.browser.version || 'unknown',\n major: result.browser.major || 'unknown',\n };\n }\n\n private getOSInfo() {\n const result = this.parser.getResult();\n return {\n name: result.os.name || 'unknown',\n version: result.os.version || 'unknown',\n };\n }\n\n /**\n * Set the session trace ID from external source (license or component prop)\n * @param traceId - The trace ID to use for all spans (32 hex characters)\n */\n setSessionTraceId(traceId: string | null): void {\n if (traceId && traceId.length === 32 && /^[a-f0-9]{32}$/i.test(traceId)) {\n this.sessionTraceId = traceId.toLowerCase();\n if (this.debug) {\n console.log('[TracingService] Session trace ID set:', this.sessionTraceId);\n }\n } else if (traceId) {\n console.warn('[TracingService] Invalid trace ID format. Must be 32 hex characters:', traceId);\n }\n }\n\n /**\n * Get the current session trace ID\n */\n getSessionTraceId(): string | null {\n return this.sessionTraceId;\n }\n\n /**\n * Generate a random span ID (16 hex characters)\n */\n private generateSpanId(): string {\n const bytes = new Uint8Array(8);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map(byte => byte.toString(16).padStart(2, '0'))\n .join('');\n }\n\n private async getGeoLocation(): Promise<GeoLocation> {\n const now = Date.now();\n\n // Return cached value if still valid\n if (this.geoCache && (now - this.geoCacheTimestamp) < this.GEO_CACHE_DURATION_MS) {\n return this.geoCache;\n }\n\n try {\n const response = await fetch('https://ipapi.co/json/', {\n signal: AbortSignal.timeout(5000), // 5 second timeout\n });\n\n if (!response.ok) {\n return {};\n }\n\n const data = await response.json();\n this.geoCache = {\n country: data.country_name,\n region: data.region,\n city: data.city,\n latitude: data.latitude,\n longitude: data.longitude,\n };\n this.geoCacheTimestamp = now;\n\n return this.geoCache;\n } catch (error) {\n console.warn('[TracingService] Failed to fetch geo location:', error);\n return this.geoCache || {};\n }\n }\n\n startSpan(name: string, attributes?: Record<string, any>): Span {\n if (!this.tracer) {\n console.warn('[TracingService] Tracer not initialized, returning no-op span');\n return trace.getTracer('noop').startSpan('noop');\n }\n\n try {\n let currentContext = context.active();\n\n // If we have a session trace ID and there's no active span, create a root span context\n if (this.sessionTraceId && !trace.getSpan(currentContext)) {\n // Create a valid span context for the custom trace ID\n const remoteSpanContext = {\n traceId: this.sessionTraceId,\n spanId: this.generateSpanId(),\n traceFlags: TraceFlags.SAMPLED,\n isRemote: true,\n };\n\n // Create a non-recording span with the custom trace context\n const remoteSpan = trace.wrapSpanContext(remoteSpanContext);\n\n // Set this span in the context so child spans inherit the trace ID\n currentContext = trace.setSpan(currentContext, remoteSpan);\n }\n\n // Get device info\n const deviceInfo = this.getDeviceInfo();\n const browserInfo = this.getBrowserInfo();\n const osInfo = this.getOSInfo();\n\n const span = this.tracer.startSpan(name, {\n attributes: {\n ...attributes,\n 'component': this.serviceName.includes('stamps') ? 'jaak-stamps' : 'jaak-visage',\n [ATTR_SERVICE_NAME]: this.serviceName,\n [ATTR_SERVICE_VERSION]: this.serviceVersion,\n 'deployment.environment': this.environment,\n\n // Add trace.id attribute for easy filtering\n 'trace.id': this.sessionTraceId || 'auto-generated',\n\n // Device info\n 'device.type': deviceInfo.type,\n 'device.vendor': deviceInfo.vendor,\n 'device.model': deviceInfo.model,\n\n // Browser info\n 'browser.name': browserInfo.name,\n 'browser.version': browserInfo.version,\n 'browser.major': browserInfo.major,\n\n // OS info\n 'os.name': osInfo.name,\n 'os.version': osInfo.version,\n\n // User agent\n 'user_agent': navigator.userAgent,\n\n ...(this.customerId && { 'customer.id': this.customerId }),\n ...(this.tenantId && { 'tenant.id': this.tenantId }),\n },\n }, currentContext);\n\n // Async add geo location (non-blocking)\n this.getGeoLocation().then(geo => {\n if (geo.country) span.setAttribute('geo.country', geo.country);\n if (geo.region) span.setAttribute('geo.region', geo.region);\n if (geo.city) span.setAttribute('geo.city', geo.city);\n }).catch(err => console.warn('Failed to add geo attributes:', err));\n\n if (this.debug) {\n console.log(`[TracingService] Started span: ${name}`, {\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n sessionTraceId: this.sessionTraceId,\n attributes,\n });\n }\n\n return span;\n } catch (error) {\n console.error('[TracingService] Failed to start span:', error);\n return trace.getTracer('noop').startSpan('noop');\n }\n }\n\n endSpan(span: Span): void {\n if (!span) {\n console.warn('[TracingService] endSpan called with null/undefined span');\n return;\n }\n\n try {\n span.end();\n } catch (error) {\n console.error('[TracingService] ❌ Failed to end span:', error);\n }\n }\n\n addSpanEvent(span: Span, name: string, attributes?: Record<string, any>): void {\n if (!span) return;\n\n try {\n span.addEvent(name, attributes);\n\n if (this.debug) {\n console.log(`[TracingService] Added event to span: ${name}`, attributes);\n }\n } catch (error) {\n console.error('[TracingService] Failed to add span event:', error);\n }\n }\n\n recordException(span: Span, error: Error): void {\n if (!span) return;\n\n try {\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (err) {\n console.error('[TracingService] Failed to record exception:', err);\n }\n }\n\n setSpanAttribute(span: Span, key: string, value: any): void {\n if (!span) return;\n\n try {\n span.setAttribute(key, value);\n\n if (this.debug) {\n console.log(`[TracingService] Set attribute: ${key} = ${value}`);\n }\n } catch (error) {\n console.error('[TracingService] Failed to set span attribute:', error);\n }\n }\n\n async trace<T>(name: string, fn: () => T | Promise<T>, attributes?: Record<string, any>): Promise<T> {\n const span = this.startSpan(name, attributes);\n\n try {\n // Run the function within the span context\n const result = await context.with(trace.setSpan(context.active(), span), async () => {\n return await fn();\n });\n\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n this.recordException(span, error as Error);\n throw error;\n } finally {\n this.endSpan(span);\n }\n }\n\n async traceAsync<T>(name: string, fn: () => Promise<T>, attributes?: Record<string, any>): Promise<T> {\n return this.trace(name, fn, attributes);\n }\n\n /**\n * Flush all pending spans to the collector\n * Call this when capture/process is complete to send all traces\n */\n async flush(): Promise<void> {\n try {\n if (!this.spanProcessor) {\n console.warn('[TracingService] No span processor available to flush');\n return;\n }\n\n await this.spanProcessor.forceFlush();\n } catch (error) {\n console.error('[TracingService] ❌ Failed to flush spans:', error);\n throw error;\n }\n }\n\n async cleanup(): Promise<void> {\n try {\n if (this.spanProcessor) {\n await this.spanProcessor.forceFlush();\n await this.spanProcessor.shutdown();\n }\n\n if (this.provider) {\n await this.provider.shutdown();\n }\n } catch (error) {\n console.error('[TracingService] Failed to cleanup:', error);\n }\n }\n\n /**\n * Get the current trace ID (useful for logging correlation)\n */\n getCurrentTraceId(): string | undefined {\n try {\n const span = trace.getSpan(context.active());\n return span?.spanContext().traceId;\n } catch {\n return undefined;\n }\n }\n\n /**\n * Get the current span ID\n */\n getCurrentSpanId(): string | undefined {\n try {\n const span = trace.getSpan(context.active());\n return span?.spanContext().spanId;\n } catch {\n return undefined;\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ITracingService.js","sourceRoot":"","sources":["../../../src/services/interfaces/ITracingService.ts"],"names":[],"mappings":"","sourcesContent":["import { Span } from '@opentelemetry/api';\n\nexport interface ITracingService {\n /**\n * Initializes the tracing service with the collector endpoint\n */\n initialize(): void;\n\n /**\n * Starts a new span with the given name\n * @param name - Name of the span\n * @param attributes - Optional attributes to add to the span\n * @returns The created span\n */\n startSpan(name: string, attributes?: Record<string, any>): Span;\n\n /**\n * Ends a span\n * @param span - The span to end\n */\n endSpan(span: Span): void;\n\n /**\n * Adds an event to a span\n * @param span - The span to add the event to\n * @param name - Name of the event\n * @param attributes - Optional attributes for the event\n */\n addSpanEvent(span: Span, name: string, attributes?: Record<string, any>): void;\n\n /**\n * Records an exception in a span\n * @param span - The span to record the exception in\n * @param error - The error to record\n */\n recordException(span: Span, error: Error): void;\n\n /**\n * Sets an attribute on a span\n * @param span - The span to set the attribute on\n * @param key - Attribute key\n * @param value - Attribute value\n */\n setSpanAttribute(span: Span, key: string, value: any): void;\n\n /**\n * Wraps a function with automatic span creation\n * @param name - Name of the span\n * @param fn - Function to wrap\n * @param attributes - Optional attributes\n */\n trace<T>(name: string, fn: () => T | Promise<T>, attributes?: Record<string, any>): Promise<T>;\n\n /**\n * Cleans up resources\n */\n cleanup(): void;\n\n /**\n * Set the session trace ID from external source (license or component prop)\n * @param traceId - The trace ID to use for all spans (32 hex characters)\n */\n setSessionTraceId(traceId: string | null): void;\n\n /**\n * Get the current session trace ID\n */\n getSessionTraceId(): string | null;\n}\n"]}
1
+ {"version":3,"file":"ITracingService.js","sourceRoot":"","sources":["../../../src/services/interfaces/ITracingService.ts"],"names":[],"mappings":"","sourcesContent":["import { Span } from '@opentelemetry/api';\n\nexport interface ITracingService {\n /**\n * Initializes the tracing service with the collector endpoint\n */\n initialize(): void;\n\n /**\n * Starts a new span with the given name\n * @param name - Name of the span\n * @param attributes - Optional attributes to add to the span\n * @returns The created span\n */\n startSpan(name: string, attributes?: Record<string, any>): Span;\n\n /**\n * Ends a span\n * @param span - The span to end\n */\n endSpan(span: Span): void;\n\n /**\n * Adds an event to a span\n * @param span - The span to add the event to\n * @param name - Name of the event\n * @param attributes - Optional attributes for the event\n */\n addSpanEvent(span: Span, name: string, attributes?: Record<string, any>): void;\n\n /**\n * Records an exception in a span\n * @param span - The span to record the exception in\n * @param error - The error to record\n */\n recordException(span: Span, error: Error): void;\n\n /**\n * Sets an attribute on a span\n * @param span - The span to set the attribute on\n * @param key - Attribute key\n * @param value - Attribute value\n */\n setSpanAttribute(span: Span, key: string, value: any): void;\n\n /**\n * Wraps a function with automatic span creation\n * @param name - Name of the span\n * @param fn - Function to wrap\n * @param attributes - Optional attributes\n */\n trace<T>(name: string, fn: () => T | Promise<T>, attributes?: Record<string, any>): Promise<T>;\n\n /**\n * Flushes all pending spans to the collector\n * Call this when capture/process is complete\n */\n flush(): Promise<void>;\n\n /**\n * Cleans up resources\n */\n cleanup(): void;\n\n /**\n * Set the session trace ID from external source (license or component prop)\n * @param traceId - The trace ID to use for all spans (32 hex characters)\n */\n setSessionTraceId(traceId: string | null): void;\n\n /**\n * Get the current session trace ID\n */\n getSessionTraceId(): string | null;\n}\n"]}