/
render.ts
340 lines (316 loc) · 9.4 KB
/
render.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
334
335
336
337
338
339
340
// deno-lint-ignore-file no-explicit-any
import * as esbuild from "https://deno.land/x/esbuild@v0.15.10/mod.js";
import { denoPlugin } from "https://deno.land/x/esbuild_deno_loader@0.6.0/mod.ts";
import { EXPIRY_SECONDS } from "../server/constant.ts";
import { React, ReactDOMServer, Status, STATUS_TEXT } from "../server/deps.ts";
import { isJSX } from "../server/handler.ts";
import {
Container,
HttpRequest,
JSXHandler,
RenderOptions,
SSR,
} from "../types.d.ts";
export function createSSR(el: JSXHandler | JSX.Element): SSR {
let element: JSX.Element;
let status: 200;
let html: string;
let pageDir = "pages";
let staticPath = "/public";
let title: string;
let bundleName: string;
const scriptInstance: string[] = [];
const styleInstance: string[] = [];
const linkInstance: string[] = [];
const metaInstance: string[] = [];
let props: any;
let lang: string;
let htmlAttr: string;
let bodyAttr: string;
let rootAttr: string;
let ogDescription: string;
let ogTitle: string;
let ogImage: string;
let ogURL: string;
let ogType: string;
let ogSiteName: string;
let twitterCard: string;
let twitterImageAlt: string;
let metaDesc: string;
let httpRequest: HttpRequest;
let cache: Container;
if (isJSX(el)) {
const jsxElement = <JSX.Element> el;
bundleName = jsxElement.type.name;
element = jsxElement;
} else {
const jsxElement = <JSXHandler> el;
bundleName = jsxElement.name.toLowerCase();
element = React.createElement(jsxElement, props);
}
function createHydrate(rootComponent: string, rootTSX: string) {
rootTSX = rootTSX.toLowerCase();
return `import React from "https://esm.sh/react@18.2.0";import { createRoot } from "https://esm.sh/react-dom@18.2.0/client";import ${rootComponent} from "./${rootTSX}.tsx";const props = window.__INITIAL_STATE__ || {};const container = document.getElementById("root");const root = createRoot(container);root.render(<${rootComponent} {...props} />);`;
}
function createMeta(meta: string) {
return `<meta ${meta}>`;
}
function createScript(script: string) {
return `<script ${script}></script>`;
}
function createLink(link: string) {
return `<link ${link}>`;
}
function createStyle(style: string) {
return `<style>${style}</style>`;
}
function createDescription(desc: string) {
return `<meta property="og:description" content="${desc}">`;
}
function createMetaDescription(metaDesc: string) {
return `<meta name="description" content="${metaDesc}">`;
}
function createSiteName(siteName: string) {
return `<meta property="og:site_name" content="${siteName}">`;
}
function createURL(url: string) {
return `<meta property="og:url" content="${url}">`;
}
function createImage(img: string) {
return `<meta property="og:image" content="${img}">`;
}
function createType(type: string) {
return `<meta property="og:type" content="${type}">`;
}
function createTitle(title: string) {
return `<meta property="og:title" content="${title}">`;
}
function createTwitterCard(card: string) {
return `<meta name="twitter:card" content="${card}">`;
}
function createTwitterImageAlt(alt: string) {
return `<meta name="twitter:image:alt" content="${alt}">`;
}
/**
* @param bundle
* @param rootComponent
* @param rootTSX
*/
function createBundle(
bundle?: string,
rootComponent?: string,
rootTSX?: string,
) {
const cwd = Deno.cwd();
const b = bundle ? bundle : "bundle";
const hydrateTarget = `${cwd}/${pageDir}/${rootTSX}.hydrate.tsx`;
const bundlePath = `${cwd}${staticPath}/${b}.js`;
try {
if (!rootComponent) rootComponent = "App";
if (!rootTSX) rootTSX = "app";
Deno.writeTextFile(
hydrateTarget,
createHydrate(rootComponent, rootTSX),
);
} catch (err) {
console.error(err);
throw err;
}
esbuild.build({
plugins: [denoPlugin()],
entryPoints: [hydrateTarget],
outfile: bundlePath,
bundle: true,
minify: true,
format: "esm",
}).then(() => {
Deno.remove(hydrateTarget);
});
}
function createHTML(
element: JSX.Element,
options: RenderOptions,
initialData: any,
) {
const props = initialData
? `<script>window.__INITIAL_STATE__ = ${
JSON.stringify(initialData)
};</script>`
: "";
const htmlLang = lang ? ` lang =${lang}` : "";
const initAttr = htmlAttr ? htmlAttr : ``;
const initBodyAttr = bodyAttr ? ` ${bodyAttr}` : ``;
const initRootAttr = rootAttr ? ` ${rootAttr}` : ``;
const component = ReactDOMServer.renderToString(element);
const title = options.title ?? "";
const link = options.link ?? "";
const meta = options.meta ?? "";
const script = options.script ?? "";
const style = options.style ?? "";
const bundle = options.bundle ?? "bundle";
const description = ogDescription ? createDescription(ogDescription) : "";
const initOgTitle = ogTitle ? createTitle(ogTitle) : "";
const initOgImage = ogImage ? createImage(ogImage) : "";
const initOgSiteName = ogSiteName ? createSiteName(ogSiteName) : "";
const initOgType = ogType ? createType(ogType) : "";
const initOgURL = ogURL ? createURL(ogURL) : "";
const initTwitterCard = twitterCard ? createTwitterCard(twitterCard) : "";
const alt = twitterImageAlt ? createTwitterImageAlt(twitterImageAlt) : "";
const initMetaDesc = metaDesc ? createMetaDescription(metaDesc) : "";
return `<!DOCTYPE html><html ${initAttr} ${htmlLang}><head><meta charset="UTF-8">${meta}${initMetaDesc}${description}${initOgTitle}${initOgImage}${initOgSiteName}${initOgType}${initOgURL}${initTwitterCard}${alt}${title}${link}${style}${props}</head><body${initBodyAttr}><div id="root" ${initRootAttr}>${component}</div><script type="module" src="${staticPath}/${bundle}.js"></script>${script}<body></html>`;
}
const instance = {
dir: (d: string) => {
pageDir = d;
return instance;
},
title: (t: string) => {
title = `<title>${t}</title>`;
return instance;
},
script: (s: string) => {
const script = createScript(s);
const found = scriptInstance.find((v) => {
return v === script;
});
if (!found) {
scriptInstance.push(script);
}
return instance;
},
htmlAttr: (a: string) => {
htmlAttr = a;
return instance;
},
bodyAttr: (b: string) => {
bodyAttr = b;
return instance;
},
rootAttr: (r: string) => {
rootAttr = r;
return instance;
},
ogDesc: (d: string) => {
ogDescription = d;
return instance;
},
ogTitle: (t: string) => {
ogTitle = t;
return instance;
},
ogType: (t: string) => {
ogType = t;
return instance;
},
ogImage: (i: string) => {
ogImage = i;
return instance;
},
ogURL: (u: string) => {
ogURL = u;
return instance;
},
ogSiteName: (name: string) => {
ogSiteName = name;
return instance;
},
twitterCard: (c: string) => {
twitterCard = c;
return instance;
},
metaDesc: (d: string) => {
metaDesc = d;
return instance;
},
meta: (m: string) => {
const meta = createMeta(m);
const found = metaInstance.find((v) => {
return v === meta;
});
if (!found) {
metaInstance.push(meta);
}
return instance;
},
style: (s: string) => {
const style = createStyle(s);
const found = styleInstance.find((v) => {
return v === style;
});
if (!found) {
styleInstance.push(style);
}
return instance;
},
link: (l: string) => {
const link = createLink(l);
const found = linkInstance.find((v) => {
return v === link;
});
if (!found) {
linkInstance.push(link);
}
return instance;
},
cdn: (path: string) => {
staticPath = path;
return instance;
},
props: (p: any) => {
props = p;
return instance;
},
lang: (l: string) => {
lang = l;
return instance;
},
request: (r: HttpRequest) => {
httpRequest = r;
return instance;
},
cache: (c: Container) => {
cache = c;
return instance;
},
render: () => {
const bundle = bundleName;
const meta = metaInstance.length > 0 ? metaInstance.join("") : "";
const script = scriptInstance.length > 0 ? scriptInstance.join("") : "";
const link = linkInstance.length > 0 ? linkInstance.join("") : "";
const style = styleInstance.length > 0 ? styleInstance.join("") : "";
const opt = {
title,
meta,
script,
link,
style,
bundle,
};
const pageID = "ssr-" + httpRequest.url;
if (cache.get(pageID)) {
html = <string> cache.get(pageID);
} else {
html = createHTML(element, opt, props);
cache.set(pageID, html, {
isExpired: true,
expirySeconds: EXPIRY_SECONDS,
});
}
return new Response(html, {
status,
statusText: STATUS_TEXT[<Status> status],
headers: {
"Cache-Control": "max-age=0",
"content-type": "text/html",
},
});
},
bundle: (name: string) => {
bundleName = name;
return instance;
},
_createBundle: createBundle,
_getBundleName: () => bundleName,
};
return instance;
}