@raymondfox/ts-toolbox 1.0.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 (175) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/http/HttpClient.d.ts +75 -0
  3. package/dist/http/HttpClient.d.ts.map +1 -0
  4. package/dist/http/HttpClient.js +237 -0
  5. package/dist/http/HttpClient.js.map +1 -0
  6. package/dist/http/index.d.ts +4 -0
  7. package/dist/http/index.d.ts.map +1 -0
  8. package/dist/http/index.js +9 -0
  9. package/dist/http/index.js.map +1 -0
  10. package/dist/http/types.d.ts +78 -0
  11. package/dist/http/types.d.ts.map +1 -0
  12. package/dist/http/types.js +23 -0
  13. package/dist/http/types.js.map +1 -0
  14. package/dist/index.d.ts +6 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +24 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/logger/Logger.d.ts +62 -0
  19. package/dist/logger/Logger.d.ts.map +1 -0
  20. package/dist/logger/Logger.js +120 -0
  21. package/dist/logger/Logger.js.map +1 -0
  22. package/dist/logger/formatters/JsonFormatter.d.ts +14 -0
  23. package/dist/logger/formatters/JsonFormatter.d.ts.map +1 -0
  24. package/dist/logger/formatters/JsonFormatter.js +27 -0
  25. package/dist/logger/formatters/JsonFormatter.js.map +1 -0
  26. package/dist/logger/formatters/LoggerFormatter.d.ts +21 -0
  27. package/dist/logger/formatters/LoggerFormatter.d.ts.map +1 -0
  28. package/dist/logger/formatters/LoggerFormatter.js +3 -0
  29. package/dist/logger/formatters/LoggerFormatter.js.map +1 -0
  30. package/dist/logger/formatters/PrettyFormatter.d.ts +26 -0
  31. package/dist/logger/formatters/PrettyFormatter.d.ts.map +1 -0
  32. package/dist/logger/formatters/PrettyFormatter.js +72 -0
  33. package/dist/logger/formatters/PrettyFormatter.js.map +1 -0
  34. package/dist/logger/formatters/index.d.ts +5 -0
  35. package/dist/logger/formatters/index.d.ts.map +1 -0
  36. package/dist/logger/formatters/index.js +8 -0
  37. package/dist/logger/formatters/index.js.map +1 -0
  38. package/dist/logger/index.d.ts +19 -0
  39. package/dist/logger/index.d.ts.map +1 -0
  40. package/dist/logger/index.js +40 -0
  41. package/dist/logger/index.js.map +1 -0
  42. package/dist/logger/transports/BufferedTransport.d.ts +71 -0
  43. package/dist/logger/transports/BufferedTransport.d.ts.map +1 -0
  44. package/dist/logger/transports/BufferedTransport.js +111 -0
  45. package/dist/logger/transports/BufferedTransport.js.map +1 -0
  46. package/dist/logger/transports/ConsoleTransport.d.ts +26 -0
  47. package/dist/logger/transports/ConsoleTransport.d.ts.map +1 -0
  48. package/dist/logger/transports/ConsoleTransport.js +39 -0
  49. package/dist/logger/transports/ConsoleTransport.js.map +1 -0
  50. package/dist/logger/transports/DiscordTransport.d.ts +48 -0
  51. package/dist/logger/transports/DiscordTransport.d.ts.map +1 -0
  52. package/dist/logger/transports/DiscordTransport.js +96 -0
  53. package/dist/logger/transports/DiscordTransport.js.map +1 -0
  54. package/dist/logger/transports/FileTransport.d.ts +104 -0
  55. package/dist/logger/transports/FileTransport.d.ts.map +1 -0
  56. package/dist/logger/transports/FileTransport.js +251 -0
  57. package/dist/logger/transports/FileTransport.js.map +1 -0
  58. package/dist/logger/transports/HttpTransport.d.ts +47 -0
  59. package/dist/logger/transports/HttpTransport.d.ts.map +1 -0
  60. package/dist/logger/transports/HttpTransport.js +57 -0
  61. package/dist/logger/transports/HttpTransport.js.map +1 -0
  62. package/dist/logger/transports/LoggerTransport.d.ts +52 -0
  63. package/dist/logger/transports/LoggerTransport.d.ts.map +1 -0
  64. package/dist/logger/transports/LoggerTransport.js +33 -0
  65. package/dist/logger/transports/LoggerTransport.js.map +1 -0
  66. package/dist/logger/transports/index.d.ts +13 -0
  67. package/dist/logger/transports/index.d.ts.map +1 -0
  68. package/dist/logger/transports/index.js +16 -0
  69. package/dist/logger/transports/index.js.map +1 -0
  70. package/dist/logger/types/LogLevel.d.ts +17 -0
  71. package/dist/logger/types/LogLevel.d.ts.map +1 -0
  72. package/dist/logger/types/LogLevel.js +23 -0
  73. package/dist/logger/types/LogLevel.js.map +1 -0
  74. package/dist/logger/types/LogMessage.d.ts +19 -0
  75. package/dist/logger/types/LogMessage.d.ts.map +1 -0
  76. package/dist/logger/types/LogMessage.js +3 -0
  77. package/dist/logger/types/LogMessage.js.map +1 -0
  78. package/dist/logger/types/LoggerOptions.d.ts +17 -0
  79. package/dist/logger/types/LoggerOptions.d.ts.map +1 -0
  80. package/dist/logger/types/LoggerOptions.js +3 -0
  81. package/dist/logger/types/LoggerOptions.js.map +1 -0
  82. package/dist/logger/types/index.d.ts +4 -0
  83. package/dist/logger/types/index.d.ts.map +1 -0
  84. package/dist/logger/types/index.js +18 -0
  85. package/dist/logger/types/index.js.map +1 -0
  86. package/dist/retry/index.d.ts +3 -0
  87. package/dist/retry/index.d.ts.map +1 -0
  88. package/dist/retry/index.js +6 -0
  89. package/dist/retry/index.js.map +1 -0
  90. package/dist/retry/retry.d.ts +38 -0
  91. package/dist/retry/retry.d.ts.map +1 -0
  92. package/dist/retry/retry.js +117 -0
  93. package/dist/retry/retry.js.map +1 -0
  94. package/dist/retry/types.d.ts +65 -0
  95. package/dist/retry/types.d.ts.map +1 -0
  96. package/dist/retry/types.js +3 -0
  97. package/dist/retry/types.js.map +1 -0
  98. package/dist/socket/browserSocket/BrowserSocketClient.d.ts +82 -0
  99. package/dist/socket/browserSocket/BrowserSocketClient.d.ts.map +1 -0
  100. package/dist/socket/browserSocket/BrowserSocketClient.js +345 -0
  101. package/dist/socket/browserSocket/BrowserSocketClient.js.map +1 -0
  102. package/dist/socket/browserSocket/index.d.ts +2 -0
  103. package/dist/socket/browserSocket/index.d.ts.map +1 -0
  104. package/dist/socket/browserSocket/index.js +6 -0
  105. package/dist/socket/browserSocket/index.js.map +1 -0
  106. package/dist/socket/index.d.ts +6 -0
  107. package/dist/socket/index.d.ts.map +1 -0
  108. package/dist/socket/index.js +15 -0
  109. package/dist/socket/index.js.map +1 -0
  110. package/dist/socket/nodeSocket/NodeSocketClient.d.ts +70 -0
  111. package/dist/socket/nodeSocket/NodeSocketClient.d.ts.map +1 -0
  112. package/dist/socket/nodeSocket/NodeSocketClient.js +357 -0
  113. package/dist/socket/nodeSocket/NodeSocketClient.js.map +1 -0
  114. package/dist/socket/nodeSocket/NodeSocketServer.d.ts +101 -0
  115. package/dist/socket/nodeSocket/NodeSocketServer.d.ts.map +1 -0
  116. package/dist/socket/nodeSocket/NodeSocketServer.js +472 -0
  117. package/dist/socket/nodeSocket/NodeSocketServer.js.map +1 -0
  118. package/dist/socket/nodeSocket/index.d.ts +4 -0
  119. package/dist/socket/nodeSocket/index.d.ts.map +1 -0
  120. package/dist/socket/nodeSocket/index.js +8 -0
  121. package/dist/socket/nodeSocket/index.js.map +1 -0
  122. package/dist/socket/shared/ConnectionState.d.ts +5 -0
  123. package/dist/socket/shared/ConnectionState.d.ts.map +1 -0
  124. package/dist/socket/shared/ConnectionState.js +3 -0
  125. package/dist/socket/shared/ConnectionState.js.map +1 -0
  126. package/dist/socket/shared/Socket.d.ts +34 -0
  127. package/dist/socket/shared/Socket.d.ts.map +1 -0
  128. package/dist/socket/shared/Socket.js +83 -0
  129. package/dist/socket/shared/Socket.js.map +1 -0
  130. package/dist/socket/shared/SocketEvent.d.ts +8 -0
  131. package/dist/socket/shared/SocketEvent.d.ts.map +1 -0
  132. package/dist/socket/shared/SocketEvent.js +3 -0
  133. package/dist/socket/shared/SocketEvent.js.map +1 -0
  134. package/dist/socket/shared/SocketMessage.d.ts +25 -0
  135. package/dist/socket/shared/SocketMessage.d.ts.map +1 -0
  136. package/dist/socket/shared/SocketMessage.js +3 -0
  137. package/dist/socket/shared/SocketMessage.js.map +1 -0
  138. package/dist/socket/shared/SocketMiddleware.d.ts +15 -0
  139. package/dist/socket/shared/SocketMiddleware.d.ts.map +1 -0
  140. package/dist/socket/shared/SocketMiddleware.js +27 -0
  141. package/dist/socket/shared/SocketMiddleware.js.map +1 -0
  142. package/dist/socket/shared/SocketOptions.d.ts +47 -0
  143. package/dist/socket/shared/SocketOptions.d.ts.map +1 -0
  144. package/dist/socket/shared/SocketOptions.js +3 -0
  145. package/dist/socket/shared/SocketOptions.js.map +1 -0
  146. package/dist/socket/shared/SocketSerializer.d.ts +16 -0
  147. package/dist/socket/shared/SocketSerializer.d.ts.map +1 -0
  148. package/dist/socket/shared/SocketSerializer.js +16 -0
  149. package/dist/socket/shared/SocketSerializer.js.map +1 -0
  150. package/dist/socket/shared/SocketValidation.d.ts +10 -0
  151. package/dist/socket/shared/SocketValidation.d.ts.map +1 -0
  152. package/dist/socket/shared/SocketValidation.js +3 -0
  153. package/dist/socket/shared/SocketValidation.js.map +1 -0
  154. package/dist/socket/shared/TypedSocket.d.ts +48 -0
  155. package/dist/socket/shared/TypedSocket.d.ts.map +1 -0
  156. package/dist/socket/shared/TypedSocket.js +3 -0
  157. package/dist/socket/shared/TypedSocket.js.map +1 -0
  158. package/dist/socket/shared/index.d.ts +12 -0
  159. package/dist/socket/shared/index.d.ts.map +1 -0
  160. package/dist/socket/shared/index.js +10 -0
  161. package/dist/socket/shared/index.js.map +1 -0
  162. package/dist/timeout/index.d.ts +4 -0
  163. package/dist/timeout/index.d.ts.map +1 -0
  164. package/dist/timeout/index.js +9 -0
  165. package/dist/timeout/index.js.map +1 -0
  166. package/dist/timeout/timeout.d.ts +39 -0
  167. package/dist/timeout/timeout.d.ts.map +1 -0
  168. package/dist/timeout/timeout.js +68 -0
  169. package/dist/timeout/timeout.js.map +1 -0
  170. package/dist/timeout/types.d.ts +30 -0
  171. package/dist/timeout/types.d.ts.map +1 -0
  172. package/dist/timeout/types.js +17 -0
  173. package/dist/timeout/types.js.map +1 -0
  174. package/package.json +79 -0
  175. package/readme.md +928 -0
