@iii-dev/helpers 0.19.4-alpha.5 → 0.19.7-next.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.
- package/dist/http/index.cjs +1 -1
- package/dist/http/index.cjs.map +1 -1
- package/dist/http/index.d.cts +1 -1
- package/dist/http/index.d.mts +1 -1
- package/dist/http/index.mjs +1 -1
- package/dist/http/index.mjs.map +1 -1
- package/dist/{index-CEjPaG4S.d.cts → index-B2thODQm.d.cts} +2 -2
- package/dist/{index-KWqP5kbF.d.mts → index-Cr3b3Tmk.d.mts} +2 -2
- package/dist/observability/index.cjs +2 -2
- package/dist/observability/index.cjs.map +1 -1
- package/dist/observability/index.d.cts +2 -2
- package/dist/observability/index.d.mts +2 -2
- package/dist/observability/index.mjs +2 -2
- package/dist/observability/index.mjs.map +1 -1
- package/dist/observability/internal.cjs +1 -1
- package/dist/observability/internal.d.cts +1 -1
- package/dist/observability/internal.d.mts +1 -1
- package/dist/observability/internal.mjs +1 -1
- package/dist/stream/index.d.cts +1 -1
- package/dist/stream/index.d.mts +1 -1
- package/dist/{telemetry-system-CLZLK3nL.mjs → telemetry-system-DZc-9gY3.mjs} +2 -2
- package/dist/telemetry-system-DZc-9gY3.mjs.map +1 -0
- package/dist/{telemetry-system-CY8_emop.cjs → telemetry-system-eOJBYcZF.cjs} +2 -2
- package/dist/telemetry-system-eOJBYcZF.cjs.map +1 -0
- package/package.json +3 -1
- package/dist/telemetry-system-CLZLK3nL.mjs.map +0 -1
- package/dist/telemetry-system-CY8_emop.cjs.map +0 -1
package/dist/http/index.cjs
CHANGED
|
@@ -12,7 +12,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
12
12
|
* ```typescript
|
|
13
13
|
* import { http } from '@iii-dev/helpers/http'
|
|
14
14
|
*
|
|
15
|
-
*
|
|
15
|
+
* worker.registerFunction(
|
|
16
16
|
* 'my-api',
|
|
17
17
|
* http(async (req, res) => {
|
|
18
18
|
* res.status(200)
|
package/dist/http/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/http/index.ts"],"sourcesContent":["/**\n * HTTP method accepted by {@link HttpInvocationConfig}. Distinct from the core\n * `builtin_triggers` HTTP method enum, which also covers HEAD/OPTIONS.\n */\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\n/**\n * Authentication configuration for HTTP-invoked functions.\n *\n * - `hmac` -- HMAC signature verification using a shared secret.\n * - `bearer` -- Bearer token authentication.\n * - `api_key` -- API key sent via a custom header.\n */\nexport type HttpAuthConfig =\n | { type: 'hmac'; secret_key: string }\n | { type: 'bearer'; token_key: string }\n | { type: 'api_key'; header: string; value_key: string }\n\n/**\n * Configuration for registering an HTTP-invoked function (Lambda, Cloudflare\n * Workers, etc.) instead of a local handler.\n */\nexport type HttpInvocationConfig = {\n /** URL to invoke. */\n url: string\n /** HTTP method. Defaults to `POST`. */\n method?: HttpMethod\n /** Timeout in milliseconds. */\n timeout_ms?: number\n /** Custom headers to send with the request. */\n headers?: Record<string, string>\n /** Authentication configuration. */\n auth?: HttpAuthConfig\n}\n\n/**\n * Incoming buffered HTTP request received by a function handler.\n *\n * @typeParam TBody - Type of the parsed request body.\n */\nexport type HttpRequest<TBody = unknown> = {\n path_params: Record<string, string>\n query_params: Record<string, string | string[]>\n body: TBody\n headers: Record<string, string | string[]>\n method: string\n request_body: HttpStreamReader\n}\n\n/**\n * Structured buffered HTTP response returned from function handlers.\n *\n * @typeParam TStatus - HTTP status code literal type.\n * @typeParam TBody - Type of the response body.\n *\n * @example\n * ```typescript\n * const response: HttpResponse = {\n * status_code: 200,\n * headers: { 'content-type': 'application/json' },\n * body: { message: 'ok' },\n * }\n * ```\n */\nexport type HttpResponse<\n TStatus extends number = number,\n TBody = string | Buffer | Record<string, unknown>,\n> = {\n /** HTTP status code. */\n status_code: TStatus\n /** Response headers. */\n headers?: Record<string, string>\n /** Response body. */\n body?: TBody\n}\n\n/**\n * Structural shape of the reader end of a stream channel. Declared locally so\n * the helpers package does not runtime-depend on the core SDK.\n */\ntype HttpStreamReader = {\n stream: NodeJS.ReadableStream\n readAll: () => Promise<Buffer>\n onMessage: (callback: (msg: string) => void) => void\n close: () => void\n}\n\n/** Structural shape of the writer end of a stream channel. */\ntype HttpStreamWriter = {\n sendMessage: (message: string) => unknown\n stream: NodeJS.WritableStream\n close: () => unknown\n}\n\n/** Structural shape of a streaming request passed to the {@link http} handler. */\ntype HttpStreamingRequest = {\n path_params: Record<string, string>\n query_params: Record<string, string | string[]>\n body: unknown\n headers: Record<string, string | string[]>\n method: string\n request_body: HttpStreamReader\n}\n\n/** Structural shape of the streaming response passed to the {@link http} handler. */\ntype HttpStreamingResponse = {\n status: (statusCode: number) => void\n headers: (headers: Record<string, string>) => void\n stream: NodeJS.WritableStream\n close: () => void\n}\n\n/** Structural shape of the internal request delivered by the runtime. */\ntype HttpInternalRequest = HttpStreamingRequest & { response: HttpStreamWriter }\n\n/**\n * Helper that wraps an HTTP-style handler (with separate `req`/`res` arguments)\n * into the function handler format expected by the SDK.\n *\n * @param callback - Async handler receiving a streaming request and response.\n * @returns A function handler compatible with `IIIClient.registerFunction`.\n *\n * @example\n * ```typescript\n * import { http } from '@iii-dev/helpers/http'\n *\n *
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/http/index.ts"],"sourcesContent":["/**\n * HTTP method accepted by {@link HttpInvocationConfig}. Distinct from the core\n * `builtin_triggers` HTTP method enum, which also covers HEAD/OPTIONS.\n */\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\n/**\n * Authentication configuration for HTTP-invoked functions.\n *\n * - `hmac` -- HMAC signature verification using a shared secret.\n * - `bearer` -- Bearer token authentication.\n * - `api_key` -- API key sent via a custom header.\n */\nexport type HttpAuthConfig =\n | { type: 'hmac'; secret_key: string }\n | { type: 'bearer'; token_key: string }\n | { type: 'api_key'; header: string; value_key: string }\n\n/**\n * Configuration for registering an HTTP-invoked function (Lambda, Cloudflare\n * Workers, etc.) instead of a local handler.\n */\nexport type HttpInvocationConfig = {\n /** URL to invoke. */\n url: string\n /** HTTP method. Defaults to `POST`. */\n method?: HttpMethod\n /** Timeout in milliseconds. */\n timeout_ms?: number\n /** Custom headers to send with the request. */\n headers?: Record<string, string>\n /** Authentication configuration. */\n auth?: HttpAuthConfig\n}\n\n/**\n * Incoming buffered HTTP request received by a function handler.\n *\n * @typeParam TBody - Type of the parsed request body.\n */\nexport type HttpRequest<TBody = unknown> = {\n path_params: Record<string, string>\n query_params: Record<string, string | string[]>\n body: TBody\n headers: Record<string, string | string[]>\n method: string\n request_body: HttpStreamReader\n}\n\n/**\n * Structured buffered HTTP response returned from function handlers.\n *\n * @typeParam TStatus - HTTP status code literal type.\n * @typeParam TBody - Type of the response body.\n *\n * @example\n * ```typescript\n * const response: HttpResponse = {\n * status_code: 200,\n * headers: { 'content-type': 'application/json' },\n * body: { message: 'ok' },\n * }\n * ```\n */\nexport type HttpResponse<\n TStatus extends number = number,\n TBody = string | Buffer | Record<string, unknown>,\n> = {\n /** HTTP status code. */\n status_code: TStatus\n /** Response headers. */\n headers?: Record<string, string>\n /** Response body. */\n body?: TBody\n}\n\n/**\n * Structural shape of the reader end of a stream channel. Declared locally so\n * the helpers package does not runtime-depend on the core SDK.\n */\ntype HttpStreamReader = {\n stream: NodeJS.ReadableStream\n readAll: () => Promise<Buffer>\n onMessage: (callback: (msg: string) => void) => void\n close: () => void\n}\n\n/** Structural shape of the writer end of a stream channel. */\ntype HttpStreamWriter = {\n sendMessage: (message: string) => unknown\n stream: NodeJS.WritableStream\n close: () => unknown\n}\n\n/** Structural shape of a streaming request passed to the {@link http} handler. */\ntype HttpStreamingRequest = {\n path_params: Record<string, string>\n query_params: Record<string, string | string[]>\n body: unknown\n headers: Record<string, string | string[]>\n method: string\n request_body: HttpStreamReader\n}\n\n/** Structural shape of the streaming response passed to the {@link http} handler. */\ntype HttpStreamingResponse = {\n status: (statusCode: number) => void\n headers: (headers: Record<string, string>) => void\n stream: NodeJS.WritableStream\n close: () => void\n}\n\n/** Structural shape of the internal request delivered by the runtime. */\ntype HttpInternalRequest = HttpStreamingRequest & { response: HttpStreamWriter }\n\n/**\n * Helper that wraps an HTTP-style handler (with separate `req`/`res` arguments)\n * into the function handler format expected by the SDK.\n *\n * @param callback - Async handler receiving a streaming request and response.\n * @returns A function handler compatible with `IIIClient.registerFunction`.\n *\n * @example\n * ```typescript\n * import { http } from '@iii-dev/helpers/http'\n *\n * worker.registerFunction(\n * 'my-api',\n * http(async (req, res) => {\n * res.status(200)\n * res.headers({ 'content-type': 'application/json' })\n * res.stream.end(JSON.stringify({ hello: 'world' }))\n * res.close()\n * }),\n * )\n * ```\n */\nexport const http = (\n // biome-ignore lint/suspicious/noConfusingVoidType: void is necessary here\n callback: (req: HttpStreamingRequest, res: HttpStreamingResponse) => Promise<void | HttpResponse>,\n) => {\n return async (req: HttpInternalRequest) => {\n const { response, ...request } = req\n\n const httpResponse: HttpStreamingResponse = {\n status: (status_code: number) =>\n response.sendMessage(JSON.stringify({ type: 'set_status', status_code })),\n headers: (headers: Record<string, string>) =>\n response.sendMessage(JSON.stringify({ type: 'set_headers', headers })),\n stream: response.stream,\n close: () => response.close(),\n }\n\n return callback(request, httpResponse)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyIA,MAAa,QAEX,aACG;AACH,QAAO,OAAO,QAA6B;EACzC,MAAM,EAAE,UAAU,GAAG,YAAY;AAWjC,SAAO,SAAS,SAT4B;GAC1C,SAAS,gBACP,SAAS,YAAY,KAAK,UAAU;IAAE,MAAM;IAAc;IAAa,CAAC,CAAC;GAC3E,UAAU,YACR,SAAS,YAAY,KAAK,UAAU;IAAE,MAAM;IAAe;IAAS,CAAC,CAAC;GACxE,QAAQ,SAAS;GACjB,aAAa,SAAS,OAAO;GAC9B,CAEqC"}
|
package/dist/http/index.d.cts
CHANGED
|
@@ -113,7 +113,7 @@ type HttpInternalRequest = HttpStreamingRequest & {
|
|
|
113
113
|
* ```typescript
|
|
114
114
|
* import { http } from '@iii-dev/helpers/http'
|
|
115
115
|
*
|
|
116
|
-
*
|
|
116
|
+
* worker.registerFunction(
|
|
117
117
|
* 'my-api',
|
|
118
118
|
* http(async (req, res) => {
|
|
119
119
|
* res.status(200)
|
package/dist/http/index.d.mts
CHANGED
|
@@ -113,7 +113,7 @@ type HttpInternalRequest = HttpStreamingRequest & {
|
|
|
113
113
|
* ```typescript
|
|
114
114
|
* import { http } from '@iii-dev/helpers/http'
|
|
115
115
|
*
|
|
116
|
-
*
|
|
116
|
+
* worker.registerFunction(
|
|
117
117
|
* 'my-api',
|
|
118
118
|
* http(async (req, res) => {
|
|
119
119
|
* res.status(200)
|
package/dist/http/index.mjs
CHANGED
package/dist/http/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/http/index.ts"],"sourcesContent":["/**\n * HTTP method accepted by {@link HttpInvocationConfig}. Distinct from the core\n * `builtin_triggers` HTTP method enum, which also covers HEAD/OPTIONS.\n */\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\n/**\n * Authentication configuration for HTTP-invoked functions.\n *\n * - `hmac` -- HMAC signature verification using a shared secret.\n * - `bearer` -- Bearer token authentication.\n * - `api_key` -- API key sent via a custom header.\n */\nexport type HttpAuthConfig =\n | { type: 'hmac'; secret_key: string }\n | { type: 'bearer'; token_key: string }\n | { type: 'api_key'; header: string; value_key: string }\n\n/**\n * Configuration for registering an HTTP-invoked function (Lambda, Cloudflare\n * Workers, etc.) instead of a local handler.\n */\nexport type HttpInvocationConfig = {\n /** URL to invoke. */\n url: string\n /** HTTP method. Defaults to `POST`. */\n method?: HttpMethod\n /** Timeout in milliseconds. */\n timeout_ms?: number\n /** Custom headers to send with the request. */\n headers?: Record<string, string>\n /** Authentication configuration. */\n auth?: HttpAuthConfig\n}\n\n/**\n * Incoming buffered HTTP request received by a function handler.\n *\n * @typeParam TBody - Type of the parsed request body.\n */\nexport type HttpRequest<TBody = unknown> = {\n path_params: Record<string, string>\n query_params: Record<string, string | string[]>\n body: TBody\n headers: Record<string, string | string[]>\n method: string\n request_body: HttpStreamReader\n}\n\n/**\n * Structured buffered HTTP response returned from function handlers.\n *\n * @typeParam TStatus - HTTP status code literal type.\n * @typeParam TBody - Type of the response body.\n *\n * @example\n * ```typescript\n * const response: HttpResponse = {\n * status_code: 200,\n * headers: { 'content-type': 'application/json' },\n * body: { message: 'ok' },\n * }\n * ```\n */\nexport type HttpResponse<\n TStatus extends number = number,\n TBody = string | Buffer | Record<string, unknown>,\n> = {\n /** HTTP status code. */\n status_code: TStatus\n /** Response headers. */\n headers?: Record<string, string>\n /** Response body. */\n body?: TBody\n}\n\n/**\n * Structural shape of the reader end of a stream channel. Declared locally so\n * the helpers package does not runtime-depend on the core SDK.\n */\ntype HttpStreamReader = {\n stream: NodeJS.ReadableStream\n readAll: () => Promise<Buffer>\n onMessage: (callback: (msg: string) => void) => void\n close: () => void\n}\n\n/** Structural shape of the writer end of a stream channel. */\ntype HttpStreamWriter = {\n sendMessage: (message: string) => unknown\n stream: NodeJS.WritableStream\n close: () => unknown\n}\n\n/** Structural shape of a streaming request passed to the {@link http} handler. */\ntype HttpStreamingRequest = {\n path_params: Record<string, string>\n query_params: Record<string, string | string[]>\n body: unknown\n headers: Record<string, string | string[]>\n method: string\n request_body: HttpStreamReader\n}\n\n/** Structural shape of the streaming response passed to the {@link http} handler. */\ntype HttpStreamingResponse = {\n status: (statusCode: number) => void\n headers: (headers: Record<string, string>) => void\n stream: NodeJS.WritableStream\n close: () => void\n}\n\n/** Structural shape of the internal request delivered by the runtime. */\ntype HttpInternalRequest = HttpStreamingRequest & { response: HttpStreamWriter }\n\n/**\n * Helper that wraps an HTTP-style handler (with separate `req`/`res` arguments)\n * into the function handler format expected by the SDK.\n *\n * @param callback - Async handler receiving a streaming request and response.\n * @returns A function handler compatible with `IIIClient.registerFunction`.\n *\n * @example\n * ```typescript\n * import { http } from '@iii-dev/helpers/http'\n *\n *
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/http/index.ts"],"sourcesContent":["/**\n * HTTP method accepted by {@link HttpInvocationConfig}. Distinct from the core\n * `builtin_triggers` HTTP method enum, which also covers HEAD/OPTIONS.\n */\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\n/**\n * Authentication configuration for HTTP-invoked functions.\n *\n * - `hmac` -- HMAC signature verification using a shared secret.\n * - `bearer` -- Bearer token authentication.\n * - `api_key` -- API key sent via a custom header.\n */\nexport type HttpAuthConfig =\n | { type: 'hmac'; secret_key: string }\n | { type: 'bearer'; token_key: string }\n | { type: 'api_key'; header: string; value_key: string }\n\n/**\n * Configuration for registering an HTTP-invoked function (Lambda, Cloudflare\n * Workers, etc.) instead of a local handler.\n */\nexport type HttpInvocationConfig = {\n /** URL to invoke. */\n url: string\n /** HTTP method. Defaults to `POST`. */\n method?: HttpMethod\n /** Timeout in milliseconds. */\n timeout_ms?: number\n /** Custom headers to send with the request. */\n headers?: Record<string, string>\n /** Authentication configuration. */\n auth?: HttpAuthConfig\n}\n\n/**\n * Incoming buffered HTTP request received by a function handler.\n *\n * @typeParam TBody - Type of the parsed request body.\n */\nexport type HttpRequest<TBody = unknown> = {\n path_params: Record<string, string>\n query_params: Record<string, string | string[]>\n body: TBody\n headers: Record<string, string | string[]>\n method: string\n request_body: HttpStreamReader\n}\n\n/**\n * Structured buffered HTTP response returned from function handlers.\n *\n * @typeParam TStatus - HTTP status code literal type.\n * @typeParam TBody - Type of the response body.\n *\n * @example\n * ```typescript\n * const response: HttpResponse = {\n * status_code: 200,\n * headers: { 'content-type': 'application/json' },\n * body: { message: 'ok' },\n * }\n * ```\n */\nexport type HttpResponse<\n TStatus extends number = number,\n TBody = string | Buffer | Record<string, unknown>,\n> = {\n /** HTTP status code. */\n status_code: TStatus\n /** Response headers. */\n headers?: Record<string, string>\n /** Response body. */\n body?: TBody\n}\n\n/**\n * Structural shape of the reader end of a stream channel. Declared locally so\n * the helpers package does not runtime-depend on the core SDK.\n */\ntype HttpStreamReader = {\n stream: NodeJS.ReadableStream\n readAll: () => Promise<Buffer>\n onMessage: (callback: (msg: string) => void) => void\n close: () => void\n}\n\n/** Structural shape of the writer end of a stream channel. */\ntype HttpStreamWriter = {\n sendMessage: (message: string) => unknown\n stream: NodeJS.WritableStream\n close: () => unknown\n}\n\n/** Structural shape of a streaming request passed to the {@link http} handler. */\ntype HttpStreamingRequest = {\n path_params: Record<string, string>\n query_params: Record<string, string | string[]>\n body: unknown\n headers: Record<string, string | string[]>\n method: string\n request_body: HttpStreamReader\n}\n\n/** Structural shape of the streaming response passed to the {@link http} handler. */\ntype HttpStreamingResponse = {\n status: (statusCode: number) => void\n headers: (headers: Record<string, string>) => void\n stream: NodeJS.WritableStream\n close: () => void\n}\n\n/** Structural shape of the internal request delivered by the runtime. */\ntype HttpInternalRequest = HttpStreamingRequest & { response: HttpStreamWriter }\n\n/**\n * Helper that wraps an HTTP-style handler (with separate `req`/`res` arguments)\n * into the function handler format expected by the SDK.\n *\n * @param callback - Async handler receiving a streaming request and response.\n * @returns A function handler compatible with `IIIClient.registerFunction`.\n *\n * @example\n * ```typescript\n * import { http } from '@iii-dev/helpers/http'\n *\n * worker.registerFunction(\n * 'my-api',\n * http(async (req, res) => {\n * res.status(200)\n * res.headers({ 'content-type': 'application/json' })\n * res.stream.end(JSON.stringify({ hello: 'world' }))\n * res.close()\n * }),\n * )\n * ```\n */\nexport const http = (\n // biome-ignore lint/suspicious/noConfusingVoidType: void is necessary here\n callback: (req: HttpStreamingRequest, res: HttpStreamingResponse) => Promise<void | HttpResponse>,\n) => {\n return async (req: HttpInternalRequest) => {\n const { response, ...request } = req\n\n const httpResponse: HttpStreamingResponse = {\n status: (status_code: number) =>\n response.sendMessage(JSON.stringify({ type: 'set_status', status_code })),\n headers: (headers: Record<string, string>) =>\n response.sendMessage(JSON.stringify({ type: 'set_headers', headers })),\n stream: response.stream,\n close: () => response.close(),\n }\n\n return callback(request, httpResponse)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyIA,MAAa,QAEX,aACG;AACH,QAAO,OAAO,QAA6B;EACzC,MAAM,EAAE,UAAU,GAAG,YAAY;AAWjC,SAAO,SAAS,SAT4B;GAC1C,SAAS,gBACP,SAAS,YAAY,KAAK,UAAU;IAAE,MAAM;IAAc;IAAa,CAAC,CAAC;GAC3E,UAAU,YACR,SAAS,YAAY,KAAK,UAAU;IAAE,MAAM;IAAe;IAAS,CAAC,CAAC;GACxE,QAAQ,SAAS;GACjB,aAAa,SAAS,OAAO;GAC9B,CAEqC"}
|
|
@@ -40,7 +40,7 @@ interface OtelConfig {
|
|
|
40
40
|
/**
|
|
41
41
|
* Span processor flush delay in milliseconds. Defaults to 100ms. This is how
|
|
42
42
|
* long an ended span waits in the batch buffer before it is flushed to the
|
|
43
|
-
* engine
|
|
43
|
+
* engine, the OpenTelemetry default of 5000ms is what makes traces appear
|
|
44
44
|
* seconds after the action. Env override: OTEL_SPANS_FLUSH_INTERVAL_MS.
|
|
45
45
|
*/
|
|
46
46
|
spansFlushIntervalMs?: number;
|
|
@@ -174,4 +174,4 @@ declare function withSpan<T>(name: string, options: {
|
|
|
174
174
|
}, fn: (span: Span$1) => Promise<T>): Promise<T>;
|
|
175
175
|
//#endregion
|
|
176
176
|
export { injectTraceparent as A, currentTraceId as C, getAllBaggage as D, extractTraceparent as E, setBaggageEntry as M, OtelConfig as N, getBaggageEntry as O, ReconnectionConfig as P, currentSpanId as S, extractContext as T, recordSpanEvent as _, flushOtel as a, BaggageSpanProcessor as b, getTracer as c, withSpan as d, REDACTED_PLACEHOLDER as f, currentSpanIsRecording as g, resolveMaxBytesFromEnv as h, Span$1 as i, removeBaggageEntry as j, injectBaggage as k, initOtel as l, redactAndTruncate as m, Meter$1 as n, getLogger as o, redact as p, SeverityNumber as r, getMeter as s, Logger as t, shutdownOtel as u, setCurrentSpanAttribute as v, extractBaggage as w, DEFAULT_ALLOWLIST as x, setCurrentSpanError as y };
|
|
177
|
-
//# sourceMappingURL=index-
|
|
177
|
+
//# sourceMappingURL=index-B2thODQm.d.cts.map
|
|
@@ -40,7 +40,7 @@ interface OtelConfig {
|
|
|
40
40
|
/**
|
|
41
41
|
* Span processor flush delay in milliseconds. Defaults to 100ms. This is how
|
|
42
42
|
* long an ended span waits in the batch buffer before it is flushed to the
|
|
43
|
-
* engine
|
|
43
|
+
* engine, the OpenTelemetry default of 5000ms is what makes traces appear
|
|
44
44
|
* seconds after the action. Env override: OTEL_SPANS_FLUSH_INTERVAL_MS.
|
|
45
45
|
*/
|
|
46
46
|
spansFlushIntervalMs?: number;
|
|
@@ -174,4 +174,4 @@ declare function withSpan<T>(name: string, options: {
|
|
|
174
174
|
}, fn: (span: Span$1) => Promise<T>): Promise<T>;
|
|
175
175
|
//#endregion
|
|
176
176
|
export { injectTraceparent as A, currentTraceId as C, getAllBaggage as D, extractTraceparent as E, setBaggageEntry as M, OtelConfig as N, getBaggageEntry as O, ReconnectionConfig as P, currentSpanId as S, extractContext as T, recordSpanEvent as _, flushOtel as a, BaggageSpanProcessor as b, getTracer as c, withSpan as d, REDACTED_PLACEHOLDER as f, currentSpanIsRecording as g, resolveMaxBytesFromEnv as h, Span$1 as i, removeBaggageEntry as j, injectBaggage as k, initOtel as l, redactAndTruncate as m, Meter$1 as n, getLogger as o, redact as p, SeverityNumber$1 as r, getMeter as s, Logger as t, shutdownOtel as u, setCurrentSpanAttribute as v, extractBaggage as w, DEFAULT_ALLOWLIST as x, setCurrentSpanError as y };
|
|
177
|
-
//# sourceMappingURL=index-
|
|
177
|
+
//# sourceMappingURL=index-Cr3b3Tmk.d.mts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_telemetry_system = require('../telemetry-system-
|
|
2
|
+
const require_telemetry_system = require('../telemetry-system-eOJBYcZF.cjs');
|
|
3
3
|
let _opentelemetry_api_logs = require("@opentelemetry/api-logs");
|
|
4
4
|
let _opentelemetry_api = require("@opentelemetry/api");
|
|
5
5
|
let node_perf_hooks = require("node:perf_hooks");
|
|
@@ -22,7 +22,7 @@ let node_perf_hooks = require("node:perf_hooks");
|
|
|
22
22
|
*
|
|
23
23
|
* const logger = new Logger()
|
|
24
24
|
*
|
|
25
|
-
* // Basic logging
|
|
25
|
+
* // Basic logging, trace context is injected automatically
|
|
26
26
|
* logger.info('Worker connected')
|
|
27
27
|
*
|
|
28
28
|
* // Structured context for dashboards and alerting
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["getOtelLogger","currentTraceId","currentSpanId","SeverityNumber","trace","SpanKind","otelContext","SpanStatusCode","performance"],"sources":["../../src/observability/logger.ts","../../src/observability/http-instrumentation.ts","../../src/observability/worker-metrics.ts","../../src/observability/otel-worker-gauges.ts","../../src/observability/utils.ts"],"sourcesContent":["import { AnyValue, AnyValueMap, SeverityNumber } from '@opentelemetry/api-logs'\nimport {\n currentSpanId,\n currentTraceId,\n getLogger as getOtelLogger,\n} from './telemetry-system'\n\n/** @internal */\nexport type LoggerParams = {\n message: string\n trace_id?: string\n span_id?: string\n service_name?: string\n data?: unknown\n /** @deprecated Use service_name instead */\n function_name?: string\n}\n\n/**\n * Structured logger that emits logs as OpenTelemetry LogRecords.\n *\n * Every log call automatically captures the active trace and span context,\n * correlating your logs with distributed traces without any manual wiring.\n * When OTel is not initialized, Logger gracefully falls back to `console.*`.\n *\n * Pass structured data as the second argument to any log method. Using an\n * object of key-value pairs (instead of string interpolation) lets you\n * filter, aggregate, and build dashboards in your observability backend.\n *\n * @example\n * ```typescript\n * import { Logger } from 'iii-sdk'\n *\n * const logger = new Logger()\n *\n * // Basic logging — trace context is injected automatically\n * logger.info('Worker connected')\n *\n * // Structured context for dashboards and alerting\n * logger.info('Order processed', { orderId: 'ord_123', amount: 49.99, currency: 'USD' })\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\nexport class Logger {\n private _otelLogger: ReturnType<typeof getOtelLogger> | null = null\n\n private get otelLogger() {\n // Lazy initialization: re-fetch logger if not yet available\n if (!this._otelLogger) {\n this._otelLogger = getOtelLogger()\n }\n return this._otelLogger\n }\n\n constructor(\n private readonly traceId?: string,\n private readonly serviceName?: string,\n private readonly spanId?: string,\n ) {}\n\n private emit(message: string, severity: SeverityNumber, data?: unknown): void {\n const attributes: AnyValueMap = {}\n const traceId = this.traceId ?? currentTraceId()\n const spanId = this.spanId ?? currentSpanId()\n\n if (traceId) {\n attributes.trace_id = traceId\n }\n if (spanId) {\n attributes.span_id = spanId\n }\n if (this.serviceName) {\n attributes['service.name'] = this.serviceName\n }\n if (data !== undefined) {\n attributes['log.data'] = data as AnyValue\n }\n\n if (this.otelLogger) {\n this.otelLogger.emit({\n severityNumber: severity,\n body: message,\n attributes: Object.keys(attributes).length > 0 ? attributes : undefined,\n })\n } else {\n // Fallback to console when OTEL is not available\n switch (severity) {\n case SeverityNumber.DEBUG:\n console.debug(message, data)\n break\n case SeverityNumber.INFO:\n console.info(message, data)\n break\n case SeverityNumber.WARN:\n console.warn(message, data)\n break\n case SeverityNumber.ERROR:\n console.error(message, data)\n break\n default:\n console.log(message, data)\n }\n }\n }\n\n /**\n * Log an info-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.info('Order processed', { orderId: 'ord_123', status: 'completed' })\n * ```\n */\n info(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.INFO, data)\n }\n\n /**\n * Log a warning-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * ```\n */\n warn(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.WARN, data)\n }\n\n /**\n * Log an error-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\n error(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.ERROR, data)\n }\n\n /**\n * Log a debug-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.debug('Cache lookup', { key: 'user:42', hit: false })\n * ```\n */\n debug(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.DEBUG, data)\n }\n}\n","import { context as otelContext, propagation, SpanKind, SpanStatusCode, trace, type Tracer } from '@opentelemetry/api'\n\nconst SAFE_REQUEST_HEADERS = ['content-type', 'accept'] as const\nconst SAFE_RESPONSE_HEADERS = ['content-type'] as const\n\nexport interface TracedFetchInit extends RequestInit {\n tracer?: Tracer\n}\n\n/**\n * Execute a fetch request inside an OTel CLIENT span.\n *\n * Mirrors the Rust execute_traced_request shape: injects W3C traceparent into\n * outgoing headers, records HTTP semantic-convention attributes, and sets\n * ERROR span status for HTTP responses with status >= 400 or network errors.\n */\nexport async function executeTracedRequest(\n input: RequestInfo | URL,\n init?: TracedFetchInit,\n): Promise<Response> {\n const tracer = init?.tracer ?? trace.getTracer('iii-node-sdk')\n const rawUrl = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n let url: URL | null\n try {\n url = new URL(rawUrl)\n } catch {\n url = null\n }\n const method = (init?.method ?? (typeof input === 'object' && 'method' in input ? input.method : 'GET') ?? 'GET').toUpperCase()\n const name = url?.pathname ? `${method} ${url.pathname}` : method\n\n return tracer.startActiveSpan(\n name,\n {\n kind: SpanKind.CLIENT,\n attributes: {\n 'http.request.method': method,\n 'url.full': url?.toString() ?? rawUrl,\n 'network.protocol.name': 'http',\n ...(url\n ? {\n 'server.address': url.hostname,\n 'url.scheme': url.protocol.replace(':', ''),\n 'url.path': url.pathname,\n }\n : {}),\n ...(url?.port ? { 'server.port': Number(url.port) } : {}),\n ...(url?.search ? { 'url.query': url.search.slice(1) } : {}),\n },\n },\n async (span) => {\n try {\n // Seed with the Request's own headers so they survive when caller\n // passes a Request object; init.headers (if any) then overrides.\n const baseHeaders =\n typeof input === 'object' && 'headers' in input ? input.headers : undefined\n const headers = new Headers(baseHeaders)\n if (init?.headers) {\n for (const [k, v] of new Headers(init.headers).entries()) headers.set(k, v)\n }\n const carrier: Record<string, string> = {}\n propagation.inject(otelContext.active(), carrier)\n for (const [k, v] of Object.entries(carrier)) headers.set(k, v)\n\n for (const h of SAFE_REQUEST_HEADERS) {\n const v = headers.get(h)\n if (v) span.setAttribute(`http.request.header.${h}`, v)\n }\n\n const response = await fetch(input, { ...init, headers })\n span.setAttribute('http.response.status_code', response.status)\n const cl = response.headers.get('content-length')\n if (cl) span.setAttribute('http.response.body.size', Number(cl))\n for (const h of SAFE_RESPONSE_HEADERS) {\n const v = response.headers.get(h)\n if (v) span.setAttribute(`http.response.header.${h}`, v)\n }\n\n if (response.status >= 400) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: String(response.status) })\n span.setAttribute('error.type', String(response.status))\n } else {\n span.setStatus({ code: SpanStatusCode.OK })\n }\n return response\n } catch (err) {\n const error = err as Error\n span.recordException(error)\n span.setStatus({ code: SpanStatusCode.ERROR, message: error.message })\n span.setAttribute('error.type', error.name)\n throw err\n } finally {\n span.end()\n }\n },\n )\n}\n","/**\n * Worker metrics collection for the III Node SDK.\n *\n * Collects CPU, memory, and event loop metrics for worker health monitoring.\n * Uses the Node.js built-in `monitorEventLoopDelay` API for accurate\n * event loop lag measurements.\n */\n\nimport { type IntervalHistogram, monitorEventLoopDelay, performance } from 'node:perf_hooks'\n\n/**\n * Worker metrics data structure used internally for OTEL metric collection.\n */\nexport type WorkerMetrics = {\n memory_heap_used?: number\n memory_heap_total?: number\n memory_rss?: number\n memory_external?: number\n cpu_user_micros?: number\n cpu_system_micros?: number\n cpu_percent?: number\n event_loop_lag_ms?: number\n uptime_seconds?: number\n timestamp_ms: number\n runtime: string\n}\n\n/**\n * Configuration options for the WorkerMetricsCollector.\n */\nexport interface WorkerMetricsCollectorOptions {\n /**\n * Event loop delay histogram resolution in milliseconds.\n * Lower values provide more accurate measurements but use more resources.\n * @default 20\n */\n eventLoopResolutionMs?: number\n}\n\n/**\n * Collects worker resource metrics including CPU, memory, and event loop lag.\n *\n * Uses the Node.js `monitorEventLoopDelay` API for high-precision event loop\n * delay measurements instead of manual `setImmediate` timing.\n *\n * @example\n * ```typescript\n * const collector = new WorkerMetricsCollector()\n *\n * // Collect metrics periodically\n * setInterval(() => {\n * const metrics = collector.collect()\n * console.log('CPU:', metrics.cpu_percent, '%')\n * console.log('Event Loop Lag:', metrics.event_loop_lag_ms, 'ms')\n * }, 5000)\n *\n * // Clean up when done\n * collector.stopMonitoring()\n * ```\n */\nexport class WorkerMetricsCollector {\n private readonly startTime: number\n private lastCpuUsage: NodeJS.CpuUsage\n private lastCpuTime: number\n private eventLoopHistogram: IntervalHistogram | null = null\n\n /**\n * Creates a new WorkerMetricsCollector instance.\n *\n * @param options - Configuration options\n */\n constructor(options: WorkerMetricsCollectorOptions = {}) {\n this.startTime = Date.now()\n this.lastCpuUsage = process.cpuUsage()\n this.lastCpuTime = performance.now()\n this.startEventLoopMonitoring(options.eventLoopResolutionMs ?? 20)\n }\n\n /**\n * Starts the event loop delay histogram monitoring.\n *\n * @param resolutionMs - Histogram resolution in milliseconds\n */\n private startEventLoopMonitoring(resolutionMs: number): void {\n // Sanitize resolution: must be a positive finite number, minimum 1ms\n const safeResolutionMs =\n Number.isFinite(resolutionMs) && resolutionMs > 0 ? Math.max(1, Math.floor(resolutionMs)) : 20 // Default fallback\n\n this.eventLoopHistogram = monitorEventLoopDelay({ resolution: safeResolutionMs })\n this.eventLoopHistogram.enable()\n }\n\n /**\n * Stops the event loop monitoring and releases resources.\n * Should be called when the collector is no longer needed.\n */\n public stopMonitoring(): void {\n if (this.eventLoopHistogram) {\n this.eventLoopHistogram.disable()\n this.eventLoopHistogram = null\n }\n }\n\n /**\n * Collects current worker metrics.\n *\n * This method calculates CPU usage since the last collection,\n * reads memory usage, and gets event loop delay statistics.\n * The event loop histogram is reset after each collection for\n * accurate per-interval measurements.\n *\n * @returns Current worker metrics snapshot\n */\n collect(): WorkerMetrics {\n const memoryUsage = process.memoryUsage()\n const cpuUsage = process.cpuUsage()\n const now = performance.now()\n\n // Calculate CPU percentage since last collection\n const cpuDelta = {\n user: cpuUsage.user - this.lastCpuUsage.user,\n system: cpuUsage.system - this.lastCpuUsage.system,\n }\n const timeDelta = (now - this.lastCpuTime) * 1000 // Convert ms to microseconds\n const cpuPercent = timeDelta > 0 ? ((cpuDelta.user + cpuDelta.system) / timeDelta) * 100 : 0\n\n // Update state for next collection\n this.lastCpuUsage = cpuUsage\n this.lastCpuTime = now\n\n // Get event loop lag from histogram (in nanoseconds, convert to ms)\n let eventLoopLagMs = 0\n if (this.eventLoopHistogram) {\n // Mean is in nanoseconds, convert to milliseconds\n eventLoopLagMs = this.eventLoopHistogram.mean / 1_000_000\n // Reset histogram for next collection interval\n this.eventLoopHistogram.reset()\n }\n\n return {\n memory_heap_used: memoryUsage.heapUsed,\n memory_heap_total: memoryUsage.heapTotal,\n memory_rss: memoryUsage.rss,\n memory_external: memoryUsage.external,\n cpu_user_micros: cpuUsage.user,\n cpu_system_micros: cpuUsage.system,\n cpu_percent: Math.min(cpuPercent, 100), // Cap at 100%\n event_loop_lag_ms: eventLoopLagMs,\n uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000),\n timestamp_ms: Date.now(),\n runtime: 'node',\n }\n }\n}\n","import type { Meter, BatchObservableResult, Observable } from '@opentelemetry/api'\nimport { WorkerMetricsCollector } from './worker-metrics'\n\nexport interface WorkerGaugesOptions {\n workerId: string\n workerName?: string\n}\n\nlet registeredGauges = false\nlet metricsCollector: WorkerMetricsCollector | null = null\nlet registeredMeter: Meter | null = null\nlet registeredBatchCallback: ((observableResult: BatchObservableResult) => void) | null = null\nlet registeredObservables: Observable[] = []\n\nexport function registerWorkerGauges(meter: Meter, options: WorkerGaugesOptions): void {\n if (registeredGauges) {\n return\n }\n\n const { workerId, workerName } = options\n const baseAttributes = {\n 'worker.id': workerId,\n ...(workerName && { 'worker.name': workerName }),\n }\n\n metricsCollector = new WorkerMetricsCollector()\n\n const memoryHeapUsed = meter.createObservableGauge('iii.worker.memory.heap_used', {\n description: 'Worker heap memory used in bytes',\n unit: 'bytes',\n })\n\n const memoryHeapTotal = meter.createObservableGauge('iii.worker.memory.heap_total', {\n description: 'Worker total heap memory in bytes',\n unit: 'bytes',\n })\n\n const memoryRss = meter.createObservableGauge('iii.worker.memory.rss', {\n description: 'Worker resident set size in bytes',\n unit: 'bytes',\n })\n\n const memoryExternal = meter.createObservableGauge('iii.worker.memory.external', {\n description: 'Worker external memory in bytes',\n unit: 'bytes',\n })\n\n const cpuPercent = meter.createObservableGauge('iii.worker.cpu.percent', {\n description: 'Worker CPU usage percentage',\n unit: '%',\n })\n\n const cpuUserMicros = meter.createObservableGauge('iii.worker.cpu.user_micros', {\n description: 'Worker CPU user time in microseconds',\n unit: 'us',\n })\n\n const cpuSystemMicros = meter.createObservableGauge('iii.worker.cpu.system_micros', {\n description: 'Worker CPU system time in microseconds',\n unit: 'us',\n })\n\n const eventLoopLag = meter.createObservableGauge('iii.worker.event_loop.lag_ms', {\n description: 'Worker event loop lag in milliseconds',\n unit: 'ms',\n })\n\n const uptimeSeconds = meter.createObservableGauge('iii.worker.uptime_seconds', {\n description: 'Worker uptime in seconds',\n unit: 's',\n })\n\n const batchCallback = (observableResult: BatchObservableResult) => {\n if (!metricsCollector) return\n\n const metrics = metricsCollector.collect()\n\n if (metrics.memory_heap_used !== undefined) {\n observableResult.observe(memoryHeapUsed, metrics.memory_heap_used, baseAttributes)\n }\n if (metrics.memory_heap_total !== undefined) {\n observableResult.observe(memoryHeapTotal, metrics.memory_heap_total, baseAttributes)\n }\n if (metrics.memory_rss !== undefined) {\n observableResult.observe(memoryRss, metrics.memory_rss, baseAttributes)\n }\n if (metrics.memory_external !== undefined) {\n observableResult.observe(memoryExternal, metrics.memory_external, baseAttributes)\n }\n if (metrics.cpu_percent !== undefined) {\n observableResult.observe(cpuPercent, metrics.cpu_percent, baseAttributes)\n }\n if (metrics.cpu_user_micros !== undefined) {\n observableResult.observe(cpuUserMicros, metrics.cpu_user_micros, baseAttributes)\n }\n if (metrics.cpu_system_micros !== undefined) {\n observableResult.observe(cpuSystemMicros, metrics.cpu_system_micros, baseAttributes)\n }\n if (metrics.event_loop_lag_ms !== undefined) {\n observableResult.observe(eventLoopLag, metrics.event_loop_lag_ms, baseAttributes)\n }\n if (metrics.uptime_seconds !== undefined) {\n observableResult.observe(uptimeSeconds, metrics.uptime_seconds, baseAttributes)\n }\n }\n\n meter.addBatchObservableCallback(batchCallback, [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ])\n\n registeredMeter = meter\n registeredBatchCallback = batchCallback\n registeredObservables = [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ]\n\n registeredGauges = true\n}\n\nexport function stopWorkerGauges(): void {\n // Remove the batch observable callback before stopping\n if (registeredMeter && registeredBatchCallback) {\n registeredMeter.removeBatchObservableCallback(registeredBatchCallback, registeredObservables)\n }\n\n if (metricsCollector) {\n metricsCollector.stopMonitoring()\n metricsCollector = null\n }\n\n registeredMeter = null\n registeredBatchCallback = null\n registeredObservables = []\n registeredGauges = false\n}\n","/**\n * Safely stringify a value, handling circular references, BigInt, and other edge cases.\n * Returns \"[unserializable]\" if serialization fails for any reason.\n */\nexport function safeStringify(value: unknown): string {\n const seen = new WeakSet<object>()\n\n try {\n const result = JSON.stringify(value, (_key, val) => {\n // Handle BigInt\n if (typeof val === 'bigint') {\n return val.toString()\n }\n\n // Handle circular references\n if (val !== null && typeof val === 'object') {\n if (seen.has(val)) {\n return '[Circular]'\n }\n seen.add(val)\n }\n\n return val\n })\n return result ?? '[unserializable]'\n } catch {\n return '[unserializable]'\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,SAAb,MAAoB;CAClB,AAAQ,cAAuD;CAE/D,IAAY,aAAa;AAEvB,MAAI,CAAC,KAAK,YACR,MAAK,cAAcA,oCAAe;AAEpC,SAAO,KAAK;;CAGd,YACE,AAAiB,SACjB,AAAiB,aACjB,AAAiB,QACjB;EAHiB;EACA;EACA;;CAGnB,AAAQ,KAAK,SAAiB,UAA0B,MAAsB;EAC5E,MAAM,aAA0B,EAAE;EAClC,MAAM,UAAU,KAAK,WAAWC,yCAAgB;EAChD,MAAM,SAAS,KAAK,UAAUC,wCAAe;AAE7C,MAAI,QACF,YAAW,WAAW;AAExB,MAAI,OACF,YAAW,UAAU;AAEvB,MAAI,KAAK,YACP,YAAW,kBAAkB,KAAK;AAEpC,MAAI,SAAS,OACX,YAAW,cAAc;AAG3B,MAAI,KAAK,WACP,MAAK,WAAW,KAAK;GACnB,gBAAgB;GAChB,MAAM;GACN,YAAY,OAAO,KAAK,WAAW,CAAC,SAAS,I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A;EACA;EACA;EACA;EACA;EACD;AAED,oBAAmB;;AAGrB,SAAgB,mBAAyB;AAEvC,KAAI,mBAAmB,wBACrB,iBAAgB,8BAA8B,yBAAyB,sBAAsB;AAG/F,KAAI,kBAAkB;AACpB,mBAAiB,gBAAgB;AACjC,qBAAmB;;AAGrB,mBAAkB;AAClB,2BAA0B;AAC1B,yBAAwB,EAAE;AAC1B,oBAAmB;;;;;;;;;ACjJrB,SAAgB,cAAc,OAAwB;CACpD,MAAM,uBAAO,IAAI,SAAiB;AAElC,KAAI;AAiBF,SAhBe,KAAK,UAAU,QAAQ,MAAM,QAAQ;AAElD,OAAI,OAAO,QAAQ,SACjB,QAAO,IAAI,UAAU;AAIvB,OAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;AAC3C,QAAI,KAAK,IAAI,IAAI,CACf,QAAO;AAET,SAAK,IAAI,IAAI;;AAGf,UAAO;IACP,IACe;SACX;AACN,SAAO"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["getOtelLogger","currentTraceId","currentSpanId","SeverityNumber","trace","SpanKind","otelContext","SpanStatusCode","performance"],"sources":["../../src/observability/logger.ts","../../src/observability/http-instrumentation.ts","../../src/observability/worker-metrics.ts","../../src/observability/otel-worker-gauges.ts","../../src/observability/utils.ts"],"sourcesContent":["import { AnyValue, AnyValueMap, SeverityNumber } from '@opentelemetry/api-logs'\nimport {\n currentSpanId,\n currentTraceId,\n getLogger as getOtelLogger,\n} from './telemetry-system'\n\n/** @internal */\nexport type LoggerParams = {\n message: string\n trace_id?: string\n span_id?: string\n service_name?: string\n data?: unknown\n /** @deprecated Use service_name instead */\n function_name?: string\n}\n\n/**\n * Structured logger that emits logs as OpenTelemetry LogRecords.\n *\n * Every log call automatically captures the active trace and span context,\n * correlating your logs with distributed traces without any manual wiring.\n * When OTel is not initialized, Logger gracefully falls back to `console.*`.\n *\n * Pass structured data as the second argument to any log method. Using an\n * object of key-value pairs (instead of string interpolation) lets you\n * filter, aggregate, and build dashboards in your observability backend.\n *\n * @example\n * ```typescript\n * import { Logger } from 'iii-sdk'\n *\n * const logger = new Logger()\n *\n * // Basic logging, trace context is injected automatically\n * logger.info('Worker connected')\n *\n * // Structured context for dashboards and alerting\n * logger.info('Order processed', { orderId: 'ord_123', amount: 49.99, currency: 'USD' })\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\nexport class Logger {\n private _otelLogger: ReturnType<typeof getOtelLogger> | null = null\n\n private get otelLogger() {\n // Lazy initialization: re-fetch logger if not yet available\n if (!this._otelLogger) {\n this._otelLogger = getOtelLogger()\n }\n return this._otelLogger\n }\n\n constructor(\n private readonly traceId?: string,\n private readonly serviceName?: string,\n private readonly spanId?: string,\n ) {}\n\n private emit(message: string, severity: SeverityNumber, data?: unknown): void {\n const attributes: AnyValueMap = {}\n const traceId = this.traceId ?? currentTraceId()\n const spanId = this.spanId ?? currentSpanId()\n\n if (traceId) {\n attributes.trace_id = traceId\n }\n if (spanId) {\n attributes.span_id = spanId\n }\n if (this.serviceName) {\n attributes['service.name'] = this.serviceName\n }\n if (data !== undefined) {\n attributes['log.data'] = data as AnyValue\n }\n\n if (this.otelLogger) {\n this.otelLogger.emit({\n severityNumber: severity,\n body: message,\n attributes: Object.keys(attributes).length > 0 ? attributes : undefined,\n })\n } else {\n // Fallback to console when OTEL is not available\n switch (severity) {\n case SeverityNumber.DEBUG:\n console.debug(message, data)\n break\n case SeverityNumber.INFO:\n console.info(message, data)\n break\n case SeverityNumber.WARN:\n console.warn(message, data)\n break\n case SeverityNumber.ERROR:\n console.error(message, data)\n break\n default:\n console.log(message, data)\n }\n }\n }\n\n /**\n * Log an info-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.info('Order processed', { orderId: 'ord_123', status: 'completed' })\n * ```\n */\n info(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.INFO, data)\n }\n\n /**\n * Log a warning-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * ```\n */\n warn(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.WARN, data)\n }\n\n /**\n * Log an error-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\n error(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.ERROR, data)\n }\n\n /**\n * Log a debug-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.debug('Cache lookup', { key: 'user:42', hit: false })\n * ```\n */\n debug(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.DEBUG, data)\n }\n}\n","import { context as otelContext, propagation, SpanKind, SpanStatusCode, trace, type Tracer } from '@opentelemetry/api'\n\nconst SAFE_REQUEST_HEADERS = ['content-type', 'accept'] as const\nconst SAFE_RESPONSE_HEADERS = ['content-type'] as const\n\nexport interface TracedFetchInit extends RequestInit {\n tracer?: Tracer\n}\n\n/**\n * Execute a fetch request inside an OTel CLIENT span.\n *\n * Mirrors the Rust execute_traced_request shape: injects W3C traceparent into\n * outgoing headers, records HTTP semantic-convention attributes, and sets\n * ERROR span status for HTTP responses with status >= 400 or network errors.\n */\nexport async function executeTracedRequest(\n input: RequestInfo | URL,\n init?: TracedFetchInit,\n): Promise<Response> {\n const tracer = init?.tracer ?? trace.getTracer('iii-node-sdk')\n const rawUrl = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n let url: URL | null\n try {\n url = new URL(rawUrl)\n } catch {\n url = null\n }\n const method = (init?.method ?? (typeof input === 'object' && 'method' in input ? input.method : 'GET') ?? 'GET').toUpperCase()\n const name = url?.pathname ? `${method} ${url.pathname}` : method\n\n return tracer.startActiveSpan(\n name,\n {\n kind: SpanKind.CLIENT,\n attributes: {\n 'http.request.method': method,\n 'url.full': url?.toString() ?? rawUrl,\n 'network.protocol.name': 'http',\n ...(url\n ? {\n 'server.address': url.hostname,\n 'url.scheme': url.protocol.replace(':', ''),\n 'url.path': url.pathname,\n }\n : {}),\n ...(url?.port ? { 'server.port': Number(url.port) } : {}),\n ...(url?.search ? { 'url.query': url.search.slice(1) } : {}),\n },\n },\n async (span) => {\n try {\n // Seed with the Request's own headers so they survive when caller\n // passes a Request object; init.headers (if any) then overrides.\n const baseHeaders =\n typeof input === 'object' && 'headers' in input ? input.headers : undefined\n const headers = new Headers(baseHeaders)\n if (init?.headers) {\n for (const [k, v] of new Headers(init.headers).entries()) headers.set(k, v)\n }\n const carrier: Record<string, string> = {}\n propagation.inject(otelContext.active(), carrier)\n for (const [k, v] of Object.entries(carrier)) headers.set(k, v)\n\n for (const h of SAFE_REQUEST_HEADERS) {\n const v = headers.get(h)\n if (v) span.setAttribute(`http.request.header.${h}`, v)\n }\n\n const response = await fetch(input, { ...init, headers })\n span.setAttribute('http.response.status_code', response.status)\n const cl = response.headers.get('content-length')\n if (cl) span.setAttribute('http.response.body.size', Number(cl))\n for (const h of SAFE_RESPONSE_HEADERS) {\n const v = response.headers.get(h)\n if (v) span.setAttribute(`http.response.header.${h}`, v)\n }\n\n if (response.status >= 400) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: String(response.status) })\n span.setAttribute('error.type', String(response.status))\n } else {\n span.setStatus({ code: SpanStatusCode.OK })\n }\n return response\n } catch (err) {\n const error = err as Error\n span.recordException(error)\n span.setStatus({ code: SpanStatusCode.ERROR, message: error.message })\n span.setAttribute('error.type', error.name)\n throw err\n } finally {\n span.end()\n }\n },\n )\n}\n","/**\n * Worker metrics collection for the III Node SDK.\n *\n * Collects CPU, memory, and event loop metrics for worker health monitoring.\n * Uses the Node.js built-in `monitorEventLoopDelay` API for accurate\n * event loop lag measurements.\n */\n\nimport { type IntervalHistogram, monitorEventLoopDelay, performance } from 'node:perf_hooks'\n\n/**\n * Worker metrics data structure used internally for OTEL metric collection.\n */\nexport type WorkerMetrics = {\n memory_heap_used?: number\n memory_heap_total?: number\n memory_rss?: number\n memory_external?: number\n cpu_user_micros?: number\n cpu_system_micros?: number\n cpu_percent?: number\n event_loop_lag_ms?: number\n uptime_seconds?: number\n timestamp_ms: number\n runtime: string\n}\n\n/**\n * Configuration options for the WorkerMetricsCollector.\n */\nexport interface WorkerMetricsCollectorOptions {\n /**\n * Event loop delay histogram resolution in milliseconds.\n * Lower values provide more accurate measurements but use more resources.\n * @default 20\n */\n eventLoopResolutionMs?: number\n}\n\n/**\n * Collects worker resource metrics including CPU, memory, and event loop lag.\n *\n * Uses the Node.js `monitorEventLoopDelay` API for high-precision event loop\n * delay measurements instead of manual `setImmediate` timing.\n *\n * @example\n * ```typescript\n * const collector = new WorkerMetricsCollector()\n *\n * // Collect metrics periodically\n * setInterval(() => {\n * const metrics = collector.collect()\n * console.log('CPU:', metrics.cpu_percent, '%')\n * console.log('Event Loop Lag:', metrics.event_loop_lag_ms, 'ms')\n * }, 5000)\n *\n * // Clean up when done\n * collector.stopMonitoring()\n * ```\n */\nexport class WorkerMetricsCollector {\n private readonly startTime: number\n private lastCpuUsage: NodeJS.CpuUsage\n private lastCpuTime: number\n private eventLoopHistogram: IntervalHistogram | null = null\n\n /**\n * Creates a new WorkerMetricsCollector instance.\n *\n * @param options - Configuration options\n */\n constructor(options: WorkerMetricsCollectorOptions = {}) {\n this.startTime = Date.now()\n this.lastCpuUsage = process.cpuUsage()\n this.lastCpuTime = performance.now()\n this.startEventLoopMonitoring(options.eventLoopResolutionMs ?? 20)\n }\n\n /**\n * Starts the event loop delay histogram monitoring.\n *\n * @param resolutionMs - Histogram resolution in milliseconds\n */\n private startEventLoopMonitoring(resolutionMs: number): void {\n // Sanitize resolution: must be a positive finite number, minimum 1ms\n const safeResolutionMs =\n Number.isFinite(resolutionMs) && resolutionMs > 0 ? Math.max(1, Math.floor(resolutionMs)) : 20 // Default fallback\n\n this.eventLoopHistogram = monitorEventLoopDelay({ resolution: safeResolutionMs })\n this.eventLoopHistogram.enable()\n }\n\n /**\n * Stops the event loop monitoring and releases resources.\n * Should be called when the collector is no longer needed.\n */\n public stopMonitoring(): void {\n if (this.eventLoopHistogram) {\n this.eventLoopHistogram.disable()\n this.eventLoopHistogram = null\n }\n }\n\n /**\n * Collects current worker metrics.\n *\n * This method calculates CPU usage since the last collection,\n * reads memory usage, and gets event loop delay statistics.\n * The event loop histogram is reset after each collection for\n * accurate per-interval measurements.\n *\n * @returns Current worker metrics snapshot\n */\n collect(): WorkerMetrics {\n const memoryUsage = process.memoryUsage()\n const cpuUsage = process.cpuUsage()\n const now = performance.now()\n\n // Calculate CPU percentage since last collection\n const cpuDelta = {\n user: cpuUsage.user - this.lastCpuUsage.user,\n system: cpuUsage.system - this.lastCpuUsage.system,\n }\n const timeDelta = (now - this.lastCpuTime) * 1000 // Convert ms to microseconds\n const cpuPercent = timeDelta > 0 ? ((cpuDelta.user + cpuDelta.system) / timeDelta) * 100 : 0\n\n // Update state for next collection\n this.lastCpuUsage = cpuUsage\n this.lastCpuTime = now\n\n // Get event loop lag from histogram (in nanoseconds, convert to ms)\n let eventLoopLagMs = 0\n if (this.eventLoopHistogram) {\n // Mean is in nanoseconds, convert to milliseconds\n eventLoopLagMs = this.eventLoopHistogram.mean / 1_000_000\n // Reset histogram for next collection interval\n this.eventLoopHistogram.reset()\n }\n\n return {\n memory_heap_used: memoryUsage.heapUsed,\n memory_heap_total: memoryUsage.heapTotal,\n memory_rss: memoryUsage.rss,\n memory_external: memoryUsage.external,\n cpu_user_micros: cpuUsage.user,\n cpu_system_micros: cpuUsage.system,\n cpu_percent: Math.min(cpuPercent, 100), // Cap at 100%\n event_loop_lag_ms: eventLoopLagMs,\n uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000),\n timestamp_ms: Date.now(),\n runtime: 'node',\n }\n }\n}\n","import type { Meter, BatchObservableResult, Observable } from '@opentelemetry/api'\nimport { WorkerMetricsCollector } from './worker-metrics'\n\nexport interface WorkerGaugesOptions {\n workerId: string\n workerName?: string\n}\n\nlet registeredGauges = false\nlet metricsCollector: WorkerMetricsCollector | null = null\nlet registeredMeter: Meter | null = null\nlet registeredBatchCallback: ((observableResult: BatchObservableResult) => void) | null = null\nlet registeredObservables: Observable[] = []\n\nexport function registerWorkerGauges(meter: Meter, options: WorkerGaugesOptions): void {\n if (registeredGauges) {\n return\n }\n\n const { workerId, workerName } = options\n const baseAttributes = {\n 'worker.id': workerId,\n ...(workerName && { 'worker.name': workerName }),\n }\n\n metricsCollector = new WorkerMetricsCollector()\n\n const memoryHeapUsed = meter.createObservableGauge('iii.worker.memory.heap_used', {\n description: 'Worker heap memory used in bytes',\n unit: 'bytes',\n })\n\n const memoryHeapTotal = meter.createObservableGauge('iii.worker.memory.heap_total', {\n description: 'Worker total heap memory in bytes',\n unit: 'bytes',\n })\n\n const memoryRss = meter.createObservableGauge('iii.worker.memory.rss', {\n description: 'Worker resident set size in bytes',\n unit: 'bytes',\n })\n\n const memoryExternal = meter.createObservableGauge('iii.worker.memory.external', {\n description: 'Worker external memory in bytes',\n unit: 'bytes',\n })\n\n const cpuPercent = meter.createObservableGauge('iii.worker.cpu.percent', {\n description: 'Worker CPU usage percentage',\n unit: '%',\n })\n\n const cpuUserMicros = meter.createObservableGauge('iii.worker.cpu.user_micros', {\n description: 'Worker CPU user time in microseconds',\n unit: 'us',\n })\n\n const cpuSystemMicros = meter.createObservableGauge('iii.worker.cpu.system_micros', {\n description: 'Worker CPU system time in microseconds',\n unit: 'us',\n })\n\n const eventLoopLag = meter.createObservableGauge('iii.worker.event_loop.lag_ms', {\n description: 'Worker event loop lag in milliseconds',\n unit: 'ms',\n })\n\n const uptimeSeconds = meter.createObservableGauge('iii.worker.uptime_seconds', {\n description: 'Worker uptime in seconds',\n unit: 's',\n })\n\n const batchCallback = (observableResult: BatchObservableResult) => {\n if (!metricsCollector) return\n\n const metrics = metricsCollector.collect()\n\n if (metrics.memory_heap_used !== undefined) {\n observableResult.observe(memoryHeapUsed, metrics.memory_heap_used, baseAttributes)\n }\n if (metrics.memory_heap_total !== undefined) {\n observableResult.observe(memoryHeapTotal, metrics.memory_heap_total, baseAttributes)\n }\n if (metrics.memory_rss !== undefined) {\n observableResult.observe(memoryRss, metrics.memory_rss, baseAttributes)\n }\n if (metrics.memory_external !== undefined) {\n observableResult.observe(memoryExternal, metrics.memory_external, baseAttributes)\n }\n if (metrics.cpu_percent !== undefined) {\n observableResult.observe(cpuPercent, metrics.cpu_percent, baseAttributes)\n }\n if (metrics.cpu_user_micros !== undefined) {\n observableResult.observe(cpuUserMicros, metrics.cpu_user_micros, baseAttributes)\n }\n if (metrics.cpu_system_micros !== undefined) {\n observableResult.observe(cpuSystemMicros, metrics.cpu_system_micros, baseAttributes)\n }\n if (metrics.event_loop_lag_ms !== undefined) {\n observableResult.observe(eventLoopLag, metrics.event_loop_lag_ms, baseAttributes)\n }\n if (metrics.uptime_seconds !== undefined) {\n observableResult.observe(uptimeSeconds, metrics.uptime_seconds, baseAttributes)\n }\n }\n\n meter.addBatchObservableCallback(batchCallback, [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ])\n\n registeredMeter = meter\n registeredBatchCallback = batchCallback\n registeredObservables = [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ]\n\n registeredGauges = true\n}\n\nexport function stopWorkerGauges(): void {\n // Remove the batch observable callback before stopping\n if (registeredMeter && registeredBatchCallback) {\n registeredMeter.removeBatchObservableCallback(registeredBatchCallback, registeredObservables)\n }\n\n if (metricsCollector) {\n metricsCollector.stopMonitoring()\n metricsCollector = null\n }\n\n registeredMeter = null\n registeredBatchCallback = null\n registeredObservables = []\n registeredGauges = false\n}\n","/**\n * Safely stringify a value, handling circular references, BigInt, and other edge cases.\n * Returns \"[unserializable]\" if serialization fails for any reason.\n */\nexport function safeStringify(value: unknown): string {\n const seen = new WeakSet<object>()\n\n try {\n const result = JSON.stringify(value, (_key, val) => {\n // Handle BigInt\n if (typeof val === 'bigint') {\n return val.toString()\n }\n\n // Handle circular references\n if (val !== null && typeof val === 'object') {\n if (seen.has(val)) {\n return '[Circular]'\n }\n seen.add(val)\n }\n\n return val\n })\n return result ?? '[unserializable]'\n } catch {\n return '[unserializable]'\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,SAAb,MAAoB;CAClB,AAAQ,cAAuD;CAE/D,IAAY,aAAa;AAEvB,MAAI,CAAC,KAAK,YACR,MAAK,cAAcA,oCAAe;AAEpC,SAAO,KAAK;;CAGd,YACE,AAAiB,SACjB,AAAiB,aACjB,AAAiB,QACjB;EAHiB;EACA;EACA;;CAGnB,AAAQ,KAAK,SAAiB,UAA0B,MAAsB;EAC5E,MAAM,aAA0B,EAAE;EAClC,MAAM,UAAU,KAAK,WAAWC,yCAAgB;EAChD,MAAM,SAAS,KAAK,UAAUC,wCAAe;AAE7C,MAAI,QACF,YAAW,WAAW;AAExB,MAAI,OACF,YAAW,UAAU;AAEvB,MAAI,KAAK,YACP,YAAW,kBAAkB,KAAK;AAEpC,MAAI,SAAS,OACX,YAAW,cAAc;AAG3B,MA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ACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAEF,mBAAkB;AAClB,2BAA0B;AAC1B,yBAAwB;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD;AAED,oBAAmB;;AAGrB,SAAgB,mBAAyB;AAEvC,KAAI,mBAAmB,wBACrB,iBAAgB,8BAA8B,yBAAyB,sBAAsB;AAG/F,KAAI,kBAAkB;AACpB,mBAAiB,gBAAgB;AACjC,qBAAmB;;AAGrB,mBAAkB;AAClB,2BAA0B;AAC1B,yBAAwB,EAAE;AAC1B,oBAAmB;;;;;;;;;ACjJrB,SAAgB,cAAc,OAAwB;CACpD,MAAM,uBAAO,IAAI,SAAiB;AAElC,KAAI;AAiBF,SAhBe,KAAK,UAAU,QAAQ,MAAM,QAAQ;AAElD,OAAI,OAAO,QAAQ,SACjB,QAAO,IAAI,UAAU;AAIvB,OAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;AAC3C,QAAI,KAAK,IAAI,IAAI,CACf,QAAO;AAET,SAAK,IAAI,IAAI;;AAGf,UAAO;IACP,IACe;SACX;AACN,SAAO"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as injectTraceparent, C as currentTraceId, D as getAllBaggage, E as extractTraceparent, M as setBaggageEntry, N as OtelConfig, O as getBaggageEntry, P as ReconnectionConfig, S as currentSpanId, T as extractContext, _ as recordSpanEvent, a as flushOtel, b as BaggageSpanProcessor, d as withSpan, f as REDACTED_PLACEHOLDER, g as currentSpanIsRecording, h as resolveMaxBytesFromEnv, i as Span, j as removeBaggageEntry, k as injectBaggage, l as initOtel, m as redactAndTruncate, n as Meter, o as getLogger, p as redact, r as SeverityNumber, t as Logger$1, u as shutdownOtel, v as setCurrentSpanAttribute, w as extractBaggage, x as DEFAULT_ALLOWLIST, y as setCurrentSpanError } from "../index-
|
|
1
|
+
import { A as injectTraceparent, C as currentTraceId, D as getAllBaggage, E as extractTraceparent, M as setBaggageEntry, N as OtelConfig, O as getBaggageEntry, P as ReconnectionConfig, S as currentSpanId, T as extractContext, _ as recordSpanEvent, a as flushOtel, b as BaggageSpanProcessor, d as withSpan, f as REDACTED_PLACEHOLDER, g as currentSpanIsRecording, h as resolveMaxBytesFromEnv, i as Span, j as removeBaggageEntry, k as injectBaggage, l as initOtel, m as redactAndTruncate, n as Meter, o as getLogger, p as redact, r as SeverityNumber, t as Logger$1, u as shutdownOtel, v as setCurrentSpanAttribute, w as extractBaggage, x as DEFAULT_ALLOWLIST, y as setCurrentSpanError } from "../index-B2thODQm.cjs";
|
|
2
2
|
import { Meter as Meter$1, Tracer } from "@opentelemetry/api";
|
|
3
3
|
|
|
4
4
|
//#region src/observability/logger.d.ts
|
|
@@ -19,7 +19,7 @@ import { Meter as Meter$1, Tracer } from "@opentelemetry/api";
|
|
|
19
19
|
*
|
|
20
20
|
* const logger = new Logger()
|
|
21
21
|
*
|
|
22
|
-
* // Basic logging
|
|
22
|
+
* // Basic logging, trace context is injected automatically
|
|
23
23
|
* logger.info('Worker connected')
|
|
24
24
|
*
|
|
25
25
|
* // Structured context for dashboards and alerting
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as injectTraceparent, C as currentTraceId, D as getAllBaggage, E as extractTraceparent, M as setBaggageEntry, N as OtelConfig, O as getBaggageEntry, P as ReconnectionConfig, S as currentSpanId, T as extractContext, _ as recordSpanEvent, a as flushOtel, b as BaggageSpanProcessor, d as withSpan, f as REDACTED_PLACEHOLDER, g as currentSpanIsRecording, h as resolveMaxBytesFromEnv, i as Span, j as removeBaggageEntry, k as injectBaggage, l as initOtel, m as redactAndTruncate, n as Meter, o as getLogger, p as redact, r as SeverityNumber, t as Logger$1, u as shutdownOtel, v as setCurrentSpanAttribute, w as extractBaggage, x as DEFAULT_ALLOWLIST, y as setCurrentSpanError } from "../index-
|
|
1
|
+
import { A as injectTraceparent, C as currentTraceId, D as getAllBaggage, E as extractTraceparent, M as setBaggageEntry, N as OtelConfig, O as getBaggageEntry, P as ReconnectionConfig, S as currentSpanId, T as extractContext, _ as recordSpanEvent, a as flushOtel, b as BaggageSpanProcessor, d as withSpan, f as REDACTED_PLACEHOLDER, g as currentSpanIsRecording, h as resolveMaxBytesFromEnv, i as Span, j as removeBaggageEntry, k as injectBaggage, l as initOtel, m as redactAndTruncate, n as Meter, o as getLogger, p as redact, r as SeverityNumber, t as Logger$1, u as shutdownOtel, v as setCurrentSpanAttribute, w as extractBaggage, x as DEFAULT_ALLOWLIST, y as setCurrentSpanError } from "../index-Cr3b3Tmk.mjs";
|
|
2
2
|
import { Meter as Meter$1, Tracer } from "@opentelemetry/api";
|
|
3
3
|
|
|
4
4
|
//#region src/observability/logger.d.ts
|
|
@@ -19,7 +19,7 @@ import { Meter as Meter$1, Tracer } from "@opentelemetry/api";
|
|
|
19
19
|
*
|
|
20
20
|
* const logger = new Logger()
|
|
21
21
|
*
|
|
22
|
-
* // Basic logging
|
|
22
|
+
* // Basic logging, trace context is injected automatically
|
|
23
23
|
* logger.info('Worker connected')
|
|
24
24
|
*
|
|
25
25
|
* // Structured context for dashboards and alerting
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as BaggageSpanProcessor, C as extractTraceparent, D as injectTraceparent, E as injectBaggage, O as removeBaggageEntry, S as extractContext, T as getBaggageEntry, _ as patchGlobalFetch, b as currentTraceId, c as withSpan, d as redactAndTruncate, f as resolveMaxBytesFromEnv, g as setCurrentSpanError, h as setCurrentSpanAttribute, j as DEFAULT_ALLOWLIST, k as setBaggageEntry, l as REDACTED_PLACEHOLDER, m as recordSpanEvent, n as flushOtel, o as initOtel, p as currentSpanIsRecording, r as getLogger, s as shutdownOtel, t as SeverityNumber, u as redact, v as unpatchGlobalFetch, w as getAllBaggage, x as extractBaggage, y as currentSpanId } from "../telemetry-system-
|
|
1
|
+
import { A as BaggageSpanProcessor, C as extractTraceparent, D as injectTraceparent, E as injectBaggage, O as removeBaggageEntry, S as extractContext, T as getBaggageEntry, _ as patchGlobalFetch, b as currentTraceId, c as withSpan, d as redactAndTruncate, f as resolveMaxBytesFromEnv, g as setCurrentSpanError, h as setCurrentSpanAttribute, j as DEFAULT_ALLOWLIST, k as setBaggageEntry, l as REDACTED_PLACEHOLDER, m as recordSpanEvent, n as flushOtel, o as initOtel, p as currentSpanIsRecording, r as getLogger, s as shutdownOtel, t as SeverityNumber, u as redact, v as unpatchGlobalFetch, w as getAllBaggage, x as extractBaggage, y as currentSpanId } from "../telemetry-system-DZc-9gY3.mjs";
|
|
2
2
|
import { SeverityNumber as SeverityNumber$1 } from "@opentelemetry/api-logs";
|
|
3
3
|
import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
|
|
4
4
|
import { monitorEventLoopDelay, performance } from "node:perf_hooks";
|
|
@@ -21,7 +21,7 @@ import { monitorEventLoopDelay, performance } from "node:perf_hooks";
|
|
|
21
21
|
*
|
|
22
22
|
* const logger = new Logger()
|
|
23
23
|
*
|
|
24
|
-
* // Basic logging
|
|
24
|
+
* // Basic logging, trace context is injected automatically
|
|
25
25
|
* logger.info('Worker connected')
|
|
26
26
|
*
|
|
27
27
|
* // Structured context for dashboards and alerting
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["getOtelLogger","SeverityNumber","otelContext"],"sources":["../../src/observability/logger.ts","../../src/observability/http-instrumentation.ts","../../src/observability/worker-metrics.ts","../../src/observability/otel-worker-gauges.ts","../../src/observability/utils.ts"],"sourcesContent":["import { AnyValue, AnyValueMap, SeverityNumber } from '@opentelemetry/api-logs'\nimport {\n currentSpanId,\n currentTraceId,\n getLogger as getOtelLogger,\n} from './telemetry-system'\n\n/** @internal */\nexport type LoggerParams = {\n message: string\n trace_id?: string\n span_id?: string\n service_name?: string\n data?: unknown\n /** @deprecated Use service_name instead */\n function_name?: string\n}\n\n/**\n * Structured logger that emits logs as OpenTelemetry LogRecords.\n *\n * Every log call automatically captures the active trace and span context,\n * correlating your logs with distributed traces without any manual wiring.\n * When OTel is not initialized, Logger gracefully falls back to `console.*`.\n *\n * Pass structured data as the second argument to any log method. Using an\n * object of key-value pairs (instead of string interpolation) lets you\n * filter, aggregate, and build dashboards in your observability backend.\n *\n * @example\n * ```typescript\n * import { Logger } from 'iii-sdk'\n *\n * const logger = new Logger()\n *\n * // Basic logging — trace context is injected automatically\n * logger.info('Worker connected')\n *\n * // Structured context for dashboards and alerting\n * logger.info('Order processed', { orderId: 'ord_123', amount: 49.99, currency: 'USD' })\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\nexport class Logger {\n private _otelLogger: ReturnType<typeof getOtelLogger> | null = null\n\n private get otelLogger() {\n // Lazy initialization: re-fetch logger if not yet available\n if (!this._otelLogger) {\n this._otelLogger = getOtelLogger()\n }\n return this._otelLogger\n }\n\n constructor(\n private readonly traceId?: string,\n private readonly serviceName?: string,\n private readonly spanId?: string,\n ) {}\n\n private emit(message: string, severity: SeverityNumber, data?: unknown): void {\n const attributes: AnyValueMap = {}\n const traceId = this.traceId ?? currentTraceId()\n const spanId = this.spanId ?? currentSpanId()\n\n if (traceId) {\n attributes.trace_id = traceId\n }\n if (spanId) {\n attributes.span_id = spanId\n }\n if (this.serviceName) {\n attributes['service.name'] = this.serviceName\n }\n if (data !== undefined) {\n attributes['log.data'] = data as AnyValue\n }\n\n if (this.otelLogger) {\n this.otelLogger.emit({\n severityNumber: severity,\n body: message,\n attributes: Object.keys(attributes).length > 0 ? attributes : undefined,\n })\n } else {\n // Fallback to console when OTEL is not available\n switch (severity) {\n case SeverityNumber.DEBUG:\n console.debug(message, data)\n break\n case SeverityNumber.INFO:\n console.info(message, data)\n break\n case SeverityNumber.WARN:\n console.warn(message, data)\n break\n case SeverityNumber.ERROR:\n console.error(message, data)\n break\n default:\n console.log(message, data)\n }\n }\n }\n\n /**\n * Log an info-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.info('Order processed', { orderId: 'ord_123', status: 'completed' })\n * ```\n */\n info(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.INFO, data)\n }\n\n /**\n * Log a warning-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * ```\n */\n warn(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.WARN, data)\n }\n\n /**\n * Log an error-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\n error(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.ERROR, data)\n }\n\n /**\n * Log a debug-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.debug('Cache lookup', { key: 'user:42', hit: false })\n * ```\n */\n debug(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.DEBUG, data)\n }\n}\n","import { context as otelContext, propagation, SpanKind, SpanStatusCode, trace, type Tracer } from '@opentelemetry/api'\n\nconst SAFE_REQUEST_HEADERS = ['content-type', 'accept'] as const\nconst SAFE_RESPONSE_HEADERS = ['content-type'] as const\n\nexport interface TracedFetchInit extends RequestInit {\n tracer?: Tracer\n}\n\n/**\n * Execute a fetch request inside an OTel CLIENT span.\n *\n * Mirrors the Rust execute_traced_request shape: injects W3C traceparent into\n * outgoing headers, records HTTP semantic-convention attributes, and sets\n * ERROR span status for HTTP responses with status >= 400 or network errors.\n */\nexport async function executeTracedRequest(\n input: RequestInfo | URL,\n init?: TracedFetchInit,\n): Promise<Response> {\n const tracer = init?.tracer ?? trace.getTracer('iii-node-sdk')\n const rawUrl = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n let url: URL | null\n try {\n url = new URL(rawUrl)\n } catch {\n url = null\n }\n const method = (init?.method ?? (typeof input === 'object' && 'method' in input ? input.method : 'GET') ?? 'GET').toUpperCase()\n const name = url?.pathname ? `${method} ${url.pathname}` : method\n\n return tracer.startActiveSpan(\n name,\n {\n kind: SpanKind.CLIENT,\n attributes: {\n 'http.request.method': method,\n 'url.full': url?.toString() ?? rawUrl,\n 'network.protocol.name': 'http',\n ...(url\n ? {\n 'server.address': url.hostname,\n 'url.scheme': url.protocol.replace(':', ''),\n 'url.path': url.pathname,\n }\n : {}),\n ...(url?.port ? { 'server.port': Number(url.port) } : {}),\n ...(url?.search ? { 'url.query': url.search.slice(1) } : {}),\n },\n },\n async (span) => {\n try {\n // Seed with the Request's own headers so they survive when caller\n // passes a Request object; init.headers (if any) then overrides.\n const baseHeaders =\n typeof input === 'object' && 'headers' in input ? input.headers : undefined\n const headers = new Headers(baseHeaders)\n if (init?.headers) {\n for (const [k, v] of new Headers(init.headers).entries()) headers.set(k, v)\n }\n const carrier: Record<string, string> = {}\n propagation.inject(otelContext.active(), carrier)\n for (const [k, v] of Object.entries(carrier)) headers.set(k, v)\n\n for (const h of SAFE_REQUEST_HEADERS) {\n const v = headers.get(h)\n if (v) span.setAttribute(`http.request.header.${h}`, v)\n }\n\n const response = await fetch(input, { ...init, headers })\n span.setAttribute('http.response.status_code', response.status)\n const cl = response.headers.get('content-length')\n if (cl) span.setAttribute('http.response.body.size', Number(cl))\n for (const h of SAFE_RESPONSE_HEADERS) {\n const v = response.headers.get(h)\n if (v) span.setAttribute(`http.response.header.${h}`, v)\n }\n\n if (response.status >= 400) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: String(response.status) })\n span.setAttribute('error.type', String(response.status))\n } else {\n span.setStatus({ code: SpanStatusCode.OK })\n }\n return response\n } catch (err) {\n const error = err as Error\n span.recordException(error)\n span.setStatus({ code: SpanStatusCode.ERROR, message: error.message })\n span.setAttribute('error.type', error.name)\n throw err\n } finally {\n span.end()\n }\n },\n )\n}\n","/**\n * Worker metrics collection for the III Node SDK.\n *\n * Collects CPU, memory, and event loop metrics for worker health monitoring.\n * Uses the Node.js built-in `monitorEventLoopDelay` API for accurate\n * event loop lag measurements.\n */\n\nimport { type IntervalHistogram, monitorEventLoopDelay, performance } from 'node:perf_hooks'\n\n/**\n * Worker metrics data structure used internally for OTEL metric collection.\n */\nexport type WorkerMetrics = {\n memory_heap_used?: number\n memory_heap_total?: number\n memory_rss?: number\n memory_external?: number\n cpu_user_micros?: number\n cpu_system_micros?: number\n cpu_percent?: number\n event_loop_lag_ms?: number\n uptime_seconds?: number\n timestamp_ms: number\n runtime: string\n}\n\n/**\n * Configuration options for the WorkerMetricsCollector.\n */\nexport interface WorkerMetricsCollectorOptions {\n /**\n * Event loop delay histogram resolution in milliseconds.\n * Lower values provide more accurate measurements but use more resources.\n * @default 20\n */\n eventLoopResolutionMs?: number\n}\n\n/**\n * Collects worker resource metrics including CPU, memory, and event loop lag.\n *\n * Uses the Node.js `monitorEventLoopDelay` API for high-precision event loop\n * delay measurements instead of manual `setImmediate` timing.\n *\n * @example\n * ```typescript\n * const collector = new WorkerMetricsCollector()\n *\n * // Collect metrics periodically\n * setInterval(() => {\n * const metrics = collector.collect()\n * console.log('CPU:', metrics.cpu_percent, '%')\n * console.log('Event Loop Lag:', metrics.event_loop_lag_ms, 'ms')\n * }, 5000)\n *\n * // Clean up when done\n * collector.stopMonitoring()\n * ```\n */\nexport class WorkerMetricsCollector {\n private readonly startTime: number\n private lastCpuUsage: NodeJS.CpuUsage\n private lastCpuTime: number\n private eventLoopHistogram: IntervalHistogram | null = null\n\n /**\n * Creates a new WorkerMetricsCollector instance.\n *\n * @param options - Configuration options\n */\n constructor(options: WorkerMetricsCollectorOptions = {}) {\n this.startTime = Date.now()\n this.lastCpuUsage = process.cpuUsage()\n this.lastCpuTime = performance.now()\n this.startEventLoopMonitoring(options.eventLoopResolutionMs ?? 20)\n }\n\n /**\n * Starts the event loop delay histogram monitoring.\n *\n * @param resolutionMs - Histogram resolution in milliseconds\n */\n private startEventLoopMonitoring(resolutionMs: number): void {\n // Sanitize resolution: must be a positive finite number, minimum 1ms\n const safeResolutionMs =\n Number.isFinite(resolutionMs) && resolutionMs > 0 ? Math.max(1, Math.floor(resolutionMs)) : 20 // Default fallback\n\n this.eventLoopHistogram = monitorEventLoopDelay({ resolution: safeResolutionMs })\n this.eventLoopHistogram.enable()\n }\n\n /**\n * Stops the event loop monitoring and releases resources.\n * Should be called when the collector is no longer needed.\n */\n public stopMonitoring(): void {\n if (this.eventLoopHistogram) {\n this.eventLoopHistogram.disable()\n this.eventLoopHistogram = null\n }\n }\n\n /**\n * Collects current worker metrics.\n *\n * This method calculates CPU usage since the last collection,\n * reads memory usage, and gets event loop delay statistics.\n * The event loop histogram is reset after each collection for\n * accurate per-interval measurements.\n *\n * @returns Current worker metrics snapshot\n */\n collect(): WorkerMetrics {\n const memoryUsage = process.memoryUsage()\n const cpuUsage = process.cpuUsage()\n const now = performance.now()\n\n // Calculate CPU percentage since last collection\n const cpuDelta = {\n user: cpuUsage.user - this.lastCpuUsage.user,\n system: cpuUsage.system - this.lastCpuUsage.system,\n }\n const timeDelta = (now - this.lastCpuTime) * 1000 // Convert ms to microseconds\n const cpuPercent = timeDelta > 0 ? ((cpuDelta.user + cpuDelta.system) / timeDelta) * 100 : 0\n\n // Update state for next collection\n this.lastCpuUsage = cpuUsage\n this.lastCpuTime = now\n\n // Get event loop lag from histogram (in nanoseconds, convert to ms)\n let eventLoopLagMs = 0\n if (this.eventLoopHistogram) {\n // Mean is in nanoseconds, convert to milliseconds\n eventLoopLagMs = this.eventLoopHistogram.mean / 1_000_000\n // Reset histogram for next collection interval\n this.eventLoopHistogram.reset()\n }\n\n return {\n memory_heap_used: memoryUsage.heapUsed,\n memory_heap_total: memoryUsage.heapTotal,\n memory_rss: memoryUsage.rss,\n memory_external: memoryUsage.external,\n cpu_user_micros: cpuUsage.user,\n cpu_system_micros: cpuUsage.system,\n cpu_percent: Math.min(cpuPercent, 100), // Cap at 100%\n event_loop_lag_ms: eventLoopLagMs,\n uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000),\n timestamp_ms: Date.now(),\n runtime: 'node',\n }\n }\n}\n","import type { Meter, BatchObservableResult, Observable } from '@opentelemetry/api'\nimport { WorkerMetricsCollector } from './worker-metrics'\n\nexport interface WorkerGaugesOptions {\n workerId: string\n workerName?: string\n}\n\nlet registeredGauges = false\nlet metricsCollector: WorkerMetricsCollector | null = null\nlet registeredMeter: Meter | null = null\nlet registeredBatchCallback: ((observableResult: BatchObservableResult) => void) | null = null\nlet registeredObservables: Observable[] = []\n\nexport function registerWorkerGauges(meter: Meter, options: WorkerGaugesOptions): void {\n if (registeredGauges) {\n return\n }\n\n const { workerId, workerName } = options\n const baseAttributes = {\n 'worker.id': workerId,\n ...(workerName && { 'worker.name': workerName }),\n }\n\n metricsCollector = new WorkerMetricsCollector()\n\n const memoryHeapUsed = meter.createObservableGauge('iii.worker.memory.heap_used', {\n description: 'Worker heap memory used in bytes',\n unit: 'bytes',\n })\n\n const memoryHeapTotal = meter.createObservableGauge('iii.worker.memory.heap_total', {\n description: 'Worker total heap memory in bytes',\n unit: 'bytes',\n })\n\n const memoryRss = meter.createObservableGauge('iii.worker.memory.rss', {\n description: 'Worker resident set size in bytes',\n unit: 'bytes',\n })\n\n const memoryExternal = meter.createObservableGauge('iii.worker.memory.external', {\n description: 'Worker external memory in bytes',\n unit: 'bytes',\n })\n\n const cpuPercent = meter.createObservableGauge('iii.worker.cpu.percent', {\n description: 'Worker CPU usage percentage',\n unit: '%',\n })\n\n const cpuUserMicros = meter.createObservableGauge('iii.worker.cpu.user_micros', {\n description: 'Worker CPU user time in microseconds',\n unit: 'us',\n })\n\n const cpuSystemMicros = meter.createObservableGauge('iii.worker.cpu.system_micros', {\n description: 'Worker CPU system time in microseconds',\n unit: 'us',\n })\n\n const eventLoopLag = meter.createObservableGauge('iii.worker.event_loop.lag_ms', {\n description: 'Worker event loop lag in milliseconds',\n unit: 'ms',\n })\n\n const uptimeSeconds = meter.createObservableGauge('iii.worker.uptime_seconds', {\n description: 'Worker uptime in seconds',\n unit: 's',\n })\n\n const batchCallback = (observableResult: BatchObservableResult) => {\n if (!metricsCollector) return\n\n const metrics = metricsCollector.collect()\n\n if (metrics.memory_heap_used !== undefined) {\n observableResult.observe(memoryHeapUsed, metrics.memory_heap_used, baseAttributes)\n }\n if (metrics.memory_heap_total !== undefined) {\n observableResult.observe(memoryHeapTotal, metrics.memory_heap_total, baseAttributes)\n }\n if (metrics.memory_rss !== undefined) {\n observableResult.observe(memoryRss, metrics.memory_rss, baseAttributes)\n }\n if (metrics.memory_external !== undefined) {\n observableResult.observe(memoryExternal, metrics.memory_external, baseAttributes)\n }\n if (metrics.cpu_percent !== undefined) {\n observableResult.observe(cpuPercent, metrics.cpu_percent, baseAttributes)\n }\n if (metrics.cpu_user_micros !== undefined) {\n observableResult.observe(cpuUserMicros, metrics.cpu_user_micros, baseAttributes)\n }\n if (metrics.cpu_system_micros !== undefined) {\n observableResult.observe(cpuSystemMicros, metrics.cpu_system_micros, baseAttributes)\n }\n if (metrics.event_loop_lag_ms !== undefined) {\n observableResult.observe(eventLoopLag, metrics.event_loop_lag_ms, baseAttributes)\n }\n if (metrics.uptime_seconds !== undefined) {\n observableResult.observe(uptimeSeconds, metrics.uptime_seconds, baseAttributes)\n }\n }\n\n meter.addBatchObservableCallback(batchCallback, [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ])\n\n registeredMeter = meter\n registeredBatchCallback = batchCallback\n registeredObservables = [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ]\n\n registeredGauges = true\n}\n\nexport function stopWorkerGauges(): void {\n // Remove the batch observable callback before stopping\n if (registeredMeter && registeredBatchCallback) {\n registeredMeter.removeBatchObservableCallback(registeredBatchCallback, registeredObservables)\n }\n\n if (metricsCollector) {\n metricsCollector.stopMonitoring()\n metricsCollector = null\n }\n\n registeredMeter = null\n registeredBatchCallback = null\n registeredObservables = []\n registeredGauges = false\n}\n","/**\n * Safely stringify a value, handling circular references, BigInt, and other edge cases.\n * Returns \"[unserializable]\" if serialization fails for any reason.\n */\nexport function safeStringify(value: unknown): string {\n const seen = new WeakSet<object>()\n\n try {\n const result = JSON.stringify(value, (_key, val) => {\n // Handle BigInt\n if (typeof val === 'bigint') {\n return val.toString()\n }\n\n // Handle circular references\n if (val !== null && typeof val === 'object') {\n if (seen.has(val)) {\n return '[Circular]'\n }\n seen.add(val)\n }\n\n return val\n })\n return result ?? '[unserializable]'\n } catch {\n return '[unserializable]'\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,SAAb,MAAoB;CAClB,AAAQ,cAAuD;CAE/D,IAAY,aAAa;AAEvB,MAAI,CAAC,KAAK,YACR,MAAK,cAAcA,WAAe;AAEpC,SAAO,KAAK;;CAGd,YACE,AAAiB,SACjB,AAAiB,aACjB,AAAiB,QACjB;EAHiB;EACA;EACA;;CAGnB,AAAQ,KAAK,SAAiB,UAA0B,MAAsB;EAC5E,MAAM,aAA0B,EAAE;EAClC,MAAM,UAAU,KAAK,WAAW,gBAAgB;EAChD,MAAM,SAAS,KAAK,UAAU,eAAe;AAE7C,MAAI,QACF,YAAW,WAAW;AAExB,MAAI,OACF,YAAW,UAAU;AAEvB,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QAAQ,gBAAgB,eAAe;;AAInF,OAAM,2BAA2B,eAAe;EAC9C;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAEF,mBAAkB;AAClB,2BAA0B;AAC1B,yBAAwB;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD;AAED,oBAAmB;;AAGrB,SAAgB,mBAAyB;AAEvC,KAAI,mBAAmB,wBACrB,iBAAgB,8BAA8B,yBAAyB,sBAAsB;AAG/F,KAAI,kBAAkB;AACpB,mBAAiB,gBAAgB;AACjC,qBAAmB;;AAGrB,mBAAkB;AAClB,2BAA0B;AAC1B,yBAAwB,EAAE;AAC1B,oBAAmB;;;;;;;;;ACjJrB,SAAgB,cAAc,OAAwB;CACpD,MAAM,uBAAO,IAAI,SAAiB;AAElC,KAAI;AAiBF,SAhBe,KAAK,UAAU,QAAQ,MAAM,QAAQ;AAElD,OAAI,OAAO,QAAQ,SACjB,QAAO,IAAI,UAAU;AAIvB,OAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;AAC3C,QAAI,KAAK,IAAI,IAAI,CACf,QAAO;AAET,SAAK,IAAI,IAAI;;AAGf,UAAO;IACP,IACe;SACX;AACN,SAAO"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["getOtelLogger","SeverityNumber","otelContext"],"sources":["../../src/observability/logger.ts","../../src/observability/http-instrumentation.ts","../../src/observability/worker-metrics.ts","../../src/observability/otel-worker-gauges.ts","../../src/observability/utils.ts"],"sourcesContent":["import { AnyValue, AnyValueMap, SeverityNumber } from '@opentelemetry/api-logs'\nimport {\n currentSpanId,\n currentTraceId,\n getLogger as getOtelLogger,\n} from './telemetry-system'\n\n/** @internal */\nexport type LoggerParams = {\n message: string\n trace_id?: string\n span_id?: string\n service_name?: string\n data?: unknown\n /** @deprecated Use service_name instead */\n function_name?: string\n}\n\n/**\n * Structured logger that emits logs as OpenTelemetry LogRecords.\n *\n * Every log call automatically captures the active trace and span context,\n * correlating your logs with distributed traces without any manual wiring.\n * When OTel is not initialized, Logger gracefully falls back to `console.*`.\n *\n * Pass structured data as the second argument to any log method. Using an\n * object of key-value pairs (instead of string interpolation) lets you\n * filter, aggregate, and build dashboards in your observability backend.\n *\n * @example\n * ```typescript\n * import { Logger } from 'iii-sdk'\n *\n * const logger = new Logger()\n *\n * // Basic logging, trace context is injected automatically\n * logger.info('Worker connected')\n *\n * // Structured context for dashboards and alerting\n * logger.info('Order processed', { orderId: 'ord_123', amount: 49.99, currency: 'USD' })\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\nexport class Logger {\n private _otelLogger: ReturnType<typeof getOtelLogger> | null = null\n\n private get otelLogger() {\n // Lazy initialization: re-fetch logger if not yet available\n if (!this._otelLogger) {\n this._otelLogger = getOtelLogger()\n }\n return this._otelLogger\n }\n\n constructor(\n private readonly traceId?: string,\n private readonly serviceName?: string,\n private readonly spanId?: string,\n ) {}\n\n private emit(message: string, severity: SeverityNumber, data?: unknown): void {\n const attributes: AnyValueMap = {}\n const traceId = this.traceId ?? currentTraceId()\n const spanId = this.spanId ?? currentSpanId()\n\n if (traceId) {\n attributes.trace_id = traceId\n }\n if (spanId) {\n attributes.span_id = spanId\n }\n if (this.serviceName) {\n attributes['service.name'] = this.serviceName\n }\n if (data !== undefined) {\n attributes['log.data'] = data as AnyValue\n }\n\n if (this.otelLogger) {\n this.otelLogger.emit({\n severityNumber: severity,\n body: message,\n attributes: Object.keys(attributes).length > 0 ? attributes : undefined,\n })\n } else {\n // Fallback to console when OTEL is not available\n switch (severity) {\n case SeverityNumber.DEBUG:\n console.debug(message, data)\n break\n case SeverityNumber.INFO:\n console.info(message, data)\n break\n case SeverityNumber.WARN:\n console.warn(message, data)\n break\n case SeverityNumber.ERROR:\n console.error(message, data)\n break\n default:\n console.log(message, data)\n }\n }\n }\n\n /**\n * Log an info-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.info('Order processed', { orderId: 'ord_123', status: 'completed' })\n * ```\n */\n info(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.INFO, data)\n }\n\n /**\n * Log a warning-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * ```\n */\n warn(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.WARN, data)\n }\n\n /**\n * Log an error-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\n error(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.ERROR, data)\n }\n\n /**\n * Log a debug-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.debug('Cache lookup', { key: 'user:42', hit: false })\n * ```\n */\n debug(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.DEBUG, data)\n }\n}\n","import { context as otelContext, propagation, SpanKind, SpanStatusCode, trace, type Tracer } from '@opentelemetry/api'\n\nconst SAFE_REQUEST_HEADERS = ['content-type', 'accept'] as const\nconst SAFE_RESPONSE_HEADERS = ['content-type'] as const\n\nexport interface TracedFetchInit extends RequestInit {\n tracer?: Tracer\n}\n\n/**\n * Execute a fetch request inside an OTel CLIENT span.\n *\n * Mirrors the Rust execute_traced_request shape: injects W3C traceparent into\n * outgoing headers, records HTTP semantic-convention attributes, and sets\n * ERROR span status for HTTP responses with status >= 400 or network errors.\n */\nexport async function executeTracedRequest(\n input: RequestInfo | URL,\n init?: TracedFetchInit,\n): Promise<Response> {\n const tracer = init?.tracer ?? trace.getTracer('iii-node-sdk')\n const rawUrl = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n let url: URL | null\n try {\n url = new URL(rawUrl)\n } catch {\n url = null\n }\n const method = (init?.method ?? (typeof input === 'object' && 'method' in input ? input.method : 'GET') ?? 'GET').toUpperCase()\n const name = url?.pathname ? `${method} ${url.pathname}` : method\n\n return tracer.startActiveSpan(\n name,\n {\n kind: SpanKind.CLIENT,\n attributes: {\n 'http.request.method': method,\n 'url.full': url?.toString() ?? rawUrl,\n 'network.protocol.name': 'http',\n ...(url\n ? {\n 'server.address': url.hostname,\n 'url.scheme': url.protocol.replace(':', ''),\n 'url.path': url.pathname,\n }\n : {}),\n ...(url?.port ? { 'server.port': Number(url.port) } : {}),\n ...(url?.search ? { 'url.query': url.search.slice(1) } : {}),\n },\n },\n async (span) => {\n try {\n // Seed with the Request's own headers so they survive when caller\n // passes a Request object; init.headers (if any) then overrides.\n const baseHeaders =\n typeof input === 'object' && 'headers' in input ? input.headers : undefined\n const headers = new Headers(baseHeaders)\n if (init?.headers) {\n for (const [k, v] of new Headers(init.headers).entries()) headers.set(k, v)\n }\n const carrier: Record<string, string> = {}\n propagation.inject(otelContext.active(), carrier)\n for (const [k, v] of Object.entries(carrier)) headers.set(k, v)\n\n for (const h of SAFE_REQUEST_HEADERS) {\n const v = headers.get(h)\n if (v) span.setAttribute(`http.request.header.${h}`, v)\n }\n\n const response = await fetch(input, { ...init, headers })\n span.setAttribute('http.response.status_code', response.status)\n const cl = response.headers.get('content-length')\n if (cl) span.setAttribute('http.response.body.size', Number(cl))\n for (const h of SAFE_RESPONSE_HEADERS) {\n const v = response.headers.get(h)\n if (v) span.setAttribute(`http.response.header.${h}`, v)\n }\n\n if (response.status >= 400) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: String(response.status) })\n span.setAttribute('error.type', String(response.status))\n } else {\n span.setStatus({ code: SpanStatusCode.OK })\n }\n return response\n } catch (err) {\n const error = err as Error\n span.recordException(error)\n span.setStatus({ code: SpanStatusCode.ERROR, message: error.message })\n span.setAttribute('error.type', error.name)\n throw err\n } finally {\n span.end()\n }\n },\n )\n}\n","/**\n * Worker metrics collection for the III Node SDK.\n *\n * Collects CPU, memory, and event loop metrics for worker health monitoring.\n * Uses the Node.js built-in `monitorEventLoopDelay` API for accurate\n * event loop lag measurements.\n */\n\nimport { type IntervalHistogram, monitorEventLoopDelay, performance } from 'node:perf_hooks'\n\n/**\n * Worker metrics data structure used internally for OTEL metric collection.\n */\nexport type WorkerMetrics = {\n memory_heap_used?: number\n memory_heap_total?: number\n memory_rss?: number\n memory_external?: number\n cpu_user_micros?: number\n cpu_system_micros?: number\n cpu_percent?: number\n event_loop_lag_ms?: number\n uptime_seconds?: number\n timestamp_ms: number\n runtime: string\n}\n\n/**\n * Configuration options for the WorkerMetricsCollector.\n */\nexport interface WorkerMetricsCollectorOptions {\n /**\n * Event loop delay histogram resolution in milliseconds.\n * Lower values provide more accurate measurements but use more resources.\n * @default 20\n */\n eventLoopResolutionMs?: number\n}\n\n/**\n * Collects worker resource metrics including CPU, memory, and event loop lag.\n *\n * Uses the Node.js `monitorEventLoopDelay` API for high-precision event loop\n * delay measurements instead of manual `setImmediate` timing.\n *\n * @example\n * ```typescript\n * const collector = new WorkerMetricsCollector()\n *\n * // Collect metrics periodically\n * setInterval(() => {\n * const metrics = collector.collect()\n * console.log('CPU:', metrics.cpu_percent, '%')\n * console.log('Event Loop Lag:', metrics.event_loop_lag_ms, 'ms')\n * }, 5000)\n *\n * // Clean up when done\n * collector.stopMonitoring()\n * ```\n */\nexport class WorkerMetricsCollector {\n private readonly startTime: number\n private lastCpuUsage: NodeJS.CpuUsage\n private lastCpuTime: number\n private eventLoopHistogram: IntervalHistogram | null = null\n\n /**\n * Creates a new WorkerMetricsCollector instance.\n *\n * @param options - Configuration options\n */\n constructor(options: WorkerMetricsCollectorOptions = {}) {\n this.startTime = Date.now()\n this.lastCpuUsage = process.cpuUsage()\n this.lastCpuTime = performance.now()\n this.startEventLoopMonitoring(options.eventLoopResolutionMs ?? 20)\n }\n\n /**\n * Starts the event loop delay histogram monitoring.\n *\n * @param resolutionMs - Histogram resolution in milliseconds\n */\n private startEventLoopMonitoring(resolutionMs: number): void {\n // Sanitize resolution: must be a positive finite number, minimum 1ms\n const safeResolutionMs =\n Number.isFinite(resolutionMs) && resolutionMs > 0 ? Math.max(1, Math.floor(resolutionMs)) : 20 // Default fallback\n\n this.eventLoopHistogram = monitorEventLoopDelay({ resolution: safeResolutionMs })\n this.eventLoopHistogram.enable()\n }\n\n /**\n * Stops the event loop monitoring and releases resources.\n * Should be called when the collector is no longer needed.\n */\n public stopMonitoring(): void {\n if (this.eventLoopHistogram) {\n this.eventLoopHistogram.disable()\n this.eventLoopHistogram = null\n }\n }\n\n /**\n * Collects current worker metrics.\n *\n * This method calculates CPU usage since the last collection,\n * reads memory usage, and gets event loop delay statistics.\n * The event loop histogram is reset after each collection for\n * accurate per-interval measurements.\n *\n * @returns Current worker metrics snapshot\n */\n collect(): WorkerMetrics {\n const memoryUsage = process.memoryUsage()\n const cpuUsage = process.cpuUsage()\n const now = performance.now()\n\n // Calculate CPU percentage since last collection\n const cpuDelta = {\n user: cpuUsage.user - this.lastCpuUsage.user,\n system: cpuUsage.system - this.lastCpuUsage.system,\n }\n const timeDelta = (now - this.lastCpuTime) * 1000 // Convert ms to microseconds\n const cpuPercent = timeDelta > 0 ? ((cpuDelta.user + cpuDelta.system) / timeDelta) * 100 : 0\n\n // Update state for next collection\n this.lastCpuUsage = cpuUsage\n this.lastCpuTime = now\n\n // Get event loop lag from histogram (in nanoseconds, convert to ms)\n let eventLoopLagMs = 0\n if (this.eventLoopHistogram) {\n // Mean is in nanoseconds, convert to milliseconds\n eventLoopLagMs = this.eventLoopHistogram.mean / 1_000_000\n // Reset histogram for next collection interval\n this.eventLoopHistogram.reset()\n }\n\n return {\n memory_heap_used: memoryUsage.heapUsed,\n memory_heap_total: memoryUsage.heapTotal,\n memory_rss: memoryUsage.rss,\n memory_external: memoryUsage.external,\n cpu_user_micros: cpuUsage.user,\n cpu_system_micros: cpuUsage.system,\n cpu_percent: Math.min(cpuPercent, 100), // Cap at 100%\n event_loop_lag_ms: eventLoopLagMs,\n uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000),\n timestamp_ms: Date.now(),\n runtime: 'node',\n }\n }\n}\n","import type { Meter, BatchObservableResult, Observable } from '@opentelemetry/api'\nimport { WorkerMetricsCollector } from './worker-metrics'\n\nexport interface WorkerGaugesOptions {\n workerId: string\n workerName?: string\n}\n\nlet registeredGauges = false\nlet metricsCollector: WorkerMetricsCollector | null = null\nlet registeredMeter: Meter | null = null\nlet registeredBatchCallback: ((observableResult: BatchObservableResult) => void) | null = null\nlet registeredObservables: Observable[] = []\n\nexport function registerWorkerGauges(meter: Meter, options: WorkerGaugesOptions): void {\n if (registeredGauges) {\n return\n }\n\n const { workerId, workerName } = options\n const baseAttributes = {\n 'worker.id': workerId,\n ...(workerName && { 'worker.name': workerName }),\n }\n\n metricsCollector = new WorkerMetricsCollector()\n\n const memoryHeapUsed = meter.createObservableGauge('iii.worker.memory.heap_used', {\n description: 'Worker heap memory used in bytes',\n unit: 'bytes',\n })\n\n const memoryHeapTotal = meter.createObservableGauge('iii.worker.memory.heap_total', {\n description: 'Worker total heap memory in bytes',\n unit: 'bytes',\n })\n\n const memoryRss = meter.createObservableGauge('iii.worker.memory.rss', {\n description: 'Worker resident set size in bytes',\n unit: 'bytes',\n })\n\n const memoryExternal = meter.createObservableGauge('iii.worker.memory.external', {\n description: 'Worker external memory in bytes',\n unit: 'bytes',\n })\n\n const cpuPercent = meter.createObservableGauge('iii.worker.cpu.percent', {\n description: 'Worker CPU usage percentage',\n unit: '%',\n })\n\n const cpuUserMicros = meter.createObservableGauge('iii.worker.cpu.user_micros', {\n description: 'Worker CPU user time in microseconds',\n unit: 'us',\n })\n\n const cpuSystemMicros = meter.createObservableGauge('iii.worker.cpu.system_micros', {\n description: 'Worker CPU system time in microseconds',\n unit: 'us',\n })\n\n const eventLoopLag = meter.createObservableGauge('iii.worker.event_loop.lag_ms', {\n description: 'Worker event loop lag in milliseconds',\n unit: 'ms',\n })\n\n const uptimeSeconds = meter.createObservableGauge('iii.worker.uptime_seconds', {\n description: 'Worker uptime in seconds',\n unit: 's',\n })\n\n const batchCallback = (observableResult: BatchObservableResult) => {\n if (!metricsCollector) return\n\n const metrics = metricsCollector.collect()\n\n if (metrics.memory_heap_used !== undefined) {\n observableResult.observe(memoryHeapUsed, metrics.memory_heap_used, baseAttributes)\n }\n if (metrics.memory_heap_total !== undefined) {\n observableResult.observe(memoryHeapTotal, metrics.memory_heap_total, baseAttributes)\n }\n if (metrics.memory_rss !== undefined) {\n observableResult.observe(memoryRss, metrics.memory_rss, baseAttributes)\n }\n if (metrics.memory_external !== undefined) {\n observableResult.observe(memoryExternal, metrics.memory_external, baseAttributes)\n }\n if (metrics.cpu_percent !== undefined) {\n observableResult.observe(cpuPercent, metrics.cpu_percent, baseAttributes)\n }\n if (metrics.cpu_user_micros !== undefined) {\n observableResult.observe(cpuUserMicros, metrics.cpu_user_micros, baseAttributes)\n }\n if (metrics.cpu_system_micros !== undefined) {\n observableResult.observe(cpuSystemMicros, metrics.cpu_system_micros, baseAttributes)\n }\n if (metrics.event_loop_lag_ms !== undefined) {\n observableResult.observe(eventLoopLag, metrics.event_loop_lag_ms, baseAttributes)\n }\n if (metrics.uptime_seconds !== undefined) {\n observableResult.observe(uptimeSeconds, metrics.uptime_seconds, baseAttributes)\n }\n }\n\n meter.addBatchObservableCallback(batchCallback, [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ])\n\n registeredMeter = meter\n registeredBatchCallback = batchCallback\n registeredObservables = [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ]\n\n registeredGauges = true\n}\n\nexport function stopWorkerGauges(): void {\n // Remove the batch observable callback before stopping\n if (registeredMeter && registeredBatchCallback) {\n registeredMeter.removeBatchObservableCallback(registeredBatchCallback, registeredObservables)\n }\n\n if (metricsCollector) {\n metricsCollector.stopMonitoring()\n metricsCollector = null\n }\n\n registeredMeter = null\n registeredBatchCallback = null\n registeredObservables = []\n registeredGauges = false\n}\n","/**\n * Safely stringify a value, handling circular references, BigInt, and other edge cases.\n * Returns \"[unserializable]\" if serialization fails for any reason.\n */\nexport function safeStringify(value: unknown): string {\n const seen = new WeakSet<object>()\n\n try {\n const result = JSON.stringify(value, (_key, val) => {\n // Handle BigInt\n if (typeof val === 'bigint') {\n return val.toString()\n }\n\n // Handle circular references\n if (val !== null && typeof val === 'object') {\n if (seen.has(val)) {\n return '[Circular]'\n }\n seen.add(val)\n }\n\n return val\n })\n return result ?? '[unserializable]'\n } catch {\n return '[unserializable]'\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,SAAb,MAAoB;CAClB,AAAQ,cAAuD;CAE/D,IAAY,aAAa;AAEvB,MAAI,CAAC,KAAK,YACR,MAAK,cAAcA,WAAe;AAEpC,SAAO,KAAK;;CAGd,YACE,AAAiB,SACjB,AAAiB,aACjB,AAAiB,QACjB;EAHiB;EACA;EACA;;CAGnB,AAAQ,KAAK,SAAiB,UAA0B,MAAsB;EAC5E,MAAM,aAA0B,EAAE;EAClC,MAAM,UAAU,KAAK,WAAW,gBAAgB;EAChD,MAAM,SAAS,KAAK,UAAU,eAAe;AAE7C,MAAI,QACF,YAAW,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AQ,mBAAmB,OAC7B,kBAAiB,QAAQ,eAAe,QAAQ,gBAAgB,eAAe;;AAInF,OAAM,2BAA2B,eAAe;EAC9C;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAEF,mBAAkB;AAClB,2BAA0B;AAC1B,yBAAwB;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD;AAED,oBAAmB;;AAGrB,SAAgB,mBAAyB;AAEvC,KAAI,mBAAmB,wBACrB,iBAAgB,8BAA8B,yBAAyB,sBAAsB;AAG/F,KAAI,kBAAkB;AACpB,mBAAiB,gBAAgB;AACjC,qBAAmB;;AAGrB,mBAAkB;AAClB,2BAA0B;AAC1B,yBAAwB,EAAE;AAC1B,oBAAmB;;;;;;;;;ACjJrB,SAAgB,cAAc,OAAwB;CACpD,MAAM,uBAAO,IAAI,SAAiB;AAElC,KAAI;AAiBF,SAhBe,KAAK,UAAU,QAAQ,MAAM,QAAQ;AAElD,OAAI,OAAO,QAAQ,SACjB,QAAO,IAAI,UAAU;AAIvB,OAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;AAC3C,QAAI,KAAK,IAAI,IAAI,CACf,QAAO;AAET,SAAK,IAAI,IAAI;;AAGf,UAAO;IACP,IACe;SACX;AACN,SAAO"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_telemetry_system = require('../telemetry-system-
|
|
2
|
+
const require_telemetry_system = require('../telemetry-system-eOJBYcZF.cjs');
|
|
3
3
|
|
|
4
4
|
exports.getMeter = require_telemetry_system.getMeter;
|
|
5
5
|
exports.getTracer = require_telemetry_system.getTracer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { c as getTracer, s as getMeter } from "../index-
|
|
1
|
+
import { c as getTracer, s as getMeter } from "../index-B2thODQm.cjs";
|
|
2
2
|
export { getMeter, getTracer };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { c as getTracer, s as getMeter } from "../index-
|
|
1
|
+
import { c as getTracer, s as getMeter } from "../index-Cr3b3Tmk.mjs";
|
|
2
2
|
export { getMeter, getTracer };
|
package/dist/stream/index.d.cts
CHANGED
|
@@ -166,7 +166,7 @@ type MergePath = string | string[];
|
|
|
166
166
|
* - Missing or non-object intermediates along the path are
|
|
167
167
|
* auto-replaced with `{}` so a stray `null` or scalar never
|
|
168
168
|
* blocks future merges.
|
|
169
|
-
* - The merge is shallow at the target
|
|
169
|
+
* - The merge is shallow at the target, top-level keys of `value`
|
|
170
170
|
* replace same-named keys; siblings are preserved.
|
|
171
171
|
* - Each path segment is a literal key. `["a.b"]` writes a single
|
|
172
172
|
* key named `"a.b"`, not `a → b`.
|
package/dist/stream/index.d.mts
CHANGED
|
@@ -166,7 +166,7 @@ type MergePath = string | string[];
|
|
|
166
166
|
* - Missing or non-object intermediates along the path are
|
|
167
167
|
* auto-replaced with `{}` so a stray `null` or scalar never
|
|
168
168
|
* blocks future merges.
|
|
169
|
-
* - The merge is shallow at the target
|
|
169
|
+
* - The merge is shallow at the target, top-level keys of `value`
|
|
170
170
|
* replace same-named keys; siblings are preserved.
|
|
171
171
|
* - Each path segment is a literal key. `["a.b"]` writes a single
|
|
172
172
|
* key named `"a.b"`, not `a → b`.
|
|
@@ -670,7 +670,7 @@ const SAFE_RESPONSE_HEADERS = ["content-type"];
|
|
|
670
670
|
let originalFetch = null;
|
|
671
671
|
/**
|
|
672
672
|
* Substring patterns from `OTEL_FETCH_IGNORE_URLS` (comma-separated). A fetch
|
|
673
|
-
* whose URL contains any pattern is executed WITHOUT creating a span
|
|
673
|
+
* whose URL contains any pattern is executed WITHOUT creating a span, use it
|
|
674
674
|
* to drop noisy/high-frequency calls (health checks, polling, internal
|
|
675
675
|
* endpoints) that would otherwise flood traces.
|
|
676
676
|
*/
|
|
@@ -1123,4 +1123,4 @@ async function withSpan(name, options, fn) {
|
|
|
1123
1123
|
|
|
1124
1124
|
//#endregion
|
|
1125
1125
|
export { BaggageSpanProcessor as A, extractTraceparent as C, injectTraceparent as D, injectBaggage as E, removeBaggageEntry as O, extractContext as S, getBaggageEntry as T, patchGlobalFetch as _, getTracer as a, currentTraceId as b, withSpan as c, redactAndTruncate as d, resolveMaxBytesFromEnv as f, setCurrentSpanError as g, setCurrentSpanAttribute as h, getMeter as i, DEFAULT_ALLOWLIST as j, setBaggageEntry as k, REDACTED_PLACEHOLDER as l, recordSpanEvent as m, flushOtel as n, initOtel as o, currentSpanIsRecording as p, getLogger as r, shutdownOtel as s, SeverityNumber$1 as t, redact as u, unpatchGlobalFetch as v, getAllBaggage as w, extractBaggage as x, currentSpanId as y };
|
|
1126
|
-
//# sourceMappingURL=telemetry-system-
|
|
1126
|
+
//# sourceMappingURL=telemetry-system-DZc-9gY3.mjs.map
|