forked from sveltejs/kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.js
250 lines (218 loc) · 7.46 KB
/
render.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
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
import devalue from 'devalue';
import { writable } from 'svelte/store';
import { coalesce_to_error } from '../../../utils/error.js';
import { hash } from '../../hash.js';
import { escape_html_attr } from '../../../utils/escape.js';
import { s } from '../../../utils/misc.js';
// TODO rename this function/module
/**
* @param {{
* branch: Array<import('./types').Loaded>;
* options: import('types/internal').SSRRenderOptions;
* $session: any;
* page_config: { hydrate: boolean, router: boolean, ssr: boolean };
* status: number;
* error?: Error,
* url: URL;
* params: Record<string, string>
* }} opts
*/
export async function render_response({
branch,
options,
$session,
page_config,
status,
error,
url,
params
}) {
const css = new Set(options.manifest._.entry.css);
const js = new Set(options.manifest._.entry.js);
const styles = new Set();
/** @type {Array<{ url: string, body: string, json: string }>} */
const serialized_data = [];
let rendered;
let is_private = false;
let maxage;
if (error) {
error.stack = options.get_stack(error);
}
if (page_config.ssr) {
branch.forEach(({ node, loaded, fetched, uses_credentials }) => {
if (node.css) node.css.forEach((url) => css.add(url));
if (node.js) node.js.forEach((url) => js.add(url));
if (node.styles) node.styles.forEach((content) => styles.add(content));
// TODO probably better if `fetched` wasn't populated unless `hydrate`
if (fetched && page_config.hydrate) serialized_data.push(...fetched);
if (uses_credentials) is_private = true;
maxage = loaded.maxage;
});
const session = writable($session);
/** @type {Record<string, any>} */
const props = {
stores: {
page: writable(null),
navigating: writable(null),
session
},
page: { url, params, status, error },
components: branch.map(({ node }) => node.module.default)
};
// TODO remove this for 1.0
/**
* @param {string} property
* @param {string} replacement
*/
const print_error = (property, replacement) => {
Object.defineProperty(props.page, property, {
get: () => {
throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
}
});
};
print_error('origin', 'origin');
print_error('path', 'pathname');
print_error('query', 'searchParams');
// props_n (instead of props[n]) makes it easy to avoid
// unnecessary updates for layout components
for (let i = 0; i < branch.length; i += 1) {
props[`props_${i}`] = await branch[i].loaded.props;
}
let session_tracking_active = false;
const unsubscribe = session.subscribe(() => {
if (session_tracking_active) is_private = true;
});
session_tracking_active = true;
try {
rendered = options.root.render(props);
} finally {
unsubscribe();
}
} else {
rendered = { head: '', html: '', css: { code: '', map: null } };
}
const include_js = page_config.router || page_config.hydrate;
if (!include_js) js.clear();
// TODO strip the AMP stuff out of the build if not relevant
const links = options.amp
? styles.size > 0 || rendered.css.code.length > 0
? `<style amp-custom>${Array.from(styles).concat(rendered.css.code).join('\n')}</style>`
: ''
: [
// From https://web.dev/priority-hints/:
// Generally, preloads will load in the order the parser gets to them for anything above "Medium" priority
// Thus, we should list CSS first
...Array.from(css).map((dep) => `<link rel="stylesheet" href="${options.prefix}${dep}">`),
...Array.from(js).map((dep) => `<link rel="modulepreload" href="${options.prefix}${dep}">`)
].join('\n\t\t');
/** @type {string} */
let init = '';
if (options.amp) {
init = `
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style>
<noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
<script async src="https://cdn.ampproject.org/v0.js"></script>`;
init += options.service_worker
? '<script async custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js"></script>'
: '';
} else if (include_js) {
// prettier-ignore
init = `<script type="module">
import { start } from ${s(options.prefix + options.manifest._.entry.file)};
start({
target: ${options.target ? `document.querySelector(${s(options.target)})` : 'document.body'},
paths: ${s(options.paths)},
session: ${try_serialize($session, (error) => {
throw new Error(`Failed to serialize session data: ${error.message}`);
})},
route: ${!!page_config.router},
spa: ${!page_config.ssr},
trailing_slash: ${s(options.trailing_slash)},
hydrate: ${page_config.ssr && page_config.hydrate ? `{
status: ${status},
error: ${serialize_error(error)},
nodes: [
${(branch || [])
.map(({ node }) => `import(${s(options.prefix + node.entry)})`)
.join(',\n\t\t\t\t\t\t')}
],
url: new URL(${s(url.href)}),
params: ${devalue(params)}
}` : 'null'}
});
</script>`;
}
if (options.service_worker && !options.amp) {
init += `<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('${options.service_worker}');
}
</script>`;
}
const head = [
rendered.head,
styles.size && !options.amp
? `<style data-svelte>${Array.from(styles).join('\n')}</style>`
: '',
links,
init
].join('\n\n\t\t');
let body = rendered.html;
if (options.amp) {
if (options.service_worker) {
body += `<amp-install-serviceworker src="${options.service_worker}" layout="nodisplay"></amp-install-serviceworker>`;
}
} else {
body += serialized_data
.map(({ url, body, json }) => {
let attributes = `type="application/json" data-type="svelte-data" data-url=${escape_html_attr(
url
)}`;
if (body) attributes += ` data-body="${hash(body)}"`;
return `<script ${attributes}>${json}</script>`;
})
.join('\n\n\t');
}
/** @type {import('types/helper').ResponseHeaders} */
const headers = {
'content-type': 'text/html'
};
if (maxage) {
headers['cache-control'] = `${is_private ? 'private' : 'public'}, max-age=${maxage}`;
}
if (!options.floc) {
headers['permissions-policy'] = 'interest-cohort=()';
}
return {
status,
headers,
body: options.template({ head, body })
};
}
/**
* @param {any} data
* @param {(error: Error) => void} [fail]
*/
function try_serialize(data, fail) {
try {
return devalue(data);
} catch (err) {
if (fail) fail(coalesce_to_error(err));
return null;
}
}
// Ensure we return something truthy so the client will not re-render the page over the error
/** @param {(Error & {frame?: string} & {loc?: object}) | undefined | null} error */
function serialize_error(error) {
if (!error) return null;
let serialized = try_serialize(error);
if (!serialized) {
const { name, message, stack } = error;
serialized = try_serialize({ ...error, name, message, stack });
}
if (!serialized) {
serialized = '{}';
}
return serialized;
}