autotel 4.0.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 (232) hide show
  1. package/README.md +26 -1
  2. package/dist/auto.cjs +2 -2
  3. package/dist/auto.js +1 -1
  4. package/dist/correlation-id.cjs +1 -1
  5. package/dist/correlation-id.js +1 -1
  6. package/dist/decorators.cjs +1 -1
  7. package/dist/decorators.js +1 -1
  8. package/dist/{event-Dlqr4ZNL.cjs → event-BhHREDJk.cjs} +3 -3
  9. package/dist/{event-Dlqr4ZNL.cjs.map → event-BhHREDJk.cjs.map} +1 -1
  10. package/dist/{event-_58ryBjh.js → event-ByBTV9M2.js} +3 -3
  11. package/dist/{event-_58ryBjh.js.map → event-ByBTV9M2.js.map} +1 -1
  12. package/dist/event.cjs +1 -1
  13. package/dist/event.js +1 -1
  14. package/dist/{functional-BGkT8J-h.js → functional-DtI0u4vx.js} +19 -19
  15. package/dist/functional-DtI0u4vx.js.map +1 -0
  16. package/dist/{functional-C4CzoVrX.cjs → functional-zpzNLhky.cjs} +4 -4
  17. package/dist/{functional-C4CzoVrX.cjs.map → functional-zpzNLhky.cjs.map} +1 -1
  18. package/dist/functional.cjs +1 -1
  19. package/dist/functional.js +1 -1
  20. package/dist/http.cjs +1 -1
  21. package/dist/http.js +1 -1
  22. package/dist/index.cjs +5 -5
  23. package/dist/index.d.cts +1 -1
  24. package/dist/index.d.ts +1 -1
  25. package/dist/index.js +5 -5
  26. package/dist/{init-DJQOdVlN.d.ts → init-B7u-DjxM.d.ts} +57 -2
  27. package/dist/init-B7u-DjxM.d.ts.map +1 -0
  28. package/dist/{init-DvapOXCc.cjs → init-BX7AmFRl.cjs} +40 -21
  29. package/dist/init-BX7AmFRl.cjs.map +1 -0
  30. package/dist/{init-Ch6t7MNI.js → init-D-jnNMix.js} +39 -20
  31. package/dist/init-D-jnNMix.js.map +1 -0
  32. package/dist/{init-CNp-ee80.d.cts → init-DSrRmVnz.d.cts} +57 -2
  33. package/dist/init-DSrRmVnz.d.cts.map +1 -0
  34. package/dist/instrumentation.cjs +1 -1
  35. package/dist/instrumentation.js +1 -1
  36. package/dist/logger-D3Ej3DII.js +446 -0
  37. package/dist/logger-D3Ej3DII.js.map +1 -0
  38. package/dist/logger-thMPLpOG.cjs +487 -0
  39. package/dist/logger-thMPLpOG.cjs.map +1 -0
  40. package/dist/logger.cjs +8 -236
  41. package/dist/logger.js +2 -204
  42. package/dist/messaging.cjs +1 -1
  43. package/dist/messaging.js +1 -1
  44. package/dist/semantic-helpers.cjs +1 -1
  45. package/dist/semantic-helpers.js +1 -1
  46. package/dist/{track-3HY4NGV-.cjs → track-D59FfpL0.cjs} +2 -2
  47. package/dist/{track-3HY4NGV-.cjs.map → track-D59FfpL0.cjs.map} +1 -1
  48. package/dist/{track-nsKVy-pj.js → track-wc0HafS_.js} +6 -6
  49. package/dist/track-wc0HafS_.js.map +1 -0
  50. package/dist/webhook.cjs +1 -1
  51. package/dist/webhook.js +1 -1
  52. package/dist/workflow-distributed.cjs +1 -1
  53. package/dist/workflow-distributed.js +1 -1
  54. package/dist/workflow.cjs +1 -1
  55. package/dist/workflow.js +1 -1
  56. package/dist/{yaml-config-B3dQ82GR.cjs → yaml-config-Ck2uB0Dp.cjs} +2 -1
  57. package/dist/yaml-config-Ck2uB0Dp.cjs.map +1 -0
  58. package/dist/yaml-config.cjs +1 -1
  59. package/dist/yaml-config.d.cts +7 -1
  60. package/dist/yaml-config.d.cts.map +1 -1
  61. package/dist/yaml-config.d.ts +7 -1
  62. package/dist/yaml-config.d.ts.map +1 -1
  63. package/dist/yaml-config.js +1 -0
  64. package/dist/yaml-config.js.map +1 -1
  65. package/package.json +1 -2
  66. package/skills/autotel-core/SKILL.md +2 -0
  67. package/skills/autotel-instrumentation/SKILL.md +25 -0
  68. package/skills/debug-missing-spans/SKILL.md +3 -1
  69. package/skills/migrate-to-autotel/SKILL.md +24 -23
  70. package/skills/review-otel-patterns/SKILL.md +5 -4
  71. package/dist/functional-BGkT8J-h.js.map +0 -1
  72. package/dist/init-CNp-ee80.d.cts.map +0 -1
  73. package/dist/init-Ch6t7MNI.js.map +0 -1
  74. package/dist/init-DJQOdVlN.d.ts.map +0 -1
  75. package/dist/init-DvapOXCc.cjs.map +0 -1
  76. package/dist/logger.cjs.map +0 -1
  77. package/dist/logger.js.map +0 -1
  78. package/dist/track-nsKVy-pj.js.map +0 -1
  79. package/dist/yaml-config-B3dQ82GR.cjs.map +0 -1
  80. package/src/attribute-redacting-processor.test.ts +0 -763
  81. package/src/attribute-redacting-processor.ts +0 -621
  82. package/src/attributes/attachers.ts +0 -161
  83. package/src/attributes/builders.ts +0 -529
  84. package/src/attributes/domains.ts +0 -42
  85. package/src/attributes/index.ts +0 -81
  86. package/src/attributes/registry.ts +0 -323
  87. package/src/attributes/types.ts +0 -211
  88. package/src/attributes/utils.ts +0 -64
  89. package/src/attributes/validators.ts +0 -266
  90. package/src/attributes.test.ts +0 -292
  91. package/src/auto.ts +0 -67
  92. package/src/autotel-logger.test.ts +0 -548
  93. package/src/autotel-logger.ts +0 -364
  94. package/src/baggage-span-processor.test.ts +0 -202
  95. package/src/baggage-span-processor.ts +0 -100
  96. package/src/business-baggage.test.ts +0 -500
  97. package/src/business-baggage.ts +0 -669
  98. package/src/circuit-breaker.test.ts +0 -341
  99. package/src/circuit-breaker.ts +0 -184
  100. package/src/config.test.ts +0 -94
  101. package/src/config.ts +0 -172
  102. package/src/correlated-events.test.ts +0 -151
  103. package/src/correlated-events.ts +0 -47
  104. package/src/correlation-id.test.ts +0 -163
  105. package/src/correlation-id.ts +0 -206
  106. package/src/db.test.ts +0 -252
  107. package/src/db.ts +0 -447
  108. package/src/decorators.test.ts +0 -153
  109. package/src/decorators.ts +0 -188
  110. package/src/define-event.test.ts +0 -41
  111. package/src/define-event.ts +0 -58
  112. package/src/devtools.ts +0 -60
  113. package/src/drain-pipeline.test.ts +0 -68
  114. package/src/drain-pipeline.ts +0 -199
  115. package/src/drain-toolkit.test.ts +0 -113
  116. package/src/drain-toolkit.ts +0 -129
  117. package/src/enricher-toolkit.test.ts +0 -67
  118. package/src/enricher-toolkit.ts +0 -79
  119. package/src/enrichers.test.ts +0 -150
  120. package/src/enrichers.ts +0 -145
  121. package/src/env-config.test.ts +0 -323
  122. package/src/env-config.ts +0 -309
  123. package/src/error-catalog.test.ts +0 -133
  124. package/src/error-catalog.ts +0 -262
  125. package/src/event-queue.test.ts +0 -864
  126. package/src/event-queue.ts +0 -699
  127. package/src/event-subscriber.ts +0 -262
  128. package/src/event-testing.ts +0 -197
  129. package/src/event.test.ts +0 -1104
  130. package/src/event.ts +0 -988
  131. package/src/events-config.ts +0 -235
  132. package/src/exporters.ts +0 -165
  133. package/src/filtering-span-processor.test.ts +0 -281
  134. package/src/filtering-span-processor.ts +0 -111
  135. package/src/flatten-attributes.test.ts +0 -76
  136. package/src/flatten-attributes.ts +0 -80
  137. package/src/functional.strict-types.typecheck.ts +0 -53
  138. package/src/functional.test.ts +0 -1464
  139. package/src/functional.ts +0 -2539
  140. package/src/functional.types.test.ts +0 -135
  141. package/src/hook.mjs +0 -15
  142. package/src/http.test.ts +0 -485
  143. package/src/http.ts +0 -424
  144. package/src/index.ts +0 -433
  145. package/src/init-auto-redactor.test.ts +0 -53
  146. package/src/init-redactor.test.ts +0 -8
  147. package/src/init.customization.test.ts +0 -594
  148. package/src/init.integrations.test.ts +0 -399
  149. package/src/init.openllmetry.test.ts +0 -194
  150. package/src/init.protocol.test.ts +0 -215
  151. package/src/init.ts +0 -2312
  152. package/src/instrumentation.test.ts +0 -108
  153. package/src/instrumentation.ts +0 -319
  154. package/src/logger.test.ts +0 -125
  155. package/src/logger.ts +0 -341
  156. package/src/messaging-adapters.test.ts +0 -595
  157. package/src/messaging-adapters.ts +0 -583
  158. package/src/messaging-testing.test.ts +0 -573
  159. package/src/messaging-testing.ts +0 -935
  160. package/src/messaging.test.ts +0 -1646
  161. package/src/messaging.ts +0 -2245
  162. package/src/metric-helpers.ts +0 -47
  163. package/src/metric-testing.ts +0 -197
  164. package/src/metric.ts +0 -446
  165. package/src/metrics.test.ts +0 -241
  166. package/src/node-require.ts +0 -123
  167. package/src/operation-context.ts +0 -93
  168. package/src/parse-error.test.ts +0 -73
  169. package/src/parse-error.ts +0 -112
  170. package/src/posthog-logs.test.ts +0 -115
  171. package/src/posthog-logs.ts +0 -77
  172. package/src/pretty-console-exporter.test.ts +0 -545
  173. package/src/pretty-console-exporter.ts +0 -413
  174. package/src/pretty-log-formatter.test.ts +0 -123
  175. package/src/pretty-log-formatter.ts +0 -210
  176. package/src/processors/canonical-log-line-processor.test.ts +0 -523
  177. package/src/processors/canonical-log-line-processor.ts +0 -396
  178. package/src/processors.ts +0 -152
  179. package/src/rate-limiter.test.ts +0 -199
  180. package/src/rate-limiter.ts +0 -98
  181. package/src/redact-values.test.ts +0 -90
  182. package/src/redact-values.ts +0 -34
  183. package/src/register.ts +0 -37
  184. package/src/request-logger.test.ts +0 -545
  185. package/src/request-logger.ts +0 -342
  186. package/src/sampling.test.ts +0 -1060
  187. package/src/sampling.ts +0 -737
  188. package/src/security-schema.test.ts +0 -45
  189. package/src/security-schema.ts +0 -107
  190. package/src/semantic-conventions.ts +0 -15
  191. package/src/semantic-helpers.test.ts +0 -226
  192. package/src/semantic-helpers.ts +0 -438
  193. package/src/shutdown.test.ts +0 -364
  194. package/src/shutdown.ts +0 -246
  195. package/src/span-name-normalizer.test.ts +0 -377
  196. package/src/span-name-normalizer.ts +0 -213
  197. package/src/stable-hash.ts +0 -27
  198. package/src/structured-error.test.ts +0 -191
  199. package/src/structured-error.ts +0 -157
  200. package/src/stub.integration.test.ts +0 -361
  201. package/src/tail-sampling-processor.test.ts +0 -230
  202. package/src/tail-sampling-processor.ts +0 -55
  203. package/src/test-span-collector.test.ts +0 -234
  204. package/src/test-span-collector.ts +0 -150
  205. package/src/testing.ts +0 -705
  206. package/src/trace-context.test.ts +0 -73
  207. package/src/trace-context.ts +0 -567
  208. package/src/trace-helpers.new.test.ts +0 -278
  209. package/src/trace-helpers.test.ts +0 -290
  210. package/src/trace-helpers.ts +0 -710
  211. package/src/trace-hybrid.test.ts +0 -42
  212. package/src/trace-hybrid.ts +0 -37
  213. package/src/tracer-provider.test.ts +0 -183
  214. package/src/tracer-provider.ts +0 -266
  215. package/src/track.test.ts +0 -154
  216. package/src/track.ts +0 -216
  217. package/src/validate.test.ts +0 -287
  218. package/src/validate.ts +0 -307
  219. package/src/validation-attributes.ts +0 -43
  220. package/src/validation.test.ts +0 -330
  221. package/src/validation.ts +0 -246
  222. package/src/variable-name-inference.test.ts +0 -178
  223. package/src/variable-name-inference.ts +0 -242
  224. package/src/webhook.test.ts +0 -649
  225. package/src/webhook.ts +0 -637
  226. package/src/workflow-distributed.test.ts +0 -786
  227. package/src/workflow-distributed.ts +0 -916
  228. package/src/workflow.async-safety.integration.test.ts +0 -345
  229. package/src/workflow.test.ts +0 -647
  230. package/src/workflow.ts +0 -810
  231. package/src/yaml-config.test.ts +0 -337
  232. package/src/yaml-config.ts +0 -342
@@ -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
- });