@dim24/servin 0.0.0-stage → 0.0.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/LICENSE +21 -0
- package/README.md +1655 -3
- package/example/index.js +43 -0
- package/example/router.js +11 -0
- package/index.js +3 -0
- package/package.json +38 -4
- package/src/server.js +793 -0
- package/src/servin.test.js +292 -0
- package/src/session.js +311 -0
- package/src/tree.js +504 -0
- package/src/utils.js +436 -0
- package/src/websocket.js +311 -0
- package/src/wire.js +254 -0
- package/test.js +45 -0
package/src/utils.js
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
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
|
+
'.pdf': 'application/pdf',
|
|
21
|
+
'.mp4': 'video/mp4',
|
|
22
|
+
'.webm': 'video/webm',
|
|
23
|
+
'.mp3': 'audio/mpeg',
|
|
24
|
+
'.wav': 'audio/wav',
|
|
25
|
+
'.zip': 'application/zip'
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const HTML_ESCAPE_MAP = {
|
|
29
|
+
'&': '&',
|
|
30
|
+
'<': '<',
|
|
31
|
+
'>': '>',
|
|
32
|
+
'"': '"',
|
|
33
|
+
"\'": '\''
|
|
34
|
+
};
|
|
35
|
+
// test mark error
|
|
36
|
+
|
|
37
|
+
export function escapeHtml(value) {
|
|
38
|
+
if (value === null || value === undefined) return '';
|
|
39
|
+
return String(value).replace(/[&<>"']/g, (ch) => HTML_ESCAPE_MAP[ch]);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class HtmlResponse {
|
|
43
|
+
constructor(html) {
|
|
44
|
+
this.html = String(html);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export class FileStreamResponse {
|
|
49
|
+
constructor(filePath) {
|
|
50
|
+
this.filePath = path.resolve(filePath);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function parseDuration(input, fallbackMs = 0) {
|
|
55
|
+
if (typeof input === 'number') return input;
|
|
56
|
+
if (typeof input !== 'string') return fallbackMs;
|
|
57
|
+
const match = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i.exec(input.trim());
|
|
58
|
+
if (!match) return fallbackMs;
|
|
59
|
+
const val = Number(match[1]);
|
|
60
|
+
const unit = match[2].toLowerCase();
|
|
61
|
+
const multipliers = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
|
|
62
|
+
return Math.round(val * multipliers[unit]);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function parseBytes(input, fallbackBytes = Infinity) {
|
|
66
|
+
if (typeof input === 'number') return input;
|
|
67
|
+
if (typeof input !== 'string') return fallbackBytes;
|
|
68
|
+
const match = /^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)$/i.exec(input.trim());
|
|
69
|
+
if (!match) return fallbackBytes;
|
|
70
|
+
const val = Number(match[1]);
|
|
71
|
+
const unit = match[2].toLowerCase();
|
|
72
|
+
const multipliers = { b: 1, kb: 1024, mb: 1024 ** 2, gb: 1024 ** 3 };
|
|
73
|
+
return Math.round(val * multipliers[unit]);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function applyFieldMask(data, fieldsParam) {
|
|
77
|
+
if (!fieldsParam || data === null || typeof data !== 'object') return data;
|
|
78
|
+
const paths = fieldsParam.split(',').map((s) => s.trim()).filter(Boolean);
|
|
79
|
+
if (paths.length === 0) return data;
|
|
80
|
+
|
|
81
|
+
const tree = {};
|
|
82
|
+
for (const p of paths) {
|
|
83
|
+
const parts = p.split('.');
|
|
84
|
+
let cur = tree;
|
|
85
|
+
for (let i = 0; i < parts.length; i++) {
|
|
86
|
+
const part = parts[i];
|
|
87
|
+
if (i === parts.length - 1) cur[part] = true;
|
|
88
|
+
else {
|
|
89
|
+
if (cur[part] !== true) cur[part] = cur[part] || {};
|
|
90
|
+
cur = cur[part];
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function filterNode(val, mask) {
|
|
96
|
+
if (mask === true || val === null || typeof val !== 'object') return val;
|
|
97
|
+
if (Array.isArray(val)) return val.map((item) => filterNode(item, mask));
|
|
98
|
+
const out = {};
|
|
99
|
+
for (const key of Object.keys(mask)) {
|
|
100
|
+
if (key in val) out[key] = filterNode(val[key], mask[key]);
|
|
101
|
+
}
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return filterNode(data, tree);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function applyRedaction(data, patterns = []) {
|
|
109
|
+
if (!patterns || patterns.length === 0 || data === null || typeof data !== 'object') {
|
|
110
|
+
return data;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const regexes = patterns.map((pat) => {
|
|
114
|
+
const escaped = pat.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
|
|
115
|
+
return new RegExp(`^${escaped}$`, 'i');
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
function isBlocked(keyPath, keyName) {
|
|
119
|
+
return regexes.some((rx) => rx.test(keyName) || rx.test(keyPath));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function scrub(val, prefix = '') {
|
|
123
|
+
if (val === null || typeof val !== 'object') return val;
|
|
124
|
+
if (val instanceof Date || val instanceof Uint8Array) return val;
|
|
125
|
+
if (Array.isArray(val)) return val.map((item) => scrub(item, prefix));
|
|
126
|
+
const out = {};
|
|
127
|
+
for (const [k, v] of Object.entries(val)) {
|
|
128
|
+
const fullPath = prefix ? `${prefix}.${k}` : k;
|
|
129
|
+
if (!isBlocked(fullPath, k)) {
|
|
130
|
+
out[k] = scrub(v, fullPath);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return scrub(data);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
140
|
+
|
|
141
|
+
export function validateExpect(payload, schema, basePath = '') {
|
|
142
|
+
const errors = [];
|
|
143
|
+
if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
144
|
+
return [{ field: basePath || 'body', message: 'Expected a JSON object' }];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
for (const [key, rule] of Object.entries(schema)) {
|
|
148
|
+
const fieldPath = basePath ? `${basePath}.${key}` : key;
|
|
149
|
+
const val = payload[key];
|
|
150
|
+
|
|
151
|
+
if (Array.isArray(rule)) {
|
|
152
|
+
if (val === undefined || !rule.includes(val)) {
|
|
153
|
+
errors.push({ field: fieldPath, message: `Must be one of: ${rule.join(', ')}` });
|
|
154
|
+
}
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (typeof rule === 'object' && rule !== null) {
|
|
159
|
+
if (val === undefined || val === null) {
|
|
160
|
+
errors.push({ field: fieldPath, message: 'Required object is missing' });
|
|
161
|
+
} else {
|
|
162
|
+
errors.push(...validateExpect(val, rule, fieldPath));
|
|
163
|
+
}
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if (typeof rule === 'string') {
|
|
168
|
+
const optional = rule.endsWith('?');
|
|
169
|
+
const baseType = optional ? rule.slice(0, -1) : rule;
|
|
170
|
+
|
|
171
|
+
if (val === undefined || val === null) {
|
|
172
|
+
if (!optional) errors.push({ field: fieldPath, message: 'Field is required' });
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (baseType === 'email') {
|
|
177
|
+
if (typeof val !== 'string' || !EMAIL_RE.test(val)) {
|
|
178
|
+
errors.push({ field: fieldPath, message: 'Must be a valid email address' });
|
|
179
|
+
}
|
|
180
|
+
} else if (baseType === 'array') {
|
|
181
|
+
if (!Array.isArray(val)) {
|
|
182
|
+
errors.push({ field: fieldPath, message: 'Must be an array' });
|
|
183
|
+
}
|
|
184
|
+
} else if (baseType === 'number') {
|
|
185
|
+
if (typeof val !== 'number' || Number.isNaN(val)) {
|
|
186
|
+
errors.push({ field: fieldPath, message: 'Must be a valid number' });
|
|
187
|
+
}
|
|
188
|
+
} else if (typeof val !== baseType) {
|
|
189
|
+
errors.push({ field: fieldPath, message: `Must be of type ${baseType}` });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return errors;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export async function buildFileHttpResponse(descriptor, reqHeaders) {
|
|
198
|
+
let stat;
|
|
199
|
+
try {
|
|
200
|
+
stat = await fsp.stat(descriptor.filePath);
|
|
201
|
+
} catch {
|
|
202
|
+
return Response.json({ error: 'File Not Found' }, { status: 404 });
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (!stat.isFile()) {
|
|
206
|
+
return Response.json({ error: 'Not a file' }, { status: 404 });
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const etag = `W/"${stat.size}-${Math.floor(stat.mtimeMs)}"`;
|
|
210
|
+
if (reqHeaders.get('if-none-match') === etag) {
|
|
211
|
+
return new Response(null, {
|
|
212
|
+
status: 304,
|
|
213
|
+
headers: { ETag: etag, 'Accept-Ranges': 'bytes' }
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const ext = path.extname(descriptor.filePath).toLowerCase();
|
|
218
|
+
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
|
|
219
|
+
const rangeHeader = reqHeaders.get('range');
|
|
220
|
+
|
|
221
|
+
if (rangeHeader && rangeHeader.startsWith('bytes=')) {
|
|
222
|
+
const [startStr, endStr] = rangeHeader.replace('bytes=', '').split('-');
|
|
223
|
+
const start = startStr ? parseInt(startStr, 10) : 0;
|
|
224
|
+
const end = endStr ? parseInt(endStr, 10) : stat.size - 1;
|
|
225
|
+
|
|
226
|
+
if (Number.isNaN(start) || Number.isNaN(end) || start > end || end >= stat.size) {
|
|
227
|
+
return new Response(null, {
|
|
228
|
+
status: 416,
|
|
229
|
+
headers: { 'Content-Range': `bytes */${stat.size}` }
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const nodeStream = fs.createReadStream(descriptor.filePath, { start, end });
|
|
234
|
+
return new Response(Readable.toWeb(nodeStream), {
|
|
235
|
+
status: 206,
|
|
236
|
+
headers: {
|
|
237
|
+
'Content-Type': contentType,
|
|
238
|
+
'Content-Length': String(end - start + 1),
|
|
239
|
+
'Content-Range': `bytes ${start}-${end}/${stat.size}`,
|
|
240
|
+
'Accept-Ranges': 'bytes',
|
|
241
|
+
ETag: etag
|
|
242
|
+
}
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const nodeStream = fs.createReadStream(descriptor.filePath);
|
|
247
|
+
return new Response(Readable.toWeb(nodeStream), {
|
|
248
|
+
status: 200,
|
|
249
|
+
headers: {
|
|
250
|
+
'Content-Type': contentType,
|
|
251
|
+
'Content-Length': String(stat.size),
|
|
252
|
+
'Accept-Ranges': 'bytes',
|
|
253
|
+
ETag: etag
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export async function* parseMultipartStream(webStream, contentType, opts = {}) {
|
|
259
|
+
const boundaryMatch = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType || '');
|
|
260
|
+
if (!boundaryMatch) {
|
|
261
|
+
throw Object.assign(new Error('Invalid multipart/form-data boundary'), { status: 400 });
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const boundary = boundaryMatch[1] || boundaryMatch[2].trim();
|
|
265
|
+
const firstDelimiter = Buffer.from(`--${boundary}`);
|
|
266
|
+
const nextDelimiter = Buffer.from(`\r\n--${boundary}`);
|
|
267
|
+
const headerEndSep = Buffer.from('\r\n\r\n');
|
|
268
|
+
const maxFileSize = parseBytes(opts.maxFileSize, Infinity);
|
|
269
|
+
|
|
270
|
+
const reader = webStream.getReader();
|
|
271
|
+
let buf = Buffer.alloc(0);
|
|
272
|
+
let eof = false;
|
|
273
|
+
|
|
274
|
+
async function pullMore() {
|
|
275
|
+
if (eof) return false;
|
|
276
|
+
const { done, value } = await reader.read();
|
|
277
|
+
if (done) {
|
|
278
|
+
eof = true;
|
|
279
|
+
return false;
|
|
280
|
+
}
|
|
281
|
+
buf = Buffer.concat([buf, Buffer.from(value)]);
|
|
282
|
+
return true;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
while (buf.indexOf(firstDelimiter) === -1) {
|
|
286
|
+
if (!(await pullMore())) return;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const startIdx = buf.indexOf(firstDelimiter) + firstDelimiter.length;
|
|
290
|
+
buf = buf.subarray(startIdx);
|
|
291
|
+
|
|
292
|
+
while (true) {
|
|
293
|
+
while (buf.length < 4 && !eof) await pullMore();
|
|
294
|
+
if (buf.subarray(0, 2).toString() === '--') break;
|
|
295
|
+
if (buf.subarray(0, 2).toString() === '\r\n') buf = buf.subarray(2);
|
|
296
|
+
|
|
297
|
+
while (buf.indexOf(headerEndSep) === -1) {
|
|
298
|
+
if (!(await pullMore())) return;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const headerEndIdx = buf.indexOf(headerEndSep);
|
|
302
|
+
const rawHeaders = buf.subarray(0, headerEndIdx).toString('utf8');
|
|
303
|
+
buf = buf.subarray(headerEndIdx + 4);
|
|
304
|
+
|
|
305
|
+
const dispMatch = /content-disposition:\s*form-data;([^\r\n]+)/i.exec(rawHeaders);
|
|
306
|
+
const nameMatch = dispMatch && /name="([^"]+)"/i.exec(dispMatch[1]);
|
|
307
|
+
const fileMatch = dispMatch && /filename="([^"]*)"/i.exec(dispMatch[1]);
|
|
308
|
+
const typeMatch = /content-type:\s*([^\r\n]+)/i.exec(rawHeaders);
|
|
309
|
+
|
|
310
|
+
const name = nameMatch ? nameMatch[1] : '';
|
|
311
|
+
const filename = fileMatch ? fileMatch[1] : null;
|
|
312
|
+
const partType = typeMatch ? typeMatch[1].trim() : 'text/plain';
|
|
313
|
+
const isFile = filename !== null;
|
|
314
|
+
|
|
315
|
+
let partDone = false;
|
|
316
|
+
let bytesRead = 0;
|
|
317
|
+
const guardLen = nextDelimiter.length + 4;
|
|
318
|
+
|
|
319
|
+
const partStream = new ReadableStream({
|
|
320
|
+
async pull(controller) {
|
|
321
|
+
if (partDone) {
|
|
322
|
+
controller.close();
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
while (true) {
|
|
327
|
+
const delimIdx = buf.indexOf(nextDelimiter);
|
|
328
|
+
if (delimIdx !== -1) {
|
|
329
|
+
const chunk = buf.subarray(0, delimIdx);
|
|
330
|
+
buf = buf.subarray(delimIdx + nextDelimiter.length);
|
|
331
|
+
partDone = true;
|
|
332
|
+
if (chunk.length > 0) {
|
|
333
|
+
bytesRead += chunk.length;
|
|
334
|
+
if (isFile && bytesRead > maxFileSize) {
|
|
335
|
+
const err = Object.assign(new Error('File exceeds maxFileSize'), { status: 413 });
|
|
336
|
+
controller.error(err);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
controller.enqueue(new Uint8Array(chunk));
|
|
340
|
+
}
|
|
341
|
+
controller.close();
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
if (buf.length > guardLen) {
|
|
346
|
+
const safeEnd = buf.length - guardLen;
|
|
347
|
+
const chunk = buf.subarray(0, safeEnd);
|
|
348
|
+
buf = buf.subarray(safeEnd);
|
|
349
|
+
bytesRead += chunk.length;
|
|
350
|
+
if (isFile && bytesRead > maxFileSize) {
|
|
351
|
+
const err = Object.assign(new Error('File exceeds maxFileSize'), { status: 413 });
|
|
352
|
+
controller.error(err);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
controller.enqueue(new Uint8Array(chunk));
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
if (!(await pullMore())) {
|
|
360
|
+
partDone = true;
|
|
361
|
+
if (buf.length > 0) {
|
|
362
|
+
controller.enqueue(new Uint8Array(buf));
|
|
363
|
+
buf = Buffer.alloc(0);
|
|
364
|
+
}
|
|
365
|
+
controller.close();
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
let consumed = false;
|
|
373
|
+
const consumeBuffer = async () => {
|
|
374
|
+
consumed = true;
|
|
375
|
+
const r = partStream.getReader();
|
|
376
|
+
const chunks = [];
|
|
377
|
+
while (true) {
|
|
378
|
+
const { done, value } = await r.read();
|
|
379
|
+
if (done) break;
|
|
380
|
+
chunks.push(Buffer.from(value));
|
|
381
|
+
}
|
|
382
|
+
return Buffer.concat(chunks);
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
const trackedStream = new ReadableStream({
|
|
386
|
+
async start(controller) {
|
|
387
|
+
consumed = true;
|
|
388
|
+
const r = partStream.getReader();
|
|
389
|
+
try {
|
|
390
|
+
while (true) {
|
|
391
|
+
const { done, value } = await r.read();
|
|
392
|
+
if (done) break;
|
|
393
|
+
controller.enqueue(value);
|
|
394
|
+
}
|
|
395
|
+
controller.close();
|
|
396
|
+
} catch (err) {
|
|
397
|
+
controller.error(err);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
yield {
|
|
403
|
+
name,
|
|
404
|
+
filename,
|
|
405
|
+
contentType: partType,
|
|
406
|
+
isFile,
|
|
407
|
+
isField: !isFile,
|
|
408
|
+
stream: trackedStream,
|
|
409
|
+
async text() {
|
|
410
|
+
return (await consumeBuffer()).toString('utf8');
|
|
411
|
+
},
|
|
412
|
+
async json() {
|
|
413
|
+
return JSON.parse((await consumeBuffer()).toString('utf8'));
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
if (!consumed) {
|
|
418
|
+
await consumeBuffer();
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
export function createLagMonitor(thresholdMs = 60) {
|
|
424
|
+
const histogram = monitorEventLoopDelay({ resolution: 20 });
|
|
425
|
+
histogram.enable();
|
|
426
|
+
return {
|
|
427
|
+
isOverloaded() {
|
|
428
|
+
const p95Ms = histogram.percentile(95) / 1e6;
|
|
429
|
+
histogram.reset();
|
|
430
|
+
return p95Ms > thresholdMs;
|
|
431
|
+
},
|
|
432
|
+
stop() {
|
|
433
|
+
histogram.disable();
|
|
434
|
+
}
|
|
435
|
+
};
|
|
436
|
+
}
|