@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,301 +1,406 @@
1
1
  'use strict';
2
2
 
3
- const fs = require('fs');
4
- const path = require('path');
5
- const { promisify } = require('util');
6
- const crypto = require('crypto');
7
-
8
- const stat = promisify(fs.stat);
9
- const readFile = promisify(fs.readFile);
10
- const readdir = promisify(fs.readdir);
11
-
12
- const DEFAULT_MAX_AGE = 0;
13
- const DEFAULT_INDEX = ['index.html'];
14
-
15
- function staticFiles(root, options = {}) {
16
- const opts = {
17
- root: path.resolve(root),
18
- maxAge: options.maxAge || DEFAULT_MAX_AGE,
19
- index: options.index || DEFAULT_INDEX,
20
- hidden: options.hidden || false,
21
- dotfiles: options.dotfiles || 'ignore',
22
- etag: options.etag !== false,
23
- lastModified: options.lastModified !== false,
24
- extensions: options.extensions || [],
25
- fallthrough: options.fallthrough !== false,
26
- redirect: options.redirect !== false,
27
- setHeaders: options.setHeaders,
28
- ...options
29
- };
30
-
31
- const cache = new Map();
32
-
33
- return async (ctx, next) => {
34
- if (ctx.method !== 'GET' && ctx.method !== 'HEAD') {
35
- return next();
36
- }
37
-
38
- let pathname;
39
- try {
40
- pathname = decodeURIComponent(ctx.path);
41
- } catch (e) {
42
- return ctx.status(400).json({ error: 'Invalid URL encoding' });
43
- }
44
-
45
- // Normalize the path to prevent directory traversal
46
- const normalizedPath = path.normalize(pathname).replace(/^(\.\.(\/|\\|$))+/, '');
47
-
48
- // Ensure the path doesn't contain any traversal patterns
49
- if (pathname.includes('..') || pathname.includes('\0')) {
50
- if (opts.fallthrough) {
51
- return next();
52
- }
53
- return ctx.status(403).json({ error: 'Forbidden' });
54
- }
55
-
56
- const filePath = path.join(opts.root, normalizedPath);
57
-
58
- // Ensure the resolved path is within the root directory
59
- if (!filePath.startsWith(opts.root)) {
60
- if (opts.fallthrough) {
61
- return next();
62
- }
63
- return ctx.status(403).json({ error: 'Forbidden' });
64
- }
65
-
66
- try {
67
- const stats = await stat(filePath);
68
-
69
- if (stats.isDirectory()) {
70
- return await handleDirectory(ctx, filePath, opts, next);
71
- }
72
-
73
- if (stats.isFile()) {
74
- return await sendFile(ctx, filePath, stats, opts);
75
- }
76
-
77
- } catch (error) {
78
- if (error.code === 'ENOENT') {
79
- return await tryExtensions(ctx, filePath, opts, next);
80
- }
81
-
82
- if (opts.fallthrough) {
83
- return next();
84
- }
85
-
86
- return ctx.status(500).json({ error: 'Internal Server Error' });
87
- }
88
-
89
- if (opts.fallthrough) {
90
- return next();
91
- }
92
-
93
- ctx.status(404).json({ error: 'Not Found' });
94
- };
95
- }
96
-
97
- async function handleDirectory(ctx, dirPath, opts, next) {
98
- if (opts.redirect && !ctx.path.endsWith('/')) {
99
- // Using string concatenation for URL paths (not filesystem paths)
100
- const redirectPath = `${ctx.path}/`;
101
- return ctx.redirect(redirectPath);
102
- }
103
-
104
- for (const indexFile of opts.index) {
105
- const indexPath = path.join(dirPath, indexFile);
106
-
107
- try {
108
- const stats = await stat(indexPath);
109
- if (stats.isFile()) {
110
- return await sendFile(ctx, indexPath, stats, opts);
111
- }
112
- } catch (error) {
113
- continue;
114
- }
115
- }
116
-
117
- if (opts.fallthrough) {
118
- return next();
119
- }
120
-
121
- ctx.status(404).json({ error: 'Not Found' });
122
- }
123
-
124
- async function tryExtensions(ctx, filePath, opts, next) {
125
- for (const ext of opts.extensions) {
126
- const extPath = filePath + ext;
127
-
128
- try {
129
- const stats = await stat(extPath);
130
- if (stats.isFile()) {
131
- return await sendFile(ctx, extPath, stats, opts);
132
- }
133
- } catch (error) {
134
- continue;
135
- }
136
- }
137
-
138
- if (opts.fallthrough) {
139
- return next();
140
- }
141
-
142
- ctx.status(404).json({ error: 'Not Found' });
143
- }
144
-
145
- async function sendFile(ctx, filePath, stats, opts) {
146
- const basename = path.basename(filePath);
147
-
148
- if (!opts.hidden && basename.startsWith('.')) {
149
- if (opts.dotfiles === 'deny') {
150
- return ctx.status(403).json({ error: 'Forbidden' });
151
- } else if (opts.dotfiles === 'ignore') {
152
- return ctx.status(404).json({ error: 'Not Found' });
153
- }
154
- }
155
-
156
- const contentType = getContentType(filePath);
157
- ctx.set('Content-Type', contentType);
158
- ctx.set('Content-Length', stats.size);
159
-
160
- if (opts.lastModified) {
161
- ctx.set('Last-Modified', stats.mtime.toUTCString());
162
- }
163
-
164
- if (opts.etag) {
165
- const etag = generateETag(stats);
166
- ctx.set('ETag', etag);
167
-
168
- if (ctx.get('if-none-match') === etag) {
169
- return ctx.status(304).end();
170
- }
171
- }
172
-
173
- if (opts.maxAge) {
174
- const cacheControl = `public, max-age=${opts.maxAge}`;
175
- ctx.set('Cache-Control', cacheControl);
176
- }
177
-
178
- const range = ctx.get('range');
179
- if (range) {
180
- return await sendRangeFile(ctx, filePath, stats, range);
181
- }
182
-
183
- if (opts.setHeaders) {
184
- opts.setHeaders(ctx, filePath, stats);
185
- }
186
-
187
- if (ctx.method === 'HEAD') {
188
- return ctx.status(200).end();
189
- }
190
-
191
- try {
192
- const content = await readFile(filePath);
193
- ctx.status(200).send(content);
194
- } catch (error) {
195
- ctx.status(500).json({ error: 'Internal Server Error' });
196
- }
197
- }
198
-
199
- async function sendRangeFile(ctx, filePath, stats, rangeHeader) {
200
- const ranges = parseRange(stats.size, rangeHeader);
201
-
202
- if (!ranges || ranges.length === 0) {
203
- ctx.set('Content-Range', `bytes */${stats.size}`);
204
- return ctx.status(416).json({ error: 'Range Not Satisfiable' });
205
- }
206
-
207
- if (ranges.length === 1) {
208
- const range = ranges[0];
209
- const start = range.start;
210
- const end = range.end;
211
- const chunkSize = end - start + 1;
212
-
213
- ctx.set('Content-Range', `bytes ${start}-${end}/${stats.size}`);
214
- ctx.set('Content-Length', chunkSize);
215
- ctx.set('Accept-Ranges', 'bytes');
216
- ctx.status(206);
217
-
218
- const stream = fs.createReadStream(filePath, { start, end });
219
- stream.pipe(ctx.res);
220
- } else {
221
- ctx.status(416).json({ error: 'Multiple ranges not supported' });
222
- }
223
- }
224
-
225
- function parseRange(size, rangeHeader) {
226
- if (!rangeHeader || !rangeHeader.startsWith('bytes=')) {
227
- return null;
228
- }
229
-
230
- const ranges = [];
231
- const parts = rangeHeader.slice(6).split(',');
232
-
233
- for (const part of parts) {
234
- const [start, end] = part.trim().split('-');
235
- const startNum = parseInt(start);
236
- const endNum = parseInt(end);
237
-
238
- if (isNaN(startNum) && isNaN(endNum)) {
239
- continue;
240
- }
241
-
242
- if (isNaN(startNum)) {
243
- ranges.push({ start: Math.max(0, size - endNum), end: size - 1 });
244
- } else if (isNaN(endNum)) {
245
- ranges.push({ start: startNum, end: size - 1 });
246
- } else {
247
- ranges.push({ start: startNum, end: Math.min(endNum, size - 1) });
248
- }
249
- }
250
-
251
- return ranges;
252
- }
253
-
254
- function getContentType(filePath) {
255
- const ext = path.extname(filePath).toLowerCase();
256
-
257
- const mimeTypes = {
258
- '.html': 'text/html',
259
- '.htm': 'text/html',
260
- '.js': 'application/javascript',
261
- '.css': 'text/css',
262
- '.json': 'application/json',
263
- '.png': 'image/png',
264
- '.jpg': 'image/jpeg',
265
- '.jpeg': 'image/jpeg',
266
- '.gif': 'image/gif',
267
- '.svg': 'image/svg+xml',
268
- '.ico': 'image/x-icon',
269
- '.pdf': 'application/pdf',
270
- '.txt': 'text/plain',
271
- '.md': 'text/markdown',
272
- '.xml': 'application/xml',
273
- '.zip': 'application/zip',
274
- '.tar': 'application/x-tar',
275
- '.gz': 'application/gzip',
276
- '.mp4': 'video/mp4',
277
- '.webm': 'video/webm',
278
- '.mp3': 'audio/mpeg',
279
- '.wav': 'audio/wav',
280
- '.woff': 'font/woff',
281
- '.woff2': 'font/woff2',
282
- '.ttf': 'font/ttf',
283
- '.otf': 'font/otf'
284
- };
285
-
286
- return mimeTypes[ext] || 'application/octet-stream';
287
- }
288
-
289
- function generateETag(stats) {
290
- const hash = crypto.createHash('md5');
291
- hash.update(stats.size.toString());
292
- hash.update(stats.mtime.getTime().toString());
293
- return `"${hash.digest('hex')}"`;
294
- }
295
-
296
- function serveStatic(root, options) {
297
- return staticFiles(root, options);
298
- }
299
-
300
- module.exports = staticFiles;
301
- module.exports.serveStatic = serveStatic;
3
+ /**
4
+ * @fileoverview Static file serving middleware for Spark Framework
5
+ * @since 1.0.0
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const { promisify } = require('util');
11
+ const crypto = require('crypto');
12
+
13
+ const stat = promisify(fs.stat);
14
+
15
+ // SECURITY: File operation timeout to prevent hanging on slow/malicious filesystems
16
+ const FILE_OPERATION_TIMEOUT = 5000; // 5 seconds
17
+
18
+ /**
19
+ * Reject a promise that does not settle in time.
20
+ *
21
+ * @param {Promise} promise - Promise to wrap
22
+ * @param {number} [timeout] - Timeout in milliseconds
23
+ * @returns {Promise}
24
+ * @private
25
+ */
26
+ function withTimeout(promise, timeout = FILE_OPERATION_TIMEOUT) {
27
+ let timeoutId;
28
+
29
+ const timeoutPromise = new Promise((_, reject) => {
30
+ timeoutId = setTimeout(() => reject(new Error('File operation timeout')), timeout);
31
+ });
32
+
33
+ return Promise.race([
34
+ promise.finally(() => clearTimeout(timeoutId)),
35
+ timeoutPromise
36
+ ]);
37
+ }
38
+
39
+ const DEFAULT_MAX_AGE = 0;
40
+ const DEFAULT_INDEX = ['index.html'];
41
+
42
+ /**
43
+ * Create a static file serving middleware.
44
+ *
45
+ * Files are streamed (with backpressure) rather than buffered in memory.
46
+ * Requests that try to leave `root` (`..`, encoded `%2e%2e%2f`, null bytes)
47
+ * never reach the filesystem. Any path segment starting with a dot (for
48
+ * example `/.git/config` or `/.env`) is treated according to `dotfiles`.
49
+ *
50
+ * @param {string} root - Directory to serve
51
+ * @param {Object} [options={}] - Options
52
+ * @param {number} [options.maxAge=0] - Cache-Control max-age in seconds
53
+ * @param {string|string[]} [options.index=['index.html']] - Directory index files (false to disable)
54
+ * @param {string} [options.dotfiles='ignore'] - 'ignore' (404), 'deny' (403) or 'allow'
55
+ * @param {boolean} [options.hidden=false] - Legacy alias for `dotfiles: 'allow'`
56
+ * @param {boolean} [options.etag=true] - Send ETag and honour If-None-Match
57
+ * @param {boolean} [options.lastModified=true] - Send Last-Modified and honour If-Modified-Since
58
+ * @param {string[]} [options.extensions=[]] - Extensions to try when the file is missing
59
+ * @param {boolean} [options.fallthrough=true] - Call next() instead of replying 404/403 for missing or rejected paths
60
+ * @param {boolean} [options.redirect=true] - Redirect directories to a trailing slash
61
+ * @param {Function} [options.setHeaders] - Called as setHeaders(ctx, fileName, stats)
62
+ * @returns {Function} Middleware
63
+ *
64
+ * @example
65
+ * app.use(staticFiles('./public', { maxAge: 3600 }));
66
+ */
67
+ function staticFiles(root, options = {}) {
68
+ const opts = {
69
+ ...options,
70
+ root: path.resolve(root),
71
+ maxAge: options.maxAge || DEFAULT_MAX_AGE,
72
+ index: options.index === false ? [] : [].concat(options.index || DEFAULT_INDEX),
73
+ dotfiles: options.hidden ? 'allow' : (options.dotfiles || 'ignore'),
74
+ etag: options.etag !== false,
75
+ lastModified: options.lastModified !== false,
76
+ extensions: options.extensions || [],
77
+ fallthrough: options.fallthrough !== false,
78
+ redirect: options.redirect !== false,
79
+ setHeaders: options.setHeaders
80
+ };
81
+
82
+ const rootWithSep = opts.root.endsWith(path.sep) ? opts.root : opts.root + path.sep;
83
+
84
+ const notFound = (ctx, next) => {
85
+ if (opts.fallthrough) {
86
+ return next();
87
+ }
88
+ return ctx.status(404).json({ error: 'Not Found' });
89
+ };
90
+
91
+ const forbidden = (ctx, next) => {
92
+ if (opts.fallthrough) {
93
+ return next();
94
+ }
95
+ return ctx.status(403).json({ error: 'Forbidden' });
96
+ };
97
+
98
+ return async (ctx, next) => {
99
+ if (ctx.method !== 'GET' && ctx.method !== 'HEAD') {
100
+ return next();
101
+ }
102
+
103
+ let pathname;
104
+ try {
105
+ pathname = decodeURIComponent(ctx.path);
106
+ } catch (e) {
107
+ return ctx.status(400).json({ error: 'Invalid URL encoding' });
108
+ }
109
+
110
+ // A second decoding pass only serves to detect double-encoded traversal
111
+ // (%252e%252e%252f); the file is looked up with the single-decoded path.
112
+ let doubleDecoded = pathname;
113
+ try {
114
+ doubleDecoded = decodeURIComponent(pathname);
115
+ } catch (e) {
116
+ // not double-encoded
117
+ }
118
+
119
+ if (isTraversal(pathname) || isTraversal(doubleDecoded)) {
120
+ return forbidden(ctx, next);
121
+ }
122
+
123
+ const relativePath = path.normalize(pathname).replace(/^[/\\]+/, '');
124
+ const filePath = path.join(opts.root, relativePath);
125
+
126
+ // Ensure the resolved path is within the root directory
127
+ if (filePath !== opts.root && !filePath.startsWith(rootWithSep)) {
128
+ return forbidden(ctx, next);
129
+ }
130
+
131
+ // Dot segments anywhere in the path (/.git/config, /.env, /a/.ssh/key)
132
+ if (opts.dotfiles !== 'allow' && hasDotSegment(relativePath)) {
133
+ if (opts.dotfiles === 'deny') {
134
+ return ctx.status(403).json({ error: 'Forbidden' });
135
+ }
136
+ return notFound(ctx, next);
137
+ }
138
+
139
+ let stats;
140
+ try {
141
+ stats = await withTimeout(stat(filePath));
142
+ } catch (error) {
143
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
144
+ return tryExtensions(ctx, filePath, opts, () => notFound(ctx, next));
145
+ }
146
+ if (opts.fallthrough) {
147
+ return next();
148
+ }
149
+ return ctx.status(500).json({ error: 'Internal Server Error' });
150
+ }
151
+
152
+ if (stats.isDirectory()) {
153
+ return handleDirectory(ctx, filePath, opts, () => notFound(ctx, next));
154
+ }
155
+
156
+ if (stats.isFile()) {
157
+ return sendFile(ctx, filePath, stats, opts);
158
+ }
159
+
160
+ return notFound(ctx, next);
161
+ };
162
+ }
163
+
164
+ /**
165
+ * Whether a decoded path tries to escape the root.
166
+ *
167
+ * @param {string} pathname - Decoded request path
168
+ * @returns {boolean}
169
+ * @private
170
+ */
171
+ function isTraversal(pathname) {
172
+ return pathname.includes('\0') ||
173
+ pathname.split(/[/\\]/).some(segment => segment === '..');
174
+ }
175
+
176
+ /**
177
+ * Whether any segment of a relative path starts with a dot.
178
+ *
179
+ * @param {string} relativePath - Path relative to the root
180
+ * @returns {boolean}
181
+ * @private
182
+ */
183
+ function hasDotSegment(relativePath) {
184
+ return relativePath.split(/[/\\]/).some(segment => segment.length > 1 && segment.startsWith('.'));
185
+ }
186
+
187
+ async function handleDirectory(ctx, dirPath, opts, notFound) {
188
+ if (opts.redirect && !ctx.path.endsWith('/')) {
189
+ const base = ctx.mountpath ? `${ctx.mountpath}${ctx.path}` : ctx.path;
190
+ return ctx.redirect(`${base}/`);
191
+ }
192
+
193
+ for (const indexFile of opts.index) {
194
+ const indexPath = path.join(dirPath, indexFile);
195
+ try {
196
+ const stats = await withTimeout(stat(indexPath));
197
+ if (stats.isFile()) {
198
+ return sendFile(ctx, indexPath, stats, opts);
199
+ }
200
+ } catch (error) {
201
+ continue;
202
+ }
203
+ }
204
+
205
+ return notFound();
206
+ }
207
+
208
+ async function tryExtensions(ctx, filePath, opts, notFound) {
209
+ for (const ext of opts.extensions) {
210
+ const extPath = filePath + (ext.startsWith('.') ? ext : `.${ext}`);
211
+ try {
212
+ const stats = await withTimeout(stat(extPath));
213
+ if (stats.isFile()) {
214
+ return sendFile(ctx, extPath, stats, opts);
215
+ }
216
+ } catch (error) {
217
+ continue;
218
+ }
219
+ }
220
+
221
+ return notFound();
222
+ }
223
+
224
+ /**
225
+ * Whether the client's cached copy is still valid.
226
+ *
227
+ * @private
228
+ */
229
+ function isNotModified(ctx, etag, stats, opts) {
230
+ const ifNoneMatch = ctx.get('if-none-match');
231
+ if (ifNoneMatch && opts.etag) {
232
+ const tags = ifNoneMatch.split(',').map(tag => tag.trim().replace(/^W\//, ''));
233
+ return tags.includes('*') || tags.includes(etag);
234
+ }
235
+
236
+ const ifModifiedSince = ctx.get('if-modified-since');
237
+ if (ifModifiedSince && opts.lastModified) {
238
+ const since = Date.parse(ifModifiedSince);
239
+ return !Number.isNaN(since) && Math.floor(stats.mtime.getTime() / 1000) * 1000 <= since;
240
+ }
241
+
242
+ return false;
243
+ }
244
+
245
+ async function sendFile(ctx, filePath, stats, opts) {
246
+ const contentType = getContentType(filePath);
247
+ ctx.set('Content-Type', contentType);
248
+ ctx.set('Accept-Ranges', 'bytes');
249
+
250
+ if (opts.lastModified) {
251
+ ctx.set('Last-Modified', stats.mtime.toUTCString());
252
+ }
253
+
254
+ const etag = generateETag(stats);
255
+ if (opts.etag) {
256
+ ctx.set('ETag', etag);
257
+ }
258
+
259
+ if (opts.maxAge) {
260
+ ctx.set('Cache-Control', `public, max-age=${opts.maxAge}`);
261
+ }
262
+
263
+ if (opts.setHeaders) {
264
+ try {
265
+ opts.setHeaders(ctx, path.basename(filePath), stats);
266
+ } catch (error) {
267
+ console.error('Error in setHeaders callback:', error.message);
268
+ }
269
+ }
270
+
271
+ if (isNotModified(ctx, etag, stats, opts)) {
272
+ ctx.removeHeader('Content-Type');
273
+ return ctx.status(304).end();
274
+ }
275
+
276
+ let start = 0;
277
+ let end = stats.size - 1;
278
+
279
+ const rangeHeader = ctx.get('range');
280
+ if (rangeHeader) {
281
+ const ranges = parseRange(stats.size, rangeHeader);
282
+ if (ranges === null) {
283
+ // Not a byte range we understand: send the whole file
284
+ } else if (ranges.length !== 1) {
285
+ ctx.set('Content-Range', `bytes */${stats.size}`);
286
+ return ctx.status(416).json({ error: 'Range Not Satisfiable' });
287
+ } else {
288
+ start = ranges[0].start;
289
+ end = ranges[0].end;
290
+ ctx.set('Content-Range', `bytes ${start}-${end}/${stats.size}`);
291
+ ctx.status(206);
292
+ }
293
+ } else {
294
+ ctx.status(200);
295
+ }
296
+
297
+ const length = stats.size === 0 ? 0 : end - start + 1;
298
+ ctx.set('Content-Length', length);
299
+
300
+ if (ctx.method === 'HEAD' || length === 0) {
301
+ return ctx.end();
302
+ }
303
+
304
+ return ctx.stream(fs.createReadStream(filePath, { start, end }));
305
+ }
306
+
307
+ /**
308
+ * Parse a Range header.
309
+ *
310
+ * @param {number} size - File size
311
+ * @param {string} rangeHeader - Range header value
312
+ * @returns {Array<{start: number, end: number}>|null} Satisfiable ranges, or
313
+ * null when the header is not a byte range
314
+ * @private
315
+ */
316
+ function parseRange(size, rangeHeader) {
317
+ if (!rangeHeader || !rangeHeader.startsWith('bytes=')) {
318
+ return null;
319
+ }
320
+
321
+ const ranges = [];
322
+ const parts = rangeHeader.slice(6).split(',');
323
+
324
+ for (const part of parts) {
325
+ const match = /^\s*(\d*)\s*-\s*(\d*)\s*$/.exec(part);
326
+ if (!match || (match[1] === '' && match[2] === '')) {
327
+ continue;
328
+ }
329
+
330
+ if (match[1] === '') {
331
+ // Suffix range: last N bytes
332
+ const suffix = parseInt(match[2], 10);
333
+ if (suffix > 0 && size > 0) {
334
+ ranges.push({ start: Math.max(0, size - suffix), end: size - 1 });
335
+ }
336
+ continue;
337
+ }
338
+
339
+ const start = parseInt(match[1], 10);
340
+ const end = match[2] === '' ? size - 1 : Math.min(parseInt(match[2], 10), size - 1);
341
+ if (start <= end && start < size) {
342
+ ranges.push({ start, end });
343
+ }
344
+ }
345
+
346
+ return ranges;
347
+ }
348
+
349
+ function getContentType(filePath) {
350
+ const ext = path.extname(filePath).toLowerCase();
351
+
352
+ const mimeTypes = {
353
+ '.html': 'text/html; charset=utf-8',
354
+ '.htm': 'text/html; charset=utf-8',
355
+ '.js': 'application/javascript; charset=utf-8',
356
+ '.mjs': 'application/javascript; charset=utf-8',
357
+ '.css': 'text/css; charset=utf-8',
358
+ '.json': 'application/json; charset=utf-8',
359
+ '.png': 'image/png',
360
+ '.jpg': 'image/jpeg',
361
+ '.jpeg': 'image/jpeg',
362
+ '.gif': 'image/gif',
363
+ '.webp': 'image/webp',
364
+ '.svg': 'image/svg+xml',
365
+ '.ico': 'image/x-icon',
366
+ '.pdf': 'application/pdf',
367
+ '.txt': 'text/plain; charset=utf-8',
368
+ '.md': 'text/markdown; charset=utf-8',
369
+ '.xml': 'application/xml',
370
+ '.zip': 'application/zip',
371
+ '.tar': 'application/x-tar',
372
+ '.gz': 'application/gzip',
373
+ '.mp4': 'video/mp4',
374
+ '.webm': 'video/webm',
375
+ '.mp3': 'audio/mpeg',
376
+ '.wav': 'audio/wav',
377
+ '.woff': 'font/woff',
378
+ '.woff2': 'font/woff2',
379
+ '.ttf': 'font/ttf',
380
+ '.otf': 'font/otf',
381
+ '.wasm': 'application/wasm'
382
+ };
383
+
384
+ return mimeTypes[ext] || 'application/octet-stream';
385
+ }
386
+
387
+ function generateETag(stats) {
388
+ const hash = crypto.createHash('sha256');
389
+ hash.update(stats.size.toString());
390
+ hash.update(stats.mtime.getTime().toString());
391
+ return `"${hash.digest('hex').substring(0, 32)}"`;
392
+ }
393
+
394
+ /**
395
+ * Alias of staticFiles
396
+ *
397
+ * @param {string} root - Directory to serve
398
+ * @param {Object} [options] - Options
399
+ * @returns {Function} Middleware
400
+ */
401
+ function serveStatic(root, options) {
402
+ return staticFiles(root, options);
403
+ }
404
+
405
+ module.exports = staticFiles;
406
+ module.exports.serveStatic = serveStatic;