@pingops/sdk 0.1.2 → 0.2.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.
package/dist/index.cjs CHANGED
@@ -1,248 +1,7 @@
1
- let _opentelemetry_sdk_node = require("@opentelemetry/sdk-node");
2
- let _opentelemetry_resources = require("@opentelemetry/resources");
3
- let _opentelemetry_semantic_conventions = require("@opentelemetry/semantic-conventions");
4
- let _opentelemetry_sdk_trace_node = require("@opentelemetry/sdk-trace-node");
5
- let _pingops_otel = require("@pingops/otel");
6
- let _pingops_core = require("@pingops/core");
1
+ const require_pingops = require('./pingops-Bbm0Xd0z.cjs');
7
2
 
8
- //#region src/init-state.ts
9
- /**
10
- * Shared state for tracking SDK initialization
11
- * This module exists to avoid circular dependencies between pingops.ts and instrumentation.ts
12
- */
13
- let isSdkInitializedFlag$1 = false;
14
- /**
15
- * Sets the SDK initialization flag.
16
- * Called by initializePingops when the SDK is initialized.
17
- */
18
- function setSdkInitialized(initialized) {
19
- isSdkInitializedFlag$1 = initialized;
20
- }
21
- /**
22
- * Checks if global instrumentation is enabled.
23
- * This is used to determine instrumentation behavior:
24
- * - If true: all HTTP requests are instrumented
25
- * - If false: only requests within wrapHttp blocks are instrumented
26
- */
27
- function isGlobalInstrumentationEnabled() {
28
- return isSdkInitializedFlag$1;
29
- }
30
-
31
- //#endregion
32
- //#region src/pingops.ts
33
- /**
34
- * PingOps SDK singleton for manual instrumentation
35
- *
36
- * Provides initializePingops and shutdownPingops functions.
37
- * wrapHttp is available from @pingops/core and will auto-initialize
38
- * from environment variables if needed.
39
- */
40
- const initLogger = (0, _pingops_core.createLogger)("[PingOps Initialize]");
41
- const logger = (0, _pingops_core.createLogger)("[PingOps Pingops]");
42
- let sdkInstance = null;
43
- let isSdkInitializedFlag = false;
44
- /**
45
- * Global state to track initialization
46
- */
47
- let isInitialized = false;
48
- let initializationPromise = null;
49
- /**
50
- * Initializes PingOps SDK
51
- *
52
- * This function:
53
- * 1. Creates an OpenTelemetry NodeSDK instance
54
- * 2. Configures Resource with service.name
55
- * 3. Registers PingopsSpanProcessor
56
- * 4. Enables HTTP/fetch/GenAI instrumentation
57
- * 5. Starts the SDK
58
- *
59
- * @param config - Configuration for the SDK
60
- * @param explicit - Whether this is an explicit call (default: true).
61
- * Set to false when called internally by wrapHttp auto-initialization.
62
- */
63
- function initializePingops(config, explicit = true) {
64
- if (isSdkInitializedFlag) {
65
- if (config.debug) initLogger.warn("[PingOps] SDK already initialized, skipping");
66
- return;
67
- }
68
- const resource = (0, _opentelemetry_resources.resourceFromAttributes)({ [_opentelemetry_semantic_conventions.ATTR_SERVICE_NAME]: config.serviceName });
69
- const processor = new _pingops_otel.PingopsSpanProcessor(config);
70
- const instrumentations = (0, _pingops_otel.getInstrumentations)(isGlobalInstrumentationEnabled);
71
- const nodeSdk = new _opentelemetry_sdk_node.NodeSDK({
72
- resource,
73
- spanProcessors: [processor],
74
- instrumentations
75
- });
76
- nodeSdk.start();
77
- sdkInstance = nodeSdk;
78
- isSdkInitializedFlag = true;
79
- setSdkInitialized(explicit);
80
- try {
81
- const isolatedProvider = new _opentelemetry_sdk_trace_node.NodeTracerProvider({
82
- resource,
83
- spanProcessors: [processor]
84
- });
85
- isolatedProvider.register();
86
- (0, _pingops_otel.setPingopsTracerProvider)(isolatedProvider);
87
- } catch (error) {
88
- if (config.debug) initLogger.error("[PingOps] Failed to create isolated TracerProvider:", error instanceof Error ? error.message : String(error));
89
- }
90
- if (config.debug) initLogger.info("[PingOps] SDK initialized");
91
- }
92
- /**
93
- * Shuts down the SDK and flushes remaining spans
94
- */
95
- async function shutdownPingops() {
96
- await (0, _pingops_otel.shutdownTracerProvider)();
97
- if (!sdkInstance) return;
98
- await sdkInstance.shutdown();
99
- sdkInstance = null;
100
- isSdkInitializedFlag = false;
101
- setSdkInitialized(false);
102
- }
103
- /**
104
- * Checks if the SDK is already initialized by checking if a NodeTracerProvider is available
105
- */
106
- function isSdkInitialized() {
107
- try {
108
- const provider = (0, _pingops_otel.getPingopsTracerProvider)();
109
- const initialized = provider instanceof _opentelemetry_sdk_trace_node.NodeTracerProvider;
110
- logger.debug("Checked SDK initialization status", {
111
- initialized,
112
- providerType: provider.constructor.name
113
- });
114
- return initialized;
115
- } catch (error) {
116
- logger.debug("Error checking SDK initialization status", { error: error instanceof Error ? error.message : String(error) });
117
- return false;
118
- }
119
- }
120
- /**
121
- * Auto-initializes the SDK from environment variables if not already initialized
122
- */
123
- async function ensureInitialized() {
124
- if (isSdkInitialized()) {
125
- logger.debug("SDK already initialized, skipping auto-initialization");
126
- isInitialized = true;
127
- return;
128
- }
129
- if (isInitialized) {
130
- logger.debug("SDK initialization flag already set, skipping");
131
- return;
132
- }
133
- if (initializationPromise) {
134
- logger.debug("SDK initialization already in progress, waiting...");
135
- return initializationPromise;
136
- }
137
- logger.info("Starting SDK auto-initialization from environment variables");
138
- initializationPromise = Promise.resolve().then(() => {
139
- const apiKey = process.env.PINGOPS_API_KEY;
140
- const baseUrl = process.env.PINGOPS_BASE_URL;
141
- const serviceName = process.env.PINGOPS_SERVICE_NAME;
142
- const debug = process.env.PINGOPS_DEBUG === "true";
143
- logger.debug("Reading environment variables", {
144
- hasApiKey: !!apiKey,
145
- hasBaseUrl: !!baseUrl,
146
- hasServiceName: !!serviceName,
147
- debug
148
- });
149
- if (!apiKey || !baseUrl || !serviceName) {
150
- const missing = [
151
- !apiKey && "PINGOPS_API_KEY",
152
- !baseUrl && "PINGOPS_BASE_URL",
153
- !serviceName && "PINGOPS_SERVICE_NAME"
154
- ].filter(Boolean);
155
- logger.error("Missing required environment variables for auto-initialization", { missing });
156
- throw new Error(`PingOps SDK auto-initialization requires PINGOPS_API_KEY, PINGOPS_BASE_URL, and PINGOPS_SERVICE_NAME environment variables. Missing: ${missing.join(", ")}`);
157
- }
158
- const config = {
159
- apiKey,
160
- baseUrl,
161
- serviceName,
162
- debug
163
- };
164
- logger.info("Initializing SDK with config", {
165
- baseUrl,
166
- serviceName,
167
- debug
168
- });
169
- initializePingops(config, false);
170
- isInitialized = true;
171
- logger.info("SDK auto-initialization completed successfully");
172
- });
173
- try {
174
- await initializationPromise;
175
- } catch (error) {
176
- logger.error("SDK auto-initialization failed", { error: error instanceof Error ? error.message : String(error) });
177
- throw error;
178
- } finally {
179
- initializationPromise = null;
180
- }
181
- }
182
- /**
183
- * Wraps a function to set attributes on HTTP spans created within the wrapped block.
184
- *
185
- * This function sets attributes (userId, sessionId, tags, metadata) in the OpenTelemetry
186
- * context, which are automatically propagated to all spans created within the wrapped function.
187
- *
188
- * Instrumentation behavior:
189
- * - If `initializePingops` was called: All HTTP requests are instrumented by default.
190
- * `wrapHttp` only adds attributes to spans created within the wrapped block.
191
- * - If `initializePingops` was NOT called: Only HTTP requests within `wrapHttp` blocks
192
- * are instrumented. Requests outside `wrapHttp` are not instrumented.
193
- *
194
- * @param options - Options including attributes to propagate to spans
195
- * @param fn - Function to execute within the attribute context
196
- * @returns The result of the function
197
- *
198
- * @example
199
- * ```typescript
200
- * import { wrapHttp } from '@pingops/sdk';
201
- *
202
- * // Scenario 1: initializePingops was called
203
- * initializePingops({ ... });
204
- *
205
- * // All HTTP requests are instrumented, but this block adds attributes
206
- * const result = await wrapHttp({
207
- * attributes: {
208
- * userId: 'user-123',
209
- * sessionId: 'session-456',
210
- * tags: ['production', 'api'],
211
- * metadata: { environment: 'prod', version: '1.0.0' }
212
- * }
213
- * }, async () => {
214
- * // This HTTP request will be instrumented AND have the attributes set above
215
- * const response = await fetch('https://api.example.com/users/123');
216
- * return response.json();
217
- * });
218
- *
219
- * // HTTP requests outside wrapHttp are still instrumented, just without the attributes
220
- * const otherResponse = await fetch('https://api.example.com/other');
221
- *
222
- * // Scenario 2: initializePingops was NOT called
223
- * // Only requests within wrapHttp are instrumented
224
- * await wrapHttp({
225
- * attributes: { userId: 'user-123' }
226
- * }, async () => {
227
- * // This request IS instrumented
228
- * return fetch('https://api.example.com/data');
229
- * });
230
- *
231
- * // This request is NOT instrumented (outside wrapHttp)
232
- * await fetch('https://api.example.com/other');
233
- * ```
234
- */
235
- function wrapHttp(options, fn) {
236
- return (0, _pingops_core.wrapHttp)({
237
- ...options,
238
- checkInitialized: isSdkInitialized,
239
- isGlobalInstrumentationEnabled,
240
- ensureInitialized
241
- }, fn);
242
- }
243
-
244
- //#endregion
245
- exports.initializePingops = initializePingops;
246
- exports.shutdownPingops = shutdownPingops;
247
- exports.wrapHttp = wrapHttp;
248
- //# sourceMappingURL=index.cjs.map
3
+ exports.getActiveSpanId = require_pingops.getActiveSpanId;
4
+ exports.getActiveTraceId = require_pingops.getActiveTraceId;
5
+ exports.initializePingops = require_pingops.initializePingops;
6
+ exports.shutdownPingops = require_pingops.shutdownPingops;
7
+ exports.startTrace = require_pingops.startTrace;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { PingopsProcessorConfig } from "@pingops/otel";
2
- import { WrapHttpAttributes, WrapHttpAttributes as WrapHttpAttributes$1 } from "@pingops/core";
2
+ import { PingopsTraceAttributes, PingopsTraceAttributes as PingopsTraceAttributes$1 } from "@pingops/core";
3
3
 
