autotel 4.1.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/package.json +1 -2
  2. package/src/attribute-redacting-processor.test.ts +0 -763
  3. package/src/attribute-redacting-processor.ts +0 -621
  4. package/src/attributes/attachers.ts +0 -161
  5. package/src/attributes/builders.ts +0 -529
  6. package/src/attributes/domains.ts +0 -42
  7. package/src/attributes/index.ts +0 -81
  8. package/src/attributes/registry.ts +0 -323
  9. package/src/attributes/types.ts +0 -211
  10. package/src/attributes/utils.ts +0 -64
  11. package/src/attributes/validators.ts +0 -266
  12. package/src/attributes.test.ts +0 -292
  13. package/src/auto.ts +0 -67
  14. package/src/autotel-logger.test.ts +0 -548
  15. package/src/autotel-logger.ts +0 -364
  16. package/src/baggage-span-processor.test.ts +0 -202
  17. package/src/baggage-span-processor.ts +0 -100
  18. package/src/business-baggage.test.ts +0 -500
  19. package/src/business-baggage.ts +0 -669
  20. package/src/circuit-breaker.test.ts +0 -341
  21. package/src/circuit-breaker.ts +0 -184
  22. package/src/config.test.ts +0 -94
  23. package/src/config.ts +0 -172
  24. package/src/correlated-events.test.ts +0 -151
  25. package/src/correlated-events.ts +0 -47
  26. package/src/correlation-id.test.ts +0 -163
  27. package/src/correlation-id.ts +0 -206
  28. package/src/db.test.ts +0 -252
  29. package/src/db.ts +0 -447
  30. package/src/decorators.test.ts +0 -153
  31. package/src/decorators.ts +0 -188
  32. package/src/define-event.test.ts +0 -41
  33. package/src/define-event.ts +0 -58
  34. package/src/devtools.ts +0 -60
  35. package/src/drain-pipeline.test.ts +0 -68
  36. package/src/drain-pipeline.ts +0 -199
  37. package/src/drain-toolkit.test.ts +0 -113
  38. package/src/drain-toolkit.ts +0 -129
  39. package/src/enricher-toolkit.test.ts +0 -67
  40. package/src/enricher-toolkit.ts +0 -79
  41. package/src/enrichers.test.ts +0 -150
  42. package/src/enrichers.ts +0 -145
  43. package/src/env-config.test.ts +0 -323
  44. package/src/env-config.ts +0 -309
  45. package/src/error-catalog.test.ts +0 -133
  46. package/src/error-catalog.ts +0 -262
  47. package/src/event-queue.test.ts +0 -864
  48. package/src/event-queue.ts +0 -699
  49. package/src/event-subscriber.ts +0 -262
  50. package/src/event-testing.ts +0 -197
  51. package/src/event.test.ts +0 -1104
  52. package/src/event.ts +0 -988
  53. package/src/events-config.ts +0 -235
  54. package/src/exporters.ts +0 -165
  55. package/src/filtering-span-processor.test.ts +0 -281
  56. package/src/filtering-span-processor.ts +0 -111
  57. package/src/flatten-attributes.test.ts +0 -76
  58. package/src/flatten-attributes.ts +0 -80
  59. package/src/functional.strict-types.typecheck.ts +0 -53
  60. package/src/functional.test.ts +0 -1464
  61. package/src/functional.ts +0 -2539
  62. package/src/functional.types.test.ts +0 -135
  63. package/src/hook.mjs +0 -15
  64. package/src/http.test.ts +0 -485
  65. package/src/http.ts +0 -424
  66. package/src/index.ts +0 -433
  67. package/src/init-auto-redactor.test.ts +0 -53
  68. package/src/init-redactor.test.ts +0 -8
  69. package/src/init.customization.test.ts +0 -665
  70. package/src/init.integrations.test.ts +0 -399
  71. package/src/init.openllmetry.test.ts +0 -194
  72. package/src/init.protocol.test.ts +0 -215
  73. package/src/init.ts +0 -2439
  74. package/src/instrumentation.test.ts +0 -108
  75. package/src/instrumentation.ts +0 -319
  76. package/src/logger.test.ts +0 -125
  77. package/src/logger.ts +0 -341
  78. package/src/messaging-adapters.test.ts +0 -595
  79. package/src/messaging-adapters.ts +0 -583
  80. package/src/messaging-testing.test.ts +0 -573
  81. package/src/messaging-testing.ts +0 -935
  82. package/src/messaging.test.ts +0 -1646
  83. package/src/messaging.ts +0 -2245
  84. package/src/metric-helpers.ts +0 -47
  85. package/src/metric-testing.ts +0 -197
  86. package/src/metric.ts +0 -446
  87. package/src/metrics.test.ts +0 -241
  88. package/src/node-require.ts +0 -123
  89. package/src/operation-context.ts +0 -93
  90. package/src/parse-error.test.ts +0 -73
  91. package/src/parse-error.ts +0 -112
  92. package/src/posthog-logs.test.ts +0 -115
  93. package/src/posthog-logs.ts +0 -77
  94. package/src/pretty-console-exporter.test.ts +0 -545
  95. package/src/pretty-console-exporter.ts +0 -413
  96. package/src/pretty-log-formatter.test.ts +0 -123
  97. package/src/pretty-log-formatter.ts +0 -210
  98. package/src/processors/canonical-log-line-processor.test.ts +0 -523
  99. package/src/processors/canonical-log-line-processor.ts +0 -396
  100. package/src/processors.ts +0 -152
  101. package/src/rate-limiter.test.ts +0 -199
  102. package/src/rate-limiter.ts +0 -98
  103. package/src/redact-values.test.ts +0 -90
  104. package/src/redact-values.ts +0 -34
  105. package/src/register.ts +0 -37
  106. package/src/request-logger.test.ts +0 -545
  107. package/src/request-logger.ts +0 -342
  108. package/src/sampling.test.ts +0 -1060
  109. package/src/sampling.ts +0 -737
  110. package/src/security-schema.test.ts +0 -45
  111. package/src/security-schema.ts +0 -107
  112. package/src/semantic-conventions.ts +0 -15
  113. package/src/semantic-helpers.test.ts +0 -226
  114. package/src/semantic-helpers.ts +0 -438
  115. package/src/shutdown.test.ts +0 -364
  116. package/src/shutdown.ts +0 -246
  117. package/src/span-name-normalizer.test.ts +0 -377
  118. package/src/span-name-normalizer.ts +0 -213
  119. package/src/stable-hash.ts +0 -27
  120. package/src/structured-error.test.ts +0 -191
  121. package/src/structured-error.ts +0 -157
  122. package/src/stub.integration.test.ts +0 -361
  123. package/src/tail-sampling-processor.test.ts +0 -230
  124. package/src/tail-sampling-processor.ts +0 -55
  125. package/src/test-span-collector.test.ts +0 -234
  126. package/src/test-span-collector.ts +0 -150
  127. package/src/testing.ts +0 -705
  128. package/src/trace-context.test.ts +0 -73
  129. package/src/trace-context.ts +0 -567
  130. package/src/trace-helpers.new.test.ts +0 -278
  131. package/src/trace-helpers.test.ts +0 -290
  132. package/src/trace-helpers.ts +0 -710
  133. package/src/trace-hybrid.test.ts +0 -42
  134. package/src/trace-hybrid.ts +0 -37
  135. package/src/tracer-provider.test.ts +0 -183
  136. package/src/tracer-provider.ts +0 -266
  137. package/src/track.test.ts +0 -154
  138. package/src/track.ts +0 -216
  139. package/src/validate.test.ts +0 -287
  140. package/src/validate.ts +0 -307
  141. package/src/validation-attributes.ts +0 -43
  142. package/src/validation.test.ts +0 -330
  143. package/src/validation.ts +0 -246
  144. package/src/variable-name-inference.test.ts +0 -178
  145. package/src/variable-name-inference.ts +0 -242
  146. package/src/webhook.test.ts +0 -649
  147. package/src/webhook.ts +0 -637
  148. package/src/workflow-distributed.test.ts +0 -786
  149. package/src/workflow-distributed.ts +0 -916
  150. package/src/workflow.async-safety.integration.test.ts +0 -345
  151. package/src/workflow.test.ts +0 -647
  152. package/src/workflow.ts +0 -810
  153. package/src/yaml-config.test.ts +0 -373
  154. package/src/yaml-config.ts +0 -351
