@oxog/spark 1.1.1 → 1.3.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 (64) hide show
  1. package/CHANGELOG.md +656 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +90 -89
  5. package/src/core/application.js +1068 -956
  6. package/src/core/context.js +1098 -830
  7. package/src/core/middleware.js +303 -217
  8. package/src/index.js +183 -280
  9. package/src/middleware/body-parser.js +482 -526
  10. package/src/middleware/cache.js +177 -170
  11. package/src/middleware/compression.js +177 -182
  12. package/src/middleware/cors.js +176 -95
  13. package/src/middleware/health.js +219 -218
  14. package/src/middleware/logger.js +195 -194
  15. package/src/middleware/metrics.js +339 -327
  16. package/src/middleware/rate-limit.js +367 -319
  17. package/src/middleware/security.js +442 -332
  18. package/src/middleware/session.js +647 -529
  19. package/src/middleware/static.js +404 -299
  20. package/src/router/layer.js +197 -117
  21. package/src/router/route.js +149 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +145 -147
  24. package/src/utils/context-pool.js +83 -82
  25. package/src/utils/regex-validator.js +187 -163
  26. package/src/utils/safe-json.js +110 -0
  27. package/types/index.d.ts +538 -291
  28. package/dist/LICENSE +0 -21
  29. package/dist/README.md +0 -242
  30. package/dist/core/application.js +0 -959
  31. package/dist/core/context.js +0 -833
  32. package/dist/core/middleware.js +0 -220
  33. package/dist/core/request.js +0 -335
  34. package/dist/core/response.js +0 -377
  35. package/dist/index.js +0 -280
  36. package/dist/middleware/body-parser.js +0 -528
  37. package/dist/middleware/cache.js +0 -173
  38. package/dist/middleware/compression.js +0 -185
  39. package/dist/middleware/cors.js +0 -97
  40. package/dist/middleware/health.js +0 -221
  41. package/dist/middleware/index.js +0 -23
  42. package/dist/middleware/logger.js +0 -197
  43. package/dist/middleware/metrics.js +0 -330
  44. package/dist/middleware/rate-limit.js +0 -322
  45. package/dist/middleware/security.js +0 -335
  46. package/dist/middleware/session.js +0 -532
  47. package/dist/middleware/static.js +0 -301
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -119
  50. package/dist/router/route.js +0 -125
  51. package/dist/router/router.js +0 -758
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -150
  54. package/dist/utils/cache.js +0 -443
  55. package/dist/utils/context-pool.js +0 -85
  56. package/dist/utils/error-types.js +0 -134
  57. package/dist/utils/http.js +0 -415
  58. package/dist/utils/regex-validator.js +0 -166
  59. package/src/core/request.js +0 -335
  60. package/src/core/response.js +0 -377
  61. package/src/middleware/index.js +0 -23
  62. package/src/utils/cache.js +0 -443
  63. package/src/utils/error-types.js +0 -134
  64. package/src/utils/http.js +0 -415