4
4
  //#region src/pingops.d.ts
5
5
 
@@ -13,71 +13,60 @@ import { WrapHttpAttributes, WrapHttpAttributes as WrapHttpAttributes$1 } from "
13
13
  * 4. Enables HTTP/fetch/GenAI instrumentation
14
14
  * 5. Starts the SDK
15
15
  *
16
- * @param config - Configuration for the SDK
16
+ * @param config - Configuration object, config file path, or config file wrapper
17
17
  * @param explicit - Whether this is an explicit call (default: true).
18
- * Set to false when called internally by wrapHttp auto-initialization.
18
+ * Set to false when called internally by startTrace auto-initialization.
19
19
  */
20
20
  declare function initializePingops(config: PingopsProcessorConfig, explicit?: boolean): void;
21
+ declare function initializePingops(configFilePath: string, explicit?: boolean): void;
22
+ declare function initializePingops(config: {
23
+ configFile: string;
24
+ }, explicit?: boolean): void;
21
25
  /**
22
26
  * Shuts down the SDK and flushes remaining spans
23
27
  */
24
28
  declare function shutdownPingops(): Promise<void>;
25
29
  /**
26
- * Wraps a function to set attributes on HTTP spans created within the wrapped block.
27
- *
28
- * This function sets attributes (userId, sessionId, tags, metadata) in the OpenTelemetry
29
- * context, which are automatically propagated to all spans created within the wrapped function.
30
- *
31
- * Instrumentation behavior:
32
- * - If `initializePingops` was called: All HTTP requests are instrumented by default.
33
- * `wrapHttp` only adds attributes to spans created within the wrapped block.
34
- * - If `initializePingops` was NOT called: Only HTTP requests within `wrapHttp` blocks
35
- * are instrumented. Requests outside `wrapHttp` are not instrumented.
30
+ * Returns the trace ID of the currently active span, if any.
31
+ */
32
+ declare function getActiveTraceId(): string | undefined;
33
+ /**
34
+ * Returns the span ID of the currently active span, if any.
35
+ */
36
+ declare function getActiveSpanId(): string | undefined;
37
+ /**
38
+ * Starts a new trace using the PingOps tracer provider and runs the callback within that trace.
39
+ * Sets attributes (traceId, userId, sessionId, tags, metadata, etc.) in context so they are
40
+ * propagated to spans created within the callback.
36
41
  *
37
- * @param options - Options including attributes to propagate to spans
38
- * @param fn - Function to execute within the attribute context
39
- * @returns The result of the function
42
+ * @param options - Options including optional attributes and optional seed for deterministic traceId
43
+ * @param fn - Function to execute within the trace and attribute context
44
+ * @returns Promise resolving to the result of the function
40
45
  *
41
46
  * @example
42
47
  * ```typescript
43
- * import { wrapHttp } from '@pingops/sdk';
48
+ * import { startTrace, initializePingops } from '@pingops/sdk';
44
49
  *
45
- * // Scenario 1: initializePingops was called
46
50
  * initializePingops({ ... });
47
51
  *
48
- * // All HTTP requests are instrumented, but this block adds attributes
49
- * const result = await wrapHttp({
52
+ * const result = await startTrace({
50
53
  * attributes: {
51
54
  * userId: 'user-123',
52
55
  * sessionId: 'session-456',
53
56
  * tags: ['production', 'api'],
54
57
  * metadata: { environment: 'prod', version: '1.0.0' }
55
- * }
58
+ * },
59
+ * seed: 'request-123' // optional: deterministic traceId from this seed
56
60
  * }, async () => {
57
- * // This HTTP request will be instrumented AND have the attributes set above
58
61
  * const response = await fetch('https://api.example.com/users/123');
59
62
  * return response.json();
60
63
  * });
61
- *
62
- * // HTTP requests outside wrapHttp are still instrumented, just without the attributes
63
- * const otherResponse = await fetch('https://api.example.com/other');
64
- *
65
- * // Scenario 2: initializePingops was NOT called
66
- * // Only requests within wrapHttp are instrumented
67
- * await wrapHttp({
68
- * attributes: { userId: 'user-123' }
69
- * }, async () => {
70
- * // This request IS instrumented
71
- * return fetch('https://api.example.com/data');
72
- * });
73
- *
74
- * // This request is NOT instrumented (outside wrapHttp)
75
- * await fetch('https://api.example.com/other');
76
64
  * ```
77
65
  */
