@sveltejs/kit 1.0.0-next.36 → 1.0.0-next.360

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +28 -0
  3. package/assets/app/navigation.js +24 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/app/stores.js +97 -0
  6. package/assets/client/singletons.js +13 -0
  7. package/assets/client/start.js +1789 -0
  8. package/assets/components/error.svelte +18 -2
  9. package/assets/env.js +8 -0
  10. package/assets/paths.js +13 -0
  11. package/assets/server/index.js +3407 -0
  12. package/dist/chunks/_commonjsHelpers.js +3 -0
  13. package/dist/chunks/error.js +663 -0
  14. package/dist/chunks/index.js +15744 -0
  15. package/dist/chunks/index2.js +210 -0
  16. package/dist/chunks/multipart-parser.js +445 -0
  17. package/dist/chunks/sync.js +980 -0
  18. package/dist/chunks/write_tsconfig.js +274 -0
  19. package/dist/cli.js +64 -117
  20. package/dist/hooks.js +28 -0
  21. package/dist/node/polyfills.js +12238 -0
  22. package/dist/node.js +5855 -0
  23. package/dist/vite.js +3143 -0
  24. package/package.json +100 -55
  25. package/types/ambient.d.ts +345 -0
  26. package/types/index.d.ts +294 -0
  27. package/types/internal.d.ts +326 -0
  28. package/types/private.d.ts +235 -0
  29. package/CHANGELOG.md +0 -377
  30. package/assets/runtime/app/navigation.js +0 -23
  31. package/assets/runtime/app/navigation.js.map +0 -1
  32. package/assets/runtime/app/paths.js +0 -2
  33. package/assets/runtime/app/paths.js.map +0 -1
  34. package/assets/runtime/app/stores.js +0 -78
  35. package/assets/runtime/app/stores.js.map +0 -1
  36. package/assets/runtime/internal/singletons.js +0 -15
  37. package/assets/runtime/internal/singletons.js.map +0 -1
  38. package/assets/runtime/internal/start.js +0 -614
  39. package/assets/runtime/internal/start.js.map +0 -1
  40. package/assets/runtime/utils-85ebcc60.js +0 -18
  41. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  42. package/dist/api.js +0 -28
  43. package/dist/api.js.map +0 -1
  44. package/dist/cli.js.map +0 -1
  45. package/dist/create_app.js +0 -502
  46. package/dist/create_app.js.map +0 -1
  47. package/dist/index.js +0 -327
  48. package/dist/index.js.map +0 -1
  49. package/dist/index2.js +0 -3497
  50. package/dist/index2.js.map +0 -1
  51. package/dist/index3.js +0 -296
  52. package/dist/index3.js.map +0 -1
  53. package/dist/index4.js +0 -311
  54. package/dist/index4.js.map +0 -1
  55. package/dist/index5.js +0 -221
  56. package/dist/index5.js.map +0 -1
  57. package/dist/index6.js +0 -730
  58. package/dist/index6.js.map +0 -1
  59. package/dist/renderer.js +0 -2429
  60. package/dist/renderer.js.map +0 -1
  61. package/dist/standard.js +0 -100
  62. package/dist/standard.js.map +0 -1
  63. package/dist/utils.js +0 -61
  64. package/dist/utils.js.map +0 -1
