@elysiumjs/argus 0.1.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ import { Elysia } from 'elysia';
2
+ /**
3
+ * Elysia plugin that creates OpenTelemetry request spans.
4
+ *
5
+ * Each HTTP request gets a span with method, path, and status information.
6
+ * Errors (5xx) are recorded as error spans.
7
+ *
8
+ * @author Axel Nana <axel.nana@workbud.com>
9
+ * @returns An Elysia plugin instance.
10
+ */
11
+ export declare const argusPlugin: () => Elysia<"", {
12
+ decorator: {};
13
+ store: {};
14
+ derive: {};
15
+ resolve: {};
16
+ }, {
17
+ typebox: {};
18
+ error: {};
19
+ }, {
20
+ schema: {};
21
+ standaloneSchema: {};
22
+ macro: {};
23
+ macroFn: {};
24
+ parser: {};
25
+ response: {};
26
+ }, {}, {
27
+ derive: {};
28
+ resolve: {};
29
+ schema: {};
30
+ standaloneSchema: {};
31
+ response: {};
32
+ }, {
33
+ derive: {
34
+ readonly __argusSpan: import("@opentelemetry/api").Span;
35
+ };
36
+ resolve: {};
37
+ schema: {};
38
+ standaloneSchema: {};
39
+ response: {};
40
+ }>;
package/dist/sdk.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ import type { TracingConfig } from './types';
2
+ /**
3
+ * ArgusSDK initializes OpenTelemetry for the Elysium framework.
4
+ *
5
+ * CRITICAL: For full auto-instrumentation this MUST be called before any
6
+ * application code runs (e.g. from a `--preload` file). Auto-instrumentation
7
+ * patches modules at import time; modules imported before OTel is initialized
8
+ * won't be instrumented. `ArgusModule` initialises the SDK in `onInit`, which
9
+ * only covers modules loaded afterwards; when the SDK was already initialised
10
+ * (e.g. by a preload), the module detects it with {@link ArgusSDK.isInitialized}
11
+ * and leaves it alone.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * // src/instrument.ts (loaded FIRST via --preload or entrypoint)
16
+ * import { ArgusSDK } from '@elysiumjs/argus';
17
+ *
18
+ * ArgusSDK.initialize({
19
+ * enabled: true,
20
+ * serviceName: 'my-api',
21
+ * exporter: 'otlp-http',
22
+ * endpoint: 'http://localhost:4318/v1/traces'
23
+ * });
24
+ * ```
25
+ *
26
+ * @author Axel Nana <axel.nana@workbud.com>
27
+ */
28
+ export declare class ArgusSDK {
29
+ private static instance;
30
+ private sdk;
31
+ private constructor();
32
+ /**
33
+ * Whether {@link ArgusSDK.initialize} has already been called.
34
+ * @author Axel Nana <axel.nana@workbud.com>
35
+ */
36
+ static isInitialized(): boolean;
37
+ /**
38
+ * Initializes the OpenTelemetry SDK.
39
+ * Can only be called once — subsequent calls are ignored with a warning.
40
+ * @author Axel Nana <axel.nana@workbud.com>
41
+ * @param config The tracing configuration.
42
+ */
43
+ static initialize(config: TracingConfig): void;
44
+ /**
45
+ * Creates the appropriate trace exporter based on the config.
46
+ * @author Axel Nana <axel.nana@workbud.com>
47
+ * @param config The tracing configuration.
48
+ * @returns A span exporter instance.
49
+ */
50
+ private static createExporter;
51
+ /**
52
+ * Shuts down the OpenTelemetry SDK gracefully.
53
+ * @author Axel Nana <axel.nana@workbud.com>
54
+ */
55
+ static shutdown(): Promise<void>;
56
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Configuration for the Argus telemetry SDK.
3
+ * @author Axel Nana <axel.nana@workbud.com>
4
+ */
5
+ export interface TracingConfig {
6
+ /**
7
+ * Whether tracing is enabled.
8
+ */
9
+ enabled: boolean;
10
+ /**
11
+ * The service name reported in spans.
12
+ */
13
+ serviceName: string;
14
+ /**
15
+ * The exporter to use. Only `otlp-http` and `console` are supported.
16
+ * gRPC is not supported on Bun.
17
+ */
18
+ exporter: 'otlp-http' | 'console';
19
+ /**
20
+ * The OTLP endpoint URL.
21
+ * @default 'http://localhost:4318/v1/traces'
22
+ */
23
+ endpoint?: string;
24
+ /**
25
+ * Sampling rate between 0.0 and 1.0.
26
+ * @default 1.0
27
+ */
28
+ samplingRate?: number;
29
+ }
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@elysiumjs/argus",
3
- "version": "0.1.1",
3
+ "version": "0.2.3",
4
4
  "license": "Apache-2.0",
5
5
  "description": "OpenTelemetry telemetry package for the Elysium.js framework.",
6
6
  "private": false,
7
7
  "author": "Workbud Technologies Inc.",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "https://github.com/workbud/elysium"
10
+ "url": "git+https://github.com/na2axl/elysiumjs.git",
11
+ "directory": "@elysiumjs/argus"
11
12
  },