78
- declare function wrapHttp<T>(options: {
79
- attributes?: WrapHttpAttributes$1;
80
- }, fn: () => T | Promise<T>): T | Promise<T>;
66
+ declare function startTrace<T>(options: {
67
+ attributes?: PingopsTraceAttributes$1;
68
+ seed?: string;
69
+ }, fn: () => T | Promise<T>): Promise<T>;
81
70
  //#endregion
82
- export { type WrapHttpAttributes, initializePingops, shutdownPingops, wrapHttp };
71
+ export { type PingopsTraceAttributes, getActiveSpanId, getActiveTraceId, initializePingops, shutdownPingops, startTrace };
83
72
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../src/pingops.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;;iBAwDgB,iBAAA,SACN;;;;iBAoEY,eAAA,CAAA,GAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgLzB;eACU;aACd,IAAI,QAAQ,KACrB,IAAI,QAAQ"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/pingops.ts"],"sourcesContent":[],"mappings":";;;;;AA+SA;AAOA;AAiCA;;;;;;;;;;;;iBArRgB,iBAAA,SACN;iBAGM,iBAAA;iBAIA,iBAAA;;;;;;iBAuGM,eAAA,CAAA,GAAmB;;;;iBA8HzB,gBAAA,CAAA;;;;iBAOA,eAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiCM;eACI;;aACd,IAAI,QAAQ,KACrB,QAAQ"}
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { PingopsProcessorConfig } from "@pingops/otel";
2
- import { WrapHttpAttributes, WrapHttpAttributes as WrapHttpAttributes$1 } from "@pingops/core";
2
+ import { PingopsTraceAttributes, PingopsTraceAttributes as PingopsTraceAttributes$1 } from "@pingops/core";
3
3
 
