@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,833 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * @fileoverview Context class for handling HTTP requests and responses in Spark Framework
5
- * @author Spark Framework Team
6
- * @since 1.0.0
7
- * @version 1.0.0
8
- */
9
-
10
- const { URL } = require('url');
11
- const querystring = require('querystring');
12
-
13
- /**
14
- * Context class that wraps HTTP request and response objects
15
- *
16
- * The Context class provides a unified interface for handling HTTP requests and responses.
17
- * It parses incoming request data, provides helper methods for setting headers and status codes,
18
- * and includes convenience methods for sending various types of responses.
19
- *
20
- * @class Context
21
- * @since 1.0.0
22
- *
23
- * @example
24
- * // In a middleware or route handler
25
- * app.get('/users/:id', (ctx) => {
26
- * const userId = ctx.params.id;
27
- * const userAgent = ctx.get('user-agent');
28
- *
29
- * ctx.set('X-Response-Time', '10ms');
30
- * ctx.json({ id: userId, userAgent });
31
- * });
32
- *
33
- * @example
34
- * // Working with cookies
35
- * app.post('/login', (ctx) => {
36
- * const { username, password } = ctx.body;
37
- *
38
- * if (authenticate(username, password)) {
39
- * ctx.setCookie('session', 'abc123', {
40
- * httpOnly: true,
41
- * secure: true,
42
- * maxAge: 3600000
43
- * });
44
- * ctx.json({ success: true });
45
- * } else {
46
- * ctx.status(401).json({ error: 'Invalid credentials' });
47
- * }
48
- * });
49
- */
50
- class Context {
51
- /**
52
- * Create a new Context instance
53
- *
54
- * @param {http.IncomingMessage} req - The HTTP request object
55
- * @param {http.ServerResponse} res - The HTTP response object
56
- * @param {Application} app - The Spark application instance
57
- *
58
- * @since 1.0.0
59
- *
60
- * @example
61
- * // Context is typically created automatically by the framework
62
- * const ctx = new Context(req, res, app);
63
- */
64
- constructor(req, res, app) {
65
- /**
66
- * The HTTP request object
67
- * @type {http.IncomingMessage}
68
- * @readonly
69
- */
70
- this.req = req;
71
-
72
- /**
73
- * The HTTP response object
74
- * @type {http.ServerResponse}
75
- * @readonly
76
- */
77
- this.res = res;
78
-
79
- /**
80
- * The Spark application instance
81
- * @type {Application}
82
- * @readonly
83
- */
84
- this.app = app;
85
-
86
- /**
87
- * Whether a response has been sent
88
- * @type {boolean}
89
- * @readonly
90
- */
91
- this.responded = false;
92
-
93
- /**
94
- * The HTTP status code for the response
95
- * @type {number}
96
- */
97
- this.statusCode = 200;
98
-
99
- this.initializeUrl();
100
- this.initializeHeaders();
101
- this.initializeQuery();
102
- this.initializeCookies();
103
-
104
- /**
105
- * Route parameters extracted from the URL
106
- * @type {Object}
107
- * @example
108
- * // For route '/users/:id' with URL '/users/123'
109
- * ctx.params.id // '123'
110
- */
111
- this.params = {};
112
-
113
- /**
114
- * Parsed request body
115
- * @type {*}
116
- */
117
- this.body = null;
118
-
119
- /**
120
- * Uploaded files (when using multipart/form-data)
121
- * @type {Object|null}
122
- */
123
- this.files = null;
124
-
125
- /**
126
- * Session data (when session middleware is used)
127
- * @type {Object|null}
128
- */
129
- this.session = null;
130
-
131
- /**
132
- * Application state for storing custom data
133
- * @type {Object}
134
- */
135
- this.state = {};
136
- }
137
-
138
- /**
139
- * Initialize URL-related properties from the request
140
- *
141
- * Parses the request URL and extracts path, method, and other URL components.
142
- * Handles malformed URLs by throwing an appropriate error.
143
- *
144
- * @private
145
- * @throws {Error} When the URL cannot be parsed
146
- * @since 1.0.0
147
- */
148
- initializeUrl() {
149
- const protocol = this.req.connection.encrypted ? 'https' : 'http';
150
- const host = this.req.headers.host || 'localhost';
151
-
152
- try {
153
- /**
154
- * Parsed URL object
155
- * @type {URL|null}
156
- * @readonly
157
- */
158
- this.url = new URL(this.req.url, `${protocol}://${host}`);
159
-
160
- /**
161
- * Request path (pathname without query string)
162
- * @type {string}
163
- * @readonly
164
- */
165
- this.path = this.url.pathname;
166
- } catch (error) {
167
- // Handle malformed URLs - throw proper error instead of just logging
168
- this.url = null;
169
- this.path = '/';
170
- this.statusCode = 400;
171
- this.body = { error: 'Invalid URL format' };
172
- throw new Error(`Failed to parse URL: ${error.message}`);
173
- }
174
-
175
- /**
176
- * HTTP method (GET, POST, PUT, etc.)
177
- * @type {string}
178
- * @readonly
179
- */
180
- this.method = this.req.method ? this.req.method.toUpperCase() : 'GET';
181
-
182
- /**
183
- * Original request URL including query string
184
- * @type {string}
185
- * @readonly
186
- */
187
- this.originalUrl = this.req.url;
188
- }
189
-
190
- /**
191
- * Initialize request and response headers
192
- *
193
- * Copies request headers and initializes response headers object.
194
- *
195
- * @private
196
- * @since 1.0.0
197
- */
198
- initializeHeaders() {
199
- /**
200
- * Request headers (lowercase keys)
201
- * @type {Object}
202
- * @readonly
203
- */
204
- this.headers = { ...this.req.headers };
205
-
206
- /**
207
- * Response headers to be sent
208
- * @type {Object}
209
- * @private
210
- */
211
- this.responseHeaders = {};
212
- }
213
-
214
- /**
215
- * Initialize query string parameters
216
- *
217
- * Parses the URL query string into an object.
218
- *
219
- * @private
220
- * @since 1.0.0
221
- */
222
- initializeQuery() {
223
- /**
224
- * Parsed query string parameters
225
- * @type {Object}
226
- * @readonly
227
- * @example
228
- * // For URL '/search?q=hello&limit=10'
229
- * ctx.query.q // 'hello'
230
- * ctx.query.limit // '10'
231
- */
232
- this.query = {};
233
- if (this.url.search) {
234
- this.query = querystring.parse(this.url.search.slice(1));
235
- }
236
- }
237
-
238
- /**
239
- * Initialize cookies from the request
240
- *
241
- * Parses the Cookie header and decodes cookie values.
242
- * Malformed cookies are skipped and logged.
243
- *
244
- * @private
245
- * @since 1.0.0
246
- */
247
- initializeCookies() {
248
- /**
249
- * Parsed cookies from the request
250
- * @type {Object}
251
- * @readonly
252
- * @example
253
- * // For Cookie header 'session=abc123; theme=dark'
254
- * ctx.cookies.session // 'abc123'
255
- * ctx.cookies.theme // 'dark'
256
- */
257
- this.cookies = {};
258
- const cookieHeader = this.req.headers.cookie;
259
- if (cookieHeader) {
260
- cookieHeader.split(';').forEach(cookie => {
261
- const [name, value] = cookie.trim().split('=');
262
- if (name && value) {
263
- try {
264
- this.cookies[name] = decodeURIComponent(value);
265
- } catch (error) {
266
- // Skip malformed cookie values
267
- console.error(`Failed to decode cookie ${name}: ${error.message}`);
268
- }
269
- }
270
- });
271
- }
272
- }
273
-
274
- /**
275
- * Get a request header value
276
- *
277
- * @param {string} headerName - The header name (case-insensitive)
278
- * @returns {string|undefined} The header value or undefined if not present
279
- *
280
- * @since 1.0.0
281
- *
282
- * @example
283
- * const userAgent = ctx.get('User-Agent');
284
- * const contentType = ctx.get('content-type');
285
- */
286
- get(headerName) {
287
- return this.headers[headerName.toLowerCase()];
288
- }
289
-
290
- /**
291
- * Set a response header
292
- *
293
- * Sets a response header with validation for security and RFC compliance.
294
- * Header names and values are validated to prevent injection attacks.
295
- *
296
- * @param {string} headerName - The header name
297
- * @param {string|number} value - The header value
298
- * @returns {Context} The context instance for method chaining
299
- *
300
- * @throws {Error} When header name or value is invalid
301
- *
302
- * @since 1.0.0
303
- *
304
- * @example
305
- * ctx.set('Content-Type', 'application/json');
306
- * ctx.set('X-Response-Time', '10ms');
307
- *
308
- * @example
309
- * // Method chaining
310
- * ctx.set('Content-Type', 'text/html')
311
- * .set('Cache-Control', 'no-cache');
312
- */
313
- set(headerName, value) {
314
- // Validate header name
315
- if (!headerName || typeof headerName !== 'string') {
316
- throw new Error('Header name must be a non-empty string');
317
- }
318
-
319
- // Validate header name format (RFC 7230)
320
- if (!/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(headerName)) {
321
- throw new Error(`Invalid header name: ${headerName}`);
322
- }
323
-
324
- // Validate header value
325
- if (value !== undefined && value !== null) {
326
- const stringValue = String(value);
327
- // Check for invalid characters in header value (CRLF and null byte)
328
- if (/[\r\n\x00]/.test(stringValue)) {
329
- throw new Error('Header value cannot contain CRLF or null characters');
330
- }
331
- // Check header value length
332
- if (stringValue.length > 8192) {
333
- throw new Error('Header value too long (max 8192 characters)');
334
- }
335
- this.responseHeaders[headerName.toLowerCase()] = stringValue;
336
- }
337
-
338
- return this;
339
- }
340
-
341
- /**
342
- * Alias for set() method
343
- *
344
- * @param {string} name - The header name
345
- * @param {string|number} value - The header value
346
- * @returns {Context} The context instance for method chaining
347
- *
348
- * @since 1.0.0
349
- * @see {@link Context#set}
350
- */
351
- setHeader(name, value) {
352
- return this.set(name, value);
353
- }
354
-
355
- /**
356
- * Get a response header value
357
- *
358
- * @param {string} name - The header name (case-insensitive)
359
- * @returns {string|undefined} The header value or undefined if not set
360
- *
361
- * @since 1.0.0
362
- *
363
- * @example
364
- * ctx.set('Content-Type', 'application/json');
365
- * const contentType = ctx.getHeader('content-type'); // 'application/json'
366
- */
367
- getHeader(name) {
368
- return this.responseHeaders[name.toLowerCase()];
369
- }
370
-
371
- /**
372
- * Remove a response header
373
- *
374
- * @param {string} name - The header name (case-insensitive)
375
- * @returns {Context} The context instance for method chaining
376
- *
377
- * @since 1.0.0
378
- *
379
- * @example
380
- * ctx.removeHeader('X-Powered-By');
381
- */
382
- removeHeader(name) {
383
- delete this.responseHeaders[name.toLowerCase()];
384
- return this;
385
- }
386
-
387
- /**
388
- * Set the HTTP status code
389
- *
390
- * @param {number|string} code - HTTP status code (100-599)
391
- * @returns {Context} The context instance for method chaining
392
- *
393
- * @throws {Error} When status code is invalid
394
- *
395
- * @since 1.0.0
396
- *
397
- * @example
398
- * ctx.status(200); // OK
399
- * ctx.status(404); // Not Found
400
- * ctx.status(500); // Internal Server Error
401
- *
402
- * @example
403
- * // Method chaining
404
- * ctx.status(201).json({ id: 123, name: 'User' });
405
- */
406
- status(code) {
407
- // Validate status code
408
- const statusCode = parseInt(code);
409
- if (isNaN(statusCode) || statusCode < 100 || statusCode > 599) {
410
- throw new Error(`Invalid status code: ${code}. Must be between 100 and 599`);
411
- }
412
- this.statusCode = statusCode;
413
- return this;
414
- }
415
-
416
- /**
417
- * Redirect to a URL
418
- *
419
- * Sets the Location header and status code, then ends the response.
420
- *
421
- * @param {string} url - The URL to redirect to
422
- * @param {number} [status=302] - HTTP status code for redirect
423
- * @returns {Context} The context instance for method chaining
424
- *
425
- * @since 1.0.0
426
- *
427
- * @example
428
- * // Temporary redirect (302)
429
- * ctx.redirect('/login');
430
- *
431
- * @example
432
- * // Permanent redirect (301)
433
- * ctx.redirect('/new-path', 301);
434
- */
435
- redirect(url, status = 302) {
436
- this.status(status);
437
- this.set('Location', url);
438
- this.end();
439
- return this;
440
- }
441
-
442
- /**
443
- * Send a JSON response
444
- *
445
- * Sets the Content-Type header to application/json and sends the data as JSON.
446
- *
447
- * @param {*} data - The data to send as JSON
448
- * @returns {Context} The context instance for method chaining
449
- *
450
- * @since 1.0.0
451
- *
452
- * @example
453
- * ctx.json({ message: 'Hello World' });
454
- *
455
- * @example
456
- * // With status code
457
- * ctx.status(201).json({ id: 123, name: 'User' });
458
- */
459
- json(data) {
460
- this.set('Content-Type', 'application/json');
461
- this.send(JSON.stringify(data));
462
- return this;
463
- }
464
-
465
- /**
466
- * Send a plain text response
467
- *
468
- * Sets the Content-Type header to text/plain and sends the data as text.
469
- *
470
- * @param {string} data - The text data to send
471
- * @returns {Context} The context instance for method chaining
472
- *
473
- * @since 1.0.0
474
- *
475
- * @example
476
- * ctx.text('Hello World');
477
- *
478
- * @example
479
- * // With status code
480
- * ctx.status(200).text('Success');
481
- */
482
- text(data) {
483
- this.set('Content-Type', 'text/plain');
484
- this.send(data);
485
- return this;
486
- }
487
-
488
- /**
489
- * Send an HTML response
490
- *
491
- * Sets the Content-Type header to text/html and sends the data as HTML.
492
- *
493
- * @param {string} data - The HTML data to send
494
- * @returns {Context} The context instance for method chaining
495
- *
496
- * @since 1.0.0
497
- *
498
- * @example
499
- * ctx.html('<h1>Hello World</h1>');
500
- *
501
- * @example
502
- * // With status code
503
- * ctx.status(200).html('<p>Welcome!</p>');
504
- */
505
- html(data) {
506
- this.set('Content-Type', 'text/html');
507
- this.send(data);
508
- return this;
509
- }
510
-
511
- /**
512
- * Send a response with data
513
- *
514
- * Sends the response with the specified data. This method is called by other
515
- * response methods like json(), text(), and html(). Once called, no further
516
- * response methods can be used.
517
- *
518
- * @param {*} data - The data to send
519
- * @returns {Context} The context instance for method chaining
520
- *
521
- * @since 1.0.0
522
- *
523
- * @example
524
- * ctx.send('Hello World');
525
- * ctx.send(Buffer.from('binary data'));
526
- */
527
- send(data) {
528
- if (this.responded) {
529
- return this;
530
- }
531
-
532
- this.responded = true;
533
- this.res.statusCode = this.statusCode;
534
-
535
- Object.keys(this.responseHeaders).forEach(name => {
536
- this.res.setHeader(name, this.responseHeaders[name]);
537
- });
538
-
539
- if (data === null || data === undefined) {
540
- this.res.end();
541
- } else if (typeof data === 'string' || Buffer.isBuffer(data)) {
542
- this.res.end(data);
543
- } else {
544
- this.res.end(String(data));
545
- }
546
-
547
- return this;
548
- }
549
-
550
- /**
551
- * End the response
552
- *
553
- * Ends the response optionally with data. This is an alias for send().
554
- *
555
- * @param {*} [data] - Optional data to send before ending
556
- * @returns {Context} The context instance for method chaining
557
- *
558
- * @since 1.0.0
559
- *
560
- * @example
561
- * ctx.status(204).end(); // No content
562
- * ctx.end('Final message');
563
- */
564
- end(data) {
565
- if (data) {
566
- this.send(data);
567
- } else {
568
- this.send();
569
- }
570
- return this;
571
- }
572
-
573
- setCookie(name, value, options = {}) {
574
- // Validate cookie name
575
- if (!name || typeof name !== 'string') {
576
- throw new Error('Cookie name must be a non-empty string');
577
- }
578
-
579
- // Validate cookie name format (RFC 6265)
580
- if (!/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(name)) {
581
- throw new Error(`Invalid cookie name: ${name}`);
582
- }
583
-
584
- // Check for control characters in cookie name
585
- if (/[\x00-\x1F\x7F]/.test(name)) {
586
- throw new Error('Cookie name cannot contain control characters');
587
- }
588
-
589
- // Validate cookie value
590
- if (value === null || value === undefined) {
591
- value = '';
592
- }
593
-
594
- // Convert value to string and check for invalid characters
595
- const stringValue = String(value);
596
- if (/[\x00-\x1F\x7F]/.test(stringValue)) {
597
- throw new Error('Cookie value cannot contain control characters');
598
- }
599
-
600
- let cookieString = `${name}=${encodeURIComponent(value)}`;
601
-
602
- if (options.domain) {
603
- cookieString += `; Domain=${options.domain}`;
604
- }
605
-
606
- if (options.path) {
607
- cookieString += `; Path=${options.path}`;
608
- }
609
-
610
- if (options.expires) {
611
- cookieString += `; Expires=${options.expires.toUTCString()}`;
612
- }
613
-
614
- if (options.maxAge) {
615
- cookieString += `; Max-Age=${options.maxAge}`;
616
- }
617
-
618
- if (options.httpOnly) {
619
- cookieString += '; HttpOnly';
620
- }
621
-
622
- if (options.secure) {
623
- cookieString += '; Secure';
624
- }
625
-
626
- if (options.sameSite) {
627
- const validSameSite = ['Strict', 'Lax', 'None'];
628
- const sameSiteValue = options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1).toLowerCase();
629
- if (!validSameSite.includes(sameSiteValue)) {
630
- throw new Error(`Invalid SameSite value: ${options.sameSite}. Must be 'Strict', 'Lax', or 'None'`);
631
- }
632
- cookieString += `; SameSite=${sameSiteValue}`;
633
- }
634
-
635
- const existingCookies = this.responseHeaders['set-cookie'] || [];
636
- if (Array.isArray(existingCookies)) {
637
- existingCookies.push(cookieString);
638
- this.responseHeaders['set-cookie'] = existingCookies;
639
- } else if (existingCookies) {
640
- this.responseHeaders['set-cookie'] = [existingCookies, cookieString];
641
- } else {
642
- this.responseHeaders['set-cookie'] = [cookieString];
643
- }
644
-
645
- return this;
646
- }
647
-
648
- clearCookie(name, options = {}) {
649
- const clearOptions = {
650
- ...options,
651
- expires: new Date(0),
652
- maxAge: 0
653
- };
654
- return this.setCookie(name, '', clearOptions);
655
- }
656
-
657
- is(type) {
658
- const contentType = this.get('content-type');
659
- if (!contentType) return false;
660
-
661
- const mimeTypes = {
662
- json: 'application/json',
663
- form: 'application/x-www-form-urlencoded',
664
- multipart: 'multipart/form-data',
665
- text: 'text/plain',
666
- html: 'text/html'
667
- };
668
-
669
- const targetType = mimeTypes[type] || type;
670
- return contentType.includes(targetType);
671
- }
672
-
673
- accepts(types) {
674
- const accept = this.get('accept') || '*/*';
675
-
676
- if (typeof types === 'string') {
677
- types = [types];
678
- }
679
-
680
- for (const type of types) {
681
- if (accept.includes(type) || accept.includes('*/*')) {
682
- return type;
683
- }
684
- }
685
-
686
- return false;
687
- }
688
-
689
- fresh() {
690
- const method = this.method;
691
- const status = this.statusCode;
692
-
693
- if (method !== 'GET' && method !== 'HEAD') return false;
694
- if ((status >= 200 && status < 300) || status === 304) return true;
695
-
696
- return false;
697
- }
698
-
699
- stale() {
700
- return !this.fresh();
701
- }
702
-
703
- secure() {
704
- return this.req.connection.encrypted;
705
- }
706
-
707
- xhr() {
708
- return this.get('x-requested-with') === 'XMLHttpRequest';
709
- }
710
-
711
- ip() {
712
- return this.get('x-forwarded-for') ||
713
- this.get('x-real-ip') ||
714
- this.req.connection.remoteAddress ||
715
- this.req.socket.remoteAddress;
716
- }
717
-
718
- ips() {
719
- const forwarded = this.get('x-forwarded-for');
720
- return forwarded ? forwarded.split(/\s*,\s*/) : [this.ip()];
721
- }
722
-
723
- protocol() {
724
- return this.req.connection.encrypted ? 'https' : 'http';
725
- }
726
-
727
- host() {
728
- return this.get('host') || 'localhost';
729
- }
730
-
731
- hostname() {
732
- return this.host().split(':')[0];
733
- }
734
-
735
- port() {
736
- const host = this.host();
737
- const portMatch = host.match(/:(\d+)$/);
738
- return portMatch ? parseInt(portMatch[1]) : (this.secure() ? 443 : 80);
739
- }
740
-
741
- subdomains() {
742
- const hostname = this.hostname();
743
- const parts = hostname.split('.');
744
- return parts.length > 2 ? parts.slice(0, -2).reverse() : [];
745
- }
746
-
747
- type() {
748
- const contentType = this.get('content-type');
749
- return contentType ? contentType.split(';')[0] : '';
750
- }
751
-
752
- charset() {
753
- const contentType = this.get('content-type');
754
- if (!contentType) return '';
755
-
756
- const match = contentType.match(/charset=([^;]+)/);
757
- return match ? match[1] : '';
758
- }
759
-
760
- length() {
761
- const contentLength = this.get('content-length');
762
- return contentLength ? parseInt(contentLength) : 0;
763
- }
764
-
765
- toString() {
766
- return `${this.method} ${this.originalUrl}`;
767
- }
768
-
769
- toJSON() {
770
- return {
771
- method: this.method,
772
- url: this.originalUrl,
773
- path: this.path,
774
- query: this.query,
775
- params: this.params,
776
- headers: this.headers,
777
- cookies: this.cookies,
778
- statusCode: this.statusCode,
779
- responded: this.responded
780
- };
781
- }
782
-
783
- /**
784
- * Initialize context with new request/response (for object pooling)
785
- * @param {IncomingMessage} req - HTTP request
786
- * @param {ServerResponse} res - HTTP response
787
- * @param {Application} app - Spark application
788
- */
789
- init(req, res, app) {
790
- this.req = req;
791
- this.res = res;
792
- this.app = app;
793
- this.responded = false;
794
- this.statusCode = 200;
795
-
796
- this.initializeUrl();
797
- this.initializeHeaders();
798
- this.initializeQuery();
799
- this.initializeCookies();
800
-
801
- this.params = {};
802
- this.body = null;
803
- this.files = null;
804
- this.session = null;
805
- this.state = {};
806
- }
807
-
808
- /**
809
- * Reset context for object pooling
810
- */
811
- reset() {
812
- this.req = null;
813
- this.res = null;
814
- this.app = null;
815
- this.responded = false;
816
- this.statusCode = 200;
817
- this.url = null;
818
- this.path = null;
819
- this.method = null;
820
- this.originalUrl = null;
821
- this.headers = {};
822
- this.responseHeaders = {};
823
- this.query = {};
824
- this.cookies = {};
825
- this.params = {};
826
- this.body = null;
827
- this.files = null;
828
- this.session = null;
829
- this.state = {};
830
- }
831
- }
832
-
833
- module.exports = Context;