@celljs/serve-static 4.0.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 (46) hide show
  1. package/README.md +5 -1
  2. package/esm/node/embedded-assets.d.ts +1 -1
  3. package/esm/node/embedded-assets.js +15 -11
  4. package/esm/node/embedded-assets.js.map +1 -1
  5. package/esm/node/mime.d.ts +6 -0
  6. package/esm/node/mime.js +28 -0
  7. package/esm/node/mime.js.map +1 -0
  8. package/esm/node/module.d.ts +1 -1
  9. package/esm/node/serve-static-middleware.d.ts +18 -1
  10. package/esm/node/serve-static-middleware.js +74 -30
  11. package/esm/node/serve-static-middleware.js.map +1 -1
  12. package/esm/node/serve-static.d.ts +9 -2
  13. package/esm/node/serve-static.js +258 -65
  14. package/esm/node/serve-static.js.map +1 -1
  15. package/lib/node/embedded-assets.d.ts +1 -1
  16. package/lib/node/embedded-assets.d.ts.map +1 -1
  17. package/lib/node/embedded-assets.js +15 -14
  18. package/lib/node/embedded-assets.js.map +1 -1
  19. package/lib/node/mime.d.ts +7 -0
  20. package/lib/node/mime.d.ts.map +1 -0
  21. package/lib/node/mime.js +31 -0
  22. package/lib/node/mime.js.map +1 -0
  23. package/lib/node/module.d.ts +1 -1
  24. package/lib/node/serve-static-middleware.d.ts +18 -1
  25. package/lib/node/serve-static-middleware.d.ts.map +1 -1
  26. package/lib/node/serve-static-middleware.js +72 -28
  27. package/lib/node/serve-static-middleware.js.map +1 -1
  28. package/lib/node/serve-static-middleware.spec.d.ts +2 -0
  29. package/lib/node/serve-static-middleware.spec.d.ts.map +1 -0
  30. package/lib/node/serve-static-middleware.spec.js +232 -0
  31. package/lib/node/serve-static-middleware.spec.js.map +1 -0
  32. package/lib/node/serve-static.d.ts +9 -2
  33. package/lib/node/serve-static.d.ts.map +1 -1
  34. package/lib/node/serve-static.js +259 -69
  35. package/lib/node/serve-static.js.map +1 -1
  36. package/lib/node/serve-static.spec.d.ts +2 -0
  37. package/lib/node/serve-static.spec.d.ts.map +1 -0
  38. package/lib/node/serve-static.spec.js +139 -0
  39. package/lib/node/serve-static.spec.js.map +1 -0
  40. package/package.json +7 -9
  41. package/src/node/embedded-assets.ts +16 -12
  42. package/src/node/mime.ts +27 -0
  43. package/src/node/serve-static-middleware.spec.ts +284 -0
  44. package/src/node/serve-static-middleware.ts +79 -31
  45. package/src/node/serve-static.spec.ts +151 -0
  46. package/src/node/serve-static.ts +259 -74
