@celljs/serve-static 4.0.0 → 4.1.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.
- package/esm/node/embedded-assets.d.ts +1 -1
- package/esm/node/embedded-assets.js +13 -7
- package/esm/node/embedded-assets.js.map +1 -1
- package/esm/node/serve-static-middleware.d.ts +18 -1
- package/esm/node/serve-static-middleware.js +72 -29
- package/esm/node/serve-static-middleware.js.map +1 -1
- package/esm/node/serve-static.d.ts +1 -1
- package/esm/node/serve-static.js +5 -4
- package/esm/node/serve-static.js.map +1 -1
- package/lib/node/embedded-assets.d.ts +1 -1
- package/lib/node/embedded-assets.d.ts.map +1 -1
- package/lib/node/embedded-assets.js +13 -7
- package/lib/node/embedded-assets.js.map +1 -1
- package/lib/node/serve-static-middleware.d.ts +18 -1
- package/lib/node/serve-static-middleware.d.ts.map +1 -1
- package/lib/node/serve-static-middleware.js +71 -28
- package/lib/node/serve-static-middleware.js.map +1 -1
- package/lib/node/serve-static-middleware.spec.d.ts +2 -0
- package/lib/node/serve-static-middleware.spec.d.ts.map +1 -0
- package/lib/node/serve-static-middleware.spec.js +232 -0
- package/lib/node/serve-static-middleware.spec.js.map +1 -0
- package/lib/node/serve-static.d.ts +1 -1
- package/lib/node/serve-static.d.ts.map +1 -1
- package/lib/node/serve-static.js +5 -4
- package/lib/node/serve-static.js.map +1 -1
- package/package.json +5 -6
- package/src/node/embedded-assets.ts +13 -7
- package/src/node/serve-static-middleware.spec.ts +284 -0
- package/src/node/serve-static-middleware.ts +78 -31
- package/src/node/serve-static.ts +5 -4
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { afterAll, afterEach, beforeAll, describe, it } from 'bun:test';
|
|
2
|
+
import { expect } from 'chai';
|
|
3
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { createServer } from 'node:http';
|
|
5
|
+
import type { AddressInfo } from 'node:net';
|
|
6
|
+
import { tmpdir } from 'node:os';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { EmbeddedAssets } from './embedded-assets';
|
|
9
|
+
import { ServeStaticMiddleware } from './serve-static-middleware';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* ServeStaticMiddleware.handle() 在真实的 HTTP 请求下的行为。next() 用桩代替下游链:写一个 404 'next' 响应。
|
|
13
|
+
*
|
|
14
|
+
* “handle() 一定 settle”的用例防止泄漏再次出现:文件发送成功时 serve() 不会回调,以前 handle() 返回的 Promise
|
|
15
|
+
* 因此永远不会 settle,上游中间件链和请求上下文一直被挂住(每个静态请求泄漏约 4.7KB,见 cell-refactor/baseline/baseline.md §4.4)。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
interface Outcome {
|
|
19
|
+
status: number;
|
|
20
|
+
headers: Headers;
|
|
21
|
+
body: string;
|
|
22
|
+
/** 下游 next() 被调用的次数。 */
|
|
23
|
+
nextCalls: number;
|
|
24
|
+
/** 响应结束后再等 SETTLE_GRACE_MS,handle() 返回的 Promise 的状态。 */
|
|
25
|
+
settled: 'resolved' | 'rejected' | 'pending';
|
|
26
|
+
/** handle() 处理之后 request.url 的值(spa 回退不改写它)。 */
|
|
27
|
+
finalUrl?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const SETTLE_GRACE_MS = 100;
|
|
31
|
+
|
|
32
|
+
const ASSETS = {
|
|
33
|
+
'/index.html': '<html>spa</html>',
|
|
34
|
+
'/app.js': 'run()',
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
let root: string;
|
|
38
|
+
let rootWithoutIndex: string;
|
|
39
|
+
|
|
40
|
+
beforeAll(() => {
|
|
41
|
+
root = mkdtempSync(join(tmpdir(), 'cell-serve-static-'));
|
|
42
|
+
for (const [path, content] of Object.entries(ASSETS)) {
|
|
43
|
+
writeFileSync(join(root, path), content);
|
|
44
|
+
}
|
|
45
|
+
rootWithoutIndex = join(root, 'no-index');
|
|
46
|
+
mkdirSync(rootWithoutIndex);
|
|
47
|
+
writeFileSync(join(rootWithoutIndex, 'app.js'), ASSETS['/app.js']);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
afterAll(() => rmSync(root, { recursive: true, force: true }));
|
|
51
|
+
|
|
52
|
+
afterEach(() => {
|
|
53
|
+
(globalThis as Record<symbol, unknown>)[EmbeddedAssets.KEY] = undefined;
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
/** serve-static 自带 cell.yml 的默认值;每次都新建,因为中间件会改写 options。 */
|
|
57
|
+
function config(dir: string, spa = true, options: Record<string, unknown> = {}) {
|
|
58
|
+
return { spa, root: dir, options: { maxAge: 31536000000, immutable: true, ...options } };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 像容器那样创建中间件:注入属性,再调用 @PostConstruct。 */
|
|
62
|
+
function createMiddleware(cfg: ReturnType<typeof config>): ServeStaticMiddleware {
|
|
63
|
+
const middleware = new ServeStaticMiddleware();
|
|
64
|
+
Object.assign(middleware, { config: cfg, path: '/', requestMatcher: { match: async () => true } });
|
|
65
|
+
(middleware as unknown as { init(): void }).init();
|
|
66
|
+
return middleware;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function request(target: ReturnType<typeof config> | ServeStaticMiddleware, url: string, method = 'GET'): Promise<Outcome> {
|
|
70
|
+
const middleware = target instanceof ServeStaticMiddleware ? target : createMiddleware(target);
|
|
71
|
+
|
|
72
|
+
let nextCalls = 0;
|
|
73
|
+
let settled: Outcome['settled'] = 'pending';
|
|
74
|
+
let finalUrl: string | undefined;
|
|
75
|
+
const server = createServer((req, res) => {
|
|
76
|
+
const query = Object.fromEntries(new URL(req.url ?? '/', 'http://localhost').searchParams);
|
|
77
|
+
Object.assign(req, { query });
|
|
78
|
+
const next = async () => {
|
|
79
|
+
nextCalls++;
|
|
80
|
+
res.statusCode = 404;
|
|
81
|
+
res.end('next');
|
|
82
|
+
};
|
|
83
|
+
middleware.handle({ request: req, response: res } as any, next).then(
|
|
84
|
+
() => {
|
|
85
|
+
settled = 'resolved';
|
|
86
|
+
},
|
|
87
|
+
() => {
|
|
88
|
+
settled = 'rejected';
|
|
89
|
+
},
|
|
90
|
+
);
|
|
91
|
+
res.on('finish', () => {
|
|
92
|
+
finalUrl = req.url;
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
96
|
+
try {
|
|
97
|
+
const { port } = server.address() as AddressInfo;
|
|
98
|
+
const response = await fetch(`http://127.0.0.1:${port}${url}`, { method });
|
|
99
|
+
const body = await response.text();
|
|
100
|
+
await new Promise(resolve => setTimeout(resolve, SETTLE_GRACE_MS));
|
|
101
|
+
return { status: response.status, headers: response.headers, body, nextCalls, settled, finalUrl };
|
|
102
|
+
} finally {
|
|
103
|
+
server.closeAllConnections();
|
|
104
|
+
await new Promise(resolve => server.close(resolve));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 和 embedded-assets.spec.ts 用同一路径、不同内容:解码缓存按资产表区分,不会串。 */
|
|
109
|
+
const EMBEDDED_INDEX = '<html>embedded</html>';
|
|
110
|
+
|
|
111
|
+
function embed(files: Record<string, string>): void {
|
|
112
|
+
const assets = new Map(Object.entries(files).map(([path, content], i) => [path, { body: Buffer.from(content).toString('base64'), etag: `"${i}"` }]));
|
|
113
|
+
(globalThis as Record<symbol, unknown>)[EmbeddedAssets.KEY] = assets;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
describe('ServeStaticMiddleware', () => {
|
|
117
|
+
describe('磁盘上的文件', () => {
|
|
118
|
+
it('成功:返回文件内容和缓存头,不调用 next', async () => {
|
|
119
|
+
const result = await request(config(root), '/app.js');
|
|
120
|
+
expect(result.status).to.equal(200);
|
|
121
|
+
expect(result.body).to.equal('run()');
|
|
122
|
+
expect(result.headers.get('cache-control')).to.equal('public, max-age=31536000, immutable');
|
|
123
|
+
expect(result.nextCalls).to.equal(0);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('成功:handle() 在响应结束后 settle(send 成功时不回调 next)', async () => {
|
|
127
|
+
const result = await request(config(root), '/app.js');
|
|
128
|
+
expect(result.status).to.equal(200);
|
|
129
|
+
expect(result.settled).to.equal('resolved');
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it('HEAD:200、没有响应体,不调用 next', async () => {
|
|
133
|
+
const result = await request(config(root), '/app.js', 'HEAD');
|
|
134
|
+
expect(result.status).to.equal(200);
|
|
135
|
+
expect(result.body).to.equal('');
|
|
136
|
+
expect(result.headers.get('content-length')).to.equal(String(ASSETS['/app.js'].length));
|
|
137
|
+
expect(result.nextCalls).to.equal(0);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('HEAD:handle() 在响应结束后 settle', async () => {
|
|
141
|
+
const result = await request(config(root), '/app.js', 'HEAD');
|
|
142
|
+
expect(result.status).to.equal(200);
|
|
143
|
+
expect(result.settled).to.equal('resolved');
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it('404(spa 关闭):文件不存在时交给 next,handle() settle', async () => {
|
|
147
|
+
const result = await request(config(root, false), '/missing.js');
|
|
148
|
+
expect(result.nextCalls).to.equal(1);
|
|
149
|
+
expect(result.status).to.equal(404);
|
|
150
|
+
expect(result.body).to.equal('next');
|
|
151
|
+
expect(result.settled).to.equal('resolved');
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it('spa 回退:未知路径返回 index.html,不调用 next,也不改写 request.url', async () => {
|
|
155
|
+
const result = await request(config(root), '/users/42');
|
|
156
|
+
expect(result.status).to.equal(200);
|
|
157
|
+
expect(result.body).to.equal('<html>spa</html>');
|
|
158
|
+
expect(result.finalUrl).to.equal('/users/42');
|
|
159
|
+
expect(result.nextCalls).to.equal(0);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it('spa 回退:handle() 在响应结束后 settle', async () => {
|
|
163
|
+
const result = await request(config(root), '/users/42');
|
|
164
|
+
expect(result.status).to.equal(200);
|
|
165
|
+
expect(result.settled).to.equal('resolved');
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it('spa 回退且 index.html 缺失:只调用一次 next,handle() settle', async () => {
|
|
169
|
+
const result = await request(config(rootWithoutIndex), '/users/42');
|
|
170
|
+
expect(result.nextCalls).to.equal(1);
|
|
171
|
+
expect(result.status).to.equal(404);
|
|
172
|
+
expect(result.finalUrl).to.equal('/users/42');
|
|
173
|
+
expect(result.settled).to.equal('resolved');
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it('index.html 的 Cache-Control:没有配置 htmlMaxAge 时是 max-age=0,不是 NaN', async () => {
|
|
177
|
+
const result = await request(config(root), '/index.html');
|
|
178
|
+
expect(result.status).to.equal(200);
|
|
179
|
+
expect(result.headers.get('cache-control')).to.equal('public, max-age=0');
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it('index.html 的 Cache-Control:htmlMaxAge(毫秒)换算成秒;其他文件不受影响', async () => {
|
|
183
|
+
const cfg = config(root, true, { htmlMaxAge: 60000 });
|
|
184
|
+
expect((await request(cfg, '/index.html')).headers.get('cache-control')).to.equal('public, max-age=60');
|
|
185
|
+
expect((await request(cfg, '/app.js')).headers.get('cache-control')).to.equal('public, max-age=31536000, immutable');
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it('options.headers 加到每个文件上', async () => {
|
|
189
|
+
const result = await request(config(root, true, { headers: { 'x-frame-options': 'DENY' } }), '/app.js');
|
|
190
|
+
expect(result.headers.get('x-frame-options')).to.equal('DENY');
|
|
191
|
+
});
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
describe('直接交给 next 的请求', () => {
|
|
195
|
+
it('非 GET/HEAD 交给 next,handle() settle', async () => {
|
|
196
|
+
const result = await request(config(root), '/app.js', 'POST');
|
|
197
|
+
expect(result.nextCalls).to.equal(1);
|
|
198
|
+
expect(result.settled).to.equal('resolved');
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it('?static=skip 交给 next,handle() settle', async () => {
|
|
202
|
+
const result = await request(config(root), '/app.js?static=skip');
|
|
203
|
+
expect(result.nextCalls).to.equal(1);
|
|
204
|
+
expect(result.settled).to.equal('resolved');
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it('root 没有配置(paths.public 缺失)时不报错,交给 next', async () => {
|
|
208
|
+
const cfg = { ...config(root), root: undefined as unknown as string };
|
|
209
|
+
const result = await request(cfg, '/app.js');
|
|
210
|
+
expect(result.nextCalls).to.equal(1);
|
|
211
|
+
expect(result.settled).to.equal('resolved');
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it('没有前端(root 不存在且没有内嵌资源)时交给 next', async () => {
|
|
215
|
+
const result = await request(config(join(root, 'absent')), '/app.js');
|
|
216
|
+
expect(result.nextCalls).to.equal(1);
|
|
217
|
+
expect(result.settled).to.equal('resolved');
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
describe('只初始化一次', () => {
|
|
222
|
+
it('多次请求不改写共享的 cell.serve-static.options,文件服务只创建一次', async () => {
|
|
223
|
+
const cfg = config(root, true, { headers: { 'x-a': '1' } });
|
|
224
|
+
const original = structuredClone(cfg.options);
|
|
225
|
+
const middleware = createMiddleware(cfg);
|
|
226
|
+
const serve = (middleware as unknown as { serve: unknown }).serve;
|
|
227
|
+
for (const url of ['/app.js', '/index.html', '/users/42', '/missing.js']) {
|
|
228
|
+
expect((await request(middleware, url)).settled).to.equal('resolved');
|
|
229
|
+
}
|
|
230
|
+
expect(cfg.options).to.deep.equal(original);
|
|
231
|
+
expect((middleware as unknown as { serve: unknown }).serve).to.equal(serve);
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it('同一个实例上并发的请求都 settle', async () => {
|
|
235
|
+
const middleware = createMiddleware(config(root));
|
|
236
|
+
const results = await Promise.all(['/app.js', '/index.html', '/users/1', '/users/2'].map(url => request(middleware, url)));
|
|
237
|
+
expect(results.map(r => [r.status, r.settled])).to.deep.equal([
|
|
238
|
+
[200, 'resolved'],
|
|
239
|
+
[200, 'resolved'],
|
|
240
|
+
[200, 'resolved'],
|
|
241
|
+
[200, 'resolved'],
|
|
242
|
+
]);
|
|
243
|
+
});
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
describe('内嵌资源(cell build --single)', () => {
|
|
247
|
+
it('成功:从内存返回文件,root 不存在也可以,不调用 next', async () => {
|
|
248
|
+
embed({ '/index.html': EMBEDDED_INDEX, '/assets/embedded-only.js': 'embedded()' });
|
|
249
|
+
const result = await request(config(join(root, 'absent')), '/assets/embedded-only.js');
|
|
250
|
+
expect(result.status).to.equal(200);
|
|
251
|
+
expect(result.body).to.equal('embedded()');
|
|
252
|
+
expect(result.nextCalls).to.equal(0);
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
it('成功:handle() 在响应结束后 settle(EmbeddedAssets.serve 用 res.end() 发送,不回调)', async () => {
|
|
256
|
+
embed({ '/index.html': EMBEDDED_INDEX, '/assets/embedded-only.js': 'embedded()' });
|
|
257
|
+
const result = await request(config(join(root, 'absent')), '/assets/embedded-only.js');
|
|
258
|
+
expect(result.status).to.equal(200);
|
|
259
|
+
expect(result.settled).to.equal('resolved');
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
it('文件不存在(spa 关闭)时交给 next,handle() settle', async () => {
|
|
263
|
+
embed({ '/index.html': EMBEDDED_INDEX });
|
|
264
|
+
const result = await request(config(join(root, 'absent'), false), '/missing.js');
|
|
265
|
+
expect(result.nextCalls).to.equal(1);
|
|
266
|
+
expect(result.settled).to.equal('resolved');
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
it('重新注册的资产表不会拿到旧表的缓存内容', async () => {
|
|
270
|
+
embed({ '/index.html': '<html>first</html>' });
|
|
271
|
+
expect((await request(config(join(root, 'absent')), '/index.html')).body).to.equal('<html>first</html>');
|
|
272
|
+
embed({ '/index.html': '<html>second</html>' });
|
|
273
|
+
expect((await request(config(join(root, 'absent')), '/index.html')).body).to.equal('<html>second</html>');
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it('spa 回退到内嵌的 index.html', async () => {
|
|
277
|
+
embed({ '/index.html': EMBEDDED_INDEX });
|
|
278
|
+
const result = await request(config(join(root, 'absent')), '/users/42');
|
|
279
|
+
expect(result.status).to.equal(200);
|
|
280
|
+
expect(result.body).to.equal(EMBEDDED_INDEX);
|
|
281
|
+
expect(result.nextCalls).to.equal(0);
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
});
|
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import { Middleware, Context, RequestMatcher, HTTP_MIDDLEWARE_PRIORITY } from '@celljs/web/lib/node';
|
|
2
2
|
import {serveStatic, mime} from './serve-static';
|
|
3
3
|
import { EmbeddedAssets } from './embedded-assets';
|
|
4
|
-
import { Value, Component, Autowired } from '@celljs/core';
|
|
4
|
+
import { Value, Component, Autowired, PostConstruct } from '@celljs/core';
|
|
5
5
|
import { HttpMethod, MediaType, HttpHeaders } from '@celljs/http';
|
|
6
6
|
import { SERVER_PATH } from '@celljs/web';
|
|
7
7
|
import { OutgoingMessage } from 'http';
|
|
8
8
|
import { existsSync } from 'fs';
|
|
9
|
+
import type { ServeStaticOption } from './type';
|
|
10
|
+
|
|
11
|
+
type Serve = (req: any, res: any, next: (err?: any) => void, url?: string) => void;
|
|
12
|
+
|
|
13
|
+
const SPA_INDEX = '/index.html';
|
|
14
|
+
|
|
9
15
|
@Component(Middleware)
|
|
10
16
|
export class ServeStaticMiddleware implements Middleware {
|
|
11
17
|
|
|
@@ -22,12 +28,51 @@ export class ServeStaticMiddleware implements Middleware {
|
|
|
22
28
|
* Whether there is a frontend to serve: embedded in the bundle (`--single`) or on disk. On
|
|
23
29
|
* Cloudflare Workers the platform serves the frontend and the worker has no copy.
|
|
24
30
|
*/
|
|
25
|
-
protected hasFrontend
|
|
31
|
+
protected hasFrontend: boolean;
|
|
32
|
+
|
|
33
|
+
/** Options of the file server: a copy of `cell.serve-static.options`, which stays untouched. */
|
|
34
|
+
protected options: ServeStaticOption & Record<string, any>;
|
|
35
|
+
|
|
36
|
+
protected serve: Serve;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Sets up the file server once. Cloudflare Workers allow I/O (`existsSync`) only while a request is
|
|
40
|
+
* handled; the application, and with it this component, starts on the first request there.
|
|
41
|
+
*/
|
|
42
|
+
@PostConstruct()
|
|
43
|
+
protected init(): void {
|
|
44
|
+
const { headers, htmlMaxAge, ...options } = this.config.options ?? {};
|
|
45
|
+
this.options = { ...options, baseHref: this.path };
|
|
46
|
+
this.options.setHeaders ??= this.createSetHeaders(headers, htmlMaxAge);
|
|
47
|
+
const embedded = EmbeddedAssets.get();
|
|
48
|
+
const root = this.config.root;
|
|
49
|
+
// No frontend (no `paths.public`, or nothing built there): every request goes on to the chain.
|
|
50
|
+
this.hasFrontend = !!embedded || (typeof root === 'string' && existsSync(root));
|
|
51
|
+
if (embedded) {
|
|
52
|
+
this.serve = EmbeddedAssets.serve(embedded, this.options);
|
|
53
|
+
} else if (this.hasFrontend) {
|
|
54
|
+
this.serve = serveStatic(root, this.options);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Adds the configured `headers` to every file, and gives HTML files their own Cache-Control
|
|
60
|
+
* (`htmlMaxAge` in milliseconds, default 0) so that a new build of the page is picked up.
|
|
61
|
+
*/
|
|
62
|
+
protected createSetHeaders(headers: Record<string, string> | undefined, htmlMaxAge: unknown): (res: OutgoingMessage, path: string) => void {
|
|
63
|
+
const htmlCacheControl = `public, max-age=${Math.floor(Math.max(0, Number(htmlMaxAge ?? 0) || 0) / 1000)}`;
|
|
64
|
+
return (res, path) => {
|
|
65
|
+
if (headers) {
|
|
66
|
+
Object.keys(headers).forEach(key => res.setHeader(key, headers[key]));
|
|
67
|
+
}
|
|
68
|
+
if ((mime as any).lookup!(path) === MediaType.TEXT_HTML) {
|
|
69
|
+
res.setHeader(HttpHeaders.CACHE_CONTROL, htmlCacheControl);
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
}
|
|
26
73
|
|
|
27
74
|
async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
|
|
28
|
-
this.config.options.baseHref = this.path;
|
|
29
75
|
const method = ctx.request.method;
|
|
30
|
-
this.hasFrontend ??= !!EmbeddedAssets.get() || existsSync(this.config.root);
|
|
31
76
|
|
|
32
77
|
if (!this.hasFrontend || !(method === HttpMethod.GET || method === HttpMethod.HEAD) || ctx.request.query['static'] === 'skip') {
|
|
33
78
|
await next();
|
|
@@ -44,41 +89,43 @@ export class ServeStaticMiddleware implements Middleware {
|
|
|
44
89
|
return;
|
|
45
90
|
}
|
|
46
91
|
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
92
|
+
return new Promise<void>((resolve, reject) => {
|
|
93
|
+
const response = ctx.response;
|
|
94
|
+
// A file that is sent ends the response without calling back: the request is done then.
|
|
95
|
+
const done = () => {
|
|
96
|
+
stopWaiting();
|
|
97
|
+
resolve();
|
|
98
|
+
};
|
|
99
|
+
const stopWaiting = () => {
|
|
100
|
+
response.off('finish', done);
|
|
101
|
+
response.off('close', done);
|
|
102
|
+
};
|
|
103
|
+
// The rest of the chain answers instead: its outcome is this middleware's outcome.
|
|
104
|
+
const passOn = () => {
|
|
105
|
+
stopWaiting();
|
|
106
|
+
next().then(resolve, reject);
|
|
107
|
+
};
|
|
108
|
+
response.once('finish', done);
|
|
109
|
+
response.once('close', done);
|
|
60
110
|
|
|
61
|
-
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
const url = ctx.request.url;
|
|
65
|
-
if (url !== '/index.html') {
|
|
111
|
+
// The SPA fallback serves /index.html for the request without changing request.url.
|
|
112
|
+
const attempt = (url: string) => this.serve(ctx.request, response, (err?: any) => {
|
|
113
|
+
if (url !== SPA_INDEX) {
|
|
66
114
|
if (!this.config.spa) {
|
|
67
|
-
|
|
115
|
+
passOn();
|
|
68
116
|
return;
|
|
69
117
|
}
|
|
70
|
-
|
|
71
|
-
executor(resolve, reject);
|
|
118
|
+
attempt(SPA_INDEX);
|
|
72
119
|
} else if (err) {
|
|
120
|
+
stopWaiting();
|
|
73
121
|
reject(err);
|
|
74
122
|
} else {
|
|
75
|
-
|
|
123
|
+
passOn();
|
|
76
124
|
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
return new Promise(executor);
|
|
125
|
+
}, url);
|
|
126
|
+
attempt(ctx.request.url);
|
|
127
|
+
});
|
|
81
128
|
}
|
|
82
129
|
priority = HTTP_MIDDLEWARE_PRIORITY + 500;
|
|
83
130
|
|
|
84
|
-
}
|
|
131
|
+
}
|
package/src/node/serve-static.ts
CHANGED
|
@@ -12,7 +12,8 @@ export const serveStatic = (root: string, opts: ServeStaticOption) => {
|
|
|
12
12
|
|
|
13
13
|
opts.root = resolve(root);
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
/** `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) => {
|
|
16
17
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
17
18
|
if (fallthrough) {
|
|
18
19
|
return next();
|
|
@@ -28,11 +29,11 @@ export const serveStatic = (root: string, opts: ServeStaticOption) => {
|
|
|
28
29
|
|
|
29
30
|
let forwardError = !fallthrough;
|
|
30
31
|
|
|
31
|
-
const
|
|
32
|
+
const target: URL = new URL(`${url.replace(baseHref, '/')}`, `http://${req.headers.host}`);
|
|
32
33
|
|
|
33
|
-
const stream = send(req,
|
|
34
|
+
const stream = send(req, target.pathname, opts) as any;
|
|
34
35
|
|
|
35
|
-
stream.on('directory', onDirectory(
|
|
36
|
+
stream.on('directory', onDirectory(target));
|
|
36
37
|
|
|
37
38
|
if (setHeaders) {
|
|
38
39
|
stream.on('headers', setHeaders);
|