@pingops/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,259 @@
1
+ /**
2
+ * PingOps SDK singleton for manual instrumentation
3
+ *
4
+ * Provides initializePingops and shutdownPingops functions.
5
+ * wrapHttp is available from @pingops/core and will auto-initialize
6
+ * from environment variables if needed.
7
+ */
8
+ import { NodeSDK } from "@opentelemetry/sdk-node";
9
+ import { resourceFromAttributes } from "@opentelemetry/resources";
10
+ import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
11
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
12
+ import { setPingopsTracerProvider, shutdownTracerProvider, PingopsSpanProcessor, } from "@pingops/otel";
13
+ import { createLogger } from "@pingops/core";
14
+ import { setSdkInitialized, isGlobalInstrumentationEnabled, } from "./init-state";
15
+ import { wrapHttp as coreWrapHttp, } from "@pingops/core";
16
+ import { getPingopsTracerProvider } from "@pingops/otel";
17
+ import { getInstrumentations } from "@pingops/otel";
18
+ const initLogger = createLogger("[PingOps Initialize]");
19
+ const logger = createLogger("[PingOps Pingops]");
20
+ let sdkInstance = null;
21
+ let isSdkInitializedFlag = false;
22
+ /**
23
+ * Global state to track initialization
24
+ */
25
+ let isInitialized = false;
26
+ let initializationPromise = null;
27
+ /**
28
+ * Initializes PingOps SDK
29
+ *
30
+ * This function:
31
+ * 1. Creates an OpenTelemetry NodeSDK instance
32
+ * 2. Configures Resource with service.name
33
+ * 3. Registers PingopsSpanProcessor
34
+ * 4. Enables HTTP/fetch/GenAI instrumentation
35
+ * 5. Starts the SDK
36
+ *
37
+ * @param config - Configuration for the SDK
38
+ * @param explicit - Whether this is an explicit call (default: true).
39
+ * Set to false when called internally by wrapHttp auto-initialization.
40
+ */
41
+ export function initializePingops(config, explicit = true) {
42
+ if (isSdkInitializedFlag) {
43
+ if (config.debug) {
44
+ initLogger.warn("[PingOps] SDK already initialized, skipping");
45
+ }
46
+ return;
47
+ }
48
+ // Create resource with service name
49
+ const resource = resourceFromAttributes({
50
+ [ATTR_SERVICE_NAME]: config.serviceName,
51
+ });
52
+ const processor = new PingopsSpanProcessor(config);
53
+ const instrumentations = getInstrumentations(isGlobalInstrumentationEnabled);
54
+ // Node.js SDK
55
+ const nodeSdk = new NodeSDK({
56
+ resource,
57
+ spanProcessors: [processor],
58
+ instrumentations,
59
+ });
60
+ nodeSdk.start();
61
+ sdkInstance = nodeSdk;
62
+ // Mark SDK as initialized
63
+ isSdkInitializedFlag = true;
64
+ // Only enable global instrumentation if this was an explicit call
65
+ // If called via wrapHttp auto-initialization, global instrumentation stays disabled
66
+ setSdkInitialized(explicit);
67
+ // Initialize isolated TracerProvider for manual spans AFTER NodeSDK starts
68
+ // This ensures manual spans created via startSpan are processed by the same processor
69
+ // We register it after NodeSDK so it takes precedence as the global provider
70
+ try {
71
+ // In version 2.2.0, span processors are passed in the constructor
72
+ const isolatedProvider = new NodeTracerProvider({
73
+ resource,
74
+ spanProcessors: [processor],
75
+ });
76
+ // Register the provider globally
77
+ isolatedProvider.register();
78
+ // Set it in global state
79
+ setPingopsTracerProvider(isolatedProvider);
80
+ }
81
+ catch (error) {
82
+ if (config.debug) {
83
+ initLogger.error("[PingOps] Failed to create isolated TracerProvider:", error instanceof Error ? error.message : String(error));
84
+ }
85
+ // Continue without isolated provider - manual spans will use global provider
86
+ }
87
+ if (config.debug) {
88
+ initLogger.info("[PingOps] SDK initialized");
89
+ }
90
+ }
91
+ /**
92
+ * Shuts down the SDK and flushes remaining spans
93
+ */
94
+ export async function shutdownPingops() {
95
+ // Shutdown isolated TracerProvider first
96
+ await shutdownTracerProvider();
97
+ if (!sdkInstance) {
98
+ return;
99
+ }
100
+ await sdkInstance.shutdown();
101
+ sdkInstance = null;
102
+ isSdkInitializedFlag = false;
103
+ setSdkInitialized(false);
104
+ }
105
+ /**
106
+ * Checks if the SDK is already initialized by checking if a NodeTracerProvider is available
107
+ */
108
+ function isSdkInitialized() {
109
+ try {
110
+ const provider = getPingopsTracerProvider();
111
+ // If we have a NodeTracerProvider (not the default NoOpTracerProvider), SDK is initialized
112
+ const initialized = provider instanceof NodeTracerProvider;
113
+ logger.debug("Checked SDK initialization status", {
114
+ initialized,
115
+ providerType: provider.constructor.name,
116
+ });
117
+ return initialized;
118
+ }
119
+ catch (error) {
120
+ logger.debug("Error checking SDK initialization status", {
121
+ error: error instanceof Error ? error.message : String(error),
122
+ });
123
+ return false;
124
+ }
125
+ }
126
+ /**
127
+ * Auto-initializes the SDK from environment variables if not already initialized
128
+ */
129
+ async function ensureInitialized() {
130
+ // Check if SDK is already initialized (e.g., by calling initializePingops directly)
131
+ if (isSdkInitialized()) {
132
+ logger.debug("SDK already initialized, skipping auto-initialization");
133
+ isInitialized = true;
134
+ return;
135
+ }
136
+ if (isInitialized) {
137
+ logger.debug("SDK initialization flag already set, skipping");
138
+ return;
139
+ }
140
+ // If initialization is in progress, wait for it
141
+ if (initializationPromise) {
142
+ logger.debug("SDK initialization already in progress, waiting...");
143
+ return initializationPromise;
144
+ }
145
+ // Start initialization
146
+ logger.info("Starting SDK auto-initialization from environment variables");
147
+ initializationPromise = Promise.resolve().then(() => {
148
+ const apiKey = process.env.PINGOPS_API_KEY;
149
+ const baseUrl = process.env.PINGOPS_BASE_URL;
150
+ const serviceName = process.env.PINGOPS_SERVICE_NAME;
151
+ const debug = process.env.PINGOPS_DEBUG === "true";
152
+ logger.debug("Reading environment variables", {
153
+ hasApiKey: !!apiKey,
154
+ hasBaseUrl: !!baseUrl,
155
+ hasServiceName: !!serviceName,
156
+ debug,
157
+ });
158
+ if (!apiKey || !baseUrl || !serviceName) {
159
+ const missing = [
160
+ !apiKey && "PINGOPS_API_KEY",
161
+ !baseUrl && "PINGOPS_BASE_URL",
162
+ !serviceName && "PINGOPS_SERVICE_NAME",
163
+ ].filter(Boolean);
164
+ logger.error("Missing required environment variables for auto-initialization", {
165
+ missing,
166
+ });
167
+ throw new Error(`PingOps SDK auto-initialization requires PINGOPS_API_KEY, PINGOPS_BASE_URL, and PINGOPS_SERVICE_NAME environment variables. Missing: ${missing.join(", ")}`);
168
+ }
169
+ const config = {
170
+ apiKey,
171
+ baseUrl,
172
+ serviceName,
173
+ debug,
174
+ };
175
+ logger.info("Initializing SDK with config", {
176
+ baseUrl,
177
+ serviceName,
178
+ debug,
179
+ });
180
+ // Call initializePingops with explicit=false since this is auto-initialization
181
+ initializePingops(config, false);
182
+ isInitialized = true;
183
+ logger.info("SDK auto-initialization completed successfully");
184
+ });
185
+ try {
186
+ await initializationPromise;
187
+ }
188
+ catch (error) {
189
+ logger.error("SDK auto-initialization failed", {
190
+ error: error instanceof Error ? error.message : String(error),
191
+ });
192
+ throw error;
193
+ }
194
+ finally {
195
+ initializationPromise = null;
196
+ }
197
+ }
198
+ /**
199
+ * Wraps a function to set attributes on HTTP spans created within the wrapped block.
200
+ *
201
+ * This function sets attributes (userId, sessionId, tags, metadata) in the OpenTelemetry
202
+ * context, which are automatically propagated to all spans created within the wrapped function.
203
+ *
204
+ * Instrumentation behavior:
205
+ * - If `initializePingops` was called: All HTTP requests are instrumented by default.
206
+ * `wrapHttp` only adds attributes to spans created within the wrapped block.
207
+ * - If `initializePingops` was NOT called: Only HTTP requests within `wrapHttp` blocks
208
+ * are instrumented. Requests outside `wrapHttp` are not instrumented.
209
+ *
210
+ * @param options - Options including attributes to propagate to spans
211
+ * @param fn - Function to execute within the attribute context
212
+ * @returns The result of the function
213
+ *
214
+ * @example
215
+ * ```typescript
216
+ * import { wrapHttp } from '@pingops/sdk';
217
+ *
218
+ * // Scenario 1: initializePingops was called
219
+ * initializePingops({ ... });
220
+ *
221
+ * // All HTTP requests are instrumented, but this block adds attributes
222
+ * const result = await wrapHttp({
223
+ * attributes: {
224
+ * userId: 'user-123',
225
+ * sessionId: 'session-456',
226
+ * tags: ['production', 'api'],
227
+ * metadata: { environment: 'prod', version: '1.0.0' }
228
+ * }
229
+ * }, async () => {
230
+ * // This HTTP request will be instrumented AND have the attributes set above
231
+ * const response = await fetch('https://api.example.com/users/123');
232
+ * return response.json();
233
+ * });
234
+ *
235
+ * // HTTP requests outside wrapHttp are still instrumented, just without the attributes
236
+ * const otherResponse = await fetch('https://api.example.com/other');
237
+ *
238
+ * // Scenario 2: initializePingops was NOT called
239
+ * // Only requests within wrapHttp are instrumented
240
+ * await wrapHttp({
241
+ * attributes: { userId: 'user-123' }
242
+ * }, async () => {
243
+ * // This request IS instrumented
244
+ * return fetch('https://api.example.com/data');
245
+ * });
246
+ *
247
+ * // This request is NOT instrumented (outside wrapHttp)
248
+ * await fetch('https://api.example.com/other');
249
+ * ```
250
+ */
251
+ export function wrapHttp(options, fn) {
252
+ return coreWrapHttp({
253
+ ...options,
254
+ checkInitialized: isSdkInitialized,
255
+ isGlobalInstrumentationEnabled: isGlobalInstrumentationEnabled,
256
+ ensureInitialized: ensureInitialized,
257
+ }, fn);
258
+ }
259
+ //# sourceMappingURL=pingops.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pingops.js","sourceRoot":"","sources":["../src/pingops.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAClD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AACxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAEnE,OAAO,EACL,wBAAwB,EACxB,sBAAsB,EACtB,oBAAoB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EACL,iBAAiB,EACjB,8BAA8B,GAC/B,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,QAAQ,IAAI,YAAY,GAEzB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EAA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oDG;AACH,MAAM,UAAU,QAAQ,CACtB,OAA4C,EAC5C,EAAwB;IAExB,OAAO,YAAY,CACjB;QACE,GAAG,OAAO;QACV,gBAAgB,EAAE,gBAAgB;QAClC,8BAA8B,EAAE,8BAA8B;QAC9D,iBAAiB,EAAE,iBAAiB;KACrC,EACD,EAAE,CACH,CAAC;AACJ,CAAC"}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Span wrapper for PingOps SDK
3
+ *
4
+ * Provides PingopsSpan class similar to LangfuseSpan for wrapping OpenTelemetry spans
5
+ * with PingOps-specific functionality.
6
+ */
7
+ import { TimeInput, Span, SpanContext } from '@opentelemetry/api';
8
+ import type { Attributes } from '@opentelemetry/api';
9
+ import type { SpanAttributes } from './tracer-provider';
10
+ /**
11
+ * Base class for PingOps span wrappers
12
+ *
13
+ * Provides common functionality for wrapping OpenTelemetry spans with PingOps-specific features.
14
+ */
15
+ declare abstract class PingopsBaseSpan {
16
+ /** The underlying OpenTelemetry span */
17
+ readonly otelSpan: Span;
18
+ /** The span ID from the OpenTelemetry span context */
19
+ id: string;
20
+ /** The trace ID from the OpenTelemetry span context */
21
+ traceId: string;
22
+ constructor(otelSpan: Span);
23
+ /**
24
+ * Ends the span, marking it as complete.
25
+ *
26
+ * @param endTime - Optional end time, defaults to current time
27
+ */
28
+ end(endTime?: TimeInput): void;
29
+ /**
30
+ * Updates the span with new attributes.
31
+ *
32
+ * @param attributes - Span attributes to set
33
+ * @returns This span for method chaining
34
+ */
35
+ update(attributes: SpanAttributes): PingopsSpan;
36
+ }
37
+ /**
38
+ * PingOps span wrapper for tracking operations
39
+ *
40
+ * Provides a convenient wrapper around OpenTelemetry spans with PingOps-specific
41
+ * attribute handling and lifecycle management.
42
+ */
43
+ export declare class PingopsSpan extends PingopsBaseSpan {
44
+ constructor(otelSpan: Span);
45
+ }
46
+ /**
47
+ * Creates an OpenTelemetry span with the PingOps tracer.
48
+ *
49
+ * @param params - Parameters for span creation
50
+ * @returns The created OpenTelemetry span
51
+ * @internal
52
+ */
53
+ export declare function createOtelSpan(params: {
54
+ name: string;
55
+ startTime?: TimeInput;
56
+ parentSpanContext?: SpanContext;
57
+ attributes?: Attributes;
58
+ }): Span;
59
+ export {};
60
+ //# sourceMappingURL=span-wrapper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"span-wrapper.d.ts","sourceRoot":"","sources":["../src/span-wrapper.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAkB,SAAS,EAAE,IAAI,EAAE,WAAW,EAAW,MAAM,oBAAoB,CAAC;AAC3F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD;;;;GAIG;AACH,uBAAe,eAAe;IAC5B,wCAAwC;IACxC,SAAgB,QAAQ,EAAE,IAAI,CAAC;IAC/B,sDAAsD;IAC/C,EAAE,EAAE,MAAM,CAAC;IAClB,uDAAuD;IAChD,OAAO,EAAE,MAAM,CAAC;gBAEX,QAAQ,EAAE,IAAI;IAO1B;;;;OAIG;IACI,GAAG,CAAC,OAAO,CAAC,EAAE,SAAS,GAAG,IAAI;IAIrC;;;;;OAKG;IACI,MAAM,CAAC,UAAU,EAAE,cAAc,GAAG,WAAW;CA8CvD;AAED;;;;;GAKG;AACH,qBAAa,WAAY,SAAQ,eAAe;gBAClC,QAAQ,EAAE,IAAI;CAG3B;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE;IACrC,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,iBAAiB,CAAC,EAAE,WAAW,CAAC;IAChC,UAAU,CAAC,EAAE,UAAU,CAAC;CACzB,GAAG,IAAI,CAYP"}
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Span wrapper for PingOps SDK
3
+ *
4
+ * Provides PingopsSpan class similar to LangfuseSpan for wrapping OpenTelemetry spans
5
+ * with PingOps-specific functionality.
6
+ */
7
+ import { trace, context } from '@opentelemetry/api';
8
+ import { getPingopsTracerProvider } from './tracer-provider';
9
+ /**
10
+ * Base class for PingOps span wrappers
11
+ *
12
+ * Provides common functionality for wrapping OpenTelemetry spans with PingOps-specific features.
13
+ */
14
+ class PingopsBaseSpan {
15
+ /** The underlying OpenTelemetry span */
16
+ otelSpan;
17
+ /** The span ID from the OpenTelemetry span context */
18
+ id;
19
+ /** The trace ID from the OpenTelemetry span context */
20
+ traceId;
21
+ constructor(otelSpan) {
22
+ this.otelSpan = otelSpan;
23
+ const spanContext = otelSpan.spanContext();
24
+ this.id = spanContext.spanId;
25
+ this.traceId = spanContext.traceId;
26
+ }
27
+ /**
28
+ * Ends the span, marking it as complete.
29
+ *
30
+ * @param endTime - Optional end time, defaults to current time
31
+ */
32
+ end(endTime) {
33
+ this.otelSpan.end(endTime);
34
+ }
35
+ /**
36
+ * Updates the span with new attributes.
37
+ *
38
+ * @param attributes - Span attributes to set
39
+ * @returns This span for method chaining
40
+ */
41
+ update(attributes) {
42
+ const otelAttributes = {};
43
+ // Handle nested attributes object
44
+ if (attributes.attributes) {
45
+ Object.assign(otelAttributes, attributes.attributes);
46
+ }
47
+ // Handle input/output
48
+ if (attributes.input !== undefined) {
49
+ otelAttributes['span.input'] =
50
+ typeof attributes.input === 'string'
51
+ ? attributes.input
52
+ : JSON.stringify(attributes.input);
53
+ }
54
+ if (attributes.output !== undefined) {
55
+ otelAttributes['span.output'] =
56
+ typeof attributes.output === 'string'
57
+ ? attributes.output
58
+ : JSON.stringify(attributes.output);
59
+ }
60
+ // Handle metadata
61
+ if (attributes.metadata !== undefined) {
62
+ for (const [key, value] of Object.entries(attributes.metadata)) {
63
+ otelAttributes[`span.metadata.${key}`] =
64
+ typeof value === 'string' ? value : JSON.stringify(value);
65
+ }
66
+ }
67
+ // Add any other custom attributes (excluding the special keys)
68
+ for (const [key, value] of Object.entries(attributes)) {
69
+ if (key !== 'attributes' &&
70
+ key !== 'input' &&
71
+ key !== 'output' &&
72
+ key !== 'metadata') {
73
+ otelAttributes[key] = value;
74
+ }
75
+ }
76
+ this.otelSpan.setAttributes(otelAttributes);
77
+ return this;
78
+ }
79
+ }
80
+ /**
81
+ * PingOps span wrapper for tracking operations
82
+ *
83
+ * Provides a convenient wrapper around OpenTelemetry spans with PingOps-specific
84
+ * attribute handling and lifecycle management.
85
+ */
86
+ export class PingopsSpan extends PingopsBaseSpan {
87
+ constructor(otelSpan) {
88
+ super(otelSpan);
89
+ }
90
+ }
91
+ /**
92
+ * Creates an OpenTelemetry span with the PingOps tracer.
93
+ *
94
+ * @param params - Parameters for span creation
95
+ * @returns The created OpenTelemetry span
96
+ * @internal
97
+ */
98
+ export function createOtelSpan(params) {
99
+ const provider = getPingopsTracerProvider();
100
+ const tracer = provider.getTracer('@pingops/sdk', '0.1.0');
101
+ return tracer.startSpan(params.name, {
102
+ startTime: params.startTime,
103
+ attributes: params.attributes,
104
+ }, createParentContext(params.parentSpanContext));
105
+ }
106
+ /**
107
+ * Creates a parent context from a span context.
108
+ *
109
+ * @param parentSpanContext - The span context to use as parent
110
+ * @returns The created context or undefined if no parent provided
111
+ * @internal
112
+ */
113
+ function createParentContext(parentSpanContext) {
114
+ if (!parentSpanContext)
115
+ return undefined;
116
+ return trace.setSpanContext(context.active(), parentSpanContext);
117
+ }
118
+ //# sourceMappingURL=span-wrapper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"span-wrapper.js","sourceRoot":"","sources":["../src/span-wrapper.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,KAAK,EAAE,OAAO,EAAyC,MAAM,oBAAoB,CAAC;AAE3F,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAG7D;;;;GAIG;AACH,MAAe,eAAe;IAC5B,wCAAwC;IACxB,QAAQ,CAAO;IAC/B,sDAAsD;IAC/C,EAAE,CAAS;IAClB,uDAAuD;IAChD,OAAO,CAA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AAiB;QAAE,OAAO,SAAS,CAAC;IAEzC,OAAO,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,iBAAiB,CAAC,CAAC;AACnE,CAAC"}
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Tracer Provider with global state and isolated TracerProvider architecture
3
+ *
4
+ * This module provides an isolated TracerProvider that shares the same
5
+ * span processors (like PingopsSpanProcessor) with the main OpenTelemetry SDK.
6
+ * This ensures manual spans created via startSpan are properly processed.
7
+ *
8
+ * Architecture follows Langfuse's pattern with global state management.
9
+ */
10
+ import { TimeInput } from '@opentelemetry/api';
11
+ import type { Attributes, Span, TracerProvider } from '@opentelemetry/api';
12
+ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
13
+ import type { SpanProcessor } from '@opentelemetry/sdk-trace-base';
14
+ /**
15
+ * Options for starting a span
16
+ */
17
+ export interface StartSpanOptions {
18
+ /** Span attributes */
19
+ attributes?: Attributes;
20
+ /** Custom start time for the span */
21
+ startTime?: TimeInput;
22
+ }
23
+ /**
24
+ * Attributes for updating trace-level information
25
+ */
26
+ export interface TraceAttributes {
27
+ /** User ID associated with the trace */
28
+ userId?: string;
29
+ /** Session ID for grouping related traces */
30
+ sessionId?: string;
31
+ /** Tags for categorizing traces */
32
+ tags?: string[];
33
+ /** Additional metadata */
34
+ metadata?: Record<string, unknown>;
35
+ /** Custom attributes */
36
+ [key: string]: unknown;
37
+ }
38
+ /**
39
+ * Attributes for updating span-level information
40
+ */
41
+ export interface SpanAttributes {
42
+ /** Input data for the operation */
43
+ input?: unknown;
44
+ /** Output data from the operation */
45
+ output?: unknown;
46
+ /** Additional metadata */
47
+ metadata?: Record<string, unknown>;
48
+ /** Custom attributes */
49
+ attributes?: Attributes;
50
+ /** Custom attributes */
51
+ [key: string]: unknown;
52
+ }
53
+ /**
54
+ * Sets an isolated TracerProvider for PingOps tracing operations.
55
+ *
56
+ * This allows PingOps to use its own TracerProvider instance, separate from
57
+ * the global OpenTelemetry TracerProvider. This is useful for avoiding conflicts
58
+ * with other OpenTelemetry instrumentation in the application.
59
+ *
60
+ * @param provider - The TracerProvider instance to use, or null to clear the isolated provider
61
+ * @public
62
+ */
63
+ export declare function setPingopsTracerProvider(provider: TracerProvider | null): void;
64
+ /**
65
+ * Gets the TracerProvider for PingOps tracing operations.
66
+ *
67
+ * Returns the isolated TracerProvider if one has been set via setPingopsTracerProvider(),
68
+ * otherwise falls back to the global OpenTelemetry TracerProvider.
69
+ *
70
+ * @returns The TracerProvider instance to use for PingOps tracing
71
+ * @public
72
+ */
73
+ export declare function getPingopsTracerProvider(): TracerProvider;
74
+ /**
75
+ * Initializes the isolated TracerProvider with the given span processors
76
+ *
77
+ * This creates a separate TracerProvider that shares the same span processors
78
+ * (like PingopsSpanProcessor) with the main SDK. This ensures manual spans
79
+ * are processed correctly.
80
+ *
81
+ * @param spanProcessors - Array of span processors to use (e.g., PingopsSpanProcessor)
82
+ * @param serviceName - Service name for resource attributes
83
+ * @deprecated Use setPingopsTracerProvider instead
84
+ */
85
+ export declare function initializeTracerProvider(spanProcessors: SpanProcessor[], serviceName: string): void;
86
+ /**
87
+ * Gets the isolated TracerProvider instance
88
+ *
89
+ * @returns The TracerProvider instance, or null if not initialized
90
+ * @deprecated Use getPingopsTracerProvider instead
91
+ */
92
+ export declare function getTracerProvider(): NodeTracerProvider | null;
93
+ /**
94
+ * Shuts down the TracerProvider and flushes remaining spans
95
+ */
96
+ export declare function shutdownTracerProvider(): Promise<void>;
97
+ /**
98
+ * Starts a span, executes the function, and automatically ends the span
99
+ *
100
+ * This function uses the isolated TracerProvider to ensure spans are
101
+ * properly processed by PingopsSpanProcessor and other registered processors.
102
+ *
103
+ * The span is automatically set as active in the OpenTelemetry context, allowing
104
+ * child spans and updates to work correctly.
105
+ *
106
+ * @param name - Span name
107
+ * @param options - Span options including attributes
108
+ * @param fn - Function to execute within the span context (can be sync or async)
109
+ * @returns The result of the function
110
+ *
111
+ * @example
112
+ * ```typescript
113
+ * import { startSpan } from '@pingops/sdk';
114
+ *
115
+ * const result = await startSpan('your-span-name', {
116
+ * attributes: {
117
+ * customer_id: 'cust_123',
118
+ * correlation_id: 'req_456',
119
+ * },
120
+ * }, async (span) => {
121
+ * const result = await fetch('https://api.example.com');
122
+ * return 'done';
123
+ * });
124
+ * ```
125
+ */
126
+ export declare function startSpan<T>(name: string, options: StartSpanOptions, fn: (span: Span) => T | Promise<T>): T | Promise<T>;
127
+ /**
128
+ * Updates the currently active trace with new attributes.
129
+ *
130
+ * This function finds the currently active OpenTelemetry span and updates
131
+ * it with trace-level attributes. If no active span is found, a warning is logged.
132
+ *
133
+ * @param attributes - Trace attributes to set
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * import { updateActiveTrace } from '@pingops/sdk';
138
+ *
139
+ * // Inside an active span context
140
+ * updateActiveTrace({
141
+ * userId: 'user-123',
142
+ * sessionId: 'session-456',
143
+ * tags: ['production', 'critical'],
144
+ * });
145
+ * ```
146
+ */
147
+ export declare function updateActiveTrace(attributes: TraceAttributes): void;
148
+ /**
149
+ * Updates the currently active span with new attributes.
150
+ *
151
+ * This function finds the currently active OpenTelemetry span in the execution context
152
+ * and updates it with span-level attributes. If no active span exists, the update is skipped.
153
+ *
154
+ * @param attributes - Span attributes to update
155
+ *
156
+ * @example
157
+ * ```typescript
158
+ * import { startSpan, updateActiveSpan } from '@pingops/sdk';
159
+ *
160
+ * await startSpan('data-processing', {
161
+ * attributes: { step: 'initialization' },
162
+ * }, async (span) => {
163
+ * // Process data...
164
+ * const result = await processData(inputData);
165
+ *
166
+ * // Update with results
167
+ * updateActiveSpan({
168
+ * attributes: { processed_records: result.count },
169
+ * output: { success: true },
170
+ * });
171
+ * });
172
+ * ```
173
+ */
174
+ export declare function updateActiveSpan(attributes: SpanAttributes): void;
175
+ //# sourceMappingURL=tracer-provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracer-provider.d.ts","sourceRoot":"","sources":["../src/tracer-provider.ts"],"names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