4
4
  //#region src/pingops.d.ts
5
5
 
@@ -13,71 +13,60 @@ import { WrapHttpAttributes, WrapHttpAttributes as WrapHttpAttributes$1 } from "
13
13
  * 4. Enables HTTP/fetch/GenAI instrumentation
14
14
  * 5. Starts the SDK
15
15
  *
16
- * @param config - Configuration for the SDK
16
+ * @param config - Configuration object, config file path, or config file wrapper
17
17
  * @param explicit - Whether this is an explicit call (default: true).
18
- * Set to false when called internally by wrapHttp auto-initialization.
18
+ * Set to false when called internally by startTrace auto-initialization.
19
19
  */
20
20
  declare function initializePingops(config: PingopsProcessorConfig, explicit?: boolean): void;
21
+ declare function initializePingops(configFilePath: string, explicit?: boolean): void;
22
+ declare function initializePingops(config: {
23
+ configFile: string;
24
+ }, explicit?: boolean): void;
21
25
  /**
22
26
  * Shuts down the SDK and flushes remaining spans
23
27
  */
24
28
  declare function shutdownPingops(): Promise<void>;
25
29
  /**
26
- * Wraps a function to set attributes on HTTP spans created within the wrapped block.
27
- *
28
- * This function sets attributes (userId, sessionId, tags, metadata) in the OpenTelemetry
29
- * context, which are automatically propagated to all spans created within the wrapped function.
30
- *
31
- * Instrumentation behavior:
32
- * - If `initializePingops` was called: All HTTP requests are instrumented by default.
33
- * `wrapHttp` only adds attributes to spans created within the wrapped block.
34
- * - If `initializePingops` was NOT called: Only HTTP requests within `wrapHttp` blocks
35
- * are instrumented. Requests outside `wrapHttp` are not instrumented.
30
+ * Returns the trace ID of the currently active span, if any.
31
+ */
32
+ declare function getActiveTraceId(): string | undefined;
33
+ /**
34
+ * Returns the span ID of the currently active span, if any.
35
+ */
36
+ declare function getActiveSpanId(): string | undefined;
37
+ /**
38
+ * Starts a new trace using the PingOps tracer provider and runs the callback within that trace.
39
+ * Sets attributes (traceId, userId, sessionId, tags, metadata, etc.) in context so they are
40
+ * propagated to spans created within the callback.
36
41
  *
37
- * @param options - Options including attributes to propagate to spans
38
- * @param fn - Function to execute within the attribute context
39
- * @returns The result of the function
42
+ * @param options - Options including optional attributes and optional seed for deterministic traceId
43
+ * @param fn - Function to execute within the trace and attribute context
44
+ * @returns Promise resolving to the result of the function
40
45
  *
41
46
  * @example
42
47
  * ```typescript
43
- * import { wrapHttp } from '@pingops/sdk';
48
+ * import { startTrace, initializePingops } from '@pingops/sdk';
44
49
  *
45
- * // Scenario 1: initializePingops was called
46
50
  * initializePingops({ ... });
47
51
  *
48
- * // All HTTP requests are instrumented, but this block adds attributes
49
- * const result = await wrapHttp({
52
+ * const result = await startTrace({
50
53
  * attributes: {
51
54
  * userId: 'user-123',
52
55
  * sessionId: 'session-456',
53
56
  * tags: ['production', 'api'],
54
57
  * metadata: { environment: 'prod', version: '1.0.0' }
55
- * }
58
+ * },
59
+ * seed: 'request-123' // optional: deterministic traceId from this seed
56
60
  * }, async () => {
57
- * // This HTTP request will be instrumented AND have the attributes set above
58
61
  * const response = await fetch('https://api.example.com/users/123');
59
62
  * return response.json();
60
63
  * });
61
- *
62
- * // HTTP requests outside wrapHttp are still instrumented, just without the attributes
63
- * const otherResponse = await fetch('https://api.example.com/other');
64
- *
65
- * // Scenario 2: initializePingops was NOT called
66
- * // Only requests within wrapHttp are instrumented
67
- * await wrapHttp({
68
- * attributes: { userId: 'user-123' }
69
- * }, async () => {
70
- * // This request IS instrumented
71
- * return fetch('https://api.example.com/data');
72
- * });
73
- *
74
- * // This request is NOT instrumented (outside wrapHttp)
75
- * await fetch('https://api.example.com/other');
76
64
  * ```
77
65
  */
