@stacksjs/bun-router 0.0.17 → 0.0.19

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 (153) hide show
  1. package/dist/chunk-2mx7fq49.js +4 -0
  2. package/dist/chunk-a8p83068.js +103 -0
  3. package/dist/{chunk-cgptvjdf.js → chunk-y3xq6wq6.js} +1 -1
  4. package/dist/cli.js +4 -3
  5. package/dist/container/index.js +1149 -211
  6. package/dist/container/service-provider.d.ts +3 -3
  7. package/dist/development/performance-profiler.d.ts +3 -3
  8. package/dist/development/route-debugger.d.ts +1 -1
  9. package/dist/development/route-inspector.d.ts +2 -2
  10. package/dist/index.js +369 -2209
  11. package/dist/observability/integration.d.ts +1 -1
  12. package/dist/response/macros.d.ts +1 -1
  13. package/dist/router/index.d.ts +7 -7
  14. package/dist/router/router.d.ts +0 -32
  15. package/dist/testing/performance-testing.d.ts +2 -2
  16. package/dist/testing/test-client.d.ts +1 -1
  17. package/dist/testing/websocket-testing.d.ts +1 -1
  18. package/package.json +7 -7
  19. package/dist/chunk-1ahs68ys.js +0 -18
  20. package/dist/chunk-g3ybefhg.js +0 -1923
  21. package/src/auth.ts +0 -489
  22. package/src/cache/lru-cache.ts +0 -457
  23. package/src/cache/middleware-memoization.ts +0 -531
  24. package/src/cache/route-cache-warmer.ts +0 -486
  25. package/src/cache/sqlite-cache.ts +0 -783
  26. package/src/cache/streaming-cache.ts +0 -572
  27. package/src/cli/colors.ts +0 -29
  28. package/src/cli/index.ts +0 -287
  29. package/src/cli/middleware.ts +0 -291
  30. package/src/cli/openapi.ts +0 -407
  31. package/src/cli/router.ts +0 -188
  32. package/src/cli/routes.ts +0 -265
  33. package/src/cli/utils.ts +0 -531
  34. package/src/cli.ts +0 -5
  35. package/src/config.ts +0 -322
  36. package/src/container/container.ts +0 -786
  37. package/src/container/contextual-binding.ts +0 -606
  38. package/src/container/decorators.ts +0 -368
  39. package/src/container/index.ts +0 -49
  40. package/src/container/service-provider.ts +0 -596
  41. package/src/development/hot-reload.ts +0 -673
  42. package/src/development/index.ts +0 -499
  43. package/src/development/performance-profiler.ts +0 -717
  44. package/src/development/route-debugger.ts +0 -527
  45. package/src/development/route-inspector.ts +0 -749
  46. package/src/development/typescript-utilities.ts +0 -682
  47. package/src/docs.ts +0 -397
  48. package/src/errors/circuit-breaker.ts +0 -733
  49. package/src/errors/error-handler.ts +0 -569
  50. package/src/errors/error-reporting.ts +0 -672
  51. package/src/errors/exceptions.ts +0 -536
  52. package/src/errors/graceful-degradation.ts +0 -623
  53. package/src/errors/index.ts +0 -21
  54. package/src/errors/router-errors.ts +0 -632
  55. package/src/file-serving/static-files.ts +0 -718
  56. package/src/index.ts +0 -66
  57. package/src/middleware/auth.ts +0 -220
  58. package/src/middleware/content_security_policy.ts +0 -215
  59. package/src/middleware/cors.ts +0 -142
  60. package/src/middleware/csrf.ts +0 -166
  61. package/src/middleware/ddos_protection.ts +0 -279
  62. package/src/middleware/file_security.ts +0 -191
  63. package/src/middleware/file_upload.ts +0 -275
  64. package/src/middleware/helmet.ts +0 -268
  65. package/src/middleware/index.ts +0 -117
  66. package/src/middleware/input_validation.ts +0 -453
  67. package/src/middleware/json_body.ts +0 -37
  68. package/src/middleware/performance_alerting.ts +0 -540
  69. package/src/middleware/performance_dashboard.ts +0 -661
  70. package/src/middleware/performance_monitor.ts +0 -945
  71. package/src/middleware/pipeline.ts +0 -489
  72. package/src/middleware/rate_limit.ts +0 -251
  73. package/src/middleware/request_id.ts +0 -36
  74. package/src/middleware/request_signing.ts +0 -638
  75. package/src/middleware/request_tracer.ts +0 -653
  76. package/src/middleware/response_cache.ts +0 -778
  77. package/src/middleware/security.ts +0 -482
  78. package/src/middleware/security_suite.ts +0 -257
  79. package/src/middleware/session.ts +0 -91
  80. package/src/model-binding/index.ts +0 -18
  81. package/src/model-binding/model-middleware.ts +0 -425
  82. package/src/model-binding/model-registry.ts +0 -550
  83. package/src/model-binding.ts +0 -370
  84. package/src/model-resolver-factory.ts +0 -106
  85. package/src/observability/correlation.ts +0 -691
  86. package/src/observability/health-checks.ts +0 -729
  87. package/src/observability/index.ts +0 -184
  88. package/src/observability/integration.ts +0 -548
  89. package/src/observability/metrics.ts +0 -753
  90. package/src/observability/tracing.ts +0 -638
  91. package/src/optimization/bun-utilities.ts +0 -778
  92. package/src/query-builder-integration.ts +0 -137
  93. package/src/request/context.ts +0 -109
  94. package/src/request/enhanced-request.ts +0 -876
  95. package/src/request/macros.ts +0 -822
  96. package/src/response/macros.ts +0 -665
  97. package/src/response/response-factory.ts +0 -596
  98. package/src/router/api-routes.ts +0 -243
  99. package/src/router/file-based-routing.ts +0 -697
  100. package/src/router/file-streaming.ts +0 -383
  101. package/src/router/fluent-routing.ts +0 -866
  102. package/src/router/group-organization.ts +0 -229
  103. package/src/router/handler-resolver.ts +0 -327
  104. package/src/router/http-methods.ts +0 -407
  105. package/src/router/index.ts +0 -193
  106. package/src/router/middleware-groups.ts +0 -222
  107. package/src/router/middleware-integration.ts +0 -399
  108. package/src/router/middleware.ts +0 -234
  109. package/src/router/model-binding.ts +0 -215
  110. package/src/router/optimized-route-matching.ts +0 -302
  111. package/src/router/route-building.ts +0 -221
  112. package/src/router/route-compiler.ts +0 -691
  113. package/src/router/route-matching.ts +0 -368
  114. package/src/router/route-trie.ts +0 -450
  115. package/src/router/router.ts +0 -1616
  116. package/src/router/server.ts +0 -684
  117. package/src/router/validation-integration.ts +0 -449
  118. package/src/router/view-rendering.ts +0 -233
  119. package/src/router/websocket.ts +0 -100
  120. package/src/routing/route-caching.ts +0 -402
  121. package/src/routing/route-throttling.ts +0 -469
  122. package/src/routing/subdomain-routing.ts +0 -492
  123. package/src/session/database-store.ts +0 -109
  124. package/src/session/file-store.ts +0 -148
  125. package/src/session/index.ts +0 -244
  126. package/src/session/memory-store.ts +0 -88
  127. package/src/session/redis-store.ts +0 -93
  128. package/src/streaming/index.ts +0 -17
  129. package/src/streaming/sse-handler.ts +0 -482
  130. package/src/streaming/stream-handler.ts +0 -552
  131. package/src/testing/auth-testing.ts +0 -448
  132. package/src/testing/file-upload-testing.ts +0 -543
  133. package/src/testing/index.ts +0 -10
  134. package/src/testing/middleware-testing.ts +0 -322
  135. package/src/testing/model-binding-testing.ts +0 -645
  136. package/src/testing/performance-testing.ts +0 -738
  137. package/src/testing/test-client.ts +0 -310
  138. package/src/testing/test-request.ts +0 -315
  139. package/src/testing/test-response.ts +0 -332
  140. package/src/testing/types.ts +0 -224
  141. package/src/testing/websocket-testing.ts +0 -590
  142. package/src/types/controller-types.ts +0 -385
  143. package/src/types/core.ts +0 -683
  144. package/src/types/middleware-types.ts +0 -422
  145. package/src/types/request-response-augmentation.ts +0 -489
  146. package/src/types/route-inference.ts +0 -372
  147. package/src/types.ts +0 -2123
  148. package/src/url.ts +0 -131
  149. package/src/utils/index.ts +0 -1
  150. package/src/utils/query-preservation.ts +0 -201
  151. package/src/utils.ts +0 -395
  152. package/src/validation/validator.ts +0 -688
  153. package/src/websocket/clustering.ts +0 -769