@@ -1,191 +0,0 @@
1
- import { describe, expect, it, vi } from 'vitest';
2
- import type { Span, SpanContext } from '@opentelemetry/api';
3
- import {
4
- createStructuredError,
5
- getStructuredErrorAttributes,
6
- recordStructuredError,
7
- } from './structured-error';
8
- import { createTraceContext, type TraceContext } from './trace-context';
9
-
10
- function createFakeSpan(): {
11
- span: Span;
12
- recordException: ReturnType<typeof vi.fn>;
13
- setStatus: ReturnType<typeof vi.fn>;
14
- setAttributes: ReturnType<typeof vi.fn>;
15
- } {
16
- const recordException = vi.fn();
17
- const setStatus = vi.fn();
18
- const setAttributes = vi.fn();
19
- const spanContext: SpanContext = {
20
- traceId: '0123456789abcdef0123456789abcdef',
21
- spanId: '0123456789abcdef',
22
- traceFlags: 1,
23
- };
24
- const span = {
25
- spanContext: () => spanContext,
26
- setAttribute: vi.fn(),
27
- setAttributes,
28
- setStatus,
29
- recordException,
30
- addEvent: vi.fn(),
31
- addLink: vi.fn(),
32
- addLinks: vi.fn(),
33
- updateName: vi.fn(),
34
- isRecording: () => true,
35
- end: vi.fn(),
36
- } as unknown as Span;
37
- return { span, recordException, setStatus, setAttributes };
38
- }
39
-
40
- describe('structured-error helpers', () => {
41
- it('creates an error with structured diagnostic fields', () => {
42
- const err = createStructuredError({
43
- message: 'Payment failed',
44
- why: 'Card declined by issuer',
45
- fix: 'Use a different card',
46
- link: 'https://docs.example.com/errors/card-declined',
47
- code: 'PAYMENT_DECLINED',
48
- status: 402,
49
- details: { retryable: false, provider: 'stripe' },
50
- });
51
-
52
- expect(err.message).toBe('Payment failed');
53
- expect(err.why).toBe('Card declined by issuer');
54
- expect(err.fix).toBe('Use a different card');
55
- expect(err.link).toBe('https://docs.example.com/errors/card-declined');
56
- expect(err.code).toBe('PAYMENT_DECLINED');
57
- expect(err.status).toBe(402);
58
- expect(err.details).toEqual({ retryable: false, provider: 'stripe' });
59
- });
60
-
61
- it('toString() renders a human-readable diagnostic summary', () => {
62
- const err = createStructuredError({
63
- message: 'Payment failed',
64
- why: 'Card declined by issuer',
65
- fix: 'Use a different card',
66
- link: 'https://docs.example.com/errors/card-declined',
67
- code: 'PAYMENT_DECLINED',
68
- status: 402,
69
- cause: new Error('upstream timeout'),
70
- });
71
-
72
- const output = err.toString();
73
- expect(output).toBe(
74
- [
75
- 'StructuredError: Payment failed',
76
- ' Why: Card declined by issuer',
77
- ' Fix: Use a different card',
78
- ' Link: https://docs.example.com/errors/card-declined',
79
- ' Code: PAYMENT_DECLINED',
80
- ' Status: 402',
81
- ' Caused by: Error: upstream timeout',
82
- ].join('\n'),
83
- );
84
- });
85
-
86
- it('toString() omits undefined fields', () => {
87
- const err = createStructuredError({ message: 'Something broke' });
88
- expect(err.toString()).toBe('StructuredError: Something broke');
89
- });
90
-
91
- it('extracts canonical attributes for span logging', () => {
92
- const err = createStructuredError({
93
- message: 'Export failed',
94
- why: 'Template not found',
95
- fix: 'Upload template and retry',
96
- details: { export: { format: 'pdf' } },
97
- });
98
-
99
- const attrs = getStructuredErrorAttributes(err);
100
- expect(attrs).toMatchObject({
101
- 'error.type': 'StructuredError',
102
- 'error.message': 'Export failed',
103
- 'error.why': 'Template not found',
104
- 'error.fix': 'Upload template and retry',
105
- 'error.details.export.format': 'pdf',
106
- });
107
- });
108
-
109
- it('records structured error onto trace context', () => {
110
- const ctx = {
111
- recordException: vi.fn(),
112
- setStatus: vi.fn(),
113
- setAttributes: vi.fn(),
114
- } as unknown as TraceContext;
115
-
116
- const err = createStructuredError({
117
- message: 'Checkout failed',
118
- why: 'Inventory mismatch',
119
- fix: 'Re-sync inventory and retry',
120
- });
121
-
122
- recordStructuredError(ctx, err);
123
-
124
- expect(ctx.recordException).toHaveBeenCalledWith(err);
125
- expect(ctx.setStatus).toHaveBeenCalledWith({
126
- code: 2,
127
- message: 'Checkout failed',
128
- });
129
- expect(ctx.setAttributes).toHaveBeenCalledWith(
130
- expect.objectContaining({
131
- 'error.message': 'Checkout failed',
132
- 'error.why': 'Inventory mismatch',
133
- 'error.fix': 'Re-sync inventory and retry',
134
- }),
135
- );
136
- });
137
- });
138
-
139
- describe('ctx.recordError', () => {
140
- it('records a structured error onto the underlying span', () => {
141
- const { span, recordException, setStatus, setAttributes } =
142
- createFakeSpan();
143
- const ctx = createTraceContext(span);
144
- const err = createStructuredError({
145
- message: 'Order failed',
146
- why: 'Inventory unavailable',
147
- fix: 'Retry after restock',
148
- });
149
-
150
- ctx.recordError(err);
151
-
152
- expect(recordException).toHaveBeenCalledWith(err);
153
- expect(setStatus).toHaveBeenCalledWith({
154
- code: 2,
155
- message: 'Order failed',
156
- });
157
- expect(setAttributes).toHaveBeenCalledWith(
158
- expect.objectContaining({
159
- 'error.message': 'Order failed',
160
- 'error.why': 'Inventory unavailable',
161
- 'error.fix': 'Retry after restock',
162
- }),
163
- );
164
- });
165
-
166
- it('coerces non-Error values to Error so it is safe in catch blocks', () => {
167
- const { span, recordException, setStatus, setAttributes } =
168
- createFakeSpan();
169
- const ctx = createTraceContext(span);
170
-
171
- ctx.recordError('boom');
172
-
173
- expect(recordException).toHaveBeenCalledTimes(1);
174
- const recorded = recordException.mock.calls[0][0];
175
- expect(recorded).toBeInstanceOf(Error);
176
- expect(recorded.message).toBe('boom');
177
- expect(setStatus).toHaveBeenCalledWith({ code: 2, message: 'boom' });
178
- expect(setAttributes).toHaveBeenCalled();
179
- });
180
- });
181
-
182
- describe('ctx.track', () => {
183
- it('exposes track on the trace context as the ergonomic replacement for ctx.addEvent', () => {
184
- const { span } = createFakeSpan();
185
- const ctx = createTraceContext(span);
186
-
187
- expect(typeof ctx.track).toBe('function');
188
- // Smoke test — should not throw without init() (track is a no-op when no queue is configured)
189
- expect(() => ctx.track('test.event', { foo: 'bar' })).not.toThrow();
190
- });
191
- });
@@ -1,157 +0,0 @@
1
- import { SpanStatusCode } from '@opentelemetry/api';
2
- import type { AttributeValue, TraceContext } from './trace-context';
3
- import { flattenToAttributes } from './flatten-attributes';
4
-
5
- const internalKey = Symbol.for('autotel.error.internal');
6
-
7
- export interface StructuredErrorInput {
8
- message: string;
9
- why?: string;
10
- fix?: string;
11
- link?: string;
12
- code?: string | number;
13
- status?: number;
14
- cause?: unknown;
15
- details?: Record<string, unknown>;
16
- name?: string;
17
- /** Backend-only context. Omitted from toJSON() and never serialized to clients. */
18
- internal?: Record<string, unknown>;
19
- }
20
-
21
- export interface StructuredError extends Error {
22
- why?: string;
23
- fix?: string;
24
- link?: string;
25
- code?: string | number;
26
- status?: number;
27
- details?: Record<string, unknown>;
28
- /** Backend-only context. Omitted from toJSON() and never serialized to clients. */
29
- readonly internal?: Record<string, unknown>;
30
- }
31
-
32
- export function createStructuredError(
33
- input: StructuredErrorInput,
34
- ): StructuredError {
35
- const error = new Error(input.message, {
36
- cause: input.cause,
37
- }) as StructuredError;
38
-
39
- error.name = input.name ?? 'StructuredError';
40
- if (input.why !== undefined) error.why = input.why;
41
- if (input.fix !== undefined) error.fix = input.fix;
42
- if (input.link !== undefined) error.link = input.link;
43
- if (input.code !== undefined) error.code = input.code;
44
- if (input.status !== undefined) error.status = input.status;
45
- if (input.details !== undefined) error.details = input.details;
46
-
47
- if (input.internal !== undefined) {
48
- Object.defineProperty(error, internalKey, {
49
- value: input.internal,
50
- enumerable: false,
51
- writable: false,
52
- configurable: true,
53
- });
54
- }
55
-
56
- Object.defineProperty(error, 'internal', {
57
- get() {
58
- return (
59
- this as StructuredError & { [internalKey]?: Record<string, unknown> }
60
- )[internalKey];
61
- },
62
- enumerable: false,
63
- configurable: true,
64
- });
65
-
66
- error.toString = () => {
67
- const lines = [`${error.name}: ${error.message}`];
68
- if (error.why) lines.push(` Why: ${error.why}`);
69
- if (error.fix) lines.push(` Fix: ${error.fix}`);
70
- if (error.link) lines.push(` Link: ${error.link}`);
71
- if (error.code !== undefined) lines.push(` Code: ${error.code}`);
72
- if (error.status !== undefined) lines.push(` Status: ${error.status}`);
73
- if (error.cause) {
74
- const cause = error.cause as Error;
75
- lines.push(` Caused by: ${cause.name}: ${cause.message}`);
76
- }
77
- return lines.join('\n');
78
- };
79
-
80
- return error;
81
- }
82
-
83
- export function structuredErrorToJSON(
84
- error: StructuredError,
85
- ): Record<string, unknown> {
86
- const result: Record<string, unknown> = {
87
- name: error.name,
88
- message: error.message,
89
- };
90
-
91
- if (error.status !== undefined) result.status = error.status;
92
- if (error.why || error.fix || error.link) {
93
- result.data = {
94
- ...(error.why && { why: error.why }),
95
- ...(error.fix && { fix: error.fix }),
96
- ...(error.link && { link: error.link }),
97
- };
98
- }
99
- if (error.code !== undefined) result.code = error.code;
100
- if (error.details) result.details = error.details;
101
- if (error.cause instanceof Error) {
102
- result.cause = { name: error.cause.name, message: error.cause.message };
103
- }
104
-
105
- return result;
106
- }
107
-
108
- export function getStructuredErrorAttributes(
109
- error: Error,
110
- ): Record<string, AttributeValue> {
111
- const structured = error as StructuredError;
112
- const attributes: Record<string, AttributeValue> = {
113
- 'error.type': error.name || 'Error',
114
- 'error.message': error.message,
115
- };
116
-
117
- if (error.stack) attributes['error.stack'] = error.stack;
118
- if (structured.why) attributes['error.why'] = structured.why;
119
- if (structured.fix) attributes['error.fix'] = structured.fix;
120
- if (structured.link) attributes['error.link'] = structured.link;
121
- if (structured.code !== undefined) {
122
- attributes['error.code'] =
123
- typeof structured.code === 'string'
124
- ? structured.code
125
- : String(structured.code);
126
- }
127
- if (structured.status !== undefined) {
128
- attributes['error.status'] = structured.status;
129
- }
130
- if (structured.details) {
131
- Object.assign(
132
- attributes,
133
- flattenToAttributes(structured.details, 'error.details'),
134
- );
135
- }
136
-
137
- return attributes;
138
- }
139
-
140
- export function recordStructuredError(
141
- ctx: Pick<TraceContext, 'setAttributes' | 'setStatus'>,
142
- error: Error,
143
- ): void {
144
- const maybeRecordException = (
145
- ctx as unknown as {
146
- recordException?: (e: Error) => void;
147
- }
148
- ).recordException;
149
- if (typeof maybeRecordException === 'function') {
150
- maybeRecordException(error);
151
- }
152
- ctx.setStatus({
153
- code: SpanStatusCode.ERROR,
154
- message: error.message,
155
- });
156
- ctx.setAttributes(getStructuredErrorAttributes(error));
157
- }
@@ -1,361 +0,0 @@
1
- /**
2
- * Integration tests for autotel
3
- *
4
- * Tests end-to-end flows with all components working together
5
- */
6
-
7
- import { describe, it, expect, beforeEach, afterEach } from 'vitest';
8
- import { init } from './init';
9
- import { trace } from './functional';
10
- import { track, resetEventQueue } from './track';
11
- import { Event, resetEvents } from './event';
12
- import { flush, shutdown } from './shutdown';
13
- import { resetMetrics } from './metric';
14
- import { resetConfig } from './config';
15
- import { EventAttributes, EventSubscriber } from './event-subscriber';
16
-
17
- // Test adapter that collects events
18
- class TestAdapter implements EventSubscriber {
19
- name = 'test-adapter';
20
- events: Array<{ type: string; name: string; attributes?: EventAttributes }> =
21
- [];
22
-
23
- async trackEvent(name: string, attributes?: EventAttributes): Promise<void> {
24
- this.events.push({ type: 'event', name, attributes });
25
- }
26
-
27
- async trackFunnelStep(
28
- funnel: string,
29
- status: string,
30
- attributes?: EventAttributes,
31
- ): Promise<void> {
32
- this.events.push({
33
- type: 'funnel',
34
- name: `${funnel}.${status}`,
35
- attributes,
36
- });
37
- }
38
-
39
- async trackOutcome(
40
- operation: string,
41
- status: string,
42
- attributes?: EventAttributes,
43
- ): Promise<void> {
44
- this.events.push({
45
- type: 'outcome',
46
- name: `${operation}.${status}`,
47
- attributes,
48
- });
49
- }
50
-
51
- async trackValue(
52
- metric: string,
53
- value: number,
54
- attributes?: EventAttributes,
55
- ): Promise<void> {
56
- this.events.push({
57
- type: 'value',
58
- name: metric,
59
- attributes: { ...attributes, value },
60
- });
61
- }
62
-
63
- async shutdown(): Promise<void> {
64
- // Cleanup if needed
65
- }
66
-
67
- reset(): void {
68
- this.events = [];
69
- }
70
- }
71
-
72
- describe('Integration Test Suite', () => {
73
- let testAdapter: TestAdapter;
74
-
75
- beforeEach(() => {
76
- // Reset all global state between tests
77
- resetEventQueue();
78
- resetEvents();
79
- resetMetrics();
80
- resetConfig();
81
- testAdapter = new TestAdapter();
82
- });
83
-
84
- afterEach(async () => {
85
- // Clean up after each test
86
- await shutdown();
87
- });
88
-
89
- describe('Full stack initialization', () => {
90
- it('should initialize all components together', () => {
91
- init({
92
- service: 'test-app',
93
- subscribers: [testAdapter],
94
- version: '1.0.0',
95
- environment: 'test',
96
- });
97
-
98
- expect(true).toBe(true); // Should not throw
99
- });
100
- });
101
-
102
- describe('Tracing + Events integration', () => {
103
- it('should correlate traces with events events', async () => {
104
- init({
105
- service: 'user-service',
106
- subscribers: [testAdapter],
107
- });
108
-
109
- // Create trace function
110
- const createUser = trace(async (userId: string, plan: string) => {
111
- // Track events event inside trace function
112
- track('user.signup', { userId, plan });
113
- return { id: userId, plan };
114
- });
115
-
116
- // Execute
117
- const result = await createUser('user123', 'pro');
118
-
119
- // Should return expected result
120
- expect(result).toEqual({ id: 'user123', plan: 'pro' });
121
-
122
- // Flush to send events
123
- await flush();
124
-
125
- // Events event should be tracked
126
- // (traceId correlation happens automatically)
127
- const event = testAdapter.events.filter((e) => e.name === 'user.signup');
128
- expect(event.length).toBeGreaterThan(0);
129
- });
130
-
131
- it('should handle nested trace functions', async () => {
132
- init({
133
- service: 'order-service',
134
- subscribers: [testAdapter],
135
- });
136
-
137
- const validateOrder = trace(async (orderId: string) => {
138
- track('order.validated', { orderId });
139
- return true;
140
- });
141
-
142
- const processPayment = trace(async (orderId: string, amount: number) => {
143
- track('payment.processed', { orderId, amount });
144
- return { success: true };
145
- });
146
-
147
- const createOrder = trace(async (orderId: string, amount: number) => {
148
- await validateOrder(orderId);
149
- await processPayment(orderId, amount);
150
- track('order.completed', { orderId, amount });
151
- return { orderId, status: 'completed' };
152
- });
153
-
154
- await createOrder('order123', 99.99);
155
- await flush();
156
-
157
- // All events should be tracked
158
- expect(testAdapter.events.length).toBeGreaterThanOrEqual(3);
159
- expect(testAdapter.events.map((e) => e.name)).toContain(
160
- 'order.validated',
161
- );
162
- expect(testAdapter.events.map((e) => e.name)).toContain(
163
- 'payment.processed',
164
- );
165
- expect(testAdapter.events.map((e) => e.name)).toContain(
166
- 'order.completed',
167
- );
168
- });
169
- });
170
-
171
- describe('Events class integration', () => {
172
- it('should track all events event types', async () => {
173
- const event = new Event('checkout', {
174
- subscribers: [testAdapter],
175
- });
176
-
177
- // Track different event types
178
- event.trackEvent('checkout.started', { cartValue: 149.99 });
179
- event.trackFunnelStep('checkout', 'started', { userId: '123' });
180
- event.trackFunnelStep('checkout', 'started', {
181
- userId: '123',
182
- step: 'payment_info',
183
- });
184
- event.trackFunnelStep('checkout', 'completed', { userId: '123' });
185
- event.trackOutcome('payment.process', 'success', { amount: 149.99 });
186
- event.trackValue('revenue', 149.99, { currency: 'USD' });
187
-
188
- // Flush adapters
189
- await event.flush();
190
-
191
- // All events should be captured
192
- expect(testAdapter.events.length).toBe(6);
193
- expect(testAdapter.events.map((e) => e.type)).toEqual([
194
- 'event',
195
- 'funnel',
196
- 'funnel',
197
- 'funnel',
198
- 'outcome',
199
- 'value',
200
- ]);
201
- });
202
- });
203
-
204
- describe('Error handling integration', () => {
205
- it('should handle adapter failures gracefully', async () => {
206
- const failingAdapter: EventSubscriber = {
207
- name: 'failing-adapter',
208
- trackEvent: async () => {
209
- throw new Error('Adapter error');
210
- },
211
- trackFunnelStep: async () => {},
212
- trackOutcome: async () => {},
213
- trackValue: async () => {},
214
- };
215
-
216
- const event = new Event('test', {
217
- subscribers: [failingAdapter, testAdapter], // Mix failing and working
218
- });
219
-
220
- // Should not throw even though one adapter fails
221
- event.trackEvent('test.event', { foo: 'bar' });
222
-
223
- await event.flush();
224
-
225
- // Working adapter should still receive events
226
- expect(testAdapter.events.length).toBeGreaterThan(0);
227
- });
228
-
229
- it('should handle circuit breaker opening', async () => {
230
- let callCount = 0;
231
-
232
- const unreliableAdapter: EventSubscriber = {
233
- name: 'unreliable-adapter',
234
- trackEvent: async () => {
235
- callCount++;
236
- // Fail first 5 times to trip circuit breaker
237
- if (callCount <= 5) {
238
- throw new Error('Service unavailable');
239
- }
240
- },
241
- trackFunnelStep: async () => {},
242
- trackOutcome: async () => {},
243
- trackValue: async () => {},
244
- };
245
-
246
- const event = new Event('test', {
247
- subscribers: [unreliableAdapter],
248
- });
249
-
250
- // Send events one at a time to allow circuit breaker to open
251
- for (let i = 0; i < 10; i++) {
252
- event.trackEvent(`event.${i}`, { index: i });
253
- // Wait a bit to allow circuit breaker to process
254
- await new Promise((resolve) => setTimeout(resolve, 10));
255
- }
256
-
257
- await event.flush();
258
-
259
- // Circuit should open after 5 failures
260
- // Remaining calls should be fast-failed
261
- expect(callCount).toBeLessThanOrEqual(6); // 5 failures + maybe 1 half-open test
262
- });
263
- });
264
-
265
- describe('Input validation integration', () => {
266
- it('should sanitize sensitive data across all components', async () => {
267
- init({
268
- service: 'auth-service',
269
- subscribers: [testAdapter],
270
- });
271
-
272
- // Track with sensitive data
273
- track('user.login', {
274
- email: 'user@example.com',
275
- password: 'secret123', // Should be redacted
276
- apiKey: 'abc123', // Should be redacted
277
- userId: '123', // Should NOT be redacted
278
- });
279
-
280
- await flush();
281
-
282
- const event = testAdapter.events.find((e) => e.name === 'user.login');
283
- expect(event?.attributes?.email).toBe('user@example.com');
284
- expect(event?.attributes?.password).toBe('[REDACTED]');
285
- expect(event?.attributes?.apiKey).toBe('[REDACTED]');
286
- expect(event?.attributes?.userId).toBe('123');
287
- });
288
-
289
- it('should validate event names', () => {
290
- const event = new Event('test', {
291
- subscribers: [testAdapter],
292
- });
293
-
294
- // Invalid event names should throw
295
- expect(() => {
296
- event.trackEvent('', { foo: 'bar' });
297
- }).toThrow();
298
-
299
- expect(() => {
300
- event.trackEvent('invalid event name', { foo: 'bar' });
301
- }).toThrow();
302
- });
303
- });
304
-
305
- describe('Graceful shutdown integration', () => {
306
- it('should shutdown all components cleanly', async () => {
307
- init({
308
- service: 'test-service',
309
- subscribers: [testAdapter],
310
- });
311
-
312
- track('test.event', { foo: 'bar' });
313
-
314
- await shutdown();
315
-
316
- // Events should be flushed
317
- expect(testAdapter.events.length).toBeGreaterThan(0);
318
- });
319
- });
320
-
321
- describe('Performance under load', () => {
322
- it('should handle high event volume', async () => {
323
- init({
324
- service: 'high-volume-service',
325
- subscribers: [testAdapter],
326
- });
327
-
328
- // Send 1000 events
329
- for (let i = 0; i < 1000; i++) {
330
- track(`event.${i}`, { index: i });
331
- }
332
-
333
- await flush({ timeout: 10_000 }); // 10s timeout for high-volume test
334
-
335
- // All events should be captured
336
- expect(testAdapter.events.length).toBeGreaterThanOrEqual(1000);
337
- });
338
-
339
- it('should batch events efficiently', async () => {
340
- init({
341
- service: 'batch-test',
342
- subscribers: [testAdapter],
343
- });
344
-
345
- const startTime = Date.now();
346
-
347
- // Track 500 events
348
- for (let i = 0; i < 500; i++) {
349
- track(`event.${i}`, { index: i });
350
- }
351
-
352
- await flush({ timeout: 10_000 }); // 10s timeout for high-volume test
353
-
354
- const duration = Date.now() - startTime;
355
-
356
- // Should complete in reasonable time (batching improves performance)
357
- // This is a sanity check - actual threshold depends on hardware
358
- expect(duration).toBeLessThan(10_000); // 10 seconds (increased for CI/CD reliability)
359
- });
360
- });
361
- });