@oxog/spark 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +632 -293
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -89
  5. package/src/core/application.js +1070 -956
  6. package/src/core/context.js +1100 -830
  7. package/src/core/middleware.js +305 -217
  8. package/src/index.js +183 -278
  9. package/src/middleware/body-parser.js +484 -526
  10. package/src/middleware/cache.js +179 -170
  11. package/src/middleware/compression.js +179 -182
  12. package/src/middleware/cors.js +178 -95
  13. package/src/middleware/health.js +221 -218
  14. package/src/middleware/logger.js +197 -194
  15. package/src/middleware/metrics.js +341 -327
  16. package/src/middleware/rate-limit.js +369 -319
  17. package/src/middleware/security.js +444 -332
  18. package/src/middleware/session.js +649 -529
  19. package/src/middleware/static.js +406 -299
  20. package/src/router/layer.js +199 -117
  21. package/src/router/route.js +151 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +147 -144
  24. package/src/utils/context-pool.js +85 -82
  25. package/src/utils/regex-validator.js +189 -176
  26. package/src/utils/safe-json.js +110 -0
  27. package/types/index.d.ts +536 -291
  28. package/dist/LICENSE +0 -21
  29. package/dist/README.md +0 -242
  30. package/dist/core/application.js +0 -957
  31. package/dist/core/context.js +0 -831
  32. package/dist/core/middleware.js +0 -218
  33. package/dist/core/request.js +0 -333
  34. package/dist/core/response.js +0 -375
  35. package/dist/index.js +0 -278
  36. package/dist/middleware/body-parser.js +0 -526
  37. package/dist/middleware/cache.js +0 -171
  38. package/dist/middleware/compression.js +0 -183
  39. package/dist/middleware/cors.js +0 -95
  40. package/dist/middleware/health.js +0 -219
  41. package/dist/middleware/index.js +0 -21
  42. package/dist/middleware/logger.js +0 -195
  43. package/dist/middleware/metrics.js +0 -328
  44. package/dist/middleware/rate-limit.js +0 -320
  45. package/dist/middleware/security.js +0 -333
  46. package/dist/middleware/session.js +0 -530
  47. package/dist/middleware/static.js +0 -299
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -117
  50. package/dist/router/route.js +0 -123
  51. package/dist/router/router.js +0 -756
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -145
  54. package/dist/utils/cache.js +0 -441
  55. package/dist/utils/context-pool.js +0 -83
  56. package/dist/utils/error-types.js +0 -132
  57. package/dist/utils/http.js +0 -413
  58. package/dist/utils/regex-validator.js +0 -177
  59. package/src/core/request.js +0 -333
  60. package/src/core/response.js +0 -375
  61. package/src/middleware/index.js +0 -21
  62. package/src/utils/cache.js +0 -441
  63. package/src/utils/error-types.js +0 -132
  64. package/src/utils/http.js +0 -413