12
13
  "keywords": [
13
14
  "elysium",
@@ -19,18 +20,23 @@
19
20
  "typescript",
20
21
  "bun"
21
22
  ],
22
- "homepage": "https://github.com/workbud/elysium",
23
- "module": "index.ts",
23
+ "homepage": "https://github.com/na2axl/elysiumjs/tree/main/@elysiumjs/argus#readme",
24
+ "bugs": {
25
+ "url": "https://github.com/na2axl/elysiumjs/issues"
26
+ },
27
+ "module": "dist/index.js",
24
28
  "type": "module",
25
29
  "main": "dist/index.js",
26
30
  "types": "dist/index.d.ts",
27
- "sideEffects": [
28
- "./src/sdk.ts"
31
+ "files": [
32
+ "dist",
33
+ "CHANGELOG.md"
29
34
  ],
35
+ "sideEffects": false,
30
36
  "scripts": {
31
37
  "format": "prettier --write \"./src/**/*.ts\"",
32
38
  "clean": "rimraf dist",
33
- "build:js": "bun build ./src/index.ts --outdir ./dist --target bun -e @elysiumjs/* -e @opentelemetry/* --root ./src --minify",
39
+ "build:js": "bun build ./src/index.ts --outdir ./dist --target bun -e @elysiumjs/* -e @opentelemetry/* --root ./src --minify-syntax --minify-whitespace",
34
40
  "build:ts": "tsc",
35
41
  "build": "bun run clean && bun run build:js && bun run build:ts",
36
42
  "test": "bun test",
@@ -39,20 +45,20 @@
39
45
  "prepublishOnly": "bun run build"
40
46
  },
41
47
  "dependencies": {
42
- "@opentelemetry/api": "^1.9.0",
43
- "@opentelemetry/sdk-node": "^0.57.0",
44
- "@opentelemetry/sdk-trace-base": "^1.30.0",
45
- "@opentelemetry/exporter-trace-otlp-http": "^0.57.0",
46
- "@opentelemetry/resources": "^1.30.0",
47
- "@opentelemetry/semantic-conventions": "^1.30.0"
48
+ "@opentelemetry/api": "^1.10.0",
49
+ "@opentelemetry/exporter-trace-otlp-http": "^0.300.0",
50
+ "@opentelemetry/resources": "^3.0.0",
51
+ "@opentelemetry/sdk-node": "^0.300.0",
52
+ "@opentelemetry/sdk-trace-base": "^2.12.0",
53
+ "@opentelemetry/semantic-conventions": "^1.43.0"
48
54
  },
49
55
  "devDependencies": {
50
- "@elysiumjs/core": "0.6.1",
51
- "@elysiumjs/hermes": "0.3.1"
56
+ "@elysiumjs/core": "0.10.0",
57
+ "@elysiumjs/hermes": "0.4.3"
52
58
  },
53
59
  "peerDependencies": {
54
- "@elysiumjs/core": "^0.6.1",
55
- "@elysiumjs/hermes": "^0.3.1"
60
+ "@elysiumjs/core": "^0.10.0",
61
+ "@elysiumjs/hermes": "^0.4.3"
56
62
  },
57
63
  "peerDependenciesMeta": {
58
64
  "@elysiumjs/hermes": {
@@ -1,8 +0,0 @@
1
- $ bun run clean && bun run build:js && bun run build:ts
2
- $ rimraf dist
3
- $ bun build ./src/index.ts --outdir ./dist --target bun -e @elysiumjs/* -e @opentelemetry/* --root ./src --minify
4
- Bundled 287 modules in 90ms
5
-
6
- index.js 0.38 MB (entry point)
7
-
8
- $ tsc
package/index.ts DELETED
@@ -1,15 +0,0 @@
1
- // Copyright (c) 2026-present Workbud Technologies Inc. All rights reserved.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- export * from './src/index';
@@ -1,45 +0,0 @@
1
- // Copyright (c) 2026-present Workbud Technologies Inc. All rights reserved.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import { trace } from '@opentelemetry/api';
16
-
17
- /**
18
- * Enriches a log context object with `traceId` and `spanId` from the
19
- * active OpenTelemetry span.
20
- *
21
- * Use this in Hermes log calls to correlate logs with traces:
22
- *
23
- * @example
24
- * ```typescript
25
- * import { withTraceContext } from '@elysiumjs/argus';
26
- *
27
- * logger.info('Processing request', withTraceContext({ userId: '123' }));
28
- * // Output: { msg: "Processing request", userId: "123", traceId: "abc...", spanId: "def..." }
29
- * ```
30
- *
31
- * @author Axel Nana <axel.nana@workbud.com>
32
- * @param ctx The base context to enrich.
33
- * @returns The context with `traceId` and `spanId` injected if an active span exists.
34
- */
35
- export function withTraceContext(ctx: Record<string, unknown> = {}): Record<string, unknown> {
36
- const span = trace.getActiveSpan();
37
- if (!span) return ctx;
38
-
39
- const spanCtx = span.spanContext();
40
- return {
41
- ...ctx,
42
- traceId: spanCtx.traceId,
43
- spanId: spanCtx.spanId
44
- };
45
- }
@@ -1,72 +0,0 @@
1
- // Copyright (c) 2026-present Workbud Technologies Inc. All rights reserved.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import type { SpanOptions } from '@opentelemetry/api';
16
-
17
- import { SpanStatusCode, trace } from '@opentelemetry/api';
18
-
19
- /**
20
- * Decorator that wraps a method in an OpenTelemetry span.
21
- *
22
- * Creates a child span for each method invocation, recording success
23
- * or error status. Exceptions are recorded on the span before re-throwing.
24
- *
25
- * @example
26
- * ```typescript
27
- * class UserService {
28
- * @Traced('user.findById')
29
- * async findById(id: string) {
30
- * return db.query('SELECT * FROM users WHERE id = $1', [id]);
31
- * }
32
- * }
33
- * ```
34
- *
35
- * @author Axel Nana <axel.nana@workbud.com>
36
- * @param name Optional span name. Defaults to `ClassName.methodName`.
37
- * @param options Optional OpenTelemetry span options.
38
- * @returns A method decorator.
39
- */
40
- export function Traced(name?: string, options?: SpanOptions): MethodDecorator {
41
- return function (
42
- target: object,
43
- propertyKey: string | symbol,
44
- descriptor: TypedPropertyDescriptor<any>
45
- ) {
46
- const original = descriptor.value;
47
- const spanName = name ?? `${target.constructor.name}.${String(propertyKey)}`;
48
-
49
- descriptor.value = async function (...args: any[]) {
50
- const tracer = trace.getTracer('@elysiumjs/argus');
51
-
52
- return tracer.startActiveSpan(spanName, options ?? {}, async (span) => {
53
- try {
54
- const result = await original.apply(this, args);
55
- span.setStatus({ code: SpanStatusCode.OK });
56
- return result;
57
- } catch (error) {
58
- span.setStatus({
59
- code: SpanStatusCode.ERROR,
60
- message: error instanceof Error ? error.message : 'Unknown error'
61
- });
62
- span.recordException(error as Error);
63
- throw error;
64
- } finally {
65
- span.end();
66
- }
67
- });
68
- };
69
-
70
- return descriptor;
71
- };
72
- }
package/src/index.ts DELETED
@@ -1,20 +0,0 @@
1
- // Copyright (c) 2026-present Workbud Technologies Inc. All rights reserved.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- export type { TracingConfig } from './types';
16
-
17
- export { ArgusSDK } from './sdk';
18
- export { Traced } from './decorators/traced';
19
- export { withTraceContext } from './correlation';
20
- export { argusPlugin } from './plugin';
package/src/plugin.ts DELETED
@@ -1,62 +0,0 @@
1
- // Copyright (c) 2026-present Workbud Technologies Inc. All rights reserved.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import { SpanStatusCode, trace } from '@opentelemetry/api';
16
- import { Elysia } from 'elysia';
17
-
18
- /**
19
- * Elysia plugin that creates OpenTelemetry request spans.
20
- *
21
- * Each HTTP request gets a span with method, path, and status information.
22
- * Errors (5xx) are recorded as error spans.
23
- *
24
- * @author Axel Nana <axel.nana@workbud.com>
25
- * @returns An Elysia plugin instance.
26
- */
27
- export const argusPlugin = () => {
28
- const tracer = trace.getTracer('@elysiumjs/argus');
29
-
30
- return new Elysia({ name: '@elysiumjs/argus' })
31
- .derive(({ request }) => {
32
- const url = new URL(request.url);
33
- const span = tracer.startSpan(`${request.method} ${url.pathname}`, {
34
- attributes: {
35
- 'http.method': request.method,
36
- 'http.url': request.url,
37
- 'http.target': url.pathname
38
- }
39
- });
40
-
41
- return { __argusSpan: span };
42
- })
43
- .onAfterResponse(({ __argusSpan, request }) => {
44
- if (__argusSpan) {
45
- __argusSpan.setStatus({ code: SpanStatusCode.OK });
46
- __argusSpan.setAttribute('http.method', request.method);
47
- __argusSpan.end();
48
- }
49
- })
50
- .onError(({ __argusSpan, error }) => {
51
- if (__argusSpan) {
52
- __argusSpan.setStatus({
53
- code: SpanStatusCode.ERROR,
54
- message: error instanceof Error ? error.message : 'Unknown error'
55
- });
56
- if (error instanceof Error) {
57
- __argusSpan.recordException(error);
58
- }
59
- __argusSpan.end();
60
- }
61
- });
62
- };
package/src/sdk.ts DELETED
@@ -1,110 +0,0 @@
1
- // Copyright (c) 2026-present Workbud Technologies Inc. All rights reserved.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import type { TracingConfig } from './types';
16
-
17
- import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
18
- import { Resource } from '@opentelemetry/resources';
19
- import { NodeSDK } from '@opentelemetry/sdk-node';
20
- import { ConsoleSpanExporter, TraceIdRatioBasedSampler } from '@opentelemetry/sdk-trace-base';
21
- import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
22
-
23
- /**
24
- * ArgusSDK initializes OpenTelemetry for the Elysium framework.
25
- *
26
- * CRITICAL: This MUST be called before any application code runs.
27
- * Auto-instrumentation patches modules at import time; if app code
28
- * imports modules before OTel is initialized, those imports won't
29
- * be instrumented.
30
- *
31
- * @example
32
- * ```typescript
33
- * // src/instrument.ts (loaded FIRST via --preload or entrypoint)
34
- * import { ArgusSDK } from '@elysiumjs/argus';
35
- *
36
- * ArgusSDK.initialize({
37
- * enabled: true,
38
- * serviceName: 'my-api',
39
- * exporter: 'otlp-http',
40
- * endpoint: 'http://localhost:4318/v1/traces'
41
- * });
42
- * ```
43
- *
44
- * @author Axel Nana <axel.nana@workbud.com>
45
- */
46
- export class ArgusSDK {
47
- private static instance: ArgusSDK;
48
- private sdk: NodeSDK | null = null;
49
-
50
- private constructor() {}
51
-
52
- /**
53
- * Initializes the OpenTelemetry SDK.
54
- * Can only be called once — subsequent calls are ignored with a warning.
55
- * @author Axel Nana <axel.nana@workbud.com>
56
- * @param config The tracing configuration.
57
- */
58
- public static initialize(config: TracingConfig): void {
59
- if (ArgusSDK.instance) {
60
- console.error('[Argus] SDK already initialized. Ignoring duplicate call.');
61
- return;
62
- }
63
-
64
- ArgusSDK.instance = new ArgusSDK();
65
-
66
- if (!config.enabled) return;
67
-
68
- const exporter = ArgusSDK.createExporter(config);
69
-
70
- ArgusSDK.instance.sdk = new NodeSDK({
71
- resource: new Resource({
72
- [ATTR_SERVICE_NAME]: config.serviceName
73
- }),
74
- traceExporter: exporter,
75
- ...(config.samplingRate !== undefined && {
76
- sampler: new TraceIdRatioBasedSampler(config.samplingRate)
77
- })
78
- });
79
-
80
- ArgusSDK.instance.sdk.start();
81
- }
82
-
83
- /**
84
- * Creates the appropriate trace exporter based on the config.
85
- * @author Axel Nana <axel.nana@workbud.com>
86
- * @param config The tracing configuration.
87
- * @returns A span exporter instance.
88
- */
89
- private static createExporter(config: TracingConfig) {
90
- switch (config.exporter) {
91
- case 'otlp-http':
92
- return new OTLPTraceExporter({
93
- url: config.endpoint ?? 'http://localhost:4318/v1/traces'
94
- });
95
- case 'console':
96
- default:
97
- return new ConsoleSpanExporter();
98
- }
99
- }
100
-
101
- /**
102
- * Shuts down the OpenTelemetry SDK gracefully.
103
- * @author Axel Nana <axel.nana@workbud.com>
104
- */
105
- public static async shutdown(): Promise<void> {
106
- if (ArgusSDK.instance?.sdk) {
107
- await ArgusSDK.instance.sdk.shutdown();
108
- }
109
- }
110
- }
package/src/types.ts DELETED
@@ -1,47 +0,0 @@
1
- // Copyright (c) 2026-present Workbud Technologies Inc. All rights reserved.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- /**
16
- * Configuration for the Argus telemetry SDK.
17
- * @author Axel Nana <axel.nana@workbud.com>
18
- */
19
- export interface TracingConfig {
20
- /**
21
- * Whether tracing is enabled.
22
- */
23
- enabled: boolean;
24
-
25
- /**
26
- * The service name reported in spans.
27
- */
28
- serviceName: string;
29
-
30
- /**
31
- * The exporter to use. Only `otlp-http` and `console` are supported.
32
- * gRPC is not supported on Bun.
33
- */
34
- exporter: 'otlp-http' | 'console';
35
-
36
- /**
37
- * The OTLP endpoint URL.
38
- * @default 'http://localhost:4318/v1/traces'
39
- */
40
- endpoint?: string;
41
-
42
- /**
43
- * Sampling rate between 0.0 and 1.0.
44
- * @default 1.0
45
- */
46
- samplingRate?: number;
47
- }
@@ -1,86 +0,0 @@
1
- // Copyright (c) 2026-present Workbud Technologies Inc. All rights reserved.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import { trace } from '@opentelemetry/api';
16
- import { afterEach, describe, expect, it, spyOn } from 'bun:test';
17
-
18
- import { withTraceContext } from '../src/correlation';
19
-
20
- describe('withTraceContext', () => {
21
- let getActiveSpanSpy: ReturnType<typeof spyOn>;
22
-
23
- afterEach(() => {
24
- getActiveSpanSpy?.mockRestore();
25
- });
26
-
27
- it('should return context unchanged when no active span', () => {
28
- getActiveSpanSpy = spyOn(trace, 'getActiveSpan').mockReturnValue(undefined as any);
29
-
30
- const ctx = { userId: '123' };
31
- const result = withTraceContext(ctx);
32
-
33
- expect(result).toEqual({ userId: '123' });
34
- expect(result).toBe(ctx); // Same reference
35
- });
36
-
37
- it('should enrich context with traceId and spanId', () => {
38
- const mockSpan = {
39
- spanContext: () => ({
40
- traceId: 'abc123',
41
- spanId: 'def456',
42
- traceFlags: 1
43
- })
44
- };
45
- getActiveSpanSpy = spyOn(trace, 'getActiveSpan').mockReturnValue(mockSpan as any);
46
-
47
- const result = withTraceContext({ userId: '123' });
48
-
49
- expect(result.userId).toBe('123');
50
- expect(result.traceId).toBe('abc123');
51
- expect(result.spanId).toBe('def456');
52
- });
53
-
54
- it('should work with empty context', () => {
55
- const mockSpan = {
56
- spanContext: () => ({
57
- traceId: 'trace-1',
58
- spanId: 'span-1',
59
- traceFlags: 1
60
- })
61
- };
62
- getActiveSpanSpy = spyOn(trace, 'getActiveSpan').mockReturnValue(mockSpan as any);
63
-
64
- const result = withTraceContext();
65
-
66
- expect(result.traceId).toBe('trace-1');
67
- expect(result.spanId).toBe('span-1');
68
- });
69
-
70
- it('should not mutate the original context', () => {
71
- const mockSpan = {
72
- spanContext: () => ({
73
- traceId: 'trace-1',
74
- spanId: 'span-1',
75
- traceFlags: 1
76
- })
77
- };
78
- getActiveSpanSpy = spyOn(trace, 'getActiveSpan').mockReturnValue(mockSpan as any);
79
-
80
- const original = { key: 'value' };
81
- const result = withTraceContext(original);
82
-
83
- expect(original).toEqual({ key: 'value' }); // Not mutated
84
- expect(result).not.toBe(original); // New object
85
- });
86
- });