package/readme.md ADDED
@@ -0,0 +1,928 @@
1
+ # TS Toolkit
2
+
3
+ A collection of reusable, TypeScript-first tools for Node.js and other JavaScript/TypeScript environments.
4
+
5
+ The goal is to provide small, composable and strongly typed utilities for common application and development needs, without forcing a specific framework or architecture.
6
+
7
+ ---
8
+
9
+ ## 🚧 Features
10
+
11
+ ### ✅ Logger
12
+
13
+ Structured, extensible logging system with multiple log levels, scopes, formatters and transports.
14
+
15
+ * [x] Log levels
16
+
17
+ * `TRACE`
18
+ * `DEBUG`
19
+ * `INFO`
20
+ * `SUCCESS`
21
+ * `WARN`
22
+ * `ERROR`
23
+ * `FATAL`
24
+ * [x] Structured metadata
25
+ * [x] Scoped loggers
26
+ * [x] Nested scopes
27
+ * [x] Custom formatters
28
+ * [x] Transport system
29
+ * [x] Per-transport log levels
30
+ * [x] Console transport
31
+ * [x] File transport
32
+ * [x] Pretty formatter
33
+ * [x] JSON formatter
34
+ * [x] HTTP transport
35
+ * [x] Discord webhook transport
36
+ * [x] Custom transport API
37
+ * [x] Log rotation
38
+ * [x] File size limits
39
+ * [x] Buffered/asynchronous transports
40
+
41
+ Example:
42
+
43
+ ```ts
44
+ const logger = new Logger({
45
+ level: LogLevel.TRACE
46
+ });
47
+
48
+ logger.use(new ConsoleTransport({
49
+ formatter: new PrettyFormatter({
50
+ colors: true
51
+ })
52
+ }));
53
+
54
+ logger.use(new FileTransport({
55
+ filePath: './logs/app.log',
56
+ level: LogLevel.INFO
57
+ }));
58
+
59
+ const dbLogger = logger.scope('Database');
60
+
61
+ dbLogger.info('Connected');
62
+ dbLogger.error('Connection lost', {
63
+ retry: 3
64
+ });
65
+ ```
66
+
67
+ ---
68
+
69
+ ### ✅ Socket
70
+
71
+ Event-based communication layer supporting Node.js servers, Node.js clients and browser clients.
72
+
73
+ #### Node
74
+
75
+ * [x] Node Socket Server
76
+ * [x] Node Socket Client
77
+ * [x] Event subscription
78
+ * [x] Event unsubscription
79
+ * [x] Event emission
80
+ * [x] Broadcast
81
+ * [x] Rooms/channels
82
+ * [x] Middleware
83
+ * [x] Authentication
84
+ * [x] Connection lifecycle events
85
+ * [x] Reconnection
86
+ * [x] Heartbeat / ping-pong
87
+ * [x] Connection timeout
88
+ * [x] Typed events
89
+ * [x] Request/response events
90
+ * [x] RPC-style communication
91
+
92
+ #### Browser
93
+
94
+ * [x] Browser Socket Client
95
+ * [x] Event subscription
96
+ * [x] Event unsubscription
97
+ * [x] Event emission
98
+ * [x] Automatic reconnection
99
+ * [x] Connection state
100
+ * [x] Typed events
101
+ * [x] Request/response events
102
+
103
+ #### Shared
104
+
105
+ * [x] Shared event definitions
106
+ * [x] Typed event maps
107
+ * [x] Event middleware
108
+ * [x] Event validation
109
+ * [x] Message serialization
110
+ * [x] Request/response abstraction
111
+
112
+ ---
113
+
114
+ ## ⏳ Retry
115
+
116
+ Utilities for retrying unreliable operations.
117
+
118
+ * [ ] Basic retry
119
+ * [ ] Configurable retry count
120
+ * [ ] Fixed delay
121
+ * [ ] Exponential backoff
122
+ * [ ] Custom backoff strategy
123
+ * [ ] Maximum delay
124
+ * [ ] Retry conditions
125
+ * [ ] Retry callbacks
126
+ * [ ] Abort/cancellation support
127
+
128
+ Example:
129
+
130
+ ```ts
131
+ await retry(() => connectDatabase(), {
132
+ retries: 5,
133
+ delay: 1000,
134
+ backoff: 'exponential'
135
+ });
136
+ ```
137
+
138
+ ---
139
+
140
+ ## ⏳ Timeout
141
+
142
+ Utilities for limiting the execution time of asynchronous operations.
143
+
144
+ * [ ] Promise timeout
145
+ * [ ] Configurable timeout
146
+ * [ ] Custom timeout error
147
+ * [ ] AbortSignal support
148
+ * [ ] Timeout callbacks
149
+
150
+ Example:
151
+
152
+ ```ts
153
+ await withTimeout(
154
+ fetchData(),
155
+ 5000
156
+ );
157
+ ```
158
+
159
+ ---
160
+
161
+ ## ⏳ HTTP
162
+
163
+ Small, TypeScript-first HTTP utilities.
164
+
165
+ * [ ] HTTP client
166
+ * [ ] Typed responses
167
+ * [ ] Request configuration
168
+ * [ ] Request timeout
169
+ * [ ] Headers
170
+ * [ ] Query parameters
171
+ * [ ] JSON requests
172
+ * [ ] Request interceptors
173
+ * [ ] Response interceptors
174
+ * [ ] Error normalization
175
+ * [ ] Retry integration
176
+ * [ ] Logger integration
177
+ * [ ] Request ID / correlation ID
178
+
179
+ Example:
180
+
181
+ ```ts
182
+ const response = await http.get<User>('/api/users/1');
183
+
184
+ console.log(response.data);
185
+ ```
186
+
187
+ ---
188
+
189
+ ## ⏳ Request Logger
190
+
191
+ Utilities for logging HTTP requests and responses.
192
+
193
+ * [ ] HTTP method
194
+ * [ ] URL/path
195
+ * [ ] Status code
196
+ * [ ] Response time
197
+ * [ ] Request ID
198
+ * [ ] Request metadata
199
+ * [ ] Response metadata
200
+ * [ ] Configurable log levels
201
+ * [ ] Sensitive data filtering
202
+
203
+ Example:
204
+
205
+ ```text
206
+ → POST /api/users
207
+ ← 201 /api/users 42ms
208
+ ```
209
+
210
+ ---
211
+
212
+ ## ⏳ Correlation / Request ID
213
+
214
+ Utilities for tracking a request across different parts of an application.
215
+
216
+ * [ ] Request ID generation
217
+ * [ ] Request context
218
+ * [ ] Logger integration
219
+ * [ ] HTTP integration
220
+ * [ ] Socket integration
221
+ * [ ] Async context support
222
+ * [ ] ID propagation
223
+
224
+ Example:
225
+
226
+ ```text
227
+ [req: 8f31c2]
228
+
229
+ POST /api/users
230
+ ↓
231
+ Auth
232
+ ↓
233
+ UserService
234
+ ↓
235
+ Database
236
+ ↓
237
+ Response 201
238
+ ```
239
+
240
+ ---
241
+
242
+ ## ⏳ Health Check
243
+
244
+ Simple application and dependency health monitoring.
245
+
246
+ * [ ] Health check registry
247
+ * [ ] Custom checks
248
+ * [ ] Async checks
249
+ * [ ] Dependency status
250
+ * [ ] Timeout per check
251
+ * [ ] Health status aggregation
252
+ * [ ] JSON serialization
253
+
254
+ Example:
255
+
256
+ ```ts
257
+ health.register('database', async () => {
258
+ await database.query('SELECT 1');
259
+ return true;
260
+ });
261
+
262
+ health.register('redis', async () => {
263
+ return redis.ping();
264
+ });
265
+ ```
266
+
267
+ Possible result:
268
+
269
+ ```json
270
+ {
271
+ "status": "healthy",
272
+ "checks": {
273
+ "database": "healthy",
274
+ "redis": "healthy"
275
+ }
276
+ }
277
+ ```
278
+
279
+ ---
280
+
281
+ ## ⏳ Process Monitor
282
+
283
+ Utilities for monitoring the Node.js process.
284
+
285
+ * [ ] CPU usage
286
+ * [ ] Memory usage
287
+ * [ ] Heap usage
288
+ * [ ] Process uptime
289
+ * [ ] Event loop metrics
290
+ * [ ] Process information
291
+ * [ ] Memory threshold events
292
+ * [ ] CPU threshold events
293
+ * [ ] Logger integration
294
+ * [ ] Health integration
295
+
296
+ Example:
297
+
298
+ ```ts
299
+ monitor.on('high-memory', data => {
300
+ logger.warn('High memory usage', data);
301
+ });
302
+ ```
303
+
304
+ ---
305
+
306
+ ## ⏳ Scheduler
307
+
308
+ Lightweight task scheduling utilities.
309
+
310
+ * [ ] Delayed tasks
311
+ * [ ] Repeating tasks
312
+ * [ ] Cron expressions
313
+ * [ ] Task cancellation
314
+ * [ ] Task status
315
+ * [ ] Error handling
316
+ * [ ] Logger integration
317
+ * [ ] Prevent overlapping executions
318
+
319
+ Example:
320
+
321
+ ```ts
322
+ scheduler.every('5m', () => {
323
+ cleanupTemporaryFiles();
324
+ });
325
+ ```
326
+
327
+ ---
328
+
329
+ ## ⏳ Cache
330
+
331
+ Simple caching abstractions.
332
+
333
+ ### Memory Cache
334
+
335
+ * [ ] `get`
336
+ * [ ] `set`
337
+ * [ ] `delete`
338
+ * [ ] `has`
339
+ * [ ] `clear`
340
+ * [ ] TTL
341
+ * [ ] Maximum entries
342
+ * [ ] Expiration
343
+ * [ ] Cache statistics
344
+
345
+ Example:
346
+
347
+ ```ts
348
+ const user = await cache.remember(
349
+ 'user:123',
350
+ 60_000,
351
+ () => getUser(123)
352
+ );
353
+ ```
354
+
355
+ ### External Cache
356
+
357
+ * [ ] Cache adapter interface
358
+ * [ ] IndexDb adapter
359
+ * [ ] InMemory adapter
360
+ * [ ] Redis adapter
361
+ * [ ] Custom cache adapters
362
+
363
+ ---
364
+
365
+ ## ⏳ Configuration
366
+
367
+ Typed application configuration utilities.
368
+
369
+ * [ ] Environment variable reader
370
+ * [ ] Typed environment variables
371
+ * [ ] Default values
372
+ * [ ] Required variables
373
+ * [ ] Environment validation
374
+ * [ ] Custom configuration providers
375
+ * [ ] Configuration schema
376
+
377
+ Example:
378
+
379
+ ```ts
380
+ const config = defineConfig({
381
+ port: env.number('PORT', 3000),
382
+ databaseUrl: env.string('DATABASE_URL'),
383
+ debug: env.boolean('DEBUG', false)
384
+ });
385
+ ```
386
+
387
+ ---
388
+
389
+ ## ⏳ Validation
390
+
391
+ General-purpose TypeScript validation utilities.
392
+
393
+ * [ ] String validation
394
+ * [ ] Number validation
395
+ * [ ] Boolean validation
396
+ * [ ] Array validation
397
+ * [ ] Object validation
398
+ * [ ] Optional values
399
+ * [ ] Custom validators
400
+ * [ ] Composable schemas
401
+ * [ ] Typed validation results
402
+ * [ ] Validation errors
403
+
404
+ Example:
405
+
406
+ ```ts
407
+ const result = schema.validate(data);
408
+
409
+ if (!result.success) {
410
+ console.error(result.errors);
411
+ }
412
+ ```
413
+
414
+ ---
415
+
416
+ ## ⏳ Events
417
+
418
+ General-purpose in-process event utilities.
419
+
420
+ > Separate from the Socket module. These events do not require network communication.
421
+
422
+ * [ ] Event emitter
423
+ * [ ] `on`
424
+ * [ ] `once`
425
+ * [ ] `off`
426
+ * [ ] `emit`
427
+ * [ ] Async events
428
+ * [ ] Typed event maps
429
+ * [ ] Event middleware
430
+ * [ ] Error handling
431
+ * [ ] Event history/debugging
432
+
433
+ ---
434
+
435
+ ## ⏳ Webhooks
436
+
437
+ Generic webhook utilities.
438
+
439
+ * [ ] Webhook client
440
+ * [ ] POST requests
441
+ * [ ] Custom headers
442
+ * [ ] Payload serialization
443
+ * [ ] Retry
444
+ * [ ] Timeout
445
+ * [ ] Signature validation
446
+ * [ ] Incoming webhook handler
447
+
448
+ Possible integrations:
449
+
450
+ * [ ] Discord
451
+ * [ ] Slack
452
+ * [ ] Generic HTTP
453
+ * [ ] Custom webhook providers
454
+
455
+ ---
456
+
457
+ ## ⏳ Notifications
458
+
459
+ High-level notification abstraction built on top of transports.
460
+
461
+ * [ ] Notification interface
462
+ * [ ] Console notifications
463
+ * [ ] Discord notifications
464
+ * [ ] HTTP notifications
465
+ * [ ] Custom notification providers
466
+ * [ ] Severity levels
467
+ * [ ] Logger integration
468
+
469
+ Example:
470
+
471
+ ```ts
472
+ notifications.send({
473
+ level: 'error',
474
+ title: 'Database Error',
475
+ message: 'Connection lost'
476
+ });
477
+ ```
478
+
479
+ ---
480
+
481
+ ## ⏳ Utilities
482
+
483
+ Small utilities that do not justify external dependencies.
484
+
485
+ * [ ] ID generation
486
+ * [ ] Random utilities
487
+ * [ ] Date/time utilities
488
+ * [ ] Object utilities
489
+ * [ ] String utilities
490
+ * [ ] Array utilities
491
+ * [ ] Promise utilities
492
+ * [ ] Async helpers
493
+ * [ ] Debounce
494
+ * [ ] Throttle
495
+ * [ ] Memoization
496
+ * [ ] Deep clone
497
+ * [ ] Deep merge
498
+
499
+ ---
500
+
501
+ # Architecture Goals
502
+
503
+ The toolkit should follow a few principles:
504
+
505
+ * **TypeScript-first**
506
+ * **Strong typing**
507
+ * **Small and composable modules**
508
+ * **Minimal dependencies**
509
+ * **Framework agnostic**
510
+ * **Explicit configuration**
511
+ * **Extensible APIs**
512
+ * **Node.js friendly**
513
+ * **Browser-compatible where possible**
514
+ * **No unnecessary abstractions**
515
+
516
+ Modules should be usable independently whenever possible.
517
+
518
+ For example:
519
+
520
+ ```ts
521
+ import {
522
+ Logger,
523
+ ConsoleTransport
524
+ } from 'ts-toolkit';
525
+ ```
526
+
527
+ does not require using Socket.
528
+
529
+ Likewise:
530
+
531
+ ```ts
532
+ import {
533
+ NodeSocketServer
534
+ } from 'ts-toolkit/socket';
535
+ ```
536
+
537
+ does not require using Logger.
538
+
539
+ ---
540
+
541
+ # Planned Integrations
542
+
543
+ The toolkit may eventually provide integrations between modules without tightly coupling them.
544
+
545
+ Examples:
546
+
547
+ ```text
548
+ Logger
549
+ ├── ConsoleTransport
550
+ ├── FileTransport
551
+ ├── DiscordTransport
552
+ └── HttpTransport
553
+
554
+ HTTP
555
+ ├── Retry
556
+ ├── Timeout
557
+ ├── Logger
558
+ └── Request ID
559
+
560
+ Socket
561
+ ├── Logger
562
+ ├── Retry
563
+ ├── Timeout
564
+ └── Request ID
565
+
566
+ Health
567
+ ├── Logger
568
+ └── Process Monitor
569
+
570
+ Scheduler
571
+ ├── Logger
572
+ └── Retry
573
+ ```
574
+
575
+ The goal is to make these integrations **opt-in** rather than automatic.
576
+
577
+ ## Instrumentation & Tracing
578
+
579
+ The toolkit provides lightweight instrumentation for tracking application execution flows through **Traces** and **Spans**.
580
+
581
+ A **Trace** represents a complete operation or request, while a **Span** represents an individual step within that operation.
582
+
583
+ ```text
584
+ Trace
585
+ └── Span: enviar-pedido
586
+ ├── Span: montar-payload
587
+ ├── Span: consultar-estoque
588
+ └── Span: enviar-api
589
+ ```
590
+
591
+ Unlike a `Transport`, which defines **where** data is sent, or a `Formatter`, which defines **how** data is represented, instrumentation is responsible for describing **what happened during an operation**.
592
+
593
+ ```text
594
+ Tracer
595
+ │
596
+ │ creates and tracks
597
+ ▼
598
+ Trace / Span
599
+ │
600
+ ▼
601
+ Logger
602
+ │
603
+ ├── ConsoleTransport
604
+ ├── FileTransport
605
+ └── MonitorTransport
606
+ ```
607
+
608
+ ### Traces and Spans
609
+
610
+ A trace can contain multiple nested spans.
611
+
612
+ For example, processing an order might consist of:
613
+
614
+ ```text
615
+ enviar-pedido
616
+ ├── montar-payload
617
+ ├── consultar-estoque
618
+ └── enviar-api
619
+ ```
620
+
621
+ Each span can contain information such as:
622
+
623
+ * operation name
624
+ * start and end time
625
+ * duration
626
+ * status
627
+ * error information
628
+ * parent span
629
+ * trace ID
630
+ * custom attributes
631
+ * metadata
632
+
633
+ The resulting trace can then be visualized by the Monitor:
634
+
635
+ ```text
636
+ enviar-pedido 184ms
637
+ ├── montar-payload 12ms
638
+ ├── consultar-estoque 31ms
639
+ └── enviar-api ERROR
640
+ ```
641
+
642
+ ### Simple Tracing
643
+
644
+ For small operations, the `run()` API can be used:
645
+
646
+ ```ts
647
+ await tracer.run('montar-payload', () => {
648
+ return buildPayload(order);
649
+ });
650
+ ```
651
+
652
+ The tracer automatically measures the operation and records its success or failure.
653
+
654
+ ### Nested Tracing
655
+
656
+ Traces can be nested without manually passing parent information.
657
+
658
+ ```ts
659
+ await tracer.run('enviar-pedido', async () => {
660
+
661
+ const payload = await tracer.run(
662
+ 'montar-payload',
663
+ () => buildPayload(order)
664
+ );
665
+
666
+ return tracer.run(
667
+ 'enviar-api',
668
+ () => api.send(payload)
669
+ );
670
+ });
671
+ ```
672
+
673
+ The tracer can automatically associate nested operations with their parent:
674
+
675
+ ```text
676
+ enviar-pedido
677
+ ├── montar-payload
678
+ └── enviar-api
679
+ ```
680
+
681
+ In Node.js, execution context can be maintained automatically so that nested operations do not need to explicitly receive a parent span.
682
+
683
+ ### Manual Spans
684
+
685
+ For operations that require more control, a span can be created explicitly:
686
+
687
+ ```ts
688
+ const span = tracer.start('enviar-pedido');
689
+
690
+ try {
691
+ const payload = await span.run(
692
+ 'montar-payload',
693
+ () => buildPayload(order)
694
+ );
695
+
696
+ return await span.run(
697
+ 'enviar-api',
698
+ () => api.send(payload)
699
+ );
700
+ } finally {
701
+ span.end();
702
+ }
703
+ ```
704
+
705
+ This allows applications to control the lifetime of long-running operations while still preserving nested spans.
706
+
707
+ ### Decorators
708
+
709
+ For class methods, tracing can optionally be applied through decorators:
710
+
711
+ ```ts
712
+ class OrderService {
713
+
714
+ @Trace()
715
+ async enviarPedido(order: Order) {
716
+ const payload = await this.montarPayload(order);
717
+
718
+ return this.enviarApi(payload);
719
+ }
720
+
721
+ @Trace()
722
+ async montarPayload(order: Order) {
723
+ return buildPayload(order);
724
+ }
725
+
726
+ @Trace()
727
+ async enviarApi(payload: Payload) {
728
+ return api.send(payload);
729
+ }
730
+ }
731
+ ```
732
+
733
+ The decorator automatically creates a span around the method execution.
734
+
735
+ Decorators are an optional API. The tracer can also be used without decorators through `run()` or explicit spans.
736
+
737
+ ### HTTP Tracing
738
+
739
+ HTTP operations can have specialized instrumentation capable of collecting request and response information.
740
+
741
+ ```ts
742
+ await httpTracer.trace({
743
+ method: 'POST',
744
+ url: 'https://api.example.com/orders',
745
+ body: payload
746
+ });
747
+ ```
748
+
749
+ An HTTP span may contain:
750
+
751
+ ```ts
752
+ {
753
+ type: 'http',
754
+ method: 'POST',
755
+ url: 'https://api.example.com/orders',
756
+ duration: 42,
757
+ request: {
758
+ headers: {},
759
+ body: {}
760
+ },
761
+ response: {
762
+ status: 201,
763
+ headers: {},
764
+ body: {}
765
+ }
766
+ }
767
+ ```
768
+
769
+ Sensitive information such as authorization headers, passwords, tokens, and other credentials should be filtered or redacted before being recorded.
770
+
771
+ ### Trace Context
772
+
773
+ Every trace can have a unique `traceId`, while each span can have its own identifier and parent relationship.
774
+
775
+ ```text
776
+ Trace ID: 8f31c2
777
+
778
+ enviar-pedido
779
+ │
780
+ ├── validar-pedido
781
+ ├── montar-payload
782
+ ├── consultar-estoque
783
+ └── enviar-api
784
+ ```
785
+
786
+ This context allows the Monitor to reconstruct complete execution flows across different parts of an application.
787
+
788
+ For example, a single HTTP request could produce:
789
+
790
+ ```text
791
+ POST /api/orders
792
+ │
793
+ ├── authenticate-user
794
+ ├── validate-order
795
+ ├── database.query
796
+ ├── payment.request
797
+ │ └── HTTP POST /payment
798
+ └── response
799
+ ```
800
+
801
+ ### Monitor Integration
802
+
803
+ When used with `MonitorTransport`, traces can be displayed as an execution tree instead of a collection of unrelated log messages.
804
+
805
+ For example:
806
+
807
+ ```text
808
+ TanamaoPDV
809
+
810
+ Trace #8F31C2
811
+
812
+ enviar-pedido 184ms
813
+ │
814
+ ├── montar-payload 12ms
815
+ │
816
+ ├── consultar-estoque 31ms
817
+ │
818
+ └── enviar-api 141ms ERROR
819
+ ├── POST /payment 140ms
820
+ └── HTTP 500
821
+ ```
822
+
823
+ This makes it possible to identify not only **that an operation failed**, but also **which step failed and how long each step took**.
824
+
825
+ ### Instrumentation vs Logger
826
+
827
+ Tracing and logging have different responsibilities:
828
+
829
+ ```text
830
+ Logger
831
+ → records information
832
+
833
+ Tracer
834
+ → records execution flow
835
+
836
+ Trace
837
+ → represents a complete operation
838
+
839
+ Span
840
+ → represents one operation within a trace
841
+
842
+ Formatter
843
+ → formats information
844
+
845
+ Transport
846
+ → sends information
847
+ ```
848
+
849
+ A tracer can integrate with the Logger, but it should remain independent from the logging implementation.
850
+
851
+ This allows the same instrumentation data to be consumed by the Console, File, Monitor, or other integrations without coupling the core tracer to a specific destination.
852
+
853
+ ### Future Instrumentation
854
+
855
+ The same tracing model can be extended beyond functions and HTTP requests:
856
+
857
+ ```text
858
+ Instrumentation
859
+ ├── FunctionTracer
860
+ ├── HttpTracer
861
+ ├── DatabaseTracer
862
+ ├── SocketTracer
863
+ ├── ProcessTracer
864
+ └── CustomTracer
865
+ ```
866
+
867
+ This allows different parts of an application to participate in the same trace while preserving a consistent execution model.
868
+
869
+
870
+ ---
871
+
872
+ # Roadmap
873
+
874
+ ### Phase 1 — Core
875
+
876
+ * [x] Logger
877
+ * [x] Socket
878
+ * [x] Retry
879
+ * [x] Timeout
880
+ * [x] HTTP
881
+
882
+ ### Phase 2 — Application Tools
883
+
884
+ * [ ] Request Logger
885
+ * [ ] Request ID
886
+ * [ ] Health Check
887
+ * [ ] Configuration
888
+ * [ ] Validation
889
+
890
+ ### Phase 3 — Developer Tools
891
+
892
+ * [ ] Process Monitor
893
+ * [ ] Scheduler
894
+ * [ ] Cache
895
+ * [ ] Webhooks
896
+ * [ ] Notifications
897
+
898
+ ### Phase 4 — Integrations
899
+
900
+ * [ ] Discord
901
+ * [ ] Slack
902
+ * [ ] HTTP logging API
903
+ * [ ] Redis
904
+ * [ ] Additional transports
905
+ * [ ] Additional adapters
906
+
907
+ ---
908
+
909
+ # Philosophy
910
+
911
+ > Build the boring parts once.
912
+
913
+ TS Toolkit is intended to provide the small infrastructure pieces that repeatedly appear in Node.js and TypeScript projects:
914
+
915
+ ```text
916
+ Logging
917
+ Communication
918
+ HTTP
919
+ Retries
920
+ Timeouts
921
+ Monitoring
922
+ Scheduling
923
+ Caching
924
+ Validation
925
+ Configuration
926
+ ```
927
+
928
+ Instead of every project implementing slightly different versions of the same utilities, TS Toolkit provides consistent, typed and composable building blocks.