@pingops/sdk 0.1.0 → 0.1.2

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 (44) hide show
  1. package/dist/index.cjs +248 -0
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/{pingops.d.ts → index.d.cts} +12 -14
  4. package/dist/index.d.cts.map +1 -0
  5. package/dist/index.d.mts +83 -0
  6. package/dist/index.d.mts.map +1 -0
  7. package/dist/index.mjs +246 -0
  8. package/dist/index.mjs.map +1 -0
  9. package/package.json +19 -7
  10. package/dist/config.d.ts +0 -7
  11. package/dist/config.d.ts.map +0 -1
  12. package/dist/config.js +0 -5
  13. package/dist/config.js.map +0 -1
  14. package/dist/index.d.ts +0 -6
  15. package/dist/index.d.ts.map +0 -1
  16. package/dist/index.js +0 -5
  17. package/dist/index.js.map +0 -1
  18. package/dist/init-state.d.ts +0 -17
  19. package/dist/init-state.d.ts.map +0 -1
  20. package/dist/init-state.js +0 -22
  21. package/dist/init-state.js.map +0 -1
  22. package/dist/initialize.d.ts +0 -20
  23. package/dist/initialize.d.ts.map +0 -1
  24. package/dist/initialize.js +0 -86
  25. package/dist/initialize.js.map +0 -1
  26. package/dist/instrumentation.d.ts +0 -14
  27. package/dist/instrumentation.d.ts.map +0 -1
  28. package/dist/instrumentation.js +0 -76
  29. package/dist/instrumentation.js.map +0 -1
  30. package/dist/logger.d.ts +0 -25
  31. package/dist/logger.d.ts.map +0 -1
  32. package/dist/logger.js +0 -40
  33. package/dist/logger.js.map +0 -1
  34. package/dist/pingops.d.ts.map +0 -1
  35. package/dist/pingops.js +0 -259
  36. package/dist/pingops.js.map +0 -1
  37. package/dist/span-wrapper.d.ts +0 -60
  38. package/dist/span-wrapper.d.ts.map +0 -1
  39. package/dist/span-wrapper.js +0 -118
  40. package/dist/span-wrapper.js.map +0 -1
  41. package/dist/tracer-provider.d.ts +0 -175
  42. package/dist/tracer-provider.d.ts.map +0 -1
  43. package/dist/tracer-provider.js +0 -537
  44. package/dist/tracer-provider.js.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,248 @@
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");
7
+
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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["isSdkInitializedFlag","ATTR_SERVICE_NAME","PingopsSpanProcessor","NodeSDK","NodeTracerProvider"],"sources":["../src/init-state.ts","../src/pingops.ts"],"sourcesContent":["/**\n * Shared state for tracking SDK initialization\n * This module exists to avoid circular dependencies between pingops.ts and instrumentation.ts\n */\n\nlet isSdkInitializedFlag = false;\n\n/**\n * Sets the SDK initialization flag.\n * Called by initializePingops when the SDK is initialized.\n */\nexport function setSdkInitialized(initialized: boolean): void {\n isSdkInitializedFlag = initialized;\n}\n\n/**\n * Checks if global instrumentation is enabled.\n * This is used to determine instrumentation behavior:\n * - If true: all HTTP requests are instrumented\n * - If false: only requests within wrapHttp blocks are instrumented\n */\nexport function isGlobalInstrumentationEnabled(): boolean {\n return isSdkInitializedFlag;\n}\n","/**\n * PingOps SDK singleton for manual instrumentation\n *\n * Provides initializePingops and shutdownPingops functions.\n * wrapHttp is available from @pingops/core and will auto-initialize\n * from environment variables if needed.\n */\n\nimport { NodeSDK } from \"@opentelemetry/sdk-node\";\nimport { resourceFromAttributes } from \"@opentelemetry/resources\";\nimport { ATTR_SERVICE_NAME } from \"@opentelemetry/semantic-conventions\";\nimport { NodeTracerProvider } from \"@opentelemetry/sdk-trace-node\";\nimport type { PingopsProcessorConfig } from \"@pingops/otel\";\nimport {\n setPingopsTracerProvider,\n shutdownTracerProvider,\n PingopsSpanProcessor,\n} from \"@pingops/otel\";\nimport { createLogger } from \"@pingops/core\";\nimport {\n setSdkInitialized,\n isGlobalInstrumentationEnabled,\n} from \"./init-state\";\nimport {\n wrapHttp as coreWrapHttp,\n type WrapHttpAttributes,\n} from \"@pingops/core\";\nimport { getPingopsTracerProvider } from \"@pingops/otel\";\nimport { getInstrumentations } from \"@pingops/otel\";\n\nconst initLogger = createLogger(\"[PingOps Initialize]\");\nconst logger = createLogger(\"[PingOps Pingops]\");\n\nlet sdkInstance: NodeSDK | null = null;\nlet isSdkInitializedFlag = false;\n\n/**\n * Global state to track initialization\n */\nlet isInitialized = false;\nlet initializationPromise: Promise<void> | null = null;\n\n/**\n * Initializes PingOps SDK\n *\n * This function:\n * 1. Creates an OpenTelemetry NodeSDK instance\n * 2. Configures Resource with service.name\n * 3. Registers PingopsSpanProcessor\n * 4. Enables HTTP/fetch/GenAI instrumentation\n * 5. Starts the SDK\n *\n * @param config - Configuration for the SDK\n * @param explicit - Whether this is an explicit call (default: true).\n * Set to false when called internally by wrapHttp auto-initialization.\n */\nexport function initializePingops(\n config: PingopsProcessorConfig,\n explicit: boolean = true\n): void {\n if (isSdkInitializedFlag) {\n if (config.debug) {\n initLogger.warn(\"[PingOps] SDK already initialized, skipping\");\n }\n return;\n }\n\n // Create resource with service name\n const resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: config.serviceName,\n });\n\n const processor = new PingopsSpanProcessor(config);\n const instrumentations = getInstrumentations(isGlobalInstrumentationEnabled);\n\n // Node.js SDK\n const nodeSdk = new NodeSDK({\n resource,\n spanProcessors: [processor],\n instrumentations,\n });\n\n nodeSdk.start();\n sdkInstance = nodeSdk;\n\n // Mark SDK as initialized\n isSdkInitializedFlag = true;\n\n // Only enable global instrumentation if this was an explicit call\n // If called via wrapHttp auto-initialization, global instrumentation stays disabled\n setSdkInitialized(explicit);\n\n // Initialize isolated TracerProvider for manual spans AFTER NodeSDK starts\n // This ensures manual spans created via startSpan are processed by the same processor\n // We register it after NodeSDK so it takes precedence as the global provider\n try {\n // In version 2.2.0, span processors are passed in the constructor\n const isolatedProvider = new NodeTracerProvider({\n resource,\n spanProcessors: [processor],\n });\n\n // Register the provider globally\n isolatedProvider.register();\n\n // Set it in global state\n setPingopsTracerProvider(isolatedProvider);\n } catch (error) {\n if (config.debug) {\n initLogger.error(\n \"[PingOps] Failed to create isolated TracerProvider:\",\n error instanceof Error ? error.message : String(error)\n );\n }\n // Continue without isolated provider - manual spans will use global provider\n }\n\n if (config.debug) {\n initLogger.info(\"[PingOps] SDK initialized\");\n }\n}\n\n/**\n * Shuts down the SDK and flushes remaining spans\n */\nexport async function shutdownPingops(): Promise<void> {\n // Shutdown isolated TracerProvider first\n await shutdownTracerProvider();\n\n if (!sdkInstance) {\n return;\n }\n\n await sdkInstance.shutdown();\n sdkInstance = null;\n isSdkInitializedFlag = false;\n setSdkInitialized(false);\n}\n\n/**\n * Checks if the SDK is already initialized by checking if a NodeTracerProvider is available\n */\nfunction isSdkInitialized(): boolean {\n try {\n const provider = getPingopsTracerProvider();\n // If we have a NodeTracerProvider (not the default NoOpTracerProvider), SDK is initialized\n const initialized = provider instanceof NodeTracerProvider;\n logger.debug(\"Checked SDK initialization status\", {\n initialized,\n providerType: provider.constructor.name,\n });\n return initialized;\n } catch (error) {\n logger.debug(\"Error checking SDK initialization status\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return false;\n }\n}\n\n/**\n * Auto-initializes the SDK from environment variables if not already initialized\n */\nasync function ensureInitialized(): Promise<void> {\n // Check if SDK is already initialized (e.g., by calling initializePingops directly)\n if (isSdkInitialized()) {\n logger.debug(\"SDK already initialized, skipping auto-initialization\");\n isInitialized = true;\n return;\n }\n\n if (isInitialized) {\n logger.debug(\"SDK initialization flag already set, skipping\");\n return;\n }\n\n // If initialization is in progress, wait for it\n if (initializationPromise) {\n logger.debug(\"SDK initialization already in progress, waiting...\");\n return initializationPromise;\n }\n\n // Start initialization\n logger.info(\"Starting SDK auto-initialization from environment variables\");\n initializationPromise = Promise.resolve().then(() => {\n const apiKey = process.env.PINGOPS_API_KEY;\n const baseUrl = process.env.PINGOPS_BASE_URL;\n const serviceName = process.env.PINGOPS_SERVICE_NAME;\n const debug = process.env.PINGOPS_DEBUG === \"true\";\n\n logger.debug(\"Reading environment variables\", {\n hasApiKey: !!apiKey,\n hasBaseUrl: !!baseUrl,\n hasServiceName: !!serviceName,\n debug,\n });\n\n if (!apiKey || !baseUrl || !serviceName) {\n const missing = [\n !apiKey && \"PINGOPS_API_KEY\",\n !baseUrl && \"PINGOPS_BASE_URL\",\n !serviceName && \"PINGOPS_SERVICE_NAME\",\n ].filter(Boolean);\n\n logger.error(\n \"Missing required environment variables for auto-initialization\",\n {\n missing,\n }\n );\n\n throw new Error(\n `PingOps SDK auto-initialization requires PINGOPS_API_KEY, PINGOPS_BASE_URL, and PINGOPS_SERVICE_NAME environment variables. Missing: ${missing.join(\", \")}`\n );\n }\n\n const config: PingopsProcessorConfig = {\n apiKey,\n baseUrl,\n serviceName,\n debug,\n };\n\n logger.info(\"Initializing SDK with config\", {\n baseUrl,\n serviceName,\n debug,\n });\n\n // Call initializePingops with explicit=false since this is auto-initialization\n initializePingops(config, false);\n isInitialized = true;\n\n logger.info(\"SDK auto-initialization completed successfully\");\n });\n\n try {\n await initializationPromise;\n } catch (error) {\n logger.error(\"SDK auto-initialization failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n initializationPromise = null;\n }\n}\n\n/**\n * Wraps a function to set attributes on HTTP spans created within the wrapped block.\n *\n * This function sets attributes (userId, sessionId, tags, metadata) in the OpenTelemetry\n * context, which are automatically propagated to all spans created within the wrapped function.\n *\n * Instrumentation behavior:\n * - If `initializePingops` was called: All HTTP requests are instrumented by default.\n * `wrapHttp` only adds attributes to spans created within the wrapped block.\n * - If `initializePingops` was NOT called: Only HTTP requests within `wrapHttp` blocks\n * are instrumented. Requests outside `wrapHttp` are not instrumented.\n *\n * @param options - Options including attributes to propagate to spans\n * @param fn - Function to execute within the attribute context\n * @returns The result of the function\n *\n * @example\n * ```typescript\n * import { wrapHttp } from '@pingops/sdk';\n *\n * // Scenario 1: initializePingops was called\n * initializePingops({ ... });\n *\n * // All HTTP requests are instrumented, but this block adds attributes\n * const result = await wrapHttp({\n * attributes: {\n * userId: 'user-123',\n * sessionId: 'session-456',\n * tags: ['production', 'api'],\n * metadata: { environment: 'prod', version: '1.0.0' }\n * }\n * }, async () => {\n * // This HTTP request will be instrumented AND have the attributes set above\n * const response = await fetch('https://api.example.com/users/123');\n * return response.json();\n * });\n *\n * // HTTP requests outside wrapHttp are still instrumented, just without the attributes\n * const otherResponse = await fetch('https://api.example.com/other');\n *\n * // Scenario 2: initializePingops was NOT called\n * // Only requests within wrapHttp are instrumented\n * await wrapHttp({\n * attributes: { userId: 'user-123' }\n * }, async () => {\n * // This request IS instrumented\n * return fetch('https://api.example.com/data');\n * });\n *\n * // This request is NOT instrumented (outside wrapHttp)\n * await fetch('https://api.example.com/other');\n * ```\n */\nexport function wrapHttp<T>(\n options: { attributes?: WrapHttpAttributes },\n fn: () => T | Promise<T>\n): T | Promise<T> {\n return coreWrapHttp(\n {\n ...options,\n checkInitialized: isSdkInitialized,\n isGlobalInstrumentationEnabled: isGlobalInstrumentationEnabled,\n ensureInitialized: ensureInitialized,\n },\n fn\n );\n}\n"],"mappings":";;;;;;;;;;;;AAKA,IAAIA,yBAAuB;;;;;AAM3B,SAAgB,kBAAkB,aAA4B;AAC5D,0BAAuB;;;;;;;;AASzB,SAAgB,iCAA0C;AACxD,QAAOA;;;;;;;;;;;;ACQT,MAAM,6CAA0B,uBAAuB;AACvD,MAAM,yCAAsB,oBAAoB;AAEhD,IAAI,cAA8B;AAClC,IAAI,uBAAuB;;;;AAK3B,IAAI,gBAAg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downPingops functions.
5
- * wrapHttp is available from @pingops/core and will auto-initialize
6
- * from environment variables if needed.
7
- */
8
- import type { PingopsProcessorConfig } from "@pingops/otel";
9
- import { type WrapHttpAttributes } from "@pingops/core";
1
+ import { PingopsProcessorConfig } from "@pingops/otel";
2
+ import { WrapHttpAttributes, WrapHttpAttributes as WrapHttpAttributes$1 } from "@pingops/core";
3
+
4
+ //#region src/pingops.d.ts
5
+
10
6
  /**
11
7
  * Initializes PingOps SDK
12
8
  *
@@ -21,11 +17,11 @@ import { type WrapHttpAttributes } from "@pingops/core";
21
17
  * @param explicit - Whether this is an explicit call (default: true).
22
18
  * Set to false when called internally by wrapHttp auto-initialization.
23
19
  */
