@celljs/serve-static 4.1.0 → 4.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 (40) hide show
  1. package/README.md +5 -1
  2. package/esm/node/embedded-assets.js +2 -4
  3. package/esm/node/embedded-assets.js.map +1 -1
  4. package/esm/node/mime.d.ts +6 -0
  5. package/esm/node/mime.js +28 -0
  6. package/esm/node/mime.js.map +1 -0
  7. package/esm/node/module.d.ts +1 -1
  8. package/esm/node/serve-static-middleware.js +3 -2
  9. package/esm/node/serve-static-middleware.js.map +1 -1
  10. package/esm/node/serve-static.d.ts +9 -2
  11. package/esm/node/serve-static.js +256 -64
  12. package/esm/node/serve-static.js.map +1 -1
  13. package/lib/node/embedded-assets.d.ts.map +1 -1
  14. package/lib/node/embedded-assets.js +2 -7
  15. package/lib/node/embedded-assets.js.map +1 -1
  16. package/lib/node/mime.d.ts +7 -0
  17. package/lib/node/mime.d.ts.map +1 -0
  18. package/lib/node/mime.js +31 -0
  19. package/lib/node/mime.js.map +1 -0
  20. package/lib/node/module.d.ts +1 -1
  21. package/lib/node/serve-static-middleware.d.ts.map +1 -1
  22. package/lib/node/serve-static-middleware.js +2 -1
  23. package/lib/node/serve-static-middleware.js.map +1 -1
  24. package/lib/node/serve-static-middleware.spec.js +1 -1
  25. package/lib/node/serve-static-middleware.spec.js.map +1 -1
  26. package/lib/node/serve-static.d.ts +9 -2
  27. package/lib/node/serve-static.d.ts.map +1 -1
  28. package/lib/node/serve-static.js +257 -68
  29. package/lib/node/serve-static.js.map +1 -1
  30. package/lib/node/serve-static.spec.d.ts +2 -0
  31. package/lib/node/serve-static.spec.d.ts.map +1 -0
  32. package/lib/node/serve-static.spec.js +139 -0
  33. package/lib/node/serve-static.spec.js.map +1 -0
  34. package/package.json +7 -8
  35. package/src/node/embedded-assets.ts +3 -5
  36. package/src/node/mime.ts +27 -0
  37. package/src/node/serve-static-middleware.spec.ts +2 -2
  38. package/src/node/serve-static-middleware.ts +4 -3
  39. package/src/node/serve-static.spec.ts +151 -0
  40. package/src/node/serve-static.ts +258 -74
@@ -1,24 +1,81 @@
1
1
  import type { ServeStaticOption } from './type';
2
- import send from 'send';
3
- import { resolve } from 'path';
4
- /* eslint-disable @typescript-eslint/ban-ts-comment */
2
+ import { createReadStream, stat, Stats } from 'fs';
3
+ import { join, normalize, resolve, sep } from 'path';
4
+ import { HttpError } from '@celljs/web/lib/node';
5
+ import { MimeUtil } from './mime';
5
6
 