@@ -1,778 +0,0 @@
1
- /**
2
- * Bun Runtime Optimization Utilities
3
- *
4
- * Generic optimization utilities leveraging Bun's runtime capabilities
5
- */
6
-
7
- import { Buffer } from 'node:buffer'
8
- import process from 'node:process'
9
-
10
- export interface BunOptimizationConfig {
11
- enableJIT?: boolean
12
- enableGC?: boolean
13
- memoryLimit?: number
14
- cpuLimit?: number
15
- enableProfiling?: boolean
16
- enableTracing?: boolean
17
- }
18
-
19
- export interface PerformanceMetrics {
20
- memoryUsage: {
21
- rss: number
22
- heapUsed: number
23
- heapTotal: number
24
- external: number
25
- arrayBuffers: number
26
- }
27
- cpuUsage: {
28
- user: number
29
- system: number
30
- }
31
- eventLoop: {
32
- delay: number
33
- utilization: number
34
- }
35
- gc: {
36
- collections: number
37
- duration: number
38
- freed: number
39
- }
40
- bunSpecific: {
41
- jitCompilations: number
42
- nativeCallsOptimized: number
43
- fileSystemCacheHits: number
44
- }
45
- }
46
-
47
- /**
48
- * Bun runtime optimizer
49
- */
50
- export class BunOptimizer {
51
- private config: Required<BunOptimizationConfig>
52
- private metrics: PerformanceMetrics
53
- private gcObserver?: PerformanceObserver
54
- private performanceObserver?: PerformanceObserver
55
-
56
- constructor(config: BunOptimizationConfig = {}) {
57
- this.config = {
58
- enableJIT: config.enableJIT ?? true,
59
- enableGC: config.enableGC ?? true,
60
- memoryLimit: config.memoryLimit ?? 512 * 1024 * 1024, // 512MB
61
- cpuLimit: config.cpuLimit ?? 80, // 80% CPU
62
- enableProfiling: config.enableProfiling ?? false,
63
- enableTracing: config.enableTracing ?? false,
64
- ...config,
65
- }
66
-
67
- this.metrics = this.initializeMetrics()
68
- this.setupOptimizations()
69
- this.setupMonitoring()
70
- }
71
-
72
- /**
73
- * Initialize performance metrics
74
- */
75
- private initializeMetrics(): PerformanceMetrics {
76
- const memUsage = process.memoryUsage()
77
- const cpuUsage = process.cpuUsage()
78
-
79
- return {
80
- memoryUsage: {
81
- rss: memUsage.rss,
82
- heapUsed: memUsage.heapUsed,
83
- heapTotal: memUsage.heapTotal,
84
- external: memUsage.external,
85
- arrayBuffers: memUsage.arrayBuffers,
86
- },
87
- cpuUsage: {
88
- user: cpuUsage.user,
89
- system: cpuUsage.system,
90
- },
91
- eventLoop: {
92
- delay: 0,
93
- utilization: 0,
94
- },
95
- gc: {
96
- collections: 0,
97
- duration: 0,
98
- freed: 0,
99
- },
100
- bunSpecific: {
101
- jitCompilations: 0,
102
- nativeCallsOptimized: 0,
103
- fileSystemCacheHits: 0,
104
- },
105
- }
106
- }
107
-
108
- /**
109
- * Setup Bun-specific optimizations
110
- */
111
- private setupOptimizations(): void {
112
- // Enable JIT compilation hints
113
- if (this.config.enableJIT) {
114
- this.enableJITOptimizations()
115
- }
116
-
117
- // Configure garbage collection
118
- if (this.config.enableGC) {
119
- this.configureGarbageCollection()
120
- }
121
-
122
- // Set memory limits
123
- if (this.config.memoryLimit > 0) {
124
- this.setMemoryLimits()
125
- }
126
- }
127
-
128
- /**
129
- * Enable JIT compilation optimizations
130
- */
131
- private enableJITOptimizations(): void {
132
- // Bun-specific JIT hints
133
- if (typeof Bun !== 'undefined') {
134
- // Warm up common code paths
135
- this.warmupCodePaths()
136
-
137
- // Enable native optimizations
138
- this.enableNativeOptimizations()
139
- }
140
- }
141
-
142
- /**
143
- * Warm up common code paths for JIT
144
- */
145
- private warmupCodePaths(): void {
146
- // Common operations to warm up JIT
147
- const warmupOperations = [
148
- () => JSON.stringify({ test: 'data' }),
149
- () => JSON.parse('{"test":"data"}'),
150
- () => new URL('http://localhost:3000'),
151
- () => new Headers({ 'content-type': 'application/json' }),
152
- () => new Response('test'),
153
- () => Buffer.from('test'),
154
- () => new TextEncoder().encode('test'),
155
- () => new TextDecoder().decode(new Uint8Array([116, 101, 115, 116])),
156
- ]
157
-
158
- // Run warmup operations multiple times
159
- for (let i = 0; i < 100; i++) {
160
- warmupOperations.forEach((op) => {
161
- try {
162
- op()
163
- }
164
- catch (error) {
165
- console.error(error)
166
- // Ignore warmup errors
167
- }
168
- })
169
- }
170
-
171
- this.metrics.bunSpecific.jitCompilations += warmupOperations.length
172
- }
173
-
174
- /**
175
- * Enable native call optimizations
176
- */
177
- private enableNativeOptimizations(): void {
178
- // Optimize common native calls
179
- const originalFetch = globalThis.fetch
180
- const wrappedFetch = ((...args: Parameters<typeof fetch>) => {
181
- this.metrics.bunSpecific.nativeCallsOptimized++
182
- return originalFetch(...args)
183
- }) as typeof fetch
184
-
185
- // Preserve preconnect property if it exists
186
- if ('preconnect' in originalFetch) {
187
- (wrappedFetch as any).preconnect = (originalFetch as any).preconnect
188
- }
189
-
190
- globalThis.fetch = wrappedFetch
191
-
192
- // Optimize file system operations
193
- if (typeof Bun !== 'undefined' && Bun.file) {
194
- const originalFile = Bun.file
195
- Bun.file = ((...args: Parameters<typeof originalFile>) => {
196
- this.metrics.bunSpecific.fileSystemCacheHits++
197
- return originalFile(...args)
198
- }) as typeof originalFile
199
- }
200
- }
201
-
202
- /**
203
- * Configure garbage collection
204
- */
205
- private configureGarbageCollection(): void {
206
- // Setup GC monitoring
207
- if (typeof PerformanceObserver !== 'undefined') {
208
- this.gcObserver = new (PerformanceObserver as any)((list: PerformanceObserverEntryList) => {
209
- for (const entry of list.getEntries()) {
210
- if (entry.entryType === 'gc') {
211
- this.metrics.gc.collections++
212
- this.metrics.gc.duration += entry.duration
213
- }
214
- }
215
- })
216
-
217
- try {
218
- this.gcObserver?.observe({ entryTypes: ['gc'] })
219
- }
220
- catch (error) {
221
- console.error(error)
222
- // GC observation not supported
223
- }
224
- }
225
-
226
- // Trigger periodic GC if memory usage is high
227
- setInterval(() => {
228
- const memUsage = process.memoryUsage()
229
- if (memUsage.heapUsed > this.config.memoryLimit * 0.8) {
230
- if (globalThis.gc) {
231
- const before = memUsage.heapUsed
232
- globalThis.gc()
233
- const after = process.memoryUsage().heapUsed
234
- this.metrics.gc.freed += before - after
235
- }
236
- }
237
- }, 30000) // Check every 30 seconds
238
- }
239
-
240
- /**
241
- * Set memory limits
242
- */
243
- private setMemoryLimits(): void {
244
- // Monitor memory usage
245
- setInterval(() => {
246
- const memUsage = process.memoryUsage()
247
- this.metrics.memoryUsage = {
248
- rss: memUsage.rss,
249
- heapUsed: memUsage.heapUsed,
250
- heapTotal: memUsage.heapTotal,
251
- external: memUsage.external,
252
- arrayBuffers: memUsage.arrayBuffers,
253
- }
254
-
255
- // Warn if approaching memory limit
256
- if (memUsage.heapUsed > this.config.memoryLimit * 0.9) {
257
- console.warn(`Memory usage approaching limit: ${Math.round(memUsage.heapUsed / 1024 / 1024)}MB`)
258
- }
259
- }, 5000) // Check every 5 seconds
260
- }
261
-
262
- /**
263
- * Setup performance monitoring
264
- */
265
- private setupMonitoring(): void {
266
- // Monitor event loop
267
- setInterval(() => {
268
- const start = performance.now()
269
- setImmediate(() => {
270
- const delay = performance.now() - start
271
- this.metrics.eventLoop.delay = delay
272
- this.metrics.eventLoop.utilization = Math.min(delay / 16.67, 1) // 60fps baseline
273
- })
274
- }, 1000)
275
-
276
- // Monitor CPU usage
277
- setInterval(() => {
278
- const cpuUsage = process.cpuUsage()
279
- this.metrics.cpuUsage = {
280
- user: cpuUsage.user,
281
- system: cpuUsage.system,
282
- }
283
- }, 5000)
284
-
285
- // Setup performance observer
286
- if (typeof PerformanceObserver !== 'undefined') {
287
- this.performanceObserver = new (PerformanceObserver as any)((list: PerformanceObserverEntryList) => {
288
- for (const entry of list.getEntries()) {
289
- if (entry.entryType === 'measure') {
290
- // Track custom performance measures
291
- }
292
- }
293
- })
294
-
295
- try {
296
- this.performanceObserver?.observe({ entryTypes: ['measure', 'navigation'] as any })
297
- }
298
- catch (error) {
299
- console.error(error)
300
- // Performance observation not supported
301
- }
302
- }
303
- }
304
-
305
- /**
306
- * Get current performance metrics
307
- */
308
- getMetrics(): PerformanceMetrics {
309
- return { ...this.metrics }
310
- }
311
-
312
- /**
313
- * Optimize specific function
314
- */
315
- optimizeFunction<T extends (...args: any[]) => any>(fn: T, options: {
316
- memoize?: boolean
317
- warmup?: boolean
318
- profile?: boolean
319
- } = {}): T {
320
- let memoCache: Map<string, any> | undefined
321
- let callCount = 0
322
-
323
- if (options.memoize) {
324
- memoCache = new Map()
325
- }
326
-
327
- if (options.warmup) {
328
- // Warmup function for JIT
329
- for (let i = 0; i < 10; i++) {
330
- try {
331
- fn()
332
- }
333
- catch (error) {
334
- console.error(error)
335
- // Ignore warmup errors
336
- }
337
- }
338
- }
339
-
340
- const optimizedFn = ((...args: any[]) => {
341
- callCount++
342
-
343
- if (options.profile) {
344
- const start = performance.now()
345
- const result = fn(...args)
346
- const duration = performance.now() - start
347
-
348
- if (duration > 10) { // Log slow calls
349
- // eslint-disable-next-line pickier/no-unused-vars
350
- console.warn(`Slow function call: ${fn.name || 'anonymous'} took ${duration.toFixed(2)}ms`)
351
- }
352
-
353
- return result
354
- }
355
-
356
- if (memoCache) {
357
- const key = JSON.stringify(args)
358
- if (memoCache.has(key)) {
359
- return memoCache.get(key)
360
- }
361
-
362
- const result = fn(...args)
363
- memoCache.set(key, result)
364
- return result
365
- }
366
-
367
- return fn(...args)
368
- }) as T
369
-
370
- // Add metadata
371
- Object.defineProperty(optimizedFn, 'callCount', {
372
- get: () => callCount,
373
- })
374
-
375
- Object.defineProperty(optimizedFn, 'clearCache', {
376
- value: () => memoCache?.clear(),
377
- })
378
-
379
- return optimizedFn
380
- }
381
-
382
- /**
383
- * Create optimized buffer operations
384
- */
385
- createBufferOptimizer() {
386
- const bufferPool = new Map<number, Buffer[]>()
387
-
388
- return {
389
- /**
390
- * Get buffer from pool or create new one
391
- */
392
- getBuffer: (size: number): Buffer => {
393
- const pool = bufferPool.get(size) || []
394
- const buffer = pool.pop()
395
-
396
- if (buffer) {
397
- buffer.fill(0) // Clear buffer
398
- return buffer
399
- }
400
-
401
- return Buffer.allocUnsafe(size)
402
- },
403
-
404
- /**
405
- * Return buffer to pool
406
- */
407
- returnBuffer: (buffer: Buffer): void => {
408
- const size = buffer.length
409
- const pool = bufferPool.get(size) || []
410
-
411
- if (pool.length < 10) { // Limit pool size
412
- pool.push(buffer)
413
- bufferPool.set(size, pool)
414
- }
415
- },
416
-
417
- /**
418
- * Clear buffer pools
419
- */
420
- clearPools: (): void => {
421
- bufferPool.clear()
422
- },
423
-
424
- /**
425
- * Get pool statistics
426
- */
427
- getStats: (): Record<number, number> => {
428
- const stats: Record<number, number> = {}
429
- bufferPool.forEach((pool, size) => {
430
- stats[size] = pool.length
431
- })
432
- return stats
433
- },
434
- }
435
- }
436
-
437
- /**
438
- * Create optimized JSON operations
439
- */
440
- createJSONOptimizer() {
441
- const parseCache = new Map<string, any>()
442
- const stringifyCache = new Map<any, string>()
443
-
444
- return {
445
- /**
446
- * Optimized JSON parse with caching
447
- */
448
- parse: (text: string): any => {
449
- if (parseCache.has(text)) {
450
- return parseCache.get(text)
451
- }
452
-
453
- const result = JSON.parse(text)
454
-
455
- if (parseCache.size < 1000) { // Limit cache size
456
- parseCache.set(text, result)
457
- }
458
-
459
- return result
460
- },
461
-
462
- /**
463
- * Optimized JSON stringify with caching
464
- */
465
- stringify: (value: any): string => {
466
- if (stringifyCache.has(value)) {
467
- return stringifyCache.get(value)!
468
- }
469
-
470
- const result = JSON.stringify(value)
471
-
472
- if (stringifyCache.size < 1000) { // Limit cache size
473
- stringifyCache.set(value, result)
474
- }
475
-
476
- return result
477
- },
478
-
479
- /**
480
- * Clear JSON caches
481
- */
482
- clearCaches: (): void => {
483
- parseCache.clear()
484
- stringifyCache.clear()
485
- },
486
-
487
- /**
488
- * Get cache statistics
489
- */
490
- getStats: (): { parseCache: number, stringifyCache: number } => ({
491
- parseCache: parseCache.size,
492
- stringifyCache: stringifyCache.size,
493
- }),
494
- }
495
- }
496
-
497
- /**
498
- * Create worker pool for CPU-intensive tasks
499
- */
500
- createWorkerPool(workerScript: string, poolSize: number = navigator.hardwareConcurrency || 4) {
501
- const workers: Worker[] = []
502
- const taskQueue: Array<{
503
- data: any
504
- resolve: (value: any) => void
505
- reject: (error: any) => void
506
- }> = []
507
- let currentWorker = 0
508
-
509
- // Initialize workers
510
- for (let i = 0; i < poolSize; i++) {
511
- const worker = new Worker(workerScript)
512
-
513
- worker.onmessage = (event) => {
514
- const task = taskQueue.shift()
515
- if (task) {
516
- if (event.data.error) {
517
- task.reject(new Error(event.data.error))
518
- }
519
- else {
520
- task.resolve(event.data.result)
521
- }
522
- }
523
- }
524
-
525
- worker.onerror = (error) => {
526
- const task = taskQueue.shift()
527
- if (task) {
528
- task.reject(error)
529
- }
530
- }
531
-
532
- workers.push(worker)
533
- }
534
-
535
- return {
536
- /**
537
- * Execute task in worker
538
- */
539
- execute: <T>(data: any): Promise<T> => {
540
- return new Promise((resolve, reject) => {
541
- taskQueue.push({ data, resolve, reject })
542
-
543
- const worker = workers[currentWorker]
544
- currentWorker = (currentWorker + 1) % workers.length
545
-
546
- worker.postMessage(data)
547
- })
548
- },
549
-
550
- /**
551
- * Terminate all workers
552
- */
553
- terminate: (): void => {
554
- workers.forEach(worker => worker.terminate())
555
- workers.length = 0
556
- },
557
-
558
- /**
559
- * Get pool statistics
560
- */
561
- getStats: (): { poolSize: number, queueSize: number, activeWorkers: number } => ({
562
- poolSize: workers.length,
563
- queueSize: taskQueue.length,
564
- activeWorkers: workers.length - taskQueue.length,
565
- }),
566
- }
567
- }
568
-
569
- /**
570
- * Generate performance report
571
- */
572
- generateReport(): string {
573
- const metrics = this.getMetrics()
574
-
575
- return `
576
- # Bun Runtime Performance Report
577
-
578
- ## Memory Usage
579
- - RSS: ${Math.round(metrics.memoryUsage.rss / 1024 / 1024)}MB
580
- - Heap Used: ${Math.round(metrics.memoryUsage.heapUsed / 1024 / 1024)}MB
581
- - Heap Total: ${Math.round(metrics.memoryUsage.heapTotal / 1024 / 1024)}MB
582
- - External: ${Math.round(metrics.memoryUsage.external / 1024 / 1024)}MB
583
- - Array Buffers: ${Math.round(metrics.memoryUsage.arrayBuffers / 1024 / 1024)}MB
584
-
585
- ## CPU Usage
586
- - User: ${Math.round(metrics.cpuUsage.user / 1000)}ms
587
- - System: ${Math.round(metrics.cpuUsage.system / 1000)}ms
588
-
589
- ## Event Loop
590
- - Delay: ${metrics.eventLoop.delay.toFixed(2)}ms
591
- - Utilization: ${(metrics.eventLoop.utilization * 100).toFixed(1)}%
592
-
593
- ## Garbage Collection
594
- - Collections: ${metrics.gc.collections}
595
- - Total Duration: ${metrics.gc.duration.toFixed(2)}ms
596
- - Memory Freed: ${Math.round(metrics.gc.freed / 1024 / 1024)}MB
597
-
598
- ## Bun-Specific Optimizations
599
- - JIT Compilations: ${metrics.bunSpecific.jitCompilations}
600
- - Native Calls Optimized: ${metrics.bunSpecific.nativeCallsOptimized}
601
- - File System Cache Hits: ${metrics.bunSpecific.fileSystemCacheHits}
602
-
603
- ## Configuration
604
- - JIT Enabled: ${this.config.enableJIT}
605
- - GC Enabled: ${this.config.enableGC}
606
- - Memory Limit: ${Math.round(this.config.memoryLimit / 1024 / 1024)}MB
607
- - CPU Limit: ${this.config.cpuLimit}%
608
- - Profiling: ${this.config.enableProfiling}
609
- - Tracing: ${this.config.enableTracing}
610
- `.trim()
611
- }
612
-
613
- /**
614
- * Cleanup resources
615
- */
616
- cleanup(): void {
617
- this.gcObserver?.disconnect()
618
- this.performanceObserver?.disconnect()
619
- }
620
- }
621
-
622
- /**
623
- * Bun optimization utilities
624
- */
625
- export const BunUtils = {
626
- /**
627
- * Check if running in Bun runtime
628
- */
629
- isBun: (): boolean => {
630
- return typeof Bun !== 'undefined'
631
- },
632
-
633
- /**
634
- * Get Bun version
635
- */
636
- getBunVersion: (): string => {
637
- return typeof Bun !== 'undefined' ? Bun.version : 'Not running in Bun'
638
- },
639
-
640
- /**
641
- * Optimize async function with Bun-specific features
642
- */
643
- optimizeAsync: <T extends (...args: any[]) => Promise<any>>(fn: T): T => {
644
- return (async (...args: any[]) => {
645
- // Use Bun's optimized Promise implementation
646
- return await fn(...args)
647
- }) as T
648
- },
649
-
650
- /**
651
- * Create optimized stream processor
652
- */
653
- createStreamProcessor: () => {
654
- return {
655
- /**
656
- * Process readable stream with Bun optimizations
657
- */
658
- processStream: async (stream: ReadableStream): Promise<Uint8Array> => {
659
- const reader = stream.getReader()
660
- const chunks: Uint8Array[] = []
661
- let totalLength = 0
662
-
663
- try {
664
- while (true) {
665
- const { done, value } = await reader.read()
666
- if (done)
667
- break
668
-
669
- chunks.push(value)
670
- totalLength += value.length
671
- }
672
-
673
- // Use Bun's optimized buffer concatenation
674
- const result = new Uint8Array(totalLength)
675
- let offset = 0
676
-
677
- for (const chunk of chunks) {
678
- result.set(chunk, offset)
679
- offset += chunk.length
680
- }
681
-
682
- return result
683
- }
684
- finally {
685
- reader.releaseLock()
686
- }
687
- },
688
-
689
- /**
690
- * Create optimized transform stream
691
- */
692
- createTransformStream: <T, U>(
693
- transformer: (chunk: T) => U | Promise<U>,
694
- ): TransformStream<T, U> => {
695
- return new TransformStream({
696
- async transform(chunk, controller) {
697
- try {
698
- const result = await transformer(chunk)
699
- controller.enqueue(result)
700
- }
701
- catch (error) {
702
- controller.error(error)
703
- }
704
- },
705
- })
706
- },
707
- }
708
- },
709
- }
710
-
711
- /**
712
- * Bun optimization factory functions
713
- */
714
- export const BunOptimizationFactory = {
715
- /**
716
- * Create development optimizer
717
- */
718
- createDevelopment: (): BunOptimizer => {
719
- return new BunOptimizer({
720
- enableJIT: true,
721
- enableGC: true,
722
- memoryLimit: 1024 * 1024 * 1024, // 1GB
723
- cpuLimit: 90,
724
- enableProfiling: true,
725
- enableTracing: true,
726
- })
727
- },
728
-
729
- /**
730
- * Create production optimizer
731
- */
732
- createProduction: (): BunOptimizer => {
733
- return new BunOptimizer({
734
- enableJIT: true,
735
- enableGC: true,
736
- memoryLimit: 512 * 1024 * 1024, // 512MB
737
- cpuLimit: 80,
738
- enableProfiling: false,
739
- enableTracing: false,
740
- })
741
- },
742
-
743
- /**
744
- * Create testing optimizer
745
- */
746
- createTesting: (): BunOptimizer => {
747
- return new BunOptimizer({
748
- enableJIT: false,
749
- enableGC: false,
750
- memoryLimit: 256 * 1024 * 1024, // 256MB
751
- cpuLimit: 70,
752
- enableProfiling: false,
753
- enableTracing: false,
754
- })
755
- },
756
- }
757
-
758
- /**
759
- * Global Bun optimizer instance
760
- */
761
- let globalOptimizer: BunOptimizer | null = null
762
-
763
- /**
764
- * Initialize global Bun optimizer
765
- */
766
- export function initializeBunOptimizer(config?: BunOptimizationConfig): BunOptimizer {
767
- if (!globalOptimizer) {
768
- globalOptimizer = new BunOptimizer(config)
769
- }
770
- return globalOptimizer
771
- }
772
-
773
- /**
774
- * Get global Bun optimizer
775
- */
776
- export function getBunOptimizer(): BunOptimizer | null {
777
- return globalOptimizer
778
- }