@oxog/spark 1.1.1 → 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 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -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 +703 -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 +536 -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,173 +1,180 @@
1
1
  'use strict';
2
2
 
3
- /**
4
- * Cache middleware for @oxog/spark
5
- * Provides response caching functionality
6
- */
7
-
8
- /**
9
- * Creates a cache middleware
10
- * @param {Object} options - Cache configuration options
11
- * @param {number} [options.maxAge=3600] - Cache max age in seconds
12
- * @param {Function} [options.key] - Function to generate cache key
13
- * @param {Function} [options.condition] - Function to determine if response should be cached
14
- * @param {Object} [options.store] - Custom cache store (default: in-memory)
15
- * @returns {Function} Cache middleware function
16
- */
17
- function cache(options = {}) {
18
- const {
19
- maxAge = 3600,
20
- key = defaultKeyGenerator,
21
- condition = defaultCondition,
22
- store = new Map()
23
- } = options;
24
-
25
- return async function cacheMiddleware(ctx, next) {
26
- // Only cache GET and HEAD requests
27
- if (ctx.method !== 'GET' && ctx.method !== 'HEAD') {
28
- return next();
29
- }
30
-
31
- // Check if caching should be applied
32
- if (!condition(ctx)) {
33
- return next();
34
- }
35
-
36
- // Generate cache key
37
- const cacheKey = key(ctx);
38
-
39
- // Check if cached response exists
40
- const cached = store.get(cacheKey);
41
- if (cached && cached.expires > Date.now()) {
42
- // Serve from cache
43
- ctx.status = cached.status;
44
- ctx.body = cached.body;
45
- ctx.set(cached.headers);
46
- ctx.set('X-Cache', 'HIT');
47
- ctx.set('Age', Math.floor((Date.now() - cached.created) / 1000));
48
- return;
49
- }
50
-
51
- // Not in cache, proceed with request
52
- await next();
53
-
54
- // Store response in cache if successful
55
- if (ctx.status >= 200 && ctx.status < 300 && ctx.body) {
56
- const cacheEntry = {
57
- status: ctx.status,
58
- body: ctx.body,
59
- headers: filterHeaders(ctx.headers),
60
- created: Date.now(),
61
- expires: Date.now() + (maxAge * 1000)
62
- };
63
-
64
- store.set(cacheKey, cacheEntry);
65
-
66
- // Set cache headers
67
- ctx.set('Cache-Control', `public, max-age=${maxAge}`);
68
- ctx.set('X-Cache', 'MISS');
69
- }
70
- };
71
- }
72
-
73
- /**
74
- * Default cache key generator
75
- * @param {Object} ctx - Koa context
76
- * @returns {string} Cache key
77
- */
78
- function defaultKeyGenerator(ctx) {
79
- return ctx.url;
80
- }
81
-
82
- /**
83
- * Default condition to determine if response should be cached
84
- * @param {Object} ctx - Koa context
85
- * @returns {boolean} Whether to cache the response
86
- */
87
- function defaultCondition(ctx) {
88
- // Don't cache if no-cache header is present
89
- const cacheControl = ctx.get('Cache-Control');
90
- if (cacheControl && cacheControl.includes('no-cache')) {
91
- return false;
92
- }
93
-
94
- // Don't cache authenticated requests by default
95
- if (ctx.get('Authorization')) {
96
- return false;
97
- }
98
-
99
- return true;
100
- }
101
-
102
- /**
103
- * Filter headers to store in cache
104
- * @param {Object} headers - Response headers
105
- * @returns {Object} Filtered headers
106
- */
107
- function filterHeaders(headers) {
108
- const filtered = {};
109
- const allowedHeaders = [
110
- 'content-type',
111
- 'content-encoding',
112
- 'content-language',
113
- 'vary',
114
- 'etag',
115
- 'last-modified'
116
- ];
117
-
118
- for (const [key, value] of Object.entries(headers)) {
119
- if (allowedHeaders.includes(key.toLowerCase())) {
120
- filtered[key] = value;
121
- }
122
- }
123
-
124
- return filtered;
125
- }
126
-
127
- /**
128
- * Memory cache store with size limits
129
- */
130
- class MemoryCacheStore {
131
- constructor(maxSize = 100) {
132
- this.cache = new Map();
133
- this.maxSize = maxSize;
134
- }
135
-
136
- get(key) {
137
- const entry = this.cache.get(key);
138
- if (entry && entry.expires > Date.now()) {
139
- // Move to end (LRU)
140
- this.cache.delete(key);
141
- this.cache.set(key, entry);
142
- return entry;
143
- }
144
- // Remove expired entry
145
- if (entry) {
146
- this.cache.delete(key);
147
- }
148
- return null;
149
- }
150
-
151
- set(key, value) {
152
- // Remove oldest entry if at capacity
153
- if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
154
- const firstKey = this.cache.keys().next().value;
155
- this.cache.delete(firstKey);
156
- }
157
-
158
- this.cache.set(key, value);
159
- }
160
-
161
- clear() {
162
- this.cache.clear();
163
- }
164
-
165
- size() {
166
- return this.cache.size;
167
- }
168
- }
169
-
170
- // Export factory function and store class
171
- cache.MemoryCacheStore = MemoryCacheStore;
172
-
3
+ /**
4
+ * Cache middleware for @oxog/spark
5
+ * Provides response caching functionality
6
+ */
7
+
8
+ /**
9
+ * Creates a cache middleware
10
+ * @param {Object} options - Cache configuration options
11
+ * @param {number} [options.maxAge=3600] - Cache max age in seconds
12
+ * @param {Function} [options.key] - Function to generate cache key
13
+ * @param {Function} [options.condition] - Function to determine if response should be cached
14
+ * @param {Object} [options.store] - Custom cache store (default: in-memory)
15
+ * @returns {Function} Cache middleware function
16
+ */
17
+ function cache(options = {}) {
18
+ const {
19
+ maxAge = 3600,
20
+ key = defaultKeyGenerator,
21
+ condition = defaultCondition,
22
+ // Bounded by default: an unbounded Map keyed by URL lets clients exhaust
23
+ // memory with unique query strings.
24
+ store = new MemoryCacheStore(options.maxEntries || 1000)
25
+ } = options;
26
+
27
+ return async function cacheMiddleware(ctx, next) {
28
+ // Only cache GET and HEAD requests
29
+ if (ctx.method !== 'GET' && ctx.method !== 'HEAD') {
30
+ return next();
31
+ }
32
+
33
+ // Check if caching should be applied
34
+ if (!condition(ctx)) {
35
+ return next();
36
+ }
37
+
38
+ const cacheKey = key(ctx);
39
+ const cached = store.get(cacheKey);
40
+
41
+ if (cached && cached.expires > Date.now()) {
42
+ ctx.status(cached.status);
43
+ for (const [name, value] of Object.entries(cached.headers)) {
44
+ ctx.set(name, value);
45
+ }
46
+ ctx.set('X-Cache', 'HIT');
47
+ ctx.set('Age', Math.floor((Date.now() - cached.created) / 1000));
48
+ ctx.send(cached.body);
49
+ return undefined;
50
+ }
51
+
52
+ // Capture what the handler sends (ctx.body holds the request body)
53
+ const originalSend = ctx.send;
54
+ ctx.send = function(body) {
55
+ if (!ctx.responded && ctx.statusCode >= 200 && ctx.statusCode < 300 &&
56
+ (typeof body === 'string' || Buffer.isBuffer(body)) &&
57
+ !ctx.getHeader('set-cookie') && !/no-store|private/i.test(String(ctx.getHeader('cache-control') || ''))) {
58
+ ctx.set('Cache-Control', `public, max-age=${maxAge}`);
59
+ ctx.set('X-Cache', 'MISS');
60
+ store.set(cacheKey, {
61
+ status: ctx.statusCode,
62
+ body,
63
+ headers: filterHeaders(ctx.responseHeaders),
64
+ created: Date.now(),
65
+ expires: Date.now() + (maxAge * 1000)
66
+ });
67
+ }
68
+ return originalSend.call(this, body);
69
+ };
70
+
71
+ try {
72
+ await next();
73
+ } finally {
74
+ ctx.send = originalSend;
75
+ }
76
+ return undefined;
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Default cache key generator
82
+ * @param {Object} ctx - Koa context
83
+ * @returns {string} Cache key
84
+ */
85
+ function defaultKeyGenerator(ctx) {
86
+ return ctx.originalUrl || ctx.url.toString();
87
+ }
88
+
89
+ /**
90
+ * Default condition to determine if response should be cached
91
+ * @param {Object} ctx - Koa context
92
+ * @returns {boolean} Whether to cache the response
93
+ */
94
+ function defaultCondition(ctx) {
95
+ // Don't cache if no-cache header is present
96
+ const cacheControl = ctx.get('Cache-Control');
97
+ if (cacheControl && cacheControl.includes('no-cache')) {
98
+ return false;
99
+ }
100
+
101
+ // Don't cache authenticated requests by default
102
+ if (ctx.get('Authorization')) {
103
+ return false;
104
+ }
105
+
106
+ return true;
107
+ }
108
+
109
+ /**
110
+ * Filter headers to store in cache
111
+ * @param {Object} headers - Response headers
112
+ * @returns {Object} Filtered headers
113
+ */
114
+ function filterHeaders(headers) {
115
+ const filtered = {};
116
+ const allowedHeaders = [
117
+ 'content-type',
118
+ 'content-encoding',
119
+ 'content-language',
120
+ 'vary',
121
+ 'etag',
122
+ 'last-modified'
123
+ ];
124
+
125
+ for (const [key, value] of Object.entries(headers)) {
126
+ if (allowedHeaders.includes(key.toLowerCase())) {
127
+ filtered[key] = value;
128
+ }
129
+ }
130
+
131
+ return filtered;
132
+ }
133
+
134
+ /**
135
+ * Memory cache store with size limits
136
+ */
137
+ class MemoryCacheStore {
138
+ constructor(maxSize = 100) {
139
+ this.cache = new Map();
140
+ this.maxSize = maxSize;
141
+ }
142
+
143
+ get(key) {
144
+ const entry = this.cache.get(key);
145
+ if (entry && entry.expires > Date.now()) {
146
+ // Move to end (LRU)
147
+ this.cache.delete(key);
148
+ this.cache.set(key, entry);
149
+ return entry;
150
+ }
151
+ // Remove expired entry
152
+ if (entry) {
153
+ this.cache.delete(key);
154
+ }
155
+ return null;
156
+ }
157
+
158
+ set(key, value) {
159
+ // Remove oldest entry if at capacity
160
+ if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
161
+ const firstKey = this.cache.keys().next().value;
162
+ this.cache.delete(firstKey);
163
+ }
164
+
165
+ this.cache.set(key, value);
166
+ }
167
+
168
+ clear() {
169
+ this.cache.clear();
170
+ }
171
+
172
+ size() {
173
+ return this.cache.size;
174
+ }
175
+ }
176
+
177
+ // Export factory function and store class
178
+ cache.MemoryCacheStore = MemoryCacheStore;
179
+
173
180
  module.exports = cache;