@@ -1,219 +1,222 @@
1
- const os = require('os');
2
- const fs = require('fs');
3
- const { promisify } = require('util');
4
-
5
- const stat = promisify(fs.stat);
6
-
7
- /**
8
- * Health check middleware with configurable checks
9
- * @param {Object} options - Health check options
10
- * @returns {Function} Middleware function
11
- */
12
- function healthCheck(options = {}) {
13
- const opts = {
14
- path: '/_health',
15
- checks: {
16
- uptime: true,
17
- memory: true,
18
- cpu: true,
19
- disk: false,
20
- custom: []
21
- },
22
- timeout: 5000,
23
- includeDetails: process.env.NODE_ENV !== 'production',
24
- ...options
25
- };
26
-
27
- return async (ctx, next) => {
28
- if (ctx.path !== opts.path) {
29
- return next();
30
- }
31
-
32
- if (ctx.method !== 'GET') {
33
- ctx.status(405).json({ error: 'Method Not Allowed' });
34
- return;
35
- }
36
-
37
- try {
38
- const healthData = await performHealthChecks(opts);
39
-
40
- const status = healthData.checks.every(check => check.status === 'healthy') ? 'healthy' : 'unhealthy';
41
- const statusCode = status === 'healthy' ? 200 : 503;
42
-
43
- ctx.status(statusCode).json({
44
- status,
45
- timestamp: new Date().toISOString(),
46
- ...healthData
47
- });
48
-
49
- } catch (error) {
50
- ctx.status(503).json({
51
- status: 'unhealthy',
52
- timestamp: new Date().toISOString(),
53
- error: error.message,
54
- checks: []
55
- });
56
- }
57
- };
58
- }
59
-
60
- async function performHealthChecks(opts) {
61
- const checks = [];
62
- const details = {};
63
-
64
- // Uptime check
65
- if (opts.checks.uptime) {
66
- const uptime = process.uptime();
67
- checks.push({
68
- name: 'uptime',
69
- status: 'healthy',
70
- value: `${Math.floor(uptime)}s`
71
- });
72
-
73
- if (opts.includeDetails) {
74
- details.uptime = {
75
- seconds: uptime,
76
- formatted: formatUptime(uptime)
77
- };
78
- }
79
- }
80
-
81
- // Memory check
82
- if (opts.checks.memory) {
83
- const memUsage = process.memoryUsage();
84
- const totalMem = os.totalmem();
85
- const freeMem = os.freemem();
86
- const usedMem = totalMem - freeMem;
87
- const memPercentage = (usedMem / totalMem) * 100;
88
-
89
- const memStatus = memPercentage > 90 ? 'unhealthy' : memPercentage > 75 ? 'degraded' : 'healthy';
90
-
91
- checks.push({
92
- name: 'memory',
93
- status: memStatus,
94
- value: `${memPercentage.toFixed(1)}%`
95
- });
96
-
97
- if (opts.includeDetails) {
98
- details.memory = {
99
- usage: memUsage,
100
- system: {
101
- total: totalMem,
102
- free: freeMem,
103
- used: usedMem,
104
- percentage: memPercentage
105
- }
106
- };
107
- }
108
- }
109
-
110
- // CPU check
111
- if (opts.checks.cpu) {
112
- const loadAvg = os.loadavg();
113
- const cpuCount = os.cpus().length;
114
- const avgLoad = loadAvg[0] / cpuCount;
115
-
116
- const cpuStatus = avgLoad > 0.8 ? 'unhealthy' : avgLoad > 0.6 ? 'degraded' : 'healthy';
117
-
118
- checks.push({
119
- name: 'cpu',
120
- status: cpuStatus,
121
- value: `${(avgLoad * 100).toFixed(1)}%`
122
- });
123
-
124
- if (opts.includeDetails) {
125
- details.cpu = {
126
- loadAverage: loadAvg,
127
- cores: cpuCount,
128
- usage: avgLoad
129
- };
130
- }
131
- }
132
-
133
- // Disk check
134
- if (opts.checks.disk) {
135
- try {
136
- const stats = await stat(process.cwd());
137
- checks.push({
138
- name: 'disk',
139
- status: 'healthy',
140
- value: 'accessible'
141
- });
142
- } catch (error) {
143
- checks.push({
144
- name: 'disk',
145
- status: 'unhealthy',
146
- value: 'inaccessible',
147
- error: error.message
148
- });
149
- }
150
- }
151
-
152
- // Custom checks
153
- for (const customCheck of opts.checks.custom) {
154
- try {
155
- const result = await Promise.race([
156
- customCheck.check(),
157
- new Promise((_, reject) =>
158
- setTimeout(() => reject(new Error('Health check timeout')), opts.timeout)
159
- )
160
- ]);
161
-
162
- checks.push({
163
- name: customCheck.name,
164
- status: result.status || 'healthy',
165
- value: result.value || 'ok',
166
- ...result
167
- });
168
- } catch (error) {
169
- checks.push({
170
- name: customCheck.name,
171
- status: 'unhealthy',
172
- value: 'failed',
173
- error: error.message
174
- });
175
- }
176
- }
177
-
178
- const result = { checks };
179
-
180
- if (opts.includeDetails) {
181
- result.details = details;
182
- result.system = {
183
- platform: os.platform(),
184
- arch: os.arch(),
185
- nodeVersion: process.version,
186
- pid: process.pid
187
- };
188
- }
189
-
190
- return result;
191
- }
192
-
193
- function formatUptime(seconds) {
194
- const days = Math.floor(seconds / 86400);
195
- const hours = Math.floor((seconds % 86400) / 3600);
196
- const minutes = Math.floor((seconds % 3600) / 60);
197
- const secs = Math.floor(seconds % 60);
198
-
199
- const parts = [];
200
- if (days > 0) parts.push(`${days}d`);
201
- if (hours > 0) parts.push(`${hours}h`);
202
- if (minutes > 0) parts.push(`${minutes}m`);
203
- if (secs > 0) parts.push(`${secs}s`);
204
-
205
- return parts.join(' ') || '0s';
206
- }
207
-
208
- /**
209
- * Create a custom health check
210
- * @param {string} name - Check name
211
- * @param {Function} checkFn - Function that returns health status
212
- * @returns {Object} Custom check object
213
- */
214
- function createCustomCheck(name, checkFn) {
215
- return { name, check: checkFn };
216
- }
217
-
218
- module.exports = healthCheck;
1
+ 'use strict';
2
+
3
+ const os = require('os');
4
+ const fs = require('fs');
5
+ const { promisify } = require('util');
6
+
7
+ const stat = promisify(fs.stat);
8
+
9
+ /**
10
+ * Health check middleware with configurable checks
11
+ * @param {Object} options - Health check options
12
+ * @returns {Function} Middleware function
13
+ */
14
+ function healthCheck(options = {}) {
15
+ const opts = {
16
+ path: '/_health',
17
+ checks: {
18
+ uptime: true,
19
+ memory: true,
20
+ cpu: true,
21
+ disk: false,
22
+ custom: []
23
+ },
24
+ timeout: 5000,
25
+ includeDetails: process.env.NODE_ENV !== 'production',
26
+ ...options
27
+ };
28
+
29
+ return async (ctx, next) => {
30
+ if (ctx.path !== opts.path) {
31
+ return next();
32
+ }
33
+
34
+ if (ctx.method !== 'GET') {
35
+ ctx.status(405).json({ error: 'Method Not Allowed' });
36
+ return;
37
+ }
38
+
39
+ try {
40
+ const healthData = await performHealthChecks(opts);
41
+
42
+ const status = healthData.checks.every(check => check.status === 'healthy') ? 'healthy' : 'unhealthy';
43
+ const statusCode = status === 'healthy' ? 200 : 503;
44
+
45
+ ctx.status(statusCode).json({
46
+ status,
47
+ timestamp: new Date().toISOString(),
48
+ ...healthData
49
+ });
50
+
51
+ } catch (error) {
52
+ ctx.status(503).json({
53
+ status: 'unhealthy',
54
+ timestamp: new Date().toISOString(),
55
+ error: error.message,
56
+ checks: []
57
+ });
58
+ }
59
+ };
60
+ }
61
+
62
+ async function performHealthChecks(opts) {
63
+ const checks = [];
64
+ const details = {};
65
+
66
+ // Uptime check
67
+ if (opts.checks.uptime) {
68
+ const uptime = process.uptime();
69
+ checks.push({
70
+ name: 'uptime',
71
+ status: 'healthy',
72
+ value: `${Math.floor(uptime)}s`
73
+ });
74
+
75
+ if (opts.includeDetails) {
76
+ details.uptime = {
77
+ seconds: uptime,
78
+ formatted: formatUptime(uptime)
79
+ };
80
+ }
81
+ }
82
+
83
+ // Memory check
84
+ if (opts.checks.memory) {
85
+ const memUsage = process.memoryUsage();
86
+ const totalMem = os.totalmem();
87
+ const freeMem = os.freemem();
88
+ const usedMem = totalMem - freeMem;
89
+ const memPercentage = (usedMem / totalMem) * 100;
90
+
91
+ const memStatus = memPercentage > 90 ? 'unhealthy' : memPercentage > 75 ? 'degraded' : 'healthy';
92
+
93
+ checks.push({
94
+ name: 'memory',
95
+ status: memStatus,
96
+ value: `${memPercentage.toFixed(1)}%`
97
+ });
98
+
99
+ if (opts.includeDetails) {
100
+ details.memory = {
101
+ usage: memUsage,
102
+ system: {
103
+ total: totalMem,
104
+ free: freeMem,
105
+ used: usedMem,
106
+ percentage: memPercentage
107
+ }
108
+ };
109
+ }
110
+ }
111
+
112
+ // CPU check
113
+ if (opts.checks.cpu) {
114
+ const loadAvg = os.loadavg();
115
+ const cpuCount = os.cpus().length;
116
+ const avgLoad = loadAvg[0] / cpuCount;
117
+
118
+ const cpuStatus = avgLoad > 0.8 ? 'unhealthy' : avgLoad > 0.6 ? 'degraded' : 'healthy';
119
+
120
+ checks.push({
121
+ name: 'cpu',
122
+ status: cpuStatus,
123
+ value: `${(avgLoad * 100).toFixed(1)}%`
124
+ });
125
+
126
+ if (opts.includeDetails) {
127
+ details.cpu = {
128
+ loadAverage: loadAvg,
129
+ cores: cpuCount,
130
+ usage: avgLoad
131
+ };
132
+ }
133
+ }
134
+
135
+ // Disk check
136
+ if (opts.checks.disk) {
137
+ try {
138
+ await stat(process.cwd());
139
+ checks.push({
140
+ name: 'disk',
141
+ status: 'healthy',
142
+ value: 'accessible'
143
+ });
144
+ } catch (error) {
145
+ checks.push({
146
+ name: 'disk',
147
+ status: 'unhealthy',
148
+ value: 'inaccessible',
149
+ error: error.message
150
+ });
151
+ }
152
+ }
153
+
154
+ // Custom checks
155
+ for (const customCheck of opts.checks.custom) {
156
+ try {
157
+ let timer;
158
+ const result = await Promise.race([
159
+ Promise.resolve().then(() => customCheck.check()),
160
+ new Promise((_, reject) => {
161
+ timer = setTimeout(() => reject(new Error('Health check timeout')), opts.timeout);
162
+ })
163
+ ]).finally(() => clearTimeout(timer));
164
+
165
+ checks.push({
166
+ ...(result && typeof result === 'object' ? result : {}),
167
+ name: customCheck.name,
168
+ status: (result && result.status) || 'healthy',
169
+ value: (result && result.value) || 'ok'
170
+ });
171
+ } catch (error) {
172
+ checks.push({
173
+ name: customCheck.name,
174
+ status: 'unhealthy',
175
+ value: 'failed',
176
+ error: error.message
177
+ });
178
+ }
179
+ }
180
+
181
+ const result = { checks };
182
+
183
+ if (opts.includeDetails) {
184
+ result.details = details;
185
+ result.system = {
186
+ platform: os.platform(),
187
+ arch: os.arch(),
188
+ nodeVersion: process.version,
189
+ pid: process.pid
190
+ };
191
+ }
192
+
193
+ return result;
194
+ }
195
+
196
+ function formatUptime(seconds) {
197
+ const days = Math.floor(seconds / 86400);
198
+ const hours = Math.floor((seconds % 86400) / 3600);
199
+ const minutes = Math.floor((seconds % 3600) / 60);
200
+ const secs = Math.floor(seconds % 60);
201
+
202
+ const parts = [];
203
+ if (days > 0) parts.push(`${days}d`);
204
+ if (hours > 0) parts.push(`${hours}h`);
205
+ if (minutes > 0) parts.push(`${minutes}m`);
206
+ if (secs > 0) parts.push(`${secs}s`);
207
+
208
+ return parts.join(' ') || '0s';
209
+ }
210
+
211
+ /**
212
+ * Create a custom health check
213
+ * @param {string} name - Check name
214
+ * @param {Function} checkFn - Function that returns health status
215
+ * @returns {Object} Custom check object
216
+ */
217
+ function createCustomCheck(name, checkFn) {
218
+ return { name, check: checkFn };
219
+ }
220
+
221
+ module.exports = healthCheck;
219
222
  module.exports.createCustomCheck = createCustomCheck;