@dim24/servin 0.0.0-stage → 0.2.1

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.
package/src/utils.js ADDED
@@ -0,0 +1,559 @@
1
+ import fs from 'node:fs';
2
+ import fsp from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { Readable } from 'node:stream';
5
+ import { monitorEventLoopDelay } from 'node:perf_hooks';
6
+
7
+ const MIME_TYPES = {
8
+ '.html': 'text/html; charset=utf-8',
9
+ '.css': 'text/css; charset=utf-8',
10
+ '.js': 'application/javascript; charset=utf-8',
11
+ '.mjs': 'application/javascript; charset=utf-8',
12
+ '.json': 'application/json; charset=utf-8',
13
+ '.txt': 'text/plain; charset=utf-8',
14
+ '.svg': 'image/svg+xml',
15
+ '.png': 'image/png',
16
+ '.jpg': 'image/jpeg',
17
+ '.jpeg': 'image/jpeg',
18
+ '.webp': 'image/webp',
19
+ '.gif': 'image/gif',
20
+ '.ico': 'image/x-icon',
21
+ '.woff': 'font/woff',
22
+ '.woff2': 'font/woff2',
23
+ '.ttf': 'font/ttf',
24
+ '.pdf': 'application/pdf',
25
+ '.mp4': 'video/mp4',
26
+ '.webm': 'video/webm',
27
+ '.mp3': 'audio/mpeg',
28
+ '.wav': 'audio/wav',
29
+ '.zip': 'application/zip'
30
+ };
31
+
32
+ const HTML_ESCAPE_MAP = {
33
+ '&': '&',
34
+ '<': '<',
35
+ '>': '>',
36
+ '"': '"',
37
+ "\'": '\''
38
+ };
39
+
40
+ export function escapeHtml(value) {
41
+ if (value === null || value === undefined) return '';
42
+ return String(value).replace(/[&<>"']/g, (ch) => HTML_ESCAPE_MAP[ch]);
43
+ }
44
+
45
+ export class HtmlResponse {
46
+ constructor(html) {
47
+ this.html = String(html);
48
+ }
49
+ }
50
+
51
+ export class FileStreamResponse {
52
+ constructor(filePath) {
53
+ this.filePath = path.resolve(filePath);
54
+ }
55
+ }
56
+
57
+ export class StaticRouteDescriptor {
58
+ constructor(targetPath, options = {}) {
59
+ if (!targetPath || typeof targetPath !== 'string') {
60
+ throw new TypeError('serveStatic(targetPath, options) requires a valid file or folder path');
61
+ }
62
+ this.targetPath = path.resolve(targetPath);
63
+ this.index = options.index !== undefined ? options.index : 'index.html';
64
+ this.dotfiles = options.dotfiles || 'ignore';
65
+ this.cacheControl = options.cacheControl || null;
66
+ this.spa = Boolean(options.spa);
67
+ this.fallbackFile = options.fallback ? path.resolve(options.fallback) : null;
68
+ }
69
+ }
70
+
71
+ export class RedirectDescriptor {
72
+ constructor(target, status = 301) {
73
+ if (!target || (typeof target !== 'string' && typeof target !== 'function')) {
74
+ throw new TypeError('redirect(target, status) requires a target URL string or resolver function');
75
+ }
76
+ this.target = target;
77
+ this.status = status;
78
+ }
79
+ }
80
+
81
+ export function parseDuration(input, fallbackMs = 0) {
82
+ if (typeof input === 'number') return input;
83
+ if (typeof input !== 'string') return fallbackMs;
84
+ const match = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i.exec(input.trim());
85
+ if (!match) return fallbackMs;
86
+ const val = Number(match[1]);
87
+ const unit = match[2].toLowerCase();
88
+ const multipliers = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
89
+ return Math.round(val * multipliers[unit]);
90
+ }
91
+
92
+ export function parseBytes(input, fallbackBytes = Infinity) {
93
+ if (typeof input === 'number') return input;
94
+ if (typeof input !== 'string') return fallbackBytes;
95
+ const match = /^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)$/i.exec(input.trim());
96
+ if (!match) return fallbackBytes;
97
+ const val = Number(match[1]);
98
+ const unit = match[2].toLowerCase();
99
+ const multipliers = { b: 1, kb: 1024, mb: 1024 ** 2, gb: 1024 ** 3 };
100
+ return Math.round(val * multipliers[unit]);
101
+ }
102
+
103
+ export function applyFieldMask(data, fieldsParam) {
104
+ if (!fieldsParam || data === null || typeof data !== 'object') return data;
105
+ const paths = fieldsParam.split(',').map((s) => s.trim()).filter(Boolean);
106
+ if (paths.length === 0) return data;
107
+
108
+ const tree = {};
109
+ for (const p of paths) {
110
+ const parts = p.split('.');
111
+ let cur = tree;
112
+ for (let i = 0; i < parts.length; i++) {
113
+ const part = parts[i];
114
+ if (i === parts.length - 1) cur[part] = true;
115
+ else {
116
+ if (cur[part] !== true) cur[part] = cur[part] || {};
117
+ cur = cur[part];
118
+ }
119
+ }
120
+ }
121
+
122
+ function filterNode(val, mask) {
123
+ if (mask === true || val === null || typeof val !== 'object') return val;
124
+ if (Array.isArray(val)) return val.map((item) => filterNode(item, mask));
125
+ const out = {};
126
+ for (const key of Object.keys(mask)) {
127
+ if (key in val) out[key] = filterNode(val[key], mask[key]);
128
+ }
129
+ return out;
130
+ }
131
+
132
+ return filterNode(data, tree);
133
+ }
134
+
135
+ export function applyRedaction(data, patterns = []) {
136
+ if (!patterns || patterns.length === 0 || data === null || typeof data !== 'object') {
137
+ return data;
138
+ }
139
+
140
+ const regexes = patterns.map((pat) => {
141
+ const escaped = pat.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
142
+ return new RegExp(`^${escaped}$`, 'i');
143
+ });
144
+
145
+ function isBlocked(keyPath, keyName) {
146
+ return regexes.some((rx) => rx.test(keyName) || rx.test(keyPath));
147
+ }
148
+
149
+ function scrub(val, prefix = '') {
150
+ if (val === null || typeof val !== 'object') return val;
151
+ if (val instanceof Date || val instanceof Uint8Array) return val;
152
+ if (Array.isArray(val)) return val.map((item) => scrub(item, prefix));
153
+ const out = {};
154
+ for (const [k, v] of Object.entries(val)) {
155
+ const fullPath = prefix ? `${prefix}.${k}` : k;
156
+ if (!isBlocked(fullPath, k)) {
157
+ out[k] = scrub(v, fullPath);
158
+ }
159
+ }
160
+ return out;
161
+ }
162
+
163
+ return scrub(data);
164
+ }
165
+
166
+ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
167
+
168
+ export function validateExpect(payload, schema, basePath = '') {
169
+ const errors = [];
170
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
171
+ return [{ field: basePath || 'body', message: 'Expected a JSON object' }];
172
+ }
173
+
174
+ for (const [key, rule] of Object.entries(schema)) {
175
+ const fieldPath = basePath ? `${basePath}.${key}` : key;
176
+ const val = payload[key];
177
+
178
+ if (Array.isArray(rule)) {
179
+ if (val === undefined || !rule.includes(val)) {
180
+ errors.push({ field: fieldPath, message: `Must be one of: ${rule.join(', ')}` });
181
+ }
182
+ continue;
183
+ }
184
+
185
+ if (typeof rule === 'object' && rule !== null) {
186
+ if (val === undefined || val === null) {
187
+ errors.push({ field: fieldPath, message: 'Required object is missing' });
188
+ } else {
189
+ errors.push(...validateExpect(val, rule, fieldPath));
190
+ }
191
+ continue;
192
+ }
193
+
194
+ if (typeof rule === 'string') {
195
+ const optional = rule.endsWith('?');
196
+ const baseType = optional ? rule.slice(0, -1) : rule;
197
+
198
+ if (val === undefined || val === null) {
199
+ if (!optional) errors.push({ field: fieldPath, message: 'Field is required' });
200
+ continue;
201
+ }
202
+
203
+ if (baseType === 'email') {
204
+ if (typeof val !== 'string' || !EMAIL_RE.test(val)) {
205
+ errors.push({ field: fieldPath, message: 'Must be a valid email address' });
206
+ }
207
+ } else if (baseType === 'array') {
208
+ if (!Array.isArray(val)) {
209
+ errors.push({ field: fieldPath, message: 'Must be an array' });
210
+ }
211
+ } else if (baseType === 'number') {
212
+ if (typeof val !== 'number' || Number.isNaN(val)) {
213
+ errors.push({ field: fieldPath, message: 'Must be a valid number' });
214
+ }
215
+ } else if (typeof val !== baseType) {
216
+ errors.push({ field: fieldPath, message: `Must be of type ${baseType}` });
217
+ }
218
+ }
219
+ }
220
+
221
+ return errors;
222
+ }
223
+
224
+ export async function buildFileHttpResponse(descriptor, reqHeaders, opts = {}) {
225
+ let stat;
226
+ try {
227
+ stat = await fsp.stat(descriptor.filePath);
228
+ } catch {
229
+ if (opts.returnMissing) return null;
230
+ return Response.json({ error: 'File Not Found' }, { status: 404 });
231
+ }
232
+
233
+ if (!stat.isFile()) {
234
+ if (opts.returnMissing) return null;
235
+ return Response.json({ error: 'Not a file' }, { status: 404 });
236
+ }
237
+
238
+ const isHead = opts.method === 'HEAD';
239
+ const baseStatus = opts.statusOverride || 200;
240
+ const etag = `W/"${stat.size}-${Math.floor(stat.mtimeMs)}"`;
241
+
242
+ const commonHeaders = {
243
+ ETag: etag,
244
+ 'Accept-Ranges': 'bytes'
245
+ };
246
+ if (opts.cacheControl) {
247
+ commonHeaders['Cache-Control'] = opts.cacheControl;
248
+ }
249
+
250
+ if (!opts.statusOverride && reqHeaders.get('if-none-match') === etag) {
251
+ return new Response(null, {
252
+ status: 304,
253
+ headers: commonHeaders
254
+ });
255
+ }
256
+
257
+ const ext = path.extname(descriptor.filePath).toLowerCase();
258
+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';
259
+ const rangeHeader = reqHeaders.get('range');
260
+
261
+ if (!opts.statusOverride && rangeHeader && rangeHeader.startsWith('bytes=')) {
262
+ const [startStr, endStr] = rangeHeader.replace('bytes=', '').split('-');
263
+ const start = startStr ? parseInt(startStr, 10) : 0;
264
+ const end = endStr ? parseInt(endStr, 10) : stat.size - 1;
265
+
266
+ if (Number.isNaN(start) || Number.isNaN(end) || start > end || end >= stat.size) {
267
+ return new Response(null, {
268
+ status: 416,
269
+ headers: { 'Content-Range': `bytes */${stat.size}` }
270
+ });
271
+ }
272
+
273
+ const body = isHead ? null : Readable.toWeb(fs.createReadStream(descriptor.filePath, { start, end }));
274
+ return new Response(body, {
275
+ status: 206,
276
+ headers: {
277
+ ...commonHeaders,
278
+ 'Content-Type': contentType,
279
+ 'Content-Length': String(end - start + 1),
280
+ 'Content-Range': `bytes ${start}-${end}/${stat.size}`
281
+ }
282
+ });
283
+ }
284
+
285
+ const body = isHead ? null : Readable.toWeb(fs.createReadStream(descriptor.filePath));
286
+ return new Response(body, {
287
+ status: baseStatus,
288
+ headers: {
289
+ ...commonHeaders,
290
+ 'Content-Type': contentType,
291
+ 'Content-Length': String(stat.size)
292
+ }
293
+ });
294
+ }
295
+
296
+ export async function buildStaticHttpResponse(descriptor, subPath, reqHeaders, method = 'GET') {
297
+ let rootStat;
298
+ try {
299
+ rootStat = await fsp.stat(descriptor.targetPath);
300
+ } catch {
301
+ return { errorStatus: 404, message: 'Not Found' };
302
+ }
303
+
304
+ const cleanSub = String(subPath || '').replace(/^\/+/, '');
305
+
306
+ if (rootStat.isFile()) {
307
+ if (cleanSub.length > 0) {
308
+ return { errorStatus: 404, message: 'Not Found' };
309
+ }
310
+ const response = await buildFileHttpResponse(
311
+ new FileStreamResponse(descriptor.targetPath),
312
+ reqHeaders,
313
+ { cacheControl: descriptor.cacheControl, method, returnMissing: true }
314
+ );
315
+ return response ? { response } : { errorStatus: 404, message: 'Not Found' };
316
+ }
317
+
318
+ if (!rootStat.isDirectory()) {
319
+ return { errorStatus: 404, message: 'Not Found' };
320
+ }
321
+
322
+ if (cleanSub.includes('\0')) {
323
+ return { errorStatus: 400, message: 'Invalid path' };
324
+ }
325
+
326
+ const parts = cleanSub ? cleanSub.split('/') : [];
327
+ for (const seg of parts) {
328
+ if (seg === '..') {
329
+ return { errorStatus: 403, message: 'Forbidden' };
330
+ }
331
+ if (seg.startsWith('.') && seg !== '.') {
332
+ if (descriptor.dotfiles === 'deny') return { errorStatus: 403, message: 'Forbidden' };
333
+ if (descriptor.dotfiles === 'ignore') return { errorStatus: 404, message: 'Not Found' };
334
+ }
335
+ }
336
+
337
+ const candidate = path.resolve(descriptor.targetPath, cleanSub);
338
+ if (candidate !== descriptor.targetPath && !candidate.startsWith(descriptor.targetPath + path.sep)) {
339
+ return { errorStatus: 403, message: 'Forbidden' };
340
+ }
341
+
342
+ let targetFile = null;
343
+ try {
344
+ const stat = await fsp.stat(candidate);
345
+ if (stat.isDirectory()) {
346
+ if (descriptor.index) {
347
+ const indexPath = path.resolve(candidate, descriptor.index);
348
+ if (indexPath.startsWith(descriptor.targetPath + path.sep)) {
349
+ const idxStat = await fsp.stat(indexPath).catch(() => null);
350
+ if (idxStat?.isFile()) targetFile = indexPath;
351
+ }
352
+ }
353
+ } else if (stat.isFile()) {
354
+ targetFile = candidate;
355
+ }
356
+ } catch {
357
+ targetFile = null;
358
+ }
359
+
360
+ if (!targetFile && (descriptor.spa || descriptor.fallbackFile)) {
361
+ const fallback = descriptor.fallbackFile
362
+ || (descriptor.index ? path.join(descriptor.targetPath, descriptor.index) : null);
363
+ if (fallback) {
364
+ const fbStat = await fsp.stat(fallback).catch(() => null);
365
+ if (fbStat?.isFile()) targetFile = fallback;
366
+ }
367
+ }
368
+
369
+ if (!targetFile) {
370
+ return { errorStatus: 404, message: 'Not Found' };
371
+ }
372
+
373
+ const response = await buildFileHttpResponse(
374
+ new FileStreamResponse(targetFile),
375
+ reqHeaders,
376
+ { cacheControl: descriptor.cacheControl, method, returnMissing: true }
377
+ );
378
+ return response ? { response } : { errorStatus: 404, message: 'Not Found' };
379
+ }
380
+
381
+ export async function* parseMultipartStream(webStream, contentType, opts = {}) {
382
+ const boundaryMatch = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType || '');
383
+ if (!boundaryMatch) {
384
+ throw Object.assign(new Error('Invalid multipart/form-data boundary'), { status: 400 });
385
+ }
386
+
387
+ const boundary = boundaryMatch[1] || boundaryMatch[2].trim();
388
+ const firstDelimiter = Buffer.from(`--${boundary}`);
389
+ const nextDelimiter = Buffer.from(`\r\n--${boundary}`);
390
+ const headerEndSep = Buffer.from('\r\n\r\n');
391
+ const maxFileSize = parseBytes(opts.maxFileSize, Infinity);
392
+
393
+ const reader = webStream.getReader();
394
+ let buf = Buffer.alloc(0);
395
+ let eof = false;
396
+
397
+ async function pullMore() {
398
+ if (eof) return false;
399
+ const { done, value } = await reader.read();
400
+ if (done) {
401
+ eof = true;
402
+ return false;
403
+ }
404
+ buf = Buffer.concat([buf, Buffer.from(value)]);
405
+ return true;
406
+ }
407
+
408
+ while (buf.indexOf(firstDelimiter) === -1) {
409
+ if (!(await pullMore())) return;
410
+ }
411
+
412
+ const startIdx = buf.indexOf(firstDelimiter) + firstDelimiter.length;
413
+ buf = buf.subarray(startIdx);
414
+
415
+ while (true) {
416
+ while (buf.length < 4 && !eof) await pullMore();
417
+ if (buf.subarray(0, 2).toString() === '--') break;
418
+ if (buf.subarray(0, 2).toString() === '\r\n') buf = buf.subarray(2);
419
+
420
+ while (buf.indexOf(headerEndSep) === -1) {
421
+ if (!(await pullMore())) return;
422
+ }
423
+
424
+ const headerEndIdx = buf.indexOf(headerEndSep);
425
+ const rawHeaders = buf.subarray(0, headerEndIdx).toString('utf8');
426
+ buf = buf.subarray(headerEndIdx + 4);
427
+
428
+ const dispMatch = /content-disposition:\s*form-data;([^\r\n]+)/i.exec(rawHeaders);
429
+ const nameMatch = dispMatch && /name="([^"]+)"/i.exec(dispMatch[1]);
430
+ const fileMatch = dispMatch && /filename="([^"]*)"/i.exec(dispMatch[1]);
431
+ const typeMatch = /content-type:\s*([^\r\n]+)/i.exec(rawHeaders);
432
+
433
+ const name = nameMatch ? nameMatch[1] : '';
434
+ const filename = fileMatch ? fileMatch[1] : null;
435
+ const partType = typeMatch ? typeMatch[1].trim() : 'text/plain';
436
+ const isFile = filename !== null;
437
+
438
+ let partDone = false;
439
+ let bytesRead = 0;
440
+ const guardLen = nextDelimiter.length + 4;
441
+
442
+ const partStream = new ReadableStream({
443
+ async pull(controller) {
444
+ if (partDone) {
445
+ controller.close();
446
+ return;
447
+ }
448
+
449
+ while (true) {
450
+ const delimIdx = buf.indexOf(nextDelimiter);
451
+ if (delimIdx !== -1) {
452
+ const chunk = buf.subarray(0, delimIdx);
453
+ buf = buf.subarray(delimIdx + nextDelimiter.length);
454
+ partDone = true;
455
+ if (chunk.length > 0) {
456
+ bytesRead += chunk.length;
457
+ if (isFile && bytesRead > maxFileSize) {
458
+ const err = Object.assign(new Error('File exceeds maxFileSize'), { status: 413 });
459
+ controller.error(err);
460
+ return;
461
+ }
462
+ controller.enqueue(new Uint8Array(chunk));
463
+ }
464
+ controller.close();
465
+ return;
466
+ }
467
+
468
+ if (buf.length > guardLen) {
469
+ const safeEnd = buf.length - guardLen;
470
+ const chunk = buf.subarray(0, safeEnd);
471
+ buf = buf.subarray(safeEnd);
472
+ bytesRead += chunk.length;
473
+ if (isFile && bytesRead > maxFileSize) {
474
+ const err = Object.assign(new Error('File exceeds maxFileSize'), { status: 413 });
475
+ controller.error(err);
476
+ return;
477
+ }
478
+ controller.enqueue(new Uint8Array(chunk));
479
+ return;
480
+ }
481
+
482
+ if (!(await pullMore())) {
483
+ partDone = true;
484
+ if (buf.length > 0) {
485
+ controller.enqueue(new Uint8Array(buf));
486
+ buf = Buffer.alloc(0);
487
+ }
488
+ controller.close();
489
+ return;
490
+ }
491
+ }
492
+ }
493
+ });
494
+
495
+ let consumed = false;
496
+ const consumeBuffer = async () => {
497
+ consumed = true;
498
+ const r = partStream.getReader();
499
+ const chunks = [];
500
+ while (true) {
501
+ const { done, value } = await r.read();
502
+ if (done) break;
503
+ chunks.push(Buffer.from(value));
504
+ }
505
+ return Buffer.concat(chunks);
506
+ };
507
+
508
+ const trackedStream = new ReadableStream({
509
+ async start(controller) {
510
+ consumed = true;
511
+ const r = partStream.getReader();
512
+ try {
513
+ while (true) {
514
+ const { done, value } = await r.read();
515
+ if (done) break;
516
+ controller.enqueue(value);
517
+ }
518
+ controller.close();
519
+ } catch (err) {
520
+ controller.error(err);
521
+ }
522
+ }
523
+ });
524
+
525
+ yield {
526
+ name,
527
+ filename,
528
+ contentType: partType,
529
+ isFile,
530
+ isField: !isFile,
531
+ stream: trackedStream,
532
+ async text() {
533
+ return (await consumeBuffer()).toString('utf8');
534
+ },
535
+ async json() {
536
+ return JSON.parse((await consumeBuffer()).toString('utf8'));
537
+ }
538
+ };
539
+
540
+ if (!consumed) {
541
+ await consumeBuffer();
542
+ }
543
+ }
544
+ }
545
+
546
+ export function createLagMonitor(thresholdMs = 60) {
547
+ const histogram = monitorEventLoopDelay({ resolution: 20 });
548
+ histogram.enable();
549
+ return {
550
+ isOverloaded() {
551
+ const p95Ms = histogram.percentile(95) / 1e6;
552
+ histogram.reset();
553
+ return p95Ms > thresholdMs;
554
+ },
555
+ stop() {
556
+ histogram.disable();
557
+ }
558
+ };
559
+ }