forked from Glatek/nattramn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
333 lines (262 loc) · 7.9 KB
/
index.ts
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import { URLPattern } from "urlpattern-polyfill";
import crypto from "crypto";
import fs from "fs/promises";
import path from "path";
const appetitClientFileData = await fs.readFile(path.resolve("./client.js"));
interface PageData {
head: string;
body: string;
headers?: HeadersInit;
}
interface PageHandlerCallback {
(req: Request, params: Record<string, string>): Promise<PageData>;
}
interface Page {
route: string;
template: string;
handler: PageHandlerCallback;
}
interface RouterConfig {
pages: Page[];
}
interface ServerConfig {
serveStatic?: string;
}
interface Config {
server: ServerConfig;
router: RouterConfig;
}
function extname(s: string) {
return s.split(".").pop();
}
const MEDIA_TYPES: Record<string, string> = {
".md": "text/markdown",
".css": "text/css",
".html": "text/html",
".htm": "text/html",
".json": "application/json",
".map": "application/json",
".txt": "text/plain",
".ts": "text/typescript",
".tsx": "text/tsx",
".js": "application/javascript",
".jsx": "text/jsx",
".gz": "application/gzip",
".webp": "image/webp",
".jpg": "image/jpeg",
".png": "image/png",
".svg": "image/svg+xml",
};
async function serveFile(request: Request, filePath: string) {
const file = await fs.readFile(path.resolve(filePath));
const headers = new Headers();
const mime = getContentType(filePath);
if (mime) {
headers.set("Content-Type", mime);
}
return new Response(file, {
status: 200,
headers,
});
}
function getContentType(path: string): string | undefined {
return MEDIA_TYPES["." + extname(path)];
}
function stringToUint8Array(s: string) {
const te = new TextEncoder();
return te.encode(s);
}
function uint8ArrayToString(s: Uint8Array) {
const td = new TextDecoder();
return td.decode(s);
}
async function sha1(input: string) {
const shasum = crypto.createHash("sha1");
shasum.update(input);
return shasum.digest("hex");
}
/**
* Function to decide wether or not we include the part
* of the template before the <appetit-router> tag or not.
*
* If answerWithPartialContent if true, then anything
* before <appetit-router> will not be sent in the request.
*/
function generatePreContent(
template: string,
answerWithPartialContent: boolean,
) {
return answerWithPartialContent
? null
: template.indexOf("<appetit-router>") !== -1
? template.split("<appetit-router>")[0]
: template;
}
/**
* Function to decide wether or not we include the part
* of the template after the <appetit-router> tag or not.
*
* If answerWithPartialContent if true, then anything
* after </appetit-router> will not be sent in the request.
*/
function generatePostContent(
template: string,
answerWithPartialContent: boolean,
) {
return answerWithPartialContent
? null
: template.indexOf("</appetit-router>") !== -1
? template.split("</appetit-router>")[1]
: template;
}
function reqToURL(req: Request) {
return new URL(req.url);
}
function canHandleRoute(req: Request, route: string) {
const url = new URL(req.url);
const matcher = new URLPattern({ pathname: route });
const result = matcher.exec(url);
return Boolean(result);
}
function routeParams(req: Request, route: string) {
const { pathname } = reqToURL(req);
const requestURL = pathname.split("/");
const routeURL = route.split("/");
return routeURL.reduce((acc, curr, i) => {
const keyname = curr.includes(":") ? curr.split(":")[1] : undefined;
if (keyname) {
return {
...acc,
[keyname]: requestURL[i],
};
}
return acc;
}, {});
}
async function proxy(req: Request, page: Page): Promise<PartialResponse> {
const partialContent = Boolean(
req.headers.get("x-partial-content") ||
reqToURL(req).searchParams.get("partialContent"),
);
const pageData = await page.handler(req, routeParams(req, page.route));
const responseBody = [];
if (!pageData) {
throw new Error("Could not create PageData from handler.");
}
const { body, head, headers: pageDataHeaders } = pageData;
const preContent = generatePreContent(page.template, partialContent);
const headers = new Headers(pageDataHeaders);
headers.set("Content-Type", "text/html");
/*
If we don't send preConent we still want to update the title in the header on client side navigations.
Send new title in X-Header-Updates.
*/
if (!preContent && head) {
const match = head.match(/<title>(.+)<\/title>/i);
if (match) {
const title = match ? match[1] : "";
const json = JSON.stringify({ title });
const encoder = new TextEncoder();
const data = JSON.stringify([...encoder.encode(json)]);
headers.set("X-Header-Updates", data);
}
}
if (preContent) {
if (head) {
const preSplit = preContent.split(/<head>/);
responseBody.push(preSplit[0]);
// const headMarkup = '<head>' + (config.server.minifyHTML ? minifyHTML(head) : head);
const headMarkup = "<head>" + head;
responseBody.push(headMarkup);
responseBody.push(preSplit[1]);
} else {
return { body: preContent, status: 200 };
}
}
// const mainBody = config.server.minifyHTML ? minifyHTML(body) : body;
const mainBody = body;
responseBody.push(
partialContent ? mainBody : `<appetit-router>${mainBody}</appetit-router>`,
);
const postContent = generatePostContent(page.template, partialContent);
if (postContent) {
await responseBody.push(postContent);
}
const finalBody = new TextEncoder().encode(responseBody.join("\n"));
return { headers, body: finalBody, status: 200 };
}
interface PartialResponse {
status: number;
body: Uint8Array | string;
headers?: Headers;
}
export default class Appetit {
config: Config;
constructor(config: Config) {
this.config = config;
Object.freeze(this.config);
}
serve(port: number) {
Bun.serve({
port,
fetch: (req: Request) => this.handleRequests(req),
});
}
async handleRequest(req: Request): Promise<PartialResponse> {
const page = this.config.router.pages.find((page) =>
canHandleRoute(req, page.route)
);
if (page) {
return proxy(req, page);
} else {
throw new Error("Could not find route.");
}
}
async handleRequests(req: Request) {
try {
const url = reqToURL(req);
const hasExtention = !extname(url.pathname)?.includes("/") ?? false;
// Handle file requests
if (hasExtention) {
if (url.pathname === "/appetit-client.js") {
return new Response(appetitClientFileData, {
headers: new Headers({
"content-type": "application/javascript",
}),
status: 200,
});
}
if (this.config.server.serveStatic) {
return serveFile(req, this.config.server.serveStatic + url.pathname);
}
return new Response(null, {
status: 404,
});
}
const handledRequest = this.handleRequest(req);
const { status, headers: responseHeaders } = await handledRequest;
let { body } = await handledRequest;
body = body instanceof Uint8Array ? body : stringToUint8Array(body);
const headers = responseHeaders || new Headers();
const checksum = await sha1(uint8ArrayToString(body));
headers.set("ETag", checksum);
if (headers.get("Cache-Control") === null) {
headers.set("Cache-Control", "public, max-age=3600");
}
headers.set("Content-Length", String(body.byteLength));
return new Response(body, { status, headers });
} catch (e) {
console.debug(
`Nattramn was asked to answer for ${req.url} but did not find a suitable way to handle it.`,
);
if (extname(req.url) === null) {
console.debug("The route is missing.", req.url);
}
if (extname(req.url) !== null) {
console.debug("The file is missing.", req.url);
}
console.error(e);
return new Response("Not Found", { status: 404 });
}
}
}