@sveltejs/kit 1.0.0-next.35 → 1.0.0-next.350

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