78
- declare function wrapHttp<T>(options: {
79
- attributes?: WrapHttpAttributes$1;
80
- }, fn: () => T | Promise<T>): T | Promise<T>;
66
+ declare function startTrace<T>(options: {
67
+ attributes?: PingopsTraceAttributes$1;
68
+ seed?: string;
69
+ }, fn: () => T | Promise<T>): Promise<T>;
81
70
  //#endregion
82
- export { type WrapHttpAttributes, initializePingops, shutdownPingops, wrapHttp };
71
+ export { type PingopsTraceAttributes, getActiveSpanId, getActiveTraceId, initializePingops, shutdownPingops, startTrace };
83
72
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/pingops.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;;iBAwDgB,iBAAA,SACN;;;;iBAoEY,eAAA,CAAA,GAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgLzB;eACU;aACd,IAAI,QAAQ,KACrB,IAAI,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/pingops.ts"],"sourcesContent":[],"mappings":";;;;;AA+SA;AAOA;AAiCA;;;;;;;;;;;;iBArRgB,iBAAA,SACN;iBAGM,iBAAA;iBAIA,iBAAA;;;;;;iBAuGM,eAAA,CAAA,GAAmB;;;;iBA8HzB,gBAAA,CAAA;;;;iBAOA,eAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiCM;eACI;;aACd,IAAI,QAAQ,KACrB,QAAQ"}