@sveltejs/kit 1.0.0-next.27 → 1.0.0-next.273

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 (86) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +20 -0
  3. package/assets/app/navigation.js +79 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/app/stores.js +97 -0
  6. package/assets/chunks/utils.js +13 -0
  7. package/assets/client/singletons.js +21 -0
  8. package/assets/client/start.js +1520 -0
  9. package/assets/components/error.svelte +18 -2
  10. package/assets/env.js +8 -0
  11. package/assets/paths.js +13 -0
  12. package/assets/server/index.js +2760 -0
  13. package/dist/chunks/amp_hook.js +56 -0
  14. package/dist/chunks/build.js +658 -0
  15. package/dist/chunks/cert.js +28154 -0
  16. package/dist/chunks/index.js +467 -0
  17. package/dist/chunks/index2.js +836 -0
  18. package/dist/chunks/index3.js +638 -0
  19. package/dist/chunks/index4.js +115 -0
  20. package/dist/chunks/index5.js +891 -0
  21. package/dist/chunks/index6.js +170 -0
  22. package/dist/chunks/index7.js +15584 -0
  23. package/dist/chunks/index8.js +4207 -0
  24. package/dist/chunks/misc.js +3 -0
  25. package/dist/chunks/multipart-parser.js +449 -0
  26. package/dist/cli.js +1132 -86
  27. package/dist/hooks.js +28 -0
  28. package/dist/install-fetch.js +6518 -0
  29. package/dist/node.js +95 -0
  30. package/package.json +96 -54
  31. package/svelte-kit.js +2 -0
  32. package/types/ambient-modules.d.ts +208 -0
  33. package/types/app.d.ts +35 -0
  34. package/types/config.d.ts +200 -0
  35. package/types/csp.d.ts +115 -0
  36. package/types/endpoint.d.ts +39 -0
  37. package/types/helper.d.ts +23 -0
  38. package/types/hooks.d.ts +37 -0
  39. package/types/index.d.ts +24 -0
  40. package/types/internal.d.ts +260 -0
  41. package/types/page.d.ts +33 -0
  42. package/CHANGELOG.md +0 -319
  43. package/assets/runtime/app/navigation.js +0 -23
  44. package/assets/runtime/app/navigation.js.map +0 -1
  45. package/assets/runtime/app/paths.js +0 -2
  46. package/assets/runtime/app/paths.js.map +0 -1
  47. package/assets/runtime/app/stores.js +0 -78
  48. package/assets/runtime/app/stores.js.map +0 -1
  49. package/assets/runtime/internal/singletons.js +0 -15
  50. package/assets/runtime/internal/singletons.js.map +0 -1
  51. package/assets/runtime/internal/start.js +0 -591
  52. package/assets/runtime/internal/start.js.map +0 -1
  53. package/assets/runtime/utils-85ebcc60.js +0 -18
  54. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  55. package/dist/api.js +0 -44
  56. package/dist/api.js.map +0 -1
  57. package/dist/build.js +0 -246
  58. package/dist/build.js.map +0 -1
  59. package/dist/cli.js.map +0 -1
  60. package/dist/colors.js +0 -37
  61. package/dist/colors.js.map +0 -1
  62. package/dist/create_app.js +0 -580
  63. package/dist/create_app.js.map +0 -1
  64. package/dist/index.js +0 -368
  65. package/dist/index.js.map +0 -1
  66. package/dist/index2.js +0 -12035
  67. package/dist/index2.js.map +0 -1
  68. package/dist/index3.js +0 -547
  69. package/dist/index3.js.map +0 -1
  70. package/dist/index4.js +0 -74
  71. package/dist/index4.js.map +0 -1
  72. package/dist/index5.js +0 -464
  73. package/dist/index5.js.map +0 -1
  74. package/dist/index6.js +0 -734
  75. package/dist/index6.js.map +0 -1
  76. package/dist/logging.js +0 -43
  77. package/dist/logging.js.map +0 -1
  78. package/dist/package.js +0 -432
  79. package/dist/package.js.map +0 -1
  80. package/dist/renderer.js +0 -2403
  81. package/dist/renderer.js.map +0 -1
  82. package/dist/standard.js +0 -101
  83. package/dist/standard.js.map +0 -1
  84. package/dist/utils.js +0 -58
  85. package/dist/utils.js.map +0 -1
  86. package/svelte-kit +0 -3
