/
worker.js
85 lines (73 loc) · 1.92 KB
/
worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { App } from '../output/server/app.js';
import { manifest, prerendered } from './manifest.js';
const app = new App(manifest);
const prefix = `/${manifest.appDir}/`;
export default {
async fetch(req, env) {
const url = new URL(req.url);
// static assets
if (url.pathname.startsWith(prefix)) {
/** @type {Response} */
const res = await env.ASSETS.fetch(req);
return new Response(res.body, {
headers: {
// include original cache headers, minus cache-control which
// is overridden, and etag which is no longer useful
'cache-control': 'public, immutable, max-age=31536000',
'content-type': res.headers.get('content-type'),
'x-robots-tag': 'noindex'
}
});
}
// prerendered pages and index.html files
const pathname = url.pathname.replace(/\/$/, '');
let file = pathname.substring(1);
try {
file = decodeURIComponent(file);
} catch (err) {
// ignore
}
if (
manifest.assets.has(file) ||
manifest.assets.has(file + '/index.html') ||
prerendered.has(pathname || '/')
) {
return env.ASSETS.fetch(req);
}
// dynamically-generated pages
try {
const rendered = await app.render({
url,
rawBody: new Uint8Array(await req.arrayBuffer()),
headers: Object.fromEntries(req.headers),
method: req.method
});
if (rendered) {
return new Response(rendered.body, {
status: rendered.status,
headers: make_headers(rendered.headers)
});
}
} catch (e) {
return new Response('Error rendering route: ' + (e.message || e.toString()), { status: 500 });
}
return new Response({
status: 404,
statusText: 'Not Found'
});
}
};
function make_headers(headers) {
const result = new Headers();
for (const header in headers) {
const value = headers[header];
if (typeof value === 'string') {
result.set(header, value);
continue;
}
for (const sub of value) {
result.append(header, sub);
}
}
return result;
}