@geekmidas/telescope 9.0.2 → 10.0.0-alpha.1

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 (122) hide show
  1. package/README.md +14 -4
  2. package/dist/{http-D5kn3_Mt.d.mts → http-BiNtg85L.d.mts} +3 -3
  3. package/dist/{http-D5kn3_Mt.d.mts.map → http-BiNtg85L.d.mts.map} +1 -1
  4. package/dist/instrumentation/http.d.mts +1 -1
  5. package/dist/instrumentation/index.cjs +2 -2
  6. package/dist/instrumentation/index.d.cts +2 -2
  7. package/dist/instrumentation/index.d.mts +3 -3
  8. package/dist/instrumentation/index.mjs +2 -2
  9. package/dist/instrumentation/middleware.cjs +1 -1
  10. package/dist/instrumentation/middleware.d.cts +1 -1
  11. package/dist/instrumentation/middleware.d.mts +1 -1
  12. package/dist/instrumentation/middleware.mjs +1 -1
  13. package/dist/instrumentation/otel.cjs +1 -1
  14. package/dist/instrumentation/otel.d.cts +1 -1
  15. package/dist/instrumentation/otel.d.mts +1 -1
  16. package/dist/instrumentation/otel.mjs +1 -1
  17. package/dist/logger/console.d.cts.map +1 -1
  18. package/dist/logger/pino.d.mts +2 -2
  19. package/dist/{middleware-DqPQpcup.cjs → middleware-Bcq6XXGG.cjs} +2 -2
  20. package/dist/middleware-Bcq6XXGG.cjs.map +1 -0
  21. package/dist/{middleware-4-GrQlOT.mjs → middleware-D1XEHvyy.mjs} +2 -2
  22. package/dist/middleware-D1XEHvyy.mjs.map +1 -0
  23. package/dist/{middleware-CA84nsNN.d.cts → middleware-PeyS-9Ny.d.cts} +2 -2
  24. package/dist/{middleware-CA84nsNN.d.cts.map → middleware-PeyS-9Ny.d.cts.map} +1 -1
  25. package/dist/{middleware-DAceVpfw.d.mts → middleware-oHvo_ZgU.d.mts} +2 -2
  26. package/dist/{middleware-DAceVpfw.d.mts.map → middleware-oHvo_ZgU.d.mts.map} +1 -1
  27. package/dist/{otel-40udNP5g.mjs → otel-B9bNoeZ2.mjs} +3 -3
  28. package/dist/otel-B9bNoeZ2.mjs.map +1 -0
  29. package/dist/{otel-SBVoVEHr.d.cts → otel-Bk89b1lX.d.cts} +3 -3
  30. package/dist/{otel-1bJPb2Z7.d.mts.map → otel-Bk89b1lX.d.cts.map} +1 -1
  31. package/dist/{otel-COrpz_GZ.cjs → otel-BzjOtVxZ.cjs} +3 -3
  32. package/dist/otel-BzjOtVxZ.cjs.map +1 -0
  33. package/dist/{otel-1bJPb2Z7.d.mts → otel-lPMsM26e.d.mts} +3 -3
  34. package/dist/{otel-SBVoVEHr.d.cts.map → otel-lPMsM26e.d.mts.map} +1 -1
  35. package/dist/storage/kysely.cjs +48 -38
  36. package/dist/storage/kysely.cjs.map +1 -1
  37. package/dist/storage/kysely.d.cts +29 -9
  38. package/dist/storage/kysely.d.cts.map +1 -1
  39. package/dist/storage/kysely.d.mts +29 -9
  40. package/dist/storage/kysely.d.mts.map +1 -1
  41. package/dist/storage/kysely.mjs +48 -38
  42. package/dist/storage/kysely.mjs.map +1 -1
  43. package/dist/tracing-PnECEbEu.d.mts.map +1 -1
  44. package/package.json +6 -3
  45. package/CHANGELOG.md +0 -72
  46. package/dist/middleware-4-GrQlOT.mjs.map +0 -1
  47. package/dist/middleware-DqPQpcup.cjs.map +0 -1
  48. package/dist/otel-40udNP5g.mjs.map +0 -1
  49. package/dist/otel-COrpz_GZ.cjs.map +0 -1
  50. package/src/Telescope.ts +0 -561
  51. package/src/__tests__/Telescope.spec.ts +0 -438
  52. package/src/__tests__/pino-transport.spec.ts +0 -115
  53. package/src/__tests__/redact.spec.ts +0 -336
  54. package/src/adapters/__tests__/lambda.spec.ts +0 -318
  55. package/src/adapters/__tests__/middy.spec.ts +0 -741
  56. package/src/adapters/index.ts +0 -22
  57. package/src/adapters/lambda.ts +0 -432
  58. package/src/adapters/middy.ts +0 -402
  59. package/src/adapters/types.ts +0 -181
  60. package/src/core.ts +0 -51
  61. package/src/index.ts +0 -34
  62. package/src/instrumentation/__tests__/core.spec.ts +0 -248
  63. package/src/instrumentation/__tests__/hono.spec.ts +0 -348
  64. package/src/instrumentation/__tests__/middleware.spec.ts +0 -528
  65. package/src/instrumentation/__tests__/otel.spec.ts +0 -291
  66. package/src/instrumentation/__tests__/tracing.spec.ts +0 -208
  67. package/src/instrumentation/core.ts +0 -228
  68. package/src/instrumentation/hono.ts +0 -270
  69. package/src/instrumentation/http.ts +0 -306
  70. package/src/instrumentation/index.ts +0 -90
  71. package/src/instrumentation/middleware.ts +0 -297
  72. package/src/instrumentation/otel.ts +0 -271
  73. package/src/instrumentation/setup.ts +0 -246
  74. package/src/instrumentation/tracing.ts +0 -145
  75. package/src/logger/__tests__/console.spec.ts +0 -366
  76. package/src/logger/__tests__/pino.spec.ts +0 -217
  77. package/src/logger/console.ts +0 -230
  78. package/src/logger/pino.ts +0 -201
  79. package/src/metrics/MetricsAggregator.ts +0 -555
  80. package/src/metrics/__tests__/MetricsAggregator.spec.ts +0 -298
  81. package/src/metrics/index.ts +0 -2
  82. package/src/metrics/storage/InMemoryMetricsStorage.ts +0 -380
  83. package/src/metrics/storage/MetricsStorage.ts +0 -74
  84. package/src/metrics/storage/index.ts +0 -3
  85. package/src/metrics/storage/types.ts +0 -243
  86. package/src/otlp/__tests__/receiver.spec.ts +0 -367
  87. package/src/otlp/__tests__/transformer.spec.ts +0 -455
  88. package/src/otlp/hono.ts +0 -120
  89. package/src/otlp/index.ts +0 -22
  90. package/src/otlp/receiver.ts +0 -162
  91. package/src/otlp/transformer.ts +0 -367
  92. package/src/otlp/types.ts +0 -364
  93. package/src/redact.ts +0 -116
  94. package/src/server/__tests__/hono.spec.ts +0 -814
  95. package/src/server/hono.ts +0 -442
  96. package/src/storage/__tests__/kysely.spec.ts +0 -715
  97. package/src/storage/__tests__/memory.spec.ts +0 -694
  98. package/src/storage/kysely.ts +0 -599
  99. package/src/storage/memory.ts +0 -204
  100. package/src/types.ts +0 -447
  101. package/src/ui-assets.ts +0 -40
  102. package/tsconfig.json +0 -9
  103. package/ui/CHANGELOG.md +0 -7
  104. package/ui/index.html +0 -12
  105. package/ui/node_modules/.bin/tsc +0 -21
  106. package/ui/node_modules/.bin/tsserver +0 -21
  107. package/ui/node_modules/.bin/vite +0 -21
  108. package/ui/package.json +0 -24
  109. package/ui/src/App.tsx +0 -595
  110. package/ui/src/api.ts +0 -88
  111. package/ui/src/components/ExceptionDetail.tsx +0 -100
  112. package/ui/src/components/FilterBar.tsx +0 -162
  113. package/ui/src/components/LogDetail.tsx +0 -91
  114. package/ui/src/components/RequestDetail.tsx +0 -143
  115. package/ui/src/main.tsx +0 -10
  116. package/ui/src/styles.css +0 -11
  117. package/ui/src/types.ts +0 -63
  118. package/ui/src/vite-env.d.ts +0 -1
  119. package/ui/src/vite-plugin-gkm-config.ts +0 -54
  120. package/ui/tsconfig.json +0 -20
  121. package/ui/tsconfig.tsbuildinfo +0 -1
  122. package/ui/vite.config.ts +0 -13