@@ -0,0 +1,2760 @@
1
+ /** @param {Partial<import('types/helper').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/hooks').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/hooks').RequestEvent} event
93
+ * @returns string
94
+ */
95
+ function normalize_request_method(event) {
96
+ const method = event.request.method.toLowerCase();
97
+ return method === 'delete' ? 'del' : method; // 'delete' is a reserved word
98
+ }
99
+
100
+ /** @param {string} body */
101
+ function error(body) {
102
+ return new Response(body, {
103
+ status: 500
104
+ });
105
+ }
106
+
107
+ /** @param {unknown} s */
108
+ function is_string(s) {
109
+ return typeof s === 'string' || s instanceof String;
110
+ }
111
+
112
+ const text_types = new Set([
113
+ 'application/xml',
114
+ 'application/json',
115
+ 'application/x-www-form-urlencoded',
116
+ 'multipart/form-data'
117
+ ]);
118
+
119
+ /**
120
+ * Decides how the body should be parsed based on its mime type. Should match what's in parse_body
121
+ *
122
+ * @param {string | undefined | null} content_type The `content-type` header of a request/response.
123
+ * @returns {boolean}
124
+ */
125
+ function is_text(content_type) {
126
+ if (!content_type) return true; // defaults to json
127
+ const type = content_type.split(';')[0].toLowerCase(); // get the mime type
128
+
129
+ return type.startsWith('text/') || type.endsWith('+xml') || text_types.has(type);
130
+ }
131
+
132
+ /**
133
+ * @param {import('types/hooks').RequestEvent} event
134
+ * @param {{ [method: string]: import('types/endpoint').RequestHandler }} mod
135
+ * @returns {Promise<Response | undefined>}
136
+ */
137
+ async function render_endpoint(event, mod) {
138
+ const method = normalize_request_method(event);
139
+
140
+ /** @type {import('types/endpoint').RequestHandler} */
141
+ let handler = mod[method];
142
+
143
+ if (!handler && method === 'head') {
144
+ handler = mod.get;
145
+ }
146
+ if (!handler) {
147
+ return;
148
+ }
149
+
150
+ const response = await handler(event);
151
+ const preface = `Invalid response from route ${event.url.pathname}`;
152
+
153
+ if (typeof response !== 'object') {
154
+ return error(`${preface}: expected an object, got ${typeof response}`);
155
+ }
156
+
157
+ if (response.fallthrough) {
158
+ return;
159
+ }
160
+
161
+ const { status = 200, body = {} } = response;
162
+ const headers =
163
+ response.headers instanceof Headers
164
+ ? new Headers(response.headers)
165
+ : to_headers(response.headers);
166
+
167
+ const type = headers.get('content-type');
168
+
169
+ if (!is_text(type) && !(body instanceof Uint8Array || is_string(body))) {
170
+ return error(
171
+ `${preface}: body must be an instance of string or Uint8Array if content-type is not a supported textual content-type`
172
+ );
173
+ }
174
+
175
+ /** @type {import('types/hooks').StrictBody} */
176
+ let normalized_body;
177
+
178
+ if (is_pojo(body) && (!type || type.startsWith('application/json'))) {
179
+ headers.set('content-type', 'application/json; charset=utf-8');
180
+ normalized_body = JSON.stringify(body);
181
+ } else {
182
+ normalized_body = /** @type {import('types/hooks').StrictBody} */ (body);
183
+ }
184
+
185
+ if (
186
+ (typeof normalized_body === 'string' || normalized_body instanceof Uint8Array) &&
187
+ !headers.has('etag')
188
+ ) {
189
+ const cache_control = headers.get('cache-control');
190
+ if (!cache_control || !/(no-store|immutable)/.test(cache_control)) {
191
+ headers.set('etag', `"${hash(normalized_body)}"`);
192
+ }
193
+ }
194
+
195
+ return new Response(method !== 'head' ? normalized_body : undefined, {
196
+ status,
197
+ headers
198
+ });
199
+ }
200
+
201
+ var chars$1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
202
+ var unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
203
+ 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)$/;
204
+ var escaped = {
205
+ '<': '\\u003C',
206
+ '>': '\\u003E',
207
+ '/': '\\u002F',
208
+ '\\': '\\\\',
209
+ '\b': '\\b',
210
+ '\f': '\\f',
211
+ '\n': '\\n',
212
+ '\r': '\\r',
213
+ '\t': '\\t',
214
+ '\0': '\\0',
215
+ '\u2028': '\\u2028',
216
+ '\u2029': '\\u2029'
217
+ };
218
+ var objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join('\0');
219
+ function devalue(value) {
220
+ var counts = new Map();
221
+ function walk(thing) {
222
+ if (typeof thing === 'function') {
223
+ throw new Error("Cannot stringify a function");
224
+ }
225
+ if (counts.has(thing)) {
226
+ counts.set(thing, counts.get(thing) + 1);
227
+ return;
228
+ }
229
+ counts.set(thing, 1);
230
+ if (!isPrimitive(thing)) {
231
+ var type = getType(thing);
232
+ switch (type) {
233
+ case 'Number':
234
+ case 'String':
235
+ case 'Boolean':
236
+ case 'Date':
237
+ case 'RegExp':
238
+ return;
239
+ case 'Array':
240
+ thing.forEach(walk);
241
+ break;
242
+ case 'Set':
243
+ case 'Map':
244
+ Array.from(thing).forEach(walk);
245
+ break;
246
+ default:
247
+ var proto = Object.getPrototypeOf(thing);
248
+ if (proto !== Object.prototype &&
249
+ proto !== null &&
250
+ Object.getOwnPropertyNames(proto).sort().join('\0') !== objectProtoOwnPropertyNames) {
251
+ throw new Error("Cannot stringify arbitrary non-POJOs");
252
+ }
253
+ if (Object.getOwnPropertySymbols(thing).length > 0) {
254
+ throw new Error("Cannot stringify POJOs with symbolic keys");
255
+ }
256
+ Object.keys(thing).forEach(function (key) { return walk(thing[key]); });
257
+ }
258
+ }
259
+ }
260
+ walk(value);
261
+ var names = new Map();
262
+ Array.from(counts)
263
+ .filter(function (entry) { return entry[1] > 1; })
264
+ .sort(function (a, b) { return b[1] - a[1]; })
265
+ .forEach(function (entry, i) {
266
+ names.set(entry[0], getName(i));
267
+ });
268
+ function stringify(thing) {
269
+ if (names.has(thing)) {
270
+ return names.get(thing);
271
+ }
272
+ if (isPrimitive(thing)) {
273
+ return stringifyPrimitive(thing);
274
+ }
275
+ var type = getType(thing);
276
+ switch (type) {
277
+ case 'Number':
278
+ case 'String':
279
+ case 'Boolean':
280
+ return "Object(" + stringify(thing.valueOf()) + ")";
281
+ case 'RegExp':
282
+ return "new RegExp(" + stringifyString(thing.source) + ", \"" + thing.flags + "\")";
283
+ case 'Date':
284
+ return "new Date(" + thing.getTime() + ")";
285
+ case 'Array':
286
+ var members = thing.map(function (v, i) { return i in thing ? stringify(v) : ''; });
287
+ var tail = thing.length === 0 || (thing.length - 1 in thing) ? '' : ',';
288
+ return "[" + members.join(',') + tail + "]";
289
+ case 'Set':
290
+ case 'Map':
291
+ return "new " + type + "([" + Array.from(thing).map(stringify).join(',') + "])";
292
+ default:
293
+ var obj = "{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":" + stringify(thing[key]); }).join(',') + "}";
294
+ var proto = Object.getPrototypeOf(thing);
295
+ if (proto === null) {
296
+ return Object.keys(thing).length > 0
297
+ ? "Object.assign(Object.create(null)," + obj + ")"
298
+ : "Object.create(null)";
299
+ }
300
+ return obj;
301
+ }
302
+ }
303
+ var str = stringify(value);
304
+ if (names.size) {
305
+ var params_1 = [];
306
+ var statements_1 = [];
307
+ var values_1 = [];
308
+ names.forEach(function (name, thing) {
309
+ params_1.push(name);
310
+ if (isPrimitive(thing)) {
311
+ values_1.push(stringifyPrimitive(thing));
312
+ return;
313
+ }
314
+ var type = getType(thing);
315
+ switch (type) {
316
+ case 'Number':
317
+ case 'String':
318
+ case 'Boolean':
319
+ values_1.push("Object(" + stringify(thing.valueOf()) + ")");
320
+ break;
321
+ case 'RegExp':
322
+ values_1.push(thing.toString());
323
+ break;
324
+ case 'Date':
325
+ values_1.push("new Date(" + thing.getTime() + ")");
326
+ break;
327
+ case 'Array':
328
+ values_1.push("Array(" + thing.length + ")");
329
+ thing.forEach(function (v, i) {
330
+ statements_1.push(name + "[" + i + "]=" + stringify(v));
331
+ });
332
+ break;
333
+ case 'Set':
334
+ values_1.push("new Set");
335
+ statements_1.push(name + "." + Array.from(thing).map(function (v) { return "add(" + stringify(v) + ")"; }).join('.'));
336
+ break;
337
+ case 'Map':
338
+ values_1.push("new Map");
339
+ statements_1.push(name + "." + Array.from(thing).map(function (_a) {
340
+ var k = _a[0], v = _a[1];
341
+ return "set(" + stringify(k) + ", " + stringify(v) + ")";
342
+ }).join('.'));
343
+ break;
344
+ default:
345
+ values_1.push(Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}');
346
+ Object.keys(thing).forEach(function (key) {
347
+ statements_1.push("" + name + safeProp(key) + "=" + stringify(thing[key]));
348
+ });
349
+ }
350
+ });
351
+ statements_1.push("return " + str);
352
+ return "(function(" + params_1.join(',') + "){" + statements_1.join(';') + "}(" + values_1.join(',') + "))";
353
+ }
354
+ else {
355
+ return str;
356
+ }
357
+ }
358
+ function getName(num) {
359
+ var name = '';
360
+ do {
361
+ name = chars$1[num % chars$1.length] + name;
362
+ num = ~~(num / chars$1.length) - 1;
363
+ } while (num >= 0);
364
+ return reserved.test(name) ? name + "_" : name;
365
+ }
366
+ function isPrimitive(thing) {
367
+ return Object(thing) !== thing;
368
+ }
369
+ function stringifyPrimitive(thing) {
370
+ if (typeof thing === 'string')
371
+ return stringifyString(thing);
372
+ if (thing === void 0)
373
+ return 'void 0';
374
+ if (thing === 0 && 1 / thing < 0)
375
+ return '-0';
376
+ var str = String(thing);
377
+ if (typeof thing === 'number')
378
+ return str.replace(/^(-)?0\./, '$1.');
379
+ return str;
380
+ }
381
+ function getType(thing) {
382
+ return Object.prototype.toString.call(thing).slice(8, -1);
383
+ }
384
+ function escapeUnsafeChar(c) {
385
+ return escaped[c] || c;
386
+ }
387
+ function escapeUnsafeChars(str) {
388
+ return str.replace(unsafeChars, escapeUnsafeChar);
389
+ }
390
+ function safeKey(key) {
391
+ return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
392
+ }
393
+ function safeProp(key) {
394
+ return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? "." + key : "[" + escapeUnsafeChars(JSON.stringify(key)) + "]";
395
+ }
396
+ function stringifyString(str) {
397
+ var result = '"';
398
+ for (var i = 0; i < str.length; i += 1) {
399
+ var char = str.charAt(i);
400
+ var code = char.charCodeAt(0);
401
+ if (char === '"') {
402
+ result += '\\"';
403
+ }
404
+ else if (char in escaped) {
405
+ result += escaped[char];
406
+ }
407
+ else if (code >= 0xd800 && code <= 0xdfff) {
408
+ var next = str.charCodeAt(i + 1);
409
+ // If this is the beginning of a [high, low] surrogate pair,
410
+ // add the next two characters, otherwise escape
411
+ if (code <= 0xdbff && (next >= 0xdc00 && next <= 0xdfff)) {
412
+ result += char + str[++i];
413
+ }
414
+ else {
415
+ result += "\\u" + code.toString(16).toUpperCase();
416
+ }
417
+ }
418
+ else {
419
+ result += char;
420
+ }
421
+ }
422
+ result += '"';
423
+ return result;
424
+ }
425
+
426
+ function noop() { }
427
+ function safe_not_equal(a, b) {
428
+ return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
429
+ }
430
+ Promise.resolve();
431
+
432
+ const subscriber_queue = [];
433
+ /**
434
+ * Creates a `Readable` store that allows reading by subscription.
435
+ * @param value initial value
436
+ * @param {StartStopNotifier}start start and stop notifications for subscriptions
437
+ */
438
+ function readable(value, start) {
439
+ return {
440
+ subscribe: writable(value, start).subscribe
441
+ };
442
+ }
443
+ /**
444
+ * Create a `Writable` store that allows both updating and reading by subscription.
445
+ * @param {*=}value initial value
446
+ * @param {StartStopNotifier=}start start and stop notifications for subscriptions
447
+ */
448
+ function writable(value, start = noop) {
449
+ let stop;
450
+ const subscribers = new Set();
451
+ function set(new_value) {
452
+ if (safe_not_equal(value, new_value)) {
453
+ value = new_value;
454
+ if (stop) { // store is ready
455
+ const run_queue = !subscriber_queue.length;
456
+ for (const subscriber of subscribers) {
457
+ subscriber[1]();
458
+ subscriber_queue.push(subscriber, value);
459
+ }
460
+ if (run_queue) {
461
+ for (let i = 0; i < subscriber_queue.length; i += 2) {
462
+ subscriber_queue[i][0](subscriber_queue[i + 1]);
463
+ }
464
+ subscriber_queue.length = 0;
465
+ }
466
+ }
467
+ }
468
+ }
469
+ function update(fn) {
470
+ set(fn(value));
471
+ }
472
+ function subscribe(run, invalidate = noop) {
473
+ const subscriber = [run, invalidate];
474
+ subscribers.add(subscriber);
475
+ if (subscribers.size === 1) {
476
+ stop = start(set) || noop;
477
+ }
478
+ run(value);
479
+ return () => {
480
+ subscribers.delete(subscriber);
481
+ if (subscribers.size === 0) {
482
+ stop();
483
+ stop = null;
484
+ }
485
+ };
486
+ }
487
+ return { set, update, subscribe };
488
+ }
489
+
490
+ /**
491
+ * @param {unknown} err
492
+ * @return {Error}
493
+ */
494
+ function coalesce_to_error(err) {
495
+ return err instanceof Error ||
496
+ (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message)
497
+ ? /** @type {Error} */ (err)
498
+ : new Error(JSON.stringify(err));
499
+ }
500
+
501
+ // dict from https://github.com/yahoo/serialize-javascript/blob/183c18a776e4635a379fdc620f81771f219832bb/index.js#L25
502
+ /** @type {Record<string, string>} */
503
+ const escape_json_in_html_dict = {
504
+ '<': '\\u003C',
505
+ '>': '\\u003E',
506
+ '/': '\\u002F',
507
+ '\u2028': '\\u2028',
508
+ '\u2029': '\\u2029'
509
+ };
510
+
511
+ const escape_json_in_html_regex = new RegExp(
512
+ `[${Object.keys(escape_json_in_html_dict).join('')}]`,
513
+ 'g'
514
+ );
515
+
516
+ /**
517
+ * Escape a JSONValue that's going to be embedded in a `<script>` tag
518
+ * @param {import("@sveltejs/kit/types/helper").JSONValue} val
519
+ */
520
+ function escape_json_in_html(val) {
521
+ return JSON.stringify(val).replace(
522
+ escape_json_in_html_regex,
523
+ (match) => escape_json_in_html_dict[match]
524
+ );
525
+ }
526
+
527
+ /**
528
+ * @param str {string} string to escape
529
+ * @param dict {Record<string, string>} dictionary of character replacements
530
+ * @param unicode_encoder {function(number): string} encoder to use for high unicode characters
531
+ * @returns {string}
532
+ */
533
+ function escape(str, dict, unicode_encoder) {
534
+ let result = '';
535
+
536
+ for (let i = 0; i < str.length; i += 1) {
537
+ const char = str.charAt(i);
538
+ const code = char.charCodeAt(0);
539
+
540
+ if (char in dict) {
541
+ result += dict[char];
542
+ } else if (code >= 0xd800 && code <= 0xdfff) {
543
+ const next = str.charCodeAt(i + 1);
544
+
545
+ // If this is the beginning of a [high, low] surrogate pair,
546
+ // add the next two characters, otherwise escape
547
+ if (code <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
548
+ result += char + str[++i];
549
+ } else {
550
+ result += unicode_encoder(code);
551
+ }
552
+ } else {
553
+ result += char;
554
+ }
555
+ }
556
+
557
+ return result;
558
+ }
559
+
560
+ /** @type {Record<string, string>} */
561
+ const escape_html_attr_dict = {
562
+ '<': '&lt;',
563
+ '>': '&gt;',
564
+ '"': '&quot;'
565
+ };
566
+
567
+ /**
568
+ * use for escaping string values to be used html attributes on the page
569
+ * e.g.
570
+ * <script data-url="here">
571
+ *
572
+ * @param {string} str
573
+ * @returns string escaped string
574
+ */
575
+ function escape_html_attr(str) {
576
+ return '"' + escape(str, escape_html_attr_dict, (code) => `&#${code};`) + '"';
577
+ }
578
+
579
+ const s = JSON.stringify;
580
+
581
+ /** @param {URL} url */
582
+ function create_prerendering_url_proxy(url) {
583
+ return new Proxy(url, {
584
+ get: (target, prop, receiver) => {
585
+ if (prop === 'search' || prop === 'searchParams') {
586
+ throw new Error(`Cannot access url.${prop} on a page with prerendering enabled`);
587
+ }
588
+ return Reflect.get(target, prop, receiver);
589
+ }
590
+ });
591
+ }
592
+
593
+ const encoder = new TextEncoder();
594
+
595
+ /**
596
+ * SHA-256 hashing function adapted from https://bitwiseshiftleft.github.io/sjcl
597
+ * modified and redistributed under BSD license
598
+ * @param {string} data
599
+ */
600
+ function sha256(data) {
601
+ if (!key[0]) precompute();
602
+
603
+ const out = init.slice(0);
604
+ const array = encode(data);
605
+
606
+ for (let i = 0; i < array.length; i += 16) {
607
+ const w = array.subarray(i, i + 16);
608
+
609
+ let tmp;
610
+ let a;
611
+ let b;
612
+
613
+ let out0 = out[0];
614
+ let out1 = out[1];
615
+ let out2 = out[2];
616
+ let out3 = out[3];
617
+ let out4 = out[4];
618
+ let out5 = out[5];
619
+ let out6 = out[6];
620
+ let out7 = out[7];
621
+
622
+ /* Rationale for placement of |0 :
623
+ * If a value can overflow is original 32 bits by a factor of more than a few
624
+ * million (2^23 ish), there is a possibility that it might overflow the
625
+ * 53-bit mantissa and lose precision.
626
+ *
627
+ * To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that
628
+ * propagates around the loop, and on the hash state out[]. I don't believe
629
+ * that the clamps on out4 and on out0 are strictly necessary, but it's close
630
+ * (for out4 anyway), and better safe than sorry.
631
+ *
632
+ * The clamps on out[] are necessary for the output to be correct even in the
633
+ * common case and for short inputs.
634
+ */
635
+
636
+ for (let i = 0; i < 64; i++) {
637
+ // load up the input word for this round
638
+
639
+ if (i < 16) {
640
+ tmp = w[i];
641
+ } else {
642
+ a = w[(i + 1) & 15];
643
+
644
+ b = w[(i + 14) & 15];
645
+
646
+ tmp = w[i & 15] =
647
+ (((a >>> 7) ^ (a >>> 18) ^ (a >>> 3) ^ (a << 25) ^ (a << 14)) +
648
+ ((b >>> 17) ^ (b >>> 19) ^ (b >>> 10) ^ (b << 15) ^ (b << 13)) +
649
+ w[i & 15] +
650
+ w[(i + 9) & 15]) |
651
+ 0;
652
+ }
653
+
654
+ tmp =
655
+ tmp +
656
+ out7 +
657
+ ((out4 >>> 6) ^ (out4 >>> 11) ^ (out4 >>> 25) ^ (out4 << 26) ^ (out4 << 21) ^ (out4 << 7)) +
658
+ (out6 ^ (out4 & (out5 ^ out6))) +
659
+ key[i]; // | 0;
660
+
661
+ // shift register
662
+ out7 = out6;
663
+ out6 = out5;
664
+ out5 = out4;
665
+
666
+ out4 = (out3 + tmp) | 0;
667
+
668
+ out3 = out2;
669
+ out2 = out1;
670
+ out1 = out0;
671
+
672
+ out0 =
673
+ (tmp +
674
+ ((out1 & out2) ^ (out3 & (out1 ^ out2))) +
675
+ ((out1 >>> 2) ^
676
+ (out1 >>> 13) ^
677
+ (out1 >>> 22) ^
678
+ (out1 << 30) ^
679
+ (out1 << 19) ^
680
+ (out1 << 10))) |
681
+ 0;
682
+ }
683
+
684
+ out[0] = (out[0] + out0) | 0;
685
+ out[1] = (out[1] + out1) | 0;
686
+ out[2] = (out[2] + out2) | 0;
687
+ out[3] = (out[3] + out3) | 0;
688
+ out[4] = (out[4] + out4) | 0;
689
+ out[5] = (out[5] + out5) | 0;
690
+ out[6] = (out[6] + out6) | 0;
691
+ out[7] = (out[7] + out7) | 0;
692
+ }
693
+
694
+ const bytes = new Uint8Array(out.buffer);
695
+ reverse_endianness(bytes);
696
+
697
+ return base64(bytes);
698
+ }
699
+
700
+ /** The SHA-256 initialization vector */
701
+ const init = new Uint32Array(8);
702
+
703
+ /** The SHA-256 hash key */
704
+ const key = new Uint32Array(64);
705
+
706
+ /** Function to precompute init and key. */
707
+ function precompute() {
708
+ /** @param {number} x */
709
+ function frac(x) {
710
+ return (x - Math.floor(x)) * 0x100000000;
711
+ }
712
+
713
+ let prime = 2;
714
+
715
+ for (let i = 0; i < 64; prime++) {
716
+ let is_prime = true;
717
+
718
+ for (let factor = 2; factor * factor <= prime; factor++) {
719
+ if (prime % factor === 0) {
720
+ is_prime = false;
721
+
722
+ break;
723
+ }
724
+ }
725
+
726
+ if (is_prime) {
727
+ if (i < 8) {
728
+ init[i] = frac(prime ** (1 / 2));
729
+ }
730
+
731
+ key[i] = frac(prime ** (1 / 3));
732
+
733
+ i++;
734
+ }
735
+ }
736
+ }
737
+
738
+ /** @param {Uint8Array} bytes */
739
+ function reverse_endianness(bytes) {
740
+ for (let i = 0; i < bytes.length; i += 4) {
741
+ const a = bytes[i + 0];
742
+ const b = bytes[i + 1];
743
+ const c = bytes[i + 2];
744
+ const d = bytes[i + 3];
745
+
746
+ bytes[i + 0] = d;
747
+ bytes[i + 1] = c;
748
+ bytes[i + 2] = b;
749
+ bytes[i + 3] = a;
750
+ }
751
+ }
752
+
753
+ /** @param {string} str */
754
+ function encode(str) {
755
+ const encoded = encoder.encode(str);
756
+ const length = encoded.length * 8;
757
+
758
+ // result should be a multiple of 512 bits in length,
759
+ // with room for a 1 (after the data) and two 32-bit
760
+ // words containing the original input bit length
761
+ const size = 512 * Math.ceil((length + 65) / 512);
762
+ const bytes = new Uint8Array(size / 8);
763
+ bytes.set(encoded);
764
+
765
+ // append a 1
766
+ bytes[encoded.length] = 0b10000000;
767
+
768
+ reverse_endianness(bytes);
769
+
770
+ // add the input bit length
771
+ const words = new Uint32Array(bytes.buffer);
772
+ words[words.length - 2] = Math.floor(length / 0x100000000); // this will always be zero for us
773
+ words[words.length - 1] = length;
774
+
775
+ return words;
776
+ }
777
+
778
+ /*
779
+ Based on https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
780
+
781
+ MIT License
782
+ Copyright (c) 2020 Egor Nepomnyaschih
783
+ Permission is hereby granted, free of charge, to any person obtaining a copy
784
+ of this software and associated documentation files (the "Software"), to deal
785
+ in the Software without restriction, including without limitation the rights
786
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
787
+ copies of the Software, and to permit persons to whom the Software is
788
+ furnished to do so, subject to the following conditions:
789
+ The above copyright notice and this permission notice shall be included in all
790
+ copies or substantial portions of the Software.
791
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
792
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
793
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
794
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
795
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
796
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
797
+ SOFTWARE.
798
+ */
799
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
800
+
801
+ /** @param {Uint8Array} bytes */
802
+ function base64(bytes) {
803
+ const l = bytes.length;
804
+
805
+ let result = '';
806
+ let i;
807
+
808
+ for (i = 2; i < l; i += 3) {
809
+ result += chars[bytes[i - 2] >> 2];
810
+ result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
811
+ result += chars[((bytes[i - 1] & 0x0f) << 2) | (bytes[i] >> 6)];
812
+ result += chars[bytes[i] & 0x3f];
813
+ }
814
+
815
+ if (i === l + 1) {
816
+ // 1 octet yet to write
817
+ result += chars[bytes[i - 2] >> 2];
818
+ result += chars[(bytes[i - 2] & 0x03) << 4];
819
+ result += '==';
820
+ }
821
+
822
+ if (i === l) {
823
+ // 2 octets yet to write
824
+ result += chars[bytes[i - 2] >> 2];
825
+ result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
826
+ result += chars[(bytes[i - 1] & 0x0f) << 2];
827
+ result += '=';
828
+ }
829
+
830
+ return result;
831
+ }
832
+
833
+ /** @type {Promise<void>} */
834
+ let csp_ready;
835
+
836
+ /** @type {() => string} */
837
+ let generate_nonce;
838
+
839
+ /** @type {(input: string) => string} */
840
+ let generate_hash;
841
+
842
+ if (typeof crypto !== 'undefined') {
843
+ const array = new Uint8Array(16);
844
+
845
+ generate_nonce = () => {
846
+ crypto.getRandomValues(array);
847
+ return base64(array);
848
+ };
849
+
850
+ generate_hash = sha256;
851
+ } else {
852
+ // TODO: remove this in favor of web crypto API once we no longer support Node 14
853
+ const name = 'crypto'; // store in a variable to fool esbuild when adapters bundle kit
854
+ csp_ready = import(name).then((crypto) => {
855
+ generate_nonce = () => {
856
+ return crypto.randomBytes(16).toString('base64');
857
+ };
858
+
859
+ generate_hash = (input) => {
860
+ return crypto.createHash('sha256').update(input, 'utf-8').digest().toString('base64');
861
+ };
862
+ });
863
+ }
864
+
865
+ const quoted = new Set([
866
+ 'self',
867
+ 'unsafe-eval',
868
+ 'unsafe-hashes',
869
+ 'unsafe-inline',
870
+ 'none',
871
+ 'strict-dynamic',
872
+ 'report-sample'
873
+ ]);
874
+
875
+ const crypto_pattern = /^(nonce|sha\d\d\d)-/;
876
+
877
+ class Csp {
878
+ /** @type {boolean} */
879
+ #use_hashes;
880
+
881
+ /** @type {boolean} */
882
+ #dev;
883
+
884
+ /** @type {boolean} */
885
+ #script_needs_csp;
886
+
887
+ /** @type {boolean} */
888
+ #style_needs_csp;
889
+
890
+ /** @type {import('types/csp').CspDirectives} */
891
+ #directives;
892
+
893
+ /** @type {import('types/csp').Source[]} */
894
+ #script_src;
895
+
896
+ /** @type {import('types/csp').Source[]} */
897
+ #style_src;
898
+
899
+ /**
900
+ * @param {{
901
+ * mode: string,
902
+ * directives: import('types/csp').CspDirectives
903
+ * }} config
904
+ * @param {{
905
+ * dev: boolean;
906
+ * prerender: boolean;
907
+ * needs_nonce: boolean;
908
+ * }} opts
909
+ */
910
+ constructor({ mode, directives }, { dev, prerender, needs_nonce }) {
911
+ this.#use_hashes = mode === 'hash' || (mode === 'auto' && prerender);
912
+ this.#directives = dev ? { ...directives } : directives; // clone in dev so we can safely mutate
913
+ this.#dev = dev;
914
+
915
+ const d = this.#directives;
916
+
917
+ if (dev) {
918
+ // remove strict-dynamic in dev...
919
+ // TODO reinstate this if we can figure out how to make strict-dynamic work
920
+ // if (d['default-src']) {
921
+ // d['default-src'] = d['default-src'].filter((name) => name !== 'strict-dynamic');
922
+ // if (d['default-src'].length === 0) delete d['default-src'];
923
+ // }
924
+
925
+ // if (d['script-src']) {
926
+ // d['script-src'] = d['script-src'].filter((name) => name !== 'strict-dynamic');
927
+ // if (d['script-src'].length === 0) delete d['script-src'];
928
+ // }
929
+
930
+ const effective_style_src = d['style-src'] || d['default-src'];
931
+
932
+ // ...and add unsafe-inline so we can inject <style> elements
933
+ if (effective_style_src && !effective_style_src.includes('unsafe-inline')) {
934
+ d['style-src'] = [...effective_style_src, 'unsafe-inline'];
935
+ }
936
+ }
937
+
938
+ this.#script_src = [];
939
+ this.#style_src = [];
940
+
941
+ const effective_script_src = d['script-src'] || d['default-src'];
942
+ const effective_style_src = d['style-src'] || d['default-src'];
943
+
944
+ this.#script_needs_csp =
945
+ !!effective_script_src &&
946
+ effective_script_src.filter((value) => value !== 'unsafe-inline').length > 0;
947
+
948
+ this.#style_needs_csp =
949
+ !dev &&
950
+ !!effective_style_src &&
951
+ effective_style_src.filter((value) => value !== 'unsafe-inline').length > 0;
952
+
953
+ this.script_needs_nonce = this.#script_needs_csp && !this.#use_hashes;
954
+ this.style_needs_nonce = this.#style_needs_csp && !this.#use_hashes;
955
+
956
+ if (this.script_needs_nonce || this.style_needs_nonce || needs_nonce) {
957
+ this.nonce = generate_nonce();
958
+ }
959
+ }
960
+
961
+ /** @param {string} content */
962
+ add_script(content) {
963
+ if (this.#script_needs_csp) {
964
+ if (this.#use_hashes) {
965
+ this.#script_src.push(`sha256-${generate_hash(content)}`);
966
+ } else if (this.#script_src.length === 0) {
967
+ this.#script_src.push(`nonce-${this.nonce}`);
968
+ }
969
+ }
970
+ }
971
+
972
+ /** @param {string} content */
973
+ add_style(content) {
974
+ if (this.#style_needs_csp) {
975
+ if (this.#use_hashes) {
976
+ this.#style_src.push(`sha256-${generate_hash(content)}`);
977
+ } else if (this.#style_src.length === 0) {
978
+ this.#style_src.push(`nonce-${this.nonce}`);
979
+ }
980
+ }
981
+ }
982
+
983
+ /** @param {boolean} [is_meta] */
984
+ get_header(is_meta = false) {
985
+ const header = [];
986
+
987
+ // due to browser inconsistencies, we can't append sources to default-src
988
+ // (specifically, Firefox appears to not ignore nonce-{nonce} directives
989
+ // on default-src), so we ensure that script-src and style-src exist
990
+
991
+ const directives = { ...this.#directives };
992
+
993
+ if (this.#style_src.length > 0) {
994
+ directives['style-src'] = [
995
+ ...(directives['style-src'] || directives['default-src'] || []),
996
+ ...this.#style_src
997
+ ];
998
+ }
999
+
1000
+ if (this.#script_src.length > 0) {
1001
+ directives['script-src'] = [
1002
+ ...(directives['script-src'] || directives['default-src'] || []),
1003
+ ...this.#script_src
1004
+ ];
1005
+ }
1006
+
1007
+ for (const key in directives) {
1008
+ if (is_meta && (key === 'frame-ancestors' || key === 'report-uri' || key === 'sandbox')) {
1009
+ // these values cannot be used with a <meta> tag
1010
+ // TODO warn?
1011
+ continue;
1012
+ }
1013
+
1014
+ // @ts-expect-error gimme a break typescript, `key` is obviously a member of directives
1015
+ const value = /** @type {string[] | true} */ (directives[key]);
1016
+
1017
+ if (!value) continue;
1018
+
1019
+ const directive = [key];
1020
+ if (Array.isArray(value)) {
1021
+ value.forEach((value) => {
1022
+ if (quoted.has(value) || crypto_pattern.test(value)) {
1023
+ directive.push(`'${value}'`);
1024
+ } else {
1025
+ directive.push(value);
1026
+ }
1027
+ });
1028
+ }
1029
+
1030
+ header.push(directive.join(' '));
1031
+ }
1032
+
1033
+ return header.join('; ');
1034
+ }
1035
+
1036
+ get_meta() {
1037
+ const content = escape_html_attr(this.get_header(true));
1038
+ return `<meta http-equiv="content-security-policy" content=${content}>`;
1039
+ }
1040
+ }
1041
+
1042
+ // TODO rename this function/module
1043
+
1044
+ const updated = {
1045
+ ...readable(false),
1046
+ check: () => false
1047
+ };
1048
+
1049
+ /**
1050
+ * @param {{
1051
+ * branch: Array<import('./types').Loaded>;
1052
+ * options: import('types/internal').SSROptions;
1053
+ * state: import('types/internal').SSRState;
1054
+ * $session: any;
1055
+ * page_config: { hydrate: boolean, router: boolean };
1056
+ * status: number;
1057
+ * error?: Error;
1058
+ * url: URL;
1059
+ * params: Record<string, string>;
1060
+ * resolve_opts: import('types/hooks').RequiredResolveOptions;
1061
+ * stuff: Record<string, any>;
1062
+ * }} opts
1063
+ */
1064
+ async function render_response({
1065
+ branch,
1066
+ options,
1067
+ state,
1068
+ $session,
1069
+ page_config,
1070
+ status,
1071
+ error,
1072
+ url,
1073
+ params,
1074
+ resolve_opts,
1075
+ stuff
1076
+ }) {
1077
+ if (state.prerender) {
1078
+ if (options.csp.mode === 'nonce') {
1079
+ throw new Error('Cannot use prerendering if config.kit.csp.mode === "nonce"');
1080
+ }
1081
+
1082
+ if (options.template_contains_nonce) {
1083
+ throw new Error('Cannot use prerendering if page template contains %svelte.nonce%');
1084
+ }
1085
+ }
1086
+
1087
+ const stylesheets = new Set(options.manifest._.entry.css);
1088
+ const modulepreloads = new Set(options.manifest._.entry.js);
1089
+ /** @type {Map<string, string>} */
1090
+ const styles = new Map();
1091
+
1092
+ /** @type {Array<{ url: string, body: string, json: string }>} */
1093
+ const serialized_data = [];
1094
+
1095
+ let shadow_props;
1096
+
1097
+ let rendered;
1098
+
1099
+ let is_private = false;
1100
+ let maxage;
1101
+
1102
+ if (error) {
1103
+ error.stack = options.get_stack(error);
1104
+ }
1105
+
1106
+ if (resolve_opts.ssr) {
1107
+ branch.forEach(({ node, props, loaded, fetched, uses_credentials }) => {
1108
+ if (node.css) node.css.forEach((url) => stylesheets.add(url));
1109
+ if (node.js) node.js.forEach((url) => modulepreloads.add(url));
1110
+ if (node.styles) Object.entries(node.styles).forEach(([k, v]) => styles.set(k, v));
1111
+
1112
+ // TODO probably better if `fetched` wasn't populated unless `hydrate`
1113
+ if (fetched && page_config.hydrate) serialized_data.push(...fetched);
1114
+ if (props) shadow_props = props;
1115
+
1116
+ if (uses_credentials) is_private = true;
1117
+
1118
+ maxage = loaded.maxage;
1119
+ });
1120
+
1121
+ const session = writable($session);
1122
+
1123
+ /** @type {Record<string, any>} */
1124
+ const props = {
1125
+ stores: {
1126
+ page: writable(null),
1127
+ navigating: writable(null),
1128
+ session,
1129
+ updated
1130
+ },
1131
+ page: {
1132
+ url: state.prerender ? create_prerendering_url_proxy(url) : url,
1133
+ params,
1134
+ status,
1135
+ error,
1136
+ stuff
1137
+ },
1138
+ components: branch.map(({ node }) => node.module.default)
1139
+ };
1140
+
1141
+ // TODO remove this for 1.0
1142
+ /**
1143
+ * @param {string} property
1144
+ * @param {string} replacement
1145
+ */
1146
+ const print_error = (property, replacement) => {
1147
+ Object.defineProperty(props.page, property, {
1148
+ get: () => {
1149
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
1150
+ }
1151
+ });
1152
+ };
1153
+
1154
+ print_error('origin', 'origin');
1155
+ print_error('path', 'pathname');
1156
+ print_error('query', 'searchParams');
1157
+
1158
+ // props_n (instead of props[n]) makes it easy to avoid
1159
+ // unnecessary updates for layout components
1160
+ for (let i = 0; i < branch.length; i += 1) {
1161
+ props[`props_${i}`] = await branch[i].loaded.props;
1162
+ }
1163
+
1164
+ let session_tracking_active = false;
1165
+ const unsubscribe = session.subscribe(() => {
1166
+ if (session_tracking_active) is_private = true;
1167
+ });
1168
+ session_tracking_active = true;
1169
+
1170
+ try {
1171
+ rendered = options.root.render(props);
1172
+ } finally {
1173
+ unsubscribe();
1174
+ }
1175
+ } else {
1176
+ rendered = { head: '', html: '', css: { code: '', map: null } };
1177
+ }
1178
+
1179
+ let { head, html: body } = rendered;
1180
+
1181
+ const inlined_style = Array.from(styles.values()).join('\n');
1182
+
1183
+ await csp_ready;
1184
+ const csp = new Csp(options.csp, {
1185
+ dev: options.dev,
1186
+ prerender: !!state.prerender,
1187
+ needs_nonce: options.template_contains_nonce
1188
+ });
1189
+
1190
+ const target = hash(body);
1191
+
1192
+ // prettier-ignore
1193
+ const init_app = `
1194
+ import { start } from ${s(options.prefix + options.manifest._.entry.file)};
1195
+ start({
1196
+ target: document.querySelector('[data-hydrate="${target}"]').parentNode,
1197
+ paths: ${s(options.paths)},
1198
+ session: ${try_serialize($session, (error) => {
1199
+ throw new Error(`Failed to serialize session data: ${error.message}`);
1200
+ })},
1201
+ route: ${!!page_config.router},
1202
+ spa: ${!resolve_opts.ssr},
1203
+ trailing_slash: ${s(options.trailing_slash)},
1204
+ hydrate: ${resolve_opts.ssr && page_config.hydrate ? `{
1205
+ status: ${status},
1206
+ error: ${serialize_error(error)},
1207
+ nodes: [
1208
+ ${(branch || [])
1209
+ .map(({ node }) => `import(${s(options.prefix + node.entry)})`)
1210
+ .join(',\n\t\t\t\t\t\t')}
1211
+ ],
1212
+ url: new URL(${s(url.href)}),
1213
+ params: ${devalue(params)}
1214
+ }` : 'null'}
1215
+ });
1216
+ `;
1217
+
1218
+ const init_service_worker = `
1219
+ if ('serviceWorker' in navigator) {
1220
+ navigator.serviceWorker.register('${options.service_worker}');
1221
+ }
1222
+ `;
1223
+
1224
+ if (options.amp) {
1225
+ head += `
1226
+ <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style>
1227
+ <noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
1228
+ <script async src="https://cdn.ampproject.org/v0.js"></script>
1229
+
1230
+ <style amp-custom>${inlined_style}\n${rendered.css.code}</style>`;
1231
+
1232
+ if (options.service_worker) {
1233
+ head +=
1234
+ '<script async custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js"></script>';
1235
+
1236
+ body += `<amp-install-serviceworker src="${options.service_worker}" layout="nodisplay"></amp-install-serviceworker>`;
1237
+ }
1238
+ } else {
1239
+ if (inlined_style) {
1240
+ const attributes = [];
1241
+ if (options.dev) attributes.push(' data-svelte');
1242
+ if (csp.style_needs_nonce) attributes.push(` nonce="${csp.nonce}"`);
1243
+
1244
+ csp.add_style(inlined_style);
1245
+
1246
+ head += `\n\t<style${attributes.join('')}>${inlined_style}</style>`;
1247
+ }
1248
+
1249
+ // prettier-ignore
1250
+ head += Array.from(stylesheets)
1251
+ .map((dep) => {
1252
+ const attributes = [
1253
+ 'rel="stylesheet"',
1254
+ `href="${options.prefix + dep}"`
1255
+ ];
1256
+
1257
+ if (csp.style_needs_nonce) {
1258
+ attributes.push(`nonce="${csp.nonce}"`);
1259
+ }
1260
+
1261
+ if (styles.has(dep)) {
1262
+ attributes.push('disabled', 'media="(max-width: 0)"');
1263
+ }
1264
+
1265
+ return `\n\t<link ${attributes.join(' ')}>`;
1266
+ })
1267
+ .join('');
1268
+
1269
+ if (page_config.router || page_config.hydrate) {
1270
+ head += Array.from(modulepreloads)
1271
+ .map((dep) => `\n\t<link rel="modulepreload" href="${options.prefix + dep}">`)
1272
+ .join('');
1273
+
1274
+ const attributes = ['type="module"', `data-hydrate="${target}"`];
1275
+
1276
+ csp.add_script(init_app);
1277
+
1278
+ if (csp.script_needs_nonce) {
1279
+ attributes.push(`nonce="${csp.nonce}"`);
1280
+ }
1281
+
1282
+ body += `\n\t\t<script ${attributes.join(' ')}>${init_app}</script>`;
1283
+
1284
+ // prettier-ignore
1285
+ body += serialized_data
1286
+ .map(({ url, body, json }) => {
1287
+ let attributes = `type="application/json" data-type="svelte-data" data-url=${escape_html_attr(url)}`;
1288
+ if (body) attributes += ` data-body="${hash(body)}"`;
1289
+
1290
+ return `<script ${attributes}>${json}</script>`;
1291
+ })
1292
+ .join('\n\t');
1293
+
1294
+ if (shadow_props) {
1295
+ // prettier-ignore
1296
+ body += `<script type="application/json" data-type="svelte-props">${escape_json_in_html(shadow_props)}</script>`;
1297
+ }
1298
+ }
1299
+
1300
+ if (options.service_worker) {
1301
+ // always include service worker unless it's turned off explicitly
1302
+ csp.add_script(init_service_worker);
1303
+
1304
+ head += `
1305
+ <script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ''}>${init_service_worker}</script>`;
1306
+ }
1307
+ }
1308
+
1309
+ if (state.prerender) {
1310
+ const http_equiv = [];
1311
+
1312
+ const csp_headers = csp.get_meta();
1313
+ if (csp_headers) {
1314
+ http_equiv.push(csp_headers);
1315
+ }
1316
+
1317
+ if (maxage) {
1318
+ http_equiv.push(`<meta http-equiv="cache-control" content="max-age=${maxage}">`);
1319
+ }
1320
+
1321
+ if (http_equiv.length > 0) {
1322
+ head = http_equiv.join('\n') + head;
1323
+ }
1324
+ }
1325
+
1326
+ const segments = url.pathname.slice(options.paths.base.length).split('/').slice(2);
1327
+ const assets =
1328
+ options.paths.assets || (segments.length > 0 ? segments.map(() => '..').join('/') : '.');
1329
+
1330
+ const html = resolve_opts.transformPage({
1331
+ html: options.template({ head, body, assets, nonce: /** @type {string} */ (csp.nonce) })
1332
+ });
1333
+
1334
+ const headers = new Headers({
1335
+ 'content-type': 'text/html',
1336
+ etag: `"${hash(html)}"`
1337
+ });
1338
+
1339
+ if (maxage) {
1340
+ headers.set('cache-control', `${is_private ? 'private' : 'public'}, max-age=${maxage}`);
1341
+ }
1342
+
1343
+ if (!options.floc) {
1344
+ headers.set('permissions-policy', 'interest-cohort=()');
1345
+ }
1346
+
1347
+ if (!state.prerender) {
1348
+ const csp_header = csp.get_header();
1349
+ if (csp_header) {
1350
+ headers.set('content-security-policy', csp_header);
1351
+ }
1352
+ }
1353
+
1354
+ return new Response(html, {
1355
+ status,
1356
+ headers
1357
+ });
1358
+ }
1359
+
1360
+ /**
1361
+ * @param {any} data
1362
+ * @param {(error: Error) => void} [fail]
1363
+ */
1364
+ function try_serialize(data, fail) {
1365
+ try {
1366
+ return devalue(data);
1367
+ } catch (err) {
1368
+ if (fail) fail(coalesce_to_error(err));
1369
+ return null;
1370
+ }
1371
+ }
1372
+
1373
+ // Ensure we return something truthy so the client will not re-render the page over the error
1374
+
1375
+ /** @param {(Error & {frame?: string} & {loc?: object}) | undefined | null} error */
1376
+ function serialize_error(error) {
1377
+ if (!error) return null;
1378
+ let serialized = try_serialize(error);
1379
+ if (!serialized) {
1380
+ const { name, message, stack } = error;
1381
+ serialized = try_serialize({ ...error, name, message, stack });
1382
+ }
1383
+ if (!serialized) {
1384
+ serialized = '{}';
1385
+ }
1386
+ return serialized;
1387
+ }
1388
+
1389
+ /**
1390
+ * @param {import('types/page').LoadOutput} loaded
1391
+ * @returns {import('types/internal').NormalizedLoadOutput}
1392
+ */
1393
+ function normalize(loaded) {
1394
+ const has_error_status =
1395
+ loaded.status && loaded.status >= 400 && loaded.status <= 599 && !loaded.redirect;
1396
+ if (loaded.error || has_error_status) {
1397
+ const status = loaded.status;
1398
+
1399
+ if (!loaded.error && has_error_status) {
1400
+ return {
1401
+ status: status || 500,
1402
+ error: new Error()
1403
+ };
1404
+ }
1405
+
1406
+ const error = typeof loaded.error === 'string' ? new Error(loaded.error) : loaded.error;
1407
+
1408
+ if (!(error instanceof Error)) {
1409
+ return {
1410
+ status: 500,
1411
+ error: new Error(
1412
+ `"error" property returned from load() must be a string or instance of Error, received type "${typeof error}"`
1413
+ )
1414
+ };
1415
+ }
1416
+
1417
+ if (!status || status < 400 || status > 599) {
1418
+ console.warn('"error" returned from load() without a valid status code — defaulting to 500');
1419
+ return { status: 500, error };
1420
+ }
1421
+
1422
+ return { status, error };
1423
+ }
1424
+
1425
+ if (loaded.redirect) {
1426
+ if (!loaded.status || Math.floor(loaded.status / 100) !== 3) {
1427
+ return {
1428
+ status: 500,
1429
+ error: new Error(
1430
+ '"redirect" property returned from load() must be accompanied by a 3xx status code'
1431
+ )
1432
+ };
1433
+ }
1434
+
1435
+ if (typeof loaded.redirect !== 'string') {
1436
+ return {
1437
+ status: 500,
1438
+ error: new Error('"redirect" property returned from load() must be a string')
1439
+ };
1440
+ }
1441
+ }
1442
+
1443
+ // TODO remove before 1.0
1444
+ if (/** @type {any} */ (loaded).context) {
1445
+ throw new Error(
1446
+ 'You are returning "context" from a load function. ' +
1447
+ '"context" was renamed to "stuff", please adjust your code accordingly.'
1448
+ );
1449
+ }
1450
+
1451
+ return /** @type {import('types/internal').NormalizedLoadOutput} */ (loaded);
1452
+ }
1453
+
1454
+ const absolute = /^([a-z]+:)?\/?\//;
1455
+ const scheme = /^[a-z]+:/;
1456
+
1457
+ /**
1458
+ * @param {string} base
1459
+ * @param {string} path
1460
+ */
1461
+ function resolve(base, path) {
1462
+ if (scheme.test(path)) return path;
1463
+
1464
+ const base_match = absolute.exec(base);
1465
+ const path_match = absolute.exec(path);
1466
+
1467
+ if (!base_match) {
1468
+ throw new Error(`bad base path: "${base}"`);
1469
+ }
1470
+
1471
+ const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
1472
+ const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
1473
+
1474
+ baseparts.pop();
1475
+
1476
+ for (let i = 0; i < pathparts.length; i += 1) {
1477
+ const part = pathparts[i];
1478
+ if (part === '.') continue;
1479
+ else if (part === '..') baseparts.pop();
1480
+ else baseparts.push(part);
1481
+ }
1482
+
1483
+ const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
1484
+
1485
+ return `${prefix}${baseparts.join('/')}`;
1486
+ }
1487
+
1488
+ /** @param {string} path */
1489
+ function is_root_relative(path) {
1490
+ return path[0] === '/' && path[1] !== '/';
1491
+ }
1492
+
1493
+ /**
1494
+ * @param {string} path
1495
+ * @param {'always' | 'never' | 'ignore'} trailing_slash
1496
+ */
1497
+ function normalize_path(path, trailing_slash) {
1498
+ if (path === '/' || trailing_slash === 'ignore') return path;
1499
+
1500
+ if (trailing_slash === 'never') {
1501
+ return path.endsWith('/') ? path.slice(0, -1) : path;
1502
+ } else if (trailing_slash === 'always' && /\/[^./]+$/.test(path)) {
1503
+ return path + '/';
1504
+ }
1505
+
1506
+ return path;
1507
+ }
1508
+
1509
+ /**
1510
+ * @param {{
1511
+ * event: import('types/hooks').RequestEvent;
1512
+ * options: import('types/internal').SSROptions;
1513
+ * state: import('types/internal').SSRState;
1514
+ * route: import('types/internal').SSRPage | null;
1515
+ * url: URL;
1516
+ * params: Record<string, string>;
1517
+ * node: import('types/internal').SSRNode;
1518
+ * $session: any;
1519
+ * stuff: Record<string, any>;
1520
+ * is_error: boolean;
1521
+ * is_leaf: boolean;
1522
+ * status?: number;
1523
+ * error?: Error;
1524
+ * }} opts
1525
+ * @returns {Promise<import('./types').Loaded | undefined>} undefined for fallthrough
1526
+ */
1527
+ async function load_node({
1528
+ event,
1529
+ options,
1530
+ state,
1531
+ route,
1532
+ url,
1533
+ params,
1534
+ node,
1535
+ $session,
1536
+ stuff,
1537
+ is_error,
1538
+ is_leaf,
1539
+ status,
1540
+ error
1541
+ }) {
1542
+ const { module } = node;
1543
+
1544
+ let uses_credentials = false;
1545
+
1546
+ /**
1547
+ * @type {Array<{
1548
+ * url: string;
1549
+ * body: string;
1550
+ * json: string;
1551
+ * }>}
1552
+ */
1553
+ const fetched = [];
1554
+
1555
+ /**
1556
+ * @type {string[]}
1557
+ */
1558
+ let set_cookie_headers = [];
1559
+
1560
+ /** @type {import('types/helper').Either<import('types/endpoint').Fallthrough, import('types/page').LoadOutput>} */
1561
+ let loaded;
1562
+
1563
+ /** @type {import('types/endpoint').ShadowData} */
1564
+ const shadow = is_leaf
1565
+ ? await load_shadow_data(
1566
+ /** @type {import('types/internal').SSRPage} */ (route),
1567
+ event,
1568
+ options,
1569
+ !!state.prerender
1570
+ )
1571
+ : {};
1572
+
1573
+ if (shadow.fallthrough) return;
1574
+
1575
+ if (shadow.cookies) {
1576
+ set_cookie_headers.push(...shadow.cookies);
1577
+ }
1578
+
1579
+ if (shadow.error) {
1580
+ loaded = {
1581
+ status: shadow.status,
1582
+ error: shadow.error
1583
+ };
1584
+ } else if (shadow.redirect) {
1585
+ loaded = {
1586
+ status: shadow.status,
1587
+ redirect: shadow.redirect
1588
+ };
1589
+ } else if (module.load) {
1590
+ /** @type {import('types/page').LoadInput | import('types/page').ErrorLoadInput} */
1591
+ const load_input = {
1592
+ url: state.prerender ? create_prerendering_url_proxy(url) : url,
1593
+ params,
1594
+ props: shadow.body || {},
1595
+ get session() {
1596
+ uses_credentials = true;
1597
+ return $session;
1598
+ },
1599
+ /**
1600
+ * @param {RequestInfo} resource
1601
+ * @param {RequestInit} opts
1602
+ */
1603
+ fetch: async (resource, opts = {}) => {
1604
+ /** @type {string} */
1605
+ let requested;
1606
+
1607
+ if (typeof resource === 'string') {
1608
+ requested = resource;
1609
+ } else {
1610
+ requested = resource.url;
1611
+
1612
+ opts = {
1613
+ method: resource.method,
1614
+ headers: resource.headers,
1615
+ body: resource.body,
1616
+ mode: resource.mode,
1617
+ credentials: resource.credentials,
1618
+ cache: resource.cache,
1619
+ redirect: resource.redirect,
1620
+ referrer: resource.referrer,
1621
+ integrity: resource.integrity,
1622
+ ...opts
1623
+ };
1624
+ }
1625
+
1626
+ opts.headers = new Headers(opts.headers);
1627
+
1628
+ // merge headers from request
1629
+ for (const [key, value] of event.request.headers) {
1630
+ if (
1631
+ key !== 'authorization' &&
1632
+ key !== 'cookie' &&
1633
+ key !== 'host' &&
1634
+ key !== 'if-none-match' &&
1635
+ !opts.headers.has(key)
1636
+ ) {
1637
+ opts.headers.set(key, value);
1638
+ }
1639
+ }
1640
+
1641
+ opts.headers.set('referer', event.url.href);
1642
+
1643
+ const resolved = resolve(event.url.pathname, requested.split('?')[0]);
1644
+
1645
+ /** @type {Response} */
1646
+ let response;
1647
+
1648
+ /** @type {import('types/internal').PrerenderDependency} */
1649
+ let dependency;
1650
+
1651
+ // handle fetch requests for static assets. e.g. prebaked data, etc.
1652
+ // we need to support everything the browser's fetch supports
1653
+ const prefix = options.paths.assets || options.paths.base;
1654
+ const filename = decodeURIComponent(
1655
+ resolved.startsWith(prefix) ? resolved.slice(prefix.length) : resolved
1656
+ ).slice(1);
1657
+ const filename_html = `${filename}/index.html`; // path may also match path/index.html
1658
+
1659
+ const is_asset = options.manifest.assets.has(filename);
1660
+ const is_asset_html = options.manifest.assets.has(filename_html);
1661
+
1662
+ if (is_asset || is_asset_html) {
1663
+ const file = is_asset ? filename : filename_html;
1664
+
1665
+ if (options.read) {
1666
+ const type = is_asset
1667
+ ? options.manifest._.mime[filename.slice(filename.lastIndexOf('.'))]
1668
+ : 'text/html';
1669
+
1670
+ response = new Response(options.read(file), {
1671
+ headers: type ? { 'content-type': type } : {}
1672
+ });
1673
+ } else {
1674
+ response = await fetch(`${url.origin}/${file}`, /** @type {RequestInit} */ (opts));
1675
+ }
1676
+ } else if (is_root_relative(resolved)) {
1677
+ if (opts.credentials !== 'omit') {
1678
+ uses_credentials = true;
1679
+
1680
+ const cookie = event.request.headers.get('cookie');
1681
+ const authorization = event.request.headers.get('authorization');
1682
+
1683
+ if (cookie) {
1684
+ opts.headers.set('cookie', cookie);
1685
+ }
1686
+
1687
+ if (authorization && !opts.headers.has('authorization')) {
1688
+ opts.headers.set('authorization', authorization);
1689
+ }
1690
+ }
1691
+
1692
+ if (opts.body && typeof opts.body !== 'string') {
1693
+ // per https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, this can be a
1694
+ // Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object.
1695
+ // non-string bodies are irksome to deal with, but luckily aren't particularly useful
1696
+ // in this context anyway, so we take the easy route and ban them
1697
+ throw new Error('Request body must be a string');
1698
+ }
1699
+
1700
+ response = await respond(new Request(new URL(requested, event.url).href, opts), options, {
1701
+ fetched: requested,
1702
+ initiator: route
1703
+ });
1704
+
1705
+ if (state.prerender) {
1706
+ dependency = { response, body: null };
1707
+ state.prerender.dependencies.set(resolved, dependency);
1708
+ }
1709
+ } else {
1710
+ // external
1711
+ if (resolved.startsWith('//')) {
1712
+ requested = event.url.protocol + requested;
1713
+ }
1714
+
1715
+ // external fetch
1716
+ // allow cookie passthrough for "same-origin"
1717
+ // if SvelteKit is serving my.domain.com:
1718
+ // - domain.com WILL NOT receive cookies
1719
+ // - my.domain.com WILL receive cookies
1720
+ // - api.domain.dom WILL NOT receive cookies
1721
+ // - sub.my.domain.com WILL receive cookies
1722
+ // ports do not affect the resolution
1723
+ // leading dot prevents mydomain.com matching domain.com
1724
+ if (
1725
+ `.${new URL(requested).hostname}`.endsWith(`.${event.url.hostname}`) &&
1726
+ opts.credentials !== 'omit'
1727
+ ) {
1728
+ uses_credentials = true;
1729
+
1730
+ const cookie = event.request.headers.get('cookie');
1731
+ if (cookie) opts.headers.set('cookie', cookie);
1732
+ }
1733
+
1734
+ const external_request = new Request(requested, /** @type {RequestInit} */ (opts));
1735
+ response = await options.hooks.externalFetch.call(null, external_request);
1736
+ }
1737
+
1738
+ const proxy = new Proxy(response, {
1739
+ get(response, key, _receiver) {
1740
+ async function text() {
1741
+ const body = await response.text();
1742
+
1743
+ /** @type {import('types/helper').ResponseHeaders} */
1744
+ const headers = {};
1745
+ for (const [key, value] of response.headers) {
1746
+ if (key === 'set-cookie') {
1747
+ set_cookie_headers = set_cookie_headers.concat(value);
1748
+ } else if (key !== 'etag') {
1749
+ headers[key] = value;
1750
+ }
1751
+ }
1752
+
1753
+ if (!opts.body || typeof opts.body === 'string') {
1754
+ // the json constructed below is later added to the dom in a script tag
1755
+ // make sure the used values are safe
1756
+ const status_number = Number(response.status);
1757
+ if (isNaN(status_number)) {
1758
+ throw new Error(
1759
+ `response.status is not a number. value: "${
1760
+ response.status
1761
+ }" type: ${typeof response.status}`
1762
+ );
1763
+ }
1764
+ // prettier-ignore
1765
+ fetched.push({
1766
+ url: requested,
1767
+ body: /** @type {string} */ (opts.body),
1768
+ json: `{"status":${status_number},"statusText":${s(response.statusText)},"headers":${s(headers)},"body":${escape_json_in_html(body)}}`
1769
+ });
1770
+ }
1771
+
1772
+ if (dependency) {
1773
+ dependency.body = body;
1774
+ }
1775
+
1776
+ return body;
1777
+ }
1778
+
1779
+ if (key === 'arrayBuffer') {
1780
+ return async () => {
1781
+ const buffer = await response.arrayBuffer();
1782
+
1783
+ if (dependency) {
1784
+ dependency.body = new Uint8Array(buffer);
1785
+ }
1786
+
1787
+ // TODO should buffer be inlined into the page (albeit base64'd)?
1788
+ // any conditions in which it shouldn't be?
1789
+
1790
+ return buffer;
1791
+ };
1792
+ }
1793
+
1794
+ if (key === 'text') {
1795
+ return text;
1796
+ }
1797
+
1798
+ if (key === 'json') {
1799
+ return async () => {
1800
+ return JSON.parse(await text());
1801
+ };
1802
+ }
1803
+
1804
+ // TODO arrayBuffer?
1805
+
1806
+ return Reflect.get(response, key, response);
1807
+ }
1808
+ });
1809
+
1810
+ return proxy;
1811
+ },
1812
+ stuff: { ...stuff }
1813
+ };
1814
+
1815
+ if (options.dev) {
1816
+ // TODO remove this for 1.0
1817
+ Object.defineProperty(load_input, 'page', {
1818
+ get: () => {
1819
+ throw new Error('`page` in `load` functions has been replaced by `url` and `params`');
1820
+ }
1821
+ });
1822
+ }
1823
+
1824
+ if (is_error) {
1825
+ /** @type {import('types/page').ErrorLoadInput} */ (load_input).status = status;
1826
+ /** @type {import('types/page').ErrorLoadInput} */ (load_input).error = error;
1827
+ }
1828
+
1829
+ loaded = await module.load.call(null, load_input);
1830
+
1831
+ if (!loaded) {
1832
+ throw new Error(`load function must return a value${options.dev ? ` (${node.entry})` : ''}`);
1833
+ }
1834
+ } else if (shadow.body) {
1835
+ loaded = {
1836
+ props: shadow.body
1837
+ };
1838
+ } else {
1839
+ loaded = {};
1840
+ }
1841
+
1842
+ if (loaded.fallthrough && !is_error) {
1843
+ return;
1844
+ }
1845
+
1846
+ // generate __data.json files when prerendering
1847
+ if (shadow.body && state.prerender) {
1848
+ const pathname = `${event.url.pathname}/__data.json`;
1849
+
1850
+ const dependency = {
1851
+ response: new Response(undefined),
1852
+ body: JSON.stringify(shadow.body)
1853
+ };
1854
+
1855
+ state.prerender.dependencies.set(pathname, dependency);
1856
+ }
1857
+
1858
+ return {
1859
+ node,
1860
+ props: shadow.body,
1861
+ loaded: normalize(loaded),
1862
+ stuff: loaded.stuff || stuff,
1863
+ fetched,
1864
+ set_cookie_headers,
1865
+ uses_credentials
1866
+ };
1867
+ }
1868
+
1869
+ /**
1870
+ *
1871
+ * @param {import('types/internal').SSRPage} route
1872
+ * @param {import('types/hooks').RequestEvent} event
1873
+ * @param {import('types/internal').SSROptions} options
1874
+ * @param {boolean} prerender
1875
+ * @returns {Promise<import('types/endpoint').ShadowData>}
1876
+ */
1877
+ async function load_shadow_data(route, event, options, prerender) {
1878
+ if (!route.shadow) return {};
1879
+
1880
+ try {
1881
+ const mod = await route.shadow();
1882
+
1883
+ if (prerender && (mod.post || mod.put || mod.del || mod.patch)) {
1884
+ throw new Error('Cannot prerender pages that have endpoints with mutative methods');
1885
+ }
1886
+
1887
+ const method = normalize_request_method(event);
1888
+ const is_get = method === 'head' || method === 'get';
1889
+ const handler = method === 'head' ? mod.head || mod.get : mod[method];
1890
+
1891
+ if (!handler && !is_get) {
1892
+ return {
1893
+ status: 405,
1894
+ error: new Error(`${method} method not allowed`)
1895
+ };
1896
+ }
1897
+
1898
+ /** @type {import('types/endpoint').ShadowData} */
1899
+ const data = {
1900
+ status: 200,
1901
+ cookies: [],
1902
+ body: {}
1903
+ };
1904
+
1905
+ if (!is_get) {
1906
+ const result = await handler(event);
1907
+
1908
+ if (result.fallthrough) return result;
1909
+
1910
+ const { status, headers, body } = validate_shadow_output(result);
1911
+ data.status = status;
1912
+
1913
+ add_cookies(/** @type {string[]} */ (data.cookies), headers);
1914
+
1915
+ // Redirects are respected...
1916
+ if (status >= 300 && status < 400) {
1917
+ data.redirect = /** @type {string} */ (
1918
+ headers instanceof Headers ? headers.get('location') : headers.location
1919
+ );
1920
+ return data;
1921
+ }
1922
+
1923
+ // ...but 4xx and 5xx status codes _don't_ result in the error page
1924
+ // rendering for non-GET requests — instead, we allow the page
1925
+ // to render with any validation errors etc that were returned
1926
+ data.body = body;
1927
+ }
1928
+
1929
+ const get = (method === 'head' && mod.head) || mod.get;
1930
+ if (get) {
1931
+ const result = await get(event);
1932
+
1933
+ if (result.fallthrough) return result;
1934
+
1935
+ const { status, headers, body } = validate_shadow_output(result);
1936
+ add_cookies(/** @type {string[]} */ (data.cookies), headers);
1937
+ data.status = status;
1938
+
1939
+ if (status >= 400) {
1940
+ data.error = new Error('Failed to load data');
1941
+ return data;
1942
+ }
1943
+
1944
+ if (status >= 300) {
1945
+ data.redirect = /** @type {string} */ (
1946
+ headers instanceof Headers ? headers.get('location') : headers.location
1947
+ );
1948
+ return data;
1949
+ }
1950
+
1951
+ data.body = { ...body, ...data.body };
1952
+ }
1953
+
1954
+ return data;
1955
+ } catch (e) {
1956
+ const error = coalesce_to_error(e);
1957
+ options.handle_error(error, event);
1958
+
1959
+ return {
1960
+ status: 500,
1961
+ error
1962
+ };
1963
+ }
1964
+ }
1965
+
1966
+ /**
1967
+ * @param {string[]} target
1968
+ * @param {Partial<import('types/helper').ResponseHeaders>} headers
1969
+ */
1970
+ function add_cookies(target, headers) {
1971
+ const cookies = headers['set-cookie'];
1972
+ if (cookies) {
1973
+ if (Array.isArray(cookies)) {
1974
+ target.push(...cookies);
1975
+ } else {
1976
+ target.push(/** @type {string} */ (cookies));
1977
+ }
1978
+ }
1979
+ }
1980
+
1981
+ /**
1982
+ * @param {import('types/endpoint').ShadowEndpointOutput} result
1983
+ */
1984
+ function validate_shadow_output(result) {
1985
+ const { status = 200, body = {} } = result;
1986
+ let headers = result.headers || {};
1987
+
1988
+ if (headers instanceof Headers) {
1989
+ if (headers.has('set-cookie')) {
1990
+ throw new Error(
1991
+ 'Endpoint request handler cannot use Headers interface with Set-Cookie headers'
1992
+ );
1993
+ }
1994
+ } else {
1995
+ headers = lowercase_keys(/** @type {Record<string, string>} */ (headers));
1996
+ }
1997
+
1998
+ if (!is_pojo(body)) {
1999
+ throw new Error('Body returned from endpoint request handler must be a plain object');
2000
+ }
2001
+
2002
+ return { status, headers, body };
2003
+ }
2004
+
2005
+ /**
2006
+ * @typedef {import('./types.js').Loaded} Loaded
2007
+ * @typedef {import('types/internal').SSROptions} SSROptions
2008
+ * @typedef {import('types/internal').SSRState} SSRState
2009
+ */
2010
+
2011
+ /**
2012
+ * @param {{
2013
+ * event: import('types/hooks').RequestEvent;
2014
+ * options: SSROptions;
2015
+ * state: SSRState;
2016
+ * $session: any;
2017
+ * status: number;
2018
+ * error: Error;
2019
+ * resolve_opts: import('types/hooks').RequiredResolveOptions;
2020
+ * }} opts
2021
+ */
2022
+ async function respond_with_error({
2023
+ event,
2024
+ options,
2025
+ state,
2026
+ $session,
2027
+ status,
2028
+ error,
2029
+ resolve_opts
2030
+ }) {
2031
+ try {
2032
+ const default_layout = await options.manifest._.nodes[0](); // 0 is always the root layout
2033
+ const default_error = await options.manifest._.nodes[1](); // 1 is always the root error
2034
+
2035
+ /** @type {Record<string, string>} */
2036
+ const params = {}; // error page has no params
2037
+
2038
+ const layout_loaded = /** @type {Loaded} */ (
2039
+ await load_node({
2040
+ event,
2041
+ options,
2042
+ state,
2043
+ route: null,
2044
+ url: event.url, // TODO this is redundant, no?
2045
+ params,
2046
+ node: default_layout,
2047
+ $session,
2048
+ stuff: {},
2049
+ is_error: false,
2050
+ is_leaf: false
2051
+ })
2052
+ );
2053
+
2054
+ const error_loaded = /** @type {Loaded} */ (
2055
+ await load_node({
2056
+ event,
2057
+ options,
2058
+ state,
2059
+ route: null,
2060
+ url: event.url,
2061
+ params,
2062
+ node: default_error,
2063
+ $session,
2064
+ stuff: layout_loaded ? layout_loaded.stuff : {},
2065
+ is_error: true,
2066
+ is_leaf: false,
2067
+ status,
2068
+ error
2069
+ })
2070
+ );
2071
+
2072
+ return await render_response({
2073
+ options,
2074
+ state,
2075
+ $session,
2076
+ page_config: {
2077
+ hydrate: options.hydrate,
2078
+ router: options.router
2079
+ },
2080
+ stuff: error_loaded.stuff,
2081
+ status,
2082
+ error,
2083
+ branch: [layout_loaded, error_loaded],
2084
+ url: event.url,
2085
+ params,
2086
+ resolve_opts
2087
+ });
2088
+ } catch (err) {
2089
+ const error = coalesce_to_error(err);
2090
+
2091
+ options.handle_error(error, event);
2092
+
2093
+ return new Response(error.stack, {
2094
+ status: 500
2095
+ });
2096
+ }
2097
+ }
2098
+
2099
+ /**
2100
+ * @typedef {import('./types.js').Loaded} Loaded
2101
+ * @typedef {import('types/internal').SSRNode} SSRNode
2102
+ * @typedef {import('types/internal').SSROptions} SSROptions
2103
+ * @typedef {import('types/internal').SSRState} SSRState
2104
+ */
2105
+
2106
+ /**
2107
+ * @param {{
2108
+ * event: import('types/hooks').RequestEvent;
2109
+ * options: SSROptions;
2110
+ * state: SSRState;
2111
+ * $session: any;
2112
+ * resolve_opts: import('types/hooks').RequiredResolveOptions;
2113
+ * route: import('types/internal').SSRPage;
2114
+ * params: Record<string, string>;
2115
+ * }} opts
2116
+ * @returns {Promise<Response | undefined>}
2117
+ */
2118
+ async function respond$1(opts) {
2119
+ const { event, options, state, $session, route, resolve_opts } = opts;
2120
+
2121
+ /** @type {Array<SSRNode | undefined>} */
2122
+ let nodes;
2123
+
2124
+ if (!resolve_opts.ssr) {
2125
+ return await render_response({
2126
+ ...opts,
2127
+ branch: [],
2128
+ page_config: {
2129
+ hydrate: true,
2130
+ router: true
2131
+ },
2132
+ status: 200,
2133
+ url: event.url,
2134
+ stuff: {}
2135
+ });
2136
+ }
2137
+
2138
+ try {
2139
+ nodes = await Promise.all(
2140
+ route.a.map((n) => options.manifest._.nodes[n] && options.manifest._.nodes[n]())
2141
+ );
2142
+ } catch (err) {
2143
+ const error = coalesce_to_error(err);
2144
+
2145
+ options.handle_error(error, event);
2146
+
2147
+ return await respond_with_error({
2148
+ event,
2149
+ options,
2150
+ state,
2151
+ $session,
2152
+ status: 500,
2153
+ error,
2154
+ resolve_opts
2155
+ });
2156
+ }
2157
+
2158
+ // the leaf node will be present. only layouts may be undefined
2159
+ const leaf = /** @type {SSRNode} */ (nodes[nodes.length - 1]).module;
2160
+
2161
+ let page_config = get_page_config(leaf, options);
2162
+
2163
+ if (!leaf.prerender && state.prerender && !state.prerender.all) {
2164
+ // if the page has `export const prerender = true`, continue,
2165
+ // otherwise bail out at this point
2166
+ return new Response(undefined, {
2167
+ status: 204
2168
+ });
2169
+ }
2170
+
2171
+ /** @type {Array<Loaded>} */
2172
+ let branch = [];
2173
+
2174
+ /** @type {number} */
2175
+ let status = 200;
2176
+
2177
+ /** @type {Error|undefined} */
2178
+ let error;
2179
+
2180
+ /** @type {string[]} */
2181
+ let set_cookie_headers = [];
2182
+
2183
+ let stuff = {};
2184
+
2185
+ ssr: if (resolve_opts.ssr) {
2186
+ for (let i = 0; i < nodes.length; i += 1) {
2187
+ const node = nodes[i];
2188
+
2189
+ /** @type {Loaded | undefined} */
2190
+ let loaded;
2191
+
2192
+ if (node) {
2193
+ try {
2194
+ loaded = await load_node({
2195
+ ...opts,
2196
+ url: event.url,
2197
+ node,
2198
+ stuff,
2199
+ is_error: false,
2200
+ is_leaf: i === nodes.length - 1
2201
+ });
2202
+
2203
+ if (!loaded) return;
2204
+
2205
+ set_cookie_headers = set_cookie_headers.concat(loaded.set_cookie_headers);
2206
+
2207
+ if (loaded.loaded.redirect) {
2208
+ return with_cookies(
2209
+ new Response(undefined, {
2210
+ status: loaded.loaded.status,
2211
+ headers: {
2212
+ location: loaded.loaded.redirect
2213
+ }
2214
+ }),
2215
+ set_cookie_headers
2216
+ );
2217
+ }
2218
+
2219
+ if (loaded.loaded.error) {
2220
+ ({ status, error } = loaded.loaded);
2221
+ }
2222
+ } catch (err) {
2223
+ const e = coalesce_to_error(err);
2224
+
2225
+ options.handle_error(e, event);
2226
+
2227
+ status = 500;
2228
+ error = e;
2229
+ }
2230
+
2231
+ if (loaded && !error) {
2232
+ branch.push(loaded);
2233
+ }
2234
+
2235
+ if (error) {
2236
+ while (i--) {
2237
+ if (route.b[i]) {
2238
+ const error_node = await options.manifest._.nodes[route.b[i]]();
2239
+
2240
+ /** @type {Loaded} */
2241
+ let node_loaded;
2242
+ let j = i;
2243
+ while (!(node_loaded = branch[j])) {
2244
+ j -= 1;
2245
+ }
2246
+
2247
+ try {
2248
+ const error_loaded = /** @type {import('./types').Loaded} */ (
2249
+ await load_node({
2250
+ ...opts,
2251
+ url: event.url,
2252
+ node: error_node,
2253
+ stuff: node_loaded.stuff,
2254
+ is_error: true,
2255
+ is_leaf: false,
2256
+ status,
2257
+ error
2258
+ })
2259
+ );
2260
+
2261
+ if (error_loaded.loaded.error) {
2262
+ continue;
2263
+ }
2264
+
2265
+ page_config = get_page_config(error_node.module, options);
2266
+ branch = branch.slice(0, j + 1).concat(error_loaded);
2267
+ stuff = { ...node_loaded.stuff, ...error_loaded.stuff };
2268
+ break ssr;
2269
+ } catch (err) {
2270
+ const e = coalesce_to_error(err);
2271
+
2272
+ options.handle_error(e, event);
2273
+
2274
+ continue;
2275
+ }
2276
+ }
2277
+ }
2278
+
2279
+ // TODO backtrack until we find an __error.svelte component
2280
+ // that we can use as the leaf node
2281
+ // for now just return regular error page
2282
+ return with_cookies(
2283
+ await respond_with_error({
2284
+ event,
2285
+ options,
2286
+ state,
2287
+ $session,
2288
+ status,
2289
+ error,
2290
+ resolve_opts
2291
+ }),
2292
+ set_cookie_headers
2293
+ );
2294
+ }
2295
+ }
2296
+
2297
+ if (loaded && loaded.loaded.stuff) {
2298
+ stuff = {
2299
+ ...stuff,
2300
+ ...loaded.loaded.stuff
2301
+ };
2302
+ }
2303
+ }
2304
+ }
2305
+
2306
+ try {
2307
+ return with_cookies(
2308
+ await render_response({
2309
+ ...opts,
2310
+ stuff,
2311
+ url: event.url,
2312
+ page_config,
2313
+ status,
2314
+ error,
2315
+ branch: branch.filter(Boolean)
2316
+ }),
2317
+ set_cookie_headers
2318
+ );
2319
+ } catch (err) {
2320
+ const error = coalesce_to_error(err);
2321
+
2322
+ options.handle_error(error, event);
2323
+
2324
+ return with_cookies(
2325
+ await respond_with_error({
2326
+ ...opts,
2327
+ status: 500,
2328
+ error
2329
+ }),
2330
+ set_cookie_headers
2331
+ );
2332
+ }
2333
+ }
2334
+
2335
+ /**
2336
+ * @param {import('types/internal').SSRComponent} leaf
2337
+ * @param {SSROptions} options
2338
+ */
2339
+ function get_page_config(leaf, options) {
2340
+ // TODO remove for 1.0
2341
+ if ('ssr' in leaf) {
2342
+ throw new Error(
2343
+ '`export const ssr` has been removed — use the handle hook instead: https://kit.svelte.dev/docs/hooks#handle'
2344
+ );
2345
+ }
2346
+
2347
+ return {
2348
+ router: 'router' in leaf ? !!leaf.router : options.router,
2349
+ hydrate: 'hydrate' in leaf ? !!leaf.hydrate : options.hydrate
2350
+ };
2351
+ }
2352
+
2353
+ /**
2354
+ * @param {Response} response
2355
+ * @param {string[]} set_cookie_headers
2356
+ */
2357
+ function with_cookies(response, set_cookie_headers) {
2358
+ if (set_cookie_headers.length) {
2359
+ set_cookie_headers.forEach((value) => {
2360
+ response.headers.append('set-cookie', value);
2361
+ });
2362
+ }
2363
+ return response;
2364
+ }
2365
+
2366
+ /**
2367
+ * @param {import('types/hooks').RequestEvent} event
2368
+ * @param {import('types/internal').SSRPage} route
2369
+ * @param {import('types/internal').SSROptions} options
2370
+ * @param {import('types/internal').SSRState} state
2371
+ * @param {import('types/hooks').RequiredResolveOptions} resolve_opts
2372
+ * @returns {Promise<Response | undefined>}
2373
+ */
2374
+ async function render_page(event, route, options, state, resolve_opts) {
2375
+ if (state.initiator === route) {
2376
+ // infinite request cycle detected
2377
+ return new Response(`Not found: ${event.url.pathname}`, {
2378
+ status: 404
2379
+ });
2380
+ }
2381
+
2382
+ if (route.shadow) {
2383
+ const type = negotiate(event.request.headers.get('accept') || 'text/html', [
2384
+ 'text/html',
2385
+ 'application/json'
2386
+ ]);
2387
+
2388
+ if (type === 'application/json') {
2389
+ return render_endpoint(event, await route.shadow());
2390
+ }
2391
+ }
2392
+
2393
+ const $session = await options.hooks.getSession(event);
2394
+
2395
+ const response = await respond$1({
2396
+ event,
2397
+ options,
2398
+ state,
2399
+ $session,
2400
+ resolve_opts,
2401
+ route,
2402
+ params: event.params // TODO this is redundant
2403
+ });
2404
+
2405
+ if (response) {
2406
+ return response;
2407
+ }
2408
+
2409
+ if (state.fetched) {
2410
+ // we came here because of a bad request in a `load` function.
2411
+ // rather than render the error page — which could lead to an
2412
+ // infinite loop, if the `load` belonged to the root layout,
2413
+ // we respond with a bare-bones 500
2414
+ return new Response(`Bad request in load function: failed to fetch ${state.fetched}`, {
2415
+ status: 500
2416
+ });
2417
+ }
2418
+ }
2419
+
2420
+ /**
2421
+ * @param {string} accept
2422
+ * @param {string[]} types
2423
+ */
2424
+ function negotiate(accept, types) {
2425
+ const parts = accept
2426
+ .split(',')
2427
+ .map((str, i) => {
2428
+ const match = /([^/]+)\/([^;]+)(?:;q=([0-9.]+))?/.exec(str);
2429
+ if (match) {
2430
+ const [, type, subtype, q = '1'] = match;
2431
+ return { type, subtype, q: +q, i };
2432
+ }
2433
+
2434
+ throw new Error(`Invalid Accept header: ${accept}`);
2435
+ })
2436
+ .sort((a, b) => {
2437
+ if (a.q !== b.q) {
2438
+ return b.q - a.q;
2439
+ }
2440
+
2441
+ if ((a.subtype === '*') !== (b.subtype === '*')) {
2442
+ return a.subtype === '*' ? 1 : -1;
2443
+ }
2444
+
2445
+ if ((a.type === '*') !== (b.type === '*')) {
2446
+ return a.type === '*' ? 1 : -1;
2447
+ }
2448
+
2449
+ return a.i - b.i;
2450
+ });
2451
+
2452
+ let accepted;
2453
+ let min_priority = Infinity;
2454
+
2455
+ for (const mimetype of types) {
2456
+ const [type, subtype] = mimetype.split('/');
2457
+ const priority = parts.findIndex(
2458
+ (part) =>
2459
+ (part.type === type || part.type === '*') &&
2460
+ (part.subtype === subtype || part.subtype === '*')
2461
+ );
2462
+
2463
+ if (priority !== -1 && priority < min_priority) {
2464
+ accepted = mimetype;
2465
+ min_priority = priority;
2466
+ }
2467
+ }
2468
+
2469
+ return accepted;
2470
+ }
2471
+
2472
+ const DATA_SUFFIX = '/__data.json';
2473
+
2474
+ /** @param {{ html: string }} opts */
2475
+ const default_transform = ({ html }) => html;
2476
+
2477
+ /** @type {import('types/internal').Respond} */
2478
+ async function respond(request, options, state = {}) {
2479
+ const url = new URL(request.url);
2480
+
2481
+ const normalized = normalize_path(url.pathname, options.trailing_slash);
2482
+
2483
+ if (normalized !== url.pathname) {
2484
+ return new Response(undefined, {
2485
+ status: 301,
2486
+ headers: {
2487
+ location: normalized + (url.search === '?' ? '' : url.search)
2488
+ }
2489
+ });
2490
+ }
2491
+
2492
+ const { parameter, allowed } = options.method_override;
2493
+ const method_override = url.searchParams.get(parameter)?.toUpperCase();
2494
+
2495
+ if (method_override) {
2496
+ if (request.method === 'POST') {
2497
+ if (allowed.includes(method_override)) {
2498
+ request = new Proxy(request, {
2499
+ get: (target, property, _receiver) => {
2500
+ if (property === 'method') return method_override;
2501
+ return Reflect.get(target, property, target);
2502
+ }
2503
+ });
2504
+ } else {
2505
+ const verb = allowed.length === 0 ? 'enabled' : 'allowed';
2506
+ const body = `${parameter}=${method_override} is not ${verb}. See https://kit.svelte.dev/docs/configuration#methodoverride`;
2507
+
2508
+ return new Response(body, {
2509
+ status: 400
2510
+ });
2511
+ }
2512
+ } else {
2513
+ throw new Error(`${parameter}=${method_override} is only allowed with POST requests`);
2514
+ }
2515
+ }
2516
+
2517
+ /** @type {import('types/hooks').RequestEvent} */
2518
+ const event = {
2519
+ request,
2520
+ url,
2521
+ params: {},
2522
+ // @ts-expect-error this picks up types that belong to the tests
2523
+ locals: {},
2524
+ platform: state.platform
2525
+ };
2526
+
2527
+ // TODO remove this for 1.0
2528
+ /**
2529
+ * @param {string} property
2530
+ * @param {string} replacement
2531
+ * @param {string} suffix
2532
+ */
2533
+ const removed = (property, replacement, suffix = '') => ({
2534
+ get: () => {
2535
+ throw new Error(`event.${property} has been replaced by event.${replacement}` + suffix);
2536
+ }
2537
+ });
2538
+
2539
+ const details = '. See https://github.com/sveltejs/kit/pull/3384 for details';
2540
+
2541
+ const body_getter = {
2542
+ get: () => {
2543
+ throw new Error(
2544
+ 'To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`' +
2545
+ details
2546
+ );
2547
+ }
2548
+ };
2549
+
2550
+ Object.defineProperties(event, {
2551
+ method: removed('method', 'request.method', details),
2552
+ headers: removed('headers', 'request.headers', details),
2553
+ origin: removed('origin', 'url.origin'),
2554
+ path: removed('path', 'url.pathname'),
2555
+ query: removed('query', 'url.searchParams'),
2556
+ body: body_getter,
2557
+ rawBody: body_getter
2558
+ });
2559
+
2560
+ /** @type {import('types/hooks').RequiredResolveOptions} */
2561
+ let resolve_opts = {
2562
+ ssr: true,
2563
+ transformPage: default_transform
2564
+ };
2565
+
2566
+ try {
2567
+ const response = await options.hooks.handle({
2568
+ event,
2569
+ resolve: async (event, opts) => {
2570
+ if (opts) {
2571
+ resolve_opts = {
2572
+ ssr: opts.ssr !== false,
2573
+ transformPage: opts.transformPage || default_transform
2574
+ };
2575
+ }
2576
+
2577
+ if (state.prerender && state.prerender.fallback) {
2578
+ return await render_response({
2579
+ url: event.url,
2580
+ params: event.params,
2581
+ options,
2582
+ state,
2583
+ $session: await options.hooks.getSession(event),
2584
+ page_config: { router: true, hydrate: true },
2585
+ stuff: {},
2586
+ status: 200,
2587
+ branch: [],
2588
+ resolve_opts: {
2589
+ ...resolve_opts,
2590
+ ssr: false
2591
+ }
2592
+ });
2593
+ }
2594
+
2595
+ let decoded = decodeURI(event.url.pathname);
2596
+
2597
+ if (options.paths.base) {
2598
+ if (!decoded.startsWith(options.paths.base)) {
2599
+ return new Response(undefined, { status: 404 });
2600
+ }
2601
+ decoded = decoded.slice(options.paths.base.length) || '/';
2602
+ }
2603
+
2604
+ const is_data_request = decoded.endsWith(DATA_SUFFIX);
2605
+
2606
+ if (is_data_request) {
2607
+ decoded = decoded.slice(0, -DATA_SUFFIX.length) || '/';
2608
+
2609
+ const normalized = normalize_path(
2610
+ url.pathname.slice(0, -DATA_SUFFIX.length),
2611
+ options.trailing_slash
2612
+ );
2613
+
2614
+ event.url = new URL(event.url.origin + normalized + event.url.search);
2615
+ }
2616
+
2617
+ for (const route of options.manifest._.routes) {
2618
+ const match = route.pattern.exec(decoded);
2619
+ if (!match) continue;
2620
+
2621
+ event.params = route.params ? decode_params(route.params(match)) : {};
2622
+
2623
+ /** @type {Response | undefined} */
2624
+ let response;
2625
+
2626
+ if (is_data_request && route.type === 'page' && route.shadow) {
2627
+ response = await render_endpoint(event, await route.shadow());
2628
+
2629
+ // loading data for a client-side transition is a special case
2630
+ if (request.headers.get('x-sveltekit-load') === 'true') {
2631
+ if (response) {
2632
+ // since redirects are opaque to the browser, we need to repackage
2633
+ // 3xx responses as 200s with a custom header
2634
+ if (response.status >= 300 && response.status < 400) {
2635
+ const location = response.headers.get('location');
2636
+
2637
+ if (location) {
2638
+ const headers = new Headers(response.headers);
2639
+ headers.set('x-sveltekit-location', location);
2640
+ response = new Response(undefined, {
2641
+ status: 204,
2642
+ headers
2643
+ });
2644
+ }
2645
+ }
2646
+ } else {
2647
+ // TODO ideally, the client wouldn't request this data
2648
+ // in the first place (at least in production)
2649
+ response = new Response('{}', {
2650
+ headers: {
2651
+ 'content-type': 'application/json'
2652
+ }
2653
+ });
2654
+ }
2655
+ }
2656
+ } else {
2657
+ response =
2658
+ route.type === 'endpoint'
2659
+ ? await render_endpoint(event, await route.load())
2660
+ : await render_page(event, route, options, state, resolve_opts);
2661
+ }
2662
+
2663
+ if (response) {
2664
+ // respond with 304 if etag matches
2665
+ if (response.status === 200 && response.headers.has('etag')) {
2666
+ let if_none_match_value = request.headers.get('if-none-match');
2667
+
2668
+ // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives
2669
+ if (if_none_match_value?.startsWith('W/"')) {
2670
+ if_none_match_value = if_none_match_value.substring(2);
2671
+ }
2672
+
2673
+ const etag = /** @type {string} */ (response.headers.get('etag'));
2674
+
2675
+ if (if_none_match_value === etag) {
2676
+ const headers = new Headers({ etag });
2677
+
2678
+ // https://datatracker.ietf.org/doc/html/rfc7232#section-4.1
2679
+ for (const key of [
2680
+ 'cache-control',
2681
+ 'content-location',
2682
+ 'date',
2683
+ 'expires',
2684
+ 'vary'
2685
+ ]) {
2686
+ const value = response.headers.get(key);
2687
+ if (value) headers.set(key, value);
2688
+ }
2689
+
2690
+ return new Response(undefined, {
2691
+ status: 304,
2692
+ headers
2693
+ });
2694
+ }
2695
+ }
2696
+
2697
+ return response;
2698
+ }
2699
+ }
2700
+
2701
+ // if this request came direct from the user, rather than
2702
+ // via a `fetch` in a `load`, render a 404 page
2703
+ if (!state.initiator) {
2704
+ const $session = await options.hooks.getSession(event);
2705
+ return await respond_with_error({
2706
+ event,
2707
+ options,
2708
+ state,
2709
+ $session,
2710
+ status: 404,
2711
+ error: new Error(`Not found: ${event.url.pathname}`),
2712
+ resolve_opts
2713
+ });
2714
+ }
2715
+
2716
+ // we can't load the endpoint from our own manifest,
2717
+ // so we need to make an actual HTTP request
2718
+ return await fetch(request);
2719
+ },
2720
+
2721
+ // TODO remove for 1.0
2722
+ // @ts-expect-error
2723
+ get request() {
2724
+ throw new Error('request in handle has been replaced with event' + details);
2725
+ }
2726
+ });
2727
+
2728
+ // TODO for 1.0, change the error message to point to docs rather than PR
2729
+ if (response && !(response instanceof Response)) {
2730
+ throw new Error('handle must return a Response object' + details);
2731
+ }
2732
+
2733
+ return response;
2734
+ } catch (/** @type {unknown} */ e) {
2735
+ const error = coalesce_to_error(e);
2736
+
2737
+ options.handle_error(error, event);
2738
+
2739
+ try {
2740
+ const $session = await options.hooks.getSession(event);
2741
+ return await respond_with_error({
2742
+ event,
2743
+ options,
2744
+ state,
2745
+ $session,
2746
+ status: 500,
2747
+ error,
2748
+ resolve_opts
2749
+ });
2750
+ } catch (/** @type {unknown} */ e) {
2751
+ const error = coalesce_to_error(e);
2752
+
2753
+ return new Response(options.dev ? error.stack : error.message, {
2754
+ status: 500
2755
+ });
2756
+ }
2757
+ }
2758
+ }
2759
+
2760
+ export { respond };