-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathserver.ts
98 lines (77 loc) · 2.29 KB
/
server.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
import { renderApplication } from "@angular/platform-server";
import type {
Element,
ExecutionContext,
HTMLRewriterElementContentHandlers,
ServiceWorkerGlobalScope,
} from "@cloudflare/workers-types";
import { QueryClient, dehydrate } from "@tanstack/query-core";
import { bootstrap } from "src/main.server";
declare const self: ServiceWorkerGlobalScope;
interface Env {
ASSETS: { fetch: typeof fetch };
}
async function workerFetchHandler(
req: Request,
env: Env,
ctx: ExecutionContext,
) {
const cache = self.caches.default;
let res = await cache.match(req.url);
if (res) return res;
const url = new URL(req.url);
const document = await env.ASSETS.fetch(
new Request(new URL("/index.csr.html", url)),
).then((res) => res.text());
const queryClient = new QueryClient();
const html = await renderApplication(() => bootstrap(queryClient), {
document,
url: url.pathname,
});
res = new self.Response(html, {
headers: {
"cache-control": "max-age=180 s-max-age=180", // 3 minutes
"content-type": "text/html; charset=utf-8",
"x-frames-option": "sameorigin",
},
});
res = new self.HTMLRewriter()
.on("body", new DehydrateQueryClientHandler(queryClient))
.transform(res);
ctx.waitUntil(cache.put(req.url, res.clone()));
return res;
}
class DehydrateQueryClientHandler
implements HTMLRewriterElementContentHandlers
{
constructor(private client: QueryClient) {}
escapeState(): string {
const ESCAPE_LOOKUP: { [match: string]: string } = {
"&": "\\u0026",
">": "\\u003e",
"<": "\\u003c",
"\u2028": "\\u2028",
"\u2029": "\\u2029",
};
const ESCAPE_REGEX = /[&><\u2028\u2029]/g;
const state = dehydrate(this.client);
const str = JSON.stringify(state);
return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
}
element(element: Element) {
element.onEndTag((tag) => {
tag.before(
'<script id="__QUERY_CLIENT_DEHYDRATED_STATE__" type="application/json">' +
this.escapeState() +
"</script>",
{ html: true },
);
});
}
}
export default {
fetch: (request: Request, env: Env, ctx: ExecutionContext) =>
(globalThis as any)["__zone_symbol__Promise"].resolve(
workerFetchHandler(request, env, ctx),
),
};