@@ -1,741 +0,0 @@
1
- import type {
2
- APIGatewayProxyEvent,
3
- APIGatewayProxyEventV2,
4
- Context,
5
- } from 'aws-lambda';
6
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
7
- import { InMemoryStorage } from '../../storage/memory';
8
- import { Telescope } from '../../Telescope';
9
- import { createTelescopeHandler, telescopeMiddleware } from '../middy';
10
-
11
- describe('Telescope Middy Middleware', () => {
12
- let telescope: Telescope;
13
- let storage: InMemoryStorage;
14
- let mockContext: Context;
15
-
16
- beforeEach(() => {
17
- storage = new InMemoryStorage();
18
- telescope = new Telescope({ storage });
19
-
20
- mockContext = {
21
- callbackWaitsForEmptyEventLoop: true,
22
- functionName: 'test-function',
23
- functionVersion: '1',
24
- invokedFunctionArn: 'arn:aws:lambda:us-east-1:123456789:function:test',
25
- memoryLimitInMB: '128',
26
- awsRequestId: 'test-request-id',
27
- logGroupName: '/aws/lambda/test',
28
- logStreamName: '2024/01/01/[$LATEST]abc123',
29
- getRemainingTimeInMillis: () => 10000,
30
- done: vi.fn(),
31
- fail: vi.fn(),
32
- succeed: vi.fn(),
33
- };
34
- });
35
-
36
- afterEach(() => {
37
- telescope.destroy();
38
- });
39
-
40
- describe('telescopeMiddleware', () => {
41
- describe('before hook', () => {
42
- it('should set callbackWaitsForEmptyEventLoop to false', async () => {
43
- const middleware = telescopeMiddleware(telescope);
44
- const request = {
45
- event: createV2Event(),
46
- context: mockContext,
47
- response: null,
48
- error: null,
49
- internal: {},
50
- };
51
-
52
- await middleware.before?.(request as any);
53
-
54
- expect(request.context.callbackWaitsForEmptyEventLoop).toBe(false);
55
- });
56
-
57
- it('should store start time on request', async () => {
58
- const middleware = telescopeMiddleware(telescope);
59
- const request = {
60
- event: createV2Event(),
61
- context: mockContext,
62
- response: null,
63
- error: null,
64
- internal: {},
65
- };
66
-
67
- await middleware.before?.(request as any);
68
-
69
- expect((request as any).__telescopeStartTime).toBeDefined();
70
- expect(typeof (request as any).__telescopeStartTime).toBe('number');
71
- });
72
- });
73
-
74
- describe('after hook', () => {
75
- it('should record request to Telescope for v2 events', async () => {
76
- const middleware = telescopeMiddleware(telescope);
77
- const event = createV2Event({
78
- method: 'POST',
79
- path: '/api/users',
80
- body: JSON.stringify({ name: 'John' }),
81
- });
82
- const request = {
83
- event,
84
- context: mockContext,
85
- response: { statusCode: 201, body: JSON.stringify({ id: '123' }) },
86
- error: null,
87
- internal: {},
88
- __telescopeStartTime: Date.now() - 100,
89
- };
90
-
91
- await middleware.after?.(request as any);
92
-
93
- const requests = await storage.getRequests();
94
- expect(requests).toHaveLength(1);
95
- expect(requests[0].method).toBe('POST');
96
- expect(requests[0].path).toBe('/api/users');
97
- expect(requests[0].status).toBe(201);
98
- expect(requests[0].duration).toBeGreaterThanOrEqual(100);
99
- });
100
-
101
- it('should record request to Telescope for v1 events', async () => {
102
- const middleware = telescopeMiddleware(telescope);
103
- const event = createV1Event({
104
- method: 'GET',
105
- path: '/api/items',
106
- query: { page: '1' },
107
- });
108
- const request = {
109
- event,
110
- context: mockContext,
111
- response: { statusCode: 200, body: JSON.stringify({ items: [] }) },
112
- error: null,
113
- internal: {},
114
- __telescopeStartTime: Date.now() - 50,
115
- };
116
-
117
- await middleware.after?.(request as any);
118
-
119
- const requests = await storage.getRequests();
120
- expect(requests).toHaveLength(1);
121
- expect(requests[0].method).toBe('GET');
122
- expect(requests[0].path).toBe('/api/items');
123
- expect(requests[0].status).toBe(200);
124
- });
125
-
126
- it('should respect recordBody option when false', async () => {
127
- const middleware = telescopeMiddleware(telescope, {
128
- recordBody: false,
129
- });
130
- const event = createV2Event({
131
- method: 'POST',
132
- path: '/api/users',
133
- body: JSON.stringify({ secret: 'password123' }),
134
- });
135
- const request = {
136
- event,
137
- context: mockContext,
138
- response: {
139
- statusCode: 200,
140
- body: JSON.stringify({ token: 'secret-token' }),
141
- },
142
- error: null,
143
- internal: {},
144
- __telescopeStartTime: Date.now(),
145
- };
146
-
147
- await middleware.after?.(request as any);
148
-
149
- const requests = await storage.getRequests();
150
- expect(requests).toHaveLength(1);
151
- expect(requests[0].body).toBeUndefined();
152
- expect(requests[0].responseBody).toBeUndefined();
153
- });
154
-
155
- it('should include body when recordBody is true (default)', async () => {
156
- const middleware = telescopeMiddleware(telescope);
157
- const event = createV2Event({
158
- method: 'POST',
159
- path: '/api/users',
160
- body: JSON.stringify({ name: 'Test' }),
161
- });
162
- const request = {
163
- event,
164
- context: mockContext,
165
- response: { statusCode: 200, body: JSON.stringify({ id: '1' }) },
166
- error: null,
167
- internal: {},
168
- __telescopeStartTime: Date.now(),
169
- };
170
-
171
- await middleware.after?.(request as any);
172
-
173
- const requests = await storage.getRequests();
174
- expect(requests[0].body).toEqual({ name: 'Test' });
175
- expect(requests[0].responseBody).toEqual({ id: '1' });
176
- });
177
-
178
- it('should extract IP from v2 event', async () => {
179
- const middleware = telescopeMiddleware(telescope);
180
- const event = createV2Event({ ip: '192.168.1.1' });
181
- const request = {
182
- event,
183
- context: mockContext,
184
- response: { statusCode: 200 },
185
- error: null,
186
- internal: {},
187
- __telescopeStartTime: Date.now(),
188
- };
189
-
190
- await middleware.after?.(request as any);
191
-
192
- const requests = await storage.getRequests();
193
- expect(requests[0].ip).toBe('192.168.1.1');
194
- });
195
-
196
- it('should extract IP from v1 event', async () => {
197
- const middleware = telescopeMiddleware(telescope);
198
- const event = createV1Event({ ip: '10.0.0.1' });
199
- const request = {
200
- event,
201
- context: mockContext,
202
- response: { statusCode: 200 },
203
- error: null,
204
- internal: {},
205
- __telescopeStartTime: Date.now(),
206
- };
207
-
208
- await middleware.after?.(request as any);
209
-
210
- const requests = await storage.getRequests();
211
- expect(requests[0].ip).toBe('10.0.0.1');
212
- });
213
- });
214
-
215
- describe('onError hook', () => {
216
- it('should record exception to Telescope', async () => {
217
- const middleware = telescopeMiddleware(telescope);
218
- const error = new Error('Something went wrong');
219
- const request = {
220
- event: createV2Event({ path: '/api/error' }),
221
- context: mockContext,
222
- response: null,
223
- error,
224
- internal: {},
225
- __telescopeStartTime: Date.now(),
226
- };
227
-
228
- await middleware.onError?.(request as any);
229
-
230
- const exceptions = await storage.getExceptions();
231
- expect(exceptions).toHaveLength(1);
232
- expect(exceptions[0].message).toBe('Something went wrong');
233
- });
234
-
235
- it('should record failed request with 500 status', async () => {
236
- const middleware = telescopeMiddleware(telescope);
237
- const error = new Error('Database connection failed');
238
- const request = {
239
- event: createV2Event({ method: 'POST', path: '/api/data' }),
240
- context: mockContext,
241
- response: null,
242
- error,
243
- internal: {},
244
- __telescopeStartTime: Date.now() - 200,
245
- };
246
-
247
- await middleware.onError?.(request as any);
248
-
249
- const requests = await storage.getRequests();
250
- expect(requests).toHaveLength(1);
251
- expect(requests[0].status).toBe(500);
252
- expect(requests[0].path).toBe('/api/data');
253
- expect(requests[0].responseBody).toEqual({
254
- error: 'Database connection failed',
255
- });
256
- });
257
- });
258
- });
259
-
260
- describe('createTelescopeHandler', () => {
261
- it('should wrap handler and record successful request', async () => {
262
- const baseHandler = async () => ({
263
- statusCode: 200,
264
- body: JSON.stringify({ success: true }),
265
- });
266
-
267
- const handler = createTelescopeHandler(telescope, baseHandler);
268
- const event = createV2Event({ method: 'GET', path: '/api/health' });
269
-
270
- const result = await handler(event, mockContext);
271
-
272
- expect(result).toEqual({
273
- statusCode: 200,
274
- body: JSON.stringify({ success: true }),
275
- });
276
-
277
- const requests = await storage.getRequests();
278
- expect(requests).toHaveLength(1);
279
- expect(requests[0].method).toBe('GET');
280
- expect(requests[0].path).toBe('/api/health');
281
- expect(requests[0].status).toBe(200);
282
- });
283
-
284
- it('should set callbackWaitsForEmptyEventLoop to false', async () => {
285
- const baseHandler = async () => ({ statusCode: 200 });
286
- const handler = createTelescopeHandler(telescope, baseHandler);
287
- const event = createV2Event();
288
-
289
- await handler(event, mockContext);
290
-
291
- expect(mockContext.callbackWaitsForEmptyEventLoop).toBe(false);
292
- });
293
-
294
- it('should record exception on error and rethrow', async () => {
295
- const error = new Error('Handler failed');
296
- const baseHandler = async () => {
297
- throw error;
298
- };
299
- const handler = createTelescopeHandler(telescope, baseHandler);
300
- const event = createV2Event({ path: '/api/failing' });
301
-
302
- await expect(handler(event, mockContext)).rejects.toThrow(
303
- 'Handler failed',
304
- );
305
-
306
- const exceptions = await storage.getExceptions();
307
- expect(exceptions).toHaveLength(1);
308
- expect(exceptions[0].message).toBe('Handler failed');
309
- });
310
-
311
- it('should respect recordBody option', async () => {
312
- const baseHandler = async () => ({
313
- statusCode: 200,
314
- body: JSON.stringify({ token: 'secret' }),
315
- });
316
-
317
- const handler = createTelescopeHandler(telescope, baseHandler, {
318
- recordBody: false,
319
- });
320
- const event = createV2Event({
321
- method: 'POST',
322
- body: JSON.stringify({ password: 'secret' }),
323
- });
324
-
325
- await handler(event, mockContext);
326
-
327
- const requests = await storage.getRequests();
328
- expect(requests[0].body).toBeUndefined();
329
- expect(requests[0].responseBody).toBeUndefined();
330
- });
331
-
332
- it('should calculate duration correctly', async () => {
333
- const baseHandler = async () => {
334
- await new Promise((resolve) => setTimeout(resolve, 50));
335
- return { statusCode: 200 };
336
- };
337
-
338
- const handler = createTelescopeHandler(telescope, baseHandler);
339
- const event = createV2Event();
340
-
341
- await handler(event, mockContext);
342
-
343
- const requests = await storage.getRequests();
344
- // Use 45ms threshold to account for setTimeout timing imprecision
345
- expect(requests[0].duration).toBeGreaterThanOrEqual(45);
346
- });
347
- });
348
-
349
- describe('request data extraction', () => {
350
- it('should handle base64 encoded body', async () => {
351
- const middleware = telescopeMiddleware(telescope);
352
- const bodyContent = { data: 'test' };
353
- const base64Body = Buffer.from(JSON.stringify(bodyContent)).toString(
354
- 'base64',
355
- );
356
-
357
- const event: APIGatewayProxyEventV2 = {
358
- ...createV2Event(),
359
- body: base64Body,
360
- isBase64Encoded: true,
361
- };
362
-
363
- const request = {
364
- event,
365
- context: mockContext,
366
- response: { statusCode: 200 },
367
- error: null,
368
- internal: {},
369
- __telescopeStartTime: Date.now(),
370
- };
371
-
372
- await middleware.after?.(request as any);
373
-
374
- const requests = await storage.getRequests();
375
- expect(requests[0].body).toEqual({ data: 'test' });
376
- });
377
-
378
- it('should handle non-JSON body gracefully', async () => {
379
- const middleware = telescopeMiddleware(telescope);
380
- const event = createV2Event({ body: 'plain text body' });
381
- const request = {
382
- event,
383
- context: mockContext,
384
- response: { statusCode: 200 },
385
- error: null,
386
- internal: {},
387
- __telescopeStartTime: Date.now(),
388
- };
389
-
390
- await middleware.after?.(request as any);
391
-
392
- const requests = await storage.getRequests();
393
- expect(requests[0].body).toBe('plain text body');
394
- });
395
-
396
- it('should handle null body', async () => {
397
- const middleware = telescopeMiddleware(telescope);
398
- const event = createV2Event({ body: null });
399
- const request = {
400
- event,
401
- context: mockContext,
402
- response: { statusCode: 200 },
403
- error: null,
404
- internal: {},
405
- __telescopeStartTime: Date.now(),
406
- };
407
-
408
- await middleware.after?.(request as any);
409
-
410
- const requests = await storage.getRequests();
411
- expect(requests[0].body).toBeUndefined();
412
- });
413
-
414
- it('should construct URL with query string for v2 events', async () => {
415
- const middleware = telescopeMiddleware(telescope);
416
- const event = createV2Event({
417
- path: '/api/search',
418
- queryString: 'q=test&page=1',
419
- });
420
- const request = {
421
- event,
422
- context: mockContext,
423
- response: { statusCode: 200 },
424
- error: null,
425
- internal: {},
426
- __telescopeStartTime: Date.now(),
427
- };
428
-
429
- await middleware.after?.(request as any);
430
-
431
- const requests = await storage.getRequests();
432
- expect(requests[0].url).toBe('/api/search?q=test&page=1');
433
- });
434
-
435
- it('should normalize headers to lowercase', async () => {
436
- const middleware = telescopeMiddleware(telescope);
437
- const event = createV2Event();
438
- event.headers = {
439
- 'Content-Type': 'application/json',
440
- 'X-Custom-Header': 'value',
441
- Authorization: 'Bearer token',
442
- };
443
- const request = {
444
- event,
445
- context: mockContext,
446
- response: { statusCode: 200 },
447
- error: null,
448
- internal: {},
449
- __telescopeStartTime: Date.now(),
450
- };
451
-
452
- await middleware.after?.(request as any);
453
-
454
- const requests = await storage.getRequests();
455
- expect(requests[0].headers).toEqual({
456
- 'content-type': 'application/json',
457
- 'x-custom-header': 'value',
458
- authorization: 'Bearer token',
459
- });
460
- });
461
- });
462
-
463
- describe('response data extraction', () => {
464
- it('should handle response without statusCode', async () => {
465
- const middleware = telescopeMiddleware(telescope);
466
- const request = {
467
- event: createV2Event(),
468
- context: mockContext,
469
- response: { data: 'raw response' }, // No statusCode
470
- error: null,
471
- internal: {},
472
- __telescopeStartTime: Date.now(),
473
- };
474
-
475
- await middleware.after?.(request as any);
476
-
477
- const requests = await storage.getRequests();
478
- expect(requests[0].status).toBe(200); // Default status
479
- });
480
-
481
- it('should parse JSON response body', async () => {
482
- const middleware = telescopeMiddleware(telescope);
483
- const request = {
484
- event: createV2Event(),
485
- context: mockContext,
486
- response: {
487
- statusCode: 200,
488
- body: JSON.stringify({ items: [1, 2, 3] }),
489
- },
490
- error: null,
491
- internal: {},
492
- __telescopeStartTime: Date.now(),
493
- };
494
-
495
- await middleware.after?.(request as any);
496
-
497
- const requests = await storage.getRequests();
498
- expect(requests[0].responseBody).toEqual({ items: [1, 2, 3] });
499
- });
500
-
501
- it('should handle non-JSON response body', async () => {
502
- const middleware = telescopeMiddleware(telescope);
503
- const request = {
504
- event: createV2Event(),
505
- context: mockContext,
506
- response: {
507
- statusCode: 200,
508
- body: '<html>Hello</html>',
509
- },
510
- error: null,
511
- internal: {},
512
- __telescopeStartTime: Date.now(),
513
- };
514
-
515
- await middleware.after?.(request as any);
516
-
517
- const requests = await storage.getRequests();
518
- expect(requests[0].responseBody).toBe('<html>Hello</html>');
519
- });
520
- });
521
-
522
- describe('size tracking', () => {
523
- it('should capture request size from Content-Length header', async () => {
524
- const middleware = telescopeMiddleware(telescope);
525
- const body = JSON.stringify({ name: 'John', data: 'test payload' });
526
- const event = createV2Event({
527
- method: 'POST',
528
- path: '/api/data',
529
- body,
530
- headers: { 'content-length': String(Buffer.byteLength(body)) },
531
- });
532
- const request = {
533
- event,
534
- context: mockContext,
535
- response: { statusCode: 200, body: '{"ok":true}' },
536
- error: null,
537
- internal: {},
538
- __telescopeStartTime: Date.now(),
539
- };
540
-
541
- await middleware.after?.(request as any);
542
-
543
- const requests = await storage.getRequests();
544
- expect(requests[0].requestSize).toBe(Buffer.byteLength(body));
545
- });
546
-
547
- it('should capture response size from Content-Length header', async () => {
548
- const middleware = telescopeMiddleware(telescope);
549
- const responseBody = JSON.stringify({ users: ['alice', 'bob'] });
550
- const event = createV2Event({ method: 'GET', path: '/api/users' });
551
- const request = {
552
- event,
553
- context: mockContext,
554
- response: {
555
- statusCode: 200,
556
- headers: {
557
- 'Content-Length': String(Buffer.byteLength(responseBody)),
558
- },
559
- body: responseBody,
560
- },
561
- error: null,
562
- internal: {},
563
- __telescopeStartTime: Date.now(),
564
- };
565
-
566
- await middleware.after?.(request as any);
567
-
568
- const requests = await storage.getRequests();
569
- expect(requests[0].responseSize).toBe(Buffer.byteLength(responseBody));
570
- });
571
-
572
- it('should calculate response size from body when Content-Length not set', async () => {
573
- const middleware = telescopeMiddleware(telescope);
574
- const responseBody = JSON.stringify({ items: [1, 2, 3, 4, 5] });
575
- const event = createV2Event({ method: 'GET', path: '/api/items' });
576
- const request = {
577
- event,
578
- context: mockContext,
579
- response: {
580
- statusCode: 200,
581
- body: responseBody,
582
- },
583
- error: null,
584
- internal: {},
585
- __telescopeStartTime: Date.now(),
586
- };
587
-
588
- await middleware.after?.(request as any);
589
-
590
- const requests = await storage.getRequests();
591
- expect(requests[0].responseSize).toBe(Buffer.byteLength(responseBody));
592
- });
593
-
594
- it('should handle multi-byte characters in response size', async () => {
595
- const middleware = telescopeMiddleware(telescope);
596
- const responseBody = JSON.stringify({ message: '你好世界' });
597
- const event = createV2Event({ method: 'GET', path: '/api/unicode' });
598
- const request = {
599
- event,
600
- context: mockContext,
601
- response: {
602
- statusCode: 200,
603
- body: responseBody,
604
- },
605
- error: null,
606
- internal: {},
607
- __telescopeStartTime: Date.now(),
608
- };
609
-
610
- await middleware.after?.(request as any);
611
-
612
- const requests = await storage.getRequests();
613
- // UTF-8 bytes for Chinese characters are more than string length
614
- expect(requests[0].responseSize).toBe(
615
- Buffer.byteLength(responseBody, 'utf8'),
616
- );
617
- });
618
-
619
- it('should track request size for v1 events', async () => {
620
- const middleware = telescopeMiddleware(telescope);
621
- const body = JSON.stringify({ data: 'v1 payload' });
622
- const event = createV1Event({
623
- method: 'POST',
624
- path: '/api/v1/data',
625
- body,
626
- headers: { 'content-length': String(Buffer.byteLength(body)) },
627
- });
628
- const request = {
629
- event,
630
- context: mockContext,
631
- response: { statusCode: 201, body: '{"id":"123"}' },
632
- error: null,
633
- internal: {},
634
- __telescopeStartTime: Date.now(),
635
- };
636
-
637
- await middleware.after?.(request as any);
638
-
639
- const requests = await storage.getRequests();
640
- expect(requests[0].requestSize).toBe(Buffer.byteLength(body));
641
- });
642
- });
643
- });
644
-
645
- // Helper functions to create mock events
646
-
647
- function createV2Event(
648
- options: {
649
- method?: string;
650
- path?: string;
651
- body?: string | null;
652
- query?: Record<string, string>;
653
- queryString?: string;
654
- ip?: string;
655
- headers?: Record<string, string>;
656
- } = {},
657
- ): APIGatewayProxyEventV2 {
658
- return {
659
- version: '2.0',
660
- routeKey: `${options.method || 'GET'} ${options.path || '/'}`,
661
- rawPath: options.path || '/',
662
- rawQueryString: options.queryString || '',
663
- headers: options.headers || {},
664
- queryStringParameters: options.query || {},
665
- body: options.body ?? null,
666
- isBase64Encoded: false,
667
- requestContext: {
668
- accountId: '123456789',
669
- apiId: 'api123',
670
- domainName: 'api.example.com',
671
- domainPrefix: 'api',
672
- http: {
673
- method: options.method || 'GET',
674
- path: options.path || '/',
675
- protocol: 'HTTP/1.1',
676
- sourceIp: options.ip || '127.0.0.1',
677
- userAgent: 'test-agent',
678
- },
679
- requestId: 'test-request-id',
680
- routeKey: `${options.method || 'GET'} ${options.path || '/'}`,
681
- stage: '$default',
682
- time: '01/Jan/2024:00:00:00 +0000',
683
- timeEpoch: Date.now(),
684
- },
685
- };
686
- }
687
-
688
- function createV1Event(
689
- options: {
690
- method?: string;
691
- path?: string;
692
- body?: string | null;
693
- query?: Record<string, string>;
694
- ip?: string;
695
- headers?: Record<string, string>;
696
- } = {},
697
- ): APIGatewayProxyEvent {
698
- return {
699
- httpMethod: options.method || 'GET',
700
- path: options.path || '/',
701
- headers: options.headers || {},
702
- multiValueHeaders: {},
703
- queryStringParameters: options.query || null,
704
- multiValueQueryStringParameters: null,
705
- pathParameters: null,
706
- stageVariables: null,
707
- body: options.body ?? null,
708
- isBase64Encoded: false,
709
- resource: options.path || '/',
710
- requestContext: {
711
- accountId: '123456789',
712
- apiId: 'api123',
713
- authorizer: null,
714
- httpMethod: options.method || 'GET',
715
- identity: {
716
- accessKey: null,
717
- accountId: null,
718
- apiKey: null,
719
- apiKeyId: null,
720
- caller: null,
721
- clientCert: null,
722
- cognitoAuthenticationProvider: null,
723
- cognitoAuthenticationType: null,
724
- cognitoIdentityId: null,
725
- cognitoIdentityPoolId: null,
726
- principalOrgId: null,
727
- sourceIp: options.ip || '127.0.0.1',
728
- user: null,
729
- userAgent: 'test-agent',
730
- userArn: null,
731
- },
732
- path: options.path || '/',
733
- protocol: 'HTTP/1.1',
734
- requestId: 'test-request-id',
735
- requestTimeEpoch: Date.now(),
736
- resourceId: 'resource123',
737
- resourcePath: options.path || '/',
738
- stage: 'test',
739
- },
740
- };
741
- }