@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,119 +1,199 @@
1
1
  'use strict';
2
2
 
3
- class Layer {
4
- constructor(path, options, handler, router = null) {
5
- this.path = path;
6
- this.handler = handler;
7
- this.name = handler.name || '<anonymous>';
8
- this.options = options;
9
- this.route = null;
10
- this.method = null;
11
- this.router = router;
12
-
13
- // Use router's pathToRegExp if available, otherwise create a default regex
14
- if (router && router.pathToRegExp) {
15
- this.regexp = router.pathToRegExp(path, options);
16
- } else {
17
- // Fallback to default regex creation without circular dependency
18
- this.regexp = this.createDefaultRegex(path, options);
19
- }
20
- this.keys = this.regexp.keys;
21
- }
22
-
23
- createDefaultRegex(path, options = {}) {
24
- const { sensitive = false, strict = false, end = true } = options;
25
-
26
- if (path instanceof RegExp) {
27
- return { regexp: path, keys: [] };
28
- }
29
-
30
- const keys = [];
31
- let regexp = path;
32
-
33
- // Escape forward slashes
34
- regexp = regexp.replace(/\\\//g, '/');
35
-
36
- // Replace parameters
37
- regexp = regexp.replace(/:([^(/\\]+)/g, (match, key) => {
38
- keys.push({ name: key, optional: false });
39
- return '([^/]+)';
40
- });
41
-
42
- // Replace wildcards
43
- regexp = regexp.replace(/\*([^(/\\]*)/g, (match, key) => {
44
- keys.push({ name: key || 'wild', optional: false });
45
- return '(.*)';
46
- });
47
-
48
- // Add end pattern
49
- if (end) {
50
- regexp += strict ? '' : '/?';
51
- }
52
-
53
- regexp += end ? '$' : '';
54
-
55
- const flags = sensitive ? '' : 'i';
56
- return {
57
- regexp: new RegExp(`^${regexp}`, flags),
58
- keys
59
- };
60
- }
61
-
62
- match(path) {
63
- const match = this.regexp.regexp.exec(path);
64
-
65
- if (!match) {
66
- return false;
67
- }
68
-
69
- const params = {};
70
-
71
- for (let i = 1; i < match.length; i++) {
72
- const key = this.keys[i - 1];
73
- const value = match[i];
74
-
75
- if (value !== undefined) {
76
- params[key.name] = decodeParam(value);
77
- }
78
- }
79
-
80
- return {
81
- path: match[0],
82
- params
83
- };
84
- }
85
-
86
- async handle(ctx, next) {
87
- if (this.handler.length > 2) {
88
- return this.handler(ctx, next);
89
- } else {
90
- await this.handler(ctx, next);
91
- }
92
- }
93
-
94
- handles_method(method) {
95
- if (this.method) {
96
- return this.method === method;
97
- }
98
-
99
- if (this.route) {
100
- return this.route.handles_method(method);
101
- }
102
-
103
- return true;
104
- }
105
- }
106
-
107
- function decodeParam(value) {
108
- if (typeof value !== 'string' || value.length === 0) {
109
- return value;
110
- }
111
-
112
- try {
113
- return decodeURIComponent(value);
114
- } catch (error) {
115
- throw new Error(`Failed to decode param '${value}'`);
116
- }
117
- }
118
-
119
- module.exports = Layer;
3
+ /**
4
+ * @fileoverview Layer: one middleware or route entry in a Router stack
5
+ * @since 1.0.0
6
+ */
7
+
8
+ const PARAM_PLACEHOLDER = '\x00PARAM\x00';
9
+ const WILDCARD_PLACEHOLDER = '\x00WILD\x00';
10
+
11
+ /**
12
+ * Compile a path pattern into a regular expression.
13
+ *
14
+ * Supported syntax: named parameters (`/users/:id`) and wildcards (`/files/*`,
15
+ * captured as `wild`). All other characters match literally.
16
+ *
17
+ * @param {string|RegExp|Array<string|RegExp>} path - Path pattern
18
+ * @param {Object} [options={}] - Matching options
19
+ * @param {boolean} [options.sensitive=false] - Case-sensitive matching
20
+ * @param {boolean} [options.strict=false] - Trailing slash is significant
21
+ * @param {boolean} [options.end=true] - Match the whole path (routes) or a
22
+ * prefix ending at a segment boundary (middleware)
23
+ * @returns {{regexp: RegExp, keys: Array<{name: string, optional: boolean}>}}
24
+ */
25
+ function pathToRegExp(path, options = {}) {
26
+ const { sensitive = false, strict = false, end = true } = options;
27
+ const flags = sensitive ? '' : 'i';
28
+
29
+ if (path instanceof RegExp) {
30
+ return { regexp: path, keys: [] };
31
+ }
32
+
33
+ if (Array.isArray(path)) {
34
+ const compiled = path.map(p => pathToRegExp(p, options));
35
+ return {
36
+ regexp: new RegExp(`(?:${compiled.map(r => r.regexp.source).join('|')})`, flags),
37
+ keys: compiled.reduce((keys, r) => keys.concat(r.keys), [])
38
+ };
39
+ }
40
+
41
+ const keys = [];
42
+ let pattern = String(path).replace(/\\\//g, '/');
43
+
44
+ // A trailing slash is optional unless the router is strict; middleware
45
+ // prefixes always ignore it ('/api/' mounts like '/api').
46
+ if ((!strict || !end) && pattern.length > 1 && pattern.endsWith('/')) {
47
+ pattern = pattern.slice(0, -1);
48
+ }
49
+ if (!end && pattern === '/') {
50
+ pattern = '';
51
+ }
52
+
53
+ // Protect parameters and wildcards, escape everything else, then restore.
54
+ pattern = pattern.replace(/:([^(/\\]+)/g, `${PARAM_PLACEHOLDER}$1`);
55
+ pattern = pattern.replace(/\*([^(/\\]*)/g, `${WILDCARD_PLACEHOLDER}$1`);
56
+ pattern = pattern.replace(/([.+?^${}()|[\]\\])/g, '\\$1');
57
+ pattern = pattern.replace(new RegExp(`${PARAM_PLACEHOLDER.replace(/\x00/g, '\\x00')}([^(/\\\\]+)`, 'g'), (match, key) => {
58
+ keys.push({ name: key, optional: false });
59
+ return '([^/]+)';
60
+ });
61
+ pattern = pattern.replace(new RegExp(`${WILDCARD_PLACEHOLDER.replace(/\x00/g, '\\x00')}([^(/\\\\]*)`, 'g'), (match, key) => {
62
+ keys.push({ name: key || 'wild', optional: false });
63
+ return '(.*)';
64
+ });
65
+
66
+ if (end) {
67
+ pattern += strict ? '$' : '/?$';
68
+ } else {
69
+ // Prefix match must end at a segment boundary: '/api' matches '/api/x',
70
+ // never '/apiary'.
71
+ pattern += '(?=/|$)';
72
+ }
73
+
74
+ return {
75
+ regexp: new RegExp(`^${pattern}`, flags),
76
+ keys
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Decode a captured path parameter.
82
+ *
83
+ * @param {string} value - Raw (percent-encoded) value
84
+ * @returns {string} Decoded value
85
+ * @throws {Error} 400 error when the value is not valid percent-encoding
86
+ * @private
87
+ */
88
+ function decodeParam(value) {
89
+ if (typeof value !== 'string' || value.length === 0) {
90
+ return value;
91
+ }
92
+ try {
93
+ return decodeURIComponent(value);
94
+ } catch (error) {
95
+ const err = new Error(`Failed to decode param '${value}'`);
96
+ err.status = 400;
97
+ err.code = 'INVALID_URL_ENCODING';
98
+ throw err;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Match a path against a compiled pattern.
104
+ *
105
+ * @param {string} path - Request path
106
+ * @param {RegExp} regexp - Compiled pattern
107
+ * @param {Array<{name: string}>} keys - Parameter keys
108
+ * @returns {false|{path: string, params: Object}} Match result
109
+ */
110
+ function matchPath(path, regexp, keys) {
111
+ const match = regexp.exec(path);
112
+ if (!match) {
113
+ return false;
114
+ }
115
+
116
+ const params = {};
117
+ for (let i = 1; i < match.length && i - 1 < keys.length; i++) {
118
+ const key = keys[i - 1];
119
+ const value = match[i];
120
+ if (key && key.name && value !== undefined) {
121
+ params[key.name] = decodeParam(value);
122
+ }
123
+ }
124
+
125
+ return { path: match[0], params };
126
+ }
127
+
128
+ class Layer {
129
+ /**
130
+ * @param {string|RegExp} path - Path pattern
131
+ * @param {Object} options - Matching options (see pathToRegExp)
132
+ * @param {Function} handler - Middleware or route dispatcher
133
+ * @param {Router} [router=null] - Owning router
134
+ */
135
+ constructor(path, options, handler, router = null) {
136
+ this.path = path;
137
+ this.handler = handler;
138
+ this.name = handler.name || '<anonymous>';
139
+ this.options = options;
140
+ this.route = null;
141
+ this.method = null;
142
+ this.router = router;
143
+ this.regexp = pathToRegExp(path, options);
144
+ this.keys = this.regexp.keys;
145
+ }
146
+
147
+ /**
148
+ * Compile a pattern (kept for backwards compatibility).
149
+ *
150
+ * @param {string|RegExp} path - Path pattern
151
+ * @param {Object} [options={}] - Matching options
152
+ * @returns {{regexp: RegExp, keys: Array}} Compiled pattern
153
+ */
154
+ createDefaultRegex(path, options = {}) {
155
+ return pathToRegExp(path, options);
156
+ }
157
+
158
+ /**
159
+ * Match a request path.
160
+ *
161
+ * @param {string} path - Request path
162
+ * @returns {false|{path: string, params: Object}} Match result
163
+ * @throws {Error} 400 error for malformed percent-encoding in a parameter
164
+ */
165
+ match(path) {
166
+ return matchPath(path, this.regexp.regexp, this.keys);
167
+ }
168
+
169
+ /**
170
+ * Run the layer's handler.
171
+ *
172
+ * @param {Context} ctx - Request context
173
+ * @param {Function} next - Continue with the next layer
174
+ * @returns {Promise<void>}
175
+ */
176
+ async handle(ctx, next) {
177
+ await this.handler(ctx, next);
178
+ }
179
+
180
+ /**
181
+ * Whether this layer handles the HTTP method.
182
+ *
183
+ * @param {string} method - HTTP method
184
+ * @returns {boolean}
185
+ */
186
+ handles_method(method) {
187
+ if (this.method) {
188
+ return this.method === method;
189
+ }
190
+ if (this.route) {
191
+ return this.route.handles_method(method);
192
+ }
193
+ return true;
194
+ }
195
+ }
196
+
197
+ module.exports = Layer;
198
+ module.exports.pathToRegExp = pathToRegExp;
199
+ module.exports.matchPath = matchPath;
@@ -1,125 +1,151 @@
1
1
  'use strict';
2
2
 
3
- class Route {
4
- constructor(path) {
5
- this.path = path;
6
- this.stack = [];
7
- this.methods = {};
8
- }
9
-
10
- get(...handlers) {
11
- handlers.forEach(handler => this.add('GET', handler));
12
- return this;
13
- }
14
-
15
- post(...handlers) {
16
- handlers.forEach(handler => this.add('POST', handler));
17
- return this;
18
- }
19
-
20
- put(...handlers) {
21
- handlers.forEach(handler => this.add('PUT', handler));
22
- return this;
23
- }
24
-
25
- delete(...handlers) {
26
- handlers.forEach(handler => this.add('DELETE', handler));
27
- return this;
28
- }
29
-
30
- patch(...handlers) {
31
- handlers.forEach(handler => this.add('PATCH', handler));
32
- return this;
33
- }
34
-
35
- head(...handlers) {
36
- handlers.forEach(handler => this.add('HEAD', handler));
37
- return this;
38
- }
39
-
40
- options(...handlers) {
41
- handlers.forEach(handler => this.add('OPTIONS', handler));
42
- return this;
43
- }
44
-
45
- all(...handlers) {
46
- const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
47
- handlers.forEach(handler => {
48
- methods.forEach(method => {
49
- this.add(method, handler);
50
- });
51
- });
52
- return this;
53
- }
54
-
55
- add(method, handler) {
56
- if (typeof handler !== 'function') {
57
- throw new Error('Handler must be a function');
58
- }
59
-
60
- if (!this.methods[method]) {
61
- this.methods[method] = true;
62
- }
63
-
64
- const layer = {
65
- method,
66
- handler,
67
- name: handler.name || '<anonymous>'
68
- };
69
-
70
- this.stack.push(layer);
71
- return this;
72
- }
73
-
74
- handles_method(method) {
75
- if (this.methods._all) {
76
- return true;
77
- }
78
-
79
- // Method'lar büyük harfle kaydediliyor, bu yüzden büyük harfe çevir
80
- const name = method.toUpperCase();
81
-
82
- if (name === 'HEAD' && !this.methods.HEAD) {
83
- return this.methods.GET;
84
- }
85
-
86
- return Boolean(this.methods[name]);
87
- }
88
-
89
- async dispatch(ctx, done) {
90
- let layerIndex = 0;
91
-
92
- const next = async (error) => {
93
- if (error) {
94
- return done(error);
95
- }
96
-
97
- if (layerIndex >= this.stack.length) {
98
- return done();
99
- }
100
-
101
- const layer = this.stack[layerIndex++];
102
-
103
- if (layer.method && layer.method !== ctx.method) {
104
- return next();
105
- }
106
-
107
- try {
108
- const result = layer.handler(ctx, next);
109
- if (result && typeof result.then === 'function') {
110
- await result;
111
- }
112
- } catch (err) {
113
- return next(err);
114
- }
115
- };
116
-
117
- await next();
118
- }
119
-
120
- toString() {
121
- return this.path;
122
- }
123
- }
124
-
125
- module.exports = Route;
3
+ /**
4
+ * @fileoverview Route: the handlers registered for one path, per HTTP method
5
+ * @since 1.0.0
6
+ */
7
+
8
+ class Route {
9
+ /**
10
+ * @param {string} path - Route path pattern
11
+ */
12
+ constructor(path) {
13
+ this.path = path;
14
+ this.stack = [];
15
+ this.methods = {};
16
+ }
17
+
18
+ get(...handlers) {
19
+ handlers.forEach(handler => this.add('GET', handler));
20
+ return this;
21
+ }
22
+
23
+ post(...handlers) {
24
+ handlers.forEach(handler => this.add('POST', handler));
25
+ return this;
26
+ }
27
+
28
+ put(...handlers) {
29
+ handlers.forEach(handler => this.add('PUT', handler));
30
+ return this;
31
+ }
32
+
33
+ delete(...handlers) {
34
+ handlers.forEach(handler => this.add('DELETE', handler));
35
+ return this;
36
+ }
37
+
38
+ patch(...handlers) {
39
+ handlers.forEach(handler => this.add('PATCH', handler));
40
+ return this;
41
+ }
42
+
43
+ head(...handlers) {
44
+ handlers.forEach(handler => this.add('HEAD', handler));
45
+ return this;
46
+ }
47
+
48
+ options(...handlers) {
49
+ handlers.forEach(handler => this.add('OPTIONS', handler));
50
+ return this;
51
+ }
52
+
53
+ /**
54
+ * Register handlers for every HTTP method.
55
+ *
56
+ * @param {...Function} handlers - Route handlers
57
+ * @returns {Route}
58
+ */
59
+ all(...handlers) {
60
+ handlers.forEach(handler => this.add(null, handler));
61
+ return this;
62
+ }
63
+
64
+ /**
65
+ * Register a handler.
66
+ *
67
+ * @param {string|null} method - Upper-case HTTP method, or null for all methods
68
+ * @param {Function} handler - Route handler
69
+ * @returns {Route}
70
+ */
71
+ add(method, handler) {
72
+ if (typeof handler !== 'function') {
73
+ throw new Error('Handler must be a function');
74
+ }
75
+
76
+ if (method === null) {
77
+ this.methods._all = true;
78
+ } else {
79
+ this.methods[method] = true;
80
+ }
81
+
82
+ this.stack.push({
83
+ method,
84
+ handler,
85
+ name: handler.name || '<anonymous>'
86
+ });
87
+ return this;
88
+ }
89
+
90
+ /**
91
+ * Whether the route has handlers for the method. HEAD falls back to GET.
92
+ *
93
+ * @param {string} method - HTTP method
94
+ * @returns {boolean}
95
+ */
96
+ handles_method(method) {
97
+ if (this.methods._all) {
98
+ return true;
99
+ }
100
+ const name = method.toUpperCase();
101
+ if (name === 'HEAD' && !this.methods.HEAD) {
102
+ return Boolean(this.methods.GET);
103
+ }
104
+ return Boolean(this.methods[name]);
105
+ }
106
+
107
+ /**
108
+ * Run the handlers registered for the request method.
109
+ *
110
+ * @param {Context} ctx - Request context
111
+ * @param {Function} done - Called with an error, or to continue past this route
112
+ * @returns {Promise<void>}
113
+ */
114
+ async dispatch(ctx, done) {
115
+ const requestMethod = ctx.method.toUpperCase();
116
+ // HEAD is answered by GET handlers unless HEAD handlers exist; Node omits
117
+ // the body of HEAD responses.
118
+ const method = requestMethod === 'HEAD' && !this.methods.HEAD ? 'GET' : requestMethod;
119
+ let index = 0;
120
+
121
+ const next = async (error) => {
122
+ if (error) {
123
+ return done(error);
124
+ }
125
+
126
+ while (index < this.stack.length) {
127
+ const layer = this.stack[index++];
128
+ if (layer.method !== null && layer.method !== method) {
129
+ continue;
130
+ }
131
+
132
+ try {
133
+ await layer.handler(ctx, next);
134
+ } catch (err) {
135
+ return done(err);
136
+ }
137
+ return undefined;
138
+ }
139
+
140
+ return done();
141
+ };
142
+
143
+ await next();
144
+ }
145
+
146
+ toString() {
147
+ return this.path;
148
+ }
149
+ }
150
+
151
+ module.exports = Route;