@sveltejs/kit 1.0.0-next.29 → 1.0.0-next.292

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