@@ -0,0 +1,3407 @@
1
+ /** @param {Partial<import('types').ResponseHeaders> | undefined} object */
2
+ function to_headers(object) {
3
+ const headers = new Headers();
4
+
5
+ if (object) {
6
+ for (const key in object) {
7
+ const value = object[key];
8
+ if (!value) continue;
9
+
10
+ if (Array.isArray(value)) {
11
+ value.forEach((value) => {
12
+ headers.append(key, /** @type {string} */ (value));
13
+ });
14
+ } else {
15
+ headers.set(key, /** @type {string} */ (value));
16
+ }
17
+ }
18
+ }
19
+
20
+ return headers;
21
+ }
22
+
23
+ /**
24
+ * Hash using djb2
25
+ * @param {import('types').StrictBody} value
26
+ */
27
+ function hash(value) {
28
+ let hash = 5381;
29
+ let i = value.length;
30
+
31
+ if (typeof value === 'string') {
32
+ while (i) hash = (hash * 33) ^ value.charCodeAt(--i);
33
+ } else {
34
+ while (i) hash = (hash * 33) ^ value[--i];
35
+ }
36
+
37
+ return (hash >>> 0).toString(36);
38
+ }
39
+
40
+ /** @param {Record<string, any>} obj */
41
+ function lowercase_keys(obj) {
42
+ /** @type {Record<string, any>} */
43
+ const clone = {};
44
+
45
+ for (const key in obj) {
46
+ clone[key.toLowerCase()] = obj[key];
47
+ }
48
+
49
+ return clone;
50
+ }
51
+
52
+ /** @param {Record<string, string>} params */
53
+ function decode_params(params) {
54
+ for (const key in params) {
55
+ // input has already been decoded by decodeURI
56
+ // now handle the rest that decodeURIComponent would do
57
+ params[key] = params[key]
58
+ .replace(/%23/g, '#')
59
+ .replace(/%3[Bb]/g, ';')
60
+ .replace(/%2[Cc]/g, ',')
61
+ .replace(/%2[Ff]/g, '/')
62
+ .replace(/%3[Ff]/g, '?')
63
+ .replace(/%3[Aa]/g, ':')
64
+ .replace(/%40/g, '@')
65
+ .replace(/%26/g, '&')
66
+ .replace(/%3[Dd]/g, '=')
67
+ .replace(/%2[Bb]/g, '+')
68
+ .replace(/%24/g, '$');
69
+ }
70
+
71
+ return params;
72
+ }
73
+
74
+ /** @param {any} body */
75
+ function is_pojo(body) {
76
+ if (typeof body !== 'object') return false;
77
+
78
+ if (body) {
79
+ if (body instanceof Uint8Array) return false;
80
+ if (body instanceof ReadableStream) return false;
81
+
82
+ // if body is a node Readable, throw an error
83
+ // TODO remove this for 1.0
84
+ if (body._readableState && typeof body.pipe === 'function') {
85
+ throw new Error('Node streams are no longer supported — use a ReadableStream instead');
86
+ }
87
+ }
88
+
89
+ return true;
90
+ }
91
+
92
+ /** @param {import('types').RequestEvent} event */
93
+ function normalize_request_method(event) {
94
+ const method = event.request.method.toLowerCase();
95
+ return method === 'delete' ? 'del' : method; // 'delete' is a reserved word
96
+ }
97
+
98
+ /** @param {string} body */
99
+ function error(body) {
100
+ return new Response(body, {
101
+ status: 500
102
+ });
103
+ }
104
+
105
+ /** @param {unknown} s */
106
+ function is_string(s) {
107
+ return typeof s === 'string' || s instanceof String;
108
+ }
109
+
110
+ const text_types = new Set([
111
+ 'application/xml',
112
+ 'application/json',
113
+ 'application/x-www-form-urlencoded',
114
+ 'multipart/form-data'
115
+ ]);
116
+
117
+ const bodyless_status_codes = new Set([101, 204, 205, 304]);
118
+
119
+ /**
120
+ * Decides how the body should be parsed based on its mime type
121
+ *
122
+ * @param {string | undefined | null} content_type The `content-type` header of a request/response.
123
+ * @returns {boolean}
124
+ */
125
+ function is_text(content_type) {
126
+ if (!content_type) return true; // defaults to json
127
+ const type = content_type.split(';')[0].toLowerCase(); // get the mime type
128
+
129
+ return type.startsWith('text/') || type.endsWith('+xml') || text_types.has(type);
130
+ }
131
+
132
+ /**
133
+ * @param {import('types').RequestEvent} event
134
+ * @param {{ [method: string]: import('types').RequestHandler }} mod
135
+ * @returns {Promise<Response>}
136
+ */
137
+ async function render_endpoint(event, mod) {
138
+ const method = normalize_request_method(event);
139
+
140
+ /** @type {import('types').RequestHandler} */
141
+ let handler = mod[method];
142
+
143
+ if (!handler && method === 'head') {
144
+ handler = mod.get;
145
+ }
146
+
147
+ if (!handler) {
148
+ const allowed = [];
149
+
150
+ for (const method in ['get', 'post', 'put', 'patch']) {
151
+ if (mod[method]) allowed.push(method.toUpperCase());
152
+ }
153
+
154
+ if (mod.del) allowed.push('DELETE');
155
+ if (mod.get || mod.head) allowed.push('HEAD');
156
+
157
+ return event.request.headers.get('x-sveltekit-load')
158
+ ? // TODO would be nice to avoid these requests altogether,
159
+ // by noting whether or not page endpoints export `get`
160
+ new Response(undefined, {
161
+ status: 204
162
+ })
163
+ : new Response(`${event.request.method} method not allowed`, {
164
+ status: 405,
165
+ headers: {
166
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
167
+ // "The server must generate an Allow header field in a 405 status code response"
168
+ allow: allowed.join(', ')
169
+ }
170
+ });
171
+ }
172
+
173
+ const response = await handler(event);
174
+ const preface = `Invalid response from route ${event.url.pathname}`;
175
+
176
+ if (typeof response !== 'object') {
177
+ return error(`${preface}: expected an object, got ${typeof response}`);
178
+ }
179
+
180
+ // TODO remove for 1.0
181
+ // @ts-expect-error
182
+ if (response.fallthrough) {
183
+ throw new Error(
184
+ 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
185
+ );
186
+ }
187
+
188
+ const { status = 200, body = {} } = response;
189
+ const headers =
190
+ response.headers instanceof Headers
191
+ ? new Headers(response.headers)
192
+ : to_headers(response.headers);
193
+
194
+ const type = headers.get('content-type');
195
+
196
+ if (!is_text(type) && !(body instanceof Uint8Array || is_string(body))) {
197
+ return error(
198
+ `${preface}: body must be an instance of string or Uint8Array if content-type is not a supported textual content-type`
199
+ );
200
+ }
201
+
202
+ /** @type {import('types').StrictBody} */
203
+ let normalized_body;
204
+
205
+ if (is_pojo(body) && (!type || type.startsWith('application/json'))) {
206
+ headers.set('content-type', 'application/json; charset=utf-8');
207
+ normalized_body = JSON.stringify(body);
208
+ } else {
209
+ normalized_body = /** @type {import('types').StrictBody} */ (body);
210
+ }
211
+
212
+ if (
213
+ (typeof normalized_body === 'string' || normalized_body instanceof Uint8Array) &&
214
+ !headers.has('etag')
215
+ ) {
216
+ const cache_control = headers.get('cache-control');
217
+ if (!cache_control || !/(no-store|immutable)/.test(cache_control)) {
218
+ headers.set('etag', `"${hash(normalized_body)}"`);
219
+ }
220
+ }
221
+
222
+ return new Response(
223
+ method !== 'head' && !bodyless_status_codes.has(status) ? normalized_body : undefined,
224
+ {
225
+ status,
226
+ headers
227
+ }
228
+ );
229
+ }
230
+
231
+ var chars$1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
232
+ var unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
233
+ var reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
234
+ var escaped = {
235
+ '<': '\\u003C',
236
+ '>': '\\u003E',
237
+ '/': '\\u002F',
238
+ '\\': '\\\\',
239
+ '\b': '\\b',
240
+ '\f': '\\f',
241
+ '\n': '\\n',
242
+ '\r': '\\r',
243
+ '\t': '\\t',
244
+ '\0': '\\0',
245
+ '\u2028': '\\u2028',
246
+ '\u2029': '\\u2029'
247
+ };
248
+ var objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join('\0');
249
+ function devalue(value) {
250
+ var counts = new Map();
251
+ function walk(thing) {
252
+ if (typeof thing === 'function') {
253
+ throw new Error("Cannot stringify a function");
254
+ }
255
+ if (counts.has(thing)) {
256
+ counts.set(thing, counts.get(thing) + 1);
257
+ return;
258
+ }
259
+ counts.set(thing, 1);
260
+ if (!isPrimitive(thing)) {
261
+ var type = getType(thing);
262
+ switch (type) {
263
+ case 'Number':
264
+ case 'String':
265
+ case 'Boolean':
266
+ case 'Date':
267
+ case 'RegExp':
268
+ return;
269
+ case 'Array':
270
+ thing.forEach(walk);
271
+ break;
272
+ case 'Set':
273
+ case 'Map':
274
+ Array.from(thing).forEach(walk);
275
+ break;
276
+ default:
277
+ var proto = Object.getPrototypeOf(thing);
278
+ if (proto !== Object.prototype &&
279
+ proto !== null &&
280
+ Object.getOwnPropertyNames(proto).sort().join('\0') !== objectProtoOwnPropertyNames) {
281
+ throw new Error("Cannot stringify arbitrary non-POJOs");
282
+ }
283
+ if (Object.getOwnPropertySymbols(thing).length > 0) {
284
+ throw new Error("Cannot stringify POJOs with symbolic keys");
285
+ }
286
+ Object.keys(thing).forEach(function (key) { return walk(thing[key]); });
287
+ }
288
+ }
289
+ }
290
+ walk(value);
291
+ var names = new Map();
292
+ Array.from(counts)
293
+ .filter(function (entry) { return entry[1] > 1; })
294
+ .sort(function (a, b) { return b[1] - a[1]; })
295
+ .forEach(function (entry, i) {
296
+ names.set(entry[0], getName(i));
297
+ });
298
+ function stringify(thing) {
299
+ if (names.has(thing)) {
300
+ return names.get(thing);
301
+ }
302
+ if (isPrimitive(thing)) {
303
+ return stringifyPrimitive(thing);
304
+ }
305
+ var type = getType(thing);
306
+ switch (type) {
307
+ case 'Number':
308
+ case 'String':
309
+ case 'Boolean':
310
+ return "Object(" + stringify(thing.valueOf()) + ")";
311
+ case 'RegExp':
312
+ return "new RegExp(" + stringifyString(thing.source) + ", \"" + thing.flags + "\")";
313
+ case 'Date':
314
+ return "new Date(" + thing.getTime() + ")";
315
+ case 'Array':
316
+ var members = thing.map(function (v, i) { return i in thing ? stringify(v) : ''; });
317
+ var tail = thing.length === 0 || (thing.length - 1 in thing) ? '' : ',';
318
+ return "[" + members.join(',') + tail + "]";
319
+ case 'Set':
320
+ case 'Map':
321
+ return "new " + type + "([" + Array.from(thing).map(stringify).join(',') + "])";
322
+ default:
323
+ var obj = "{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":" + stringify(thing[key]); }).join(',') + "}";
324
+ var proto = Object.getPrototypeOf(thing);
325
+ if (proto === null) {
326
+ return Object.keys(thing).length > 0
327
+ ? "Object.assign(Object.create(null)," + obj + ")"
328
+ : "Object.create(null)";
329
+ }
330
+ return obj;
331
+ }
332
+ }
333
+ var str = stringify(value);
334
+ if (names.size) {
335
+ var params_1 = [];
336
+ var statements_1 = [];
337
+ var values_1 = [];
338
+ names.forEach(function (name, thing) {
339
+ params_1.push(name);
340
+ if (isPrimitive(thing)) {
341
+ values_1.push(stringifyPrimitive(thing));
342
+ return;
343
+ }
344
+ var type = getType(thing);
345
+ switch (type) {
346
+ case 'Number':
347
+ case 'String':
348
+ case 'Boolean':
349
+ values_1.push("Object(" + stringify(thing.valueOf()) + ")");
350
+ break;
351
+ case 'RegExp':
352
+ values_1.push(thing.toString());
353
+ break;
354
+ case 'Date':
355
+ values_1.push("new Date(" + thing.getTime() + ")");
356
+ break;
357
+ case 'Array':
358
+ values_1.push("Array(" + thing.length + ")");
359
+ thing.forEach(function (v, i) {
360
+ statements_1.push(name + "[" + i + "]=" + stringify(v));
361
+ });
362
+ break;
363
+ case 'Set':
364
+ values_1.push("new Set");
365
+ statements_1.push(name + "." + Array.from(thing).map(function (v) { return "add(" + stringify(v) + ")"; }).join('.'));
366
+ break;
367
+ case 'Map':
368
+ values_1.push("new Map");
369
+ statements_1.push(name + "." + Array.from(thing).map(function (_a) {
370
+ var k = _a[0], v = _a[1];
371
+ return "set(" + stringify(k) + ", " + stringify(v) + ")";
372
+ }).join('.'));
373
+ break;
374
+ default:
375
+ values_1.push(Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}');
376
+ Object.keys(thing).forEach(function (key) {
377
+ statements_1.push("" + name + safeProp(key) + "=" + stringify(thing[key]));
378
+ });
379
+ }
380
+ });
381
+ statements_1.push("return " + str);
382
+ return "(function(" + params_1.join(',') + "){" + statements_1.join(';') + "}(" + values_1.join(',') + "))";
383
+ }
384
+ else {
385
+ return str;
386
+ }
387
+ }
388
+ function getName(num) {
389
+ var name = '';
390
+ do {
391
+ name = chars$1[num % chars$1.length] + name;
392
+ num = ~~(num / chars$1.length) - 1;
393
+ } while (num >= 0);
394
+ return reserved.test(name) ? name + "_" : name;
395
+ }
396
+ function isPrimitive(thing) {
397
+ return Object(thing) !== thing;
398
+ }
399
+ function stringifyPrimitive(thing) {
400
+ if (typeof thing === 'string')
401
+ return stringifyString(thing);
402
+ if (thing === void 0)
403
+ return 'void 0';
404
+ if (thing === 0 && 1 / thing < 0)
405
+ return '-0';
406
+ var str = String(thing);
407
+ if (typeof thing === 'number')
408
+ return str.replace(/^(-)?0\./, '$1.');
409
+ return str;
410
+ }
411
+ function getType(thing) {
412
+ return Object.prototype.toString.call(thing).slice(8, -1);
413
+ }
414
+ function escapeUnsafeChar(c) {
415
+ return escaped[c] || c;
416
+ }
417
+ function escapeUnsafeChars(str) {
418
+ return str.replace(unsafeChars, escapeUnsafeChar);
419
+ }
420
+ function safeKey(key) {
421
+ return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
422
+ }
423
+ function safeProp(key) {
424
+ return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? "." + key : "[" + escapeUnsafeChars(JSON.stringify(key)) + "]";
425
+ }
426
+ function stringifyString(str) {
427
+ var result = '"';
428
+ for (var i = 0; i < str.length; i += 1) {
429
+ var char = str.charAt(i);
430
+ var code = char.charCodeAt(0);
431
+ if (char === '"') {
432
+ result += '\\"';
433
+ }
434
+ else if (char in escaped) {
435
+ result += escaped[char];
436
+ }
437
+ else if (code >= 0xd800 && code <= 0xdfff) {
438
+ var next = str.charCodeAt(i + 1);
439
+ // If this is the beginning of a [high, low] surrogate pair,
440
+ // add the next two characters, otherwise escape
441
+ if (code <= 0xdbff && (next >= 0xdc00 && next <= 0xdfff)) {
442
+ result += char + str[++i];
443
+ }
444
+ else {
445
+ result += "\\u" + code.toString(16).toUpperCase();
446
+ }
447
+ }
448
+ else {
449
+ result += char;
450
+ }
451
+ }
452
+ result += '"';
453
+ return result;
454
+ }
455
+
456
+ function noop() { }
457
+ function safe_not_equal(a, b) {
458
+ return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
459
+ }
460
+ Promise.resolve();
461
+
462
+ const subscriber_queue = [];
463
+ /**
464
+ * Creates a `Readable` store that allows reading by subscription.
465
+ * @param value initial value
466
+ * @param {StartStopNotifier}start start and stop notifications for subscriptions
467
+ */
468
+ function readable(value, start) {
469
+ return {
470
+ subscribe: writable(value, start).subscribe
471
+ };
472
+ }
473
+ /**
474
+ * Create a `Writable` store that allows both updating and reading by subscription.
475
+ * @param {*=}value initial value
476
+ * @param {StartStopNotifier=}start start and stop notifications for subscriptions
477
+ */
478
+ function writable(value, start = noop) {
479
+ let stop;
480
+ const subscribers = new Set();
481
+ function set(new_value) {
482
+ if (safe_not_equal(value, new_value)) {
483
+ value = new_value;
484
+ if (stop) { // store is ready
485
+ const run_queue = !subscriber_queue.length;
486
+ for (const subscriber of subscribers) {
487
+ subscriber[1]();
488
+ subscriber_queue.push(subscriber, value);
489
+ }
490
+ if (run_queue) {
491
+ for (let i = 0; i < subscriber_queue.length; i += 2) {
492
+ subscriber_queue[i][0](subscriber_queue[i + 1]);
493
+ }
494
+ subscriber_queue.length = 0;
495
+ }
496
+ }
497
+ }
498
+ }
499
+ function update(fn) {
500
+ set(fn(value));
501
+ }
502
+ function subscribe(run, invalidate = noop) {
503
+ const subscriber = [run, invalidate];
504
+ subscribers.add(subscriber);
505
+ if (subscribers.size === 1) {
506
+ stop = start(set) || noop;
507
+ }
508
+ run(value);
509
+ return () => {
510
+ subscribers.delete(subscriber);
511
+ if (subscribers.size === 0) {
512
+ stop();
513
+ stop = null;
514
+ }
515
+ };
516
+ }
517
+ return { set, update, subscribe };
518
+ }
519
+
520
+ /**
521
+ * @param {unknown} err
522
+ * @return {Error}
523
+ */
524
+ function coalesce_to_error(err) {
525
+ return err instanceof Error ||
526
+ (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message)
527
+ ? /** @type {Error} */ (err)
528
+ : new Error(JSON.stringify(err));
529
+ }
530
+
531
+ /**
532
+ * Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
533
+ *
534
+ * The first closes the script element, so everything after is treated as raw HTML.
535
+ * The second disables further parsing until `-->`, so the script element might be unexpectedly
536
+ * kept open until until an unrelated HTML comment in the page.
537
+ *
538
+ * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
539
+ * browsers.
540
+ *
541
+ * @see tests for unsafe parsing examples.
542
+ * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
543
+ * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
544
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
545
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
546
+ * @see https://github.com/tc39/proposal-json-superset
547
+ * @type {Record<string, string>}
548
+ */
549
+ const render_json_payload_script_dict = {
550
+ '<': '\\u003C',
551
+ '\u2028': '\\u2028',
552
+ '\u2029': '\\u2029'
553
+ };
554
+
555
+ const render_json_payload_script_regex = new RegExp(
556
+ `[${Object.keys(render_json_payload_script_dict).join('')}]`,
557
+ 'g'
558
+ );
559
+
560
+ /**
561
+ * Generates a raw HTML string containing a safe script element carrying JSON data and associated attributes.
562
+ *
563
+ * It escapes all the special characters needed to guarantee the element is unbroken, but care must
564
+ * be taken to ensure it is inserted in the document at an acceptable position for a script element,
565
+ * and that the resulting string isn't further modified.
566
+ *
567
+ * Attribute names must be type-checked so we don't need to escape them.
568
+ *
569
+ * @param {import('types').PayloadScriptAttributes} attrs A list of attributes to be added to the element.
570
+ * @param {import('types').JSONValue} payload The data to be carried by the element. Must be serializable to JSON.
571
+ * @returns {string} The raw HTML of a script element carrying the JSON payload.
572
+ * @example const html = render_json_payload_script({ type: 'data', url: '/data.json' }, { foo: 'bar' });
573
+ */
574
+ function render_json_payload_script(attrs, payload) {
575
+ const safe_payload = JSON.stringify(payload).replace(
576
+ render_json_payload_script_regex,
577
+ (match) => render_json_payload_script_dict[match]
578
+ );
579
+
580
+ let safe_attrs = '';
581
+ for (const [key, value] of Object.entries(attrs)) {
582
+ if (value === undefined) continue;
583
+ safe_attrs += ` sveltekit:data-${key}=${escape_html_attr(value)}`;
584
+ }
585
+
586
+ return `<script type="application/json"${safe_attrs}>${safe_payload}</script>`;
587
+ }
588
+
589
+ /**
590
+ * When inside a double-quoted attribute value, only `&` and `"` hold special meaning.
591
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state
592
+ * @type {Record<string, string>}
593
+ */
594
+ const escape_html_attr_dict = {
595
+ '&': '&amp;',
596
+ '"': '&quot;'
597
+ };
598
+
599
+ const escape_html_attr_regex = new RegExp(
600
+ // special characters
601
+ `[${Object.keys(escape_html_attr_dict).join('')}]|` +
602
+ // high surrogate without paired low surrogate
603
+ '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' +
604
+ // a valid surrogate pair, the only match with 2 code units
605
+ // we match it so that we can match unpaired low surrogates in the same pass
606
+ // TODO: use lookbehind assertions once they are widely supported: (?<![\ud800-udbff])[\udc00-\udfff]
607
+ '[\\ud800-\\udbff][\\udc00-\\udfff]|' +
608
+ // unpaired low surrogate (see previous match)
609
+ '[\\udc00-\\udfff]',
610
+ 'g'
611
+ );
612
+
613
+ /**
614
+ * Formats a string to be used as an attribute's value in raw HTML.
615
+ *
616
+ * It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes
617
+ * characters that are special in attributes, and surrounds the whole string in double-quotes.
618
+ *
619
+ * @param {string} str
620
+ * @returns {string} Escaped string surrounded by double-quotes.
621
+ * @example const html = `<tag data-value=${escape_html_attr('value')}>...</tag>`;
622
+ */
623
+ function escape_html_attr(str) {
624
+ const escaped_str = str.replace(escape_html_attr_regex, (match) => {
625
+ if (match.length === 2) {
626
+ // valid surrogate pair
627
+ return match;
628
+ }
629
+
630
+ return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`;
631
+ });
632
+
633
+ return `"${escaped_str}"`;
634
+ }
635
+
636
+ const s = JSON.stringify;
637
+
638
+ const encoder = new TextEncoder();
639
+
640
+ /**
641
+ * SHA-256 hashing function adapted from https://bitwiseshiftleft.github.io/sjcl
642
+ * modified and redistributed under BSD license
643
+ * @param {string} data
644
+ */
645
+ function sha256(data) {
646
+ if (!key[0]) precompute();
647
+
648
+ const out = init.slice(0);
649
+ const array = encode$1(data);
650
+
651
+ for (let i = 0; i < array.length; i += 16) {
652
+ const w = array.subarray(i, i + 16);
653
+
654
+ let tmp;
655
+ let a;
656
+ let b;
657
+
658
+ let out0 = out[0];
659
+ let out1 = out[1];
660
+ let out2 = out[2];
661
+ let out3 = out[3];
662
+ let out4 = out[4];
663
+ let out5 = out[5];
664
+ let out6 = out[6];
665
+ let out7 = out[7];
666
+
667
+ /* Rationale for placement of |0 :
668
+ * If a value can overflow is original 32 bits by a factor of more than a few
669
+ * million (2^23 ish), there is a possibility that it might overflow the
670
+ * 53-bit mantissa and lose precision.
671
+ *
672
+ * To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that
673
+ * propagates around the loop, and on the hash state out[]. I don't believe
674
+ * that the clamps on out4 and on out0 are strictly necessary, but it's close
675
+ * (for out4 anyway), and better safe than sorry.
676
+ *
677
+ * The clamps on out[] are necessary for the output to be correct even in the
678
+ * common case and for short inputs.
679
+ */
680
+
681
+ for (let i = 0; i < 64; i++) {
682
+ // load up the input word for this round
683
+
684
+ if (i < 16) {
685
+ tmp = w[i];
686
+ } else {
687
+ a = w[(i + 1) & 15];
688
+
689
+ b = w[(i + 14) & 15];
690
+
691
+ tmp = w[i & 15] =
692
+ (((a >>> 7) ^ (a >>> 18) ^ (a >>> 3) ^ (a << 25) ^ (a << 14)) +
693
+ ((b >>> 17) ^ (b >>> 19) ^ (b >>> 10) ^ (b << 15) ^ (b << 13)) +
694
+ w[i & 15] +
695
+ w[(i + 9) & 15]) |
696
+ 0;
697
+ }
698
+
699
+ tmp =
700
+ tmp +
701
+ out7 +
702
+ ((out4 >>> 6) ^ (out4 >>> 11) ^ (out4 >>> 25) ^ (out4 << 26) ^ (out4 << 21) ^ (out4 << 7)) +
703
+ (out6 ^ (out4 & (out5 ^ out6))) +
704
+ key[i]; // | 0;
705
+
706
+ // shift register
707
+ out7 = out6;
708
+ out6 = out5;
709
+ out5 = out4;
710
+
711
+ out4 = (out3 + tmp) | 0;
712
+
713
+ out3 = out2;
714
+ out2 = out1;
715
+ out1 = out0;
716
+
717
+ out0 =
718
+ (tmp +
719
+ ((out1 & out2) ^ (out3 & (out1 ^ out2))) +
720
+ ((out1 >>> 2) ^
721
+ (out1 >>> 13) ^
722
+ (out1 >>> 22) ^
723
+ (out1 << 30) ^
724
+ (out1 << 19) ^
725
+ (out1 << 10))) |
726
+ 0;
727
+ }
728
+
729
+ out[0] = (out[0] + out0) | 0;
730
+ out[1] = (out[1] + out1) | 0;
731
+ out[2] = (out[2] + out2) | 0;
732
+ out[3] = (out[3] + out3) | 0;
733
+ out[4] = (out[4] + out4) | 0;
734
+ out[5] = (out[5] + out5) | 0;
735
+ out[6] = (out[6] + out6) | 0;
736
+ out[7] = (out[7] + out7) | 0;
737
+ }
738
+
739
+ const bytes = new Uint8Array(out.buffer);
740
+ reverse_endianness(bytes);
741
+
742
+ return base64(bytes);
743
+ }
744
+
745
+ /** The SHA-256 initialization vector */
746
+ const init = new Uint32Array(8);
747
+
748
+ /** The SHA-256 hash key */
749
+ const key = new Uint32Array(64);
750
+
751
+ /** Function to precompute init and key. */
752
+ function precompute() {
753
+ /** @param {number} x */
754
+ function frac(x) {
755
+ return (x - Math.floor(x)) * 0x100000000;
756
+ }
757
+
758
+ let prime = 2;
759
+
760
+ for (let i = 0; i < 64; prime++) {
761
+ let is_prime = true;
762
+
763
+ for (let factor = 2; factor * factor <= prime; factor++) {
764
+ if (prime % factor === 0) {
765
+ is_prime = false;
766
+
767
+ break;
768
+ }
769
+ }
770
+
771
+ if (is_prime) {
772
+ if (i < 8) {
773
+ init[i] = frac(prime ** (1 / 2));
774
+ }
775
+
776
+ key[i] = frac(prime ** (1 / 3));
777
+
778
+ i++;
779
+ }
780
+ }
781
+ }
782
+
783
+ /** @param {Uint8Array} bytes */
784
+ function reverse_endianness(bytes) {
785
+ for (let i = 0; i < bytes.length; i += 4) {
786
+ const a = bytes[i + 0];
787
+ const b = bytes[i + 1];
788
+ const c = bytes[i + 2];
789
+ const d = bytes[i + 3];
790
+
791
+ bytes[i + 0] = d;
792
+ bytes[i + 1] = c;
793
+ bytes[i + 2] = b;
794
+ bytes[i + 3] = a;
795
+ }
796
+ }
797
+
798
+ /** @param {string} str */
799
+ function encode$1(str) {
800
+ const encoded = encoder.encode(str);
801
+ const length = encoded.length * 8;
802
+
803
+ // result should be a multiple of 512 bits in length,
804
+ // with room for a 1 (after the data) and two 32-bit
805
+ // words containing the original input bit length
806
+ const size = 512 * Math.ceil((length + 65) / 512);
807
+ const bytes = new Uint8Array(size / 8);
808
+ bytes.set(encoded);
809
+
810
+ // append a 1
811
+ bytes[encoded.length] = 0b10000000;
812
+
813
+ reverse_endianness(bytes);
814
+
815
+ // add the input bit length
816
+ const words = new Uint32Array(bytes.buffer);
817
+ words[words.length - 2] = Math.floor(length / 0x100000000); // this will always be zero for us
818
+ words[words.length - 1] = length;
819
+
820
+ return words;
821
+ }
822
+
823
+ /*
824
+ Based on https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
825
+
826
+ MIT License
827
+ Copyright (c) 2020 Egor Nepomnyaschih
828
+ Permission is hereby granted, free of charge, to any person obtaining a copy
829
+ of this software and associated documentation files (the "Software"), to deal
830
+ in the Software without restriction, including without limitation the rights
831
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
832
+ copies of the Software, and to permit persons to whom the Software is
833
+ furnished to do so, subject to the following conditions:
834
+ The above copyright notice and this permission notice shall be included in all
835
+ copies or substantial portions of the Software.
836
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
837
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
838
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
839
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
840
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
841
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
842
+ SOFTWARE.
843
+ */
844
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
845
+
846
+ /** @param {Uint8Array} bytes */
847
+ function base64(bytes) {
848
+ const l = bytes.length;
849
+
850
+ let result = '';
851
+ let i;
852
+
853
+ for (i = 2; i < l; i += 3) {
854
+ result += chars[bytes[i - 2] >> 2];
855
+ result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
856
+ result += chars[((bytes[i - 1] & 0x0f) << 2) | (bytes[i] >> 6)];
857
+ result += chars[bytes[i] & 0x3f];
858
+ }
859
+
860
+ if (i === l + 1) {
861
+ // 1 octet yet to write
862
+ result += chars[bytes[i - 2] >> 2];
863
+ result += chars[(bytes[i - 2] & 0x03) << 4];
864
+ result += '==';
865
+ }
866
+
867
+ if (i === l) {
868
+ // 2 octets yet to write
869
+ result += chars[bytes[i - 2] >> 2];
870
+ result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
871
+ result += chars[(bytes[i - 1] & 0x0f) << 2];
872
+ result += '=';
873
+ }
874
+
875
+ return result;
876
+ }
877
+
878
+ /** @type {Promise<void>} */
879
+ let csp_ready;
880
+
881
+ const array = new Uint8Array(16);
882
+
883
+ function generate_nonce() {
884
+ crypto.getRandomValues(array);
885
+ return base64(array);
886
+ }
887
+
888
+ const quoted = new Set([
889
+ 'self',
890
+ 'unsafe-eval',
891
+ 'unsafe-hashes',
892
+ 'unsafe-inline',
893
+ 'none',
894
+ 'strict-dynamic',
895
+ 'report-sample'
896
+ ]);
897
+
898
+ const crypto_pattern = /^(nonce|sha\d\d\d)-/;
899
+
900
+ class Csp {
901
+ /** @type {boolean} */
902
+ #use_hashes;
903
+
904
+ /** @type {boolean} */
905
+ #dev;
906
+
907
+ /** @type {boolean} */
908
+ #script_needs_csp;
909
+
910
+ /** @type {boolean} */
911
+ #style_needs_csp;
912
+
913
+ /** @type {import('types').CspDirectives} */
914
+ #directives;
915
+
916
+ /** @type {import('types').Csp.Source[]} */
917
+ #script_src;
918
+
919
+ /** @type {import('types').Csp.Source[]} */
920
+ #style_src;
921
+
922
+ /**
923
+ * @param {{
924
+ * mode: string,
925
+ * directives: import('types').CspDirectives
926
+ * }} config
927
+ * @param {{
928
+ * dev: boolean;
929
+ * prerender: boolean;
930
+ * needs_nonce: boolean;
931
+ * }} opts
932
+ */
933
+ constructor({ mode, directives }, { dev, prerender, needs_nonce }) {
934
+ this.#use_hashes = mode === 'hash' || (mode === 'auto' && prerender);
935
+ this.#directives = dev ? { ...directives } : directives; // clone in dev so we can safely mutate
936
+ this.#dev = dev;
937
+
938
+ const d = this.#directives;
939
+
940
+ if (dev) {
941
+ // remove strict-dynamic in dev...
942
+ // TODO reinstate this if we can figure out how to make strict-dynamic work
943
+ // if (d['default-src']) {
944
+ // d['default-src'] = d['default-src'].filter((name) => name !== 'strict-dynamic');
945
+ // if (d['default-src'].length === 0) delete d['default-src'];
946
+ // }
947
+
948
+ // if (d['script-src']) {
949
+ // d['script-src'] = d['script-src'].filter((name) => name !== 'strict-dynamic');
950
+ // if (d['script-src'].length === 0) delete d['script-src'];
951
+ // }
952
+
953
+ const effective_style_src = d['style-src'] || d['default-src'];
954
+
955
+ // ...and add unsafe-inline so we can inject <style> elements
956
+ if (effective_style_src && !effective_style_src.includes('unsafe-inline')) {
957
+ d['style-src'] = [...effective_style_src, 'unsafe-inline'];
958
+ }
959
+ }
960
+
961
+ this.#script_src = [];
962
+ this.#style_src = [];
963
+
964
+ const effective_script_src = d['script-src'] || d['default-src'];
965
+ const effective_style_src = d['style-src'] || d['default-src'];
966
+
967
+ this.#script_needs_csp =
968
+ !!effective_script_src &&
969
+ effective_script_src.filter((value) => value !== 'unsafe-inline').length > 0;
970
+
971
+ this.#style_needs_csp =
972
+ !dev &&
973
+ !!effective_style_src &&
974
+ effective_style_src.filter((value) => value !== 'unsafe-inline').length > 0;
975
+
976
+ this.script_needs_nonce = this.#script_needs_csp && !this.#use_hashes;
977
+ this.style_needs_nonce = this.#style_needs_csp && !this.#use_hashes;
978
+
979
+ if (this.script_needs_nonce || this.style_needs_nonce || needs_nonce) {
980
+ this.nonce = generate_nonce();
981
+ }
982
+ }
983
+
984
+ /** @param {string} content */
985
+ add_script(content) {
986
+ if (this.#script_needs_csp) {
987
+ if (this.#use_hashes) {
988
+ this.#script_src.push(`sha256-${sha256(content)}`);
989
+ } else if (this.#script_src.length === 0) {
990
+ this.#script_src.push(`nonce-${this.nonce}`);
991
+ }
992
+ }
993
+ }
994
+
995
+ /** @param {string} content */
996
+ add_style(content) {
997
+ if (this.#style_needs_csp) {
998
+ if (this.#use_hashes) {
999
+ this.#style_src.push(`sha256-${sha256(content)}`);
1000
+ } else if (this.#style_src.length === 0) {
1001
+ this.#style_src.push(`nonce-${this.nonce}`);
1002
+ }
1003
+ }
1004
+ }
1005
+
1006
+ /** @param {boolean} [is_meta] */
1007
+ get_header(is_meta = false) {
1008
+ const header = [];
1009
+
1010
+ // due to browser inconsistencies, we can't append sources to default-src
1011
+ // (specifically, Firefox appears to not ignore nonce-{nonce} directives
1012
+ // on default-src), so we ensure that script-src and style-src exist
1013
+
1014
+ const directives = { ...this.#directives };
1015
+
1016
+ if (this.#style_src.length > 0) {
1017
+ directives['style-src'] = [
1018
+ ...(directives['style-src'] || directives['default-src'] || []),
1019
+ ...this.#style_src
1020
+ ];
1021
+ }
1022
+
1023
+ if (this.#script_src.length > 0) {
1024
+ directives['script-src'] = [
1025
+ ...(directives['script-src'] || directives['default-src'] || []),
1026
+ ...this.#script_src
1027
+ ];
1028
+ }
1029
+
1030
+ for (const key in directives) {
1031
+ if (is_meta && (key === 'frame-ancestors' || key === 'report-uri' || key === 'sandbox')) {
1032
+ // these values cannot be used with a <meta> tag
1033
+ // TODO warn?
1034
+ continue;
1035
+ }
1036
+
1037
+ // @ts-expect-error gimme a break typescript, `key` is obviously a member of directives
1038
+ const value = /** @type {string[] | true} */ (directives[key]);
1039
+
1040
+ if (!value) continue;
1041
+
1042
+ const directive = [key];
1043
+ if (Array.isArray(value)) {
1044
+ value.forEach((value) => {
1045
+ if (quoted.has(value) || crypto_pattern.test(value)) {
1046
+ directive.push(`'${value}'`);
1047
+ } else {
1048
+ directive.push(value);
1049
+ }
1050
+ });
1051
+ }
1052
+
1053
+ header.push(directive.join(' '));
1054
+ }
1055
+
1056
+ return header.join('; ');
1057
+ }
1058
+
1059
+ get_meta() {
1060
+ const content = escape_html_attr(this.get_header(true));
1061
+ return `<meta http-equiv="content-security-policy" content=${content}>`;
1062
+ }
1063
+ }
1064
+
1065
+ const absolute = /^([a-z]+:)?\/?\//;
1066
+ const scheme = /^[a-z]+:/;
1067
+
1068
+ /**
1069
+ * @param {string} base
1070
+ * @param {string} path
1071
+ */
1072
+ function resolve(base, path) {
1073
+ if (scheme.test(path)) return path;
1074
+
1075
+ const base_match = absolute.exec(base);
1076
+ const path_match = absolute.exec(path);
1077
+
1078
+ if (!base_match) {
1079
+ throw new Error(`bad base path: "${base}"`);
1080
+ }
1081
+
1082
+ const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
1083
+ const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
1084
+
1085
+ baseparts.pop();
1086
+
1087
+ for (let i = 0; i < pathparts.length; i += 1) {
1088
+ const part = pathparts[i];
1089
+ if (part === '.') continue;
1090
+ else if (part === '..') baseparts.pop();
1091
+ else baseparts.push(part);
1092
+ }
1093
+
1094
+ const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
1095
+
1096
+ return `${prefix}${baseparts.join('/')}`;
1097
+ }
1098
+
1099
+ /** @param {string} path */
1100
+ function is_root_relative(path) {
1101
+ return path[0] === '/' && path[1] !== '/';
1102
+ }
1103
+
1104
+ /**
1105
+ * @param {string} path
1106
+ * @param {import('types').TrailingSlash} trailing_slash
1107
+ */
1108
+ function normalize_path(path, trailing_slash) {
1109
+ if (path === '/' || trailing_slash === 'ignore') return path;
1110
+
1111
+ if (trailing_slash === 'never') {
1112
+ return path.endsWith('/') ? path.slice(0, -1) : path;
1113
+ } else if (trailing_slash === 'always' && !path.endsWith('/')) {
1114
+ return path + '/';
1115
+ }
1116
+
1117
+ return path;
1118
+ }
1119
+
1120
+ class LoadURL extends URL {
1121
+ /** @returns {string} */
1122
+ get hash() {
1123
+ throw new Error(
1124
+ 'url.hash is inaccessible from load. Consider accessing hash from the page store within the script tag of your component.'
1125
+ );
1126
+ }
1127
+ }
1128
+
1129
+ class PrerenderingURL extends URL {
1130
+ /** @returns {string} */
1131
+ get search() {
1132
+ throw new Error('Cannot access url.search on a page with prerendering enabled');
1133
+ }
1134
+
1135
+ /** @returns {URLSearchParams} */
1136
+ get searchParams() {
1137
+ throw new Error('Cannot access url.searchParams on a page with prerendering enabled');
1138
+ }
1139
+ }
1140
+
1141
+ // TODO rename this function/module
1142
+
1143
+ const updated = {
1144
+ ...readable(false),
1145
+ check: () => false
1146
+ };
1147
+
1148
+ /**
1149
+ * Creates the HTML response.
1150
+ * @param {{
1151
+ * branch: Array<import('./types').Loaded>;
1152
+ * options: import('types').SSROptions;
1153
+ * state: import('types').SSRState;
1154
+ * $session: any;
1155
+ * page_config: { hydrate: boolean, router: boolean };
1156
+ * status: number;
1157
+ * error: Error | null;
1158
+ * event: import('types').RequestEvent;
1159
+ * resolve_opts: import('types').RequiredResolveOptions;
1160
+ * stuff: Record<string, any>;
1161
+ * }} opts
1162
+ */
1163
+ async function render_response({
1164
+ branch,
1165
+ options,
1166
+ state,
1167
+ $session,
1168
+ page_config,
1169
+ status,
1170
+ error = null,
1171
+ event,
1172
+ resolve_opts,
1173
+ stuff
1174
+ }) {
1175
+ if (state.prerendering) {
1176
+ if (options.csp.mode === 'nonce') {
1177
+ throw new Error('Cannot use prerendering if config.kit.csp.mode === "nonce"');
1178
+ }
1179
+
1180
+ if (options.template_contains_nonce) {
1181
+ throw new Error('Cannot use prerendering if page template contains %sveltekit.nonce%');
1182
+ }
1183
+ }
1184
+
1185
+ const { entry } = options.manifest._;
1186
+
1187
+ const stylesheets = new Set(entry.stylesheets);
1188
+ const modulepreloads = new Set(entry.imports);
1189
+
1190
+ /** @type {Map<string, string>} */
1191
+ // TODO if we add a client entry point one day, we will need to include inline_styles with the entry, otherwise stylesheets will be linked even if they are below inlineStyleThreshold
1192
+ const inline_styles = new Map();
1193
+
1194
+ /** @type {Array<import('./types').Fetched>} */
1195
+ const serialized_data = [];
1196
+
1197
+ let shadow_props;
1198
+
1199
+ let rendered;
1200
+
1201
+ let is_private = false;
1202
+ /** @type {import('types').NormalizedLoadOutputCache | undefined} */
1203
+ let cache;
1204
+
1205
+ if (error) {
1206
+ error.stack = options.get_stack(error);
1207
+ }
1208
+
1209
+ if (resolve_opts.ssr) {
1210
+ for (const { node, props, loaded, fetched, uses_credentials } of branch) {
1211
+ if (node.imports) {
1212
+ node.imports.forEach((url) => modulepreloads.add(url));
1213
+ }
1214
+
1215
+ if (node.stylesheets) {
1216
+ node.stylesheets.forEach((url) => stylesheets.add(url));
1217
+ }
1218
+
1219
+ if (node.inline_styles) {
1220
+ Object.entries(await node.inline_styles()).forEach(([k, v]) => inline_styles.set(k, v));
1221
+ }
1222
+
1223
+ // TODO probably better if `fetched` wasn't populated unless `hydrate`
1224
+ if (fetched && page_config.hydrate) serialized_data.push(...fetched);
1225
+ if (props) shadow_props = props;
1226
+
1227
+ cache = loaded?.cache;
1228
+ is_private = cache?.private ?? uses_credentials;
1229
+ }
1230
+
1231
+ const session = writable($session);
1232
+
1233
+ /** @type {Record<string, any>} */
1234
+ const props = {
1235
+ stores: {
1236
+ page: writable(null),
1237
+ navigating: writable(null),
1238
+ /** @type {import('svelte/store').Writable<App.Session>} */
1239
+ session: {
1240
+ ...session,
1241
+ subscribe: (fn) => {
1242
+ is_private = cache?.private ?? true;
1243
+ return session.subscribe(fn);
1244
+ }
1245
+ },
1246
+ updated
1247
+ },
1248
+ /** @type {import('types').Page} */
1249
+ page: {
1250
+ error,
1251
+ params: event.params,
1252
+ routeId: event.routeId,
1253
+ status,
1254
+ stuff,
1255
+ url: state.prerendering ? new PrerenderingURL(event.url) : event.url
1256
+ },
1257
+ components: branch.map(({ node }) => node.module.default)
1258
+ };
1259
+
1260
+ // TODO remove this for 1.0
1261
+ /**
1262
+ * @param {string} property
1263
+ * @param {string} replacement
1264
+ */
1265
+ const print_error = (property, replacement) => {
1266
+ Object.defineProperty(props.page, property, {
1267
+ get: () => {
1268
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
1269
+ }
1270
+ });
1271
+ };
1272
+
1273
+ print_error('origin', 'origin');
1274
+ print_error('path', 'pathname');
1275
+ print_error('query', 'searchParams');
1276
+
1277
+ // props_n (instead of props[n]) makes it easy to avoid
1278
+ // unnecessary updates for layout components
1279
+ for (let i = 0; i < branch.length; i += 1) {
1280
+ props[`props_${i}`] = await branch[i].loaded.props;
1281
+ }
1282
+
1283
+ rendered = options.root.render(props);
1284
+ } else {
1285
+ rendered = { head: '', html: '', css: { code: '', map: null } };
1286
+ }
1287
+
1288
+ let { head, html: body } = rendered;
1289
+
1290
+ await csp_ready;
1291
+ const csp = new Csp(options.csp, {
1292
+ dev: options.dev,
1293
+ prerender: !!state.prerendering,
1294
+ needs_nonce: options.template_contains_nonce
1295
+ });
1296
+
1297
+ const target = hash(body);
1298
+
1299
+ // prettier-ignore
1300
+ const init_app = `
1301
+ import { start } from ${s(options.prefix + entry.file)};
1302
+ start({
1303
+ target: document.querySelector('[data-sveltekit-hydrate="${target}"]').parentNode,
1304
+ paths: ${s(options.paths)},
1305
+ session: ${try_serialize($session, (error) => {
1306
+ throw new Error(`Failed to serialize session data: ${error.message}`);
1307
+ })},
1308
+ route: ${!!page_config.router},
1309
+ spa: ${!resolve_opts.ssr},
1310
+ trailing_slash: ${s(options.trailing_slash)},
1311
+ hydrate: ${resolve_opts.ssr && page_config.hydrate ? `{
1312
+ status: ${status},
1313
+ error: ${serialize_error(error)},
1314
+ nodes: [${branch.map(({ node }) => node.index).join(', ')}],
1315
+ params: ${devalue(event.params)},
1316
+ routeId: ${s(event.routeId)}
1317
+ }` : 'null'}
1318
+ });
1319
+ `;
1320
+
1321
+ const init_service_worker = `
1322
+ if ('serviceWorker' in navigator) {
1323
+ addEventListener('load', () => {
1324
+ navigator.serviceWorker.register('${options.service_worker}');
1325
+ });
1326
+ }
1327
+ `;
1328
+
1329
+ if (inline_styles.size > 0) {
1330
+ const content = Array.from(inline_styles.values()).join('\n');
1331
+
1332
+ const attributes = [];
1333
+ if (options.dev) attributes.push(' data-sveltekit');
1334
+ if (csp.style_needs_nonce) attributes.push(` nonce="${csp.nonce}"`);
1335
+
1336
+ csp.add_style(content);
1337
+
1338
+ head += `\n\t<style${attributes.join('')}>${content}</style>`;
1339
+ }
1340
+
1341
+ // prettier-ignore
1342
+ head += Array.from(stylesheets)
1343
+ .map((dep) => {
1344
+ const attributes = [
1345
+ 'rel="stylesheet"',
1346
+ `href="${options.prefix + dep}"`
1347
+ ];
1348
+
1349
+ if (csp.style_needs_nonce) {
1350
+ attributes.push(`nonce="${csp.nonce}"`);
1351
+ }
1352
+
1353
+ if (inline_styles.has(dep)) {
1354
+ // don't load stylesheets that are already inlined
1355
+ // include them in disabled state so that Vite can detect them and doesn't try to add them
1356
+ attributes.push('disabled', 'media="(max-width: 0)"');
1357
+ }
1358
+
1359
+ return `\n\t<link ${attributes.join(' ')}>`;
1360
+ })
1361
+ .join('');
1362
+
1363
+ if (page_config.router || page_config.hydrate) {
1364
+ head += Array.from(modulepreloads)
1365
+ .map((dep) => `\n\t<link rel="modulepreload" href="${options.prefix + dep}">`)
1366
+ .join('');
1367
+
1368
+ const attributes = ['type="module"', `data-sveltekit-hydrate="${target}"`];
1369
+
1370
+ csp.add_script(init_app);
1371
+
1372
+ if (csp.script_needs_nonce) {
1373
+ attributes.push(`nonce="${csp.nonce}"`);
1374
+ }
1375
+
1376
+ body += `\n\t\t<script ${attributes.join(' ')}>${init_app}</script>`;
1377
+
1378
+ body += serialized_data
1379
+ .map(({ url, body, response }) =>
1380
+ render_json_payload_script(
1381
+ { type: 'data', url, body: typeof body === 'string' ? hash(body) : undefined },
1382
+ response
1383
+ )
1384
+ )
1385
+ .join('\n\t');
1386
+
1387
+ if (shadow_props) {
1388
+ body += render_json_payload_script({ type: 'props' }, shadow_props);
1389
+ }
1390
+ }
1391
+
1392
+ if (options.service_worker) {
1393
+ // always include service worker unless it's turned off explicitly
1394
+ csp.add_script(init_service_worker);
1395
+
1396
+ head += `
1397
+ <script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ''}>${init_service_worker}</script>`;
1398
+ }
1399
+
1400
+ if (state.prerendering) {
1401
+ const http_equiv = [];
1402
+
1403
+ const csp_headers = csp.get_meta();
1404
+ if (csp_headers) {
1405
+ http_equiv.push(csp_headers);
1406
+ }
1407
+
1408
+ if (cache) {
1409
+ http_equiv.push(`<meta http-equiv="cache-control" content="max-age=${cache.maxage}">`);
1410
+ }
1411
+
1412
+ if (http_equiv.length > 0) {
1413
+ head = http_equiv.join('\n') + head;
1414
+ }
1415
+ }
1416
+
1417
+ const segments = event.url.pathname.slice(options.paths.base.length).split('/').slice(2);
1418
+ const assets =
1419
+ options.paths.assets || (segments.length > 0 ? segments.map(() => '..').join('/') : '.');
1420
+
1421
+ const html = await resolve_opts.transformPage({
1422
+ html: options.template({ head, body, assets, nonce: /** @type {string} */ (csp.nonce) })
1423
+ });
1424
+
1425
+ const headers = new Headers({
1426
+ 'content-type': 'text/html',
1427
+ etag: `"${hash(html)}"`
1428
+ });
1429
+
1430
+ if (cache) {
1431
+ headers.set('cache-control', `${is_private ? 'private' : 'public'}, max-age=${cache.maxage}`);
1432
+ }
1433
+
1434
+ if (!options.floc) {
1435
+ headers.set('permissions-policy', 'interest-cohort=()');
1436
+ }
1437
+
1438
+ if (!state.prerendering) {
1439
+ const csp_header = csp.get_header();
1440
+ if (csp_header) {
1441
+ headers.set('content-security-policy', csp_header);
1442
+ }
1443
+ }
1444
+
1445
+ return new Response(html, {
1446
+ status,
1447
+ headers
1448
+ });
1449
+ }
1450
+
1451
+ /**
1452
+ * @param {any} data
1453
+ * @param {(error: Error) => void} [fail]
1454
+ */
1455
+ function try_serialize(data, fail) {
1456
+ try {
1457
+ return devalue(data);
1458
+ } catch (err) {
1459
+ if (fail) fail(coalesce_to_error(err));
1460
+ return null;
1461
+ }
1462
+ }
1463
+
1464
+ // Ensure we return something truthy so the client will not re-render the page over the error
1465
+
1466
+ /** @param {(Error & {frame?: string} & {loc?: object}) | undefined | null} error */
1467
+ function serialize_error(error) {
1468
+ if (!error) return null;
1469
+ let serialized = try_serialize(error);
1470
+ if (!serialized) {
1471
+ const { name, message, stack } = error;
1472
+ serialized = try_serialize({ ...error, name, message, stack });
1473
+ }
1474
+ if (!serialized) {
1475
+ serialized = '{}';
1476
+ }
1477
+ return serialized;
1478
+ }
1479
+
1480
+ /*!
1481
+ * cookie
1482
+ * Copyright(c) 2012-2014 Roman Shtylman
1483
+ * Copyright(c) 2015 Douglas Christopher Wilson
1484
+ * MIT Licensed
1485
+ */
1486
+
1487
+ /**
1488
+ * Module exports.
1489
+ * @public
1490
+ */
1491
+
1492
+ var parse_1 = parse$1;
1493
+ var serialize_1 = serialize;
1494
+
1495
+ /**
1496
+ * Module variables.
1497
+ * @private
1498
+ */
1499
+
1500
+ var __toString = Object.prototype.toString;
1501
+
1502
+ /**
1503
+ * RegExp to match field-content in RFC 7230 sec 3.2
1504
+ *
1505
+ * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
1506
+ * field-vchar = VCHAR / obs-text
1507
+ * obs-text = %x80-FF
1508
+ */
1509
+
1510
+ var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
1511
+
1512
+ /**
1513
+ * Parse a cookie header.
1514
+ *
1515
+ * Parse the given cookie header string into an object
1516
+ * The object has the various cookies as keys(names) => values
1517
+ *
1518
+ * @param {string} str
1519
+ * @param {object} [options]
1520
+ * @return {object}
1521
+ * @public
1522
+ */
1523
+
1524
+ function parse$1(str, options) {
1525
+ if (typeof str !== 'string') {
1526
+ throw new TypeError('argument str must be a string');
1527
+ }
1528
+
1529
+ var obj = {};
1530
+ var opt = options || {};
1531
+ var dec = opt.decode || decode;
1532
+
1533
+ var index = 0;
1534
+ while (index < str.length) {
1535
+ var eqIdx = str.indexOf('=', index);
1536
+
1537
+ // no more cookie pairs
1538
+ if (eqIdx === -1) {
1539
+ break
1540
+ }
1541
+
1542
+ var endIdx = str.indexOf(';', index);
1543
+
1544
+ if (endIdx === -1) {
1545
+ endIdx = str.length;
1546
+ } else if (endIdx < eqIdx) {
1547
+ // backtrack on prior semicolon
1548
+ index = str.lastIndexOf(';', eqIdx - 1) + 1;
1549
+ continue
1550
+ }
1551
+
1552
+ var key = str.slice(index, eqIdx).trim();
1553
+
1554
+ // only assign once
1555
+ if (undefined === obj[key]) {
1556
+ var val = str.slice(eqIdx + 1, endIdx).trim();
1557
+
1558
+ // quoted values
1559
+ if (val.charCodeAt(0) === 0x22) {
1560
+ val = val.slice(1, -1);
1561
+ }
1562
+
1563
+ obj[key] = tryDecode(val, dec);
1564
+ }
1565
+
1566
+ index = endIdx + 1;
1567
+ }
1568
+
1569
+ return obj;
1570
+ }
1571
+
1572
+ /**
1573
+ * Serialize data into a cookie header.
1574
+ *
1575
+ * Serialize the a name value pair into a cookie string suitable for
1576
+ * http headers. An optional options object specified cookie parameters.
1577
+ *
1578
+ * serialize('foo', 'bar', { httpOnly: true })
1579
+ * => "foo=bar; httpOnly"
1580
+ *
1581
+ * @param {string} name
1582
+ * @param {string} val
1583
+ * @param {object} [options]
1584
+ * @return {string}
1585
+ * @public
1586
+ */
1587
+
1588
+ function serialize(name, val, options) {
1589
+ var opt = options || {};
1590
+ var enc = opt.encode || encode;
1591
+
1592
+ if (typeof enc !== 'function') {
1593
+ throw new TypeError('option encode is invalid');
1594
+ }
1595
+
1596
+ if (!fieldContentRegExp.test(name)) {
1597
+ throw new TypeError('argument name is invalid');
1598
+ }
1599
+
1600
+ var value = enc(val);
1601
+
1602
+ if (value && !fieldContentRegExp.test(value)) {
1603
+ throw new TypeError('argument val is invalid');
1604
+ }
1605
+
1606
+ var str = name + '=' + value;
1607
+
1608
+ if (null != opt.maxAge) {
1609
+ var maxAge = opt.maxAge - 0;
1610
+
1611
+ if (isNaN(maxAge) || !isFinite(maxAge)) {
1612
+ throw new TypeError('option maxAge is invalid')
1613
+ }
1614
+
1615
+ str += '; Max-Age=' + Math.floor(maxAge);
1616
+ }
1617
+
1618
+ if (opt.domain) {
1619
+ if (!fieldContentRegExp.test(opt.domain)) {
1620
+ throw new TypeError('option domain is invalid');
1621
+ }
1622
+
1623
+ str += '; Domain=' + opt.domain;
1624
+ }
1625
+
1626
+ if (opt.path) {
1627
+ if (!fieldContentRegExp.test(opt.path)) {
1628
+ throw new TypeError('option path is invalid');
1629
+ }
1630
+
1631
+ str += '; Path=' + opt.path;
1632
+ }
1633
+
1634
+ if (opt.expires) {
1635
+ var expires = opt.expires;
1636
+
1637
+ if (!isDate(expires) || isNaN(expires.valueOf())) {
1638
+ throw new TypeError('option expires is invalid');
1639
+ }
1640
+
1641
+ str += '; Expires=' + expires.toUTCString();
1642
+ }
1643
+
1644
+ if (opt.httpOnly) {
1645
+ str += '; HttpOnly';
1646
+ }
1647
+
1648
+ if (opt.secure) {
1649
+ str += '; Secure';
1650
+ }
1651
+
1652
+ if (opt.priority) {
1653
+ var priority = typeof opt.priority === 'string'
1654
+ ? opt.priority.toLowerCase()
1655
+ : opt.priority;
1656
+
1657
+ switch (priority) {
1658
+ case 'low':
1659
+ str += '; Priority=Low';
1660
+ break
1661
+ case 'medium':
1662
+ str += '; Priority=Medium';
1663
+ break
1664
+ case 'high':
1665
+ str += '; Priority=High';
1666
+ break
1667
+ default:
1668
+ throw new TypeError('option priority is invalid')
1669
+ }
1670
+ }
1671
+
1672
+ if (opt.sameSite) {
1673
+ var sameSite = typeof opt.sameSite === 'string'
1674
+ ? opt.sameSite.toLowerCase() : opt.sameSite;
1675
+
1676
+ switch (sameSite) {
1677
+ case true:
1678
+ str += '; SameSite=Strict';
1679
+ break;
1680
+ case 'lax':
1681
+ str += '; SameSite=Lax';
1682
+ break;
1683
+ case 'strict':
1684
+ str += '; SameSite=Strict';
1685
+ break;
1686
+ case 'none':
1687
+ str += '; SameSite=None';
1688
+ break;
1689
+ default:
1690
+ throw new TypeError('option sameSite is invalid');
1691
+ }
1692
+ }
1693
+
1694
+ return str;
1695
+ }
1696
+
1697
+ /**
1698
+ * URL-decode string value. Optimized to skip native call when no %.
1699
+ *
1700
+ * @param {string} str
1701
+ * @returns {string}
1702
+ */
1703
+
1704
+ function decode (str) {
1705
+ return str.indexOf('%') !== -1
1706
+ ? decodeURIComponent(str)
1707
+ : str
1708
+ }
1709
+
1710
+ /**
1711
+ * URL-encode value.
1712
+ *
1713
+ * @param {string} str
1714
+ * @returns {string}
1715
+ */
1716
+
1717
+ function encode (val) {
1718
+ return encodeURIComponent(val)
1719
+ }
1720
+
1721
+ /**
1722
+ * Determine if value is a Date.
1723
+ *
1724
+ * @param {*} val
1725
+ * @private
1726
+ */
1727
+
1728
+ function isDate (val) {
1729
+ return __toString.call(val) === '[object Date]' ||
1730
+ val instanceof Date
1731
+ }
1732
+
1733
+ /**
1734
+ * Try decoding a string using a decoding function.
1735
+ *
1736
+ * @param {string} str
1737
+ * @param {function} decode
1738
+ * @private
1739
+ */
1740
+
1741
+ function tryDecode(str, decode) {
1742
+ try {
1743
+ return decode(str);
1744
+ } catch (e) {
1745
+ return str;
1746
+ }
1747
+ }
1748
+
1749
+ var setCookie = {exports: {}};
1750
+
1751
+ var defaultParseOptions = {
1752
+ decodeValues: true,
1753
+ map: false,
1754
+ silent: false,
1755
+ };
1756
+
1757
+ function isNonEmptyString(str) {
1758
+ return typeof str === "string" && !!str.trim();
1759
+ }
1760
+
1761
+ function parseString(setCookieValue, options) {
1762
+ var parts = setCookieValue.split(";").filter(isNonEmptyString);
1763
+ var nameValue = parts.shift().split("=");
1764
+ var name = nameValue.shift();
1765
+ var value = nameValue.join("="); // everything after the first =, joined by a "=" if there was more than one part
1766
+
1767
+ options = options
1768
+ ? Object.assign({}, defaultParseOptions, options)
1769
+ : defaultParseOptions;
1770
+
1771
+ try {
1772
+ value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value
1773
+ } catch (e) {
1774
+ console.error(
1775
+ "set-cookie-parser encountered an error while decoding a cookie with value '" +
1776
+ value +
1777
+ "'. Set options.decodeValues to false to disable this feature.",
1778
+ e
1779
+ );
1780
+ }
1781
+
1782
+ var cookie = {
1783
+ name: name, // grab everything before the first =
1784
+ value: value,
1785
+ };
1786
+
1787
+ parts.forEach(function (part) {
1788
+ var sides = part.split("=");
1789
+ var key = sides.shift().trimLeft().toLowerCase();
1790
+ var value = sides.join("=");
1791
+ if (key === "expires") {
1792
+ cookie.expires = new Date(value);
1793
+ } else if (key === "max-age") {
1794
+ cookie.maxAge = parseInt(value, 10);
1795
+ } else if (key === "secure") {
1796
+ cookie.secure = true;
1797
+ } else if (key === "httponly") {
1798
+ cookie.httpOnly = true;
1799
+ } else if (key === "samesite") {
1800
+ cookie.sameSite = value;
1801
+ } else {
1802
+ cookie[key] = value;
1803
+ }
1804
+ });
1805
+
1806
+ return cookie;
1807
+ }
1808
+
1809
+ function parse(input, options) {
1810
+ options = options
1811
+ ? Object.assign({}, defaultParseOptions, options)
1812
+ : defaultParseOptions;
1813
+
1814
+ if (!input) {
1815
+ if (!options.map) {
1816
+ return [];
1817
+ } else {
1818
+ return {};
1819
+ }
1820
+ }
1821
+
1822
+ if (input.headers && input.headers["set-cookie"]) {
1823
+ // fast-path for node.js (which automatically normalizes header names to lower-case
1824
+ input = input.headers["set-cookie"];
1825
+ } else if (input.headers) {
1826
+ // slow-path for other environments - see #25
1827
+ var sch =
1828
+ input.headers[
1829
+ Object.keys(input.headers).find(function (key) {
1830
+ return key.toLowerCase() === "set-cookie";
1831
+ })
1832
+ ];
1833
+ // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36
1834
+ if (!sch && input.headers.cookie && !options.silent) {
1835
+ console.warn(
1836
+ "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
1837
+ );
1838
+ }
1839
+ input = sch;
1840
+ }
1841
+ if (!Array.isArray(input)) {
1842
+ input = [input];
1843
+ }
1844
+
1845
+ options = options
1846
+ ? Object.assign({}, defaultParseOptions, options)
1847
+ : defaultParseOptions;
1848
+
1849
+ if (!options.map) {
1850
+ return input.filter(isNonEmptyString).map(function (str) {
1851
+ return parseString(str, options);
1852
+ });
1853
+ } else {
1854
+ var cookies = {};
1855
+ return input.filter(isNonEmptyString).reduce(function (cookies, str) {
1856
+ var cookie = parseString(str, options);
1857
+ cookies[cookie.name] = cookie;
1858
+ return cookies;
1859
+ }, cookies);
1860
+ }
1861
+ }
1862
+
1863
+ /*
1864
+ Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
1865
+ that are within a single set-cookie field-value, such as in the Expires portion.
1866
+
1867
+ This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
1868
+ Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
1869
+ React Native's fetch does this for *every* header, including set-cookie.
1870
+
1871
+ Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
1872
+ Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
1873
+ */
1874
+ function splitCookiesString(cookiesString) {
1875
+ if (Array.isArray(cookiesString)) {
1876
+ return cookiesString;
1877
+ }
1878
+ if (typeof cookiesString !== "string") {
1879
+ return [];
1880
+ }
1881
+
1882
+ var cookiesStrings = [];
1883
+ var pos = 0;
1884
+ var start;
1885
+ var ch;
1886
+ var lastComma;
1887
+ var nextStart;
1888
+ var cookiesSeparatorFound;
1889
+
1890
+ function skipWhitespace() {
1891
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
1892
+ pos += 1;
1893
+ }
1894
+ return pos < cookiesString.length;
1895
+ }
1896
+
1897
+ function notSpecialChar() {
1898
+ ch = cookiesString.charAt(pos);
1899
+
1900
+ return ch !== "=" && ch !== ";" && ch !== ",";
1901
+ }
1902
+
1903
+ while (pos < cookiesString.length) {
1904
+ start = pos;
1905
+ cookiesSeparatorFound = false;
1906
+
1907
+ while (skipWhitespace()) {
1908
+ ch = cookiesString.charAt(pos);
1909
+ if (ch === ",") {
1910
+ // ',' is a cookie separator if we have later first '=', not ';' or ','
1911
+ lastComma = pos;
1912
+ pos += 1;
1913
+
1914
+ skipWhitespace();
1915
+ nextStart = pos;
1916
+
1917
+ while (pos < cookiesString.length && notSpecialChar()) {
1918
+ pos += 1;
1919
+ }
1920
+
1921
+ // currently special character
1922
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
1923
+ // we found cookies separator
1924
+ cookiesSeparatorFound = true;
1925
+ // pos is inside the next cookie, so back up and return it.
1926
+ pos = nextStart;
1927
+ cookiesStrings.push(cookiesString.substring(start, lastComma));
1928
+ start = pos;
1929
+ } else {
1930
+ // in param ',' or param separator ';',
1931
+ // we continue from that comma
1932
+ pos = lastComma + 1;
1933
+ }
1934
+ } else {
1935
+ pos += 1;
1936
+ }
1937
+ }
1938
+
1939
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) {
1940
+ cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
1941
+ }
1942
+ }
1943
+
1944
+ return cookiesStrings;
1945
+ }
1946
+
1947
+ setCookie.exports = parse;
1948
+ setCookie.exports.parse = parse;
1949
+ var parseString_1 = setCookie.exports.parseString = parseString;
1950
+ var splitCookiesString_1 = setCookie.exports.splitCookiesString = splitCookiesString;
1951
+
1952
+ /**
1953
+ * @param {import('types').LoadOutput} loaded
1954
+ * @returns {import('types').NormalizedLoadOutput}
1955
+ */
1956
+ function normalize(loaded) {
1957
+ // TODO remove for 1.0
1958
+ // @ts-expect-error
1959
+ if (loaded.fallthrough) {
1960
+ throw new Error(
1961
+ 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
1962
+ );
1963
+ }
1964
+
1965
+ // TODO remove for 1.0
1966
+ if ('maxage' in loaded) {
1967
+ throw new Error('maxage should be replaced with cache: { maxage }');
1968
+ }
1969
+
1970
+ const has_error_status =
1971
+ loaded.status && loaded.status >= 400 && loaded.status <= 599 && !loaded.redirect;
1972
+ if (loaded.error || has_error_status) {
1973
+ const status = loaded.status;
1974
+
1975
+ if (!loaded.error && has_error_status) {
1976
+ return { status: status || 500, error: new Error() };
1977
+ }
1978
+
1979
+ const error = typeof loaded.error === 'string' ? new Error(loaded.error) : loaded.error;
1980
+
1981
+ if (!(error instanceof Error)) {
1982
+ return {
1983
+ status: 500,
1984
+ error: new Error(
1985
+ `"error" property returned from load() must be a string or instance of Error, received type "${typeof error}"`
1986
+ )
1987
+ };
1988
+ }
1989
+
1990
+ if (!status || status < 400 || status > 599) {
1991
+ console.warn('"error" returned from load() without a valid status code — defaulting to 500');
1992
+ return { status: 500, error };
1993
+ }
1994
+
1995
+ return { status, error };
1996
+ }
1997
+
1998
+ if (loaded.redirect) {
1999
+ if (!loaded.status || Math.floor(loaded.status / 100) !== 3) {
2000
+ throw new Error(
2001
+ '"redirect" property returned from load() must be accompanied by a 3xx status code'
2002
+ );
2003
+ }
2004
+
2005
+ if (typeof loaded.redirect !== 'string') {
2006
+ throw new Error('"redirect" property returned from load() must be a string');
2007
+ }
2008
+ }
2009
+
2010
+ if (loaded.dependencies) {
2011
+ if (
2012
+ !Array.isArray(loaded.dependencies) ||
2013
+ loaded.dependencies.some((dep) => typeof dep !== 'string')
2014
+ ) {
2015
+ throw new Error('"dependencies" property returned from load() must be of type string[]');
2016
+ }
2017
+ }
2018
+
2019
+ // TODO remove before 1.0
2020
+ if (/** @type {any} */ (loaded).context) {
2021
+ throw new Error(
2022
+ 'You are returning "context" from a load function. ' +
2023
+ '"context" was renamed to "stuff", please adjust your code accordingly.'
2024
+ );
2025
+ }
2026
+
2027
+ return /** @type {import('types').NormalizedLoadOutput} */ (loaded);
2028
+ }
2029
+
2030
+ /**
2031
+ * @param {string} hostname
2032
+ * @param {string} [constraint]
2033
+ */
2034
+ function domain_matches(hostname, constraint) {
2035
+ if (!constraint) return true;
2036
+
2037
+ const normalized = constraint[0] === '.' ? constraint.slice(1) : constraint;
2038
+
2039
+ if (hostname === normalized) return true;
2040
+ return hostname.endsWith('.' + normalized);
2041
+ }
2042
+
2043
+ /**
2044
+ * @param {string} path
2045
+ * @param {string} [constraint]
2046
+ */
2047
+ function path_matches(path, constraint) {
2048
+ if (!constraint) return true;
2049
+
2050
+ const normalized = constraint.endsWith('/') ? constraint.slice(0, -1) : constraint;
2051
+
2052
+ if (path === normalized) return true;
2053
+ return path.startsWith(normalized + '/');
2054
+ }
2055
+
2056
+ /**
2057
+ * Calls the user's `load` function.
2058
+ * @param {{
2059
+ * event: import('types').RequestEvent;
2060
+ * options: import('types').SSROptions;
2061
+ * state: import('types').SSRState;
2062
+ * route: import('types').SSRPage | null;
2063
+ * node: import('types').SSRNode;
2064
+ * $session: any;
2065
+ * stuff: Record<string, any>;
2066
+ * is_error: boolean;
2067
+ * is_leaf: boolean;
2068
+ * status?: number;
2069
+ * error?: Error;
2070
+ * }} opts
2071
+ * @returns {Promise<import('./types').Loaded>}
2072
+ */
2073
+ async function load_node({
2074
+ event,
2075
+ options,
2076
+ state,
2077
+ route,
2078
+ node,
2079
+ $session,
2080
+ stuff,
2081
+ is_error,
2082
+ is_leaf,
2083
+ status,
2084
+ error
2085
+ }) {
2086
+ const { module } = node;
2087
+
2088
+ let uses_credentials = false;
2089
+
2090
+ /** @type {Array<import('./types').Fetched>} */
2091
+ const fetched = [];
2092
+
2093
+ const cookies = parse_1(event.request.headers.get('cookie') || '');
2094
+
2095
+ /** @type {import('set-cookie-parser').Cookie[]} */
2096
+ const new_cookies = [];
2097
+
2098
+ /** @type {import('types').LoadOutput} */
2099
+ let loaded;
2100
+
2101
+ const should_prerender = node.module.prerender ?? options.prerender.default;
2102
+
2103
+ /** @type {import('types').ShadowData} */
2104
+ const shadow = is_leaf
2105
+ ? await load_shadow_data(
2106
+ /** @type {import('types').SSRPage} */ (route),
2107
+ event,
2108
+ options,
2109
+ should_prerender
2110
+ )
2111
+ : {};
2112
+
2113
+ if (shadow.cookies) {
2114
+ shadow.cookies.forEach((header) => {
2115
+ new_cookies.push(parseString_1(header));
2116
+ });
2117
+ }
2118
+
2119
+ if (shadow.error) {
2120
+ loaded = {
2121
+ status: shadow.status,
2122
+ error: shadow.error
2123
+ };
2124
+ } else if (shadow.redirect) {
2125
+ loaded = {
2126
+ status: shadow.status,
2127
+ redirect: shadow.redirect
2128
+ };
2129
+ } else if (module.load) {
2130
+ /** @type {import('types').LoadEvent} */
2131
+ const load_input = {
2132
+ url: state.prerendering ? new PrerenderingURL(event.url) : new LoadURL(event.url),
2133
+ params: event.params,
2134
+ props: shadow.body || {},
2135
+ routeId: event.routeId,
2136
+ get session() {
2137
+ if (node.module.prerender ?? options.prerender.default) {
2138
+ throw Error(
2139
+ 'Attempted to access session from a prerendered page. Session would never be populated.'
2140
+ );
2141
+ }
2142
+ uses_credentials = true;
2143
+ return $session;
2144
+ },
2145
+ /**
2146
+ * @param {RequestInfo} resource
2147
+ * @param {RequestInit} opts
2148
+ */
2149
+ fetch: async (resource, opts = {}) => {
2150
+ /** @type {string} */
2151
+ let requested;
2152
+
2153
+ if (typeof resource === 'string') {
2154
+ requested = resource;
2155
+ } else {
2156
+ requested = resource.url;
2157
+
2158
+ opts = {
2159
+ method: resource.method,
2160
+ headers: resource.headers,
2161
+ body: resource.body,
2162
+ mode: resource.mode,
2163
+ credentials: resource.credentials,
2164
+ cache: resource.cache,
2165
+ redirect: resource.redirect,
2166
+ referrer: resource.referrer,
2167
+ integrity: resource.integrity,
2168
+ ...opts
2169
+ };
2170
+ }
2171
+
2172
+ opts.headers = new Headers(opts.headers);
2173
+
2174
+ // merge headers from request
2175
+ for (const [key, value] of event.request.headers) {
2176
+ if (
2177
+ key !== 'authorization' &&
2178
+ key !== 'cookie' &&
2179
+ key !== 'host' &&
2180
+ key !== 'if-none-match' &&
2181
+ !opts.headers.has(key)
2182
+ ) {
2183
+ opts.headers.set(key, value);
2184
+ }
2185
+ }
2186
+
2187
+ const resolved = resolve(event.url.pathname, requested.split('?')[0]);
2188
+
2189
+ /** @type {Response} */
2190
+ let response;
2191
+
2192
+ /** @type {import('types').PrerenderDependency} */
2193
+ let dependency;
2194
+
2195
+ // handle fetch requests for static assets. e.g. prebaked data, etc.
2196
+ // we need to support everything the browser's fetch supports
2197
+ const prefix = options.paths.assets || options.paths.base;
2198
+ const filename = decodeURIComponent(
2199
+ resolved.startsWith(prefix) ? resolved.slice(prefix.length) : resolved
2200
+ ).slice(1);
2201
+ const filename_html = `${filename}/index.html`; // path may also match path/index.html
2202
+
2203
+ const is_asset = options.manifest.assets.has(filename);
2204
+ const is_asset_html = options.manifest.assets.has(filename_html);
2205
+
2206
+ if (is_asset || is_asset_html) {
2207
+ const file = is_asset ? filename : filename_html;
2208
+
2209
+ if (options.read) {
2210
+ const type = is_asset
2211
+ ? options.manifest.mimeTypes[filename.slice(filename.lastIndexOf('.'))]
2212
+ : 'text/html';
2213
+
2214
+ response = new Response(options.read(file), {
2215
+ headers: type ? { 'content-type': type } : {}
2216
+ });
2217
+ } else {
2218
+ response = await fetch(
2219
+ `${event.url.origin}/${file}`,
2220
+ /** @type {RequestInit} */ (opts)
2221
+ );
2222
+ }
2223
+ } else if (is_root_relative(resolved)) {
2224
+ if (opts.credentials !== 'omit') {
2225
+ uses_credentials = true;
2226
+
2227
+ const authorization = event.request.headers.get('authorization');
2228
+
2229
+ // combine cookies from the initiating request with any that were
2230
+ // added via set-cookie
2231
+ const combined_cookies = { ...cookies };
2232
+
2233
+ for (const cookie of new_cookies) {
2234
+ if (!domain_matches(event.url.hostname, cookie.domain)) continue;
2235
+ if (!path_matches(resolved, cookie.path)) continue;
2236
+
2237
+ combined_cookies[cookie.name] = cookie.value;
2238
+ }
2239
+
2240
+ const cookie = Object.entries(combined_cookies)
2241
+ .map(([name, value]) => `${name}=${value}`)
2242
+ .join('; ');
2243
+
2244
+ if (cookie) {
2245
+ opts.headers.set('cookie', cookie);
2246
+ }
2247
+
2248
+ if (authorization && !opts.headers.has('authorization')) {
2249
+ opts.headers.set('authorization', authorization);
2250
+ }
2251
+ }
2252
+
2253
+ if (opts.body && typeof opts.body !== 'string') {
2254
+ // per https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, this can be a
2255
+ // Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object.
2256
+ // non-string bodies are irksome to deal with, but luckily aren't particularly useful
2257
+ // in this context anyway, so we take the easy route and ban them
2258
+ throw new Error('Request body must be a string');
2259
+ }
2260
+
2261
+ response = await respond(
2262
+ new Request(new URL(requested, event.url).href, { ...opts }),
2263
+ options,
2264
+ {
2265
+ ...state,
2266
+ initiator: route
2267
+ }
2268
+ );
2269
+
2270
+ if (state.prerendering) {
2271
+ dependency = { response, body: null };
2272
+ state.prerendering.dependencies.set(resolved, dependency);
2273
+ }
2274
+ } else {
2275
+ // external
2276
+ if (resolved.startsWith('//')) {
2277
+ requested = event.url.protocol + requested;
2278
+ }
2279
+
2280
+ // external fetch
2281
+ // allow cookie passthrough for "same-origin"
2282
+ // if SvelteKit is serving my.domain.com:
2283
+ // - domain.com WILL NOT receive cookies
2284
+ // - my.domain.com WILL receive cookies
2285
+ // - api.domain.dom WILL NOT receive cookies
2286
+ // - sub.my.domain.com WILL receive cookies
2287
+ // ports do not affect the resolution
2288
+ // leading dot prevents mydomain.com matching domain.com
2289
+ if (
2290
+ `.${new URL(requested).hostname}`.endsWith(`.${event.url.hostname}`) &&
2291
+ opts.credentials !== 'omit'
2292
+ ) {
2293
+ uses_credentials = true;
2294
+
2295
+ const cookie = event.request.headers.get('cookie');
2296
+ if (cookie) opts.headers.set('cookie', cookie);
2297
+ }
2298
+
2299
+ // we need to delete the connection header, as explained here:
2300
+ // https://github.com/nodejs/undici/issues/1470#issuecomment-1140798467
2301
+ // TODO this may be a case for being selective about which headers we let through
2302
+ opts.headers.delete('connection');
2303
+
2304
+ const external_request = new Request(requested, /** @type {RequestInit} */ (opts));
2305
+ response = await options.hooks.externalFetch.call(null, external_request);
2306
+ }
2307
+
2308
+ const set_cookie = response.headers.get('set-cookie');
2309
+ if (set_cookie) {
2310
+ new_cookies.push(
2311
+ ...splitCookiesString_1(set_cookie)
2312
+ .map((str) => parseString_1(str))
2313
+ );
2314
+ }
2315
+
2316
+ const proxy = new Proxy(response, {
2317
+ get(response, key, _receiver) {
2318
+ async function text() {
2319
+ const body = await response.text();
2320
+
2321
+ /** @type {import('types').ResponseHeaders} */
2322
+ const headers = {};
2323
+ for (const [key, value] of response.headers) {
2324
+ // TODO skip others besides set-cookie and etag?
2325
+ if (key !== 'set-cookie' && key !== 'etag') {
2326
+ headers[key] = value;
2327
+ }
2328
+ }
2329
+
2330
+ if (!opts.body || typeof opts.body === 'string') {
2331
+ const status_number = Number(response.status);
2332
+ if (isNaN(status_number)) {
2333
+ throw new Error(
2334
+ `response.status is not a number. value: "${
2335
+ response.status
2336
+ }" type: ${typeof response.status}`
2337
+ );
2338
+ }
2339
+
2340
+ fetched.push({
2341
+ url: requested,
2342
+ body: opts.body,
2343
+ response: {
2344
+ status: status_number,
2345
+ statusText: response.statusText,
2346
+ headers,
2347
+ body
2348
+ }
2349
+ });
2350
+ }
2351
+
2352
+ if (dependency) {
2353
+ dependency.body = body;
2354
+ }
2355
+
2356
+ return body;
2357
+ }
2358
+
2359
+ if (key === 'arrayBuffer') {
2360
+ return async () => {
2361
+ const buffer = await response.arrayBuffer();
2362
+
2363
+ if (dependency) {
2364
+ dependency.body = new Uint8Array(buffer);
2365
+ }
2366
+
2367
+ // TODO should buffer be inlined into the page (albeit base64'd)?
2368
+ // any conditions in which it shouldn't be?
2369
+
2370
+ return buffer;
2371
+ };
2372
+ }
2373
+
2374
+ if (key === 'text') {
2375
+ return text;
2376
+ }
2377
+
2378
+ if (key === 'json') {
2379
+ return async () => {
2380
+ return JSON.parse(await text());
2381
+ };
2382
+ }
2383
+
2384
+ // TODO arrayBuffer?
2385
+
2386
+ return Reflect.get(response, key, response);
2387
+ }
2388
+ });
2389
+
2390
+ return proxy;
2391
+ },
2392
+ stuff: { ...stuff },
2393
+ status: is_error ? status ?? null : null,
2394
+ error: is_error ? error ?? null : null
2395
+ };
2396
+
2397
+ if (options.dev) {
2398
+ // TODO remove this for 1.0
2399
+ Object.defineProperty(load_input, 'page', {
2400
+ get: () => {
2401
+ throw new Error('`page` in `load` functions has been replaced by `url` and `params`');
2402
+ }
2403
+ });
2404
+ }
2405
+
2406
+ loaded = await module.load.call(null, load_input);
2407
+
2408
+ if (!loaded) {
2409
+ // TODO do we still want to enforce this now that there's no fallthrough?
2410
+ throw new Error(`load function must return a value${options.dev ? ` (${node.file})` : ''}`);
2411
+ }
2412
+ } else if (shadow.body) {
2413
+ loaded = {
2414
+ props: shadow.body
2415
+ };
2416
+ } else {
2417
+ loaded = {};
2418
+ }
2419
+
2420
+ // generate __data.json files when prerendering
2421
+ if (shadow.body && state.prerendering) {
2422
+ const pathname = `${event.url.pathname.replace(/\/$/, '')}/__data.json`;
2423
+
2424
+ const dependency = {
2425
+ response: new Response(undefined),
2426
+ body: JSON.stringify(shadow.body)
2427
+ };
2428
+
2429
+ state.prerendering.dependencies.set(pathname, dependency);
2430
+ }
2431
+
2432
+ return {
2433
+ node,
2434
+ props: shadow.body,
2435
+ loaded: normalize(loaded),
2436
+ stuff: loaded.stuff || stuff,
2437
+ fetched,
2438
+ set_cookie_headers: new_cookies.map((new_cookie) => {
2439
+ const { name, value, ...options } = new_cookie;
2440
+ // @ts-expect-error
2441
+ return serialize_1(name, value, options);
2442
+ }),
2443
+ uses_credentials
2444
+ };
2445
+ }
2446
+
2447
+ /**
2448
+ *
2449
+ * @param {import('types').SSRPage} route
2450
+ * @param {import('types').RequestEvent} event
2451
+ * @param {import('types').SSROptions} options
2452
+ * @param {boolean} prerender
2453
+ * @returns {Promise<import('types').ShadowData>}
2454
+ */
2455
+ async function load_shadow_data(route, event, options, prerender) {
2456
+ if (!route.shadow) return {};
2457
+
2458
+ try {
2459
+ const mod = await route.shadow();
2460
+
2461
+ if (prerender && (mod.post || mod.put || mod.del || mod.patch)) {
2462
+ throw new Error('Cannot prerender pages that have endpoints with mutative methods');
2463
+ }
2464
+
2465
+ const method = normalize_request_method(event);
2466
+ const is_get = method === 'head' || method === 'get';
2467
+ const handler = method === 'head' ? mod.head || mod.get : mod[method];
2468
+
2469
+ if (!handler && !is_get) {
2470
+ return {
2471
+ status: 405,
2472
+ error: new Error(`${method} method not allowed`)
2473
+ };
2474
+ }
2475
+
2476
+ /** @type {import('types').ShadowData} */
2477
+ const data = {
2478
+ status: 200,
2479
+ cookies: [],
2480
+ body: {}
2481
+ };
2482
+
2483
+ if (!is_get) {
2484
+ const result = await handler(event);
2485
+
2486
+ // TODO remove for 1.0
2487
+ // @ts-expect-error
2488
+ if (result.fallthrough) {
2489
+ throw new Error(
2490
+ 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
2491
+ );
2492
+ }
2493
+
2494
+ const { status, headers, body } = validate_shadow_output(result);
2495
+ data.status = status;
2496
+
2497
+ add_cookies(/** @type {string[]} */ (data.cookies), headers);
2498
+
2499
+ // Redirects are respected...
2500
+ if (status >= 300 && status < 400) {
2501
+ data.redirect = /** @type {string} */ (
2502
+ headers instanceof Headers ? headers.get('location') : headers.location
2503
+ );
2504
+ return data;
2505
+ }
2506
+
2507
+ // ...but 4xx and 5xx status codes _don't_ result in the error page
2508
+ // rendering for non-GET requests — instead, we allow the page
2509
+ // to render with any validation errors etc that were returned
2510
+ data.body = body;
2511
+ }
2512
+
2513
+ const get = (method === 'head' && mod.head) || mod.get;
2514
+ if (get) {
2515
+ const result = await get(event);
2516
+
2517
+ // TODO remove for 1.0
2518
+ // @ts-expect-error
2519
+ if (result.fallthrough) {
2520
+ throw new Error(
2521
+ 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
2522
+ );
2523
+ }
2524
+
2525
+ const { status, headers, body } = validate_shadow_output(result);
2526
+ add_cookies(/** @type {string[]} */ (data.cookies), headers);
2527
+ data.status = status;
2528
+
2529
+ if (status >= 400) {
2530
+ data.error = new Error('Failed to load data');
2531
+ return data;
2532
+ }
2533
+
2534
+ if (status >= 300) {
2535
+ data.redirect = /** @type {string} */ (
2536
+ headers instanceof Headers ? headers.get('location') : headers.location
2537
+ );
2538
+ return data;
2539
+ }
2540
+
2541
+ data.body = { ...body, ...data.body };
2542
+ }
2543
+
2544
+ return data;
2545
+ } catch (e) {
2546
+ const error = coalesce_to_error(e);
2547
+ options.handle_error(error, event);
2548
+
2549
+ return {
2550
+ status: 500,
2551
+ error
2552
+ };
2553
+ }
2554
+ }
2555
+
2556
+ /**
2557
+ * @param {string[]} target
2558
+ * @param {Partial<import('types').ResponseHeaders>} headers
2559
+ */
2560
+ function add_cookies(target, headers) {
2561
+ const cookies = headers['set-cookie'];
2562
+ if (cookies) {
2563
+ if (Array.isArray(cookies)) {
2564
+ target.push(...cookies);
2565
+ } else {
2566
+ target.push(/** @type {string} */ (cookies));
2567
+ }
2568
+ }
2569
+ }
2570
+
2571
+ /**
2572
+ * @param {import('types').ShadowEndpointOutput} result
2573
+ */
2574
+ function validate_shadow_output(result) {
2575
+ const { status = 200, body = {} } = result;
2576
+ let headers = result.headers || {};
2577
+
2578
+ if (headers instanceof Headers) {
2579
+ if (headers.has('set-cookie')) {
2580
+ throw new Error(
2581
+ 'Endpoint request handler cannot use Headers interface with Set-Cookie headers'
2582
+ );
2583
+ }
2584
+ } else {
2585
+ headers = lowercase_keys(/** @type {Record<string, string>} */ (headers));
2586
+ }
2587
+
2588
+ if (!is_pojo(body)) {
2589
+ throw new Error('Body returned from endpoint request handler must be a plain object');
2590
+ }
2591
+
2592
+ return { status, headers, body };
2593
+ }
2594
+
2595
+ /**
2596
+ * @typedef {import('./types.js').Loaded} Loaded
2597
+ * @typedef {import('types').SSROptions} SSROptions
2598
+ * @typedef {import('types').SSRState} SSRState
2599
+ */
2600
+
2601
+ /**
2602
+ * @param {{
2603
+ * event: import('types').RequestEvent;
2604
+ * options: SSROptions;
2605
+ * state: SSRState;
2606
+ * $session: any;
2607
+ * status: number;
2608
+ * error: Error;
2609
+ * resolve_opts: import('types').RequiredResolveOptions;
2610
+ * }} opts
2611
+ */
2612
+ async function respond_with_error({
2613
+ event,
2614
+ options,
2615
+ state,
2616
+ $session,
2617
+ status,
2618
+ error,
2619
+ resolve_opts
2620
+ }) {
2621
+ try {
2622
+ const branch = [];
2623
+ let stuff = {};
2624
+
2625
+ if (resolve_opts.ssr) {
2626
+ const default_layout = await options.manifest._.nodes[0](); // 0 is always the root layout
2627
+ const default_error = await options.manifest._.nodes[1](); // 1 is always the root error
2628
+
2629
+ const layout_loaded = /** @type {Loaded} */ (
2630
+ await load_node({
2631
+ event,
2632
+ options,
2633
+ state,
2634
+ route: null,
2635
+ node: default_layout,
2636
+ $session,
2637
+ stuff: {},
2638
+ is_error: false,
2639
+ is_leaf: false
2640
+ })
2641
+ );
2642
+
2643
+ const error_loaded = /** @type {Loaded} */ (
2644
+ await load_node({
2645
+ event,
2646
+ options,
2647
+ state,
2648
+ route: null,
2649
+ node: default_error,
2650
+ $session,
2651
+ stuff: layout_loaded ? layout_loaded.stuff : {},
2652
+ is_error: true,
2653
+ is_leaf: false,
2654
+ status,
2655
+ error
2656
+ })
2657
+ );
2658
+
2659
+ branch.push(layout_loaded, error_loaded);
2660
+ stuff = error_loaded.stuff;
2661
+ }
2662
+
2663
+ return await render_response({
2664
+ options,
2665
+ state,
2666
+ $session,
2667
+ page_config: {
2668
+ hydrate: options.hydrate,
2669
+ router: options.router
2670
+ },
2671
+ stuff,
2672
+ status,
2673
+ error,
2674
+ branch,
2675
+ event,
2676
+ resolve_opts
2677
+ });
2678
+ } catch (err) {
2679
+ const error = coalesce_to_error(err);
2680
+
2681
+ options.handle_error(error, event);
2682
+
2683
+ return new Response(error.stack, {
2684
+ status: 500
2685
+ });
2686
+ }
2687
+ }
2688
+
2689
+ /**
2690
+ * @typedef {import('./types.js').Loaded} Loaded
2691
+ * @typedef {import('types').SSRNode} SSRNode
2692
+ * @typedef {import('types').SSROptions} SSROptions
2693
+ * @typedef {import('types').SSRState} SSRState
2694
+ */
2695
+
2696
+ /**
2697
+ * Gets the nodes, calls `load` for each of them, and then calls render to build the HTML response.
2698
+ * @param {{
2699
+ * event: import('types').RequestEvent;
2700
+ * options: SSROptions;
2701
+ * state: SSRState;
2702
+ * $session: any;
2703
+ * resolve_opts: import('types').RequiredResolveOptions;
2704
+ * route: import('types').SSRPage;
2705
+ * }} opts
2706
+ * @returns {Promise<Response>}
2707
+ */
2708
+ async function respond$1(opts) {
2709
+ const { event, options, state, $session, route, resolve_opts } = opts;
2710
+
2711
+ /** @type {Array<SSRNode | undefined>} */
2712
+ let nodes;
2713
+
2714
+ if (!resolve_opts.ssr) {
2715
+ return await render_response({
2716
+ ...opts,
2717
+ branch: [],
2718
+ page_config: {
2719
+ hydrate: true,
2720
+ router: true
2721
+ },
2722
+ status: 200,
2723
+ error: null,
2724
+ event,
2725
+ stuff: {}
2726
+ });
2727
+ }
2728
+
2729
+ try {
2730
+ nodes = await Promise.all(
2731
+ // we use == here rather than === because [undefined] serializes as "[null]"
2732
+ route.a.map((n) => (n == undefined ? n : options.manifest._.nodes[n]()))
2733
+ );
2734
+ } catch (err) {
2735
+ const error = coalesce_to_error(err);
2736
+
2737
+ options.handle_error(error, event);
2738
+
2739
+ return await respond_with_error({
2740
+ event,
2741
+ options,
2742
+ state,
2743
+ $session,
2744
+ status: 500,
2745
+ error,
2746
+ resolve_opts
2747
+ });
2748
+ }
2749
+
2750
+ // the leaf node will be present. only layouts may be undefined
2751
+ const leaf = /** @type {SSRNode} */ (nodes[nodes.length - 1]).module;
2752
+
2753
+ let page_config = get_page_config(leaf, options);
2754
+
2755
+ if (state.prerendering) {
2756
+ // if the page isn't marked as prerenderable (or is explicitly
2757
+ // marked NOT prerenderable, if `prerender.default` is `true`),
2758
+ // then bail out at this point
2759
+ const should_prerender = leaf.prerender ?? options.prerender.default;
2760
+ if (!should_prerender) {
2761
+ return new Response(undefined, {
2762
+ status: 204
2763
+ });
2764
+ }
2765
+ }
2766
+
2767
+ /** @type {Array<Loaded>} */
2768
+ let branch = [];
2769
+
2770
+ /** @type {number} */
2771
+ let status = 200;
2772
+
2773
+ /** @type {Error | null} */
2774
+ let error = null;
2775
+
2776
+ /** @type {string[]} */
2777
+ let set_cookie_headers = [];
2778
+
2779
+ let stuff = {};
2780
+
2781
+ ssr: {
2782
+ for (let i = 0; i < nodes.length; i += 1) {
2783
+ const node = nodes[i];
2784
+
2785
+ /** @type {Loaded | undefined} */
2786
+ let loaded;
2787
+
2788
+ if (node) {
2789
+ try {
2790
+ loaded = await load_node({
2791
+ ...opts,
2792
+ node,
2793
+ stuff,
2794
+ is_error: false,
2795
+ is_leaf: i === nodes.length - 1
2796
+ });
2797
+
2798
+ set_cookie_headers = set_cookie_headers.concat(loaded.set_cookie_headers);
2799
+
2800
+ if (loaded.loaded.redirect) {
2801
+ return with_cookies(
2802
+ new Response(undefined, {
2803
+ status: loaded.loaded.status,
2804
+ headers: {
2805
+ location: loaded.loaded.redirect
2806
+ }
2807
+ }),
2808
+ set_cookie_headers
2809
+ );
2810
+ }
2811
+
2812
+ if (loaded.loaded.error) {
2813
+ ({ status, error } = loaded.loaded);
2814
+ }
2815
+ } catch (err) {
2816
+ const e = coalesce_to_error(err);
2817
+
2818
+ options.handle_error(e, event);
2819
+
2820
+ status = 500;
2821
+ error = e;
2822
+ }
2823
+
2824
+ if (loaded && !error) {
2825
+ branch.push(loaded);
2826
+ }
2827
+
2828
+ if (error) {
2829
+ while (i--) {
2830
+ if (route.b[i]) {
2831
+ const index = /** @type {number} */ (route.b[i]);
2832
+ const error_node = await options.manifest._.nodes[index]();
2833
+
2834
+ /** @type {Loaded} */
2835
+ let node_loaded;
2836
+ let j = i;
2837
+ while (!(node_loaded = branch[j])) {
2838
+ j -= 1;
2839
+ }
2840
+
2841
+ try {
2842
+ const error_loaded = /** @type {import('./types').Loaded} */ (
2843
+ await load_node({
2844
+ ...opts,
2845
+ node: error_node,
2846
+ stuff: node_loaded.stuff,
2847
+ is_error: true,
2848
+ is_leaf: false,
2849
+ status,
2850
+ error
2851
+ })
2852
+ );
2853
+
2854
+ if (error_loaded.loaded.error) {
2855
+ continue;
2856
+ }
2857
+
2858
+ page_config = get_page_config(error_node.module, options);
2859
+ branch = branch.slice(0, j + 1).concat(error_loaded);
2860
+ stuff = { ...node_loaded.stuff, ...error_loaded.stuff };
2861
+ break ssr;
2862
+ } catch (err) {
2863
+ const e = coalesce_to_error(err);
2864
+
2865
+ options.handle_error(e, event);
2866
+
2867
+ continue;
2868
+ }
2869
+ }
2870
+ }
2871
+
2872
+ // TODO backtrack until we find an __error.svelte component
2873
+ // that we can use as the leaf node
2874
+ // for now just return regular error page
2875
+ return with_cookies(
2876
+ await respond_with_error({
2877
+ event,
2878
+ options,
2879
+ state,
2880
+ $session,
2881
+ status,
2882
+ error,
2883
+ resolve_opts
2884
+ }),
2885
+ set_cookie_headers
2886
+ );
2887
+ }
2888
+ }
2889
+
2890
+ if (loaded && loaded.loaded.stuff) {
2891
+ stuff = {
2892
+ ...stuff,
2893
+ ...loaded.loaded.stuff
2894
+ };
2895
+ }
2896
+ }
2897
+ }
2898
+
2899
+ try {
2900
+ return with_cookies(
2901
+ await render_response({
2902
+ ...opts,
2903
+ stuff,
2904
+ event,
2905
+ page_config,
2906
+ status,
2907
+ error,
2908
+ branch: branch.filter(Boolean)
2909
+ }),
2910
+ set_cookie_headers
2911
+ );
2912
+ } catch (err) {
2913
+ const error = coalesce_to_error(err);
2914
+
2915
+ options.handle_error(error, event);
2916
+
2917
+ return with_cookies(
2918
+ await respond_with_error({
2919
+ ...opts,
2920
+ status: 500,
2921
+ error
2922
+ }),
2923
+ set_cookie_headers
2924
+ );
2925
+ }
2926
+ }
2927
+
2928
+ /**
2929
+ * @param {import('types').SSRComponent} leaf
2930
+ * @param {SSROptions} options
2931
+ */
2932
+ function get_page_config(leaf, options) {
2933
+ // TODO remove for 1.0
2934
+ if ('ssr' in leaf) {
2935
+ throw new Error(
2936
+ '`export const ssr` has been removed — use the handle hook instead: https://kit.svelte.dev/docs/hooks#handle'
2937
+ );
2938
+ }
2939
+
2940
+ return {
2941
+ router: 'router' in leaf ? !!leaf.router : options.router,
2942
+ hydrate: 'hydrate' in leaf ? !!leaf.hydrate : options.hydrate
2943
+ };
2944
+ }
2945
+
2946
+ /**
2947
+ * @param {Response} response
2948
+ * @param {string[]} set_cookie_headers
2949
+ */
2950
+ function with_cookies(response, set_cookie_headers) {
2951
+ if (set_cookie_headers.length) {
2952
+ set_cookie_headers.forEach((value) => {
2953
+ response.headers.append('set-cookie', value);
2954
+ });
2955
+ }
2956
+ return response;
2957
+ }
2958
+
2959
+ /**
2960
+ * @param {import('types').RequestEvent} event
2961
+ * @param {import('types').SSRPage} route
2962
+ * @param {import('types').SSROptions} options
2963
+ * @param {import('types').SSRState} state
2964
+ * @param {import('types').RequiredResolveOptions} resolve_opts
2965
+ * @returns {Promise<Response>}
2966
+ */
2967
+ async function render_page(event, route, options, state, resolve_opts) {
2968
+ if (state.initiator === route) {
2969
+ // infinite request cycle detected
2970
+ return new Response(`Not found: ${event.url.pathname}`, {
2971
+ status: 404
2972
+ });
2973
+ }
2974
+
2975
+ if (route.shadow) {
2976
+ const type = negotiate(event.request.headers.get('accept') || 'text/html', [
2977
+ 'text/html',
2978
+ 'application/json'
2979
+ ]);
2980
+
2981
+ if (type === 'application/json') {
2982
+ return render_endpoint(event, await route.shadow());
2983
+ }
2984
+ }
2985
+
2986
+ const $session = await options.hooks.getSession(event);
2987
+
2988
+ return respond$1({
2989
+ event,
2990
+ options,
2991
+ state,
2992
+ $session,
2993
+ resolve_opts,
2994
+ route
2995
+ });
2996
+ }
2997
+
2998
+ /**
2999
+ * @param {string} accept
3000
+ * @param {string[]} types
3001
+ */
3002
+ function negotiate(accept, types) {
3003
+ const parts = accept
3004
+ .split(',')
3005
+ .map((str, i) => {
3006
+ const match = /([^/]+)\/([^;]+)(?:;q=([0-9.]+))?/.exec(str);
3007
+ if (match) {
3008
+ const [, type, subtype, q = '1'] = match;
3009
+ return { type, subtype, q: +q, i };
3010
+ }
3011
+
3012
+ throw new Error(`Invalid Accept header: ${accept}`);
3013
+ })
3014
+ .sort((a, b) => {
3015
+ if (a.q !== b.q) {
3016
+ return b.q - a.q;
3017
+ }
3018
+
3019
+ if ((a.subtype === '*') !== (b.subtype === '*')) {
3020
+ return a.subtype === '*' ? 1 : -1;
3021
+ }
3022
+
3023
+ if ((a.type === '*') !== (b.type === '*')) {
3024
+ return a.type === '*' ? 1 : -1;
3025
+ }
3026
+
3027
+ return a.i - b.i;
3028
+ });
3029
+
3030
+ let accepted;
3031
+ let min_priority = Infinity;
3032
+
3033
+ for (const mimetype of types) {
3034
+ const [type, subtype] = mimetype.split('/');
3035
+ const priority = parts.findIndex(
3036
+ (part) =>
3037
+ (part.type === type || part.type === '*') &&
3038
+ (part.subtype === subtype || part.subtype === '*')
3039
+ );
3040
+
3041
+ if (priority !== -1 && priority < min_priority) {
3042
+ accepted = mimetype;
3043
+ min_priority = priority;
3044
+ }
3045
+ }
3046
+
3047
+ return accepted;
3048
+ }
3049
+
3050
+ /**
3051
+ * @param {RegExpMatchArray} match
3052
+ * @param {string[]} names
3053
+ * @param {string[]} types
3054
+ * @param {Record<string, import('types').ParamMatcher>} matchers
3055
+ */
3056
+ function exec(match, names, types, matchers) {
3057
+ /** @type {Record<string, string>} */
3058
+ const params = {};
3059
+
3060
+ for (let i = 0; i < names.length; i += 1) {
3061
+ const name = names[i];
3062
+ const type = types[i];
3063
+ const value = match[i + 1] || '';
3064
+
3065
+ if (type) {
3066
+ const matcher = matchers[type];
3067
+ if (!matcher) throw new Error(`Missing "${type}" param matcher`); // TODO do this ahead of time?
3068
+
3069
+ if (!matcher(value)) return;
3070
+ }
3071
+
3072
+ params[name] = value;
3073
+ }
3074
+
3075
+ return params;
3076
+ }
3077
+
3078
+ const DATA_SUFFIX = '/__data.json';
3079
+
3080
+ /** @param {{ html: string }} opts */
3081
+ const default_transform = ({ html }) => html;
3082
+
3083
+ /** @type {import('types').Respond} */
3084
+ async function respond(request, options, state) {
3085
+ let url = new URL(request.url);
3086
+
3087
+ const { parameter, allowed } = options.method_override;
3088
+ const method_override = url.searchParams.get(parameter)?.toUpperCase();
3089
+
3090
+ if (method_override) {
3091
+ if (request.method === 'POST') {
3092
+ if (allowed.includes(method_override)) {
3093
+ request = new Proxy(request, {
3094
+ get: (target, property, _receiver) => {
3095
+ if (property === 'method') return method_override;
3096
+ return Reflect.get(target, property, target);
3097
+ }
3098
+ });
3099
+ } else {
3100
+ const verb = allowed.length === 0 ? 'enabled' : 'allowed';
3101
+ const body = `${parameter}=${method_override} is not ${verb}. See https://kit.svelte.dev/docs/configuration#methodoverride`;
3102
+
3103
+ return new Response(body, {
3104
+ status: 400
3105
+ });
3106
+ }
3107
+ } else {
3108
+ throw new Error(`${parameter}=${method_override} is only allowed with POST requests`);
3109
+ }
3110
+ }
3111
+
3112
+ let decoded;
3113
+ try {
3114
+ decoded = decodeURI(url.pathname);
3115
+ } catch {
3116
+ return new Response('Malformed URI', { status: 400 });
3117
+ }
3118
+
3119
+ /** @type {import('types').SSRRoute | null} */
3120
+ let route = null;
3121
+
3122
+ /** @type {Record<string, string>} */
3123
+ let params = {};
3124
+
3125
+ if (options.paths.base && !state.prerendering?.fallback) {
3126
+ if (!decoded.startsWith(options.paths.base)) {
3127
+ return new Response('Not found', { status: 404 });
3128
+ }
3129
+ decoded = decoded.slice(options.paths.base.length) || '/';
3130
+ }
3131
+
3132
+ const is_data_request = decoded.endsWith(DATA_SUFFIX);
3133
+
3134
+ if (is_data_request) {
3135
+ const data_suffix_length = DATA_SUFFIX.length - (options.trailing_slash === 'always' ? 1 : 0);
3136
+ decoded = decoded.slice(0, -data_suffix_length) || '/';
3137
+ url = new URL(url.origin + url.pathname.slice(0, -data_suffix_length) + url.search);
3138
+ }
3139
+
3140
+ if (!state.prerendering?.fallback) {
3141
+ const matchers = await options.manifest._.matchers();
3142
+
3143
+ for (const candidate of options.manifest._.routes) {
3144
+ const match = candidate.pattern.exec(decoded);
3145
+ if (!match) continue;
3146
+
3147
+ const matched = exec(match, candidate.names, candidate.types, matchers);
3148
+ if (matched) {
3149
+ route = candidate;
3150
+ params = decode_params(matched);
3151
+ break;
3152
+ }
3153
+ }
3154
+ }
3155
+
3156
+ if (route) {
3157
+ if (route.type === 'page') {
3158
+ const normalized = normalize_path(url.pathname, options.trailing_slash);
3159
+
3160
+ if (normalized !== url.pathname && !state.prerendering?.fallback) {
3161
+ return new Response(undefined, {
3162
+ status: 301,
3163
+ headers: {
3164
+ 'x-sveltekit-normalize': '1',
3165
+ location:
3166
+ // ensure paths starting with '//' are not treated as protocol-relative
3167
+ (normalized.startsWith('//') ? url.origin + normalized : normalized) +
3168
+ (url.search === '?' ? '' : url.search)
3169
+ }
3170
+ });
3171
+ }
3172
+ } else if (is_data_request) {
3173
+ // requesting /__data.json should fail for a standalone endpoint
3174
+ return new Response(undefined, {
3175
+ status: 404
3176
+ });
3177
+ }
3178
+ }
3179
+
3180
+ /** @type {import('types').RequestEvent} */
3181
+ const event = {
3182
+ get clientAddress() {
3183
+ if (!state.getClientAddress) {
3184
+ throw new Error(
3185
+ `${
3186
+ import.meta.env.VITE_SVELTEKIT_ADAPTER_NAME
3187
+ } does not specify getClientAddress. Please raise an issue`
3188
+ );
3189
+ }
3190
+
3191
+ Object.defineProperty(event, 'clientAddress', {
3192
+ value: state.getClientAddress()
3193
+ });
3194
+
3195
+ return event.clientAddress;
3196
+ },
3197
+ locals: {},
3198
+ params,
3199
+ platform: state.platform,
3200
+ request,
3201
+ routeId: route && route.id,
3202
+ url
3203
+ };
3204
+
3205
+ // TODO remove this for 1.0
3206
+ /**
3207
+ * @param {string} property
3208
+ * @param {string} replacement
3209
+ * @param {string} suffix
3210
+ */
3211
+ const removed = (property, replacement, suffix = '') => ({
3212
+ get: () => {
3213
+ throw new Error(`event.${property} has been replaced by event.${replacement}` + suffix);
3214
+ }
3215
+ });
3216
+
3217
+ const details = '. See https://github.com/sveltejs/kit/pull/3384 for details';
3218
+
3219
+ const body_getter = {
3220
+ get: () => {
3221
+ throw new Error(
3222
+ 'To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`' +
3223
+ details
3224
+ );
3225
+ }
3226
+ };
3227
+
3228
+ Object.defineProperties(event, {
3229
+ method: removed('method', 'request.method', details),
3230
+ headers: removed('headers', 'request.headers', details),
3231
+ origin: removed('origin', 'url.origin'),
3232
+ path: removed('path', 'url.pathname'),
3233
+ query: removed('query', 'url.searchParams'),
3234
+ body: body_getter,
3235
+ rawBody: body_getter
3236
+ });
3237
+
3238
+ /** @type {import('types').RequiredResolveOptions} */
3239
+ let resolve_opts = {
3240
+ ssr: true,
3241
+ transformPage: default_transform
3242
+ };
3243
+
3244
+ // TODO match route before calling handle?
3245
+
3246
+ try {
3247
+ const response = await options.hooks.handle({
3248
+ event,
3249
+ resolve: async (event, opts) => {
3250
+ if (opts) {
3251
+ resolve_opts = {
3252
+ ssr: opts.ssr !== false,
3253
+ transformPage: opts.transformPage || default_transform
3254
+ };
3255
+ }
3256
+
3257
+ if (state.prerendering?.fallback) {
3258
+ return await render_response({
3259
+ event,
3260
+ options,
3261
+ state,
3262
+ $session: await options.hooks.getSession(event),
3263
+ page_config: { router: true, hydrate: true },
3264
+ stuff: {},
3265
+ status: 200,
3266
+ error: null,
3267
+ branch: [],
3268
+ resolve_opts: {
3269
+ ...resolve_opts,
3270
+ ssr: false
3271
+ }
3272
+ });
3273
+ }
3274
+
3275
+ if (route) {
3276
+ /** @type {Response} */
3277
+ let response;
3278
+
3279
+ if (is_data_request && route.type === 'page' && route.shadow) {
3280
+ response = await render_endpoint(event, await route.shadow());
3281
+
3282
+ // loading data for a client-side transition is a special case
3283
+ if (request.headers.has('x-sveltekit-load')) {
3284
+ // since redirects are opaque to the browser, we need to repackage
3285
+ // 3xx responses as 200s with a custom header
3286
+ if (response.status >= 300 && response.status < 400) {
3287
+ const location = response.headers.get('location');
3288
+
3289
+ if (location) {
3290
+ const headers = new Headers(response.headers);
3291
+ headers.set('x-sveltekit-location', location);
3292
+ response = new Response(undefined, {
3293
+ status: 204,
3294
+ headers
3295
+ });
3296
+ }
3297
+ }
3298
+ }
3299
+ } else {
3300
+ response =
3301
+ route.type === 'endpoint'
3302
+ ? await render_endpoint(event, await route.load())
3303
+ : await render_page(event, route, options, state, resolve_opts);
3304
+ }
3305
+
3306
+ if (response) {
3307
+ // respond with 304 if etag matches
3308
+ if (response.status === 200 && response.headers.has('etag')) {
3309
+ let if_none_match_value = request.headers.get('if-none-match');
3310
+
3311
+ // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives
3312
+ if (if_none_match_value?.startsWith('W/"')) {
3313
+ if_none_match_value = if_none_match_value.substring(2);
3314
+ }
3315
+
3316
+ const etag = /** @type {string} */ (response.headers.get('etag'));
3317
+
3318
+ if (if_none_match_value === etag) {
3319
+ const headers = new Headers({ etag });
3320
+
3321
+ // https://datatracker.ietf.org/doc/html/rfc7232#section-4.1
3322
+ for (const key of [
3323
+ 'cache-control',
3324
+ 'content-location',
3325
+ 'date',
3326
+ 'expires',
3327
+ 'vary'
3328
+ ]) {
3329
+ const value = response.headers.get(key);
3330
+ if (value) headers.set(key, value);
3331
+ }
3332
+
3333
+ return new Response(undefined, {
3334
+ status: 304,
3335
+ headers
3336
+ });
3337
+ }
3338
+ }
3339
+
3340
+ return response;
3341
+ }
3342
+ }
3343
+
3344
+ // if this request came direct from the user, rather than
3345
+ // via a `fetch` in a `load`, render a 404 page
3346
+ if (!state.initiator) {
3347
+ const $session = await options.hooks.getSession(event);
3348
+ return await respond_with_error({
3349
+ event,
3350
+ options,
3351
+ state,
3352
+ $session,
3353
+ status: 404,
3354
+ error: new Error(`Not found: ${event.url.pathname}`),
3355
+ resolve_opts
3356
+ });
3357
+ }
3358
+
3359
+ if (state.prerendering) {
3360
+ return new Response('not found', { status: 404 });
3361
+ }
3362
+
3363
+ // we can't load the endpoint from our own manifest,
3364
+ // so we need to make an actual HTTP request
3365
+ return await fetch(request);
3366
+ },
3367
+
3368
+ // TODO remove for 1.0
3369
+ // @ts-expect-error
3370
+ get request() {
3371
+ throw new Error('request in handle has been replaced with event' + details);
3372
+ }
3373
+ });
3374
+
3375
+ // TODO for 1.0, change the error message to point to docs rather than PR
3376
+ if (response && !(response instanceof Response)) {
3377
+ throw new Error('handle must return a Response object' + details);
3378
+ }
3379
+
3380
+ return response;
3381
+ } catch (/** @type {unknown} */ e) {
3382
+ const error = coalesce_to_error(e);
3383
+
3384
+ options.handle_error(error, event);
3385
+
3386
+ try {
3387
+ const $session = await options.hooks.getSession(event);
3388
+ return await respond_with_error({
3389
+ event,
3390
+ options,
3391
+ state,
3392
+ $session,
3393
+ status: 500,
3394
+ error,
3395
+ resolve_opts
3396
+ });
3397
+ } catch (/** @type {unknown} */ e) {
3398
+ const error = coalesce_to_error(e);
3399
+
3400
+ return new Response(options.dev ? error.stack : error.message, {
3401
+ status: 500
3402
+ });
3403
+ }
3404
+ }
3405
+ }
3406
+
3407
+ export { respond };