@sveltejs/kit 1.0.0-next.28 → 1.0.0-next.280

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