24
- export declare function initializePingops(config: PingopsProcessorConfig, explicit?: boolean): void;
20
+ declare function initializePingops(config: PingopsProcessorConfig, explicit?: boolean): void;
25
21
  /**
26
22
  * Shuts down the SDK and flushes remaining spans
27
23
  */
28
- export declare function shutdownPingops(): Promise<void>;
24
+ declare function shutdownPingops(): Promise<void>;
29
25
  /**
30
26
  * Wraps a function to set attributes on HTTP spans created within the wrapped block.
31
27
  *
@@ -79,7 +75,9 @@ export declare function shutdownPingops(): Promise<void>;
79
75
  * await fetch('https://api.example.com/other');
80
76
  * ```
81
77
  */
82
- export declare function wrapHttp<T>(options: {
83
- attributes?: WrapHttpAttributes;
78
+ declare function wrapHttp<T>(options: {
79
+ attributes?: WrapHttpAttributes$1;
84
80
  }, fn: () => T | Promise<T>): T | Promise<T>;
85
- //# sourceMappingURL=pingops.d.ts.map
81
+ //#endregion
82
+ export { type WrapHttpAttributes, initializePingops, shutdownPingops, wrapHttp };
83
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +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"}
@@ -0,0 +1,83 @@
1
+ import { PingopsProcessorConfig } from "@pingops/otel";
2
+ import { WrapHttpAttributes, WrapHttpAttributes as WrapHttpAttributes$1 } from "@pingops/core";
3
+
4
+ //#region src/pingops.d.ts
5
+
6
+ /**
7
+ * Initializes PingOps SDK
8
+ *
9
+ * This function:
10
+ * 1. Creates an OpenTelemetry NodeSDK instance
11
+ * 2. Configures Resource with service.name
12
+ * 3. Registers PingopsSpanProcessor
13
+ * 4. Enables HTTP/fetch/GenAI instrumentation
14
+ * 5. Starts the SDK
15
+ *
16
+ * @param config - Configuration for the SDK
17
+ * @param explicit - Whether this is an explicit call (default: true).
18
+ * Set to false when called internally by wrapHttp auto-initialization.
19
+ */
20
+ declare function initializePingops(config: PingopsProcessorConfig, explicit?: boolean): void;
21
+ /**
22
+ * Shuts down the SDK and flushes remaining spans
23
+ */
24
+ declare function shutdownPingops(): Promise<void>;
25
+ /**
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.
36
+ *
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
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * import { wrapHttp } from '@pingops/sdk';
44
+ *
45
+ * // Scenario 1: initializePingops was called
46
+ * initializePingops({ ... });
47
+ *
48
+ * // All HTTP requests are instrumented, but this block adds attributes
49
+ * const result = await wrapHttp({
50
+ * attributes: {
51
+ * userId: 'user-123',
52
+ * sessionId: 'session-456',
53
+ * tags: ['production', 'api'],
54
+ * metadata: { environment: 'prod', version: '1.0.0' }
55
+ * }
56
+ * }, async () => {
57
+ * // This HTTP request will be instrumented AND have the attributes set above
58
+ * const response = await fetch('https://api.example.com/users/123');
59
+ * return response.json();
60
+ * });
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
+ * ```
77
+ */
78
+ declare function wrapHttp<T>(options: {
79
+ attributes?: WrapHttpAttributes$1;
80
+ }, fn: () => T | Promise<T>): T | Promise<T>;
81
+ //#endregion
82
+ export { type WrapHttpAttributes, initializePingops, shutdownPingops, wrapHttp };
83
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +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"}
package/dist/index.mjs ADDED
@@ -0,0 +1,246 @@
1
+ import { NodeSDK } from "@opentelemetry/sdk-node";
2
+ import { resourceFromAttributes } from "@opentelemetry/resources";
3
+ import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
4
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
5
+ import { PingopsSpanProcessor, getInstrumentations, getPingopsTracerProvider, setPingopsTracerProvider, shutdownTracerProvider } from "@pingops/otel";
6
+ import { createLogger, wrapHttp as wrapHttp$1 } from "@pingops/core";
7
+
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 = createLogger("[PingOps Initialize]");
41
+ const logger = 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 = resourceFromAttributes({ [ATTR_SERVICE_NAME]: config.serviceName });
69
+ const processor = new PingopsSpanProcessor(config);
70
+ const instrumentations = getInstrumentations(isGlobalInstrumentationEnabled);
71
+ const nodeSdk = new 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 NodeTracerProvider({
82
+ resource,
83
+ spanProcessors: [processor]
84
+ });
85
+ isolatedProvider.register();
86
+ 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 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 = getPingopsTracerProvider();
109
+ const initialized = provider instanceof 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 wrapHttp$1({
237
+ ...options,
238
+ checkInitialized: isSdkInitialized,
239
+ isGlobalInstrumentationEnabled,
240
+ ensureInitialized
241
+ }, fn);
242
+ }
243
+
244
+ //#endregion
245
+ export { initializePingops, shutdownPingops, wrapHttp };
246
+ //# sourceMappingURL=index.mjs.map