-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathpage.js
476 lines (407 loc) · 12.4 KB
/
page.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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import devalue from 'devalue';
import fetch, { Response } from 'node-fetch';
import { writable } from 'svelte/store';
import { parse, resolve, URLSearchParams } from 'url';
import { normalize } from '../load.js';
import { ssr } from './index.js';
/**
* @param {{
* request: import('types.internal').Request;
* options: import('types.internal').SSRRenderOptions;
* $session: any;
* route: import('types.internal').SSRPage;
* status: number;
* error: Error
* }} opts
* @returns {Promise<import('types.internal').SKResponse>}
*/
async function get_response({ request, options, $session, route, status = 200, error }) {
const host = options.host || request.headers[options.host_header];
/** @type {Record<string, import('types.internal').SKResponse>} */
const dependencies = {};
const serialized_session = try_serialize($session, (error) => {
throw new Error(`Failed to serialize session data: ${error.message}`);
});
/** @type {Array<{ url: string, payload: string }>} */
const serialized_data = [];
const match = route && route.pattern.exec(request.path);
const params = route && route.params(match);
const page = {
host,
path: request.path,
query: request.query,
params
};
let uses_credentials = false;
/**
* @param {RequestInfo} resource
* @param {RequestInit} opts
*/
const fetcher = async (resource, opts = {}) => {
/** @type {string} */
let url;
if (typeof resource === 'string') {
url = resource;
} else {
url = resource.url;
opts = {
method: resource.method,
headers: resource.headers,
body: resource.body,
mode: resource.mode,
credentials: resource.credentials,
cache: resource.cache,
redirect: resource.redirect,
referrer: resource.referrer,
integrity: resource.integrity,
...opts
};
}
if (options.local && url.startsWith(options.paths.assets)) {
// when running `start`, or prerendering, `assets` should be
// config.kit.paths.assets, but we should still be able to fetch
// assets directly from `static`
url = url.replace(options.paths.assets, '');
}
const parsed = parse(url);
// TODO: fix type https://github.com/node-fetch/node-fetch/issues/1113
if (opts.credentials !== 'omit') {
uses_credentials = true;
}
let response;
if (parsed.protocol) {
// external fetch
response = await fetch(parsed.href, /** @type {import('node-fetch').RequestInit} */ (opts));
} else {
// otherwise we're dealing with an internal fetch
const resolved = resolve(request.path, parsed.pathname);
// handle fetch requests for static assets. e.g. prebaked data, etc.
// we need to support everything the browser's fetch supports
const filename = resolved.slice(1);
const filename_html = `${filename}/index.html`; // path may also match path/index.html
const asset = options.manifest.assets.find(
(d) => d.file === filename || d.file === filename_html
);
if (asset) {
// we don't have a running server while prerendering because jumping between
// processes would be inefficient so we have get_static_file instead
if (options.get_static_file) {
response = new Response(options.get_static_file(asset.file), {
headers: {
'content-type': asset.type
}
});
} else {
// TODO we need to know what protocol to use
response = await fetch(
`http://${page.host}/${asset.file}`,
/** @type {import('node-fetch').RequestInit} */ (opts)
);
}
}
if (!response) {
const rendered = await ssr(
{
host: request.host,
method: opts.method || 'GET',
headers: /** @type {import('types.internal').Headers} */ (opts.headers || {}), // TODO inject credentials...
path: resolved,
body: opts.body,
query: new URLSearchParams(parsed.query || '')
},
{
...options,
fetched: url,
initiator: route
}
);
if (rendered) {
// TODO this is primarily for the benefit of the static case,
// but could it be used elsewhere?
dependencies[resolved] = rendered;
response = new Response(rendered.body, {
status: rendered.status,
headers: rendered.headers
});
}
}
}
if (response) {
const clone = response.clone();
/** @type {import('types.internal').Headers} */
const headers = {};
clone.headers.forEach((value, key) => {
if (key !== 'etag') headers[key] = value;
});
const payload = JSON.stringify({
status: clone.status,
statusText: clone.statusText,
headers,
body: await clone.text() // TODO handle binary data
});
// TODO i guess we need to sanitize/escape this... somehow?
serialized_data.push({ url, payload });
return response;
}
return new Response('Not found', {
status: 404
});
};
const component_promises = error
? [options.manifest.layout()]
: [options.manifest.layout(), ...route.parts.map((part) => part.load())];
const components = [];
const props_promises = [];
let context = {};
let maxage;
if (options.only_render_prerenderable_pages) {
if (error) return; // don't prerender an error page
// if the page has `export const prerender = true`, continue,
// otherwise bail out at this point
const mod = await component_promises[component_promises.length - 1];
if (!mod.prerender) return;
}
for (let i = 0; i < component_promises.length; i += 1) {
let loaded;
try {
const mod = await component_promises[i];
components[i] = mod.default;
if (mod.preload) {
throw new Error(
'preload has been deprecated in favour of load. Please consult the documentation: https://kit.svelte.dev/docs#load'
);
}
if (mod.load) {
loaded = await mod.load.call(null, {
page,
get session() {
uses_credentials = true;
return $session;
},
fetch: fetcher,
context: { ...context }
});
if (!loaded) return;
}
} catch (e) {
// if load fails when we're already rendering the
// error page, there's not a lot we can do
if (error) throw e instanceof Error ? e : new Error(e);
loaded = {
error: e instanceof Error ? e : { name: 'Error', message: e.toString() },
status: 500
};
}
if (loaded) {
loaded = normalize(loaded);
// TODO there's some logic that's duplicated in the client runtime,
// it would be nice to DRY it out if possible
if (loaded.error) {
return await get_response({
request,
options,
$session,
route,
status: loaded.status,
error: loaded.error
});
}
if (loaded.redirect) {
return {
status: loaded.status,
headers: {
location: loaded.redirect
}
};
}
if (loaded.context) {
context = {
...context,
...loaded.context
};
}
maxage = loaded.maxage || 0;
props_promises[i] = loaded.props;
}
}
const session = writable($session);
let session_tracking_active = false;
const unsubscribe = session.subscribe(() => {
if (session_tracking_active) uses_credentials = true;
});
session_tracking_active = true;
if (error) {
if (options.dev) {
error.stack = await options.get_stack(error);
} else {
// remove error.stack in production
error.stack = String(error);
}
}
/** @type {Record<string, any>} */
const props = {
status,
error,
stores: {
page: writable(null),
navigating: writable(null),
session
},
page,
components
};
// leveln (instead of levels[n]) makes it easy to avoid
// unnecessary updates for layout components
for (let i = 0; i < props_promises.length; i += 1) {
props[`props_${i}`] = await props_promises[i];
}
let rendered;
try {
rendered = options.root.render(props);
} catch (e) {
if (error) throw e instanceof Error ? e : new Error(e);
return await get_response({
request,
options,
$session,
route,
status: 500,
error: e instanceof Error ? e : { name: 'Error', message: e.toString() }
});
}
unsubscribe();
// TODO all the `route &&` stuff is messy
const js_deps = route ? route.js : [];
const css_deps = route ? route.css : [];
const style = route ? route.style : '';
const s = JSON.stringify;
const prefix = `${options.paths.assets}/${options.app_dir}`;
// TODO strip the AMP stuff out of the build if not relevant
const links = options.amp
? `<style amp-custom>${
style || (await Promise.all(css_deps.map((dep) => options.get_amp_css(dep)))).join('\n')
}</style>`
: [
...js_deps.map((dep) => `<link rel="modulepreload" href="${prefix}/${dep}">`),
...css_deps.map((dep) => `<link rel="stylesheet" href="${prefix}/${dep}">`)
].join('\n\t\t\t');
const init = options.amp
? `
<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>`
: `
<script type="module">
import { start } from ${s(options.entry)};
start({
target: ${options.target ? `document.querySelector(${s(options.target)})` : 'document.body'},
paths: ${s(options.paths)},
status: ${status},
error: ${serialize_error(error)},
session: ${serialized_session},
nodes: [
${(route ? route.parts : [])
.map((part) => `import(${s(options.get_component_path(part.id))})`)
.join(',\n\t\t\t\t\t')}
],
page: {
host: ${host ? s(host) : 'location.host'},
path: ${s(request.path)},
query: new URLSearchParams(${s(request.query.toString())}),
params: ${s(params)}
}
});
</script>`;
const head = [
rendered.head,
style && !options.amp ? `<style data-svelte>${style}</style>` : '',
links,
init
].join('\n\n');
const body = options.amp
? rendered.html
: `${rendered.html}
${serialized_data
.map(({ url, payload }) => `<script type="svelte-data" url="${url}">${payload}</script>`)
.join('\n\n\t\t\t')}
`.replace(/^\t{2}/gm, '');
/** @type {import('types.internal').Headers} */
const headers = {
'content-type': 'text/html'
};
if (maxage) {
headers['cache-control'] = `${uses_credentials ? 'private' : 'public'}, max-age=${maxage}`;
}
return {
status,
headers,
body: options.template({ head, body }),
dependencies
};
}
/**
* @param {import('types.internal').Request} request
* @param {import('types.internal').SSRPage} route
* @param {any} context
* @param {import('types.internal').SSRRenderOptions} options
* @returns {Promise<import('types.internal').SKResponse>}
*/
export default async function render_page(request, route, context, options) {
if (options.initiator === route) {
// infinite request cycle detected
return {
status: 404,
headers: {},
body: `Not found: ${request.path}`
};
}
const $session = await (options.setup.getSession && options.setup.getSession({ context }));
const response = await get_response({
request,
options,
$session,
route,
status: route ? 200 : 404,
error: route ? null : new Error(`Not found: ${request.path}`)
});
if (response) {
return response;
}
if (options.fetched) {
// we came here because of a bad request in a `load` function.
// rather than render the error page — which could lead to an
// infinite loop, if the `load` belonged to the root layout,
// we respond with a bare-bones 500
return {
status: 500,
headers: {},
body: `Bad request in load function: failed to fetch ${options.fetched}`
};
}
}
/**
* @param {any} data
* @param {(error: Error) => void} [fail]
*/
function try_serialize(data, fail) {
try {
return devalue(data);
} catch (err) {
if (fail) fail(err);
return null;
}
}
// Ensure we return something truthy so the client will not re-render the page over the error
/** @param {Error} error */
function serialize_error(error) {
if (!error) return null;
let serialized = try_serialize(error);
if (!serialized) {
const { name, message, stack } = error;
serialized = try_serialize({ name, message, stack });
}
if (!serialized) {
serialized = '{}';
}
return serialized;
}