-
Notifications
You must be signed in to change notification settings - Fork 170
/
ssr.ts
233 lines (217 loc) · 7.1 KB
/
ssr.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
import { createBlankRouterURL, RouteModule } from '../framework/core/routing.ts'
import log from '../shared/log.ts'
import util from '../shared/util.ts'
import type { RouterURL } from '../types.ts'
import type { Application } from './app.ts'
/** The framework render result of SSR. */
export type FrameworkRenderResult = {
head: string[]
body: string
scripts: Record<string, any>[]
data: Record<string, string> | null
}
/** The framework renderer for SSR. */
export type FrameworkRenderer = {
render(
url: RouterURL,
AppComponent: any,
nestedPageComponents: { url: string, Component?: any }[]
): Promise<FrameworkRenderResult>
}
/** The renderer class for aleph server. */
export class Renderer {
#app: Application
#renderer: FrameworkRenderer
constructor(app: Application) {
this.#app = app
this.#renderer = { render: async () => { throw new Error("framework renderer is undefined") } }
}
setFrameworkRenderer(renderer: FrameworkRenderer) {
this.#renderer = renderer
}
/** render page base the given location. */
async renderPage(url: RouterURL, nestedModules: RouteModule[]): Promise<[string, any]> {
const start = performance.now()
const isDev = this.#app.isDev
const appModule = this.#app.findModuleByName('app')
const { default: App } = appModule ? await import(`file://${appModule.jsFile}#${appModule.hash.slice(0, 6)}`) : {} as any
const imports = nestedModules
.filter(({ url }) => this.#app.getModule(url) !== null)
.map(async ({ url }) => {
const { jsFile, hash } = this.#app.getModule(url)!
const { default: Component } = await import(`file://${jsFile}#${hash.slice(0, 6)}`)
return {
url,
Component
}
})
const { head, body, data, scripts } = await this.#renderer.render(
url,
App,
await Promise.all(imports)
)
if (isDev) {
log.info(`render '${url.pathname}' in ${Math.round(performance.now() - start)}ms`)
}
return [
createHtml({
lang: url.locale,
head: head,
scripts: [
data ? {
id: 'ssr-data',
type: 'application/json',
innerText: JSON.stringify(data, undefined, isDev ? 2 : 0),
} : '',
...this.#app.getSSRHTMLScripts(url.pagePath),
...scripts.map((script: Record<string, any>) => {
if (script.innerText && !this.#app.isDev) {
return { ...script, innerText: script.innerText }
}
return script
})
],
body: `<div id="__aleph">${body}</div>`,
minify: !isDev
}),
data
]
}
/** render custom 404 page. */
async render404Page(url: RouterURL): Promise<string> {
const appModule = this.#app.findModuleByName('app')
const e404Module = this.#app.findModuleByName('404')
const { default: App } = appModule ? await import(`file://${appModule.jsFile}#${appModule.hash.slice(0, 6)}`) : {} as any
const { default: E404 } = e404Module ? await import(`file://${e404Module.jsFile}#${e404Module.hash.slice(0, 6)}`) : {} as any
const { head, body, data, scripts } = await this.#renderer.render(
url,
App,
e404Module ? [{ url: e404Module.url, Component: E404 }] : []
)
return createHtml({
lang: url.locale,
head,
scripts: [
data ? {
id: 'ssr-data',
type: 'application/json',
innerText: JSON.stringify(data, undefined, this.#app.isDev ? 2 : 0),
} : '',
...this.#app.getSSRHTMLScripts(),
...scripts.map((script: Record<string, any>) => {
if (script.innerText && !this.#app.isDev) {
return { ...script, innerText: script.innerText }
}
return script
})
],
body: `<div id="__aleph">${body}</div>`,
minify: !this.#app.isDev
})
}
/** render custom loading page for SPA mode. */
async renderSPAIndexPage(): Promise<string> {
const { baseUrl, defaultLocale } = this.#app.config
const loadingModule = this.#app.findModuleByName('loading')
if (loadingModule) {
const { default: Loading } = await import(`file://${loadingModule.jsFile}#${loadingModule.hash.slice(0, 6)}`)
const {
head,
body,
scripts
} = await this.#renderer.render(
createBlankRouterURL(baseUrl, defaultLocale),
undefined,
[{ url: loadingModule.url, Component: Loading }]
)
return createHtml({
lang: defaultLocale,
head,
scripts: [
...this.#app.getSSRHTMLScripts(),
...scripts.map((script: Record<string, any>) => {
if (script.innerText && !this.#app.isDev) {
return { ...script, innerText: script.innerText }
}
return script
})
],
body: `<div id="__aleph">${body}</div>`,
minify: !this.#app.isDev
})
}
return createHtml({
lang: defaultLocale,
head: [],
scripts: this.#app.getSSRHTMLScripts(),
body: '',
minify: !this.#app.isDev
})
}
}
/** create html content by given arguments */
function createHtml({
body,
lang = 'en',
head = [],
className,
scripts = [],
minify = false
}: {
body: string,
lang?: string,
head?: string[],
className?: string,
scripts?: (string | { id?: string, type?: string, src?: string, innerText?: string, nomodule?: boolean, async?: boolean })[],
minify?: boolean
}) {
const eol = minify ? '' : '\n'
const indent = minify ? '' : ' '.repeat(2)
const headTags = head.map(tag => tag.trim()).concat(scripts.map(v => {
if (!util.isString(v) && util.isNEString(v.src)) {
if (v.type === 'module') {
return `<link rel="modulepreload" href=${JSON.stringify(util.cleanPath(v.src))} />`
} else if (!v.nomodule) {
return `<link rel="preload" href=${JSON.stringify(util.cleanPath(v.src))} as="script" />`
}
}
return ''
})).filter(Boolean)
const scriptTags = scripts.map(v => {
if (util.isString(v)) {
return `<script>${v}</script>`
} else if (util.isNEString(v.innerText)) {
const { innerText, ...rest } = v
return `<script${formatAttrs(rest)}>${eol}${innerText}${eol}${indent}</script>`
} else if (util.isNEString(v.src)) {
return `<script${formatAttrs({ ...v, src: util.cleanPath(v.src) })}></script>`
} else {
return ''
}
}).filter(Boolean)
if (!head.some(tag => tag.trimLeft().startsWith('<meta') && tag.includes('name="viewport"'))) {
headTags.unshift('<meta name="viewport" content="width=device-width" />')
}
return [
'<!DOCTYPE html>',
`<html lang="${lang}">`,
'<head>',
indent + '<meta charSet="utf-8" />',
...headTags.map(tag => indent + tag),
'</head>',
className ? `<body class="${className}">` : '<body>',
indent + body,
...scriptTags.map(tag => indent + tag),
'</body>',
'</html>'
].join(eol)
}
function formatAttrs(v: any): string {
return Object.keys(v).filter(k => !!v[k]).map(k => {
if (v[k] === true) {
return ` ${k}`
} else {
return ` ${k}=${JSON.stringify(String(v[k]))}`
}
}).join('')
}