@@ -0,0 +1,151 @@
1
+ import { afterAll, beforeAll, describe, it } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { createServer, Server } from 'node:http';
5
+ import type { AddressInfo } from 'node:net';
6
+ import { tmpdir } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { serveStatic } from './serve-static';
9
+ import { MimeUtil } from './mime';
10
+
11
+ let root: string;
12
+ let server: Server;
13
+ let base: string;
14
+ /** Options of the next request; next() answers 599 "next" with the status of the error, if any. */
15
+ let options: Record<string, unknown> = {};
16
+
17
+ beforeAll(async () => {
18
+ root = mkdtempSync(join(tmpdir(), 'cell-send-'));
19
+ writeFileSync(join(root, 'app.js'), '0123456789');
20
+ writeFileSync(join(root, 'index.html'), '<html></html>');
21
+ writeFileSync(join(root, '.env'), 'SECRET=1');
22
+ writeFileSync(join(root, 'page.html'), 'page');
23
+ writeFileSync(join(root, 'empty.txt'), '');
24
+ mkdirSync(join(root, 'docs'));
25
+ writeFileSync(join(root, 'docs', 'index.html'), 'docs');
26
+ server = createServer((req, res) => {
27
+ if (req.headers['x-gone']) {
28
+ // The client is gone before the file is sent.
29
+ res.destroy();
30
+ }
31
+ serveStatic(root, { baseHref: '/', root, ...options } as any)(req, res, (err?: any) => {
32
+ if (res.writableEnded) {
33
+ return;
34
+ }
35
+ res.statusCode = 599;
36
+ res.end(`next${err ? ` ${err.statusCode}` : ''}`);
37
+ });
38
+ });
39
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
40
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
41
+ });
42
+
43
+ afterAll(() => {
44
+ server.close();
45
+ rmSync(root, { recursive: true, force: true });
46
+ });
47
+
48
+ async function get(path: string, headers: Record<string, string> = {}, opts: Record<string, unknown> = {}, method = 'GET') {
49
+ options = opts;
50
+ const res = await fetch(base + path, { headers, method, redirect: 'manual' });
51
+ return { status: res.status, headers: res.headers, body: await res.text() };
52
+ }
53
+
54
+ describe('serveStatic', () => {
55
+ it('sends a file with type, length, validators and cache headers', async () => {
56
+ const res = await get('/app.js', {}, { maxAge: 60000, immutable: true });
57
+ expect(res.status).to.equal(200);
58
+ expect(res.body).to.equal('0123456789');
59
+ expect(res.headers.get('content-type')).to.equal('application/javascript; charset=UTF-8');
60
+ expect(res.headers.get('content-length')).to.equal('10');
61
+ expect(res.headers.get('accept-ranges')).to.equal('bytes');
62
+ expect(res.headers.get('cache-control')).to.equal('public, max-age=60, immutable');
63
+ expect(res.headers.get('etag')).to.match(/^W\/"a-[0-9a-f]+"$/);
64
+ expect(res.headers.get('last-modified')).to.match(/GMT$/);
65
+ expect((await get('/empty.txt')).headers.get('content-length')).to.equal('0');
66
+ });
67
+
68
+ it('answers 304 to a fresh copy and 412 to a failed precondition', async () => {
69
+ const { headers } = await get('/app.js');
70
+ const etag = headers.get('etag')!;
71
+ const notModified = await get('/app.js', { 'if-none-match': etag });
72
+ expect(notModified.status).to.equal(304);
73
+ expect(notModified.headers.get('content-type')).to.equal(null);
74
+ expect((await get('/app.js', { 'if-modified-since': headers.get('last-modified')! })).status).to.equal(304);
75
+ expect((await get('/app.js', { 'if-none-match': '"other"' })).status).to.equal(200);
76
+ expect((await get('/app.js', { 'if-none-match': etag, 'cache-control': 'no-cache' })).status).to.equal(200);
77
+ expect((await get('/app.js', { 'if-match': '"other"' })).status).to.equal(412);
78
+ expect((await get('/app.js', { 'if-match': etag })).status).to.equal(200);
79
+ });
80
+
81
+ it('sends a byte range', async () => {
82
+ const partial = await get('/app.js', { range: 'bytes=2-4' });
83
+ expect(partial.status).to.equal(206);
84
+ expect(partial.body).to.equal('234');
85
+ expect(partial.headers.get('content-range')).to.equal('bytes 2-4/10');
86
+ expect((await get('/app.js', { range: 'bytes=-3' })).body).to.equal('789');
87
+ expect((await get('/app.js', { range: 'bytes=8-' })).body).to.equal('89');
88
+ const unsatisfiable = await get('/app.js', { range: 'bytes=20-30' });
89
+ expect(unsatisfiable.status).to.equal(416);
90
+ expect(unsatisfiable.headers.get('content-range')).to.equal('bytes */10');
91
+ expect((await get('/app.js', { range: 'bytes=0-1,5-6' })).status).to.equal(200);
92
+ expect((await get('/app.js', { range: 'bytes=0-1', 'if-range': '"stale"' })).status).to.equal(200);
93
+ expect((await get('/app.js', { range: 'bytes=0-1' }, { acceptRanges: false })).status).to.equal(200);
94
+ });
95
+
96
+ it('answers HEAD without a body', async () => {
97
+ const res = await get('/app.js', {}, {}, 'HEAD');
98
+ expect(res.status).to.equal(200);
99
+ expect(res.headers.get('content-length')).to.equal('10');
100
+ expect(res.body).to.equal('');
101
+ });
102
+
103
+ it('sends index files, tries extensions, and redirects directories when asked', async () => {
104
+ expect((await get('/')).body).to.equal('<html></html>');
105
+ expect((await get('/docs/')).body).to.equal('docs');
106
+ expect((await get('/docs')).body).to.equal('next');
107
+ const redirect = await get('/docs?x=1', {}, { redirect: true });
108
+ expect(redirect.status).to.equal(301);
109
+ expect(redirect.headers.get('location')).to.equal('/docs/?x=1');
110
+ expect((await get('/page')).body).to.equal('next');
111
+ expect((await get('/page', {}, { extensions: ['html'] })).body).to.equal('page');
112
+ expect((await get('/', {}, { index: false })).body).to.equal('next');
113
+ });
114
+
115
+ it('keeps dotfiles and paths outside the root out', async () => {
116
+ expect((await get('/.env')).body).to.equal('next');
117
+ expect((await get('/.env', {}, { dotfiles: 'allow' })).body).to.equal('SECRET=1');
118
+ expect((await get('/.env', {}, { dotfiles: 'deny', fallthrough: false })).body).to.equal('next 403');
119
+ expect((await get('/%2e%2e/etc/passwd')).body).to.equal('next');
120
+ expect((await get('/a%00b')).body).to.equal('next');
121
+ expect((await get('/missing.js', {}, { fallthrough: false })).body).to.equal('next 404');
122
+ });
123
+
124
+ it('lets setHeaders win over the defaults', async () => {
125
+ const res = await get('/index.html', {}, { maxAge: 60000, setHeaders: (r: any) => r.setHeader('Cache-Control', 'no-store') });
126
+ expect(res.headers.get('cache-control')).to.equal('no-store');
127
+ });
128
+
129
+ it('does not fail when the client is gone before the file is sent', async () => {
130
+ const error = await get('/app.js', { 'x-gone': '1' }).then(() => undefined, (e: Error) => e);
131
+ expect(error).to.be.instanceOf(Error);
132
+ expect((await get('/app.js')).status).to.equal(200);
133
+ });
134
+
135
+ it('passes other methods on', async () => {
136
+ expect((await get('/app.js', {}, {}, 'POST')).body).to.equal('next');
137
+ expect((await get('/app.js', {}, { fallthrough: false }, 'POST')).status).to.equal(405);
138
+ });
139
+ });
140
+
141
+ describe('MimeUtil', () => {
142
+ it('knows the files of a frontend build', () => {
143
+ expect(MimeUtil.contentType('/a/index.html')).to.equal('text/html; charset=UTF-8');
144
+ expect(MimeUtil.contentType('x.CSS')).to.equal('text/css; charset=UTF-8');
145
+ expect(MimeUtil.contentType('x.json')).to.equal('application/json; charset=UTF-8');
146
+ expect(MimeUtil.contentType('x.svg')).to.equal('image/svg+xml');
147
+ expect(MimeUtil.contentType('x.woff2')).to.equal('font/woff2');
148
+ expect(MimeUtil.contentType('LICENSE')).to.equal('application/octet-stream');
149
+ expect(MimeUtil.lookup('js')).to.equal('application/javascript');
150
+ });
151
+ });
@@ -1,23 +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
- return (req: any, res: any, next: Function) => {
73
+ /** `url` (default `req.url`) is what to serve; the SPA fallback passes `/index.html` without changing the request. */
74
+ return (req: any, res: any, next: Next, url: string = req.url) => {
16
75
  if (req.method !== 'GET' && req.method !== 'HEAD') {
17
76
  if (fallthrough) {
18
77
  return next();
19
78
  }
20
- // method not allowed
21
79
  res.statusCode = 405;
22
80
  res.setHeader('Allow', 'GET, HEAD');
23
81
  res.setHeader('Content-Length', '0');
@@ -25,83 +83,210 @@ export const serveStatic = (root: string, opts: ServeStaticOption) => {
25
83
  next();
26
84
  return;
27
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
+ };
28
94
 
29
- 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);
30
118
 
31
- const url: URL = new URL(`${req.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
+ };
32
189
 
33
- const stream = send(req, url.pathname, opts) as any;
190
+ const end = (status: number) => {
191
+ res.statusCode = status;
192
+ res.end();
193
+ };
34
194
 
35
- stream.on('directory', onDirectory(url));
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
+ };
36
202
 
37
- if (setHeaders) {
38
- stream.on('headers', setHeaders);
39
- }
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
+ };
40
210
 
41
- if (fallthrough) {
42
- stream.on('file', function onFile() {
43
- // once file is determined, always forward error
44
- forwardError = true;
45
- });
211
+ if (path.endsWith('/')) {
212
+ return sendIndex(0);
46
213
  }
47
-
48
- // forward errors
49
- stream.on('error', function error(err: any) {
50
- if (forwardError || !(err.statusCode < 500)) {
51
- 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);
52
232
  return;
53
233
  }
54
-
55
- next();
234
+ sendFile(file, stats);
56
235
  });
57
- // pipe
58
- stream.pipe(res);
59
236
  };
237
+ };
60
238
 
61
- function createNotFoundDirectoryListener() {
62
- return function notFound() {
63
- // @ts-ignore
64
- this.error(404);
65
- };
66
- }
239
+ function isNotFound(error: NodeJS.ErrnoException): boolean {
240
+ return error.code === 'ENOENT' || error.code === 'ENAMETOOLONG' || error.code === 'ENOTDIR';
241
+ }
67
242
 
68
- function createRedirectDirectoryListener(url: URL) {
69
- return (res: any) => {
70
- // @ts-ignore
71
- if (this.hasTrailingSlash()) {
72
- // @ts-ignore
73
- this.error(404);
74
- return;
75
- }
76
- // reformat the URL
77
- const loc = encodeURI(url.href);
78
- const doc = createHtmlDocument('Redirecting', 'Redirecting to <a href="' + loc + '">' +
79
- loc + '</a>');
80
-
81
- // send redirect response
82
- res.statusCode = 301;
83
- res.setHeader('Content-Type', 'text/html; charset=UTF-8');
84
- res.setHeader('Content-Length', Buffer.byteLength(doc));
85
- res.setHeader('Content-Security-Policy', 'default-src \'none\'');
86
- res.setHeader('X-Content-Type-Options', 'nosniff');
87
- res.setHeader('Location', loc);
88
- res.end(doc);
89
- };
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));
90
248
  }
91
-
92
- function createHtmlDocument(title: string, body: string) {
93
- return '<!DOCTYPE html>\n' +
94
- '<html lang="en">\n' +
95
- '<head>\n' +
96
- '<meta charset="utf-8">\n' +
97
- '<title>' + title + '</title>\n' +
98
- '</head>\n' +
99
- '<body>\n' +
100
- '<pre>' + body + '</pre>\n' +
101
- '</body>\n' +
102
- '</html>\n';
249
+ const unmodifiedSince = Date.parse(headers['if-unmodified-since']);
250
+ if (!isNaN(unmodifiedSince)) {
251
+ return Date.parse(res.getHeader('Last-Modified')) > unmodifiedSince;
103
252
  }
253
+ return false;
254
+ }
104
255
 
105
- };
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
+ }
106
281
 
107
- 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
+ }