@dim24/servin 0.0.1 → 0.2.2
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/README.md +1033 -1063
- package/example/index.js +1 -1
- package/index.js +1 -1
- package/package.json +1 -1
- package/src/server.js +257 -28
- package/src/servin.test.js +77 -261
- package/src/tree.js +216 -17
- package/src/utils.js +139 -16
- package/src/wire.js +21 -0
package/src/tree.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { StaticRouteDescriptor, RedirectDescriptor } from './utils.js';
|
|
2
|
+
|
|
1
3
|
const GUARD_META = Symbol('servin.guard');
|
|
2
4
|
const PARAM_META = Symbol('servin.param');
|
|
3
5
|
|
|
@@ -127,10 +129,12 @@ function attachMeta(branch, { addGuard, setParam }) {
|
|
|
127
129
|
return branch.apply(this, args);
|
|
128
130
|
};
|
|
129
131
|
}
|
|
132
|
+
} else if (branch instanceof StaticRouteDescriptor || branch instanceof RedirectDescriptor) {
|
|
133
|
+
target = Object.assign(Object.create(Object.getPrototypeOf(branch)), branch);
|
|
130
134
|
} else if (branch && typeof branch === 'object') {
|
|
131
135
|
target = { ...branch };
|
|
132
136
|
} else {
|
|
133
|
-
throw new TypeError('Branch must be a route object or handler function');
|
|
137
|
+
throw new TypeError('Branch must be a route object, descriptor, or handler function');
|
|
134
138
|
}
|
|
135
139
|
|
|
136
140
|
if (nextGuards.length > 0) {
|
|
@@ -164,6 +168,14 @@ export function param(rule, branch) {
|
|
|
164
168
|
return attachMeta(branch, { setParam: rule });
|
|
165
169
|
}
|
|
166
170
|
|
|
171
|
+
export function serveStatic(targetPath, options = {}) {
|
|
172
|
+
return new StaticRouteDescriptor(targetPath, options);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function redirect(target, status = 301) {
|
|
176
|
+
return new RedirectDescriptor(target, status);
|
|
177
|
+
}
|
|
178
|
+
|
|
167
179
|
function parseVerbKey(key) {
|
|
168
180
|
if (key === 'ws') return ['WS'];
|
|
169
181
|
const parts = key.split('|').map((s) => s.trim().toUpperCase());
|
|
@@ -191,10 +203,63 @@ function classifySegment(seg, customTypes = {}, paramRule = null) {
|
|
|
191
203
|
return { type: 'static', priority: 0, value: seg, parse: null, raw: seg };
|
|
192
204
|
}
|
|
193
205
|
|
|
194
|
-
export function compileDomainTree(apiRoot = {}, customTypes = {}) {
|
|
206
|
+
export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig = null) {
|
|
195
207
|
const routes = [];
|
|
196
208
|
let nodeCounter = 0;
|
|
197
209
|
|
|
210
|
+
function registerStaticDescriptor(descriptor, baseSegments, dotPath, inheritedGuards, inheritedMeta, isRootFallback = false) {
|
|
211
|
+
const wildSeg = {
|
|
212
|
+
type: 'wild',
|
|
213
|
+
priority: isRootFallback ? 4 : 3,
|
|
214
|
+
param: 'subpath',
|
|
215
|
+
optionalWild: true,
|
|
216
|
+
parse: null,
|
|
217
|
+
raw: '$subpath'
|
|
218
|
+
};
|
|
219
|
+
const fullSegments = [...baseSegments, wildSeg];
|
|
220
|
+
const paramNames = fullSegments.filter((s) => s.type !== 'static').map((s) => s.param);
|
|
221
|
+
const descGuards = [...inheritedGuards, ...(descriptor[GUARD_META] || [])];
|
|
222
|
+
|
|
223
|
+
routes.push({
|
|
224
|
+
nodeId: `static_${++nodeCounter}`,
|
|
225
|
+
dotPath: dotPath.join('.'),
|
|
226
|
+
segments: fullSegments,
|
|
227
|
+
paramNames,
|
|
228
|
+
verbs: ['GET', 'HEAD'],
|
|
229
|
+
staticDescriptor: descriptor,
|
|
230
|
+
handler: null,
|
|
231
|
+
isAsyncGen: false,
|
|
232
|
+
guards: descGuards,
|
|
233
|
+
meta: inheritedMeta,
|
|
234
|
+
nodeCache: null,
|
|
235
|
+
ancestorCaches: [],
|
|
236
|
+
nodeInFlight: null,
|
|
237
|
+
nodeIdempotency: null
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function registerRedirectDescriptor(descriptor, fullSegments, dotPath, inheritedGuards, inheritedMeta, verbs = ['GET', 'HEAD']) {
|
|
242
|
+
const paramNames = fullSegments.filter((s) => s.type !== 'static').map((s) => s.param);
|
|
243
|
+
const descGuards = [...inheritedGuards, ...(descriptor[GUARD_META] || [])];
|
|
244
|
+
|
|
245
|
+
routes.push({
|
|
246
|
+
nodeId: `redirect_${++nodeCounter}`,
|
|
247
|
+
dotPath: dotPath.join('.'),
|
|
248
|
+
segments: fullSegments,
|
|
249
|
+
paramNames,
|
|
250
|
+
verbs,
|
|
251
|
+
redirectDescriptor: descriptor,
|
|
252
|
+
handler: null,
|
|
253
|
+
isAsyncGen: false,
|
|
254
|
+
guards: descGuards,
|
|
255
|
+
meta: inheritedMeta,
|
|
256
|
+
nodeCache: null,
|
|
257
|
+
ancestorCaches: [],
|
|
258
|
+
nodeInFlight: null,
|
|
259
|
+
nodeIdempotency: null
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
|
|
198
263
|
function walk(node, segments, dotPath, inheritedGuards, inheritedMeta, ancestorCaches) {
|
|
199
264
|
if (!node || typeof node !== 'object') return;
|
|
200
265
|
|
|
@@ -211,10 +276,19 @@ export function compileDomainTree(apiRoot = {}, customTypes = {}) {
|
|
|
211
276
|
const nodeInFlight = meta.coalesce ? new Map() : null;
|
|
212
277
|
const nodeIdempotency = meta.idempotent ? new Map() : null;
|
|
213
278
|
|
|
279
|
+
const hasExplicitDynamicChild = Object.keys(node).some(
|
|
280
|
+
(k) => !META_KEYS.has(k) && k.startsWith('$')
|
|
281
|
+
);
|
|
282
|
+
|
|
214
283
|
for (const [key, value] of Object.entries(node)) {
|
|
215
284
|
if (META_KEYS.has(key)) continue;
|
|
216
285
|
|
|
217
286
|
const verbs = parseVerbKey(key);
|
|
287
|
+
if (verbs && value instanceof RedirectDescriptor) {
|
|
288
|
+
registerRedirectDescriptor(value, segments, [...dotPath, key], guards, meta, verbs);
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
|
|
218
292
|
if (verbs && typeof value === 'function') {
|
|
219
293
|
const paramNames = segments.filter((s) => s.type !== 'static').map((s) => s.param);
|
|
220
294
|
routes.push({
|
|
@@ -232,11 +306,50 @@ export function compileDomainTree(apiRoot = {}, customTypes = {}) {
|
|
|
232
306
|
nodeInFlight,
|
|
233
307
|
nodeIdempotency
|
|
234
308
|
});
|
|
309
|
+
|
|
310
|
+
if (!hasExplicitDynamicChild) {
|
|
311
|
+
const directChildSeg = {
|
|
312
|
+
type: 'wild',
|
|
313
|
+
priority: 5,
|
|
314
|
+
param: 'id',
|
|
315
|
+
optionalWild: true,
|
|
316
|
+
directNodeParam: true,
|
|
317
|
+
parse: null,
|
|
318
|
+
raw: '$direct'
|
|
319
|
+
};
|
|
320
|
+
routes.push({
|
|
321
|
+
nodeId: `${nodeId}_direct_${key}`,
|
|
322
|
+
dotPath: [...dotPath, key].join('.'),
|
|
323
|
+
segments: [...segments, directChildSeg],
|
|
324
|
+
paramNames: [],
|
|
325
|
+
verbs,
|
|
326
|
+
handler: value,
|
|
327
|
+
isAsyncGen: value instanceof AsyncGeneratorFunction,
|
|
328
|
+
guards,
|
|
329
|
+
meta,
|
|
330
|
+
nodeCache,
|
|
331
|
+
ancestorCaches,
|
|
332
|
+
nodeInFlight,
|
|
333
|
+
nodeIdempotency
|
|
334
|
+
});
|
|
335
|
+
}
|
|
235
336
|
continue;
|
|
236
337
|
}
|
|
237
338
|
|
|
238
339
|
const paramRule = value?.[PARAM_META] ?? null;
|
|
239
340
|
|
|
341
|
+
if (value instanceof StaticRouteDescriptor) {
|
|
342
|
+
const seg = classifySegment(key, customTypes, paramRule);
|
|
343
|
+
registerStaticDescriptor(value, [...segments, seg], [...dotPath, key], guards, meta);
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
if (value instanceof RedirectDescriptor) {
|
|
348
|
+
const seg = classifySegment(key, customTypes, paramRule);
|
|
349
|
+
registerRedirectDescriptor(value, [...segments, seg], [...dotPath, key], guards, meta);
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
|
|
240
353
|
if (typeof value === 'function') {
|
|
241
354
|
const seg = classifySegment(key, customTypes, paramRule);
|
|
242
355
|
const childSegments = [...segments, seg];
|
|
@@ -270,6 +383,26 @@ export function compileDomainTree(apiRoot = {}, customTypes = {}) {
|
|
|
270
383
|
|
|
271
384
|
walk(apiRoot, [], [], [], {}, []);
|
|
272
385
|
|
|
386
|
+
if (staticConfig) {
|
|
387
|
+
if (typeof staticConfig === 'string' || staticConfig instanceof StaticRouteDescriptor) {
|
|
388
|
+
const desc = staticConfig instanceof StaticRouteDescriptor
|
|
389
|
+
? staticConfig
|
|
390
|
+
: new StaticRouteDescriptor(staticConfig);
|
|
391
|
+
registerStaticDescriptor(desc, [], ['static'], [], {}, true);
|
|
392
|
+
} else if (typeof staticConfig === 'object') {
|
|
393
|
+
for (const [mountPrefix, target] of Object.entries(staticConfig)) {
|
|
394
|
+
const desc = target instanceof StaticRouteDescriptor
|
|
395
|
+
? target
|
|
396
|
+
: new StaticRouteDescriptor(target);
|
|
397
|
+
const cleanPrefix = mountPrefix.replace(/^\/+|\/+$/g, '');
|
|
398
|
+
const prefixSegs = cleanPrefix
|
|
399
|
+
? cleanPrefix.split('/').map((s) => classifySegment(s, customTypes))
|
|
400
|
+
: [];
|
|
401
|
+
registerStaticDescriptor(desc, prefixSegs, ['static', ...prefixSegs.map((s) => s.raw)], [], {}, prefixSegs.length === 0);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
273
406
|
routes.sort((a, b) => {
|
|
274
407
|
const minLen = Math.min(a.segments.length, b.segments.length);
|
|
275
408
|
for (let i = 0; i < minLen; i++) {
|
|
@@ -295,7 +428,25 @@ export function matchDomainRoute(routes, method, pathname) {
|
|
|
295
428
|
for (let i = 0; i < route.segments.length; i++) {
|
|
296
429
|
const seg = route.segments[i];
|
|
297
430
|
if (seg.type === 'wild') {
|
|
298
|
-
|
|
431
|
+
if (i >= parts.length && !seg.optionalWild) {
|
|
432
|
+
matched = false;
|
|
433
|
+
break;
|
|
434
|
+
}
|
|
435
|
+
try {
|
|
436
|
+
const decodedParts = parts.slice(i).map(decodeURIComponent);
|
|
437
|
+
if (seg.directNodeParam) {
|
|
438
|
+
if (decodedParts.length === 1) {
|
|
439
|
+
params.id = decodedParts[0];
|
|
440
|
+
} else if (decodedParts.length > 1) {
|
|
441
|
+
params.rest = decodedParts;
|
|
442
|
+
params.id = decodedParts[0];
|
|
443
|
+
}
|
|
444
|
+
} else {
|
|
445
|
+
params[seg.param] = decodedParts.join('/');
|
|
446
|
+
}
|
|
447
|
+
} catch {
|
|
448
|
+
matched = false;
|
|
449
|
+
}
|
|
299
450
|
break;
|
|
300
451
|
}
|
|
301
452
|
if (i >= parts.length) {
|
|
@@ -348,21 +499,35 @@ export function matchDomainRoute(routes, method, pathname) {
|
|
|
348
499
|
}
|
|
349
500
|
|
|
350
501
|
export function generateVirtualClientModule(routes) {
|
|
351
|
-
const manifest = routes
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
502
|
+
const manifest = routes
|
|
503
|
+
.filter((r) => !r.staticDescriptor && !r.redirectDescriptor)
|
|
504
|
+
.map((r) => ({
|
|
505
|
+
dotPath: r.dotPath,
|
|
506
|
+
verbs: r.verbs,
|
|
507
|
+
isAsyncGen: r.isAsyncGen
|
|
508
|
+
}));
|
|
356
509
|
|
|
357
510
|
return `// Auto-generated Zero-Build Virtual ESM Client by servin
|
|
358
511
|
const MANIFEST = ${JSON.stringify(manifest, null, 2)};
|
|
359
512
|
const ORIGIN = new URL(import.meta.url).origin;
|
|
513
|
+
const HTTP_VERBS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
360
514
|
|
|
361
515
|
function parseMethod(key) {
|
|
362
516
|
if (key === 'ws') return 'WS';
|
|
363
517
|
const upper = key.split('|')[0].toUpperCase();
|
|
364
|
-
|
|
365
|
-
|
|
518
|
+
return HTTP_VERBS.has(upper) ? upper : null;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function isOptionsBag(arg) {
|
|
522
|
+
return Boolean(
|
|
523
|
+
arg &&
|
|
524
|
+
typeof arg === 'object' &&
|
|
525
|
+
!Array.isArray(arg) &&
|
|
526
|
+
!(arg instanceof FormData) &&
|
|
527
|
+
!(arg instanceof URLSearchParams) &&
|
|
528
|
+
!(arg instanceof Blob) &&
|
|
529
|
+
Object.prototype.hasOwnProperty.call(arg, 'headers')
|
|
530
|
+
);
|
|
366
531
|
}
|
|
367
532
|
|
|
368
533
|
function createNode(chain) {
|
|
@@ -438,11 +603,43 @@ function createNode(chain) {
|
|
|
438
603
|
};
|
|
439
604
|
}
|
|
440
605
|
|
|
606
|
+
let customHeaders = {};
|
|
607
|
+
let payload;
|
|
608
|
+
let queryObj;
|
|
609
|
+
|
|
441
610
|
const hasBody = method === 'POST' || method === 'PUT' || method === 'PATCH';
|
|
442
|
-
const payload = hasBody ? argQueue.shift() : undefined;
|
|
443
|
-
const queryObj = argQueue.shift();
|
|
444
|
-
const url = new URL(ORIGIN + pathname);
|
|
445
611
|
|
|
612
|
+
if (hasBody) {
|
|
613
|
+
const first = argQueue.shift();
|
|
614
|
+
if (isOptionsBag(first)) {
|
|
615
|
+
customHeaders = { ...first.headers };
|
|
616
|
+
payload = first.body !== undefined ? first.body : argQueue.shift();
|
|
617
|
+
queryObj = first.query !== undefined ? first.query : argQueue.shift();
|
|
618
|
+
} else {
|
|
619
|
+
payload = first;
|
|
620
|
+
const second = argQueue.shift();
|
|
621
|
+
if (isOptionsBag(second)) {
|
|
622
|
+
customHeaders = { ...second.headers };
|
|
623
|
+
queryObj = second.query !== undefined ? second.query : argQueue.shift();
|
|
624
|
+
} else {
|
|
625
|
+
queryObj = second;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
} else {
|
|
629
|
+
const first = argQueue.shift();
|
|
630
|
+
if (isOptionsBag(first)) {
|
|
631
|
+
customHeaders = { ...first.headers };
|
|
632
|
+
queryObj = first.query !== undefined ? first.query : argQueue.shift();
|
|
633
|
+
} else {
|
|
634
|
+
queryObj = first;
|
|
635
|
+
const second = argQueue.shift();
|
|
636
|
+
if (isOptionsBag(second)) {
|
|
637
|
+
customHeaders = { ...second.headers };
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
const url = new URL(ORIGIN + pathname);
|
|
446
643
|
if (queryObj && typeof queryObj === 'object') {
|
|
447
644
|
for (const [k, v] of Object.entries(queryObj)) {
|
|
448
645
|
if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
|
|
@@ -453,7 +650,7 @@ function createNode(chain) {
|
|
|
453
650
|
return (async function* () {
|
|
454
651
|
const res = await fetch(url, {
|
|
455
652
|
method,
|
|
456
|
-
headers: { Accept: 'text/event-stream' },
|
|
653
|
+
headers: { Accept: 'text/event-stream', ...customHeaders },
|
|
457
654
|
credentials: 'include'
|
|
458
655
|
});
|
|
459
656
|
if (!res.ok) throw Object.assign(new Error(await res.text()), { status: res.status });
|
|
@@ -475,11 +672,13 @@ function createNode(chain) {
|
|
|
475
672
|
}
|
|
476
673
|
|
|
477
674
|
return (async () => {
|
|
478
|
-
const headers = {};
|
|
675
|
+
const headers = { ...customHeaders };
|
|
479
676
|
let body;
|
|
480
677
|
if (hasBody && payload !== undefined) {
|
|
481
|
-
headers
|
|
482
|
-
|
|
678
|
+
if (!Object.keys(headers).some((k) => k.toLowerCase() === 'content-type')) {
|
|
679
|
+
headers['Content-Type'] = 'application/json';
|
|
680
|
+
}
|
|
681
|
+
body = typeof payload === 'string' ? payload : JSON.stringify(payload);
|
|
483
682
|
}
|
|
484
683
|
const res = await fetch(url, { method, headers, body, credentials: 'include' });
|
|
485
684
|
if (res.status === 204) return null;
|
package/src/utils.js
CHANGED
|
@@ -17,6 +17,10 @@ const MIME_TYPES = {
|
|
|
17
17
|
'.jpeg': 'image/jpeg',
|
|
18
18
|
'.webp': 'image/webp',
|
|
19
19
|
'.gif': 'image/gif',
|
|
20
|
+
'.ico': 'image/x-icon',
|
|
21
|
+
'.woff': 'font/woff',
|
|
22
|
+
'.woff2': 'font/woff2',
|
|
23
|
+
'.ttf': 'font/ttf',
|
|
20
24
|
'.pdf': 'application/pdf',
|
|
21
25
|
'.mp4': 'video/mp4',
|
|
22
26
|
'.webm': 'video/webm',
|
|
@@ -32,7 +36,6 @@ const HTML_ESCAPE_MAP = {
|
|
|
32
36
|
'"': '"',
|
|
33
37
|
"\'": '\''
|
|
34
38
|
};
|
|
35
|
-
// test mark error
|
|
36
39
|
|
|
37
40
|
export function escapeHtml(value) {
|
|
38
41
|
if (value === null || value === undefined) return '';
|
|
@@ -51,6 +54,30 @@ export class FileStreamResponse {
|
|
|
51
54
|
}
|
|
52
55
|
}
|
|
53
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
|
+
|
|
54
81
|
export function parseDuration(input, fallbackMs = 0) {
|
|
55
82
|
if (typeof input === 'number') return input;
|
|
56
83
|
if (typeof input !== 'string') return fallbackMs;
|
|
@@ -194,23 +221,36 @@ export function validateExpect(payload, schema, basePath = '') {
|
|
|
194
221
|
return errors;
|
|
195
222
|
}
|
|
196
223
|
|
|
197
|
-
export async function buildFileHttpResponse(descriptor, reqHeaders) {
|
|
224
|
+
export async function buildFileHttpResponse(descriptor, reqHeaders, opts = {}) {
|
|
198
225
|
let stat;
|
|
199
226
|
try {
|
|
200
227
|
stat = await fsp.stat(descriptor.filePath);
|
|
201
228
|
} catch {
|
|
229
|
+
if (opts.returnMissing) return null;
|
|
202
230
|
return Response.json({ error: 'File Not Found' }, { status: 404 });
|
|
203
231
|
}
|
|
204
232
|
|
|
205
233
|
if (!stat.isFile()) {
|
|
234
|
+
if (opts.returnMissing) return null;
|
|
206
235
|
return Response.json({ error: 'Not a file' }, { status: 404 });
|
|
207
236
|
}
|
|
208
237
|
|
|
238
|
+
const isHead = opts.method === 'HEAD';
|
|
239
|
+
const baseStatus = opts.statusOverride || 200;
|
|
209
240
|
const etag = `W/"${stat.size}-${Math.floor(stat.mtimeMs)}"`;
|
|
210
|
-
|
|
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) {
|
|
211
251
|
return new Response(null, {
|
|
212
252
|
status: 304,
|
|
213
|
-
headers:
|
|
253
|
+
headers: commonHeaders
|
|
214
254
|
});
|
|
215
255
|
}
|
|
216
256
|
|
|
@@ -218,7 +258,7 @@ export async function buildFileHttpResponse(descriptor, reqHeaders) {
|
|
|
218
258
|
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
|
|
219
259
|
const rangeHeader = reqHeaders.get('range');
|
|
220
260
|
|
|
221
|
-
if (rangeHeader && rangeHeader.startsWith('bytes=')) {
|
|
261
|
+
if (!opts.statusOverride && rangeHeader && rangeHeader.startsWith('bytes=')) {
|
|
222
262
|
const [startStr, endStr] = rangeHeader.replace('bytes=', '').split('-');
|
|
223
263
|
const start = startStr ? parseInt(startStr, 10) : 0;
|
|
224
264
|
const end = endStr ? parseInt(endStr, 10) : stat.size - 1;
|
|
@@ -230,31 +270,114 @@ export async function buildFileHttpResponse(descriptor, reqHeaders) {
|
|
|
230
270
|
});
|
|
231
271
|
}
|
|
232
272
|
|
|
233
|
-
const
|
|
234
|
-
return new Response(
|
|
273
|
+
const body = isHead ? null : Readable.toWeb(fs.createReadStream(descriptor.filePath, { start, end }));
|
|
274
|
+
return new Response(body, {
|
|
235
275
|
status: 206,
|
|
236
276
|
headers: {
|
|
277
|
+
...commonHeaders,
|
|
237
278
|
'Content-Type': contentType,
|
|
238
279
|
'Content-Length': String(end - start + 1),
|
|
239
|
-
'Content-Range': `bytes ${start}-${end}/${stat.size}
|
|
240
|
-
'Accept-Ranges': 'bytes',
|
|
241
|
-
ETag: etag
|
|
280
|
+
'Content-Range': `bytes ${start}-${end}/${stat.size}`
|
|
242
281
|
}
|
|
243
282
|
});
|
|
244
283
|
}
|
|
245
284
|
|
|
246
|
-
const
|
|
247
|
-
return new Response(
|
|
248
|
-
status:
|
|
285
|
+
const body = isHead ? null : Readable.toWeb(fs.createReadStream(descriptor.filePath));
|
|
286
|
+
return new Response(body, {
|
|
287
|
+
status: baseStatus,
|
|
249
288
|
headers: {
|
|
289
|
+
...commonHeaders,
|
|
250
290
|
'Content-Type': contentType,
|
|
251
|
-
'Content-Length': String(stat.size)
|
|
252
|
-
'Accept-Ranges': 'bytes',
|
|
253
|
-
ETag: etag
|
|
291
|
+
'Content-Length': String(stat.size)
|
|
254
292
|
}
|
|
255
293
|
});
|
|
256
294
|
}
|
|
257
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
|
+
|
|
258
381
|
export async function* parseMultipartStream(webStream, contentType, opts = {}) {
|
|
259
382
|
const boundaryMatch = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType || '');
|
|
260
383
|
if (!boundaryMatch) {
|
package/src/wire.js
CHANGED
|
@@ -36,6 +36,13 @@ export class ServinAbortError extends Error {
|
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
export class ServinRedirect {
|
|
40
|
+
constructor(location, status = 302) {
|
|
41
|
+
this.location = String(location);
|
|
42
|
+
this.status = Number(status) || 302;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
39
46
|
function renderInterpolated(val) {
|
|
40
47
|
if (val instanceof HtmlResponse) return val.html;
|
|
41
48
|
if (Array.isArray(val)) return val.map(renderInterpolated).join('');
|
|
@@ -46,6 +53,7 @@ export function createRequestContext({
|
|
|
46
53
|
req,
|
|
47
54
|
method,
|
|
48
55
|
url,
|
|
56
|
+
params,
|
|
49
57
|
signal,
|
|
50
58
|
sessionManager,
|
|
51
59
|
broker,
|
|
@@ -77,6 +85,7 @@ export function createRequestContext({
|
|
|
77
85
|
req,
|
|
78
86
|
method: (method || req?.method || 'GET').toUpperCase(),
|
|
79
87
|
url: url || (req ? new URL(req.url) : new URL('http://localhost/')),
|
|
88
|
+
params: params || {},
|
|
80
89
|
signal: signal || req?.signal || new AbortController().signal,
|
|
81
90
|
headersProxy,
|
|
82
91
|
outgoingHeaders,
|
|
@@ -140,6 +149,12 @@ export const wire = {
|
|
|
140
149
|
get url() {
|
|
141
150
|
return getCtx().url;
|
|
142
151
|
},
|
|
152
|
+
get params() {
|
|
153
|
+
return getCtx().params;
|
|
154
|
+
},
|
|
155
|
+
param(name) {
|
|
156
|
+
return getCtx().params?.[name];
|
|
157
|
+
},
|
|
143
158
|
get headers() {
|
|
144
159
|
return getCtx().headersProxy;
|
|
145
160
|
},
|
|
@@ -157,6 +172,12 @@ export const wire = {
|
|
|
157
172
|
abort(status = 400, message = 'Aborted') {
|
|
158
173
|
throw new ServinAbortError(status, message);
|
|
159
174
|
},
|
|
175
|
+
redirect(location, status = 302) {
|
|
176
|
+
if (!location) {
|
|
177
|
+
throw new TypeError('wire.redirect(location, status) requires a target URL or path');
|
|
178
|
+
}
|
|
179
|
+
throw new ServinRedirect(location, status);
|
|
180
|
+
},
|
|
160
181
|
undo(fn) {
|
|
161
182
|
if (typeof fn === 'function') {
|
|
162
183
|
getCtx().undoStack.push(fn);
|