@@ -1,197 +0,0 @@
1
- 'use strict';
2
-
3
- const util = require('util');
4
- const { EventEmitter } = require('events');
5
-
6
- const DEFAULT_FORMAT = ':method :url :status :response-time ms';
7
- const DEFAULT_SKIP = () => false;
8
-
9
- class Logger extends EventEmitter {
10
- constructor(options = {}) {
11
- super();
12
- this.options = {
13
- format: options.format || DEFAULT_FORMAT,
14
- skip: options.skip || DEFAULT_SKIP,
15
- stream: options.stream || process.stdout,
16
- immediate: options.immediate || false,
17
- ...options
18
- };
19
- }
20
-
21
- format(tokens, ctx) {
22
- const format = this.options.format;
23
-
24
- if (typeof format === 'function') {
25
- return format(tokens, ctx);
26
- }
27
-
28
- return format.replace(/:(\w+)/g, (match, token) => {
29
- return tokens[token] || '-';
30
- });
31
- }
32
-
33
- log(ctx, start, length) {
34
- if (this.options.skip(ctx)) {
35
- return;
36
- }
37
-
38
- const responseTime = Date.now() - start;
39
- const contentLength = length || ctx.get('content-length') || '-';
40
-
41
- const tokens = {
42
- method: ctx.method,
43
- url: ctx.originalUrl || ctx.url,
44
- status: ctx.statusCode,
45
- 'response-time': responseTime,
46
- 'content-length': contentLength,
47
- referrer: ctx.get('referrer') || ctx.get('referer') || '-',
48
- 'user-agent': ctx.get('user-agent') || '-',
49
- 'remote-addr': ctx.ip() || '-',
50
- 'remote-user': ctx.user ? ctx.user.name : '-',
51
- date: new Date().toISOString(),
52
- 'http-version': ctx.req.httpVersion,
53
- res: ctx.res
54
- };
55
-
56
- const line = this.format(tokens, ctx);
57
-
58
- if (this.options.stream) {
59
- this.options.stream.write(line + '\n');
60
- }
61
-
62
- this.emit('log', tokens, ctx);
63
- }
64
- }
65
-
66
- function logger(options = {}) {
67
- const log = new Logger(options);
68
-
69
- return async (ctx, next) => {
70
- const start = Date.now();
71
-
72
- if (options.immediate) {
73
- log.log(ctx, start);
74
- }
75
-
76
- await next();
77
-
78
- if (!options.immediate) {
79
- log.log(ctx, start);
80
- }
81
- };
82
- }
83
-
84
- function morgan(format, options = {}) {
85
- const formats = {
86
- combined: ':remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :content-length ":referrer" ":user-agent"',
87
- common: ':remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :content-length',
88
- dev: ':method :url :status :response-time ms - :content-length',
89
- short: ':remote-addr :remote-user :method :url HTTP/:http-version :status :content-length - :response-time ms',
90
- tiny: ':method :url :status :content-length - :response-time ms'
91
- };
92
-
93
- const logFormat = formats[format] || format || formats.dev;
94
-
95
- return logger({
96
- ...options,
97
- format: logFormat
98
- });
99
- }
100
-
101
- function accessLog(options = {}) {
102
- const opts = {
103
- format: 'combined',
104
- ...options
105
- };
106
-
107
- return morgan(opts.format, opts);
108
- }
109
-
110
- function devLogger(options = {}) {
111
- const colorStatus = (status) => {
112
- if (status >= 500) return `\x1b[31m${status}\x1b[0m`; // Red
113
- if (status >= 400) return `\x1b[33m${status}\x1b[0m`; // Yellow
114
- if (status >= 300) return `\x1b[36m${status}\x1b[0m`; // Cyan
115
- if (status >= 200) return `\x1b[32m${status}\x1b[0m`; // Green
116
- return status;
117
- };
118
-
119
- const colorMethod = (method) => {
120
- const colors = {
121
- GET: '\x1b[32m', // Green
122
- POST: '\x1b[33m', // Yellow
123
- PUT: '\x1b[34m', // Blue
124
- DELETE: '\x1b[31m', // Red
125
- PATCH: '\x1b[35m', // Magenta
126
- HEAD: '\x1b[36m', // Cyan
127
- OPTIONS: '\x1b[37m' // White
128
- };
129
-
130
- const color = colors[method] || '\x1b[37m';
131
- return `${color}${method}\x1b[0m`;
132
- };
133
-
134
- return logger({
135
- format: (tokens, ctx) => {
136
- const method = colorMethod(tokens.method);
137
- const status = colorStatus(tokens.status);
138
- const url = tokens.url;
139
- const responseTime = tokens['response-time'];
140
- const contentLength = tokens['content-length'];
141
-
142
- return `${method} ${url} ${status} ${responseTime}ms - ${contentLength}`;
143
- },
144
- ...options
145
- });
146
- }
147
-
148
- function errorLogger(options = {}) {
149
- const opts = {
150
- skip: (ctx) => ctx.statusCode < 400,
151
- ...options
152
- };
153
-
154
- return logger(opts);
155
- }
156
-
157
- function requestLogger(options = {}) {
158
- const opts = {
159
- immediate: true,
160
- format: ':method :url',
161
- ...options
162
- };
163
-
164
- return logger(opts);
165
- }
166
-
167
- function structuredLogger(options = {}) {
168
- const opts = {
169
- format: (tokens, ctx) => {
170
- const logData = {
171
- timestamp: new Date().toISOString(),
172
- method: tokens.method,
173
- url: tokens.url,
174
- status: tokens.status,
175
- responseTime: tokens['response-time'],
176
- contentLength: tokens['content-length'],
177
- userAgent: tokens['user-agent'],
178
- ip: tokens['remote-addr'],
179
- referrer: tokens.referrer
180
- };
181
-
182
- return JSON.stringify(logData);
183
- },
184
- ...options
185
- };
186
-
187
- return logger(opts);
188
- }
189
-
190
- module.exports = logger;
191
- module.exports.Logger = Logger;
192
- module.exports.morgan = morgan;
193
- module.exports.accessLog = accessLog;
194
- module.exports.devLogger = devLogger;
195
- module.exports.errorLogger = errorLogger;
196
- module.exports.requestLogger = requestLogger;
197
- module.exports.structuredLogger = structuredLogger;
@@ -1,330 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * Metrics collection middleware for performance monitoring
5
- */
6
-
7
- class MetricsCollector {
8
- constructor() {
9
- this.metrics = {
10
- requests: {
11
- total: 0,
12
- byMethod: {},
13
- byStatus: {},
14
- byPath: {}
15
- },
16
- responseTime: {
17
- total: 0,
18
- count: 0,
19
- min: Infinity,
20
- max: 0,
21
- buckets: {
22
- '<100ms': 0,
23
- '100-500ms': 0,
24
- '500ms-1s': 0,
25
- '1s-5s': 0,
26
- '>5s': 0
27
- }
28
- },
29
- errors: {
30
- total: 0,
31
- byType: {},
32
- byStatus: {}
33
- },
34
- activeConnections: 0,
35
- memory: {
36
- samples: [],
37
- maxSamples: 100
38
- }
39
- };
40
-
41
- this.startTime = Date.now();
42
- this.memoryInterval = null;
43
- this.setupMemoryTracking();
44
- }
45
-
46
- setupMemoryTracking() {
47
- this.memoryInterval = setInterval(() => {
48
- const memUsage = process.memoryUsage();
49
- this.metrics.memory.samples.push({
50
- timestamp: Date.now(),
51
- ...memUsage
52
- });
53
-
54
- // Keep only last 100 samples
55
- if (this.metrics.memory.samples.length > this.metrics.memory.maxSamples) {
56
- this.metrics.memory.samples.shift();
57
- }
58
- }, 30000); // Every 30 seconds
59
-
60
- // Don't keep process alive
61
- this.memoryInterval.unref();
62
- }
63
-
64
- recordRequest(method, path, status, duration, error = null) {
65
- // Total requests
66
- this.metrics.requests.total++;
67
-
68
- // By method
69
- this.metrics.requests.byMethod[method] = (this.metrics.requests.byMethod[method] || 0) + 1;
70
-
71
- // By status
72
- this.metrics.requests.byStatus[status] = (this.metrics.requests.byStatus[status] || 0) + 1;
73
-
74
- // By path (sanitized)
75
- const sanitizedPath = this.sanitizePath(path);
76
- this.metrics.requests.byPath[sanitizedPath] = (this.metrics.requests.byPath[sanitizedPath] || 0) + 1;
77
-
78
- // Response time
79
- this.metrics.responseTime.total += duration;
80
- this.metrics.responseTime.count++;
81
- this.metrics.responseTime.min = Math.min(this.metrics.responseTime.min, duration);
82
- this.metrics.responseTime.max = Math.max(this.metrics.responseTime.max, duration);
83
-
84
- // Response time buckets
85
- if (duration < 100) {
86
- this.metrics.responseTime.buckets['<100ms']++;
87
- } else if (duration < 500) {
88
- this.metrics.responseTime.buckets['100-500ms']++;
89
- } else if (duration < 1000) {
90
- this.metrics.responseTime.buckets['500ms-1s']++;
91
- } else if (duration < 5000) {
92
- this.metrics.responseTime.buckets['1s-5s']++;
93
- } else {
94
- this.metrics.responseTime.buckets['>5s']++;
95
- }
96
-
97
- // Errors
98
- if (error || status >= 400) {
99
- this.metrics.errors.total++;
100
- this.metrics.errors.byStatus[status] = (this.metrics.errors.byStatus[status] || 0) + 1;
101
-
102
- if (error) {
103
- const errorType = error.constructor.name;
104
- this.metrics.errors.byType[errorType] = (this.metrics.errors.byType[errorType] || 0) + 1;
105
- }
106
- }
107
- }
108
-
109
- sanitizePath(path) {
110
- // Replace IDs and numbers with placeholders
111
- return path
112
- .replace(/\/\d+/g, '/:id')
113
- .replace(/\/[a-f0-9]{24}/g, '/:id') // MongoDB ObjectIds
114
- .replace(/\/[a-f0-9-]{36}/g, '/:uuid'); // UUIDs
115
- }
116
-
117
- incrementActiveConnections() {
118
- this.metrics.activeConnections++;
119
- }
120
-
121
- decrementActiveConnections() {
122
- this.metrics.activeConnections = Math.max(0, this.metrics.activeConnections - 1);
123
- }
124
-
125
- getMetrics() {
126
- const now = Date.now();
127
- const uptime = now - this.startTime;
128
-
129
- const avgResponseTime = this.metrics.responseTime.count > 0
130
- ? this.metrics.responseTime.total / this.metrics.responseTime.count
131
- : 0;
132
-
133
- return {
134
- timestamp: now,
135
- uptime: uptime,
136
- requests: {
137
- ...this.metrics.requests,
138
- rps: this.metrics.requests.total / (uptime / 1000) // requests per second
139
- },
140
- responseTime: {
141
- ...this.metrics.responseTime,
142
- average: avgResponseTime,
143
- min: this.metrics.responseTime.min === Infinity ? 0 : this.metrics.responseTime.min
144
- },
145
- errors: {
146
- ...this.metrics.errors,
147
- errorRate: this.metrics.requests.total > 0
148
- ? (this.metrics.errors.total / this.metrics.requests.total * 100).toFixed(2) + '%'
149
- : '0%'
150
- },
151
- activeConnections: this.metrics.activeConnections,
152
- memory: this.getMemoryStats()
153
- };
154
- }
155
-
156
- getMemoryStats() {
157
- if (this.metrics.memory.samples.length === 0) {
158
- return { current: process.memoryUsage() };
159
- }
160
-
161
- const latest = this.metrics.memory.samples[this.metrics.memory.samples.length - 1];
162
- const samples = this.metrics.memory.samples;
163
-
164
- const heapUsedSamples = samples.map(s => s.heapUsed);
165
- const avg = heapUsedSamples.reduce((a, b) => a + b, 0) / heapUsedSamples.length;
166
- const max = Math.max(...heapUsedSamples);
167
- const min = Math.min(...heapUsedSamples);
168
-
169
- return {
170
- current: {
171
- heapUsed: latest.heapUsed,
172
- heapTotal: latest.heapTotal,
173
- external: latest.external,
174
- rss: latest.rss
175
- },
176
- stats: {
177
- average: avg,
178
- max: max,
179
- min: min,
180
- samples: samples.length
181
- }
182
- };
183
- }
184
-
185
- reset() {
186
- this.metrics = {
187
- requests: {
188
- total: 0,
189
- byMethod: {},
190
- byStatus: {},
191
- byPath: {}
192
- },
193
- responseTime: {
194
- total: 0,
195
- count: 0,
196
- min: Infinity,
197
- max: 0,
198
- buckets: {
199
- '<100ms': 0,
200
- '100-500ms': 0,
201
- '500ms-1s': 0,
202
- '1s-5s': 0,
203
- '>5s': 0
204
- }
205
- },
206
- errors: {
207
- total: 0,
208
- byType: {},
209
- byStatus: {}
210
- },
211
- activeConnections: 0,
212
- memory: {
213
- samples: [],
214
- maxSamples: 100
215
- }
216
- };
217
-
218
- this.startTime = Date.now();
219
- }
220
-
221
- stop() {
222
- if (this.memoryInterval) {
223
- clearInterval(this.memoryInterval);
224
- this.memoryInterval = null;
225
- }
226
- }
227
- }
228
-
229
- // Global metrics collector instance
230
- const globalCollector = new MetricsCollector();
231
-
232
- /**
233
- * Metrics middleware
234
- * @param {Object} options - Metrics options
235
- * @returns {Function} Middleware function
236
- */
237
- function metrics(options = {}) {
238
- const opts = {
239
- path: '/_metrics',
240
- collectResponseTime: true,
241
- collectMemory: true,
242
- excludePaths: ['/favicon.ico'],
243
- customCollector: null,
244
- ...options
245
- };
246
-
247
- const collector = opts.customCollector || globalCollector;
248
-
249
- const middleware = async (ctx, next) => {
250
- // Serve metrics endpoint
251
- if (ctx.path === opts.path) {
252
- if (ctx.method !== 'GET') {
253
- ctx.status(405).json({ error: 'Method Not Allowed' });
254
- return;
255
- }
256
-
257
- const metricsData = collector.getMetrics();
258
- ctx.json(metricsData);
259
- return;
260
- }
261
-
262
- // Skip excluded paths
263
- if (opts.excludePaths.includes(ctx.path)) {
264
- return next();
265
- }
266
-
267
- // Track active connections
268
- collector.incrementActiveConnections();
269
-
270
- const startTime = Date.now();
271
- let error = null;
272
-
273
- try {
274
- await next();
275
- } catch (err) {
276
- error = err;
277
- throw err;
278
- } finally {
279
- const duration = Date.now() - startTime;
280
-
281
- // Record metrics
282
- collector.recordRequest(
283
- ctx.method,
284
- ctx.path,
285
- ctx.statusCode,
286
- duration,
287
- error
288
- );
289
-
290
- // Add response time header
291
- if (opts.collectResponseTime) {
292
- ctx.set('X-Response-Time', `${duration}ms`);
293
- }
294
-
295
- // Decrement active connections
296
- collector.decrementActiveConnections();
297
- }
298
- };
299
-
300
- // Add cleanup method to middleware
301
- middleware.cleanup = () => {
302
- collector.stop();
303
- };
304
-
305
- // Add collector access
306
- middleware.collector = collector;
307
-
308
- return middleware;
309
- }
310
-
311
- /**
312
- * Create a custom metrics collector
313
- * @returns {MetricsCollector} New metrics collector instance
314
- */
315
- function createCollector() {
316
- return new MetricsCollector();
317
- }
318
-
319
- /**
320
- * Get global metrics collector
321
- * @returns {MetricsCollector} Global collector instance
322
- */
323
- function getGlobalCollector() {
324
- return globalCollector;
325
- }
326
-
327
- module.exports = metrics;
328
- module.exports.createCollector = createCollector;
329
- module.exports.getGlobalCollector = getGlobalCollector;
330
- module.exports.MetricsCollector = MetricsCollector;