@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,299 +1,406 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const { promisify } = require('util');
4
- const crypto = require('crypto');
5
-
6
- const stat = promisify(fs.stat);
7
- const readFile = promisify(fs.readFile);
8
- const readdir = promisify(fs.readdir);
9
-
10
- const DEFAULT_MAX_AGE = 0;
11
- const DEFAULT_INDEX = ['index.html'];
12
-
13
- function staticFiles(root, options = {}) {
14
- const opts = {
15
- root: path.resolve(root),
16
- maxAge: options.maxAge || DEFAULT_MAX_AGE,
17
- index: options.index || DEFAULT_INDEX,
18
- hidden: options.hidden || false,
19
- dotfiles: options.dotfiles || 'ignore',
20
- etag: options.etag !== false,
21
- lastModified: options.lastModified !== false,
22
- extensions: options.extensions || [],
23
- fallthrough: options.fallthrough !== false,
24
- redirect: options.redirect !== false,
25
- setHeaders: options.setHeaders,
26
- ...options
27
- };
28
-
29
- const cache = new Map();
30
-
31
- return async (ctx, next) => {
32
- if (ctx.method !== 'GET' && ctx.method !== 'HEAD') {
33
- return next();
34
- }
35
-
36
- let pathname;
37
- try {
38
- pathname = decodeURIComponent(ctx.path);
39
- } catch (e) {
40
- return ctx.status(400).json({ error: 'Invalid URL encoding' });
41
- }
42
-
43
- // Normalize the path to prevent directory traversal
44
- const normalizedPath = path.normalize(pathname).replace(/^(\.\.(\/|\\|$))+/, '');
45
-
46
- // Ensure the path doesn't contain any traversal patterns
47
- if (pathname.includes('..') || pathname.includes('\0')) {
48
- if (opts.fallthrough) {
49
- return next();
50
- }
51
- return ctx.status(403).json({ error: 'Forbidden' });
52
- }
53
-
54
- const filePath = path.join(opts.root, normalizedPath);
55
-
56
- // Ensure the resolved path is within the root directory
57
- if (!filePath.startsWith(opts.root)) {
58
- if (opts.fallthrough) {
59
- return next();
60
- }
61
- return ctx.status(403).json({ error: 'Forbidden' });
62
- }
63
-
64
- try {
65
- const stats = await stat(filePath);
66
-
67
- if (stats.isDirectory()) {
68
- return await handleDirectory(ctx, filePath, opts, next);
69
- }
70
-
71
- if (stats.isFile()) {
72
- return await sendFile(ctx, filePath, stats, opts);
73
- }
74
-
75
- } catch (error) {
76
- if (error.code === 'ENOENT') {
77
- return await tryExtensions(ctx, filePath, opts, next);
78
- }
79
-
80
- if (opts.fallthrough) {
81
- return next();
82
- }
83
-
84
- return ctx.status(500).json({ error: 'Internal Server Error' });
85
- }
86
-
87
- if (opts.fallthrough) {
88
- return next();
89
- }
90
-
91
- ctx.status(404).json({ error: 'Not Found' });
92
- };
93
- }
94
-
95
- async function handleDirectory(ctx, dirPath, opts, next) {
96
- if (opts.redirect && !ctx.path.endsWith('/')) {
97
- // Using string concatenation for URL paths (not filesystem paths)
98
- const redirectPath = `${ctx.path}/`;
99
- return ctx.redirect(redirectPath);
100
- }
101
-
102
- for (const indexFile of opts.index) {
103
- const indexPath = path.join(dirPath, indexFile);
104
-
105
- try {
106
- const stats = await stat(indexPath);
107
- if (stats.isFile()) {
108
- return await sendFile(ctx, indexPath, stats, opts);
109
- }
110
- } catch (error) {
111
- continue;
112
- }
113
- }
114
-
115
- if (opts.fallthrough) {
116
- return next();
117
- }
118
-
119
- ctx.status(404).json({ error: 'Not Found' });
120
- }
121
-
122
- async function tryExtensions(ctx, filePath, opts, next) {
123
- for (const ext of opts.extensions) {
124
- const extPath = filePath + ext;
125
-
126
- try {
127
- const stats = await stat(extPath);
128
- if (stats.isFile()) {
129
- return await sendFile(ctx, extPath, stats, opts);
130
- }
131
- } catch (error) {
132
- continue;
133
- }
134
- }
135
-
136
- if (opts.fallthrough) {
137
- return next();
138
- }
139
-
140
- ctx.status(404).json({ error: 'Not Found' });
141
- }
142
-
143
- async function sendFile(ctx, filePath, stats, opts) {
144
- const basename = path.basename(filePath);
145
-
146
- if (!opts.hidden && basename.startsWith('.')) {
147
- if (opts.dotfiles === 'deny') {
148
- return ctx.status(403).json({ error: 'Forbidden' });
149
- } else if (opts.dotfiles === 'ignore') {
150
- return ctx.status(404).json({ error: 'Not Found' });
151
- }
152
- }
153
-
154
- const contentType = getContentType(filePath);
155
- ctx.set('Content-Type', contentType);
156
- ctx.set('Content-Length', stats.size);
157
-
158
- if (opts.lastModified) {
159
- ctx.set('Last-Modified', stats.mtime.toUTCString());
160
- }
161
-
162
- if (opts.etag) {
163
- const etag = generateETag(stats);
164
- ctx.set('ETag', etag);
165
-
166
- if (ctx.get('if-none-match') === etag) {
167
- return ctx.status(304).end();
168
- }
169
- }
170
-
171
- if (opts.maxAge) {
172
- const cacheControl = `public, max-age=${opts.maxAge}`;
173
- ctx.set('Cache-Control', cacheControl);
174
- }
175
-
176
- const range = ctx.get('range');
177
- if (range) {
178
- return await sendRangeFile(ctx, filePath, stats, range);
179
- }
180
-
181
- if (opts.setHeaders) {
182
- opts.setHeaders(ctx, filePath, stats);
183
- }
184
-
185
- if (ctx.method === 'HEAD') {
186
- return ctx.status(200).end();
187
- }
188
-
189
- try {
190
- const content = await readFile(filePath);
191
- ctx.status(200).send(content);
192
- } catch (error) {
193
- ctx.status(500).json({ error: 'Internal Server Error' });
194
- }
195
- }
196
-
197
- async function sendRangeFile(ctx, filePath, stats, rangeHeader) {
198
- const ranges = parseRange(stats.size, rangeHeader);
199
-
200
- if (!ranges || ranges.length === 0) {
201
- ctx.set('Content-Range', `bytes */${stats.size}`);
202
- return ctx.status(416).json({ error: 'Range Not Satisfiable' });
203
- }
204
-
205
- if (ranges.length === 1) {
206
- const range = ranges[0];
207
- const start = range.start;
208
- const end = range.end;
209
- const chunkSize = end - start + 1;
210
-
211
- ctx.set('Content-Range', `bytes ${start}-${end}/${stats.size}`);
212
- ctx.set('Content-Length', chunkSize);
213
- ctx.set('Accept-Ranges', 'bytes');
214
- ctx.status(206);
215
-
216
- const stream = fs.createReadStream(filePath, { start, end });
217
- stream.pipe(ctx.res);
218
- } else {
219
- ctx.status(416).json({ error: 'Multiple ranges not supported' });
220
- }
221
- }
222
-
223
- function parseRange(size, rangeHeader) {
224
- if (!rangeHeader || !rangeHeader.startsWith('bytes=')) {
225
- return null;
226
- }
227
-
228
- const ranges = [];
229
- const parts = rangeHeader.slice(6).split(',');
230
-
231
- for (const part of parts) {
232
- const [start, end] = part.trim().split('-');
233
- const startNum = parseInt(start);
234
- const endNum = parseInt(end);
235
-
236
- if (isNaN(startNum) && isNaN(endNum)) {
237
- continue;
238
- }
239
-
240
- if (isNaN(startNum)) {
241
- ranges.push({ start: Math.max(0, size - endNum), end: size - 1 });
242
- } else if (isNaN(endNum)) {
243
- ranges.push({ start: startNum, end: size - 1 });
244
- } else {
245
- ranges.push({ start: startNum, end: Math.min(endNum, size - 1) });
246
- }
247
- }
248
-
249
- return ranges;
250
- }
251
-
252
- function getContentType(filePath) {
253
- const ext = path.extname(filePath).toLowerCase();
254
-
255
- const mimeTypes = {
256
- '.html': 'text/html',
257
- '.htm': 'text/html',
258
- '.js': 'application/javascript',
259
- '.css': 'text/css',
260
- '.json': 'application/json',
261
- '.png': 'image/png',
262
- '.jpg': 'image/jpeg',
263
- '.jpeg': 'image/jpeg',
264
- '.gif': 'image/gif',
265
- '.svg': 'image/svg+xml',
266
- '.ico': 'image/x-icon',
267
- '.pdf': 'application/pdf',
268
- '.txt': 'text/plain',
269
- '.md': 'text/markdown',
270
- '.xml': 'application/xml',
271
- '.zip': 'application/zip',
272
- '.tar': 'application/x-tar',
273
- '.gz': 'application/gzip',
274
- '.mp4': 'video/mp4',
275
- '.webm': 'video/webm',
276
- '.mp3': 'audio/mpeg',
277
- '.wav': 'audio/wav',
278
- '.woff': 'font/woff',
279
- '.woff2': 'font/woff2',
280
- '.ttf': 'font/ttf',
281
- '.otf': 'font/otf'
282
- };
283
-
284
- return mimeTypes[ext] || 'application/octet-stream';
285
- }
286
-
287
- function generateETag(stats) {
288
- const hash = crypto.createHash('md5');
289
- hash.update(stats.size.toString());
290
- hash.update(stats.mtime.getTime().toString());
291
- return `"${hash.digest('hex')}"`;
292
- }
293
-
294
- function serveStatic(root, options) {
295
- return staticFiles(root, options);
296
- }
297
-
298
- module.exports = staticFiles;
299
- module.exports.serveStatic = serveStatic;
1
+ 'use strict';
2
+
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;