/
index.js
332 lines (295 loc) · 8.82 KB
/
index.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
import { text } from '../../../exports/index.js';
import { compact } from '../../../utils/array.js';
import { normalize_error } from '../../../utils/error.js';
import { add_data_suffix } from '../../../utils/url.js';
import { HttpError, Redirect } from '../../control.js';
import {
get_option,
redirect_response,
static_error_page,
handle_error_and_jsonify,
serialize_data_node
} from '../utils.js';
import {
handle_action_json_request,
handle_action_request,
is_action_json_request,
is_action_request
} from './actions.js';
import { load_data, load_server_data } from './load_data.js';
import { render_response } from './render.js';
import { respond_with_error } from './respond_with_error.js';
/**
* @param {import('types').RequestEvent} event
* @param {import('types').SSRRoute} route
* @param {import('types').PageNodeIndexes} page
* @param {import('types').SSROptions} options
* @param {import('types').SSRManifest} manifest
* @param {import('types').SSRState} state
* @param {import('types').RequiredResolveOptions} resolve_opts
* @returns {Promise<Response>}
*/
export async function render_page(event, route, page, options, manifest, state, resolve_opts) {
if (state.initiator === route) {
// infinite request cycle detected
return text(`Not found: ${event.url.pathname}`, {
status: 404
});
}
state.initiator = route;
if (is_action_json_request(event)) {
const node = await manifest._.nodes[page.leaf]();
return handle_action_json_request(event, options, node?.server);
}
try {
const nodes = await Promise.all([
// we use == here rather than === because [undefined] serializes as "[null]"
...page.layouts.map((n) => (n == undefined ? n : manifest._.nodes[n]())),
manifest._.nodes[page.leaf]()
]);
const leaf_node = /** @type {import('types').SSRNode} */ (nodes.at(-1));
let status = 200;
/** @type {import('types').ActionResult | undefined} */
let action_result = undefined;
if (is_action_request(event, leaf_node)) {
// for action requests, first call handler in +page.server.js
// (this also determines status code)
action_result = await handle_action_request(event, leaf_node.server);
if (action_result?.type === 'redirect') {
return redirect_response(action_result.status, action_result.location);
}
if (action_result?.type === 'error') {
const error = action_result.error;
status = error instanceof HttpError ? error.status : 500;
}
if (action_result?.type === 'failure') {
status = action_result.status;
}
}
const should_prerender_data = nodes.some((node) => node?.server);
const data_pathname = add_data_suffix(event.url.pathname);
// it's crucial that we do this before returning the non-SSR response, otherwise
// SvelteKit will erroneously believe that the path has been prerendered,
// causing functions to be omitted from the manifesst generated later
const should_prerender = get_option(nodes, 'prerender');
if (should_prerender) {
const mod = leaf_node.server;
if (mod && mod.actions) {
throw new Error('Cannot prerender pages with actions');
}
} else if (state.prerendering) {
// Try to render the shell when ssr is false and prerendering not explicitly disabled.
// People can opt out of this behavior by explicitly setting prerender to false.
if (
should_prerender !== false &&
get_option(nodes, 'ssr') === false &&
!leaf_node.server?.actions
) {
return await render_response({
branch: [],
fetched: [],
page_config: {
ssr: false,
csr: get_option(nodes, 'csr') ?? true
},
status,
error: null,
event,
options,
manifest,
state,
resolve_opts
});
}
// if the page isn't marked as prerenderable, then bail out at this point
return new Response(undefined, {
status: 204
});
}
// if we fetch any endpoints while loading data for this page, they should
// inherit the prerender option of the page
state.prerender_default = should_prerender;
/** @type {import('./types').Fetched[]} */
const fetched = [];
if (get_option(nodes, 'ssr') === false) {
return await render_response({
branch: [],
fetched,
page_config: {
ssr: false,
csr: get_option(nodes, 'csr') ?? true
},
status,
error: null,
event,
options,
manifest,
state,
resolve_opts
});
}
/** @type {Array<import('./types.js').Loaded | null>} */
let branch = [];
/** @type {Error | null} */
let load_error = null;
/** @type {Array<Promise<import('types').ServerDataNode | null>>} */
const server_promises = nodes.map((node, i) => {
if (load_error) {
// if an error happens immediately, don't bother with the rest of the nodes
throw load_error;
}
return Promise.resolve().then(async () => {
try {
if (node === leaf_node && action_result?.type === 'error') {
// we wait until here to throw the error so that we can use
// any nested +error.svelte components that were defined
throw action_result.error;
}
return await load_server_data({
event,
state,
node,
parent: async () => {
/** @type {Record<string, any>} */
const data = {};
for (let j = 0; j < i; j += 1) {
const parent = await server_promises[j];
if (parent) Object.assign(data, await parent.data);
}
return data;
}
});
} catch (e) {
load_error = /** @type {Error} */ (e);
throw load_error;
}
});
});
const csr = get_option(nodes, 'csr') ?? true;
/** @type {Array<Promise<Record<string, any> | null>>} */
const load_promises = nodes.map((node, i) => {
if (load_error) throw load_error;
return Promise.resolve().then(async () => {
try {
return await load_data({
event,
fetched,
node,
parent: async () => {
const data = {};
for (let j = 0; j < i; j += 1) {
Object.assign(data, await load_promises[j]);
}
return data;
},
resolve_opts,
server_data_promise: server_promises[i],
state,
csr
});
} catch (e) {
load_error = /** @type {Error} */ (e);
throw load_error;
}
});
});
// if we don't do this, rejections will be unhandled
for (const p of server_promises) p.catch(() => {});
for (const p of load_promises) p.catch(() => {});
for (let i = 0; i < nodes.length; i += 1) {
const node = nodes[i];
if (node) {
try {
const server_data = await server_promises[i];
const data = await load_promises[i];
branch.push({ node, server_data, data });
} catch (e) {
const err = normalize_error(e);
if (err instanceof Redirect) {
if (state.prerendering && should_prerender_data) {
const body = JSON.stringify({
type: 'redirect',
location: err.location
});
state.prerendering.dependencies.set(data_pathname, {
response: text(body),
body
});
}
return redirect_response(err.status, err.location);
}
const status = err instanceof HttpError ? err.status : 500;
const error = await handle_error_and_jsonify(event, options, err);
while (i--) {
if (page.errors[i]) {
const index = /** @type {number} */ (page.errors[i]);
const node = await manifest._.nodes[index]();
let j = i;
while (!branch[j]) j -= 1;
return await render_response({
event,
options,
manifest,
state,
resolve_opts,
page_config: { ssr: true, csr: true },
status,
error,
branch: compact(branch.slice(0, j + 1)).concat({
node,
data: null,
server_data: null
}),
fetched
});
}
}
// if we're still here, it means the error happened in the root layout,
// which means we have to fall back to error.html
return static_error_page(options, status, error.message);
}
} else {
// push an empty slot so we can rewind past gaps to the
// layout that corresponds with an +error.svelte page
branch.push(null);
}
}
if (state.prerendering && should_prerender_data) {
const body = `{"type":"data","nodes":[${branch
.map((node) => serialize_data_node(node?.server_data))
.join(',')}]}`;
state.prerendering.dependencies.set(data_pathname, {
response: text(body),
body
});
}
return await render_response({
event,
options,
manifest,
state,
resolve_opts,
page_config: {
csr: get_option(nodes, 'csr') ?? true,
ssr: true
},
status,
error: null,
branch: compact(branch),
action_result,
fetched
});
} catch (e) {
// if we end up here, it means the data loaded successfull
// but the page failed to render, or that a prerendering error occurred
return await respond_with_error({
event,
options,
manifest,
state,
status: 500,
error: e,
resolve_opts
});
}
}