@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,117 +1,199 @@
1
- class Layer {
2
- constructor(path, options, handler, router = null) {
3
- this.path = path;
4
- this.handler = handler;
5
- this.name = handler.name || '<anonymous>';
6
- this.options = options;
7
- this.route = null;
8
- this.method = null;
9
- this.router = router;
10
-
11
- // Use router's pathToRegExp if available, otherwise create a default regex
12
- if (router && router.pathToRegExp) {
13
- this.regexp = router.pathToRegExp(path, options);
14
- } else {
15
- // Fallback to default regex creation without circular dependency
16
- this.regexp = this.createDefaultRegex(path, options);
17
- }
18
- this.keys = this.regexp.keys;
19
- }
20
-
21
- createDefaultRegex(path, options = {}) {
22
- const { sensitive = false, strict = false, end = true } = options;
23
-
24
- if (path instanceof RegExp) {
25
- return { regexp: path, keys: [] };
26
- }
27
-
28
- const keys = [];
29
- let regexp = path;
30
-
31
- // Escape forward slashes
32
- regexp = regexp.replace(/\\\//g, '/');
33
-
34
- // Replace parameters
35
- regexp = regexp.replace(/:([^(/\\]+)/g, (match, key) => {
36
- keys.push({ name: key, optional: false });
37
- return '([^/]+)';
38
- });
39
-
40
- // Replace wildcards
41
- regexp = regexp.replace(/\*([^(/\\]*)/g, (match, key) => {
42
- keys.push({ name: key || 'wild', optional: false });
43
- return '(.*)';
44
- });
45
-
46
- // Add end pattern
47
- if (end) {
48
- regexp += strict ? '' : '/?';
49
- }
50
-
51
- regexp += end ? '$' : '';
52
-
53
- const flags = sensitive ? '' : 'i';
54
- return {
55
- regexp: new RegExp(`^${regexp}`, flags),
56
- keys
57
- };
58
- }
59
-
60
- match(path) {
61
- const match = this.regexp.regexp.exec(path);
62
-
63
- if (!match) {
64
- return false;
65
- }
66
-
67
- const params = {};
68
-
69
- for (let i = 1; i < match.length; i++) {
70
- const key = this.keys[i - 1];
71
- const value = match[i];
72
-
73
- if (value !== undefined) {
74
- params[key.name] = decodeParam(value);
75
- }
76
- }
77
-
78
- return {
79
- path: match[0],
80
- params
81
- };
82
- }
83
-
84
- async handle(ctx, next) {
85
- if (this.handler.length > 2) {
86
- return this.handler(ctx, next);
87
- } else {
88
- await this.handler(ctx, next);
89
- }
90
- }
91
-
92
- handles_method(method) {
93
- if (this.method) {
94
- return this.method === method;
95
- }
96
-
97
- if (this.route) {
98
- return this.route.handles_method(method);
99
- }
100
-
101
- return true;
102
- }
103
- }
104
-
105
- function decodeParam(value) {
106
- if (typeof value !== 'string' || value.length === 0) {
107
- return value;
108
- }
109
-
110
- try {
111
- return decodeURIComponent(value);
112
- } catch (error) {
113
- throw new Error(`Failed to decode param '${value}'`);
114
- }
115
- }
116
-
117
- module.exports = Layer;
1
+ 'use strict';
2
+
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,123 +1,151 @@
1
- class Route {
2
- constructor(path) {
3
- this.path = path;
4
- this.stack = [];
5
- this.methods = {};
6
- }
7
-
8
- get(...handlers) {
9
- handlers.forEach(handler => this.add('GET', handler));
10
- return this;
11
- }
12
-
13
- post(...handlers) {
14
- handlers.forEach(handler => this.add('POST', handler));
15
- return this;
16
- }
17
-
18
- put(...handlers) {
19
- handlers.forEach(handler => this.add('PUT', handler));
20
- return this;
21
- }
22
-
23
- delete(...handlers) {
24
- handlers.forEach(handler => this.add('DELETE', handler));
25
- return this;
26
- }
27
-
28
- patch(...handlers) {
29
- handlers.forEach(handler => this.add('PATCH', handler));
30
- return this;
31
- }
32
-
33
- head(...handlers) {
34
- handlers.forEach(handler => this.add('HEAD', handler));
35
- return this;
36
- }
37
-
38
- options(...handlers) {
39
- handlers.forEach(handler => this.add('OPTIONS', handler));
40
- return this;
41
- }
42
-
43
- all(...handlers) {
44
- const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
45
- handlers.forEach(handler => {
46
- methods.forEach(method => {
47
- this.add(method, handler);
48
- });
49
- });
50
- return this;
51
- }
52
-
53
- add(method, handler) {
54
- if (typeof handler !== 'function') {
55
- throw new Error('Handler must be a function');
56
- }
57
-
58
- if (!this.methods[method]) {
59
- this.methods[method] = true;
60
- }
61
-
62
- const layer = {
63
- method,
64
- handler,
65
- name: handler.name || '<anonymous>'
66
- };
67
-
68
- this.stack.push(layer);
69
- return this;
70
- }
71
-
72
- handles_method(method) {
73
- if (this.methods._all) {
74
- return true;
75
- }
76
-
77
- // Method'lar büyük harfle kaydediliyor, bu yüzden büyük harfe çevir
78
- const name = method.toUpperCase();
79
-
80
- if (name === 'HEAD' && !this.methods.HEAD) {
81
- return this.methods.GET;
82
- }
83
-
84
- return Boolean(this.methods[name]);
85
- }
86
-
87
- async dispatch(ctx, done) {
88
- let layerIndex = 0;
89
-
90
- const next = async (error) => {
91
- if (error) {
92
- return done(error);
93
- }
94
-
95
- if (layerIndex >= this.stack.length) {
96
- return done();
97
- }
98
-
99
- const layer = this.stack[layerIndex++];
100
-
101
- if (layer.method && layer.method !== ctx.method) {
102
- return next();
103
- }
104
-
105
- try {
106
- const result = layer.handler(ctx, next);
107
- if (result && typeof result.then === 'function') {
108
- await result;
109
- }
110
- } catch (err) {
111
- return next(err);
112
- }
113
- };
114
-
115
- await next();
116
- }
117
-
118
- toString() {
119
- return this.path;
120
- }
121
- }
122
-
123
- module.exports = Route;
1
+ 'use strict';
2
+
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;