6
- export const serveStatic = (root: string, opts: ServeStaticOption) => {
7
+ type Next = (err?: unknown) => void;
7
8
 
8
- const { fallthrough = true, baseHref, setHeaders, redirect } = opts;
9
- const onDirectory = redirect ?
10
- createRedirectDirectoryListener :
11
- createNotFoundDirectoryListener;
9
+ const UP_PATH = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
10
+ const ONE_YEAR = 31536000000;
11
+
12
+ function parseTokens(value: string): string[] {
13
+ return value.split(',').map(token => token.trim()).filter(Boolean);
14
+ }
15
+
16
+ /** `bytes=0-99` → the ranges asked for, joined where they touch; -1 when none can be served, -2 when malformed. */
17
+ function parseRange(size: number, header: string): { start: number, end: number }[] | -1 | -2 {
18
+ const equals = header.indexOf('=');
19
+ if (equals < 0) {
20
+ return -2;
21
+ }
22
+ const ranges: { start: number, end: number }[] = [];
23
+ for (const part of header.slice(equals + 1).split(',')) {
24
+ const [startText, endText] = part.trim().split('-');
25
+ let start = parseInt(startText, 10);
26
+ let end = parseInt(endText, 10);
27
+ if (isNaN(start)) {
28
+ start = size - end;
29
+ end = size - 1;
30
+ } else if (isNaN(end) || end > size - 1) {
31
+ end = size - 1;
32
+ }
33
+ if (isNaN(start) || isNaN(end) || start > end || start < 0) {
34
+ continue;
35
+ }
36
+ ranges.push({ start, end });
37
+ }
38
+ if (ranges.length === 0) {
39
+ return -1;
40
+ }
41
+ ranges.sort((a, b) => a.start - b.start);
42
+ const combined = [ranges[0]];
43
+ for (const range of ranges.slice(1)) {
44
+ const last = combined[combined.length - 1];
45
+ if (range.start > last.end + 1) {
46
+ combined.push(range);
47
+ } else if (range.end > last.end) {
48
+ last.end = range.end;
49
+ }
50
+ }
51
+ return combined;
52
+ }
12
53
 
13
- opts.root = resolve(root);
54
+ /**
55
+ * Serves files under `root` with the options and behavior of the `send` package: Content-Type, ETag,
56
+ * Last-Modified, Cache-Control, 304 for fresh requests, 412 for failed preconditions, single byte ranges,
57
+ * `index` files, `extensions`, and dotfiles ignored by default. `next()` is called when there is no
58
+ * file to send, `next(err)` when sending fails.
59
+ */
60
+ export const serveStatic = (root: string, opts: ServeStaticOption & Record<string, any>) => {
61
+ const { fallthrough = true, baseHref, setHeaders, redirect } = opts;
62
+ root = resolve(root);
63
+ const index: string[] = opts.index === false ? [] : opts.index === undefined ? ['index.html'] : ([] as string[]).concat(opts.index);
64
+ const extensions: string[] = opts.extensions || [];
65
+ const dotfiles = opts.dotfiles ?? 'ignore';
66
+ const acceptRanges = opts.acceptRanges !== false;
67
+ const cacheControl = opts.cacheControl !== false;
68
+ const etag = opts.etag !== false;
69
+ const lastModified = opts.lastModified !== false;
70
+ const maxAge = Math.floor(Math.min(Math.max(0, Number(opts.maxAge ?? opts.maxage ?? 0) || 0), ONE_YEAR) / 1000);
71
+ const cacheControlValue = `public, max-age=${maxAge}${opts.immutable ? ', immutable' : ''}`;
14
72
 
15
73
  /** `url` (default `req.url`) is what to serve; the SPA fallback passes `/index.html` without changing the request. */
16
- return (req: any, res: any, next: Function, url: string = req.url) => {
74
+ return (req: any, res: any, next: Next, url: string = req.url) => {
17
75
  if (req.method !== 'GET' && req.method !== 'HEAD') {
18
76
  if (fallthrough) {
19
77
  return next();
20
78
  }
21
- // method not allowed
22
79
  res.statusCode = 405;
23
80
  res.setHeader('Allow', 'GET, HEAD');
24
81
  res.setHeader('Content-Length', '0');
@@ -26,83 +83,210 @@ export const serveStatic = (root: string, opts: ServeStaticOption) => {
26
83
  next();
27
84
  return;
28
85
  }
86
+ const fail = (status: number, cause?: unknown) => {
87
+ if (!fallthrough || status >= 500) {
88
+ const error = new HttpError(status, cause instanceof Error ? cause.message : undefined);
89
+ next(error);
90
+ } else {
91
+ next();
92
+ }
93
+ };
29
94
 
30
- let forwardError = !fallthrough;
95
+ const target = new URL(url.replace(baseHref, '/'), 'http://localhost');
96
+ let path: string;
97
+ try {
98
+ path = decodeURIComponent(target.pathname);
99
+ } catch {
100
+ return fail(400);
101
+ }
102
+ if (path.includes('\0')) {
103
+ return fail(400);
104
+ }
105
+ if (UP_PATH.test(normalize(`.${sep}${path}`))) {
106
+ return fail(403);
107
+ }
108
+ const relative = normalize(path).split(/[\\/]/);
109
+ if (relative.some(segment => segment.length > 1 && segment[0] === '.')) {
110
+ if (dotfiles === 'deny') {
111
+ return fail(403);
112
+ }
113
+ if (dotfiles !== 'allow') {
114
+ return fail(404);
115
+ }
116
+ }
117
+ const file = join(root, path);
31
118
 
32
- const target: URL = new URL(`${url.replace(baseHref, '/')}`, `http://${req.headers.host}`);
119
+ const sendFile = (filePath: string, stats: Stats) => {
120
+ if (res.headersSent) {
121
+ return fail(500, new Error('Can\'t set headers after they are sent.'));
122
+ }
123
+ setHeaders?.(res, filePath, stats);
124
+ if (acceptRanges && !res.getHeader('Accept-Ranges')) {
125
+ res.setHeader('Accept-Ranges', 'bytes');
126
+ }
127
+ if (cacheControl && !res.getHeader('Cache-Control')) {
128
+ res.setHeader('Cache-Control', cacheControlValue);
129
+ }
130
+ if (lastModified && !res.getHeader('Last-Modified')) {
131
+ res.setHeader('Last-Modified', stats.mtime.toUTCString());
132
+ }
133
+ if (etag && !res.getHeader('ETag')) {
134
+ res.setHeader('ETag', `W/"${stats.size.toString(16)}-${stats.mtime.getTime().toString(16)}"`);
135
+ }
136
+ if (!res.getHeader('Content-Type')) {
137
+ res.setHeader('Content-Type', MimeUtil.contentType(filePath));
138
+ }
139
+ const headers = req.headers;
140
+ if (headers['if-match'] || headers['if-unmodified-since'] || headers['if-none-match'] || headers['if-modified-since']) {
141
+ if (isPreconditionFailure(headers, res)) {
142
+ return end(412);
143
+ }
144
+ if (isFresh(headers, res)) {
145
+ for (const name of ['Content-Encoding', 'Content-Language', 'Content-Length', 'Content-Range', 'Content-Type']) {
146
+ res.removeHeader(name);
147
+ }
148
+ return end(304);
149
+ }
150
+ }
151
+ let start = 0;
152
+ let length = stats.size;
153
+ res.statusCode = 200;
154
+ const range = headers.range;
155
+ if (acceptRanges && range && /^ *bytes=/.test(range)) {
156
+ const ranges = isRangeFresh(headers, res) ? parseRange(stats.size, range) : -2;
157
+ if (ranges === -1) {
158
+ res.setHeader('Content-Range', `bytes */${stats.size}`);
159
+ return end(416);
160
+ }
161
+ if (ranges !== -2 && ranges.length === 1) {
162
+ res.statusCode = 206;
163
+ res.setHeader('Content-Range', `bytes ${ranges[0].start}-${ranges[0].end}/${stats.size}`);
164
+ start = ranges[0].start;
165
+ length = ranges[0].end - start + 1;
166
+ }
167
+ }
168
+ res.setHeader('Content-Length', length);
169
+ if (req.method === 'HEAD' || length === 0) {
170
+ res.end();
171
+ return;
172
+ }
173
+ // The client may have gone while the file was looked up.
174
+ if (res.destroyed) {
175
+ return;
176
+ }
177
+ const stream = createReadStream(filePath, { start, end: start + length - 1 });
178
+ stream.once('error', (err: Error) => {
179
+ stream.destroy();
180
+ if (res.headersSent) {
181
+ res.destroy(err);
182
+ } else {
183
+ next(err);
184
+ }
185
+ });
186
+ res.once('close', () => stream.destroy());
187
+ stream.pipe(res);
188
+ };
33
189
 
34
- const stream = send(req, target.pathname, opts) as any;
190
+ const end = (status: number) => {
191
+ res.statusCode = status;
192
+ res.end();
193
+ };
35
194
 
36
- stream.on('directory', onDirectory(target));
195
+ const sendIndex = (i: number) => {
196
+ if (i >= index.length) {
197
+ return fail(404);
198
+ }
199
+ const indexPath = join(file, index[i]);
200
+ stat(indexPath, (err: NodeJS.ErrnoException | null, stats: Stats) => err || stats.isDirectory() ? sendIndex(i + 1) : sendFile(indexPath, stats));
201
+ };
37
202
 
38
- if (setHeaders) {
39
- stream.on('headers', setHeaders);
40
- }
203
+ const tryExtension = (i: number, error: NodeJS.ErrnoException) => {
204
+ if (i >= extensions.length) {
205
+ return fail(isNotFound(error) ? 404 : 500, error);
206
+ }
207
+ const candidate = `${file}.${extensions[i]}`;
208
+ stat(candidate, (err: NodeJS.ErrnoException | null, stats: Stats) => err || stats.isDirectory() ? tryExtension(i + 1, error) : sendFile(candidate, stats));
209
+ };
41
210
 
42
- if (fallthrough) {
43
- stream.on('file', function onFile() {
44
- // once file is determined, always forward error
45
- forwardError = true;
46
- });
211
+ if (path.endsWith('/')) {
212
+ return sendIndex(0);
47
213
  }
48
-
49
- // forward errors
50
- stream.on('error', function error(err: any) {
51
- if (forwardError || !(err.statusCode < 500)) {
52
- next(err);
214
+ stat(file, (err: NodeJS.ErrnoException | null, stats: Stats) => {
215
+ if (err) {
216
+ const tryExtensions = extensions.length > 0 && !/\.[^./\\]*$/.test(path);
217
+ return tryExtensions ? tryExtension(0, err) : fail(isNotFound(err) ? 404 : 500, err);
218
+ }
219
+ if (stats.isDirectory()) {
220
+ if (!redirect) {
221
+ return fail(404);
222
+ }
223
+ const location = encodeURI(`${target.pathname}/${target.search}`);
224
+ res.statusCode = 301;
225
+ res.setHeader('Content-Type', 'text/html; charset=UTF-8');
226
+ res.setHeader('Content-Security-Policy', 'default-src \'none\'');
227
+ res.setHeader('X-Content-Type-Options', 'nosniff');
228
+ res.setHeader('Location', location);
229
+ const doc = `<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Redirecting</title>\n</head>\n<body>\n<pre>Redirecting to ${location}</pre>\n</body>\n</html>\n`;
230
+ res.setHeader('Content-Length', Buffer.byteLength(doc));
231
+ res.end(doc);
53
232
  return;
54
233
  }
55
-
56
- next();
234
+ sendFile(file, stats);
57
235
  });
58
- // pipe
59
- stream.pipe(res);
60
236
  };
237
+ };
61
238
 
62
- function createNotFoundDirectoryListener() {
63
- return function notFound() {
64
- // @ts-ignore
65
- this.error(404);
66
- };
67
- }
239
+ function isNotFound(error: NodeJS.ErrnoException): boolean {
240
+ return error.code === 'ENOENT' || error.code === 'ENAMETOOLONG' || error.code === 'ENOTDIR';
241
+ }
68
242
 
69
- function createRedirectDirectoryListener(url: URL) {
70
- return (res: any) => {
71
- // @ts-ignore
72
- if (this.hasTrailingSlash()) {
73
- // @ts-ignore
74
- this.error(404);
75
- return;
76
- }
77
- // reformat the URL
78
- const loc = encodeURI(url.href);
79
- const doc = createHtmlDocument('Redirecting', 'Redirecting to <a href="' + loc + '">' +
80
- loc + '</a>');
81
-
82
- // send redirect response
83
- res.statusCode = 301;
84
- res.setHeader('Content-Type', 'text/html; charset=UTF-8');
85
- res.setHeader('Content-Length', Buffer.byteLength(doc));
86
- res.setHeader('Content-Security-Policy', 'default-src \'none\'');
87
- res.setHeader('X-Content-Type-Options', 'nosniff');
88
- res.setHeader('Location', loc);
89
- res.end(doc);
90
- };
243
+ function isPreconditionFailure(headers: Record<string, string>, res: any): boolean {
244
+ const match = headers['if-match'];
245
+ if (match) {
246
+ const etag = res.getHeader('ETag');
247
+ return !etag || (match !== '*' && parseTokens(match).every(m => m !== etag && m !== `W/${etag}` && `W/${m}` !== etag));
91
248
  }
92
-
93
- function createHtmlDocument(title: string, body: string) {
94
- return '<!DOCTYPE html>\n' +
95
- '<html lang="en">\n' +
96
- '<head>\n' +
97
- '<meta charset="utf-8">\n' +
98
- '<title>' + title + '</title>\n' +
99
- '</head>\n' +
100
- '<body>\n' +
101
- '<pre>' + body + '</pre>\n' +
102
- '</body>\n' +
103
- '</html>\n';
249
+ const unmodifiedSince = Date.parse(headers['if-unmodified-since']);
250
+ if (!isNaN(unmodifiedSince)) {
251
+ return Date.parse(res.getHeader('Last-Modified')) > unmodifiedSince;
104
252
  }
253
+ return false;
254
+ }
105
255
 
106
- };
256
+ /** As the `fresh` package: whether the client's copy is still good. */
257
+ function isFresh(headers: Record<string, string>, res: any): boolean {
258
+ const noneMatch = headers['if-none-match'];
259
+ const modifiedSince = headers['if-modified-since'];
260
+ if (!noneMatch && !modifiedSince) {
261
+ return false;
262
+ }
263
+ if (/(?:^|,)\s*no-cache\s*(?:,|$)/.test(headers['cache-control'] ?? '')) {
264
+ return false;
265
+ }
266
+ if (noneMatch && noneMatch !== '*') {
267
+ const etag = res.getHeader('ETag');
268
+ const strip = (tag: string) => tag.startsWith('W/') ? tag.slice(2) : tag;
269
+ if (!etag || !parseTokens(noneMatch).some(tag => strip(tag) === strip(etag))) {
270
+ return false;
271
+ }
272
+ }
273
+ if (modifiedSince) {
274
+ const modified = Date.parse(res.getHeader('Last-Modified'));
275
+ if (isNaN(modified) || modified > Date.parse(modifiedSince)) {
276
+ return false;
277
+ }
278
+ }
279
+ return true;
280
+ }
107
281
 
108
- export const mime = send.mime;
282
+ function isRangeFresh(headers: Record<string, string>, res: any): boolean {
283
+ const ifRange = headers['if-range'];
284
+ if (!ifRange) {
285
+ return true;
286
+ }
287
+ if (ifRange.includes('"')) {
288
+ const etag = res.getHeader('ETag');
289
+ return !!etag && ifRange.includes(etag);
290
+ }
291
+ return Date.parse(res.getHeader('Last-Modified')) <= Date.parse(ifRange);
292
+ }